Files
PozzettiAndrea a342f20402 Serve frontend JS from javascript/, keep vendor bundles out of the main realm
Move web/ to javascript/ and declare it via [tool.comfy] web.

Rename the seven third-party bundles (playcanvas, spark, three.js, gsplat,
OrbitControls, TrackballControls) to .mjs. Every reference to them is inside the
HTML viewers, but ComfyUI auto-imports **/*.js under the web dir into the shared
browser realm, so ~8MB of vendor code was being evaluated in the main page on
every startup -- and with it 36 collision errors: document.body injection,
document-level listeners, unguarded message listeners and self.onmessage writes.
The importmap values, script srcs and three.module's internal ./three.core ref
are rewritten to match.

DisplayName becomes "GaussianPack": the namespace enforced on
registerExtension names is derived from it, and "ComfyUI-GaussianPack" made
that prefix invalid. The analysis extension is renamed to match.

js/gaussian_preview.js hooked "PlyPreviewLoadGaussianPLYEnhance", a node id
that appears nowhere in this repo, so the PLY dropdown auto-refresh had never
run; it now targets LoadPLY and LoadPLYOutput, the two nodes that actually carry
the ply_file widget. Guard its message listener on event.source.

Asset seeding resolves the input directory through
folder_paths.get_input_directory(), so it follows ComfyUI Desktop and
--input-directory instead of writing into the code tree.

comfy-test.toml moves to the current schema: [test.workflows] cuda (there is
no "gpu" key -- the accelerator is named by backend, and the old spelling parsed
to an empty list, so CUDA runners silently ran the full unfiltered set), an
explicit [test.platforms] platforms allowlist (per-platform booleans are no
longer supported), and the javascript level.
2026-08-22 20:56:09 +02:00

19356 lines
2.3 MiB
Plaintext

/**
* @license
* 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.
*/
(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;e<c.length-1;e++){let s=c[e],i=c[e+1];if(i[0]===xe.delimiter){t=i;continue}s&&i&&s[s.length-1]!==xe.delimiter&&i[0]!==xe.delimiter?t+=xe.delimiter+i:t+=i}return t},normalize(c){let t=c.startsWith(xe.delimiter),e=c.endsWith(xe.delimiter),s=c.split("/"),i="",r=[];for(let a=0;a<s.length;a++)if(s[a]!==""&&s[a]!=="."){if(s[a]===".."&&r.length>0){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<e.length-1;++s)t+=s===0?e[s]:`/${e[s]}`;else if(e[0]==="..")for(s=0;s<e.length-1;++s)t+=s===0?e[s]:`/${e[s]}`;else for(t=".",s=0;s<e.length-1;++s)t+=`/${e[s]}`;else for(s=0;s<e.length-1;++s)t+=s===0?e[s]:`/${e[s]}`;return t}};var m4=()=>{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;e<t.length;e++)c=c.replace(`{${e}}`,t[e]);return c},getCodePoint(c,t){let e=IC(c,t);return e&&e.code},getCodePoints(c){if(typeof c!="string")throw new TypeError("Not a string");let t=0,e=[],s;for(;s=IC(c,t);)e.push(s.code),t+=s.long?2:1;return e},getSymbols(c){if(typeof c!="string")throw new TypeError("Not a string");let t=0,e=c.length,s=[],i=0,r;for(;t<e;){if(i+=b4(c,t+i),r=c[t+i],Xl(r,I4,R4)&&(r=c[t+i++]),Xl(r,PC,wC)&&(r=c[t+i++]),r&&r.charCodeAt(0)===C4){r=c[t+i++];continue}let a=c.substring(t,t+i);s.push(a),t+=i,i=0}return s},fromCodePoint(...c){return c.map(t=>t>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;r<i.length;r++)i[r].callback===e&&(s&&i[r].scope!==s||(i[r].removed=!0,i.splice(r,1),r--));i.length===0&&this._callbacks.delete(t)}else{let i=this._callbacks.get(t);if(i){for(let r=0;r<i.length;r++)i[r].removed=!0;this._callbacks.delete(t)}}else{for(let i of this._callbacks.values())for(let r=0;r<i.length;r++)i[r].removed=!0;this._callbacks.clear()}return this}offByHandle(t){let e=t.name;t.removed=!0,this._callbackActive.has(e)&&this._callbackActive.get(e)===this._callbacks.get(e)&&this._callbackActive.set(e,this._callbackActive.get(e).slice());let s=this._callbacks.get(e);if(!s)return this;let i=s.indexOf(t);return i!==-1&&(s.splice(i,1),s.length===0&&this._callbacks.delete(e)),this}fire(t,e,s,i,r,a,o,l,h){if(!t)return this;let f=this._callbacks.get(t);if(!f)return this;let u;this._callbackActive.has(t)?this._callbackActive.get(t)!==f&&(u=f.slice()):this._callbackActive.set(t,f);for(let d=0;(u||this._callbackActive.get(t))&&d<(u||this._callbackActive.get(t)).length;d++){let p=(u||this._callbackActive.get(t))[d];if(p.callback&&(p.callback.call(p.scope,e,s,i,r,a,o,l,h),p._once)){let m=this._callbacks.get(t),_=m?m.indexOf(p):-1;if(_!==-1){this._callbackActive.get(t)===m&&this._callbackActive.set(t,this._callbackActive.get(t).slice());let S=this._callbacks.get(t);if(!S)continue;S[_].removed=!0,S.splice(_,1),S.length===0&&this._callbacks.delete(t)}}}return u||this._callbackActive.delete(t),this}hasEvent(t){return!!this._callbacks.get(t)?.length}};var sd=class{constructor(){n(this,"_list",[]);n(this,"_index",{})}push(t,e){if(this._index[t])throw Error(`Key already in index ${t}`);let s=this._list.push(e)-1;this._index[t]=s}has(t){return this._index[t]!==void 0}get(t){let e=this._index[t];return e!==void 0?this._list[e]:null}remove(t){let e=this._index[t];if(e!==void 0){this._list.splice(e,1),delete this._index[t];for(t in this._index){let s=this._index[t];s>e&&(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;++s)e+=this.readChar();return e}readU8(){return this.dataView.getUint8(this.offset++)}readU16(){return this.dataView.getUint16(this._inc(2),!0)}readU32(){return this.dataView.getUint32(this._inc(4),!0)}readU64(){return this.readU32()+2**32*this.readU32()}readU32be(){return this.dataView.getUint32(this._inc(4),!1)}readArray(t){for(let e=0;e<t.length;++e)t[e]=this.readU8()}readLine(){let t=this.dataView,e="";for(;!(this.offset>=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<i.length;r++)this._index[i[r]]||(s=!0,this._index[i[r]]=!0,this._list.push(i[r]),this.fire("add",i[r],this._parent));return s&&this.fire("change",this._parent),s}remove(...e){let s=!1;if(!this._list.length)return s;let i=this._processArguments(e,!0);if(!i.length)return s;for(let r=0;r<i.length;r++)this._index[i[r]]&&(s=!0,delete this._index[i[r]],this._list.splice(this._list.indexOf(i[r]),1),this.fire("remove",i[r],this._parent));return s&&this.fire("change",this._parent),s}clear(){if(!this._list.length)return;let e=this._list.slice(0);this._list=[],this._index={};for(let s=0;s<e.length;s++)this.fire("remove",e[s],this._parent);this.fire("change",this._parent)}has(...e){return this._list.length?this._has(this._processArguments(e)):!1}_has(e){if(!this._list.length||!e.length)return!1;for(let s=0;s<e.length;s++)if(e[s].length===1){if(this._index[e[s][0]])return!0}else{let i=!0;for(let r=0;r<e[s].length;r++)if(!this._index[e[s][r]]){i=!1;break}if(i)return!0}return!1}list(){return this._list.slice(0)}_processArguments(e,s){let i=[],r=[];if(!e||!e.length)return i;for(let a=0;a<e.length;a++)if(e[a]instanceof Array){s||(r=[]);for(let o=0;o<e[a].length;o++)typeof e[a][o]=="string"&&(s?i.push(e[a][o]):r.push(e[a][o]));!s&&r.length&&i.push(r)}else typeof e[a]=="string"&&(s?i.push(e[a]):i.push([e[a]]));return i}get size(){return this._list.length}};n(va,"EVENT_ADD","add"),n(va,"EVENT_REMOVE","remove"),n(va,"EVENT_CHANGE","change");var Tt=typeof window<"u"&&window.performance&&window.performance.now?performance.now.bind(performance):Date.now;function lD(c){let t="";if((c.authority||c.scheme)&&(c.host||c.hostpath))throw new Error("Can't have 'scheme' or 'authority' and 'host' or 'hostpath' option");if(c.host&&c.hostpath)throw new Error("Can't have 'host' and 'hostpath' option");if(c.path&&c.hostpath)throw new Error("Can't have 'path' and 'hostpath' option");return c.scheme&&(t+=`${c.scheme}:`),c.authority&&(t+=`//${c.authority}`),c.host&&(t+=c.host),c.path&&(t+=c.path),c.hostpath&&(t+=c.hostpath),c.query&&(t+=`?${c.query}`),c.fragment&&(t+=`#${c.fragment}`),t}var L4=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,jl=class{constructor(t){n(this,"scheme");n(this,"authority");n(this,"path");n(this,"query");n(this,"fragment");let e=t.match(L4);this.scheme=e[2],this.authority=e[4],this.path=e[5],this.query=e[7],this.fragment=e[9]}toString(){let t="";return this.scheme&&(t+=`${this.scheme}:`),this.authority&&(t+=`//${this.authority}`),t+=this.path,this.query&&(t+=`?${this.query}`),this.fragment&&(t+=`#${this.fragment}`),t}getQuery(){let t={};if(this.query){let e=decodeURIComponent(this.query).split("&");for(let s of e){let i=s.split("=");t[i[0]]=i[1]}}return t}setQuery(t){let e="";for(let s in t)t.hasOwnProperty(s)&&(e!==""&&(e+="&"),e+=`${encodeURIComponent(s)}=${encodeURIComponent(t[s])}`);this.query=e}};var M4=0,RC=1,cD=4,O4=5;var R={DEG_TO_RAD:Math.PI/180,RAD_TO_DEG:180/Math.PI,clamp(c,t,e){return c>=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&&c<r}};var ps=class ps{constructor(t=0,e=0,s=0,i=1){n(this,"r");n(this,"g");n(this,"b");n(this,"a");let r=t.length;r===3||r===4?(this.r=t[0],this.g=t[1],this.b=t[2],this.a=t[3]??1):(this.r=t,this.g=e,this.b=s,this.a=i)}clone(){let t=this.constructor;return new t(this.r,this.g,this.b,this.a)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this}equals(t){return this.r===t.r&&this.g===t.g&&this.b===t.b&&this.a===t.a}set(t,e,s,i=1){return this.r=t,this.g=e,this.b=s,this.a=i,this}lerp(t,e,s){return this.r=t.r+s*(e.r-t.r),this.g=t.g+s*(e.g-t.g),this.b=t.b+s*(e.b-t.b),this.a=t.a+s*(e.a-t.a),this}linear(t=this){return this.r=Math.pow(t.r,2.2),this.g=Math.pow(t.g,2.2),this.b=Math.pow(t.b,2.2),this.a=t.a,this}gamma(t=this){return this.r=Math.pow(t.r,1/2.2),this.g=Math.pow(t.g,1/2.2),this.b=Math.pow(t.b,1/2.2),this.a=t.a,this}mulScalar(t){return this.r*=t,this.g*=t,this.b*=t,this}fromString(t){let e=parseInt(t.replace("#","0x"),16),s;return t.length>7?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._left||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[0][0])this._left=-1/0,this._right=e[0][0],this._recip=0,this._p0=this._p1=e[0][1],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;e<t.length-1;e+=2)this.keys.push([t[e],t[e+1]]);this.sort()}get length(){return this.keys.length}add(t,e){let s=this.keys,i=s.length,r=0;for(;r<i&&!(s[r][0]>t);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<s;a++){let o=Math.abs(t-e[a][0]);if(i>=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;i<t;i++)e[i]=this._eval.evaluate(s*i);return e}quantizeClamped(t,e,s){let i=this.quantize(t);for(let r=0;r<i.length;++r)i[r]=Math.min(s,Math.max(e,i[r]));return i}};var ki=class{constructor(...t){n(this,"curves",[]);n(this,"_type",1);if(t.length>1)for(let e=0;e<t.length;e++)this.curves.push(new Ps(t[e]));else if(t.length===0)this.curves.push(new Ps);else{let e=t[0];if(typeof e=="number")for(let s=0;s<e;s++)this.curves.push(new Ps);else for(let s=0;s<e.length;s++)this.curves.push(new Ps(e[s]))}}get length(){return this.curves.length}set type(t){this._type=t;for(let e=0;e<this.curves.length;e++)this.curves[e].type=t}get type(){return this._type}get(t){return this.curves[t]}value(t,e=[]){let s=this.curves.length;e.length=s;for(let i=0;i<s;i++)e[i]=this.curves[i].value(t);return e}clone(){let t=new this.constructor;t.curves=[];for(let e=0;e<this.curves.length;e++)t.curves.push(this.curves[e].clone());return t._type=this._type,t}quantize(t){t=Math.max(t,2);let e=this.curves.length,s=new Float32Array(t*e),i=1/(t-1);for(let r=0;r<e;r++){let a=new id(this.curves[r]);for(let o=0;o<t;o++)s[o*e+r]=a.evaluate(i*o)}return s}quantizeClamped(t,e,s){let i=this.quantize(t);for(let r=0;r<i.length;++r)i[r]=Math.min(s,Math.max(e,i[r]));return i}};var bC=new Float32Array(1),hD=new Int32Array(bC.buffer),Hs=class{static float2Half(t){bC[0]=t;let e=hD[0],s=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;f<l;f++){let u=f*h,d=a*Math.cos(u),p=a*Math.sin(u);s.push(d,p)}}return s}};var ms=class ms{constructor(t=0,e=0,s=0){n(this,"x");n(this,"y");n(this,"z");t.length===3?(this.x=t[0],this.y=t[1],this.z=t[2]):(this.x=t,this.y=e,this.z=s)}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}add2(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addScaled(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}clone(){let t=this.constructor;return new t(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}cross(t,e){let s=t.x,i=t.y,r=t.z,a=e.x,o=e.y,l=e.z;return this.x=i*l-o*r,this.y=r*a-l*s,this.z=s*o-a*i,this}distance(t){let e=this.x-t.x,s=this.y-t.y,i=this.z-t.z;return Math.sqrt(e*e+s*s+i*i)}div(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}div2(t,e){return this.x=t.x/e.x,this.y=t.y/e.y,this.z=t.z/e.z,this}divScalar(t){return this.x/=t,this.y/=t,this.z/=t,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}equals(t){return this.x===t.x&&this.y===t.y&&this.z===t.z}equalsApprox(t,e=1e-6){return Math.abs(this.x-t.x)<e&&Math.abs(this.y-t.y)<e&&Math.abs(this.z-t.z)<e}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}lerp(t,e,s){return this.x=t.x+s*(e.x-t.x),this.y=t.y+s*(e.y-t.y),this.z=t.z+s*(e.z-t.z),this}mul(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}mul2(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}mulScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}normalize(t=this){let e=t.x*t.x+t.y*t.y+t.z*t.z;if(e>0){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.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this}max(t){return t.x>this.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)<e&&Math.abs(this.y-t.y)<e}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSq(){return this.x*this.x+this.y*this.y}lerp(t,e,s){return this.x=t.x+s*(e.x-t.x),this.y=t.y+s*(e.y-t.y),this}mul(t){return this.x*=t.x,this.y*=t.y,this}mul2(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this}mulScalar(t){return this.x*=t,this.y*=t,this}normalize(t=this){let e=t.x*t.x+t.y*t.y;if(e>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.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),this}max(t){return t.x>this.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)<e&&Math.abs(this.y-t.y)<e&&Math.abs(this.z-t.z)<e&&Math.abs(this.w-t.w)<e}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){return this.x=t.x+s*(e.x-t.x),this.y=t.y+s*(e.y-t.y),this.z=t.z+s*(e.z-t.z),this.w=t.w+s*(e.w-t.w),this}mul(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}mul2(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}mulScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}normalize(t=this){let e=t.x*t.x+t.y*t.y+t.z*t.z+t.w*t.w;if(e>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.x<this.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}max(t){return t.x>this.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?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)<e&&Math.abs(this.y-t.y)<e&&Math.abs(this.z-t.z)<e&&Math.abs(this.w-t.w)<e}getAxisAngle(t){let e=Math.acos(this.w)*2,s=Math.sin(e/2);return s!==0?(t.x=this.x/s,t.y=this.y/s,t.z=this.z/s,(t.x<0||t.y<0||t.z<0)&&(t.x*=-1,t.y*=-1,t.z*=-1,e*=-1)):(t.x=1,t.y=0,t.z=0),e*R.RAD_TO_DEG}getEulerAngles(t=new x){let e,s,i,r=this.x,a=this.y,o=this.z,l=this.w,h=2*(l*a-r*o);return h<=-.99999?(e=2*Math.atan2(r,l),s=-Math.PI/2,i=0):h>=.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 s<Number.EPSILON?Math.abs(t.x)>Math.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;A<f&&(f=A),w>u&&(u=w),I<d&&(d=I),D>p&&(p=D),O<m&&(m=O),G>_&&(_=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.x<e.x-s.x||t.x>e.x+s.x||t.y<e.y-s.y||t.y>e.y+s.y||t.z<e.z-s.z||t.z>e.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;d<u;d+=3){let p=t[d],m=t[d+1],_=t[d+2];p<r&&(r=p),m<a&&(a=m),_<o&&(o=_),p>l&&(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;l<h&&(u=h-l,o+=u*u),l>f&&(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 e<s*s}intersectsRay(t,e){let s=Lx.copy(t.origin).sub(this.center),i=s.dot(N4.copy(t.direction).normalize()),r=s.dot(s)-this.radius*this.radius;if(r>0&&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&&s<BC)return!1;let i=1/s;FC.sub2(t.origin,this.v0);let r=i*FC.dot(OC);if(r<0||r>1)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<f32>",returnType:"vec4f"},$4={textureType:"texture_2d<u32>",returnType:"vec4u"},Z4={textureType:"texture_2d<i32>",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<f32>"],["vec3f","vec3<f32>"],["vec4f","vec4<f32>"],["vec2i","vec2<i32>"],["vec3i","vec3<i32>"],["vec4i","vec4<i32>"],["vec2<bool>"],["vec3<bool>"],["vec4<bool>"],["mat2x2f","mat2x2<f32>"],["mat3x3f","mat3x3<f32>"],["mat4x4f","mat4x4<f32>"],["texture_2d<f32>"],["texture_cube<f32>"],["array<f32>"],["texture_depth_2d"],["texture_depth_cube"],["texture_3d<f32>"],["array<vec2<f32>>"],["array<vec3<f32>>"],["array<vec4<f32>>"],["array<mat4x4<f32>>"],["texture_2d_array<f32>"],["u32"],["vec2u","vec2<u32>"],["vec3u","vec3<u32>"],["vec4u","vec4<u32>"],["array<i32>"],["array<u32>"],["array<bool>"],["array<vec2i>","array<vec2<i32>>"],["array<vec2u>","array<vec2<u32>>"],["array<vec2b>","array<vec2<bool>>"],["array<vec3i>","array<vec3<i32>>"],["array<vec3u>","array<vec3<u32>>"],["array<vec3b>","array<vec3<bool>>"],["array<vec4i>","array<vec4<i32>>"],["array<vec4u>","array<vec4<u32>>"],["array<vec4b>","array<vec4<bool>>"],["texture_2d<i32>"],["texture_2d<u32>"],["texture_cube<i32>"],["texture_cube<u32>"],["texture_3d<i32>"],["texture_3d<u32>"],["texture_2d_array<i32>"],["texture_2d_array<u32>"]],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;t<this._levels.length;t++){let e=this._levels[t];if(e instanceof ImageBitmap)e.close(),this._levels[t]=null;else if(Array.isArray(e))for(let s=0;s<e.length;s++)e[s]instanceof ImageBitmap&&(e[s].close(),e[s]=null)}}setReleaseSourceAfterUpload(){this.releaseSourceAfterUpload=!0,!this._needsUpload&&!this._needsMipmapsUpload&&this.releaseImageSources()}recreateImpl(t=!0){let{device:e}=this;this.impl?.destroy(e),this.impl=null,this.impl=e.createTextureImpl(this),this.dirtyAll(),t&&this.upload()}_clearLevels(){this._levels=this._cubemap?[[null,null,null,null,null,null]]:[null]}resize(t,e,s=1){if(this.width!==t||this.height!==e||this.depth!==s){let i=this.device;this.adjustVramSizeTracking(i._vram,-this._gpuSize),this._gpuSize=0,this.impl.destroy(i),this._clearLevels(),this._width=Math.floor(t),this._height=Math.floor(e),this._depth=Math.floor(s),this._updateNumLevels(),this.impl=i.createTextureImpl(this),this.dirtyAll()}}loseContext(){this.impl.loseContext(),this.dirtyAll()}adjustVramSizeTracking(t,e){t.tex+=e}propertyChanged(t){this.impl.propertyChanged(t),this.renderVersionDirty=this.device.renderVersion}_updateNumLevels(){let t=this.mipmaps?gt.calcMipLevelsCount(this.width,this.height):1,e=this._numLevelsRequested;e!==void 0&&e>t,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<i.renderVersionDirty&&(this.dirty=!0)}setStorageTexture(t,e){let s=this.format.storageTextureFormatsMap.get(t),i=e instanceof Zr?e.texture:e;this.storageTextures[s]!==e?(this.storageTextures[s]=e,this.dirty=!0):this.renderVersionUpdated<i.renderVersionDirty&&(this.dirty=!0)}updateUniformBuffers(){for(let t=0;t<this.uniformBuffers.length;t++)this.uniformBuffers[t].update()}update(){let{textureFormats:t,storageTextureFormats:e,storageBufferFormats:s}=this.format;for(let i=0;i<t.length;i++){let r=t[i],a=r.scopeId.value;a||(r.name==="uSceneDepthMap"&&(a=bo(this.device,"white")),r.name==="uSceneColorMap"&&(a=bo(this.device,"pink")),a||(a=bo(this.device,"pink"))),this.setTexture(r.name,a)}for(let i=0;i<e.length;i++){let r=e[i],a=r.scopeId.value;this.setStorageTexture(r.name,a)}for(let i=0;i<s.length;i++){let r=s[i],a=r.scopeId.value;this.setStorageBuffer(r.name,a)}this.uniformBufferOffsets.length=this.uniformBuffers.length;for(let i=0;i<this.uniformBuffers.length;i++){let r=this.uniformBuffers[i];this.uniformBufferOffsets[i]=r.offset,this.renderVersionUpdated<r.renderVersionDirty&&(this.dirty=!0)}this.dirty&&(this.dirty=!1,this.renderVersionUpdated=this.device.renderVersion,this.impl.update(this))}};var St={set(c,t,e,s=1){return c&~(s<<e)|t<<e},get(c,t,e=1){return c>>t&e},all(c,t,e=1){let s=e<<t;return(c&s)===s},any(c,t,e=1){return(c&e<<t)!==0}};var Kx=7,fc=15,CD=0,PD=3,wD=7,ID=11,RD=14,bD=18,xP=22,DD=23,LD=24,MD=25,OD=26,m5=15,_5=xP,Do=class Do{constructor(t=!1,e=0,s=1,i=0,r,a,o,l=!0,h=!0,f=!0,u=!0){n(this,"target0",0);this.setColorBlend(e,s,i),this.setAlphaBlend(r??e,a??s,o??i),this.setColorWrite(l,h,f,u),this.blend=t}set blend(t){this.target0=St.set(this.target0,t?1:0,OD)}get blend(){return St.all(this.target0,OD)}setColorBlend(t,e,s){this.target0=St.set(this.target0,t,CD,Kx),this.target0=St.set(this.target0,e,PD,fc),this.target0=St.set(this.target0,s,wD,fc)}setAlphaBlend(t,e,s){this.target0=St.set(this.target0,t,ID,Kx),this.target0=St.set(this.target0,e,RD,fc),this.target0=St.set(this.target0,s,bD,fc)}setColorWrite(t,e,s,i){this.redWrite=t,this.greenWrite=e,this.blueWrite=s,this.alphaWrite=i}get colorOp(){return St.get(this.target0,CD,Kx)}get colorSrcFactor(){return St.get(this.target0,PD,fc)}get colorDstFactor(){return St.get(this.target0,wD,fc)}get alphaOp(){return St.get(this.target0,ID,Kx)}get alphaSrcFactor(){return St.get(this.target0,RD,fc)}get alphaDstFactor(){return St.get(this.target0,bD,fc)}set redWrite(t){this.target0=St.set(this.target0,t?1:0,xP)}get redWrite(){return St.all(this.target0,xP)}set greenWrite(t){this.target0=St.set(this.target0,t?1:0,DD)}get greenWrite(){return St.all(this.target0,DD)}set blueWrite(t){this.target0=St.set(this.target0,t?1:0,LD)}get blueWrite(){return St.all(this.target0,LD)}set alphaWrite(t){this.target0=St.set(this.target0,t?1:0,MD)}get alphaWrite(){return St.all(this.target0,MD)}get allWrite(){return St.get(this.target0,_5,m5)}copy(t){return this.target0=t.target0,this}clone(){return new this.constructor().copy(this)}get key(){return this.target0}equals(t){return this.target0===t.target0}};n(Do,"NOBLEND",Object.freeze(new Do)),n(Do,"NOWRITE",Object.freeze(new Do(void 0,void 0,void 0,void 0,void 0,void 0,void 0,!1,!1,!1,!1))),n(Do,"ALPHABLEND",Object.freeze(new Do(!0,0,6,8))),n(Do,"ADDBLEND",Object.freeze(new Do(!0,0,1,1)));var Oe=Do;var g5=new Si,FD=7,ND=0,BD=3,uc=class uc{constructor(t=3,e=!0){n(this,"data",0);n(this,"_depthBias",0);n(this,"_depthBiasSlope",0);n(this,"key",0);this.func=t,this.write=e}set test(t){this.func=t?3:7,this.updateKey()}get test(){return this.func!==7}set write(t){this.data=St.set(this.data,t?1:0,BD),this.updateKey()}get write(){return St.all(this.data,BD)}set func(t){this.data=St.set(this.data,t,ND,FD),this.updateKey()}get func(){return St.get(this.data,ND,FD)}set depthBias(t){this._depthBias=t,this.updateKey()}get depthBias(){return this._depthBias}set depthBiasSlope(t){this._depthBiasSlope=t,this.updateKey()}get depthBiasSlope(){return this._depthBiasSlope}copy(t){return this.data=t.data,this._depthBias=t._depthBias,this._depthBiasSlope=t._depthBiasSlope,this.key=t.key,this}clone(){return new this.constructor().copy(this)}updateKey(){let{data:t,_depthBias:e,_depthBiasSlope:s}=this,i=`${t}-${e}-${s}`;this.key=g5.get(i)}equals(t){return this.key===t.key}};n(uc,"DEFAULT",Object.freeze(new uc)),n(uc,"NODEPTH",Object.freeze(new uc(7,!1))),n(uc,"WRITEDEPTH",Object.freeze(new uc(7,!0)));var Pt=uc;var S5=0,os=class{constructor(t,e,s,i=0,r,a){this.device=t,this.format=e,this.numIndices=s,this.usage=i,this.id=S5++,this.impl=t.createIndexBufferImpl(this,a);let o=gP[e];this.bytesPerIndex=o,this.numBytes=this.numIndices*o,r?this.setData(r):this.storage=new ArrayBuffer(this.numBytes),this.adjustVramSizeTracking(t._vram,this.numBytes),this.device.buffers.add(this)}destroy(){let t=this.device;t.buffers.delete(this),this.device.indexBuffer===this&&(this.device.indexBuffer=null),this.impl.initialized&&(this.impl.destroy(t),this.adjustVramSizeTracking(t._vram,-this.storage.byteLength))}adjustVramSizeTracking(t,e){t.ib+=e}loseContext(){this.impl.loseContext()}restoreContext(){this.unlock()}getFormat(){return this.format}getNumIndices(){return this.numIndices}lock(){return this.storage}unlock(){this.impl.unlock(this)}setData(t){return t.byteLength!==this.numBytes?!1:(this.storage=t,this.unlock(),!0)}_lockTypedArray(){let t=this.lock();return this.format===2?new Uint32Array(t):this.format===1?new Uint16Array(t):new Uint8Array(t)}writeData(t,e){let s=this._lockTypedArray();if(t.length>e)if(ArrayBuffer.isView(t))t=t.subarray(0,e),s.set(t);else for(let i=0;i<e;i++)s[i]=t[i];else s.set(t);this.unlock()}readData(t){let e=this._lockTypedArray(),s=this.numIndices;if(ArrayBuffer.isView(t))t.set(e);else{t.length=0;for(let i=0;i<s;i++)t[i]=e[i]}return s}};var Nd=class{constructor(){n(this,"globalId",0);n(this,"revision",0)}equals(t){return this.globalId===t.globalId&&this.revision===t.revision}copy(t){this.globalId=t.globalId,this.revision=t.revision}reset(){this.globalId=0,this.revision=0}};var UD=0,jx=class{constructor(){UD++,this.version=new Nd,this.version.globalId=UD}increment(){this.version.revision++}};var Bd=class{constructor(t){this.name=t,this.value=null,this.versionObject=new jx}toJSON(t){}setValue(t){this.value=t,this.versionObject.increment()}getValue(){return this.value}};var Ud=class{constructor(t){this.name=t,this.variables=new Map}resolve(t){return this.variables.has(t)||this.variables.set(t,new Bd(t)),this.variables.get(t)}removeValue(t){for(let e of this.variables.values())e.value===t&&(e.value=null)}};var x5=0,ft=class{constructor(t,e,s,i){n(this,"usage",0);this.usage=i?.usage??0,this.device=t,this.format=e,this.numVertices=s,this.id=x5++,this.impl=t.createVertexBufferImpl(this,e,i),this.numBytes=e.verticesByteSize?e.verticesByteSize:e.size*s,this.adjustVramSizeTracking(t._vram,this.numBytes);let r=i?.data;r?this.setData(r):this.storage=new ArrayBuffer(this.numBytes),this.device.buffers.add(this)}destroy(){let t=this.device;t.buffers.delete(this),this.impl.initialized&&(this.impl.destroy(t),this.adjustVramSizeTracking(t._vram,-this.storage.byteLength))}adjustVramSizeTracking(t,e){t.vb+=e}loseContext(){this.impl.loseContext()}restoreContext(){this.unlock()}getFormat(){return this.format}getUsage(){return this.usage}getNumVertices(){return this.numVertices}lock(){return this.storage}unlock(){this.impl.unlock(this)}setData(t){return t.byteLength!==this.numBytes?!1:(this.storage=t,this.unlock(),!0)}};function xt(c){if(c==null)return 0;let t=0;for(let e=0,s=c.length;e<s;e++)t=(t<<5)-t+c.charCodeAt(e),t|=0;return t}function dc(c){let e=2166136261;for(let s=0;s<c.length;s++)e^=c[s],e*=16777619;return e>>>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;a<o;a++){let l=e[a];r=l.components*Wn[l.type],s&&(i=R.roundUp(i,r));let h=l.asInt??!1,f=h?!1:l.normalize??!1,u={name:l.semantic,offset:s?i:l.hasOwnProperty("offset")?l.offset:i,stride:s?r:l.hasOwnProperty("stride")?l.stride:this.size,dataType:l.type,numComponents:l.components,normalize:f,size:r,asInt:h};this._elements.push(u),s?i+=r*s:i+=Math.ceil(r/4)*4,l.semantic===_t?this.hasUv0=!0:l.semantic===ri?this.hasUv1=!0:l.semantic===Ct?this.hasColor=!0:l.semantic===vs&&(this.hasTangents=!0)}s&&(this.verticesByteSize=i),this._evaluateHash()}get elements(){return this._elements}static getDefaultInstancingFormat(t){return y5.get(t,()=>new 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;r<s;r++){let{name:a,dataType:o,numComponents:l,normalize:h,offset:f,stride:u,size:d,asInt:p}=this._elements[r],m=a+o+l+h+p;t.push(m);let _=m+f+u+d;e.push(_)}t.sort();let i=t.join();this.batchingHash=xt(i),this.shaderProcessingHashString=i,this.renderingHashString=e.join("_"),this.renderingHash=v5.get(this.renderingHashString)}};var E5=new Si,qx=class qx{constructor(t={}){n(this,"_func");n(this,"_ref");n(this,"_fail");n(this,"_zfail");n(this,"_zpass");n(this,"_readMask");n(this,"_writeMask");n(this,"_dirty",!0);n(this,"_key");this._func=t.func??7,this._ref=t.ref??0,this._readMask=t.readMask??255,this._writeMask=t.writeMask??255,this._fail=t.fail??wn,this._zfail=t.zfail??wn,this._zpass=t.zpass??wn,this._evalKey()}set func(t){this._func=t,this._dirty=!0}get func(){return this._func}set ref(t){this._ref=t,this._dirty=!0}get ref(){return this._ref}set fail(t){this._fail=t,this._dirty=!0}get fail(){return this._fail}set zfail(t){this._zfail=t,this._dirty=!0}get zfail(){return this._zfail}set zpass(t){this._zpass=t,this._dirty=!0}get zpass(){return this._zpass}set readMask(t){this._readMask=t,this._dirty=!0}get readMask(){return this._readMask}set writeMask(t){this._writeMask=t,this._dirty=!0}get writeMask(){return this._writeMask}_evalKey(){let{_func:t,_ref:e,_fail:s,_zfail:i,_zpass:r,_readMask:a,_writeMask:o}=this,l=`${t},${e},${s},${i},${r},${a},${o}`;this._key=E5.get(l),this._dirty=!1}get key(){return this._dirty&&this._evalKey(),this._key}copy(t){return this._func=t._func,this._ref=t._ref,this._readMask=t._readMask,this._writeMask=t._writeMask,this._fail=t._fail,this._zfail=t._zfail,this._zpass=t._zpass,this._dirty=t._dirty,this._key=t._key,this}clone(){return new this.constructor().copy(this)}};n(qx,"DEFAULT",Object.freeze(new qx));var Ls=qx;var A5=0,Ee=class{constructor(t,e,s=0,i=!0){n(this,"id",A5++);this.device=t,this.byteSize=e,this.bufferUsage=s;let r=i?128|s:s;this.impl=t.createBufferImpl(r),this.impl.allocate(t,e),t.buffers.add(this),this.adjustVramSizeTracking(t._vram,this.byteSize)}destroy(){let t=this.device;t.buffers.delete(this),this.impl.destroy(t),this.adjustVramSizeTracking(t._vram,-this.byteSize)}loseContext(){this.impl.loseContext()}restoreContext(){this.impl.allocate(this.device,this.byteSize)}adjustVramSizeTracking(t,e){t.sb+=e}read(t=0,e=this.byteSize,s=null,i=!1){return this.impl.read(this.device,t,e,s,i)}write(t=0,e,s=0,i){this.impl.write(this.device,t,e,s,i)}clear(t=0,e=this.byteSize){this.impl.clear(this.device,t,e)}copy(t,e=0,s=0,i=t.byteSize-e){this.device.getCommandEncoder().copyBufferToBuffer(t.impl.buffer,e,this.impl.buffer,s,i)}};var $x=class $x extends J{constructor(e,s){var i,r,a,o,l,h,f;super();n(this,"canvas");n(this,"backBuffer",null);n(this,"backBufferSize",new B);n(this,"backBufferFormat");n(this,"backBufferAntialias",!1);n(this,"isWebGPU",!1);n(this,"isWebGL2",!1);n(this,"isNull",!1);n(this,"isHdr",!1);n(this,"scope");n(this,"maxIndirectDrawCount",1024);n(this,"maxIndirectDispatchCount",256);n(this,"maxAnisotropy");n(this,"maxCubeMapSize");n(this,"maxTextureSize");n(this,"maxVolumeSize");n(this,"maxColorAttachments",1);n(this,"precision");n(this,"samples");n(this,"maxSamples",1);n(this,"supportsStencil");n(this,"supportsMultiDraw",!0);n(this,"supportsCompute",!1);n(this,"supportsStorageTextureRead",!1);n(this,"supportsSubgroups",!1);n(this,"supportsSubgroupUniformity",!1);n(this,"supportsSubgroupId",!1);n(this,"supportsLinearIndexing",!1);n(this,"supportsPointerCompositeAccess",!1);n(this,"supportsPacked4x8IntegerDotProduct",!1);n(this,"supportsTextureAndSamplerLet",!1);n(this,"supportsUnrestrictedPointerParameters",!1);n(this,"maxSubgroupSize",0);n(this,"minSubgroupSize",0);n(this,"renderTarget",null);n(this,"shaders",[]);n(this,"textures",new Set);n(this,"texturesToUpload",new Set);n(this,"targets",new Set);n(this,"renderVersion",0);n(this,"renderPassIndex");n(this,"insideRenderPass",!1);n(this,"supportsUniformBuffers",!1);n(this,"supportsClipDistances",!1);n(this,"supportsTextureFormatTier1",!1);n(this,"supportsTextureFormatTier2",!1);n(this,"supportsPrimitiveIndex",!1);n(this,"supportsShaderF16",!1);n(this,"supportsHtmlTextures",!1);n(this,"textureFloatRenderable");n(this,"textureHalfFloatRenderable");n(this,"textureRG11B10Renderable",!1);n(this,"textureFloatFilterable",!1);n(this,"quadVertexBuffer");n(this,"quadIndexBuffer");n(this,"blendState",new Oe);n(this,"depthState",new Pt);n(this,"stencilEnabled",!1);n(this,"stencilFront",new Ls);n(this,"stencilBack",new Ls);n(this,"dynamicBuffers");n(this,"gpuProfiler");n(this,"_destroyed",!1);n(this,"defaultClearOptions",{color:[0,0,0,1],depth:1,stencil:0,flags:3});n(this,"clientRect",{width:0,height:0});n(this,"_shadersDirty",!1);n(this,"capsDefines",new Map);n(this,"mapsToClear",new Set);this.canvas=e,"setAttribute"in e&&e.setAttribute("data-engine",`PlayCanvas ${Ju}`),this.initOptions={...s},(i=this.initOptions).alpha??(i.alpha=!0),(r=this.initOptions).depth??(r.depth=!0),(a=this.initOptions).stencil??(a.stencil=!0),(o=this.initOptions).antialias??(o.antialias=!0),(l=this.initOptions).powerPreference??(l.powerPreference="high-performance"),(h=this.initOptions).displayFormat??(h.displayFormat=pP),(f=this.initOptions).xrCompatible??(f.xrCompatible=ue.browser&&!!navigator.xr),this._maxPixelRatio=ue.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 u=Aa;u<=dr;u++)this._primsPerFrame[u]=0;this._renderTargetCreationTime=0,this.scope=new Ud("Device"),this.textureBias=this.scope.resolve("textureBias"),this.textureBias.setValue(0)}postInit(){let e=new Ft(this,[{semantic:ee,components:2,type:ye}]),s=new Float32Array([-1,-1,1,-1,-1,1,1,1]);this.quadVertexBuffer=new ft(this,e,4,{data:s});let i=new Uint16Array([0,1,2,2,1,3]);this.quadIndexBuffer=new os(this,1,6,0,i.buffer)}initCapsDefines(){let{capsDefines:e}=this;e.clear(),this.textureFloatFilterable&&e.set("CAPS_TEXTURE_FLOAT_FILTERABLE",""),this.textureFloatRenderable&&e.set("CAPS_TEXTURE_FLOAT_RENDERABLE",""),this.supportsMultiDraw&&e.set("CAPS_MULTI_DRAW",""),this.supportsPrimitiveIndex&&e.set("CAPS_PRIMITIVE_INDEX",""),this.supportsShaderF16&&e.set("CAPS_SHADER_F16",""),this.supportsSubgroups&&e.set("CAPS_SUBGROUPS",""),this.supportsSubgroupId&&e.set("CAPS_SUBGROUP_ID",""),this.supportsLinearIndexing&&e.set("CAPS_LINEAR_INDEXING",""),this.supportsUnrestrictedPointerParameters&&e.set("CAPS_UNRESTRICTED_POINTER_PARAMETERS",""),this.supportsPointerCompositeAccess&&e.set("CAPS_POINTER_COMPOSITE_ACCESS",""),this.supportsPacked4x8IntegerDotProduct&&e.set("CAPS_PACKED_4X8_INTEGER_DOT_PRODUCT",""),this.supportsTextureAndSamplerLet&&e.set("CAPS_TEXTURE_AND_SAMPLER_LET",""),this.supportsStorageTextureRead&&e.set("CAPS_STORAGE_TEXTURE_READ",""),ue.desktop&&e.set("PLATFORM_DESKTOP",""),ue.mobile&&e.set("PLATFORM_MOBILE",""),ue.android&&e.set("PLATFORM_ANDROID",""),ue.ios&&e.set("PLATFORM_IOS","")}destroy(){this.fire("destroy"),this.quadVertexBuffer?.destroy(),this.quadVertexBuffer=null,this.quadIndexBuffer?.destroy(),this.quadIndexBuffer=null,this.dynamicBuffers?.destroy(),this.dynamicBuffers=null,this.gpuProfiler?.destroy(),this.gpuProfiler=null,this._destroyed=!0}onDestroyShader(e){this.fire("destroy:shader",e);let s=this.shaders.indexOf(e);s!==-1&&this.shaders.splice(s,1)}onTextureDestroyed(e){this.textures.delete(e),this.texturesToUpload.delete(e),this.scope.removeValue(e)}postDestroy(){this.scope=null,this.canvas=null}loseContext(){this.contextLost=!0,this.backBufferSize.set(-1,-1);for(let e of this.textures)e.loseContext();for(let e of this.buffers)e.loseContext();for(let e of this.targets)e.loseContext();this.gpuProfiler?.loseContext()}restoreContext(){this.contextLost=!1,this.initializeRenderState(),this.initializeContextCaches();for(let e of this.buffers)e.restoreContext();this.gpuProfiler?.restoreContext?.()}toJSON(e){}initializeContextCaches(){this.vertexBuffers=[],this.shader=null,this.shaderValid=void 0,this.shaderAsyncCompile=!1,this.renderTarget=null}initializeRenderState(){this.blendState=new Oe,this.depthState=new Pt,this.cullMode=1,this.frontFace=0,this.vx=this.vy=this.vw=this.vh=0,this.sx=this.sy=this.sw=this.sh=0,this.blendColor=new F(0,0,0,0)}setStencilState(e,s){}setBlendState(e){}setBlendColor(e,s,i,r){}setDepthState(e){}setCullMode(e){}setFrontFace(e){}setDrawStates(e=Oe.NOBLEND,s=Pt.NODEPTH,i=0,r=0,a,o){this.setBlendState(e),this.setDepthState(s),this.setCullMode(i),this.setFrontFace(r),this.setStencilState(a,o)}setRenderTarget(e){this.renderTarget=e}setVertexBuffer(e){e&&this.vertexBuffers.push(e)}clearVertexBuffer(){this.vertexBuffers.length=0}getIndirectDrawSlot(e=1){return 0}get indirectDrawBuffer(){return null}getIndirectDispatchSlot(e=1){return 0}get indirectDispatchBuffer(){return null}getRenderTarget(){return this.renderTarget}initRenderTarget(e){e.initialized||(e.init(),this.targets.add(e))}draw(e,s,i,r,a=!0,o=!0){}_isBrowserInterface(e){return this._isImageBrowserInterface(e)||this._isImageCanvasInterface(e)||this._isImageVideoInterface(e)||this._isHTMLElementInterface(e)}_isImageBrowserInterface(e){return typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement}_isImageCanvasInterface(e){return typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement}_isImageVideoInterface(e){return typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement}_isHTMLElementInterface(e){return typeof HTMLElement<"u"&&e instanceof HTMLElement&&!(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement)&&!(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement)&&!(typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement)}resizeCanvas(e,s){let i=Math.min(this._maxPixelRatio,ue.browser?window.devicePixelRatio:1),r=Math.floor(e*i),a=Math.floor(s*i);(r!==this.canvas.width||a!==this.canvas.height)&&this.setResolution(r,a)}setResolution(e,s){this.canvas.width=e,this.canvas.height=s,this.fire($x.EVENT_RESIZE,e,s)}update(){this.updateClientRect()}updateClientRect(){if(ue.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!1}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,s="Unnamed"){}getRenderableHdrFormat(e=[Gi,Me,ke],s=!0,i=1){for(let r=0;r<e.length;r++){let a=e[r];switch(a){case Gi:{if(this.textureRG11B10Renderable)return a;break}case Me:if(this.textureHalfFloatRenderable)return a;break;case ke:if(this.isWebGPU&&i>1)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<c.length;e++)if(c[e]!==t[e])return!1;return!0}};var Yn=[];Yn[js]="sint8";Yn[ai]="uint8";Yn[qs]="sint16";Yn[Ri]="uint16";Yn[He]="sint32";Yn[kt]="uint32";Yn[ye]="float32";Yn[nc]="float16";var Kn=[];Kn[js]="snorm8";Kn[ai]="unorm8";Kn[qs]="snorm16";Kn[Ri]="unorm16";Kn[He]="sint32";Kn[kt]="uint32";Kn[ye]="float32";Kn[nc]="float16";var tv=class{constructor(){n(this,"cache",new Map)}get(t,e=null){let s=this.getKey(t,e),i=this.cache.get(s);return i||(i=this.create(t,e),this.cache.set(s,i)),i}getKey(t,e=null){return`${t?.renderingHashString}-${e?.renderingHashString}`}create(t,e){let s=[],i=r=>{let a=r.interleaved,o=r.instancing?"instance":"vertex",l=[],h=r.elements.length;for(let f=0;f<h;f++){let u=r.elements[f],d=ze[u.name],p=u.normalize?Kn:Yn;l.push({shaderLocation:d,offset:a?u.offset:0,format:`${p[u.dataType]}${u.numComponents>1?`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;A<C.length;A++){let w=C[A];if(ev.equals(w.hashes,g))return w.pipeline}let v=R5[S],E=this.getPipelineLayout(l),y=this.vertexBufferLayout.get(s,i),P=new TP;return P.hashes=new Uint32Array(g),P.pipeline=this.create(v,r,a,o,E,h,f,y,u,d,p,m,_),C?C.push(P):C=[P],this.cache.set(T,C),P.pipeline}getBlend(e){let s;return e.blend&&(s={color:{operation:kD[e.colorOp],srcFactor:sv[e.colorSrcFactor],dstFactor:sv[e.colorDstFactor]},alpha:{operation:kD[e.alphaOp],srcFactor:sv[e.alphaSrcFactor],dstFactor:sv[e.alphaDstFactor]}}),s}getDepthStencil(e,s,i,r,a,o){let l,{depth:h,stencil:f}=s;if(h||f){if(l={format:s.impl.depthAttachment.format},h){l.depthWriteEnabled=e.write,l.depthCompare=vP[e.func];let u=o==="triangle-list"||o==="triangle-strip";l.depthBias=u?e.depthBias:0,l.depthBiasSlopeScale=u?e.depthBiasSlope:0}else l.depthWriteEnabled=!1,l.depthCompare="always";f&&i&&(l.stencilReadMas=r.readMask,l.stencilWriteMask=r.writeMask,l.stencilFront={compare:vP[r.func],failOp:Hd[r.fail],passOp:Hd[r.zpass],depthFailOp:Hd[r.zfail]},l.stencilBack={compare:vP[a.func],failOp:Hd[a.fail],passOp:Hd[a.zpass],depthFailOp:Hd[a.zfail]})}return l}create(e,s,i,r,a,o,l,h,f,u,d,p,m){let _=this.device.wgpu,S=i.impl,g={vertex:{module:S.getVertexShaderModule(),entryPoint:S.vertexEntryPoint,buffers:h},primitive:{topology:e,frontFace:D5[m],cullMode:b5[f]},depthStencil:this.getDepthStencil(l,r,u,d,p,e),multisample:{count:r.samples},layout:a};s&&(g.primitive.stripIndexFormat=L5[s]),g.fragment={module:S.getFragmentShaderModule(),entryPoint:S.fragmentEntryPoint,targets:[]};let T=r.impl.colorAttachments;if(T.length>0){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<a.length;h++){let f=a[h];if(ev.equals(f.hashes,i))return f.pipeline}let o=this.getPipelineLayout([s.impl]),l=new yP;return l.hashes=new Uint32Array(i),l.pipeline=this.create(e,o),a?a.push(l):a=[l],this.cache.set(r,a),l.pipeline}create(e,s){let i=this.device.wgpu,r=e.impl,a={compute:{module:r.getComputeShaderModule(),entryPoint:r.computeEntryPoint},layout:s};return M5++,i.createComputePipeline(a)}};var Mo=class{constructor(){n(this,"_refCount",0)}incRefCount(){this._refCount++}decRefCount(){this._refCount--}get refCount(){return this._refCount}};var EP=class extends Mo{constructor(e){super();n(this,"object");this.object=e,this.incRefCount()}},av=class{constructor(){n(this,"cache",new Map)}destroy(){this.cache.forEach(t=>{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;r<i;++r){let a=this.initColor(t,s,e,r),o=r===0&&this.colorAttachments[0]?.format;(a.view||o)&&this.renderPassDescriptor.colorAttachments.push(a)}this.updateKey(),this.initialized=!0}initDepthStencil(t,e,s){let{samples:i,width:r,height:a,depth:o,depthBuffer:l}=s;if(o||l){let h;if(l)if(this.depthAttachment=new ov(l.impl.format),i>1){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;r<s;++r){let a=this.renderPassDescriptor.colorAttachments[r],o=t.colorArrayOps[r],l=e.isColorBufferSrgb(r);a.clearValue=l?o.clearValueLinear:o.clearValue,a.loadOp=o.clear?"clear":"load",a.storeOp=o.store?"store":"discard"}let i=this.renderPassDescriptor.depthStencilAttachment;i&&(i.depthClearValue=t.depthStencilOps.clearDepthValue,i.depthLoadOp=t.depthStencilOps.clearDepth?"clear":"load",i.depthStoreOp=t.depthStencilOps.storeDepth?"store":"discard",i.depthReadOnly=!1,this.depthAttachment.hasStencil&&(i.stencilClearValue=t.depthStencilOps.clearStencilValue,i.stencilLoadOp=t.depthStencilOps.clearStencil?"clear":"load",i.stencilStoreOp=t.depthStencilOps.storeStencil?"store":"discard",i.stencilReadOnly=!1))}loseContext(){this.initialized=!1}resolve(t,e,s,i){}};var Ts=[];Ts[Te]=1;Ts[pr]=2;Ts[Kt]=3;Ts[oi]=4;Ts[bi]=1;Ts[jr]=2;Ts[Di]=3;Ts[qr]=4;Ts[wo]=1;Ts[Dn]=2;Ts[Ln]=3;Ts[Mn]=4;Ts[lc]=8;Ts[La]=12;Ts[as]=16;Ts[pe]=1;Ts[Ma]=2;Ts[Oa]=3;Ts[Li]=4;var Y=class{constructor(t,e,s=0){n(this,"name");n(this,"type");n(this,"byteSize");n(this,"offset");n(this,"scopeId");n(this,"count");n(this,"numComponents");if(this.shortName=t,this.name=s?`${t}[0]`:t,this.type=e,this.numComponents=Ts[e],this.updateType=e,s>0)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;i<e.length;i++){let r=e[i];r.calculateOffset(s),s=r.offset*4+r.byteSize,r.scopeId=this.scope.resolve(r.name),this.map.set(r.name,r)}this.byteSize=R.roundUp(s,16)}get(t){return this.map.get(t)}};var zD=/[ \t]*(\battribute\b|\bvarying\b|\buniform\b)/g,PP=/(\battribute\b|\bvarying\b|\bout\b|\buniform\b)[ \t]*([^;]+)(;+)/g,wP="@@@",N5=/([\w-]+)\[(.*?)\]/,B5=new Set(["highp","mediump","lowp"]),U5=new Set(["sampler2DShadow","samplerCubeShadow","sampler2DArrayShadow"]),k5={sampler2D:Ds,sampler3D:bn,samplerCube:Kr,samplerCubeShadow:Kr,sampler2DShadow:Ds,sampler2DArray:Yr,sampler2DArrayShadow:Yr,isampler2D:Ds,usampler2D:Ds,isampler3D:bn,usampler3D:bn,isamplerCube:Kr,usamplerCube:Kr,isampler2DArray:Yr,usampler2DArray:Yr},z5={[Ds]:"texture2D",[Kr]:"textureCube",[bn]:"texture3D",[Yr]:"texture2DArray"},IP=class{constructor(t,e){this.line=t;let s=t.trim().split(/\s+/);if(B5.has(s[0])&&(this.precision=s.shift()),this.type=s.shift(),t.includes(","),t.includes("[")){let i=s.join(" "),r=N5.exec(i);this.name=r[1],this.arraySize=Number(r[2]),isNaN(this.arraySize)&&(e.failed=!0)}else this.name=s.shift(),this.arraySize=0;this.isSampler=this.type.indexOf("sampler")!==-1,this.isSignedInt=this.type.indexOf("isampler")!==-1,this.isUnsignedInt=this.type.indexOf("usampler")!==-1}},lv=class c{static run(t,e,s){let i=new Map,r=c.extract(e.vshader),a=c.extract(e.fshader),o=new Map,l=c.processAttributes(r.attributes,e.attributes,o,e.processingOptions),h=c.processVaryings(r.varyings,i,!0),f=c.processVaryings(a.varyings,i,!1),u=c.processOuts(a.outs),d=r.uniforms.concat(a.uniforms),m=Array.from(new Set(d)).map(v=>new 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*(?:(<storage,[^>]*>)\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<private> ${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*<storage,\s*(read|write)?>\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<e.length;l++){let h=e[l];if(h.isTexture){let f=e[l+1],u=f?.isSampler,d=h.sampleType,p=h.textureDimension;r.push(new Ki(h.name,Xi|Yi,p,d,u,u?f.name:null)),u&&l++}if(h.isStorageBuffer){let f=h.accessMode!=="read_write",u=new K(h.name,Xi|Yi,f);u.format=h.type,r.push(u)}}let a=new Ue(t,r),o="";return s.bindGroupFormats.forEach((l,h)=>{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<uniform> ub_${i} : ${r};
`,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<storage, ${r}> ${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<private> ${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}
};
${KD(f)}
${l}
// 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<e;a++){let o=i(a);t.search(new RegExp(`\\.${o}\\s*=`))!==-1&&(s+=` @location(${a}) ${o} : pcOutType${a},
`)}return t.search(/\.fragDepth\s*=/)!==-1&&(s+=` @builtin(frag_depth) fragDepth : f32
`),`${s}};
`}static floatAttributeToInt(t,e){let i={f32:"f32","vec2<f32>":"vec2f","vec3<f32>":"vec3f","vec4<f32>":"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<private> ${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;a<r;a++){let o=e._levels[a];if(o){if(e.cubemap)for(let l=0;l<6;l++){let h=o[l];h?this.isExternalImage(h)?(this.uploadExternalImage(t,h,a,l),s=!0):ArrayBuffer.isView(h)&&(this.uploadTypedArrayData(t,h,a,l),s=!0):i=!0}else if(!e._volume)if(e.array)if(e.arrayLength===o.length)for(let l=0;l<e._arrayLength;l++){let h=o[l];this.isExternalImage(h)?(this.uploadExternalImage(t,h,a,l),s=!0):ArrayBuffer.isView(h)&&(this.uploadTypedArrayData(t,h,a,l),s=!0)}else i=!0;else t._isHTMLElementInterface(o)&&t.supportsHtmlTextures?(this.uploadElementImage(t,o,a,0),s=!0):this.isExternalImage(o)?(this.uploadExternalImage(t,o,a,0),s=!0):ArrayBuffer.isView(o)&&(this.uploadTypedArrayData(t,o,a,0),s=!0)}else i=!0}s&&i&&e.mipmaps&&!En(e.format)&&!ur(e.format)&&t.mipmapRenderer.generate(this),e._gpuSize&&e.adjustVramSizeTracking(t._vram,-e._gpuSize),e._gpuSize=e.gpuSize,e.adjustVramSizeTracking(t._vram,e._gpuSize),e.releaseSourceAfterUpload&&e.releaseImageSources()}}isExternalImage(t){return typeof ImageBitmap<"u"&&t instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas}uploadExternalImage(t,e,s,i){let r={source:e,origin:[0,0],flipY:!1},a={texture:this.gpuTexture,mipLevel:s,origin:[0,0,i],aspect:"all",premultipliedAlpha:this.texture._premultiplyAlpha},o={width:this.desc.size.width,height:this.desc.size.height,depthOrArrayLayers:1};t.submit(),Q5(e instanceof HTMLCanvasElement&&e.getContext("2d")),t.wgpu.queue.copyExternalImageToTexture(r,a,o)}uploadElementImage(t,e,s,i){let r={texture:this.gpuTexture,mipLevel:s,origin:[0,0,i],aspect:"all",premultipliedAlpha:this.texture._premultiplyAlpha},a=gt.calcLevelDimension(this.texture.width,s),o=gt.calcLevelDimension(this.texture.height,s);t.submit();let l={source:e},h={destination:r,width:a,height:o};t.wgpu.queue.copyElementImageToTexture(l,h)}uploadTypedArrayData(t,e,s,i){let r=this.texture,a=t.wgpu,o={texture:this.gpuTexture,origin:[0,0,i],mipLevel:s},l=gt.calcLevelDimension(r.width,s),h=gt.calcLevelDimension(r.height,s),f=gt.calcLevelGpuSize(l,h,1,r.format),u=xs.get(r.format),d,p;if(u.size)d={offset:0,bytesPerRow:u.size*l,rowsPerImage:h},p={width:l,height:h};else if(u.blockSize){let m=_=>Math.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<i;w++){let I=w*p,D=w*d;A.set(E.subarray(I,I+d),D)}return l??new y(P)})}};var dv=class extends Lo{constructor(t){super(64)}unlock(t){let e=t.device;super.unlock(e,t.storageInt32.buffer)}};var pv=class extends Lo{constructor(t,e,s){super(32|(s?.storage?128:0))}unlock(t){let e=t.device;super.unlock(e,t.storage)}};var ka=/[ \t]*#(ifn?def|if|endif|else|elif|define|undef|extension|include)/g,OP=/define[ \t]+([^\n]+)\r?(?:\n|$)/g,ZD=/extension[ \t]+([\w-]+)[ \t]*:[ \t]*(enable|require)/g,FP=/undef[ \t]+([^\n]+)\r?(?:\n|$)/g,NP=/(ifdef|ifndef|if)[ \t]*([^\r\n]+)\r?\n/g,BP=/(endif|else|elif)(?:[ \t]+([^\r\n]*))?\r?\n?/g,QD=/\{?[\w-]+\}?/,J5=/(!|\s)?defined\(([\w-]+)\)/,eW=/!?defined\s*\([^)]*\)/g,tW=/!?defined\s*$/,sW=/([a-z_]\w*)\s*(==|!=|<|<=|>|>=)\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;l<a.length;l++){let h=a[l].match(JD);if(h){let f=parseInt(h[0].charAt(h[0].length-1),10);if(f>0&&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;o<s.length;o++)s[o].includes("#")||(s[o]=s[o].replace(a,i))}),t=s.join(`
`)}return t}static RemoveEmptyLines(t){return t!==null&&(t=t.split(/\r?\n/).map(e=>e.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;C<g;C++)T+=_.replace(rW,String(C));_=T}else l=!0}t=t.substring(0,u.index-1)+_+t.substring(UP.lastIndex),ka.lastIndex=u.index-1}else{l=!0;continue}}break}}}return o.length>0&&(l=!0),l?null:t}static _keep(t){for(let e=0;e<t.length;e++)if(!t[e].keep)return!1;return!0}static evaluateAtomicExpression(t,e){let s=!1;t=t.trim();let i=!1;if(t==="true")return{result:!0,error:s};if(t==="false")return{result:!1,error:s};if(aW.test(t))return{result:parseFloat(t)!==0,error:s};let r=J5.exec(t);if(r){i=r[1]==="!",t=r[2].trim();let l=e.has(t);return{result:i?!l:l,error:s}}let a=sW.exec(t);if(a){let l=e.get(a[1].trim())??a[1].trim(),h=e.get(a[3].trim())??a[3].trim(),f=a[2].trim(),u=!1;switch(f){case"==":u=l===h;break;case"!=":u=l!==h;break;case"<":u=l<h;break;case"<=":u=l<=h;break;case">":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;o<i.length-1;o++)if(i[o]==="(")r++;else if(i[o]===")"&&(r--,r===0)){a=!1;break}if(a)i=i.slice(1,-1).trim();else break}for(;;){let r=!1,a=0,o=0,l=-1,h=-1,f=0;for(let m=0;m<i.length;m++)if(i[m]==="("){let _=i.substring(0,m);tW.test(_)?f++:f===0&&(a++,a>o&&(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
layout(location = 0) out highp outType_0 pcFragColor0;
#if COLOR_ATTACHMENT_1
layout(location = 1) out highp outType_1 pcFragColor1;
#endif
#if COLOR_ATTACHMENT_2
layout(location = 2) out highp outType_2 pcFragColor2;
#endif
#if COLOR_ATTACHMENT_3
layout(location = 3) out highp outType_3 pcFragColor3;
#endif
#if COLOR_ATTACHMENT_4
layout(location = 4) out highp outType_4 pcFragColor4;
#endif
#if COLOR_ATTACHMENT_5
layout(location = 5) out highp outType_5 pcFragColor5;
#endif
#if COLOR_ATTACHMENT_6
layout(location = 6) out highp outType_6 pcFragColor6;
#endif
#if COLOR_ATTACHMENT_7
layout(location = 7) out highp outType_7 pcFragColor7;
#endif
#define gl_FragColor pcFragColor0
#define varying in
#define texture2D texture
#define texture2DBias texture
#define textureCube texture
#define texture2DProj textureProj
#define texture2DLod textureLod
#define texture2DProjLod textureProjLod
#define textureCubeLod textureLod
#define texture2DGrad textureGrad
#define texture2DProjGrad textureProjGrad
#define textureCubeGrad textureGrad
#define utexture2D texture
#define itexture2D texture
#define texture2DLodEXT texture2DLodEXT_is_no_longer_supported_use_texture2DLod_instead
#define texture2DProjLodEXT texture2DProjLodEXT_is_no_longer_supported_use_texture2DProjLod
#define textureCubeLodEXT textureCubeLodEXT_is_no_longer_supported_use_textureCubeLod_instead
#define texture2DGradEXT texture2DGradEXT_is_no_longer_supported_use_texture2DGrad_instead
#define texture2DProjGradEXT texture2DProjGradEXT_is_no_longer_supported_use_texture2DProjGrad_instead
#define textureCubeGradEXT textureCubeGradEXT_is_no_longer_supported_use_textureCubeGrad_instead
#define textureShadow(res, uv) textureGrad(res, uv, vec2(1, 1), vec2(1, 1))
#define SHADOWMAP_PASS(name) name
#define SHADOWMAP_ACCEPT(name) sampler2DShadow name
#define TEXTURE_PASS(name) name
#define TEXTURE_ACCEPT(name) sampler2D name
#define TEXTURE_ACCEPT_HIGHP(name) highp sampler2D name
#define GL2
`;var _v=`
#extension GL_ANGLE_multi_draw : enable
#define attribute in
#define varying out
#define texture2D texture
#define utexture2D texture
#define itexture2D texture
#define GL2
#define VERTEXSHADER
#define TEXTURE_PASS(name) name
#define TEXTURE_ACCEPT(name) sampler2D name
#define TEXTURE_ACCEPT_HIGHP(name) highp sampler2D name
`;var gv=`
#extension GL_EXT_samplerless_texture_functions : require
#ifndef outType_0
#define outType_0 vec4
#endif
#ifndef outType_1
#define outType_1 vec4
#endif
#ifndef outType_2
#define outType_2 vec4
#endif
#ifndef outType_3
#define outType_3 vec4
#endif
#ifndef outType_4
#define outType_4 vec4
#endif
#ifndef outType_5
#define outType_5 vec4
#endif
#ifndef outType_6
#define outType_6 vec4
#endif
#ifndef outType_7
#define outType_7 vec4
#endif
layout(location = 0) out highp outType_0 pcFragColor0;
layout(location = 1) out highp outType_1 pcFragColor1;
layout(location = 2) out highp outType_2 pcFragColor2;
layout(location = 3) out highp outType_3 pcFragColor3;
layout(location = 4) out highp outType_4 pcFragColor4;
layout(location = 5) out highp outType_5 pcFragColor5;
layout(location = 6) out highp outType_6 pcFragColor6;
layout(location = 7) out highp outType_7 pcFragColor7;
#define gl_FragColor pcFragColor0
#define texture2D(res, uv) texture(sampler2D(res, res ## _sampler), uv)
#define texture2DBias(res, uv, bias) texture(sampler2D(res, res ## _sampler), uv, bias)
#define texture2DLod(res, uv, lod) textureLod(sampler2D(res, res ## _sampler), uv, lod)
#define textureCube(res, uv) texture(samplerCube(res, res ## _sampler), uv)
#define textureCubeLod(res, uv, lod) textureLod(samplerCube(res, res ## _sampler), uv, lod)
#define textureShadow(res, uv) textureLod(sampler2DShadow(res, res ## _sampler), uv, 0.0)
#define itexture2D(res, uv) texture(isampler2D(res, res ## _sampler), uv)
#define utexture2D(res, uv) texture(usampler2D(res, res ## _sampler), uv)
#define texture2DLodEXT texture2DLodEXT_is_no_longer_supported_use_texture2DLod_instead
#define texture2DProjLodEXT texture2DProjLodEXT_is_no_longer_supported_use_texture2DProjLod
#define textureCubeLodEXT textureCubeLodEXT_is_no_longer_supported_use_textureCubeLod_instead
#define texture2DGradEXT texture2DGradEXT_is_no_longer_supported_use_texture2DGrad_instead
#define texture2DProjGradEXT texture2DProjGradEXT_is_no_longer_supported_use_texture2DProjGrad_instead
#define textureCubeGradEXT textureCubeGradEXT_is_no_longer_supported_use_textureCubeGrad_instead
#define SHADOWMAP_PASS(name) name, name ## _sampler
#define SHADOWMAP_ACCEPT(name) texture2D name, sampler name ## _sampler
#define TEXTURE_PASS(name) name, name ## _sampler
#define TEXTURE_ACCEPT(name) texture2D name, sampler name ## _sampler
#define TEXTURE_ACCEPT_HIGHP TEXTURE_ACCEPT
#define GL2
#define WEBGPU
`;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)
#define utexture2D(res, uv) texture(usampler2D(res, res ## _sampler), uv)
#define TEXTURE_PASS(name) name, name ## _sampler
#define TEXTURE_ACCEPT(name) texture2D name, sampler name ## _sampler
#define TEXTURE_ACCEPT_HIGHP TEXTURE_ACCEPT
#define GL2
#define WEBGPU
#define VERTEXSHADER
#define gl_VertexID gl_VertexIndex
#define gl_InstanceID gl_InstanceIndex
`;var xv=`
`;var vv=`
#define VERTEXSHADER
`;var kP=`
vec2 getGrabScreenPos(vec4 clipPos) {
vec2 uv = (clipPos.xy / clipPos.w) * 0.5 + 0.5;
#ifdef WEBGPU
uv.y = 1.0 - uv.y;
#endif
return uv;
}
vec2 getImageEffectUV(vec2 uv) {
#ifdef WEBGPU
uv.y = 1.0 - uv.y;
#endif
return uv;
}
`;var zP=`
#define WEBGPU
fn getGrabScreenPos(clipPos: vec4<f32>) -> vec2<f32> {
var uv: vec2<f32> = (clipPos.xy / clipPos.w) * 0.5 + vec2<f32>(0.5);
uv.y = 1.0 - uv.y;
return uv;
}
fn getImageEffectUV(uv: vec2<f32>) -> vec2<f32> {
var modifiedUV: vec2<f32> = uv;
modifiedUV.y = 1.0 - modifiedUV.y;
return modifiedUV;
}
struct WrappedF32 { @size(16) element: f32 }
struct WrappedI32 { @size(16) element: i32 }
struct WrappedU32 { @size(16) element: u32 }
struct WrappedVec2F { @size(16) element: vec2f }
struct WrappedVec2I { @size(16) element: vec2i }
struct WrappedVec2U { @size(16) element: vec2u }
`;var Ug=`
#ifdef CAPS_SHADER_F16
alias half = f16;
alias half2 = vec2<f16>;
alias half3 = vec3<f16>;
alias half4 = vec4<f16>;
alias half2x2 = mat2x2<f16>;
alias half3x3 = mat3x3<f16>;
alias half4x4 = mat4x4<f16>;
#else
alias half = f32;
alias half2 = vec2f;
alias half3 = vec3f;
alias half4 = vec4f;
alias half2x2 = mat2x2f;
alias half3x3 = mat3x3f;
alias half4x4 = mat4x4f;
#endif
`;var oW={vertex_position:ee,vertex_normal:Ot,vertex_tangent:vs,vertex_texCoord0:_t,vertex_texCoord1:ri,vertex_texCoord2:Ca,vertex_texCoord3:Pa,vertex_texCoord4:wa,vertex_texCoord5:Ia,vertex_texCoord6:Ra,vertex_texCoord7:ba,vertex_color:Ct,vertex_boneIndices:$t,vertex_boneWeights:bs},ns=class c{static createDefinition(t,e){let s=d=>{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<t.maxColorAttachments;C++){g+=`#define COLOR_ATTACHMENT_${C}
`;let v=T[C]??"vec4";g+=`#define outType_${C} ${v}
`}}return g+S},r=(d,p)=>{let m=c.getWGSLEnables(t,d?"vertex":"fragment");if(!d){let _=s(p);for(let S=0;S<t.maxColorAttachments;S++){let g=_[S]??"vec4",T=Bg.get(g);m+=`alias pcOutType${S} = ${T};
`}}return m},a=e.name??"Untitled",o,l,h=c.getDefinesCode(t,e.vertexDefines),f=c.getDefinesCode(t,e.fragmentDefines);return e.shaderLanguage===se?(o=`
${r(!0,e)}
${h}
${Ug}
${vv}
${zP}
${e.vertexCode}
`,l=`
${r(!1,e)}
${f}
${Ug}
${xv}
${zP}
${e.fragmentCode}
`):(o=`${c.versionCode(t)+i(Sv,_v,!0,e)+h+c.precisionCode(t)}
${kP}
${c.getShaderNameCode(a)}
${e.vertexCode}`,l=`${(e.fragmentPreamble||"")+c.versionCode(t)+i(gv,mv,!1,e)+f+c.precisionCode(t)}
${kP}
${c.getShaderNameCode(a)}
${e.fragmentCode}`),{name:a,shaderLanguage:e.shaderLanguage??fe,attributes:e.attributes,vshader:o,vincludes:e.vertexIncludes,fincludes:e.fragmentIncludes,fshader:l,feedbackVaryings:e.feedbackVaryings,useTransformFeedback:e.useTransformFeedback,meshUniformBufferFormat:e.meshUniformBufferFormat,meshBindGroupFormat:e.meshBindGroupFormat}}static getWGSLEnables(t,e){let s="";return t.supportsShaderF16&&(s+=`enable f16;
`),e==="fragment"&&t.supportsPrimitiveIndex&&(s+=`enable primitive_index;
`),t.supportsSubgroups&&(s+=`enable subgroups;
`),t.supportsSubgroupId&&(s+=`requires subgroup_id;
`),e==="compute"&&t.supportsLinearIndexing&&(s+=`requires linear_indexing;
`),t.supportsUnrestrictedPointerParameters&&(s+=`requires unrestricted_pointer_parameters;
`),t.supportsPointerCompositeAccess&&(s+=`requires pointer_composite_access;
`),t.supportsPacked4x8IntegerDotProduct&&(s+=`requires packed_4x8_integer_dot_product;
`),t.supportsTextureAndSamplerLet&&(s+=`requires texture_and_sampler_let;
`),s}static getDefinesCode(t,e){let s="";return t.capsDefines.forEach((i,r)=>{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<e&&this.scheduleSubmit()}if(!this.activeBuffer){let r=this.gpuBuffers.pop();r||(r=this.createBuffer(this.device,this.bufferSize,!1));let a=this.stagingBuffers.pop();a||(a=this.createBuffer(this.device,this.bufferSize,!0)),this.activeBuffer=new GP,this.activeBuffer.stagingBuffer=a,this.activeBuffer.gpuBuffer=r,this.activeBuffer.offset=0,this.activeBuffer.size=0}let s=this.activeBuffer,i=R.roundUp(s.size,this.bufferAlignment);t.gpuBuffer=s.gpuBuffer,t.offset=i,t.storage=s.stagingBuffer.alloc(i,e),s.size=i+e}scheduleSubmit(){this.activeBuffer&&(this.usedBuffers.push(this.activeBuffer),this.activeBuffer=null)}submit(){this.scheduleSubmit()}};var ut=[];ut[Te]=function(c,t,e){let s=c.storageFloat32;s[e]=t};ut[pr]=(c,t,e)=>{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<s;r++)i[e+r*4]=t[r]};ut[Fn]=(c,t,e,s)=>{let i=c.storageFloat32;for(let r=0;r<s;r++)i[e+r*4]=t[r*2],i[e+r*4+1]=t[r*2+1]};ut[Nn]=(c,t,e,s)=>{let i=c.storageFloat32;for(let r=0;r<s;r++)i[e+r*4]=t[r*3],i[e+r*4+1]=t[r*3+1],i[e+r*4+2]=t[r*3+2]};ut[pe]=(c,t,e,s)=>{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<s;r++)i[e+r*4]=t[r]};ut[Un]=ut[Fa];ut[Bn]=function(c,t,e,s){let i=c.storageUint32;for(let r=0;r<s;r++)i[e+r*4]=t[r]};ut[Na]=(c,t,e,s)=>{let i=c.storageInt32;for(let r=0;r<s;r++)i[e+r*4]=t[r*2],i[e+r*4+1]=t[r*2+1]};ut[zn]=ut[Na];ut[kn]=(c,t,e,s)=>{let i=c.storageUint32;for(let r=0;r<s;r++)i[e+r*4]=t[r*2],i[e+r*4+1]=t[r*2+1]};ut[Ba]=(c,t,e,s)=>{let i=c.storageInt32;for(let r=0;r<s;r++)i[e+r*4]=t[r*3],i[e+r*4+1]=t[r*3+1],i[e+r*4+2]=t[r*3+2]};ut[Vn]=ut[Ba];ut[Gn]=(c,t,e,s)=>{let i=c.storageUint32;for(let r=0;r<s;r++)i[e+r*4]=t[r*3],i[e+r*4+1]=t[r*3+1],i[e+r*4+2]=t[r*3+2]};var Qr=class{constructor(t,e,s=!0){n(this,"device");n(this,"persistent");n(this,"allocation");n(this,"storageFloat32");n(this,"storageInt32");n(this,"storageUint32");n(this,"renderVersionDirty",0);if(this.device=t,this.format=e,this.persistent=s,s){this.impl=t.createUniformBufferImpl(this);let i=new ArrayBuffer(e.byteSize);this.assignStorage(new Int32Array(i)),t._vram.ub+=this.format.byteSize}else this.allocation=new Tv}destroy(){if(this.persistent){let t=this.device;this.impl.destroy(t),t._vram.ub-=this.format.byteSize}}get offset(){return this.persistent?0:this.allocation.offset}assignStorage(t){this.storageInt32=t,this.storageUint32=new Uint32Array(t.buffer,t.byteOffset,t.byteLength/4),this.storageFloat32=new Float32Array(t.buffer,t.byteOffset,t.byteLength/4)}loseContext(){this.impl?.loseContext()}setUniform(t,e){let s=t.offset;if(e!=null){let i=ut[t.updateType];i?i(this,e,s,t.count):this.storageFloat32.set(e,s)}}set(t,e){let s=this.format.map.get(t);s&&this.setUniform(s,e)}startUpdate(t){if(!this.persistent){let e=this.allocation,s=e.gpuBuffer;this.device.dynamicBuffers.alloc(e,this.format.byteSize),this.assignStorage(e.storage),t&&(t.bindGroup=e.gpuBuffer.getBindGroup(this),t.offsets[0]=e.offset),s!==e.gpuBuffer&&(this.renderVersionDirty=this.device.renderVersion)}}endUpdate(){this.persistent?this.impl.unlock(this):(this.storageFloat32=null,this.storageInt32=null)}update(t){this.startUpdate(t);let e=this.format.uniforms;for(let s=0;s<e.length;s++){let i=e[s].scopeId.value;this.setUniform(e[s],i)}this.endUpdate()}};var lW={type:Ks,base:0,baseVertex:0,count:4,indexed:!1},Ev=class{constructor(t){let e=`
struct ub_mesh {
color : vec4f,
depth: f32
}
@group(2) @binding(0) var<uniform> ubMesh : ub_mesh;
var<private> pos : array<vec2f, 4> = array<vec2f, 4>(
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
}
@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 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<private> pos : array<vec2f, 4> = array<vec2f, 4>(
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
};
@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<f32>;
@fragment
fn fragmentMain(@location(0) texCoord : vec2f) -> @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<l;u++)h.push(t.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:u}));let f=s.getCommandEncoder();for(let u=1;u<e.mipLevelCount;u++)for(let d=0;d<l;d++){let p=t.createView({dimension:"2d",baseMipLevel:u,mipLevelCount:1,baseArrayLayer:d}),m=f.beginRenderPass({colorAttachments:[{view:p,loadOp:"clear",storeOp:"store"}]}),_=i.createBindGroup({layout:a.getBindGroupLayout(0),entries:[{binding:0,resource:this.minSampler},{binding:1,resource:h[d]}]});m.setPipeline(a),m.setBindGroup(0,_),m.draw(4),m.end(),h[d]=p}s.pipeline=null}};var Cv=class{constructor(t){n(this,"device");n(this,"bindGroupCache",new Map);this.device=t,this.bindGroupFormat=new Ue(this.device,[new Qe(Hn,Xi|Yi)])}getBindGroup(t){let e=t.format.byteSize,s=this.bindGroupCache.get(e);return s||(s=new ji(this.device,this.bindGroupFormat,t),s.update(),this.bindGroupCache.set(e,s)),s}};var Pv=class extends Cv{constructor(e,s,i){super(e);n(this,"buffer",null);n(this,"mappedRange",null);this.buffer=e.wgpu.createBuffer({size:s,usage:i?GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,mappedAtCreation:i}),i&&this.onAvailable(),e._vram.ub+=s}destroy(e){e._vram.ub-=this.buffer.size,this.buffer.destroy(),this.buffer=null}onAvailable(){this.mappedRange=this.buffer.getMappedRange()}alloc(e,s){return new Int32Array(this.mappedRange,e,s/4)}};var wv=class extends yv{constructor(){super(...arguments);n(this,"pendingStagingBuffers",[])}createBuffer(e,s,i){return new Pv(e,s,i)}submit(){super.submit();let e=this.usedBuffers.length;if(e){let s=this.device,i=this.gpuBuffers,r=s.wgpu.createCommandEncoder();for(let o=e-1;o>=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<e;o++){let l=this.usedBuffers[o].stagingBuffer;this.pendingStagingBuffers.push(l)}this.usedBuffers.length=0}}onCommandBuffersSubmitted(){let e=this.pendingStagingBuffers.length;if(e){for(let s=0;s<e;s++){let i=this.pendingStagingBuffers[s];i.buffer.mapAsync(GPUMapMode.WRITE).then(()=>{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<s.length;++i){let r=s[i],a=e[i],o=this._parsePassName(r);this._passTimings.set(o,(this._passTimings.get(o)||0)+a)}if(ed.get(AC)){let i=0;for(let r=0;r<s.length;++r){let a=s[r];i+=e[r]}}}this.pastFrameAllocations.delete(t)}getSlot(t){if(this.frameAllocations.length>=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<t;a++)r.push(Number(i[a*2+1]-i[a*2])*1e-6);return s.unmap(),this.stagingBuffers?.push(s),{renderVersion:e,timings:r}})}};var Rv=class extends Yd{constructor(e){super();n(this,"device");n(this,"frameGPUMarkerSlot");this.device=e,this.maxCount=1024,this.timestampQueriesSet=e.supportsTimestampQuery?new Iv(e,!0,2*this.maxCount):null}destroy(){this.timestampQueriesSet?.destroy(),this.timestampQueriesSet=null}frameStart(){this.processEnableRequest()}frameEnd(){this._enabled&&this.timestampQueriesSet?.resolve(this.slotCount*2)}request(){if(this._enabled){let e=this.device.renderVersion;this.timestampQueriesSet?.request(this.slotCount,e).then(s=>{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<private> pos : array<vec2f, 4> = array<vec2f, 4>(
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,
};
@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;
@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;l<o;l++){let h=e.createView({dimension:"2d",aspect:"depth-only",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:l}),f=s.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:l}),u=t.beginRenderPass({colorAttachments:[{view:f,loadOp:"clear",storeOp:"store"}]}),d=r.createBindGroup({layout:a.getBindGroupLayout(0),entries:[{binding:0,resource:h}]});u.setPipeline(a),u.setBindGroup(0,d),u.draw(4),u.end()}i.pipeline=null}};var cW=12,Dv=class{constructor(t){n(this,"uniformBuffers",[]);n(this,"bindGroup",null);this.compute=t;let{device:e,shader:s}=t,{computeBindGroupFormat:i,computeUniformBufferFormats:r}=s.impl;if(this.bindGroup=new ji(e,i),r){for(let a in r)if(r.hasOwnProperty(a)){let o=new Qr(e,r[a],!0);this.uniformBuffers.push(o),this.bindGroup.setUniformBuffer(a,o)}}this.pipeline=e.computePipeline.get(s,i)}destroy(){this.uniformBuffers.forEach(t=>t.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<e.length;i++){let r=e[i];r.mapAsync(GPUMapMode.WRITE).then(()=>{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].size<t&&(s[i].destroy(),s.splice(i,1))}upload(t,e,s,i){this.useSingleBuffer?this.uploadDirect(t,e,s,i):this.uploadStaging(t,e,s,i)}uploadDirect(t,e,s,i){let r=s*t.BYTES_PER_ELEMENT,a=i*t.BYTES_PER_ELEMENT;e.write(r,t,0,i)}uploadStaging(t,e,s,i){let r=this.uploadStream.device,a=s*t.BYTES_PER_ELEMENT,o=i*t.BYTES_PER_ELEMENT;this.pendingStagingBuffers.length>0,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;o<i.views.length;o++){let l;try{l=this._binding.getViewSubImage(this._layer,i.views[o])}catch(u){this.xrBridge._onBindingError?.(u);return}let h=l?.colorTexture;if(!h)continue;let f=null;if(typeof l.getViewDescriptor=="function")try{let u=l.getViewDescriptor();u&&(f={...u})}catch{}r.push({colorTexture:h,viewDescriptor:f,viewport:l.viewport,viewFormat:f?.format??h.format})}let a=r[0];a&&(s.xrColorTexture=a.colorTexture,s.xrColorTextureViewFormat=a.viewFormat,this._cachedFramebufferSize.set(a.colorTexture.width,a.colorTexture.height))}endFrame(){this.xrBridge.device?._clearXrState()}get presentationLayer(){return this._layer}get graphicsBinding(){return this._binding}getFramebufferSize(t,e){let s=this._layer;if(s){let i=s.textureWidth??s.width,r=s.textureHeight??s.height;if(i>0&&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<this.maxIndirectDrawCount&&(this._indirectDrawBuffer?.destroy(),this._indirectDrawBuffer=null),this._indirectDrawBuffer===null&&(this._indirectDrawBuffer=new Ee(this,this.maxIndirectDrawCount*eL,264),this._indirectDrawBufferCount=this.maxIndirectDrawCount)}getIndirectDrawSlot(e=1){this.allocateIndirectDrawBuffer();let s=this._indirectDrawNextIndex,i=this._indirectDrawNextIndex+e;return this._indirectDrawNextIndex=i,s}get indirectDispatchBuffer(){return this.allocateIndirectDispatchBuffer(),this._indirectDispatchBuffer}allocateIndirectDispatchBuffer(){this._indirectDispatchNextIndex===0&&this._indirectDispatchBufferCount<this.maxIndirectDispatchCount&&(this._indirectDispatchBuffer?.destroy(),this._indirectDispatchBuffer=null),this._indirectDispatchBuffer===null&&(this._indirectDispatchBuffer=new Ee(this,this.maxIndirectDispatchCount*hW,264),this._indirectDispatchBufferCount=this.maxIndirectDispatchCount)}getIndirectDispatchSlot(e=1){this.allocateIndirectDispatchBuffer();let s=this._indirectDispatchNextIndex,i=this._indirectDispatchNextIndex+e;return this._indirectDispatchNextIndex=i,s}setBindGroup(e,s,i){this.passEncoder&&(this.passEncoder.setBindGroup(e,s.impl.bindGroup,i??s.uniformBufferOffsets),this.bindGroupFormats[e]=s.format.impl)}submitVertexBuffer(e,s){let i=e.format,{interleaved:r,elements:a}=i,o=a.length,l=e.impl.buffer;if(r)return this.passEncoder.setVertexBuffer(s,l),1;for(let h=0;h<o;h++)this.passEncoder.setVertexBuffer(s+h,l,a[h].offset);return o}validateVBLocations(e,s){let i=r=>{let{elements:a}=r.format;for(let o=0;o<a.length;o++){let l=a[o].name,h=ze[l];VP.has(h),VP.set(h,l)}};i(e),i(s),VP.clear()}draw(e,s,i=1,r,a=!0,o=!0){if(this.shader.ready&&!this.shader.failed){let l=this.passEncoder,h=this.pipeline,f=this.vertexBuffers[0],u=this.vertexBuffers[1];if(a){if(f){let d=this.submitVertexBuffer(f,0);u&&this.submitVertexBuffer(u,d)}h=this.renderPipeline.get(e,f?.format,u?.format,s?.format,this.shader,this.renderTarget,this.bindGroupFormats,this.blendState,this.depthState,this.cullMode,this.stencilEnabled,this.stencilFront,this.stencilBack,this.frontFace),this.pipeline!==h&&(this.pipeline=h,l.setPipeline(h))}if(s&&l.setIndexBuffer(s.impl.buffer,s.impl.format),r){let p=(r.impl?.storage??this.indirectDrawBuffer).impl.buffer,m=r.count;for(let _=0;_<m;_++){let S=(r.slotIndex+_)*eL;s?l.drawIndexedIndirect(p,S):l.drawIndirect(p,S)}}else s?l.drawIndexed(e.count,i,e.base,e.baseVertex??0,0):l.draw(e.count,i,e.base,0);this._drawCallsPerFrame++}o&&(this.clearVertexBuffer(),this.pipeline=null)}setShader(e,s=!1){e!==this.shader&&(this.shader=e)}setBlendState(e){this.blendState.copy(e)}setDepthState(e){this.depthState.copy(e)}setStencilState(e,s){if(e||s){this.stencilEnabled=!0,this.stencilFront.copy(e??Ls.DEFAULT),this.stencilBack.copy(s??Ls.DEFAULT);let i=this.stencilFront.ref;this.stencilRef!==i&&(this.stencilRef=i,this.passEncoder.setStencilReference(i))}else this.stencilEnabled=!1}setBlendColor(e,s,i,r){let a=this.blendColor;(e!==a.r||s!==a.g||i!==a.b||r!==a.a)&&(a.set(e,s,i,r),this.passEncoder.setBlendConstant(a))}setCullMode(e){this.cullMode=e}setFrontFace(e){this.frontFace=e}setAlphaToCoverage(e){}initializeContextCaches(){super.initializeContextCaches()}setupPassEncoderDefaults(){this.pipeline=null,this.stencilRef=0,this.blendColor.set(0,0,0,0)}_uploadDirtyTextures(){this.texturesToUpload.forEach(e=>{(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;i<e.colorArrayOps.length;i++)e.colorArrayOps[i].genMipmaps&&this.mipmapRenderer.generate(e.renderTarget._colorBuffers[i].impl)}startComputePass(e){this._uploadDirtyTextures(),this.pipeline=null;let s=this.setupTimeStampWrites(void 0,e),i=this.getCommandEncoder();this.passEncoder=i.beginComputePass(s),this.insideRenderPass=!0}endComputePass(){this.passEncoder.end(),this.passEncoder=null,this.insideRenderPass=!1,this.bindGroupFormats.length=0}computeDispatch(e,s="Unnamed"){this.startComputePass(s);for(let i=0;i<e.length;i++){let r=e[i];r.applyParameters(),r.impl.updateBindGroup()}for(let i=0;i<e.length;i++){let r=e[i];r.impl.dispatch(r.countX,r.countY,r.countZ)}this.endComputePass()}getCommandEncoder(){let e=this.commandEncoder;return e||(e=this.wgpu.createCommandEncoder(),this.commandEncoder=e),e}endCommandEncoder(){let{commandEncoder:e}=this;if(e){let s=e.finish();this.addCommandBuffer(s),this.commandEncoder=null}}addCommandBuffer(e,s=!1){s?this.commandBuffers.unshift(e):this.commandBuffers.push(e)}submit(){this.endCommandEncoder(),this.commandBuffers.length>0&&(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<e.length;s++)e[s].destroy();e.length=0}}deferDestroy(e){e&&this._deferredDestroys.push(e)}clear(e){e.flags&&this.clearRenderer.clear(this,this.renderTarget,e,this.defaultClearOptions)}setViewport(e,s,i,r){if(this.passEncoder){if(this.xrColorTexture)return;this.renderTarget.flipY||(s=this.renderTarget.height-s-r),this.vx=e,this.vy=s,this.vw=i,this.vh=r,this.passEncoder.setViewport(e,s,i,r,0,1)}}setScissor(e,s,i,r){if(this.passEncoder){if(this.xrColorTexture)return;this.renderTarget.flipY||(s=this.renderTarget.height-s-r),this.sx=e,this.sy=s,this.sw=i,this.sh=r,this.passEncoder.setScissorRect(e,s,i,r)}}clearStorageBuffer(e,s=0,i=e.byteSize){this.getCommandEncoder().clearBuffer(e.buffer,s,i)}readStorageBuffer(e,s=0,i=e.byteSize-s,r=null,a=!1){let o=this.createBufferImpl(9);o.allocate(this,i);let l=o.buffer;return this.getCommandEncoder().copyBufferToBuffer(e.buffer,s,l,0,i),this.readBuffer(o,i,r,a)}readBuffer(e,s,i=null,r=!1){let a=e.buffer;return new Promise((o,l)=>{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;u<l;u++){let d=s.getActiveAttrib(i,u),p=s.getAttribLocation(i,d.name);tL.has(d.name)||(r.attributes[d.name]===void 0?e.failed=!0:e.attributes.set(p,d.name))}let h=t._samplerTypes,f=s.getProgramParameter(i,s.ACTIVE_UNIFORMS);for(let u=0;u<f;u++){let d=s.getActiveUniform(i,u),p=s.getUniformLocation(i,d.name);if(tL.has(d.name))continue;let m=new Bv(t,d.name,t.pcUniformType[d.type],p);h.has(d.type)?this.samplers.push(m):this.uniforms.push(m)}return e.ready=!0,!0}_isCompiled(t,e,s,i,r){let a=t.gl;if(!a.getShaderParameter(s,a.COMPILE_STATUS)){let o=a.getShaderInfoLog(s),[l,h]=this._processError(i,o),f=`Failed to compile ${r} shader:
${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<o;l++){let h=l+1===s.line?"> ":" ";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;e<t.textureUnits.length;e++){let s=t.textureUnits[e];for(let i=0;i<s.length;i++)s[i]===this._glTexture&&(s[i]=null)}t.gl.deleteTexture(this._glTexture),this._glTexture=null}}loseContext(){this._glTexture=null}propertyChanged(t){this.dirtyParameterFlags|=t}initialize(t,e){let s=t.gl;switch(this._glTexture=s.createTexture(),this._glTarget=e._cubemap?s.TEXTURE_CUBE_MAP:e._volume?s.TEXTURE_3D:e.array?s.TEXTURE_2D_ARRAY:s.TEXTURE_2D,e._format){case pd:this._glFormat=s.ALPHA,this._glInternalFormat=s.ALPHA,this._glPixelType=s.UNSIGNED_BYTE;break;case md:this._glFormat=s.LUMINANCE,this._glInternalFormat=s.LUMINANCE,this._glPixelType=s.UNSIGNED_BYTE;break;case vo:this._glFormat=s.LUMINANCE_ALPHA,this._glInternalFormat=s.LUMINANCE_ALPHA,this._glPixelType=s.UNSIGNED_BYTE;break;case Wr:this._glFormat=s.RED,this._glInternalFormat=s.R8,this._glPixelType=s.UNSIGNED_BYTE;break;case Po:this._glFormat=s.RG,this._glInternalFormat=s.RG8,this._glPixelType=s.UNSIGNED_BYTE;break;case ya:this._glFormat=s.RGB,this._glInternalFormat=s.RGB565,this._glPixelType=s.UNSIGNED_SHORT_5_6_5;break;case xn:this._glFormat=s.RGBA,this._glInternalFormat=s.RGB5_A1,this._glPixelType=s.UNSIGNED_SHORT_5_5_5_1;break;case Ea:this._glFormat=s.RGBA,this._glInternalFormat=s.RGBA4,this._glPixelType=s.UNSIGNED_SHORT_4_4_4_4;break;case Ss:this._glFormat=s.RGB,this._glInternalFormat=s.RGB8,this._glPixelType=s.UNSIGNED_BYTE;break;case ce:this._glFormat=s.RGBA,this._glInternalFormat=s.RGBA8,this._glPixelType=s.UNSIGNED_BYTE;break;case tc:case ic:break;case nf:break;case lf:this._glFormat=s.RGB,this._glInternalFormat=s.RGB9_E5,this._glPixelType=s.UNSIGNED_INT_5_9_9_9_REV;break;case cf:this._glFormat=s.RG,this._glInternalFormat=s.RG8_SNORM,this._glPixelType=s.BYTE;break;case hf:this._glFormat=s.RGBA,this._glInternalFormat=s.RGBA8_SNORM,this._glPixelType=s.BYTE;break;case ff:this._glFormat=s.RGBA,this._glInternalFormat=s.RGB10_A2,this._glPixelType=s.UNSIGNED_INT_2_10_10_10_REV;break;case uf:this._glFormat=s.RGBA_INTEGER,this._glInternalFormat=s.RGB10_A2UI,this._glPixelType=s.UNSIGNED_INT_2_10_10_10_REV;break;case To:this._glFormat=s.RGB,this._glInternalFormat=t.extCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;break;case Ql:this._glFormat=s.RGBA,this._glInternalFormat=t.extCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;break;case Gr:this._glFormat=s.RGBA,this._glInternalFormat=t.extCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;break;case Eo:this._glFormat=s.RGB,this._glInternalFormat=t.extCompressedTextureETC1.COMPRESSED_RGB_ETC1_WEBGL;break;case Vr:this._glFormat=s.RGB,this._glInternalFormat=t.extCompressedTexturePVRTC.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;break;case Hr:this._glFormat=s.RGBA,this._glInternalFormat=t.extCompressedTexturePVRTC.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;break;case Ao:this._glFormat=s.RGB,this._glInternalFormat=t.extCompressedTexturePVRTC.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;break;case Co:this._glFormat=s.RGBA,this._glInternalFormat=t.extCompressedTexturePVRTC.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;break;case Jl:this._glFormat=s.RGB,this._glInternalFormat=t.extCompressedTextureETC.COMPRESSED_RGB8_ETC2;break;case ec:this._glFormat=s.RGBA,this._glInternalFormat=t.extCompressedTextureETC.COMPRESSED_RGBA8_ETC2_EAC;break;case _d:this._glFormat=s.RGBA,this._glInternalFormat=t.extCompressedTextureASTC.COMPRESSED_RGBA_ASTC_4x4_KHR;break;case gd:this._glFormat=s.RGB,this._glInternalFormat=t.extCompressedTextureATC.COMPRESSED_RGB_ATC_WEBGL;break;case Sd:this._glFormat=s.RGBA,this._glInternalFormat=t.extCompressedTextureATC.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL;break;case Td:this._glFormat=s.RGB,this._glInternalFormat=t.extTextureCompressionBPTC.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;break;case yd:this._glFormat=s.RGB,this._glInternalFormat=t.extTextureCompressionBPTC.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;break;case Ed:this._glFormat=s.RGBA,this._glInternalFormat=t.extTextureCompressionBPTC.COMPRESSED_RGBA_BPTC_UNORM_EXT;break;case kh:this._glFormat=s.SRGB,this._glInternalFormat=t.extCompressedTextureS3TC_SRGB.COMPRESSED_SRGB_S3TC_DXT1_EXT;break;case zh:this._glFormat=s.SRGB_ALPHA,this._glInternalFormat=t.extCompressedTextureS3TC_SRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;break;case Gh:this._glFormat=s.SRGB_ALPHA,this._glInternalFormat=t.extCompressedTextureS3TC_SRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;break;case Vh:this._glFormat=s.SRGB,this._glInternalFormat=t.extCompressedTextureETC.COMPRESSED_SRGB8_ETC2;break;case Hh:this._glFormat=s.SRGB_ALPHA,this._glInternalFormat=t.extCompressedTextureETC.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;break;case Wh:this._glFormat=s.SRGB_ALPHA,this._glInternalFormat=t.extCompressedTextureASTC.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case Xh:this._glFormat=s.RGBA,this._glInternalFormat=t.extTextureCompressionBPTC.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case yn:this._glFormat=s.RED,this._glInternalFormat=s.R16F,this._glPixelType=s.HALF_FLOAT;break;case of:this._glFormat=s.RG,this._glInternalFormat=s.RG16F,this._glPixelType=s.HALF_FLOAT;break;case vn:this._glFormat=s.RGB,this._glInternalFormat=s.RGB16F,this._glPixelType=s.HALF_FLOAT;break;case Me:this._glFormat=s.RGBA,this._glInternalFormat=s.RGBA16F,this._glPixelType=s.HALF_FLOAT;break;case Kh:this._glFormat=s.RGB,this._glInternalFormat=s.RGB32F,this._glPixelType=s.FLOAT;break;case ke:this._glFormat=s.RGBA,this._glInternalFormat=s.RGBA32F,this._glPixelType=s.FLOAT;break;case Mt:this._glFormat=s.RED,this._glInternalFormat=s.R32F,this._glPixelType=s.FLOAT;break;case Ys:this._glFormat=s.DEPTH_COMPONENT,this._glInternalFormat=s.DEPTH_COMPONENT32F,this._glPixelType=s.FLOAT;break;case Xr:this._glFormat=s.DEPTH_COMPONENT,this._glInternalFormat=s.DEPTH_COMPONENT16,this._glPixelType=s.UNSIGNED_SHORT;break;case fr:this._glFormat=s.DEPTH_STENCIL,this._glInternalFormat=s.DEPTH24_STENCIL8,this._glPixelType=s.UNSIGNED_INT_24_8;break;case Gi:this._glFormat=s.RGB,this._glInternalFormat=s.R11F_G11F_B10F,this._glPixelType=s.UNSIGNED_INT_10F_11F_11F_REV;break;case yo:this._glFormat=s.RGB,this._glInternalFormat=s.SRGB8,this._glPixelType=s.UNSIGNED_BYTE;break;case st:this._glFormat=s.RGBA,this._glInternalFormat=s.SRGB8_ALPHA8,this._glPixelType=s.UNSIGNED_BYTE;break;case jh:this._glFormat=s.RED_INTEGER,this._glInternalFormat=s.R8I,this._glPixelType=s.BYTE;break;case sc:this._glFormat=s.RED_INTEGER,this._glInternalFormat=s.R8UI,this._glPixelType=s.UNSIGNED_BYTE;break;case qh:this._glFormat=s.RED_INTEGER,this._glInternalFormat=s.R16I,this._glPixelType=s.SHORT;break;case $h:this._glFormat=s.RED_INTEGER,this._glInternalFormat=s.R16UI,this._glPixelType=s.UNSIGNED_SHORT;break;case Zh:this._glFormat=s.RED_INTEGER,this._glInternalFormat=s.R32I,this._glPixelType=s.INT;break;case zt:this._glFormat=s.RED_INTEGER,this._glInternalFormat=s.R32UI,this._glPixelType=s.UNSIGNED_INT;break;case Qh:this._glFormat=s.RG_INTEGER,this._glInternalFormat=s.RG8I,this._glPixelType=s.BYTE;break;case xd:this._glFormat=s.RG_INTEGER,this._glInternalFormat=s.RG8UI,this._glPixelType=s.UNSIGNED_BYTE;break;case Jh:this._glFormat=s.RG_INTEGER,this._glInternalFormat=s.RG16I,this._glPixelType=s.SHORT;break;case ef:this._glFormat=s.RG_INTEGER,this._glInternalFormat=s.RG16UI,this._glPixelType=s.UNSIGNED_SHORT;break;case tf:this._glFormat=s.RG_INTEGER,this._glInternalFormat=s.RG32I,this._glPixelType=s.INT;break;case Tn:this._glFormat=s.RG_INTEGER,this._glInternalFormat=s.RG32UI,this._glPixelType=s.UNSIGNED_INT;break;case sf:this._glFormat=s.RGBA_INTEGER,this._glInternalFormat=s.RGBA8I,this._glPixelType=s.BYTE;break;case vd:this._glFormat=s.RGBA_INTEGER,this._glInternalFormat=s.RGBA8UI,this._glPixelType=s.UNSIGNED_BYTE;break;case rf:this._glFormat=s.RGBA_INTEGER,this._glInternalFormat=s.RGBA16I,this._glPixelType=s.SHORT;break;case Rs:this._glFormat=s.RGBA_INTEGER,this._glInternalFormat=s.RGBA16UI,this._glPixelType=s.UNSIGNED_SHORT;break;case af:this._glFormat=s.RGBA_INTEGER,this._glInternalFormat=s.RGBA32I,this._glPixelType=s.INT;break;case At:this._glFormat=s.RGBA_INTEGER,this._glInternalFormat=s.RGBA32UI,this._glPixelType=s.UNSIGNED_INT;break}this._glCreated=!1}upload(t,e){let s=t.gl;if(!e._needsUpload&&(e._needsMipmapsUpload&&e._mipmapsUploaded||!e.pot))return;let i=0,r,a,o=e.numLevels;for(e.array&&!this._glCreated&&s.texStorage3D(s.TEXTURE_2D_ARRAY,o,this._glInternalFormat,e._width,e._height,e._arrayLength);e._levels[i]||i===0;){if(!e._needsUpload&&i===0){i++;continue}else if(i&&(!e._needsMipmapsUpload||!e._mipmaps))break;if(r=e._levels[i],a=1/Math.pow(2,i),i===1&&!e._compressed&&!e._integerFormat&&e._levels.length<o&&(s.generateMipmap(this._glTarget),e._mipmapsUploaded=!0),e._cubemap){let l;if(t._isBrowserInterface(r[0]))for(l=0;l<6;l++){if(!e._levelsUpdated[0][l])continue;let h=r[l];t._isImageBrowserInterface(h)&&(h.width>t.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;l<e._arrayLength;l++)s.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,i,0,0,l,Math.max(Math.floor(e._width*a),1),Math.max(Math.floor(e._height*a),1),1,this._glInternalFormat,r[l]);else{t.setUnpackAlignment(1);for(let l=0;l<e._arrayLength;l++)s.texSubImage3D(s.TEXTURE_2D_ARRAY,i,0,0,l,Math.max(Math.floor(e._width*a),1),Math.max(Math.floor(e._height*a),1),1,this._glFormat,this._glPixelType,r[l])}}else{if(t._isBrowserInterface(r))if(t._isHTMLElementInterface(r)&&t.supportsHtmlTextures){t.setUnpackFlipY(e._flipY),t.setUnpackPremultiplyAlpha(e._premultiplyAlpha);let l=r.getBoundingClientRect(),h=Math.floor(l.width)||e._width,f=Math.floor(l.height)||e._height;s.texElementImage2D(s.TEXTURE_2D,this._glInternalFormat,r),i===0&&(e._width=h,e._height=f)}else{t._isImageBrowserInterface(r)&&(r.width>t.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;l<r;++l){let h=e.getColorBuffer(l);h&&(h.impl._glTexture||(h._width=Math.min(h.width,t.maxRenderBufferSize),h._height=Math.min(h.height,t.maxRenderBufferSize),t.setTexture(h,0)),s.framebufferTexture2D(s.FRAMEBUFFER,a+l,h._cubemap?s.TEXTURE_CUBE_MAP_POSITIVE_X+e._face:s.TEXTURE_2D,h.impl._glTexture,e.mipLevel),i.push(a+l))}s.drawBuffers(i);let o=e._depthBuffer;if(o||e._depth){let l=e._stencil?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT;if(o)o.impl._glTexture||(o._width=Math.min(o.width,t.maxRenderBufferSize),o._height=Math.min(o.height,t.maxRenderBufferSize),t.setTexture(o,0)),s.framebufferTexture2D(s.FRAMEBUFFER,l,o._cubemap?s.TEXTURE_CUBE_MAP_POSITIVE_X+e._face:s.TEXTURE_2D,e._depthBuffer.impl._glTexture,e.mipLevel);else if(!(e._samples>1)){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;a<r;++a){let o=e.getColorBuffer(a);if(o){let l=s.createRenderbuffer();this._glMsaaColorBuffers.push(l),s.bindRenderbuffer(s.RENDERBUFFER,l),s.renderbufferStorageMultisample(s.RENDERBUFFER,e._samples,o.impl._glInternalFormat,e.width,e.height),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+a,s.RENDERBUFFER,l)}}if(e._depth){let a=e._stencil?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT32F,o=e._stencil?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT,l,h=e._depthBuffer;h&&(l=`${h.id}:${e.width}:${e.height}:${e._samples}:${a}:${o}`,this._glMsaaDepthBuffer=Af(t).get(l)),this._glMsaaDepthBuffer||(this._glMsaaDepthBuffer=s.createRenderbuffer(),s.bindRenderbuffer(s.RENDERBUFFER,this._glMsaaDepthBuffer),s.renderbufferStorageMultisample(s.RENDERBUFFER,e._samples,a,e.width,e.height),this._glMsaaDepthBuffer.destroy=function(){s.deleteRenderbuffer(this)},h&&Af(t).set(l,this._glMsaaDepthBuffer)),this.msaaDepthBufferKey=l,s.framebufferRenderbuffer(s.FRAMEBUFFER,o,s.RENDERBUFFER,this._glMsaaDepthBuffer)}r>1&&(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;r<s;++r){let a=e.getColorBuffer(r),o=i.createFramebuffer();t.setFramebuffer(o);let l=this._glMsaaColorBuffers[r];i.bindRenderbuffer(i.RENDERBUFFER,l),i.renderbufferStorageMultisample(i.RENDERBUFFER,e._samples,a.impl._glInternalFormat,e.width,e.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,l),i.drawBuffers([i.COLOR_ATTACHMENT0]);let h=i.createFramebuffer();t.setFramebuffer(h),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,a._cubemap?i.TEXTURE_CUBE_MAP_POSITIVE_X+e._face:i.TEXTURE_2D,a.impl._glTexture,0),this.colorMrtFramebuffers[r]=new WP(o,h)}}_checkFbo(t,e,s=""){let i=e._colorBuffers?.map(u=>u?.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;a<this.colorMrtFramebuffers.length;a++){let o=this.colorMrtFramebuffers[a];this.internalResolve(t,o.msaaFB,o.resolveFB,e,r.COLOR_BUFFER_BIT)}i&&this.internalResolve(t,this._glFrameBuffer,this._glResolveFrameBuffer,e,r.DEPTH_BUFFER_BIT)}else{let a=!!t.defaultFramebuffer&&this._glResolveFrameBuffer===t.defaultFramebuffer;s&&a&&ue.visionos&&(t.resolveMsaaColorToXrFramebufferViaQuads(this._glFrameBuffer,this._glResolveFrameBuffer,e.width,e.height),s=!1),(s||i)&&this.internalResolve(t,this._glFrameBuffer,this._glResolveFrameBuffer,e,(s?r.COLOR_BUFFER_BIT:0)|(i?r.DEPTH_BUFFER_BIT:0))}r.bindFramebuffer(r.FRAMEBUFFER,this._glFrameBuffer)}};var Vv=class{constructor(t){n(this,"availablePBOs",[]);n(this,"pendingPBOs",[]);this.uploadStream=t,this.useSingleBuffer=t.useSingleBuffer}destroy(){let t=this.uploadStream.device.gl;this.availablePBOs.forEach(e=>t.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&&(e.deleteBuffer(i[r].pbo),i.splice(r,1))}upload(t,e,s,i){this.useSingleBuffer?this.uploadDirect(t,e,s,i):this.uploadPBO(t,e,s,i)}uploadDirect(t,e,s,i){let r=this.uploadStream.device,a=r.gl,o=e.impl;r.setTexture(e,0),r.activeTexture(0),r.bindTexture(e),r.setUnpackFlipY(!1),r.setUnpackPremultiplyAlpha(!1),r.setUnpackAlignment(t.BYTES_PER_ELEMENT);let l=t;if(o._glPixelType===a.UNSIGNED_BYTE&&t.BYTES_PER_ELEMENT!==1){let h=i*t.BYTES_PER_ELEMENT;l=new Uint8Array(t.buffer,t.byteOffset,h)}a.texImage2D(a.TEXTURE_2D,0,o._glInternalFormat,e.width,e.height,0,o._glFormat,o._glPixelType,l),o._glCreated=!0}uploadPBO(t,e,s,i){let r=this.uploadStream.device,a=r.gl,o=e.width,l=i*t.BYTES_PER_ELEMENT;this.update(l);let h=s/o,f=i/o,u=this.availablePBOs.pop()??{pbo:a.createBuffer(),size:l};a.bindBuffer(a.PIXEL_UNPACK_BUFFER,u.pbo),a.bufferData(a.PIXEL_UNPACK_BUFFER,l,a.STREAM_DRAW),a.bufferSubData(a.PIXEL_UNPACK_BUFFER,0,new Uint8Array(t.buffer,t.byteOffset,l)),a.bindBuffer(a.PIXEL_UNPACK_BUFFER,null),r.setTexture(e,0),r.activeTexture(0),r.bindTexture(e),a.bindBuffer(a.PIXEL_UNPACK_BUFFER,u.pbo),r.setUnpackFlipY(!1),r.setUnpackPremultiplyAlpha(!1),r.setUnpackAlignment(t.BYTES_PER_ELEMENT),a.pixelStorei(a.UNPACK_ROW_LENGTH,0),a.pixelStorei(a.UNPACK_SKIP_ROWS,0),a.pixelStorei(a.UNPACK_SKIP_PIXELS,0);let d=e.impl;a.texSubImage2D(a.TEXTURE_2D,0,0,h,o,f,d._glFormat,d._glPixelType,0),a.bindBuffer(a.PIXEL_UNPACK_BUFFER,null);let p=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);this.pendingPBOs.push({pbo:u.pbo,size:l,sync:p}),a.flush()}};var Hv=class{constructor(t){n(this,"_presentationLayer",null);n(this,"_graphicsBinding",null);n(this,"_cameraFbSource",null);n(this,"_cameraFbDest",null);this.xrBridge=t}destroy(t){this._graphicsBinding=null,this._presentationLayer=null,this._deleteCameraFramebuffers(t)}_deleteCameraFramebuffers(t){if(this._cameraFbSource){let e=t.gl;e.deleteFramebuffer(this._cameraFbSource),this._cameraFbSource=null,e.deleteFramebuffer(this._cameraFbDest),this._cameraFbDest=null}}beginFrame(t,e){let s=t.session.renderState.baseLayer;this.xrBridge.device.defaultFramebuffer=s?s.framebuffer:null}endFrame(){this.xrBridge.device.defaultFramebuffer=null}get presentationLayer(){return this._presentationLayer}get graphicsBinding(){return this._graphicsBinding}getFramebufferSize(t,e){let s=t.session.renderState.baseLayer;if(!s){e.set(0,0);return}e.set(s.framebufferWidth,s.framebufferHeight)}getViewport(t,e){let s=t.session.renderState.baseLayer;return s?s.getViewport(e):{x:0,y:0,width:0,height:0}}attachPresentation(t,e){let s=this.xrBridge.device;if(this._presentationLayer=new XRWebGLLayer(t,s.gl,{alpha:!0,depth:!0,stencil:!0,framebufferScaleFactor:e.framebufferScaleFactor,antialias:!1}),window.XRWebGLBinding)try{this._graphicsBinding=new XRWebGLBinding(t,s.gl)}catch(i){this.xrBridge._onBindingError?.(i)}t.updateRenderState({baseLayer:this._presentationLayer,depthNear:e.depthNear,depthFar:e.depthFar})}releasePresentation(){this._graphicsBinding=null}syncCameraColorTexture(t,e){if(!this._graphicsBinding)return;let s=this.xrBridge.device,i=s.gl,r=this._graphicsBinding.getCameraImage(t);if(!r)return;this._cameraFbSource||(this._cameraFbSource=i.createFramebuffer(),this._cameraFbDest=i.createFramebuffer());let a=t.width,o=t.height;s.setFramebuffer(this._cameraFbSource),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,r,0),s.setFramebuffer(this._cameraFbDest),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,e.impl._glTexture,0),i.bindFramebuffer(i.READ_FRAMEBUFFER,this._cameraFbSource),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,this._cameraFbDest),i.blitFramebuffer(0,o,a,0,0,0,a,o,i.COLOR_BUFFER_BIT,i.NEAREST),s.setFramebuffer(s.defaultFramebuffer)}syncCameraDepthTexture(t,e,s){if(!t?.texture)return;let i=this.xrBridge.device.gl;switch(e.impl._glTexture=t.texture,t.textureType==="texture-array"?e.impl._glTarget=i.TEXTURE_2D_ARRAY:e.impl._glTarget=i.TEXTURE_2D,s){case Mt:e.impl._glInternalFormat=i.R32F,e.impl._glPixelType=i.FLOAT,e.impl._glFormat=i.RED;break;case Ys:e.impl._glInternalFormat=i.DEPTH_COMPONENT16,e.impl._glPixelType=i.UNSIGNED_SHORT,e.impl._glFormat=i.DEPTH_COMPONENT;break}e.impl._glCreated=!0}onGraphicsDeviceLost(){let t=this.xrBridge._session;if(!t)return;let e=t.renderState;this._graphicsBinding=null,this._presentationLayer=null,this._cameraFbSource=null,this._cameraFbDest=null,t.updateRenderState({baseLayer:this._presentationLayer,depthNear:e.depthNear,depthFar:e.depthFar})}onGraphicsDeviceRestored(){let t=this.xrBridge;if(!t._session)return;let e=t.device,s=t.eventHandler;setTimeout(()=>{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<o.length;d++){let p=o[d],m=s.getQueryParameter(p,s.QUERY_RESULT);u[d]=m*1e-6,this.freeQueries.push(p)}this.report(a.renderVersion,u)}f&&(this.previousFrameQueries.forEach(u=>{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;e<arguments.length;e++)if(this.supportedExtensions.indexOf(arguments[e])!==-1)return this.gl.getExtension(arguments[e]);return null}get extDisjointTimerQuery(){return this._extDisjointTimerQuery||(this._extDisjointTimerQuery=this.getExtension("EXT_disjoint_timer_query_webgl2","EXT_disjoint_timer_query")),this._extDisjointTimerQuery}initializeExtensions(){let e=this.gl;this.supportedExtensions=e.getSupportedExtensions()??[],this._extDisjointTimerQuery=null,this.textureRG11B10Renderable=!0,this.extColorBufferFloat=this.getExtension("EXT_color_buffer_float"),this.textureFloatRenderable=!!this.extColorBufferFloat,this.extColorBufferHalfFloat=this.getExtension("EXT_color_buffer_half_float"),this.textureHalfFloatRenderable=!!this.extColorBufferHalfFloat||!!this.extColorBufferFloat,this.extDebugRendererInfo=this.getExtension("WEBGL_debug_renderer_info"),this.extTextureFloatLinear=this.getExtension("OES_texture_float_linear"),this.textureFloatFilterable=!!this.extTextureFloatLinear,this.extFloatBlend=this.getExtension("EXT_float_blend"),this.extTextureFilterAnisotropic=this.getExtension("EXT_texture_filter_anisotropic","WEBKIT_EXT_texture_filter_anisotropic"),this.extParallelShaderCompile=this.getExtension("KHR_parallel_shader_compile"),this.extMultiDraw=this.getExtension("WEBGL_multi_draw"),this.supportsMultiDraw=!!this.extMultiDraw,this.extCompressedTextureETC1=this.getExtension("WEBGL_compressed_texture_etc1"),this.extCompressedTextureETC=this.getExtension("WEBGL_compressed_texture_etc"),this.extCompressedTexturePVRTC=this.getExtension("WEBGL_compressed_texture_pvrtc","WEBKIT_WEBGL_compressed_texture_pvrtc"),this.extCompressedTextureS3TC=this.getExtension("WEBGL_compressed_texture_s3tc","WEBKIT_WEBGL_compressed_texture_s3tc"),this.extCompressedTextureS3TC_SRGB=this.getExtension("WEBGL_compressed_texture_s3tc_srgb"),this.extCompressedTextureATC=this.getExtension("WEBGL_compressed_texture_atc"),this.extCompressedTextureASTC=this.getExtension("WEBGL_compressed_texture_astc"),this.extTextureCompressionBPTC=this.getExtension("EXT_texture_compression_bptc"),this.supportsHtmlTextures=typeof e.texElementImage2D=="function"}initializeCapabilities(){let e=this.gl,s,i=typeof navigator<"u"?navigator.userAgent:"";this.maxPrecision=this.precision=this.getPrecision();let r=e.getContextAttributes();this.supportsMsaa=r?.antialias??!1,this.supportsStencil=r?.stencil??!1,this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),this.maxCubeMapSize=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),this.maxRenderBufferSize=e.getParameter(e.MAX_RENDERBUFFER_SIZE),this.maxTextures=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),this.maxCombinedTextures=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),this.maxVertexTextures=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),this.vertexUniformsCount=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),this.fragmentUniformsCount=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),this.maxColorAttachments=e.getParameter(e.MAX_COLOR_ATTACHMENTS),this.maxVolumeSize=e.getParameter(e.MAX_3D_TEXTURE_SIZE),s=this.extDebugRendererInfo,this.unmaskedRenderer=s?e.getParameter(s.UNMASKED_RENDERER_WEBGL):"",this.unmaskedVendor=s?e.getParameter(s.UNMASKED_VENDOR_WEBGL):"";let a=/\bMali-G52+/,o=/SM-[a-zA-Z0-9]+/;this.supportsGpuParticles=!(this.unmaskedVendor==="ARM"&&i.match(o))&&!this.unmaskedRenderer.match(a),s=this.extTextureFilterAnisotropic,this.maxAnisotropy=s?e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT):1;let l=!this.forceDisableMultisampling;this.maxSamples=l?e.getParameter(e.MAX_SAMPLES):1,this.maxSamples=Math.min(this.maxSamples,4),this.samples=l&&this.backBufferAntialias?this.maxSamples:1,this.supportsAreaLights=!ue.android,this.maxTextures<=8&&(this.supportsAreaLights=!1),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(!0,!0,!0,!0),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(!0),this.stencil=!1,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=wn,this.stencilZfailFront=this.stencilZfailBack=wn,this.stencilZpassFront=this.stencilZpassBack=wn,this.stencilWriteMaskFront=255,this.stencilWriteMaskBack=255,e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.stencilMask(255),this.alphaToCoverage=!1,this.raster=!0,e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.disable(e.RASTERIZER_DISCARD),this.depthBiasEnabled=!1,e.disable(e.POLYGON_OFFSET_FILL),this.clearDepth=1,e.clearDepth(1),this.clearColor=new F(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=!1,e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),this.unpackPremultiplyAlpha=!1,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),this.unpackAlignment=1,e.pixelStorei(e.UNPACK_ALIGNMENT,1)}initTextureUnits(e=16){this.textureUnits=[];for(let s=0;s<e;s++)this.textureUnits.push([null,null,null])}initializeContextCaches(){super.initializeContextCaches(),this._vaoMap=new Map,this.boundVao=null,this.activeFramebuffer=null,this.feedback=null,this.transformFeedbackBuffer=null,this.textureUnit=0,this.initTextureUnits(this.maxCombinedTextures)}loseContext(){super.loseContext();for(let e of this.shaders)e.loseContext();this.fire("devicelost")}restoreContext(){this.initializeExtensions(),this.initializeCapabilities(),super.restoreContext();for(let e of this.shaders)e.restoreContext();this.fire("devicerestored")}setViewport(e,s,i,r){(this.vx!==e||this.vy!==s||this.vw!==i||this.vh!==r)&&(this.gl.viewport(e,s,i,r),this.vx=e,this.vy=s,this.vw=i,this.vh=r)}setScissor(e,s,i,r){(this.sx!==e||this.sy!==s||this.sw!==i||this.sh!==r)&&(this.gl.scissor(e,s,i,r),this.sx=e,this.sy=s,this.sw=i,this.sh=r)}setFramebuffer(e){if(this.activeFramebuffer!==e){let s=this.gl;s.bindFramebuffer(s.FRAMEBUFFER,e),this.activeFramebuffer=e}}resolveMsaaColorToXrFramebufferViaQuads(e,s,i,r){this._xrMsaaCopy??(this._xrMsaaCopy=new Wv(this)),this._xrMsaaCopy.copy(e,s,i,r)}copyRenderTarget(e,s,i,r){let a=this.gl;if(e===this.backBuffer&&(e=null),i){if(s){if(e&&(!e._colorBuffer||!s._colorBuffer||e._colorBuffer._format!==s._colorBuffer._format))return!1}else if(!e._colorBuffer)return!1}if(r&&e&&!e._depth&&(!e._depthBuffer||!s._depthBuffer||e._depthBuffer._format!==s._depthBuffer._format))return!1;let o=this.renderTarget;this.renderTarget=s,this.updateBegin();let l=e?e.impl._glFrameBuffer:this.backBuffer?.impl._glFrameBuffer,h=s?s.impl._glFrameBuffer:this.backBuffer?.impl._glFrameBuffer;a.bindFramebuffer(a.READ_FRAMEBUFFER,l),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,h);let f=e?e.width:s?s.width:this.width,u=e?e.height:s?s.height:this.height;return a.blitFramebuffer(0,0,f,u,0,0,f,u,(i?a.COLOR_BUFFER_BIT:0)|(r?a.DEPTH_BUFFER_BIT:0),a.NEAREST),this.renderTarget=o,a.bindFramebuffer(a.FRAMEBUFFER,o?o.impl._glFrameBuffer:null),!0}frameStart(){super.frameStart(),this.updateBackbuffer(),this.gpuProfiler.frameStart()}frameEnd(){super.frameEnd(),this.gpuProfiler.frameEnd(),this.gpuProfiler.request()}startRenderPass(e){let s=e.renderTarget??this.backBuffer;this.renderTarget=s,this.updateBegin();let{width:i,height:r}=s;this.setViewport(0,0,i,r),this.setScissor(0,0,i,r);let a=e.colorOps,o=e.depthStencilOps;if(a?.clear||o.clearDepth||o.clearStencil){let l=0,h={};a?.clear&&(l|=1,h.color=[a.clearValue.r,a.clearValue.g,a.clearValue.b,a.clearValue.a]),o.clearDepth&&(l|=2,h.depth=o.clearDepthValue),o.clearStencil&&(l|=4,h.stencil=o.clearStencilValue),h.flags=l,this.clear(h)}this.insideRenderPass=!0}endRenderPass(e){this.unbindVertexArray();let s=this.renderTarget,i=e.colorArrayOps.length;if(s){qd.length=0;let r=this.gl;for(let a=0;a<i;a++){let o=e.colorArrayOps[a];o.store||o.resolve||qd.push(r.COLOR_ATTACHMENT0+a)}s!==this.backBuffer&&(e.depthStencilOps.storeDepth||qd.push(r.DEPTH_ATTACHMENT),e.depthStencilOps.storeStencil||qd.push(r.STENCIL_ATTACHMENT)),qd.length>0&&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;a<i;a++)if(e.colorArrayOps[a].genMipmaps){let l=s._colorBuffers[a];l&&l.impl._glTexture&&l.mipmaps&&(this.activeTexture(this.maxCombinedTextures-1),this.bindTexture(l),this.gl.generateMipmap(l.impl._glTarget))}}this.insideRenderPass=!1}set defaultFramebuffer(e){this._defaultFramebuffer!==e&&(this._defaultFramebuffer=e,this._defaultFramebufferChanged=!0)}get defaultFramebuffer(){return this._defaultFramebuffer}updateBegin(){if(this.boundVao=null,this._tempEnableSafariTextureUnitWorkaround)for(let i=0;i<this.textureUnits.length;++i)for(let r=0;r<3;++r)this.textureUnits[i][r]=null;let e=this.renderTarget??this.backBuffer,s=e.impl;s.initialized||this.initRenderTarget(e),this.setFramebuffer(s._glFrameBuffer)}updateEnd(){this.unbindVertexArray();let e=this.renderTarget;if(e&&e!==this.backBuffer){e._samples>1&&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;a<e.length;a++){let o=e[a];s+=o.id+o.format.renderingHash}i=this._vaoMap.get(s)}if(!i){let a=this.gl;i=a.createVertexArray(),a.bindVertexArray(i),a.bindBuffer(a.ELEMENT_ARRAY_BUFFER,null);let o=!1;for(let l=0;l<e.length;l++){let h=e[l];a.bindBuffer(a.ARRAY_BUFFER,h.impl.bufferId);let f=h.format.elements;for(let u=0;u<f.length;u++){let d=f[u],p=ze[d.name];p===0&&(o=!0),d.asInt?a.vertexAttribIPointer(p,d.numComponents,this.glType[d.dataType],d.stride,d.offset):a.vertexAttribPointer(p,d.numComponents,this.glType[d.dataType],d.normalize,d.stride,d.offset),a.enableVertexAttribArray(p),h.format.instancing&&a.vertexAttribDivisor(p,1)}}a.bindVertexArray(null),a.bindBuffer(a.ARRAY_BUFFER,null),r&&this._vaoMap.set(s,i)}return i}unbindVertexArray(){this.boundVao&&(this.boundVao=null,this.gl.bindVertexArray(null))}setBuffers(e){let s=this.gl,i;if(this.vertexBuffers.length===1){let a=this.vertexBuffers[0];a.impl.vao||(a.impl.vao=this.createVertexArray(this.vertexBuffers)),i=a.impl.vao}else i=this.createVertexArray(this.vertexBuffers);this.boundVao!==i&&(this.boundVao=i,s.bindVertexArray(i));let r=e?e.impl.bufferId:null;s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,r)}_multiDrawLoopFallback(e,s,i,r,a){let o=this.gl;if(s.indexed){let l=i.impl.glFormat,{glCounts:h,glOffsetsBytes:f,glInstanceCounts:u,count:d}=a.impl;if(r>0)for(let p=0;p<d;p++)o.drawElementsInstanced(e,h[p],l,f[p],u[p]);else for(let p=0;p<d;p++)o.drawElements(e,h[p],l,f[p])}else{let{glCounts:l,glOffsetsBytes:h,glInstanceCounts:f,count:u}=a.impl;if(r>0)for(let d=0;d<u;d++)o.drawArraysInstanced(e,h[d],l[d],f[d]);else for(let d=0;d<u;d++)o.drawArrays(e,h[d],l[d])}}draw(e,s,i,r,a=!0,o=!0){let l=this.shader;if(l&&(this.activateShader(),this.shaderValid)){let h=this.gl;a&&this.setBuffers(s);let f=0,u=l.impl.samplers;for(let _=0,S=u.length;_<S;_++){let g=u[_],T=g.scopeId.value;if(!T){let C=g.scopeId.name;C==="uSceneDepthMap"&&(T=bo(this,"white")),C==="uSceneColorMap"&&(T=bo(this,"pink")),T||(T=bo(this,"pink"))}if(T instanceof Z){let C=T;this.setTexture(C,f),g.slot!==f&&(h.uniform1i(g.locationId,f),g.slot=f),f++}else{g.array.length=0;let C=T.length;for(let v=0;v<C;v++){let E=T[v];this.setTexture(E,f),g.array[v]=f,f++}h.uniform1iv(g.locationId,g.array)}}let d=l.impl.uniforms;for(let _=0,S=d.length;_<S;_++){let g=d[_],T=g.scopeId,C=g.version,v=T.versionObject.version;if(C.globalId!==v.globalId||C.revision!==v.revision){C.globalId=v.globalId,C.revision=v.revision;let E=T.value;E!=null&&this.commitFunction[g.dataType](g,E)}}this.transformFeedbackBuffer&&(h.bindBufferBase(h.TRANSFORM_FEEDBACK_BUFFER,0,this.transformFeedbackBuffer.impl.bufferId),h.beginTransformFeedback(h.POINTS));let p=this.glPrimitive[e.type],m=e.count;if(r)if(this.extMultiDraw){let _=r.impl;if(e.indexed){let S=s.impl.glFormat;i>0?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<v;E++)for(let y=0;y<u;y++)m[E*u+y]=C[E*4+y];S(m)}else S(C)}).catch(g)})}async writeTextureAsync(e,s,i,r,a,o){let l=this.gl,h=e.impl,f=h?._glFormat??l.RGBA,u=h?._glPixelType??l.UNSIGNED_BYTE,d=l.createBuffer();l.bindBuffer(l.PIXEL_UNPACK_BUFFER,d),l.bufferData(l.PIXEL_UNPACK_BUFFER,o,l.STREAM_DRAW),l.bindTexture(l.TEXTURE_2D,h._glTexture),l.texSubImage2D(l.TEXTURE_2D,0,s,i,r,a,f,u,0),l.bindBuffer(l.PIXEL_UNPACK_BUFFER,null),e._needsUpload=!1,e._mipmapsUploaded=!1,await this.clientWaitAsync(0,16)}setAlphaToCoverage(e){this.alphaToCoverage!==e&&(this.alphaToCoverage=e,e?this.gl.enable(this.gl.SAMPLE_ALPHA_TO_COVERAGE):this.gl.disable(this.gl.SAMPLE_ALPHA_TO_COVERAGE))}setTransformFeedbackBuffer(e){if(this.transformFeedbackBuffer!==e){this.transformFeedbackBuffer=e;let s=this.gl;e?(this.feedback||(this.feedback=s.createTransformFeedback()),s.bindTransformFeedback(s.TRANSFORM_FEEDBACK,this.feedback)):s.bindTransformFeedback(s.TRANSFORM_FEEDBACK,null)}}setRaster(e){this.raster!==e&&(this.raster=e,e?this.gl.disable(this.gl.RASTERIZER_DISCARD):this.gl.enable(this.gl.RASTERIZER_DISCARD))}setStencilTest(e){if(this.stencil!==e){let s=this.gl;e?s.enable(s.STENCIL_TEST):s.disable(s.STENCIL_TEST),this.stencil=e}}setStencilFunc(e,s,i){(this.stencilFuncFront!==e||this.stencilRefFront!==s||this.stencilMaskFront!==i||this.stencilFuncBack!==e||this.stencilRefBack!==s||this.stencilMaskBack!==i)&&(this.gl.stencilFunc(this.glComparison[e],s,i),this.stencilFuncFront=this.stencilFuncBack=e,this.stencilRefFront=this.stencilRefBack=s,this.stencilMaskFront=this.stencilMaskBack=i)}setStencilFuncFront(e,s,i){if(this.stencilFuncFront!==e||this.stencilRefFront!==s||this.stencilMaskFront!==i){let r=this.gl;r.stencilFuncSeparate(r.FRONT,this.glComparison[e],s,i),this.stencilFuncFront=e,this.stencilRefFront=s,this.stencilMaskFront=i}}setStencilFuncBack(e,s,i){if(this.stencilFuncBack!==e||this.stencilRefBack!==s||this.stencilMaskBack!==i){let r=this.gl;r.stencilFuncSeparate(r.BACK,this.glComparison[e],s,i),this.stencilFuncBack=e,this.stencilRefBack=s,this.stencilMaskBack=i}}setStencilOperation(e,s,i,r){(this.stencilFailFront!==e||this.stencilZfailFront!==s||this.stencilZpassFront!==i||this.stencilFailBack!==e||this.stencilZfailBack!==s||this.stencilZpassBack!==i)&&(this.gl.stencilOp(this.glStencilOp[e],this.glStencilOp[s],this.glStencilOp[i]),this.stencilFailFront=this.stencilFailBack=e,this.stencilZfailFront=this.stencilZfailBack=s,this.stencilZpassFront=this.stencilZpassBack=i),(this.stencilWriteMaskFront!==r||this.stencilWriteMaskBack!==r)&&(this.gl.stencilMask(r),this.stencilWriteMaskFront=r,this.stencilWriteMaskBack=r)}setStencilOperationFront(e,s,i,r){(this.stencilFailFront!==e||this.stencilZfailFront!==s||this.stencilZpassFront!==i)&&(this.gl.stencilOpSeparate(this.gl.FRONT,this.glStencilOp[e],this.glStencilOp[s],this.glStencilOp[i]),this.stencilFailFront=e,this.stencilZfailFront=s,this.stencilZpassFront=i),this.stencilWriteMaskFront!==r&&(this.gl.stencilMaskSeparate(this.gl.FRONT,r),this.stencilWriteMaskFront=r)}setStencilOperationBack(e,s,i,r){(this.stencilFailBack!==e||this.stencilZfailBack!==s||this.stencilZpassBack!==i)&&(this.gl.stencilOpSeparate(this.gl.BACK,this.glStencilOp[e],this.glStencilOp[s],this.glStencilOp[i]),this.stencilFailBack=e,this.stencilZfailBack=s,this.stencilZpassBack=i),this.stencilWriteMaskBack!==r&&(this.gl.stencilMaskSeparate(this.gl.BACK,r),this.stencilWriteMaskBack=r)}setBlendState(e){let s=this.blendState;if(!s.equals(e)){let i=this.gl,{blend:r,colorOp:a,alphaOp:o,colorSrcFactor:l,colorDstFactor:h,alphaSrcFactor:f,alphaDstFactor:u}=e;if(s.blend!==r&&(r?i.enable(i.BLEND):i.disable(i.BLEND)),s.colorOp!==a||s.alphaOp!==o){let d=this.glBlendEquation;i.blendEquationSeparate(d[a],d[o])}(s.colorSrcFactor!==l||s.colorDstFactor!==h||s.alphaSrcFactor!==f||s.alphaDstFactor!==u)&&i.blendFuncSeparate(this.glBlendFunctionColor[l],this.glBlendFunctionColor[h],this.glBlendFunctionAlpha[f],this.glBlendFunctionAlpha[u]),s.allWrite!==e.allWrite&&this.gl.colorMask(e.redWrite,e.greenWrite,e.blueWrite,e.alphaWrite),s.copy(e)}}setBlendColor(e,s,i,r){let a=this.blendColor;(e!==a.r||s!==a.g||i!==a.b||r!==a.a)&&(this.gl.blendColor(e,s,i,r),a.set(e,s,i,r))}setStencilState(e,s){e||s?(this.setStencilTest(!0),e===s?(this.setStencilFunc(e.func,e.ref,e.readMask),this.setStencilOperation(e.fail,e.zfail,e.zpass,e.writeMask)):(e??(e=Ls.DEFAULT),this.setStencilFuncFront(e.func,e.ref,e.readMask),this.setStencilOperationFront(e.fail,e.zfail,e.zpass,e.writeMask),s??(s=Ls.DEFAULT),this.setStencilFuncBack(s.func,s.ref,s.readMask),this.setStencilOperationBack(s.fail,s.zfail,s.zpass,s.writeMask))):this.setStencilTest(!1)}setDepthState(e){let s=this.depthState;if(!s.equals(e)){let i=this.gl,r=e.write;s.write!==r&&i.depthMask(r);let{func:a,test:o}=e;!o&&r&&(o=!0,a=7),s.func!==a&&i.depthFunc(this.glComparison[a]),s.test!==o&&(o?i.enable(i.DEPTH_TEST):i.disable(i.DEPTH_TEST));let{depthBias:l,depthBiasSlope:h}=e;l||h?(this.depthBiasEnabled||(this.depthBiasEnabled=!0,this.gl.enable(this.gl.POLYGON_OFFSET_FILL)),i.polygonOffset(h,l)):this.depthBiasEnabled&&(this.depthBiasEnabled=!1,this.gl.disable(this.gl.POLYGON_OFFSET_FILL)),s.copy(e)}}setCullMode(e){if(this.cullMode!==e){if(e===0)this.gl.disable(this.gl.CULL_FACE);else{this.cullMode===0&&this.gl.enable(this.gl.CULL_FACE);let s=this.glCull[e];this.cullFace!==s&&(this.gl.cullFace(s),this.cullFace=s)}this.cullMode=e}}setFrontFace(e){if(this.frontFace!==e){let s=this.glFrontFace[e];this.gl.frontFace(s),this.frontFace=e}}setShader(e,s=!1){e!==this.shader&&(this.shader=e,this.shaderAsyncCompile=s,this.shaderValid=void 0)}activateShader(){let{shader:e}=this,{impl:s}=e;this.shaderValid===void 0&&(e.failed?this.shaderValid=!1:e.ready||(this.shaderAsyncCompile?s.isLinked(this)?s.finalize(this,e)||(e.failed=!0,this.shaderValid=!1):this.shaderValid=!1:s.finalize(this,e)||(e.failed=!0,this.shaderValid=!1))),this.shaderValid===void 0&&(this.gl.useProgram(s.glProgram),this.shaderValid=!0)}clearVertexArrayObjectCache(){let e=this.gl;this._vaoMap.forEach((s,i,r)=>{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;i<e.length;i++){let r=e[i];if((r===Ig||r===Xx)&&window?.navigator?.gpu){let a=r===Xx?"bare":void 0;s.push(()=>new 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;i<s;i++){let r=new KP;this.colorArrayOps[i]=r,this.samples===1&&(r.store=!0,r.resolve=!1);let a=this.renderTarget?._colorBuffers?.[i];if(this.renderTarget?.mipmaps&&a?.mipmaps){let o=ur(a._format);r.genMipmaps=!o}}}postInit(){}frameUpdate(){if(this._options&&this.renderTarget){let e=this._options.resizeSource??this.device.backBuffer,s=Math.floor(e.width*this.scaleX),i=Math.floor(e.height*this.scaleY);this.renderTarget.resize(s,i)}}setClearColor(e){let s=this.colorArrayOps.length;for(let i=0;i<s;i++){let r=this.colorArrayOps[i];e&&(r.clearValue.copy(e),r.clearValueLinear.linear(e)),r.clear=!!e}}setClearDepth(e){e!==void 0&&(this.depthStencilOps.clearDepthValue=e),this.depthStencilOps.clearDepth=e!==void 0}setClearStencil(e){e!==void 0&&(this.depthStencilOps.clearStencilValue=e),this.depthStencilOps.clearStencil=e!==void 0}render(){if(this.enabled){let e=this.device,s=this.renderTarget!==void 0;this.before(),this.executeEnabled&&(s&&!this._skipStart&&e.startRenderPass(this),this.execute(),s&&!this._skipEnd&&e.endRenderPass(this)),this.after(),e.renderPassIndex++}}};var Qv=class{constructor(t,e,s=3){e!==void 0&&!(e instanceof ft)&&(s=e,e=void 0),this.device=t.device;let i=this.device.gl,r=e??t;s===3&&r.usage!==s&&(i.bindBuffer(i.ARRAY_BUFFER,r.impl.bufferId),i.bufferData(i.ARRAY_BUFFER,r.storage,i.DYNAMIC_COPY)),this._inputBuffer=t,this._destroyOutputBuffer=!e,this._outputBuffer=e??new ft(t.device,t.format,t.numVertices,{usage:s,data:t.storage})}static createShader(t,e,s,i){return new Be(t,ns.createDefinition(t,{name:s,vertexCode:e,feedbackVaryings:i,useTransformFeedback:!0,fragmentCode:"void main(void) {gl_FragColor = vec4(0.0);}"}))}destroy(){this._destroyOutputBuffer&&this._outputBuffer.destroy()}process(t,e=!0){let s=this.device,i=s.getRenderTarget();if(s.setRenderTarget(null),s.updateBegin(),s.setVertexBuffer(this._inputBuffer),s.setRaster(!1),s.setTransformFeedbackBuffer(this._outputBuffer),s.setShader(t),s.draw({type:Aa,base:0,baseVertex:0,count:this._inputBuffer.numVertices,indexed:!1}),s.setTransformFeedbackBuffer(null),s.setRaster(!0),s.updateEnd(),s.setRenderTarget(i),e){let r=this._inputBuffer.impl.bufferId;this._inputBuffer.impl.bufferId=this._outputBuffer.impl.bufferId,this._outputBuffer.impl.bufferId=r,r=this._inputBuffer.impl.vao,this._inputBuffer.impl.vao=this._outputBuffer.impl.vao,this._outputBuffer.impl.vao=r}}get inputBuffer(){return this._inputBuffer}get outputBuffer(){return this._outputBuffer}};function SW(c){this.array[this.index]=c}function xW(c,t){this.array[this.index]=c,this.array[this.index+1]=t}function vW(c,t,e){this.array[this.index]=c,this.array[this.index+1]=t,this.array[this.index+2]=e}function TW(c,t,e,s){this.array[this.index]=c,this.array[this.index+1]=t,this.array[this.index+2]=e,this.array[this.index+3]=s}function yW(c,t,e){this.array[c]=t[e]}function EW(c,t,e){this.array[c]=t[e],this.array[c+1]=t[e+1]}function AW(c,t,e){this.array[c]=t[e],this.array[c+1]=t[e+1],this.array[c+2]=t[e+2]}function CW(c,t,e){this.array[c]=t[e],this.array[c+1]=t[e+1],this.array[c+2]=t[e+2],this.array[c+3]=t[e+3]}function PW(c,t,e){t[e]=this.array[c]}function wW(c,t,e){t[e]=this.array[c],t[e+1]=this.array[c+1]}function IW(c,t,e){t[e]=this.array[c],t[e+1]=this.array[c+1],t[e+2]=this.array[c+2]}function RW(c,t,e){t[e]=this.array[c],t[e+1]=this.array[c+1],t[e+2]=this.array[c+2],t[e+3]=this.array[c+3]}var qP=class{constructor(t,e,s){switch(this.index=0,this.numComponents=e.numComponents,s.interleaved?this.array=new Ro[e.dataType](t,e.offset):this.array=new Ro[e.dataType](t,e.offset,s.vertexCount*e.numComponents),this.stride=e.stride/this.array.constructor.BYTES_PER_ELEMENT,e.numComponents){case 1:this.set=SW,this.getToArray=PW,this.setFromArray=yW;break;case 2:this.set=xW,this.getToArray=wW,this.setFromArray=EW;break;case 3:this.set=vW,this.getToArray=IW,this.setFromArray=AW;break;case 4:this.set=TW,this.getToArray=RW,this.setFromArray=CW;break}}get(t){return this.array[this.index+t]}set(t,e,s,i){}getToArray(t,e,s){}setFromArray(t,e,s){}},Jr=class{constructor(t){this.vertexBuffer=t,this.vertexFormatSize=t.getFormat().size,this.buffer=this.vertexBuffer.lock(),this.accessors=[],this.element={};let e=this.vertexBuffer.getFormat();for(let s=0;s<e.elements.length;s++){let i=e.elements[s];this.accessors[s]=new qP(this.buffer,i,e),this.element[i.name]=this.accessors[s]}}next(t=1){let e=0,s=this.accessors,i=this.accessors.length;for(;e<i;){let r=s[e++];r.index+=t*r.stride}}end(){this.vertexBuffer.unlock()}writeData(t,e,s){let i=this.element[t];if(i){s>this.vertexBuffer.numVertices&&(s=this.vertexBuffer.numVertices);let r=i.numComponents;if(this.vertexBuffer.getFormat().interleaved){let a=0;for(let o=0;o<s;o++)i.setFromArray(a,e,o*r),a+=i.stride}else if(e.length>s*r){let a=s*r;if(ArrayBuffer.isView(e))e=e.subarray(0,a),i.array.set(e);else for(let o=0;o<a;o++)i.array[o]=e[o]}else i.array.set(e)}}readData(t,e){let s=this.element[t],i=0;if(s){i=this.vertexBuffer.numVertices;let r,a=s.numComponents;if(this.vertexBuffer.getFormat().interleaved){Array.isArray(e)&&(e.length=0),s.index=0;let o=0;for(r=0;r<i;r++)s.getToArray(o,e,r*a),o+=s.stride}else if(ArrayBuffer.isView(e))e.set(s.array);else{e.length=0;let o=i*a;for(r=0;r<o;r++)e[r]=s.array[r]}}return i}};var kg="mouse",zg="keyboard",Gg="gamepad",bW="mousex",DW="mousey",LW="padlx",MW="padly",OW="padrx",FW="padry",pae="key",mae=8,_ae=9,gae=13,Sae=13,xae=16,vae=17,Tae=18,yae=19,Eae=20,Aae=27,Cae=32,Pae=33,wae=34,Iae=35,Rae=36,bae=37,Dae=38,Lae=39,Mae=40,Oae=44,Fae=45,Nae=46,Bae=48,Uae=49,kae=50,zae=51,Gae=52,Vae=53,Hae=54,Wae=55,Xae=56,Yae=57,Kae=59,jae=61,qae=65,$ae=66,Zae=67,Qae=68,Jae=69,eoe=70,toe=71,soe=72,ioe=73,roe=74,aoe=75,ooe=76,noe=77,loe=78,coe=79,hoe=80,foe=81,uoe=82,doe=83,poe=84,moe=85,_oe=86,goe=87,Soe=88,xoe=89,voe=90,Toe=91,yoe=93,Eoe=96,Aoe=97,Coe=98,Poe=99,woe=100,Ioe=101,Roe=102,boe=103,Doe=104,Loe=105,Moe=106,Ooe=107,Foe=108,Noe=109,Boe=110,Uoe=111,koe=112,zoe=113,Goe=114,Voe=115,Hoe=116,Woe=117,Xoe=118,Yoe=119,Koe=120,joe=121,qoe=122,$oe=123,Zoe=188,Qoe=190,Joe=191,ene=219,tne=220,sne=221,ine=224,NW=-1,rne=0,ane=1,one=2,rL=0,nne=1,lne=2,cne=3,BW=0,UW=1,kW=2,zW=3,GW=4,VW=5,HW=6,WW=7,XW=8,YW=9,KW=10,jW=11,qW=12,$W=13,ZW=14,QW=15,JW=16,$P=0,ZP=1,QP=2,JP=3,eX=0,tX=1,sX=2,iX=3,rX=2,aX=0,oX=1,nX=3,lX=4,cX=5;var Zd=class{constructor(t,e){n(this,"key",null);n(this,"element",null);n(this,"event",null);e&&(this.key=e.keyCode,this.element=e.target,this.event=e)}};var Jv=new Zd;function ew(c){return Jv.key=c.keyCode,Jv.element=c.target,Jv.event=c,Jv}function eT(c){return typeof c=="string"?c.toUpperCase().charCodeAt(0):c}var hX={9:"Tab",13:"Enter",16:"Shift",17:"Control",18:"Alt",27:"Escape",37:"Left",38:"Up",39:"Right",40:"Down",46:"Delete",91:"Win"},mc=class extends J{constructor(e,s={}){super();n(this,"_element",null);n(this,"_keymap",{});n(this,"_lastmap",{});n(this,"_keyDownHandler");n(this,"_keyUpHandler");n(this,"_keyPressHandler");n(this,"_visibilityChangeHandler");n(this,"_windowBlurHandler");n(this,"preventDefault");n(this,"stopPropagation");this._keyDownHandler=this._handleKeyDown.bind(this),this._keyUpHandler=this._handleKeyUp.bind(this),this._keyPressHandler=this._handleKeyPress.bind(this),this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),this._windowBlurHandler=this._handleWindowBlur.bind(this),e&&this.attach(e),this.preventDefault=s.preventDefault||!1,this.stopPropagation=s.stopPropagation||!1}attach(e){this._element&&this.detach(),this._element=e,this._element.addEventListener("keydown",this._keyDownHandler,!1),this._element.addEventListener("keypress",this._keyPressHandler,!1),this._element.addEventListener("keyup",this._keyUpHandler,!1),document.addEventListener("visibilitychange",this._visibilityChangeHandler,!1),window.addEventListener("blur",this._windowBlurHandler,!1)}detach(){this._element&&(this._element.removeEventListener("keydown",this._keyDownHandler),this._element.removeEventListener("keypress",this._keyPressHandler),this._element.removeEventListener("keyup",this._keyUpHandler),this._element=null,document.removeEventListener("visibilitychange",this._visibilityChangeHandler,!1),window.removeEventListener("blur",this._windowBlurHandler,!1))}toKeyIdentifier(e){e=eT(e);let s=hX[e.toString()];if(s)return s;let i=e.toString(16).toUpperCase(),r=i.length;for(let a=0;a<4-r;a++)i=`0${i}`;return`U+${i}`}_handleKeyDown(e){let s=e.keyCode||e.charCode;if(s===void 0)return;let i=this.toKeyIdentifier(s);this._keymap[i]=!0,this.fire("keydown",ew(e)),this.preventDefault&&e.preventDefault(),this.stopPropagation&&e.stopPropagation()}_handleKeyUp(e){let s=e.keyCode||e.charCode;if(s===void 0)return;let i=this.toKeyIdentifier(s);delete this._keymap[i],this.fire("keyup",ew(e)),this.preventDefault&&e.preventDefault(),this.stopPropagation&&e.stopPropagation()}_handleKeyPress(e){this.fire("keypress",ew(e)),this.preventDefault&&e.preventDefault(),this.stopPropagation&&e.stopPropagation()}_handleVisibilityChange(){document.visibilityState==="hidden"&&this._handleWindowBlur()}_handleWindowBlur(){this._keymap={},this._lastmap={}}update(){for(let e in this._lastmap)delete this._lastmap[e];for(let e in this._keymap)this._keymap.hasOwnProperty(e)&&(this._lastmap[e]=this._keymap[e])}isPressed(e){let s=eT(e),i=this.toKeyIdentifier(s);return!!this._keymap[i]}wasPressed(e){let s=eT(e),i=this.toKeyIdentifier(s);return!!this._keymap[i]&&!this._lastmap[i]}wasReleased(e){let s=eT(e),i=this.toKeyIdentifier(s);return!this._keymap[i]&&!!this._lastmap[i]}};n(mc,"EVENT_KEYDOWN","keydown"),n(mc,"EVENT_KEYUP","keyup");function tT(){return!!(document.pointerLockElement||document.mozPointerLockElement||document.webkitPointerLockElement)}var za=class c{constructor(t,e){n(this,"x",0);n(this,"y",0);n(this,"dx",0);n(this,"dy",0);n(this,"button",-1);n(this,"buttons");n(this,"wheelDelta",0);n(this,"element");n(this,"ctrlKey",!1);n(this,"altKey",!1);n(this,"shiftKey",!1);n(this,"metaKey",!1);n(this,"event");let s={x:0,y:0};if(e){if(e instanceof c)throw Error("Expected MouseEvent");s=t._getTargetCoords(e)}else e={};if(s)this.x=s.x,this.y=s.y;else if(tT())this.x=0,this.y=0;else return;e.type==="wheel"&&(e.deltaY>0?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||e.clientX>=i+this._target.clientWidth||e.clientY<r||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;s<e;++s){let i=this._actions[t][s];switch(i.type){case zg:if(this._keyboard){let r=i.keys.length;for(let a=0;a<r;a++)if(this._keyboard.isPressed(i.keys[a]))return!0}break;case kg:if(this._mouse&&this._mouse.isPressed(i.button))return!0;break;case Gg:if(this._gamepads&&this._gamepads.isPressed(i.pad,i.button))return!0;break}}return!1}wasPressed(t){if(!this._actions[t])return!1;let e=this._actions[t].length;for(let s=0;s<e;++s){let i=this._actions[t][s];switch(i.type){case zg:if(this._keyboard){let r=i.keys.length;for(let a=0;a<r;a++)if(this._keyboard.wasPressed(i.keys[a]))return!0}break;case kg:if(this._mouse&&this._mouse.wasPressed(i.button))return!0;break;case Gg:if(this._gamepads&&this._gamepads.wasPressed(i.pad,i.button))return!0;break}}return!1}getAxis(t){let e=0;if(this._axes[t]){let s=this._axes[t].length;for(let i=0;i<s;i++)if(typeof this._axes[t][i]=="function"){let r=this._axes[t][i]();Math.abs(r)>Math.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<e.buttons.length?Vg.DEFAULT_DUAL:e;return s.mapping=c.mapping,s}var iw=.25;function fX(c){return new Promise(t=>{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;l<h;l++)t[l]||(t[l]=()=>0);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;l<h;l++)e[l]||(e[l]=()=>tw)}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;r<a;r++)i[r].update(t.buttons[r]);return this}updateMap(t){t.mapping="custom",iT[this.id]=t,this.map=t,this.mapping="custom",this._compileMapping()}resetMap(){if(iT[this.id]){delete iT[this.id];let t=lL(this.pad);this.map=t,this.mapping=t.mapping,this._compileMapping()}}get axes(){return this._compiledMapping.axes.map(t=>t())}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;s<i;s++){let r=e[s]._buttons;this._previous[s]||(this._previous[s]=[]);for(let a=0,o=r.length;a<o;a++){let l=r[s];this.previous[s][a]=l?!l.wasPressed&&l.pressed||l.wasReleased:!1}}return this._previous.length=this.current.length,this._previous}_ongamepadconnected(e){let s=new rT(e.gamepad,this.getMap(e.gamepad)),i=this.current,r=i.findIndex(a=>a.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;i<r;i++)if(s[i]){let a=this.findByIndex(s[i].index);if(a)e.push(a.update(s[i]));else{let o=new rT(s[i],this.getMap(s[i]));this.current.push(o),e.push(o)}}return e}destroy(){window.removeEventListener("gamepadconnected",this._ongamepadconnectedHandler,!1),window.removeEventListener("gamepaddisconnected",this._ongamepaddisconnectedHandler,!1)}getMap(e){return lL(e)}isPressed(e,s){return this.current[e]?.isPressed(s)||!1}wasPressed(e,s){return this.current[e]?.wasPressed(s)||!1}wasReleased(e,s){return this.current[e]?.wasReleased(s)||!1}getAxis(e,s){return this.current[e]?.getAxis(s)||0}pulse(e,s,i,r){let a=this.current[e];return a?a.pulse(s,i,r):Promise.resolve(!1)}pulseAll(e,s,i){return Promise.all(this.current.map(r=>r.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.maxRetries){s.retries++,s.retrying=!0;let r=R.clamp(Math.pow(2,s.retries)*nt.retryDelay,0,s.maxRetryDelay||5e3);setTimeout(()=>{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;e<this.uniformFormats.length;e++)if(this.uniformFormats[e]?.get(t))return!0;return!1}hasTexture(t){for(let e=0;e<this.bindGroupFormats.length;e++)if(this.bindGroupFormats[e]?.getTexture(t))return!0;return!1}getVertexElement(t){return this.vertexFormat?.elements.find(e=>e.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])=>e<s?-1:e>s?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;s<t.length;s++){let i=t[s];if(i)for(let[r,a]of i)e.set(r,a)}return e}};var Lw=class extends yi{constructor(t,e){super(),this.key=t,this.shaderDefinition=e}generateKey(t){return this.key}createShaderDefinition(t,e){return this.shaderDefinition}},Se=class{static createShader(t,e){let s=Ji(t),i=s.getCachedShader(e.uniqueName);if(!i){let r=t.isWebGPU&&(!!e.vertexWGSL||!!e.vertexChunk)&&(!!e.fragmentWGSL||!!e.fragmentChunk),a=ne.get(t,r?se:fe),o=e.vertexChunk?a.get(e.vertexChunk):r?e.vertexWGSL:e.vertexGLSL,l=e.fragmentChunk?a.get(e.fragmentChunk):r?e.fragmentWGSL:e.fragmentGLSL,h=Ha.merge(a,e.fragmentIncludes),f=Ha.merge(a,e.vertexIncludes);i=new Be(t,ns.createDefinition(t,{name:e.uniqueName,shaderLanguage:r?se:fe,attributes:e.attributes,vertexCode:o,fragmentCode:l,useTransformFeedback:e.useTransformFeedback,vertexIncludes:f,vertexDefines:e.vertexDefines,fragmentIncludes:h,fragmentDefines:e.fragmentDefines,fragmentOutputTypes:e.fragmentOutputTypes})),s.setCachedShader(e.uniqueName,i)}return i}static getCoreDefines(t,e){let s=new Map(t.defines);return e.cameraShaderParams.defines.forEach((r,a)=>s.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<e.length;s++){let i=t.layers.getLayerById(e[s]);i&&i.addMeshInstances([this.meshInstance])}}removeFromLayers(t,e){for(let s=0;s<e.length;s++){let i=t.layers.getLayerById(e[s]);i&&i.removeMeshInstances([this.meshInstance])}}updateBoundingBox(){this._aabb.copy(this.origMeshInstances[0].aabb);for(let t=1;t<this.origMeshInstances.length;t++)this._aabb.add(this.origMeshInstances[t].aabb);this.meshInstance.aabb=this._aabb,this.meshInstance._aabbVer=0}get model(){}};var pt=class{constructor(t,e,s,i,r=[Os]){n(this,"_ui",!1);n(this,"_sprite",!1);n(this,"_obj",{model:[],element:[],sprite:[],render:[]});n(this,"id");n(this,"name");n(this,"dynamic");n(this,"maxAabbSize");n(this,"layers");this.id=t,this.name=e,this.dynamic=s,this.maxAabbSize=i,this.layers=r}};n(pt,"MODEL","model"),n(pt,"ELEMENT","element"),n(pt,"SPRITE","sprite"),n(pt,"RENDER","render");var vL=new W,er=class{constructor(t){n(this,"bones");this._dirty=!0,this._rootBone=null,this._skinUpdateIndex=-1,this._updateBeforeCull=!0,t&&this.initSkin(t)}set rootBone(t){this._rootBone=t}get rootBone(){return this._rootBone}init(t,e){let s=e*3,i=Math.ceil(Math.sqrt(s));i=R.roundUp(i,3);let r=Math.ceil(s/i);this.boneTexture=new Z(t,{width:i,height:r,format:ke,mipmaps:!1,minFilter:0,magFilter:0,name:"skin"}),this.matrixPalette=this.boneTexture.lock({mode:ZC}),this.boneTexture.unlock()}destroy(){this.boneTexture&&(this.boneTexture.destroy(),this.boneTexture=null)}resolve(t,e){this.rootBone=t;let s=this.skin,i=[];for(let r=0;r<s.boneNames.length;r++){let a=s.boneNames[r],o=t.findByName(a);o||(o=e),i.push(o)}this.bones=i}initSkin(t){this.skin=t,this.bones=[];let e=t.inverseBindPose.length;this.init(t.device,e),this.matrices=[];for(let s=0;s<e;s++)this.matrices[s]=new W}uploadBones(t){this.boneTexture.upload()}_updateMatrices(t,e){if(this._skinUpdateIndex!==e){this._skinUpdateIndex=e,vL.copy(t.getWorldTransform()).invert();for(let s=this.bones.length-1;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;r<i;r++){let a=this.matrices[r].data,o=r*12;s[o]=a[0],s[o+1]=a[4],s[o+2]=a[8],s[o+3]=a[12],s[o+4]=a[1],s[o+5]=a[5],s[o+6]=a[9],s[o+7]=a[13],s[o+8]=a[2],s[o+9]=a[6],s[o+10]=a[10],s[o+11]=a[14]}this.uploadBones(this.skin.device)}};var Yf=class extends er{constructor(t,e,s){super();let i=e.length;this.init(t,i),this.device=t,this.rootNode=s,this.bones=e}updateMatrices(t,e){}updateMatrixPalette(t,e){let s=this.matrixPalette,i=this.bones.length;for(let r=0;r<i;r++){let a=this.bones[r].getWorldTransform().data,o=r*12;s[o]=a[0],s[o+1]=a[4],s[o+2]=a[8],s[o+3]=a[12],s[o+4]=a[1],s[o+5]=a[5],s[o+6]=a[9],s[o+7]=a[13],s[o+8]=a[2],s[o+9]=a[6],s[o+10]=a[10],s[o+11]=a[14]}this.uploadBones(this.device)}};var hY=0,ia=class{constructor(){this.initDefaults()}initDefaults(){this.recreate=!1,this.verticesUsage=0,this.indicesUsage=0,this.maxVertices=0,this.maxIndices=0,this.vertexCount=0,this.indexCount=0,this.vertexStreamsUpdated=!1,this.indexStreamUpdated=!1,this.vertexStreamDictionary={},this.indices=null}_changeVertexCount(t,e){this.vertexCount||(this.vertexCount=t)}};n(ia,"DEFAULT_COMPONENTS_POSITION",3),n(ia,"DEFAULT_COMPONENTS_NORMAL",3),n(ia,"DEFAULT_COMPONENTS_UV",2),n(ia,"DEFAULT_COMPONENTS_COLORS",4);var Ow=class{constructor(t,e,s,i,r){this.data=t,this.componentCount=e,this.dataType=s,this.dataTypeNormalize=i,this.asInt=r}},_e=class c extends Mo{constructor(e,s){super();n(this,"indexBuffer",[null]);n(this,"vertexBuffer",null);n(this,"primitive",[{type:0,base:0,baseVertex:0,count:0}]);n(this,"skin",null);n(this,"boneAabb",null);n(this,"_aabbVer",0);n(this,"_aabb",new ge);n(this,"_geometryData",null);n(this,"_morph",null);n(this,"_storageIndex",!1);n(this,"_storageVertex",!1);this.id=hY++,this.device=e,this._storageIndex=s?.storageIndex||!1,this._storageVertex=s?.storageVertex||!1}static fromGeometry(e,s,i={}){let r=new c(e,i),{positions:a,normals:o,tangents:l,colors:h,uvs:f,uvs1:u,blendIndices:d,blendWeights:p,indices:m}=s;return a&&r.setPositions(a),o&&r.setNormals(o),l&&r.setVertexStream(vs,l,4),h&&r.setColors32(h),f&&r.setUvs(0,f),u&&r.setUvs(1,u),d&&r.setVertexStream($t,d,4,d.length/4,ai),p&&r.setVertexStream(bs,p,4),m&&r.setIndices(m),r.update(),r}set morph(e){e!==this._morph&&(this._morph&&this._morph.decRefCount(),this._morph=e,e&&e.incRefCount())}get morph(){return this._morph}set aabb(e){this._aabb=e,this._aabbVer++}get aabb(){return this._aabb}destroy(){let e=this.morph;e&&(this.morph=null,e.refCount<1&&e.destroy()),this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=null);for(let s=0;s<this.indexBuffer.length;s++)this._destroyIndexBuffer(s);this.indexBuffer.length=0,this._geometryData=null}_destroyIndexBuffer(e){this.indexBuffer[e]&&(this.indexBuffer[e].destroy(),this.indexBuffer[e]=null)}_initBoneAabbs(e){this.boneAabb=[],this.boneUsed=[];let s,i,r,a,o,l=[],h=[],f=this.boneUsed,u=this.skin.boneNames.length,d,p,m;for(let E=0;E<u;E++)l[E]=new x(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),h[E]=new x(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);let _=new Jr(this.vertexBuffer),S=_.element[ee],g=_.element[bs],T=_.element[$t],C=this.vertexBuffer.numVertices;for(let E=0;E<C;E++){for(let y=0;y<4;y++)if(g.array[g.index+y]>0){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.x<s&&(a.x=s),a.y<i&&(a.y=i),a.z<r&&(a.z=r),e){let w=d=s,I=p=i,D=m=r;for(let O=0;O<e.length;O++){let G=e[O],M=G.deltaPositions[E*3],H=G.deltaPositions[E*3+1],U=G.deltaPositions[E*3+2];M<0?w+=M:d+=M,H<0?I+=H:p+=H,U<0?D+=U:m+=U}o.x>w&&(o.x=w),o.y>I&&(o.y=I),o.z>D&&(o.z=D),a.x<d&&(a.x=d),a.y<p&&(a.y=p),a.z<m&&(a.z=m)}}_.next()}let v=this.vertexBuffer.getFormat().elements.find(E=>E.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;y<u;y++)if(f[y]){let P=l[y],A=h[y];P.set(E(P.x),E(P.y),E(P.z)),A.set(E(A.x),E(A.y),E(A.z))}}for(let E=0;E<u;E++){let y=new ge;y.setMinMax(l[E],h[E]),this.boneAabb.push(y)}}_initGeometryData(){this._geometryData||(this._geometryData=new ia,this.vertexBuffer&&(this._geometryData.vertexCount=this.vertexBuffer.numVertices,this._geometryData.maxVertices=this.vertexBuffer.numVertices),this.indexBuffer.length>0&&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;r<a;r++)e.push(i[r])}}else this.indexBuffer.length>0&&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;S<o+l;S+=3)for(let g=0;g<3;g++){let T=d[S+a[g][0]]+h,C=d[S+a[g][1]]+h,v=T>C?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<a;h+=3)s[l++]=h,s[l++]=h+1,s[l++]=h+1,s[l++]=h+2,s[l++]=h+2,s[l++]=h}let r=new os(this.vertexBuffer.device,i,s.length,0,s.buffer);this.primitive[Fo]={type:Pn,base:0,baseVertex:0,count:s.length,indexed:!0},this.indexBuffer[Fo]=r}};var TL=new W,Fw=new x,yL=new $,Nw=new $,EL=new x,AL=new x,fY=new W,uY=new $,vr=new x,nS=new W,Tr=new $,Pp=new $,CL=new W,Bw=new x,IT=new x;function PL(c,t){return c instanceof Function?c:e=>{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<s;++i){let r=wL(e[i],t);if(r)return r}return null}var Pe=class extends J{constructor(e="Untitled"){super();n(this,"name");n(this,"tags",new va(this));n(this,"localPosition",new x);n(this,"localRotation",new $);n(this,"localScale",new x(1,1,1));n(this,"localEulerAngles",new x);n(this,"position",new x);n(this,"rotation",new $);n(this,"eulerAngles",new x);n(this,"_scale",null);n(this,"localTransform",new W);n(this,"_dirtyLocal",!1);n(this,"_aabbVer",0);n(this,"_frozen",!1);n(this,"worldTransform",new W);n(this,"_dirtyWorld",!1);n(this,"_worldScaleSign",0);n(this,"_normalMatrix",new Ws);n(this,"_dirtyNormal",!0);n(this,"_right",null);n(this,"_up",null);n(this,"_forward",null);n(this,"_parent",null);n(this,"_children",[]);n(this,"_graphDepth",0);n(this,"_enabled",!0);n(this,"_enabledInHierarchy",!1);n(this,"scaleCompensation",!1);this.name=e}get right(){return this._right||(this._right=new x),this.getWorldTransform().getX(this._right).normalize()}get up(){return this._up||(this._up=new x),this.getWorldTransform().getY(this._up).normalize()}get forward(){return this._forward||(this._forward=new x),this.getWorldTransform().getZ(this._forward).normalize().mulScalar(-1)}get normalMatrix(){let e=this._normalMatrix;return this._dirtyNormal&&(e.invertMat4(this.getWorldTransform()).transpose(),this._dirtyNormal=!1),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 s=this.name;for(;e&&e._parent;)s=`${e.name}/${s}`,e=e._parent;return s}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,s){e._onHierarchyStateChanged(s);let i=e._children;for(let r=0,a=i.length;r<a;r++)i[r]._enabled&&this._notifyHierarchyStateChanged(i[r],s)}_onHierarchyStateChanged(e){this._enabledInHierarchy=e,e&&!this._frozen&&this._unfreezeParentToRoot()}_cloneInternal(e){e.name=this.name;let s=this.tags._list;e.tags.clear();for(let i=0;i<s.length;i++)e.tags.add(s[i]);e.localPosition.copy(this.localPosition),e.localRotation.copy(this.localRotation),e.localScale.copy(this.localScale),e.localEulerAngles.copy(this.localEulerAngles),e.position.copy(this.position),e.rotation.copy(this.rotation),e.eulerAngles.copy(this.eulerAngles),e.localTransform.copy(this.localTransform),e._dirtyLocal=this._dirtyLocal,e.worldTransform.copy(this.worldTransform),e._dirtyWorld=this._dirtyWorld,e._dirtyNormal=this._dirtyNormal,e._aabbVer=this._aabbVer+1,e._enabled=this._enabled,e.scaleCompensation=this.scaleCompensation,e._enabledInHierarchy=!1}clone(){let e=new this.constructor;return this._cloneInternal(e),e}copy(e){return e._cloneInternal(this),this}destroy(){this.remove();let e=this._children;for(;e.length;){let s=e.pop();s._parent=null,s.destroy()}this.fire("destroy",this),this.off()}find(e,s){let i=[],r=PL(e,s);return this.forEach(a=>{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;o<r._children.length;o++)i(r._children[o],!0)};return i(this,!1),s}findByName(e){return this.findOne("name",e)}findByPath(e){let s=Array.isArray(e)?e:e.split("/"),i=this;for(let r=0,a=s.length;r<a;++r)if(i=i.children.find(o=>o.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<r;++a)i[a].forEach(e,s)}isDescendantOf(e){let s=this._parent;for(;s;){if(s===e)return!0;s=s._parent}return!1}isAncestorOf(e){return e.isDescendantOf(this)}getEulerAngles(){return this.getWorldTransform().getEulerAngles(this.eulerAngles),this.eulerAngles}getLocalEulerAngles(){return this.localRotation.getEulerAngles(this.localEulerAngles),this.localEulerAngles}getLocalPosition(){return this.localPosition}getLocalRotation(){return this.localRotation}getLocalScale(){return this.localScale}getLocalTransform(){return this._dirtyLocal&&(this.localTransform.setTRS(this.localPosition,this.localRotation,this.localScale),this._dirtyLocal=!1),this.localTransform}getPosition(){return this.getWorldTransform().getTranslation(this.position),this.position}getRotation(){return this.rotation.setFromMat4(this.getWorldTransform()),this.rotation}getScale(){return this._scale||(this._scale=new x),this.getWorldTransform().getScale(this._scale)}getWorldTransform(){return!this._dirtyLocal&&!this._dirtyWorld?this.worldTransform:(this._parent&&this._parent.getWorldTransform(),this._sync(),this.worldTransform)}get worldScaleSign(){return this._worldScaleSign===0&&(this._worldScaleSign=this.getWorldTransform().scaleSign),this._worldScaleSign}remove(){this._parent?.removeChild(this)}reparent(e,s){this.remove(),e&&(s>=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;e<this._children.length;e++)this._children[e]._dirtyWorld||this._children[e]._dirtifyWorldInternal()}this._dirtyNormal=!0,this._worldScaleSign=0,this._aabbVer++}setPosition(e,s,i){e instanceof x?vr.copy(e):vr.set(e,s,i),this._parent===null?this.localPosition.copy(vr):(nS.copy(this._parent.getWorldTransform()).invert(),nS.transformPoint(vr,this.localPosition)),this._dirtyLocal||this._dirtifyLocal()}setRotation(e,s,i,r){if(e instanceof $?Tr.copy(e):Tr.set(e,s,i,r),this._parent===null)this.localRotation.copy(Tr);else{let a=this._parent.getRotation();Pp.copy(a).invert(),this.localRotation.copy(Pp).mul(Tr)}this._dirtyLocal||this._dirtifyLocal()}setPositionAndRotation(e,s){if(this._parent===null)this.localPosition.copy(e),this.localRotation.copy(s);else{let i=this._parent.getWorldTransform();nS.copy(i).invert(),nS.transformPoint(e,this.localPosition),this.localRotation.setFromMat4(nS).mul(s)}this._dirtyLocal||this._dirtifyLocal()}setEulerAngles(e,s,i){if(this.localRotation.setFromEulerAngles(e,s,i),this._parent!==null){let r=this._parent.getRotation();Pp.copy(r).invert(),this.localRotation.mul2(Pp,this.localRotation)}this._dirtyLocal||this._dirtifyLocal()}addChild(e){this._prepareInsertChild(e),this._children.push(e),this._onInsertChild(e)}addChildAndSaveTransform(e){let s=e.getPosition(),i=e.getRotation();this._prepareInsertChild(e),e.setPosition(fY.copy(this.worldTransform).invert().transformPoint(s)),e.setRotation(uY.copy(this.getRotation()).invert().mul(i)),this._children.push(e),this._onInsertChild(e)}insertChild(e,s){this._prepareInsertChild(e),this._children.splice(s,0,e),this._onInsertChild(e)}_prepareInsertChild(e){e.remove()}_fireOnHierarchy(e,s,i){this.fire(e,i);for(let r=0;r<this._children.length;r++)this._children[r]._fireOnHierarchy(s,s,i)}_onInsertChild(e){e._parent=this;let s=e._enabled&&this.enabled;e._enabledInHierarchy!==s&&(e._enabledInHierarchy=s,e._notifyHierarchyStateChanged(e,s)),e._updateGraphDepth(),e._dirtifyWorld(),this._frozen&&e._unfreezeParentToRoot(),e._fireOnHierarchy("insert","inserthierarchy",this),this.fire&&this.fire("childinsert",e)}_updateGraphDepth(){this._graphDepth=this._parent?this._parent._graphDepth+1:0;for(let e=0,s=this._children.length;e<s;e++)this._children[e]._updateGraphDepth()}removeChild(e){let s=this._children.indexOf(e);s!==-1&&(this._children.splice(s,1),e._parent=null,e._fireOnHierarchy("remove","removehierarchy",this),this.fire("childremove",e))}_sync(){if(this._dirtyLocal&&(this.localTransform.setTRS(this.localPosition,this.localRotation,this.localScale),this._dirtyLocal=!1),this._dirtyWorld){if(this._parent===null)this.worldTransform.copy(this.localTransform);else if(this.scaleCompensation){let e,s=this._parent,i=this.localScale,r=s;if(r){for(;r&&r.scaleCompensation;)r=r._parent;r&&(r=r._parent,r&&(e=r.worldTransform.getScale(),EL.mul2(e,this.localScale),i=EL))}Nw.setFromMat4(s.worldTransform),yL.mul2(Nw,this.localRotation);let a=s.worldTransform;s.scaleCompensation&&(AL.mul2(e,s.getLocalScale()),TL.setTRS(s.worldTransform.getTranslation(Fw),Nw,AL),a=TL),a.transformPoint(this.localPosition,Fw),this.worldTransform.setTRS(Fw,yL,i)}else this.worldTransform.mulAffine2(this._parent.worldTransform,this.localTransform);this._dirtyWorld=!1}}syncHierarchy(){if(!this._enabled||this._frozen)return;this._frozen=!0,(this._dirtyLocal||this._dirtyWorld)&&this._sync();let e=this._children;for(let s=0,i=e.length;s<i;s++)e[s].syncHierarchy()}lookAt(e,s,i,r=0,a=1,o=0){if(e instanceof x)Bw.copy(e),s instanceof x?IT.copy(s):IT.copy(x.UP);else{if(i===void 0)return;Bw.set(e,s,i),IT.set(r,a,o)}CL.setLookAt(this.getPosition(),Bw,IT),Tr.setFromMat4(CL),this.setRotation(Tr)}translate(e,s,i){e instanceof x?vr.copy(e):vr.set(e,s,i),vr.add(this.getPosition()),this.setPosition(vr)}translateLocal(e,s,i){e instanceof x?vr.copy(e):vr.set(e,s,i),this.localRotation.transformVector(vr,vr),this.localPosition.add(vr),this._dirtyLocal||this._dirtifyLocal()}rotate(e,s,i){if(Tr.setFromEulerAngles(e,s,i),this._parent===null)this.localRotation.mul2(Tr,this.localRotation);else{let r=this.getRotation(),a=this._parent.getRotation();Pp.copy(a).invert(),Tr.mul2(Pp,Tr),this.localRotation.mul2(Tr,r)}this._dirtyLocal||this._dirtifyLocal()}rotateLocal(e,s,i){Tr.setFromEulerAngles(e,s,i),this.localRotation.mul(Tr),this._dirtyLocal||this._dirtifyLocal()}};var IL=new et;function ra(c){return IL.get(c)}function RL(c,t){IL.get(c,()=>t)}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<this.mesh.boneAabb.length;r++)s[r]&&(DT.setFromTransformedAabb(this.mesh.boneAabb[r],this.skinInstance.matrices[r]),i?(i=!1,t.center.copy(DT.center),t.halfExtents.copy(DT.halfExtents)):t.add(DT));e=!0}else if(this.node._aabbVer!==this._aabbVer||this.mesh._aabbVer!==this._aabbMeshVer){if(this.mesh?(t.center.copy(this.mesh.aabb.center),t.halfExtents.copy(this.mesh.aabb.halfExtents)):(t.center.set(0,0,0),t.halfExtents.set(0,0,0)),this.mesh&&this.mesh.morph){let s=this.mesh.morph.aabb;t._expand(s.getMin(),s.getMax())}e=!0,this._aabbVer=this.node._aabbVer,this._aabbMeshVer=this.mesh._aabbVer}}return e&&this._aabb.setFromTransformedAabb(t,this.node.getWorldTransform()),this._aabb}clearShaders(){this._shaderCache.forEach(t=>{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;s<t.length;s++){t[s]._renderStyle=e;let i=t[s].mesh;kw.has(i)||(kw.add(i),i.prepareRenderState(e))}kw.clear()}}_isVisible(t){return this.visible?this.isVisibleFunc?this.isVisibleFunc(t):(Uw.center=this.aabb.center,Uw.radius=this._aabb.halfExtents.length(),t.frustum.containsSphere(Uw)>0):!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<c.length;e++)if(c[e]!==t[e])return!1;return!0}return!1}function _Y(c,t){for(let e in c)if(c.hasOwnProperty(e)&&!DL(c[e],t[e]))return!1;for(let e in t)if(t.hasOwnProperty(e)&&!DL(t[e],c[e]))return!1;return!0}function Gw(c){return c.node.worldTransform.scaleSign}var Rp=class{constructor(t,e,s){this.device=t,this.rootNode=e,this.scene=s,this._init=!1,this._batchGroups={},this._batchGroupCounter=0,this._batchList=[],this._dirtyGroups=[]}destroy(){this.device=null,this.rootNode=null,this.scene=null,this._batchGroups={},this._batchList=[],this._dirtyGroups=[]}addGroup(t,e,s,i,r){if(i===void 0&&(i=this._batchGroupCounter,this._batchGroupCounter++),this._batchGroups[i])return;let a=new pt(i,t,e,s,r);return this._batchGroups[i]=a,a}removeGroup(t){if(!this._batchGroups[t])return;let e=[];for(let s=0;s<this._batchList.length;s++)this._batchList[s].batchGroupId===t?this.destroyBatch(this._batchList[s]):e.push(this._batchList[s]);this._batchList=e,this._removeModelsFromBatchGroup(this.rootNode,t),delete this._batchGroups[t]}markGroupDirty(t){this._dirtyGroups.indexOf(t)<0&&this._dirtyGroups.push(t)}getGroupByName(t){let e=this._batchGroups;for(let s in e)if(e.hasOwnProperty(s)&&e[s].name===t)return e[s];return null}getGroupById(t){return this._batchGroups[t]??null}getBatches(t){let e=[],s=this._batchList.length;for(let i=0;i<s;i++){let r=this._batchList[i];r.batchGroupId===t&&e.push(r)}return e}_removeModelsFromBatchGroup(t,e){if(t.enabled){t.model&&t.model.batchGroupId===e&&(t.model.batchGroupId=-1),t.render&&t.render.batchGroupId===e&&(t.render.batchGroupId=-1),t.element&&t.element.batchGroupId===e&&(t.element.batchGroupId=-1),t.sprite&&t.sprite.batchGroupId===e&&(t.sprite.batchGroupId=-1);for(let s=0;s<t._children.length;s++)this._removeModelsFromBatchGroup(t._children[s],e)}}insert(t,e,s){let i=this._batchGroups[e];i&&i._obj[t].indexOf(s)<0&&(i._obj[t].push(s),this.markGroupDirty(e))}remove(t,e,s){let i=this._batchGroups[e];if(i){let r=i._obj[t].indexOf(s);r>=0&&(i._obj[t].splice(r,1),this.markGroupDirty(e))}}_filterBatchableInstances(t,e){let s=!1,i=!1;for(let r=0;r<t.length;r++)t[r].skinInstance||t[r].morphInstance?s=!0:i=!0;return s?null:t}_extractRender(t,e,s,i){if(t.render){let r=this._filterBatchableInstances(t.render.meshInstances,t.name);r&&(e=i[t.render.batchGroupId]=e.concat(r),t.render.removeFromLayers())}return e}_extractModel(t,e,s,i){if(t.model&&t.model.model){let r=this._filterBatchableInstances(t.model.meshInstances,t.name);r&&(e=i[t.model.batchGroupId]=e.concat(r),t.model.removeModelFromLayers())}return e}_extractElement(t,e,s){if(!t.element)return;let i=!1;t.element._text&&t.element._text._model.meshInstances.length>0?(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;s<e.length;s++){let i=e[s],r=this._batchGroups[i];if(!r)continue;let a=t[i];a||(a=t[i]=[]);for(let o=0;o<r._obj.model.length;o++)a=this._extractModel(r._obj.model[o],a,r,t);for(let o=0;o<r._obj.render.length;o++)a=this._extractRender(r._obj.render[o],a,r,t);for(let o=0;o<r._obj.element.length;o++)this._extractElement(r._obj.element[o],a,r);for(let o=0;o<r._obj.sprite.length;o++){let l=r._obj.sprite[o];l.sprite&&l.sprite._meshInstance&&(r.dynamic||l.sprite.sprite._renderMode===Ti)&&(a.push(l.sprite._meshInstance),l.sprite.removeFromLayers(),r._sprite=!0)}}}generate(t){let e={};t||(t=Object.keys(this._batchGroups));let s=[];for(let l=0;l<this._batchList.length;l++){if(t.indexOf(this._batchList[l].batchGroupId)<0){s.push(this._batchList[l]);continue}this.destroyBatch(this._batchList[l])}if(this._batchList=s,this._collectAndRemoveMeshInstances(e,t),t===this._dirtyGroups)this._dirtyGroups.length=0;else{let l=[];for(let h=0;h<this._dirtyGroups.length;h++)t.indexOf(this._dirtyGroups[h])<0&&l.push(this._dirtyGroups[h]);this._dirtyGroups=l}let i,r,a,o;for(let l in e)if(e.hasOwnProperty(l)&&(i=e[l],a=this._batchGroups[l],!!a)){r=this.prepare(i,a.dynamic,a.maxAabbSize,a._ui||a._sprite);for(let h=0;h<r.length;h++)o=this.create(r[h],a.dynamic,parseInt(l,10)),o&&o.addToLayers(this.scene,a.layers)}}prepare(t,e,s=Number.POSITIVE_INFINITY,i){if(t.length===0)return[];let r=s*.5,a=1024,o=4294967295,l=new ge,h=new ge,f=null,u,d=[],p=0;i&&t.sort((g,T)=>g.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<m.length;G++){let M=m[G];if(e&&d[p].length>=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<t.length;o++)if(t[o].visible){let l=t[o].mesh,h=l.vertexBuffer.numVertices;if(i+=h,l.primitive[0].indexed)r+=l.primitive[0].count;else{let f=l.primitive[0].type;(f===dr||f===Ks)&&l.primitive[0].count===4&&(r+=6)}if(!s){a=t[o].material,s={};let f=l.vertexBuffer.format.elements;for(let u=0;u<f.length;u++){let d=f[u].name;s[d]={numComponents:f[u].numComponents,dataType:f[u].dataType,normalize:f[u].normalize,count:0}}e&&(s[$t]={numComponents:1,dataType:ye,normalize:!1,count:0})}}return{streams:s,batchNumVerts:i,batchNumIndices:r,material:a}}create(t,e,s){this._init||(this.vertexFormats={},this._init=!0);let i=null,r,a,o,l=null,h=this.collectBatchedMeshData(t,e);if(h.streams){let f=h.streams,u=h.material,d=h.batchNumVerts,p=h.batchNumIndices;l=new Xf(t,e,s),this._batchList.push(l);let m,_,S,g,T=0,C=0,v,E=d<=65535?Uint16Array:Uint32Array,y=new E(p);for(r in f)i=f[r],i.typeArrayType=Ro[i.dataType],i.elementByteSize=Wn[i.dataType],i.buffer=new i.typeArrayType(d*i.numComponents);for(let w=0;w<t.length;w++)if(t[w].visible){a=t[w].mesh,o=a.vertexBuffer.numVertices,e||(v=t[w].node.getWorldTransform());for(r in f)if(r!==$t){i=f[r];let I=new i.typeArrayType(i.buffer.buffer,i.elementByteSize*i.count),D=a.getVertexStream(r,I)*i.numComponents;if(i.count+=D,!e&&i.numComponents>=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;be<D;be+=i.numComponents)te=I[be],j=I[be+1],oe=I[be+2],I[be]=te*G+j*U+oe*N+V,I[be+1]=te*M+j*L+oe*k+q,I[be+2]=te*H+j*b+oe*z+re}else if(r===Ot||r===vs){bL.invertMat4(v).transpose();let[O,G,M,H,U,L,b,N,k]=bL.data,z,V,q;for(let re=0;re<D;re+=i.numComponents)z=I[re],V=I[re+1],q=I[re+2],I[re]=z*O+V*H+q*b,I[re+1]=z*G+V*U+q*N,I[re+2]=z*M+V*L+q*k}}}if(e){i=f[$t];for(let I=0;I<o;I++)i.buffer[i.count++]=w}if(a.primitive[0].indexed){m=a.primitive[0].base,_=a.primitive[0].baseVertex||0,S=a.primitive[0].count;let I=a.indexBuffer[0].getFormat();g=new Ef[I](a.indexBuffer[0].storage)}else{_=0;let I=a.primitive[0].type;if(I===dr||I===Ks)if(a.primitive[0].count===4)m=0,S=6,g=I===dr?pY:mY;else{S=0;continue}}for(let I=0;I<S;I++)y[I+C]=g[m+I]+_+T;C+=S,T+=o}a=new _e(this.device);for(r in f)i=f[r],a.setVertexStream(r,i.buffer,i.numComponents,void 0,i.dataType,i.normalize);y.length>0&&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;I<l.origMeshInstances.length;I++)w.push(l.origMeshInstances[I].node);P.skinInstance=new Yf(this.device,w,this.rootNode)}P._updateAabb=!1,P.drawOrder=l.origMeshInstances[0].drawOrder,P.stencilFront=l.origMeshInstances[0].stencilFront,P.stencilBack=l.origMeshInstances[0].stencilBack,P.flipFacesFactor=Gw(l.origMeshInstances[0]),P.castShadow=l.origMeshInstances[0].castShadow,l.meshInstance=P,l.updateBoundingBox()}return l}updateAll(){this._dirtyGroups.length>0&&this.generate(this._dirtyGroups);for(let t=0;t<this._batchList.length;t++)this._batchList[t].dynamic&&this._batchList[t].updateBoundingBox()}clone(t,e){let s=new Xf(e,t.dynamic,t.batchGroupId);this._batchList.push(s);let i=[];for(let r=0;r<e.length;r++)i.push(e[r].node);return s.meshInstance=new we(t.meshInstance.mesh,t.meshInstance.material,t.meshInstance.node),s.meshInstance._updateAabb=!1,s.meshInstance.parameters=e[0].parameters,s.meshInstance.cull=e[0].cull,s.meshInstance.layer=e[0].layer,t.dynamic&&(s.meshInstance.skinInstance=new Yf(this.device,i,this.rootNode)),s.meshInstance.castShadow=t.meshInstance.castShadow,s}destroyBatch(t){t.destroy(this.scene,this._batchGroups[t.batchGroupId].layers)}};var LL="uSceneColorMap",wc=class extends Nt{constructor(){super(...arguments);n(this,"colorRenderTarget",null);n(this,"source",null)}destroy(){super.destroy(),this.releaseRenderTarget(this.colorRenderTarget)}shouldReallocate(e,s,i){if(e?.colorBuffer.format!==i)return!0;let a=s?.width||this.device.width,o=s?.height||this.device.height;return!e||a!==e.width||o!==e.height}allocateRenderTarget(e,s,i,r){let a=new Z(i,{name:LL,format:r,width:s?s.colorBuffer.width:i.width,height:s?s.colorBuffer.height:i.height,mipmaps:!0,minFilter:5,magFilter:1,addressU:1,addressV:1});return e?(e.destroyFrameBuffers(),e._colorBuffer=a,e._colorBuffers=[a],e.evaluateDimensions()):e=new me({name:"ColorGrabRT",colorBuffer:a,depth:!1,stencil:!1,autoResolve:!1}),e}releaseRenderTarget(e){e&&(e.destroyTextureBuffers(),e.destroy())}frameUpdate(){let e=this.device,s=this.source,i=s?.colorBuffer.format??this.device.backBufferFormat;this.shouldReallocate(this.colorRenderTarget,s?.colorBuffer,i)&&(this.releaseRenderTarget(this.colorRenderTarget),this.colorRenderTarget=this.allocateRenderTarget(this.colorRenderTarget,s,e,i));let r=this.colorRenderTarget.colorBuffer;e.scope.resolve(LL).setValue(r)}execute(){let e=this.device,s=this.source,i=this.colorRenderTarget.colorBuffer;e.isWebGPU?(e.copyRenderTarget(s,this.colorRenderTarget,!0,!1),e.mipmapRenderer.generate(this.colorRenderTarget.colorBuffer.impl)):(e.copyRenderTarget(s,this.colorRenderTarget,!0,!1),e.activeTexture(e.maxCombinedTextures-1),e.bindTexture(i),e.gl.generateMipmap(i.impl._glTarget))}};var ML="uSceneDepthMap",MT=class extends Nt{constructor(e,s){super(e);n(this,"depthRenderTarget",null);n(this,"camera",null);this.camera=s}destroy(){super.destroy(),this.releaseRenderTarget(this.depthRenderTarget)}shouldReallocate(e,s){let i=s?.width||this.device.width,r=s?.height||this.device.height;return!e||i!==e.width||r!==e.height}allocateRenderTarget(e,s,i,r,a){let o=Z.createDataTexture2D(i,ML,s?s.colorBuffer.width:i.width,s?s.colorBuffer.height:i.height,r);return e?(e.destroyFrameBuffers(),a?e._depthBuffer=o:(e._colorBuffer=o,e._colorBuffers=[o]),e.evaluateDimensions()):e=new me({name:"DepthGrabRT",colorBuffer:a?null:o,depthBuffer:a?o:null,depth:!a,stencil:i.supportsStencil,autoResolve:!1}),e}releaseRenderTarget(e){e&&(e.destroyTextureBuffers(),e.destroy())}before(){let e=this.camera,s=this.device,i=e?.renderTarget??s.backBuffer,r=!0,a=i.stencil?fr:Ys;s.isWebGPU&&i.samples>1&&(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(e<t.radius)return 1;let s=Math.asin(t.radius/e),i=Math.tan(s),r=Math.tan(this.fov/2*R.DEG_TO_RAD);return Math.min(i/r,1)}return R.clamp(t.radius/this._orthoHeight,0,1)}getFrustumCorners(t=this.nearClip,e=this.farClip){let s=this.fov*R.DEG_TO_RAD,i,r;this.projection===ts?this.horizontalFov?(i=t*Math.tan(s/2),r=i/this.aspectRatio):(r=t*Math.tan(s/2),i=r*this.aspectRatio):(r=this._orthoHeight,i=r*this.aspectRatio);let a=gY;return a[0].x=i,a[0].y=-r,a[0].z=-t,a[1].x=i,a[1].y=r,a[1].z=-t,a[2].x=-i,a[2].y=r,a[2].z=-t,a[3].x=-i,a[3].y=-r,a[3].z=-t,this._projection===ts&&(this.horizontalFov?(i=e*Math.tan(s/2),r=i/this.aspectRatio):(r=e*Math.tan(s/2),i=r*this.aspectRatio)),a[4].x=i,a[4].y=-r,a[4].z=-e,a[5].x=i,a[5].y=r,a[5].z=-e,a[6].x=-i,a[6].y=r,a[6].z=-e,a[7].x=-i,a[7].y=-r,a[7].z=-e,a}setXrProperties(t){Object.assign(this._xrProperties,t),this._projMatDirty=!0}fillShaderParams(t){let e=this._farClip;return t[0]=1/e,t[1]=e,t[2]=this._nearClip,t[3]=this._projection===ni?1:0,t}};n(Wa,"_flipYProjectionMatrix",new W().setScale(1,-1,1)),n(Wa,"_webGpuDepthRangeMatrix",new W().set([1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1])),n(Wa,"_applyShaderProjectionScratch",new W);var Bs=Wa;var NL=new W,BL=new W,UL=new W,Ic=class Ic{static create(t,e,s,i){let r=new Bs(t);switch(r.node=new Pe(e),r.aspectRatio=1,r.aspectRatioMode=vp,r._scissorRectClear=!0,s){case We:r.node.setRotation(Ic.pointLightRotations[i]),r.fov=90,r.projection=ts;break;case je:r.projection=ts;break;case Ce:r.projection=ni;break}return r}static evalSpotCookieMatrix(t){let e=Ic._spotCookieCamera;e||(e=Ic.create(t.device,"SpotCookieCamera",je),Ic._spotCookieCamera=e),e.fov=t._outerConeAngle*2;let s=e._node;s.setPosition(t._node.getPosition()),s.setRotation(t._node.getRotation()),s.rotateLocal(-90,0,0),NL.setTRS(s.getPosition(),s.getRotation(),x.ONE).invert(),BL.mul2(e.projectionMatrix,NL);let i=t.cookieMatrix,r=t.atlasViewport;return UL.setViewport(r.x,r.y,r.z,r.w),i.mul2(UL,BL),i}};n(Ic,"pointLightRotations",[new $().setFromEulerAngles(0,90,180),new $().setFromEulerAngles(0,-90,180),new $().setFromEulerAngles(90,0,0),new $().setFromEulerAngles(-90,0,0),new $().setFromEulerAngles(0,180,180),new $().setFromEulerAngles(0,0,180)]),n(Ic,"_spotCookieCamera",null);var Wo=Ic;var aa=new x,jf=new Float32Array(6),SY=new x(-.5,0,0),xY=new x(0,0,.5),jt={POSITION_RANGE:0,DIRECTION_FLAGS:1,COLOR_ANGLES_BIAS:2,PROJ_MAT_0:3,ATLAS_VIEWPORT:3,PROJ_MAT_1:4,PROJ_MAT_2:5,PROJ_MAT_3:6,AREA_DATA_WIDTH:7,AREA_DATA_HEIGHT:8,COUNT:9},vY={LIGHTSHAPE_PUNCTUAL:`${$i}u`,LIGHTSHAPE_RECT:`${cT}u`,LIGHTSHAPE_DISK:`${hT}u`,LIGHTSHAPE_SPHERE:`${fT}u`,LIGHT_COLOR_DIVIDER:`${If}.0`},kL=(c,t)=>Object.keys(c).map(e=>`#define {${t}${e}} ${c[e]}`).join(`
`),zL=`
${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&&i<e){let l;i<s.length?l=s[i]:(l=new UT,s.push(l)),l.light=r,r.getBoundingBox(Vw),l.min.copy(Vw.getMin()),l.max.copy(Vw.getMax()),i++}}),s.length=i}evaluateBounds(){let t=this._usedLights,e=this.boundsMin,s=this.boundsMax;if(t.length>1){e.copy(t[1].min),s.copy(t[1].max);for(let i=2;i<t.length;i++)e.min(t[i].min),s.max(t[i].max)}else e.set(0,0,0),s.set(1,1,1);this.boundsDelta.sub2(s,e),this.lightsBuffer.setBounds(e,this.boundsDelta)}updateClusters(t){this.counts.fill(0),this.clusters.fill(0),this.lightsBuffer.areaLightsEnabled=t?t.areaLightsEnabled:!1;let e=this._cells.x,s=this._cells.z,i=this.counts,r=this._maxCellLightCount,a=this.clusters,o=this.maxCellLightCount,l=!1,h=this._usedLights;for(let f=1;f<h.length;f++){let u=h[f],d=u.light;this.lightsBuffer.addLightData(d,f),this.evalLightCellMinMax(u,NT,BT);let p=NT.x,m=BT.x,_=NT.y,S=BT.y,g=NT.z,T=BT.z;for(let C=p;C<=m;C++)for(let v=g;v<=T;v++)for(let E=_;E<=S;E++){let y=C+e*(v+E*s),P=i[y];P<r?(a[o*y+P]=f,i[y]=P+1):l=!0}}}update(t,e=null){this.updateParams(e),this.updateCells(),this.collectLights(t),this.evaluateBounds(),this.updateClusters(e),this.uploadTextures()}activate(){this.updateUniforms()}};var GL=2.399963229728653,Rc={circlePoint(c){let t=Math.sqrt(Math.random()),e=Math.random()*2*Math.PI;c.x=t*Math.cos(e),c.y=t*Math.sin(e)},circlePointDeterministic(c,t,e){let s=t*GL,i=Math.sqrt(t/e);c.x=i*Math.cos(s),c.y=i*Math.sin(s)},spherePointDeterministic(c,t,e,s=0,i=1){s=1-2*s,i=1-2*i;let r=R.lerp(s,i,t/e),a=Math.sqrt(1-r*r),o=GL*t;c.x=Math.cos(o)*a,c.y=r,c.z=Math.sin(o)*a},radicalInverse(c){let t=(c<<16|c>>>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<t;a+=4)kT(c[a+0]*.5+.5,i,r+0),kT(c[a+1]*.5+.5,i,r+4),kT(c[a+2]*.5+.5,i,r+8),kT(c[a+3]/8,i,r+12),r+=16;return{width:e,height:s,data:i}},CY=(c,t,e,s)=>{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<c;++i)CY(e,i/c,Rc.radicalInverse(i),t),s.push(e.x,e.y,e.z,0);return s},bY=(c,t)=>{let e=t/c,s=new x,i=[];for(let r=0;r<c;++r){PY(s,r/c,Rc.radicalInverse(r));let a=s.z/Math.PI,o=.5*Math.log2(e/a);i.push(s.x,s.y,s.z,o)}return i};var DY={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}},LY=(c,t)=>{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;u<f;++u){wY(a,u/f,Rc.radicalInverse(u),r);let d=a.z;if(o.set(a.x,a.y,a.z).mulScalar(2*d).sub(l),o.z>0){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<c*4;)h.push(0,0,0,0);return h},OY=(c,t,e)=>{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<l;++h)oa(t,r,{numSamples:1,rect:o,seamPixels:a}),o.x+=o.w,o.y+=o.w,o.z=Math.max(1,Math.floor(o.z*.5)),o.w=Math.max(1,Math.floor(o.w*.5));o.set(0,256*a,256*a,128*a);for(let h=1;h<7;++h)oa(t,r,{numSamples:e?.numReflectionSamples||1024,distribution:e?.distribution||"ggx",specularPower:Math.max(1,2048>>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<h;++f)oa(t[0],a,{numSamples:1,rect:l,seamPixels:o}),l.x+=l.w,l.y+=l.w,l.z=Math.max(1,Math.floor(l.z*.5)),l.w=Math.max(1,Math.floor(l.w*.5));l.set(0,256*o,256*o,128*o);for(let f=1;f<t.length;++f)oa(t[f],a,{numSamples:1,rect:l,seamPixels:o}),l.y+=l.w,l.z=Math.max(1,Math.floor(l.z*.5)),l.w=Math.max(1,Math.floor(l.w*.5));return l.set(128*o,384*o,64*o,32*o),e?.legacyAmbient?oa(t[5],a,{numSamples:1,rect:l,seamPixels:o}):oa(t[0],a,{numSamples:e?.numSamples||2048,distribution:"lambert",rect:l,seamPixels:o}),a}};var Xw={vertex_normal:Ot,vertex_tangent:vs,vertex_texCoord0:_t,vertex_texCoord1:ri,vertex_color:Ct,vertex_boneWeights:bs,vertex_boneIndices:$t},Lp=class{constructor(t,e,s=!0){n(this,"varyingsCode","");n(this,"device");n(this,"options");n(this,"shaderLanguage");n(this,"vDefines",new Map);n(this,"fDefines",new Map);n(this,"includes",new Map);n(this,"chunks",null);this.device=t,this.options=e;let i=e.shaderChunks;if(this.shaderLanguage=t.isWebGPU&&s&&(!i||i.useWGSL)?se:fe,t.isWebGPU&&this.shaderLanguage===fe&&t.hasTranspilers,this.attributes={vertex_position:ee},e.userAttributes)for(let[a,o]of Object.entries(e.userAttributes))this.attributes[o]=a;let r=ne.get(t,this.shaderLanguage);this.chunks=new Map(r),i&&(this.shaderLanguage===fe?i.glsl:i.wgsl).forEach((o,l)=>{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<l;u++)t[u]&&(r.set(`UV${u}`,!0),a[`vertex_texCoord${u}`]=`TEXCOORD${u}`),e[u]&&(r.set(`UV${u}_UNMODIFIED`,!0),o.set(`vUv${u}`,"vec2"));let h=0,f=new Set;s.forEach(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;r<i.lights.length;r++){let a=i.lights[r],o=a._type;if(e&&o!==Ce)continue;let l=t&&a._shape?a._shape:$i,h=a._shadowType,f=a.castShadows&&!i.noShadow,u=Fi.get(h);s.set(`LIGHT${r}`,!0),s.set(`LIGHT${r}TYPE`,`${lT[o]}`),s.set(`LIGHT${r}SHADOWTYPE`,`${u.name}`),s.set(`LIGHT${r}SHAPE`,`${nw[l]}`),s.set(`LIGHT${r}FALLOFF`,`${lw[a._falloffMode]}`),a.affectSpecularity&&s.set(`LIGHT${r}AFFECT_SPECULARITY`,!0),a._cookie&&(o===je&&!a._cookie._cubemap||o===We&&a._cookie._cubemap)&&(s.set(`LIGHT${r}COOKIE`,!0),s.set(`{LIGHT${r}COOKIE_CHANNEL}`,a._cookieChannel),o===je&&(a._cookieTransform&&s.set(`LIGHT${r}COOKIE_TRANSFORM`,!0),a._cookieFalloff&&s.set(`LIGHT${r}COOKIE_FALLOFF`,!0))),f&&(s.set(`LIGHT${r}CASTSHADOW`,!0),u.pcf&&s.set(`LIGHT${r}SHADOW_PCF`,!0),a._normalOffsetBias&&!a._isVsm&&s.set(`LIGHT${r}_SHADOW_SAMPLE_NORMAL_OFFSET`,!0),o===Ce&&(s.set(`LIGHT${r}_SHADOW_SAMPLE_ORTHO`,!0),a.cascadeBlend>0&&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)return s.substring(0,i[e]);if(i[e]>s.length){let r=s,a=r.charAt(r.length-1),o=i[e]-r.length;for(let l=0;l<o;l++)r+=a;return r}return s}}createVertexShader(e,s){let i=[],r=[],a=[];for(let l in Dc){let h=`${l}Map`;if(s[`${l}VertexColor`]){let f=`${l}VertexColorChannel`;s[f]=this._correctChannel(l,s[f],Dc)}if(s[h]){let f=`${h}Channel`,u=`${h}Transform`,d=`${h}Uv`;s[d]=Math.min(s[d],1),s[f]=this._correctChannel(l,s[f],Dc);let p=s[d];i[p]=!0,r[p]=r[p]||s[h]&&!s[u],s[u]&&a.push({name:l,id:s[u],uv:s[d]})}}s.forceUv1&&(i[1]=!0,r[1]=r[1]!==void 0?r[1]:!0),e.generateVertexShader(i,r,a)}prepareFragmentDefines(e,s,i){let r=(a,o,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;o<sr.length;o++){let l=sr[o];if(l.src===e&&l.dst===s&&l.op===t&&l.src===r&&l.dst===a&&l.op===i)return o}return ls}set depthState(t){this._depthState.copy(t)}get depthState(){return this._depthState}set depthTest(t){this._depthState.test=t}get depthTest(){return this._depthState.test}set depthFunc(t){this._depthState.func=t}get depthFunc(){return this._depthState.func}set depthWrite(t){this._depthState.write=t}get depthWrite(){return this._depthState.write}copy(t){this.name=t.name,this.alphaTest=t.alphaTest,this.alphaToCoverage=t.alphaToCoverage,this._blendState.copy(t._blendState),this._depthState.copy(t._depthState),this.cull=t.cull,this.frontFace=t.frontFace,this.stencilFront=t.stencilFront?.clone(),t.stencilBack&&(this.stencilBack=t.stencilFront===t.stencilBack?this.stencilFront:t.stencilBack.clone()),this.clearParameters();for(let e in t.parameters)t.parameters.hasOwnProperty(e)&&this._setParameterSimple(e,t.parameters[e].data);return this.defines.clear(),t.defines.forEach((e,s)=>this.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;i<s.length;i++)this.setParameter(s[i]);return}t=s.name,e=s.value}this._setParameterSimple(t,e)}deleteParameter(t){this.parameters[t]&&delete this.parameters[t]}setParameters(t,e){let s=this.parameters;e===void 0&&(e=s);for(let i in e){let r=s[i];r&&(r.scopeId||(r.scopeId=t.scope.resolve(i)),r.scopeId.setValue(r.data))}}setDefine(t,e){let s=!1,{defines:i}=this;e!==void 0&&e!==!1?(s=!i.has(t)||i.get(t)!==e,i.set(t,e)):(s=i.has(t),i.delete(t)),this._definesDirty||(this._definesDirty=s)}getDefine(t){return this.defines.has(t)}destroy(){this.variants.clear();for(let t of this.meshInstances)if(t.clearShaders(),t._material=null,t.mesh){let e=ra(t.mesh.device);this!==e&&(t.material=e)}this.meshInstances.clear()}addMeshInstanceRef(t){this.meshInstances.add(t)}removeMeshInstanceRef(t){this.meshInstances.delete(t)}};var Lc=class c{static update(t,e,s,i,r,a,o){c.updateSharedOptions(t,e,s,r,a),c.updateMaterialOptions(t,e),c.updateEnvOptions(t,e,s,i),c.updateLightingOptions(t,e,s,r,o)}static updateSharedOptions(t,e,s,i,r){t.shaderChunks=e.shaderChunks,t.pass=r,t.alphaTest=e.alphaTest>0,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<e.length;r++){let a=e[r];a.enabled&&a.mask&i&&s.push(a)}}};var HL=(c,t)=>{if(c.length!==t.length)return!1;for(let e=0;e<c.length;++e)if(c[e]!==t[e])return!1;return!0},YY=c=>c.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<s.length;i++)if(HL(s[i][0].value,t[0].value)&&HL(s[i][1].value,t[1].value))return i+1;return s.push(t)}};function qt(c,t=!0,e=!0){let s={};return s[`${c}Map`]="texture",s[`${c}MapTiling`]="vec2",s[`${c}MapOffset`]="vec2",s[`${c}MapRotation`]="number",s[`${c}MapUv`]="number",t&&(s[`${c}MapChannel`]="string",e&&(s[`${c}VertexColor`]="boolean",s[`${c}VertexColorChannel`]="string")),s}var Mc={name:"string",chunks:"chunks",mappingFormat:"string",_engine:"boolean",ambient:"rgb",...qt("ao"),...qt("aoDetail",!0,!1),aoDetailMode:"string",aoIntensity:"number",diffuse:"rgb",...qt("diffuse"),...qt("diffuseDetail",!0,!1),diffuseDetailMode:"string",vertexColorGamma:"boolean",specular:"rgb",specularTint:"boolean",...qt("specular"),occludeSpecular:"enum:occludeSpecular",specularityFactor:"number",specularityFactorTint:"boolean",...qt("specularityFactor"),useMetalness:"boolean",metalness:"number",enableGGXSpecular:"boolean",metalnessTint:"boolean",...qt("metalness"),useMetalnessSpecularColor:"boolean",anisotropyIntensity:"number",anisotropyRotation:"number",...qt("anisotropy"),shininess:"number",gloss:"number",glossInvert:"boolean",...qt("gloss"),clearCoat:"number",...qt("clearCoat"),clearCoatGloss:"number",clearCoatGlossInvert:"boolean",...qt("clearCoatGloss"),clearCoatBumpiness:"number",...qt("clearCoatNormal",!1),useSheen:"boolean",sheen:"rgb",...qt("sheen"),sheenGloss:"number",sheenGlossInvert:"boolean",...qt("sheenGloss"),fresnelModel:"number",emissive:"rgb",...qt("emissive"),emissiveIntensity:"number",...qt("normal",!1),bumpiness:"number",...qt("normalDetail",!1),normalDetailMapBumpiness:"number",...qt("height",!0,!1),heightMapFactor:"number",alphaToCoverage:"boolean",alphaTest:"number",alphaFade:"number",alphaDither:"number",opacity:"number",...qt("opacity"),opacityFadesSpecular:"boolean",opacityDither:"string",opacityShadowDither:"string",reflectivity:"number",refraction:"number",refractionTint:"boolean",...qt("refraction"),refractionIndex:"number",dispersion:"number",thickness:"number",thicknessTint:"boolean",...qt("thickness"),attenuation:"rgb",attenuationDistance:"number",useDynamicRefraction:"boolean",sphereMap:"texture",cubeMap:"cubemap",cubeMapProjection:"number",cubeMapProjectionBox:"boundingbox",useIridescence:"boolean",iridescence:"number",iridescenceTint:"boolean",...qt("iridescence"),iridescenceThicknessTint:"boolean",iridescenceThicknessMin:"number",iridescenceThicknessMax:"number",iridescenceRefractionIndex:"number",...qt("iridescenceThickness"),...qt("light"),depthTest:"boolean",depthFunc:"enum:depthFunc",depthWrite:"boolean",depthBias:"number",slopeDepthBias:"number",cull:"enum:cull",blendType:"enum:blendType",useFog:"boolean",useLighting:"boolean",useSkybox:"boolean",useTonemap:"boolean",envAtlas:"texture",twoSidedLighting:"boolean",shadowCatcher:"boolean"},qf=[];for(let c in Mc)Mc[c]==="texture"&&qf.push(c);var hS=[];for(let c in Mc)Mc[c]==="cubemap"&&hS.push(c);var WL={aoMapVertexColor:"boolean",diffuseMapTint:"boolean",diffuseMapVertexColor:"boolean",emissiveMapTint:"boolean",emissiveMapVertexColor:"boolean",glossMapVertexColor:"boolean",metalnessMapVertexColor:"boolean",opacityMapVertexColor:"boolean",specularAntialias:"boolean",specularMapTint:"boolean",specularMapVertexColor:"boolean",ambientTint:"boolean",emissiveTint:"boolean",diffuseTint:"boolean",sheenTint:"boolean",conserveEnergy:"boolean",useGamma:"boolean",useGammaTonemap:"boolean",sheenGlossTint:"boolean",anisotropy:"boolean"};var WT={},XL={},fS=new Set,HT=new F,it=class extends Us{constructor(){super();n(this,"userAttributes",new Map);n(this,"onUpdateShader");this._assetReferences={},this._activeParams=new Set,this._activeLightingParams=new Set,this.shaderOptBuilder=new VT,this.reset()}reset(){Object.keys(WT).forEach(e=>{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<e.length;o++){let l=e[o];if(l._type===Ce)for(let h=0;h<6;h++){let f=Math.max(QY[h].dot(l._direction),0)*l._intensity,u=l._color;s[h*3]+=u.r*f,s[h*3+1]+=u.g*f,s[h*3+2]+=u.b*f}}}};var JY=(c,t,e,s)=>{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;e<t.length;e++)t[e].destroy();this.renderTargets.length=0}static create(t,e){let s=null;return e._type===We?s=this.createCubemap(t,e._shadowResolution,e._shadowType):s=this.create2dMap(t,e._shadowResolution,e._shadowType),s}static createAtlas(t,e,s){let i=this.create2dMap(t,e,s),r=i.renderTargets,a=r[0];for(let o=0;o<5;o++)r.push(a);return i}static create2dMap(t,e,s){let i=Fi.get(s),r=i.format;r===Mt&&!t.textureFloatRenderable&&t.textureHalfFloatRenderable&&(r=yn);let a=xs.get(r)?.name,o=1;s===fp&&(o=t.extTextureFloatLinear?1:0),s===xc&&(o=0);let l=new Z(t,{format:r,width:e,height:e,mipmaps:!1,minFilter:o,magFilter:o,addressU:1,addressV:1,name:`ShadowMap2D_${a}`}),h=null;return i?.pcf?(l.compareOnRead=!0,l.compareFunc=1,h=new me({depthBuffer:l})):h=new me({colorBuffer:l,depth:!0}),t.isWebGPU&&(h.flipY=!0),new c(l,[h])}static createCubemap(t,e,s){let i=Fi.get(s),r=xs.get(i.format)?.name,a=s===xc,o=a?0:1,l=new Z(t,{format:i?.format,width:e,height:e,cubemap:!0,mipmaps:!1,minFilter:o,magFilter:o,addressU:1,addressV:1,name:`ShadowMapCube_${r}`});a||(l.compareOnRead=!0,l.compareFunc=1);let h=[];for(let f=0;f<6;f++)a?h.push(new me({colorBuffer:l,face:f,depth:!0})):h.push(new me({depthBuffer:l,face:f}));return new c(l,h)}};var t6=[],s6=[],rl=new Q,qw=new Q,dS=class{constructor(t){this.size=Math.floor(t.w*1024),this.used=!1,this.lightId=-1,this.rect=t}},KT=class{constructor(t){this.device=t,this.version=1,this.shadowAtlasResolution=2048,this.shadowAtlas=null,this.shadowEdgePixels=3,this.cookieAtlasResolution=4,this.cookieAtlas=Z.createDataTexture2D(this.device,"CookieAtlas",this.cookieAtlasResolution,this.cookieAtlasResolution,st),this.cookieRenderTarget=new me({colorBuffer:this.cookieAtlas,depth:!1,flipY:!0}),this.slots=[],this.atlasSplit=[],this.cubeSlotsOffsets=[new B(0,0),new B(0,1),new B(1,0),new B(1,1),new B(2,0),new B(2,1)],this.scissorVec=new Q,this.allocateShadowAtlas(1),this.allocateCookieAtlas(1),this.allocateUniforms()}destroy(){this.destroyShadowAtlas(),this.destroyCookieAtlas()}destroyShadowAtlas(){this.shadowAtlas?.destroy(),this.shadowAtlas=null}destroyCookieAtlas(){this.cookieAtlas?.destroy(),this.cookieAtlas=null,this.cookieRenderTarget?.destroy(),this.cookieRenderTarget=null}allocateShadowAtlas(t,e=Oi){let s=this.shadowAtlas?.texture.format,i=Fi.get(e).format;if(!this.shadowAtlas||this.shadowAtlas.texture.width!==t||s!==i){this.version++,this.destroyShadowAtlas(),this.shadowAtlas=Xo.createAtlas(this.device,t,e),this.shadowAtlas.cached=!0;let r=4/this.shadowAtlasResolution;this.scissorVec.set(r,r,-2*r,-2*r)}}allocateCookieAtlas(t){this.cookieAtlas.width!==t&&(this.cookieRenderTarget.resize(t,t),this.version++)}allocateUniforms(){this._shadowAtlasTextureId=this.device.scope.resolve("shadowAtlasTexture"),this._shadowAtlasParamsId=this.device.scope.resolve("shadowAtlasParams"),this._shadowAtlasParams=new Float32Array(2),this._cookieAtlasTextureId=this.device.scope.resolve("cookieAtlasTexture")}updateUniforms(){let e=this.shadowAtlas.renderTargets[0].depthBuffer;this._shadowAtlasTextureId.setValue(e),this._shadowAtlasParams[0]=this.shadowAtlasResolution,this._shadowAtlasParams[1]=this.shadowEdgePixels,this._shadowAtlasParamsId.setValue(this._shadowAtlasParams),this._cookieAtlasTextureId.setValue(this.cookieAtlas)}subdivide(t,e){let s=e.atlasSplit;if(!s){let r=Math.ceil(Math.sqrt(t));s=s6,s[0]=r,s.length=1}if(!((r,a)=>r.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;o<r;o++)for(let l=0;l<r;l++){let h=new Q(o*a,l*a,a,a),f=this.atlasSplit[1+o*r+l];if(f>1)for(let u=0;u<f;u++)for(let d=0;d<f;d++){let p=a/f,m=new Q(h.x+u*p,h.y+d*p,p,p);this.slots.push(new dS(m))}else this.slots.push(new dS(h))}}else this.slots.push(new dS(new Q(0,0,1,1)));this.slots.sort((a,o)=>o.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;f<h.length;f++){let u=h[f];if(u.visibleThisFrame){let d=i&&u.castShadows,p=s&&!!u.cookie;r||(r=d),a||(a=p),(d||p)&&o.push(u)}}})(t),o.sort((h,f)=>f.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;i<s;i++)if(t.castShadows||t._cookie){if(rl.copy(e),qw.copy(e),t._type===je&&rl.add(this.scissorVec),t._type===We){let r=rl.z/3,a=this.cubeSlotsOffsets[i];rl.x+=r*a.x,rl.y+=r*a.y,rl.z=r,rl.w=r,qw.copy(rl)}if(t.castShadows){let r=t.getRenderData(null,i);r.shadowViewport.copy(rl),r.shadowScissor.copy(qw)}}}assignSlot(t,e,s){t.atlasViewportAllocated=!0;let i=this.slots[e];i.lightId=t.id,i.used=!0,s&&(t.atlasSlotUpdated=!0,t.atlasVersion=this.version,t.atlasSlotIndex=e)}update(t,e){this.shadowAtlasResolution=e.shadowAtlasResolution,this.cookieAtlasResolution=e.cookieAtlasResolution;let s=this.collectLights(t,e);if(s.length>0){let i=this.slots;for(let o=0;o<i.length;o++)i[o].used=!1;let r=Math.min(s.length,i.length);for(let o=0;o<r;o++){let l=s[o];l.castShadows&&(l._shadowMap=this.shadowAtlas);let h=i[l.atlasSlotIndex];if(l.atlasVersion===this.version&&l.id===h?.lightId){let f=i[l.atlasSlotIndex];f.size===i[o].size&&!f.used&&this.assignSlot(l,l.atlasSlotIndex,!1)}}let a=0;for(let o=0;o<r;o++){for(;a<i.length&&i[a].used;)a++;let l=s[o];l.atlasViewportAllocated||this.assignSlot(l,a,!0);let h=i[l.atlasSlotIndex];this.setupSlot(l,h.rect)}}this.updateUniforms()}};var jT=class{constructor(){this.cache=new Map}destroy(){this.clear(),this.cache=null}clear(){this.cache.forEach(t=>{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;o<a;o++){let l=t.getRenderData(null,o),h=l.shadowCamera;h.nearClip=t.attenuationEnd/1e3,h.farClip=t.attenuationEnd;let f=h._node,u=t._node;if(f.setPosition(u.getPosition()),r===je)h.fov=t._outerConeAngle*2,f.setRotation(u.getRotation()),f.rotateLocal(-90,0,0);else if(r===We)if(i){let m=2/(this.shadowRenderer.lightTextureAtlas.shadowAtlasResolution*t.atlasViewport.z/3)*this.shadowRenderer.lightTextureAtlas.shadowEdgePixels;h.fov=Math.atan(1+m)*R.RAD_TO_DEG*2}else h.fov=90;this.renderer.updateCameraFrustum(h),this.shadowRenderer.cullShadowCasters(e,t,l.visibleCasters,h,s)}}prepareLights(t,e){let s;for(let i=0;i<e.length;i++){let r=e[i];if(this.shadowRenderer.needsShadowRendering(r)&&r.atlasViewportAllocated){t.push(r);for(let a=0;a<r.numShadowFaces;a++)s=this.shadowRenderer.prepareFace(r,null,a)}}return s}buildNonClusteredRenderPasses(t,e){for(let s=0;s<e.length;s++){let i=e[s];if(this.shadowRenderer.needsShadowRendering(i)){let r=i._type===je,a=i.numShadowFaces;for(let o=0;o<a;o++){let l=new Fp(this.device,this.shadowRenderer,i,o,r);t.addRenderPass(l)}}}}};var $T=class extends yt{constructor(t,e,s,i,r){super(t),this.shadowRenderer=e,this.light=s,this.camera=i,this.allCascadesRendering=r}execute(){let{light:t,camera:e,shadowRenderer:s,allCascadesRendering:i}=this,r=t.numShadowFaces,a=t.shadowUpdateOverrides;for(let o=0;o<r;o++)a?.[o]!==$s&&s.renderFace(t,e,o,!i),a?.[o]===Qi&&(a[o]=$s)}after(){this.shadowRenderer.renderVsm(this.light,this.camera)}};var ZT=new ge,al=new x,qL=new W,bt=[new x,new x,new x,new x,new x,new x,new x,new x],$w={min:0,max:0};function i6(c,t,e){bt[0].x=bt[1].x=bt[2].x=bt[3].x=t.x,bt[1].y=bt[3].y=bt[7].y=bt[5].y=t.y,bt[2].z=bt[3].z=bt[6].z=bt[7].z=t.z,bt[4].x=bt[5].x=bt[6].x=bt[7].x=e.x,bt[0].y=bt[2].y=bt[4].y=bt[6].y=e.y,bt[0].z=bt[1].z=bt[4].z=bt[5].z=e.z;let s=9999999999,i=-9999999999;for(let r=0;r<8;++r){c.transformPoint(bt[r],bt[r]);let a=bt[r].z;a<s&&(s=a),a>i&&(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;o<t.numCascades&&a?.[o]!==$s;o++){let l=t.getRenderData(s,o),h=l.shadowCamera;h.renderTarget=t._shadowMap.renderTargets[0],l.shadowViewport.copy(t.cascades[o]),l.shadowScissor.copy(t.cascades[o]);let f=h._node,u=t._node;f.setPosition(u.getPosition()),f.setRotation(u.getRotation()),f.rotateLocal(-90,0,0);let d=o===0?r:t._shadowCascadeDistances[o-1],p=t._shadowCascadeDistances[o],m=s.getFrustumCorners(d,p);al.set(0,0,0);let _=s.node.getWorldTransform();for(let U=0;U<8;U++)_.transformPoint(m[U],m[U]),al.add(m[U]);al.mulScalar(1/8);let S=0;for(let U=0;U<8;U++){let L=m[U].sub(al).length();L>S&&(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<<o,O=l.visibleCasters,G=O.length,M=0;for(let U=0;U<G;U++){let L=O[U];L.shadowCascadeMask&D&&(O[M++]=L,M===1?ZT.copy(L.aabb):ZT.add(L.aabb))}G!==M&&(O.length=M),qL.copy(f.getWorldTransform()).invert();let H=i6(qL,ZT.getMin(),ZT.getMax());f.translateLocal(0,0,H.max+.1),h.farClip=H.max-H.min+.2,l.projectionCompensation=S}}generateSplitDistances(t,e,s){t._shadowCascadeDistances.fill(s);for(let i=1;i<t.numCascades;i++){let r=i/t.numCascades,a=e+(s-e)*r,o=e*(s/e)**r,l=R.lerp(a,o,t.cascadeDistribution);t._shadowCascadeDistances[i-1]=l}}getLightRenderPass(t,e){let s=null;if(this.shadowRenderer.needsShadowRendering(t)){let i=t.numShadowFaces,r=t.shadowUpdateOverrides,a=!0,o;for(let l=0;l<i;l++)r?.[l]===$s&&(a=!1),o=this.shadowRenderer.prepareFace(t,e,l);s=new $T(this.device,this.shadowRenderer,t,e,a),this.shadowRenderer.setupRenderPass(s,o,a)}return s}};var Zw=new Set,$L=new W,ZL=new W,$f=new Float32Array(2),pS=new Q(1,1,0,0),QL=new W;function r6(c,t){return Math.exp(-(c*c)/(2*t*t))}function a6(c){let t=(c-1)/6,e=(c-1)*.5,s=new Array(c),i=0;for(let r=0;r<c;++r)s[r]=r6(r-e,t),i+=s[r];for(let r=0;r<c;++r)s[r]/=i;return s}var Np=class{constructor(t,e){n(this,"shadowPassCache",[]);this.device=t.device,this.renderer=t,this.lightTextureAtlas=e;let s=this.device.scope;this.sourceId=s.resolve("source"),this.pixelOffsetId=s.resolve("pixelOffset"),this.weightId=s.resolve("weight[0]"),this.blurVsmShader=[{},{}],this.blurVsmWeights={},this.shadowMapLightRadiusId=s.resolve("light_radius"),this.viewUniformFormat=null,this.viewBindGroupFormat=null,this.blendStateWrite=new Oe,this.blendStateNoWrite=new Oe,this.blendStateNoWrite.setColorWrite(!1,!1,!1,!1)}static createShadowCamera(t,e,s,i){let r=Wo.create(t,Gf,s,i),a=Fi.get(e),o=a?.vsm??!1,l=a?.pcf??!1;return o?r.clearColor=new F(0,0,0,0):r.clearColor=new F(1,1,1,1),r.clearDepthBuffer=!0,r.clearStencilBuffer=!1,r.clearColorBuffer=!l,r}_cullShadowCastersInternal(t,e,s){let i=t.length;for(let r=0;r<i;r++){let a=t[r];a.castShadow&&(!a.cull||a._isVisible(s))&&(a.visibleThisFrame=!0,e.push(a))}}cullShadowCasters(t,e,s,i,r){if(this.renderer.scene?.fire(tS,i),s.length=0,r)this._cullShadowCastersInternal(r,s,i);else{let a=t.layerList,o=a.length;for(let l=0;l<o;l++){let h=a[l];h._lightsSet.has(e)&&(Zw.has(h)||(Zw.add(h),this._cullShadowCastersInternal(h.shadowCasters,s,i)))}Zw.clear()}s.sort(this.sortCompareShader),this.renderer.scene?.fire(sS,i)}sortCompareShader(t,e){let s=t._sortKeyShadow,i=e._sortKeyShadow;return s===i?e.mesh.id-t.mesh.id:i-s}setupRenderState(t,e){let i=this.renderer.scene.clusteredLightingEnabled?e._isPcf:e._isPcf&&e._type!==We;t.setBlendState(i?this.blendStateNoWrite:this.blendStateWrite),t.setDepthState(e.shadowDepthState),t.setStencilState(null,null)}dispatchUniforms(t,e,s,i){let r=e._node;t._type!==Ce&&(this.renderer.dispatchViewPos(r.getPosition()),this.shadowMapLightRadiusId.setValue(t.attenuationEnd)),$L.setTRS(r.getPosition(),r.getRotation(),x.ONE).invert(),ZL.mul2(e.projectionMatrix,$L);let a=s.shadowViewport;e.rect=a,e.scissorRect=s.shadowScissor,QL.setViewport(a.x,a.y,a.z,a.w),s.shadowMatrix.mul2(QL,ZL),t._type===Ce&&t._shadowMatrixPalette.set(s.shadowMatrix.data,i*16)}getShadowPass(t){let e=t._type,s=t._shadowType,i=this.shadowPassCache[e]?.[s];if(!i){let r=`ShadowPass_${e}_${s}`;i=Ns.get(this.device).allocate(r,{isShadow:!0,lightType:e,shadowType:s}),this.shadowPassCache[e]||(this.shadowPassCache[e]=[]),this.shadowPassCache[e][s]=i}return i.index}submitCasters(t,e,s){let i=this.device,r=this.renderer,a=r.scene,o=1<<kf,l=this.getShadowPass(e),h=s.shaderParams,f=s.renderTarget.flipY?-1:1,u=t.length;for(let d=0;d<u;d++){let p=t[d],m=p.mesh,_=p.instancingData;if(_&&_.count<=0)continue;p.ensureMaterial(i);let S=p.material;r.setBaseConstants(i,S),r.setSkinning(i,p),S.dirty&&(S.updateUniforms(i,a),S.dirty=!1),r.setupCullModeAndFrontFace(!0,f,p),S.setParameters(i),p.setParameters(i,o);let g=p.getShaderInstance(l,0,a,h,this.viewUniformFormat,this.viewBindGroupFormat),T=g.shader;if(T.failed)continue;p._sortKeyShadow=T.id,i.setShader(T),r.setVertexBuffers(i,m),r.setMorphing(i,p.morphInstance),_&&i.setVertexBuffer(_.vertexBuffer),r.setMeshInstanceMatrices(p),r.setupMeshUniformBuffers(g);let C=p.renderStyle,v=p.getDrawCommands(s);i.draw(m.primitive[C],m.indexBuffer[C],_?.count,v),r._shadowDrawCalls++,_&&r._instancedDrawCalls++}}needsShadowRendering(t){let e=t.enabled&&t.castShadows&&t.shadowUpdateMode!==$s&&t.visibleThisFrame;return t.shadowUpdateMode===Qi&&(t.shadowUpdateMode=$s),e&&(this.renderer._shadowMapUpdates+=t.numShadowFaces),e}getLightRenderData(t,e,s){return t.getRenderData(t._type===Ce?e:null,s)}setupRenderPass(t,e,s){let i=e.renderTarget;t.init(i),t.depthStencilOps.clearDepthValue=1,t.depthStencilOps.clearDepth=s,i.depthBuffer?t.depthStencilOps.storeDepth=!0:(t.colorOps.clearValue.copy(e.clearColor),t.colorOps.clear=s,t.depthStencilOps.storeDepth=!1),t.requiresCubemaps=!1}prepareFace(t,e,s){let i=t._type,a=this.getLightRenderData(t,e,s).shadowCamera,o=i===Ce?0:s;return a.renderTarget=t._shadowMap.renderTargets[o],a}renderFace(t,e,s,i){let r=this.device,a=this.getLightRenderData(t,e,s),o=a.shadowCamera;this.dispatchUniforms(t,o,a,s);let l=o.renderTarget,h=this.renderer;h.setCameraUniforms(o,l),r.supportsUniformBuffers&&h.setupViewUniformBuffers(a.viewBindGroups,this.viewUniformFormat,this.viewBindGroupFormat,null),h.setupViewport(o,l),i&&h.clear(o),this.setupRenderState(r,t),this.submitCasters(a.visibleCasters,t,o)}renderVsm(t,e){t._isVsm&&t._vsmBlurSize>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<a;u++)r[u].render();return}let o=e.backBuffer?.impl,l=e.xrColorTexture,h=o?.assignedColorTexture??null,f=o?.colorAttachments?.[0]?.format??null;for(let u=0;u<i;u++){let d=s[u];e.xrCurrentViewIndex=u,e.xrColorTexture=d.colorTexture,e.xrColorTextureViewDescriptor=d.viewDescriptor,o?.assignColorTexture?.(d.colorTexture,d.viewFormat);for(let p=0;p<a;p++)r[p].render()}e.xrCurrentViewIndex=-1,e.xrColorTextureViewDescriptor=null,e.xrColorTexture=l??null,o&&h&&f&&o.assignedColorTexture!==h&&o.assignColorTexture(h,f)}};var JT=[],ey=class{constructor(t){n(this,"_empty",null);n(this,"_allocated",[]);n(this,"_clusters",new Map);this.device=t}destroy(){this._empty&&(this._empty.destroy(),this._empty=null),this._allocated.forEach(t=>{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;i<s;i++){let r=e[i];r.lightClusters=null;let a=r.layer;if(a.hasClusteredLights&&a.meshInstances.length){let o=a.getLightIdHash(),h=this._clusters.get(o)?.lightClusters;h||(h=JT.pop()??new sl(this.device),this._allocated.push(h),this._clusters.set(o,r)),r.lightClusters=h}r.lightClusters||(r.lightClusters=this.empty)}}assign(t){JT.push(...this._allocated),this._allocated.length=0,this._clusters.clear();let e=t.length;for(let s=0;s<e;s++){let i=t[s];if(i instanceof Zf){let r=i.children;for(let a=0;a<r.length;a++)this._assignClustersForPass(r[a])}else this._assignClustersForPass(i)}JT.forEach(s=>s.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;i<e.length;i++){let r=e[i];r._type!==Ce&&r.atlasViewportAllocated&&(!r.atlasSlotUpdated&&!this._forceCopy||r.enabled&&r.cookie&&r.visibleThisFrame&&s.push(r))}this._forceCopy=!1}initInvViewProjMatrices(){if(!Qw.length)for(let e=0;e<6;e++){let s=Wo.create(this.device,null,We,e),i=s.projectionMatrix,r=s.node.getLocalTransform().clone().invert();Qw[e]=new W().mul2(i,r).invert()}}get quadRenderer2D(){if(!this._quadRenderer2D){let e=Se.createShader(this.device,{uniqueName:"cookieRenderer2d",attributes:{vertex_position:ee},vertexChunk:"cookieBlitVS",fragmentChunk:"cookieBlit2DPS"});this._quadRenderer2D=new hs(e)}return this._quadRenderer2D}get quadRendererCube(){if(!this._quadRendererCube){let e=Se.createShader(this.device,{uniqueName:"cookieRendererCube",attributes:{vertex_position:ee},vertexChunk:"cookieBlitVS",fragmentChunk:"cookieBlitCubePS"});this._quadRendererCube=new hs(e)}return this._quadRendererCube}execute(){this.device.setDrawStates();let s=this.renderTarget.colorBuffer.width,i=this._cubeSlotsOffsets,r=this._filteredLights;for(let a=0;a<r.length;a++){let o=r[a],l=o.numShadowFaces,h=l>1?this.quadRendererCube:this.quadRenderer2D;l>1&&this.initInvViewProjMatrices(),this.blitTextureId.setValue(o.cookie);for(let f=0;f<l;f++){if(Oc.copy(o.atlasViewport),l>1){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;s<e;s++){let i=t[s];for(let r=0;r<i.numShadowFaces;r++)this.shadowRenderer.renderFace(i,null,r,!0)}t.length=0}};var sy=class extends Nt{constructor(t,e,s,i,r){super(t),this.renderer=e,this.frameGraph=null,this.cookiesRenderPass=ty.create(r.cookieRenderTarget,r.cubeSlotsOffsets),this.beforePasses.push(this.cookiesRenderPass),this.shadowRenderPass=new Bp(t,s,i),this.beforePasses.push(this.shadowRenderPass)}update(t,e,s,i,r){this.frameGraph=t,this.cookiesRenderPass.enabled=s,s&&this.cookiesRenderPass.update(i),this.shadowRenderPass.enabled=e,e&&this.shadowRenderPass.update(r)}destroy(){this.cookiesRenderPass.destroy(),this.cookiesRenderPass=null}execute(){let{renderer:t}=this,{scene:e}=t;t.worldClustersAllocator.update(this.frameGraph.renderPasses,e.lighting)}};var Jw=0,Yo=new W,Fc=new W,Up=new W,JL=new Ws,eI=new Br,eM=new So,tI=new Set,sI=new Set,iI=new hc,mS=[0,0,0,1],iy={color:mS,depth:1,stencil:0,flags:0},tM=[new B(.5,.333333),new B(.25,.666667),new B(.75,.111111),new B(.125,.444444),new B(.625,.777778),new B(.375,.222222),new B(.875,.555556),new B(.0625,.888889),new B(.5625,.037037),new B(.3125,.37037),new B(.8125,.703704),new B(.1875,.148148),new B(.6875,.481481),new B(.4375,.814815),new B(.9375,.259259),new B(.03125,.592593)],o6=new W,n6=new W,l6=new W,c6=new W,kp=new Set,rI=[],aI=[],ry=class{constructor(t,e){n(this,"clustersDebugRendered",!1);n(this,"scene");n(this,"processingMeshInstances",new Set);n(this,"worldClustersAllocator");n(this,"lights",[]);n(this,"localLights",[]);n(this,"cameraDirShadowLights",new Map);n(this,"dirLightShadows",new Map);n(this,"blueNoise",new Op(123));n(this,"gsplatDirector",null);this.device=t,this.scene=e,this.worldClustersAllocator=new ey(t),this.lightTextureAtlas=new KT(t),this.shadowMapCache=new jT,this.shadowRenderer=new Np(this,this.lightTextureAtlas),this._shadowRendererLocal=new qT(this,this.shadowRenderer),this._shadowRendererDirectional=new QT(this,this.shadowRenderer),this.scene.clusteredLightingEnabled&&(this._renderPassUpdateClustered=new sy(this.device,this,this.shadowRenderer,this._shadowRendererLocal,this.lightTextureAtlas)),this.viewUniformFormat=null,this.viewBindGroupFormat=null,this._skinTime=0,this._morphTime=0,this._cullTime=0,this._shadowMapTime=0,this._lightClustersTime=0,this._layerCompositionUpdateTime=0,this._shadowDrawCalls=0,this._skinDrawCalls=0,this._instancedDrawCalls=0,this._shadowMapUpdates=0,this._numDrawCallsCulled=0,this._camerasRendered=0,this._lightClusters=0,this._gsplatCount=0;let s=t.scope;this.boneTextureId=s.resolve("texture_poseMap"),this.modelMatrixId=s.resolve("matrix_model"),this.normalMatrixId=s.resolve("matrix_normal"),this.viewInvId=s.resolve("matrix_viewInverse"),this.viewPos=new Float32Array(3),this.viewPosId=s.resolve("view_position"),this.projId=s.resolve("matrix_projection"),this.projSkyboxId=s.resolve("matrix_projectionSkybox"),this.viewId=s.resolve("matrix_view"),this.viewId3=s.resolve("matrix_view3"),this.viewProjId=s.resolve("matrix_viewProjection"),this.flipYId=s.resolve("projectionFlipY"),this.tbnBasis=s.resolve("tbnBasis"),this.cameraParams=new Float32Array(4),this.cameraParamsId=s.resolve("camera_params"),this.viewportSize=new Float32Array(4),this.viewportSizeId=s.resolve("viewport_size"),this.viewIndexId=s.resolve("view_index"),this.viewIndexId.setValue(0),this.blueNoiseJitterVersion=0,this.blueNoiseJitterVec=new Q,this.blueNoiseJitterData=new Float32Array(4),this.blueNoiseJitterId=s.resolve("blueNoiseJitter"),this.blueNoiseTextureId=s.resolve("blueNoiseTex32"),this.alphaTestId=s.resolve("alpha_ref"),this.opacityMapId=s.resolve("texture_opacityMap"),this.exposureId=s.resolve("exposure"),this.morphPositionTex=s.resolve("morphPositionTex"),this.morphNormalTex=s.resolve("morphNormalTex"),this.morphTexParams=s.resolve("morph_tex_params"),this.lightCube=new YT,this.constantLightCube=s.resolve("lightCube[0]")}destroy(){this.shadowRenderer=null,this._shadowRendererLocal=null,this._shadowRendererDirectional=null,this.shadowMapCache.destroy(),this.shadowMapCache=null,this._renderPassUpdateClustered?.destroy(),this._renderPassUpdateClustered=null,this.lightTextureAtlas.destroy(),this.lightTextureAtlas=null,this.gsplatDirector?.destroy(),this.gsplatDirector=null}setupViewport(t,e){let s=this.device,i=e?e.width:s.width,r=e?e.height:s.height,a=t.rect,o=Math.floor(a.x*i),l=Math.floor(a.y*r),h=Math.floor(a.z*i),f=Math.floor(a.w*r);if(s.setViewport(o,l,h,f),t._scissorRectClear){let u=t.scissorRect;o=Math.floor(u.x*i),l=Math.floor(u.y*r),h=Math.floor(u.z*i),f=Math.floor(u.w*r)}s.setScissor(o,l,h,f)}setCameraUniforms(t,e){let s=e?.flipY,i=null;if(t.xr&&t.xr.session){let l=t._node?.parent?.getWorldTransform()||null;i=t.xr.views.list;for(let f=0;f<i.length;f++)i[f].updateTransforms(l)}else{let l=t.projectionMatrix;t.calculateProjection&&t.calculateProjection(l,xp);let h=t.getProjectionMatrixSkybox(),f=this.device.isWebGPU;l=Bs.applyShaderProjectionTransform(l,o6,s,f),h=Bs.applyShaderProjectionTransform(h,n6,s,f);let{jitter:u}=t,d=0,p=0;if(u>0){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;i<s.length;i++)Yo.mul2(s[i].projMat,s[i].viewOffMat),eM.setFromMat4(Yo),t.frustum.add(eM);return}let e=t.projectionMatrix;if(t.calculateProjection&&t.calculateProjection(e,xp),t.calculateTransform)t.calculateTransform(Fc,xp);else{let s=t._node.getPosition(),i=t._node.getRotation();Fc.setTRS(s,i,x.ONE),this.viewInvId.setValue(Fc.data)}Up.copy(Fc).invert(),Yo.mul2(e,Up),t.frustum.setFromMat4(Yo)}setBaseConstants(t,e){t.setCullMode(e.cull),t.setFrontFace(e.frontFace),e.opacityMap&&this.opacityMapId.setValue(e.opacityMap),(e.opacityMap||e.alphaTest>0)&&this.alphaTestId.setValue(e.alphaTest)}updateCpuSkinMatrices(t){Jw++;let e=t.length;if(e!==0)for(let s=0;s<e;s++){let i=t[s].skinInstance;i&&(i.updateMatrices(t[s].node,Jw),i._dirty=!0)}}updateGpuSkinMatrices(t){for(let e of t){let s=e.skinInstance;s&&s._dirty&&(s.updateMatrixPalette(e.node,Jw),s._dirty=!1)}}updateMorphing(t){for(let e of t){let s=e.morphInstance;s&&s._dirty&&s.update()}}updateGSplats(t){for(let e of t)e.gsplatInstance?.update()}gpuUpdate(t){this.updateGpuSkinMatrices(t),this.updateMorphing(t),this.updateGSplats(t)}setVertexBuffers(t,e){t.setVertexBuffer(e.vertexBuffer)}setMorphing(t,e){e&&(e.prepareRendering(t),t.setVertexBuffer(e.morph.vertexBufferIds),this.morphPositionTex.setValue(e.texturePositions),this.morphNormalTex.setValue(e.textureNormals),this.morphTexParams.setValue(e._textureParams))}setSkinning(t,e){let s=e.skinInstance;if(s){this._skinDrawCalls++;let i=s.boneTexture;this.boneTextureId.setValue(i)}}dispatchViewPos(t){let e=this.viewPos;e[0]=t.x,e[1]=t.y,e[2]=t.z,this.viewPosId.setValue(e)}initViewBindGroupFormat(t){if(this.device.supportsUniformBuffers&&!this.viewUniformFormat){let e=[new Y("matrix_view",as),new Y("matrix_viewInverse",as),new Y("matrix_projection",as),new Y("matrix_projectionSkybox",as),new Y("matrix_viewProjection",as),new Y("matrix_view3",La),new Y("cubeMapRotationMatrix",La),new Y("view_position",Kt),new Y("viewport_size",oi),new Y("skyboxIntensity",Te),new Y("exposure",Te),new Y("textureBias",Te),new Y("view_index",Te)];t&&e.push(new Y("clusterCellsCountByBoundsSize",Kt),new Y("clusterBoundsMin",Kt),new Y("clusterBoundsDelta",Kt),new Y("clusterCellsDot",Di),new Y("clusterCellsMax",Di),new Y("shadowAtlasParams",pr),new Y("clusterMaxCells",bi),new Y("numClusteredLights",bi),new Y("clusterTextureWidth",bi)),this.viewUniformFormat=new Xe(this.device,e);let s=[new Qe(Hn,Xi|Yi)];this.viewBindGroupFormat=new Ue(this.device,s)}}setupViewUniforms(t,e){this.projId.setValue(t.projMat.data),this.projSkyboxId.setValue(t.projMat.data),this.viewId.setValue(t.viewOffMat.data),this.viewInvId.setValue(t.viewInvOffMat.data),this.viewId3.setValue(t.viewMat3.data),this.viewProjId.setValue(t.projViewOffMat.data),this.viewPosId.setValue(t.positionData),this.viewIndexId.setValue(e)}setupViewUniformBuffers(t,e,s,i){let{device:r}=this,a=i?.length??1;for(;t.length<a;){let o=new Qr(r,e,!1),l=new ji(r,s,o);t.push(l)}if(i)for(let o=0;o<a;o++){let l=i[o];this.setupViewUniforms(l,o);let h=t[o];h.defaultUniformBuffer.update(),h.update()}else{let o=t[0];o.defaultUniformBuffer.update(),o.update()}i||r.setBindGroup(Io,t[0])}setupMeshUniformBuffers(t){let e=this.device;if(e.supportsUniformBuffers){let s=t.getBindGroup(e);s.update(),e.setBindGroup(Ua,s),t.getUniformBuffer(e).update(iI),e.setBindGroup($r,iI.bindGroup,iI.offsets)}}setMeshInstanceMatrices(t,e=!1){let s=t.node.worldTransform;this.modelMatrixId.setValue(s.data),e&&this.normalMatrixId.setValue(t.node.normalMatrix.data)}cull(t,e,s){let i=s.opaque;i.length=0;let r=s.transparent;r.length=0;let a=t.frustumCulling,o=e.length;for(let l=0;l<o;l++){let h=e[l];h.visible&&(!a||!h.cull||h._isVisible(t))&&(h.visibleThisFrame=!0,(h.transparent?r:i).push(h),(h.skinInstance||h.morphInstance||h.gsplatInstance)&&(this.processingMeshInstances.add(h),h.gsplatInstance&&h.gsplatInstance.cameras.push(t)))}}collectLights(t){this.lights.length=0,this.localLights.length=0;let e=this.scene._stats,s=t.layerList.length;for(let i=0;i<s;i++){let r=t.layerList[i];if(!sI.has(r)){sI.add(r);let a=r._lights;for(let o=0;o<a.length;o++){let l=a[o];tI.has(l)||(tI.add(l),this.lights.push(l),l._type!==Ce&&this.localLights.push(l))}}}e.lights=this.lights.length,tI.clear(),sI.clear()}cullLights(t,e){let s=this.scene.clusteredLightingEnabled,i=this.scene.physicalUnits;for(let r=0;r<e.length;r++){let a=e[r];if(a.enabled)if(a._type!==Ce)if(a.getBoundingSphere(eI),t.frustum.containsSphere(eI)){a.visibleThisFrame=!0,a.usePhysicalUnits=i;let o=t.getScreenSize(eI);a.maxScreenSize=Math.max(a.maxScreenSize,o)}else s||a.castShadows&&!a.shadowMap&&(a.visibleThisFrame=!0);else a.usePhysicalUnits=this.scene.physicalUnits}}cullShadowmaps(t){let e=this.scene.clusteredLightingEnabled;for(let i=0;i<this.localLights.length;i++){let r=this.localLights[i];r._type!==Ce&&(e?r.atlasSlotUpdated&&r.shadowUpdateMode===$s&&(r.shadowUpdateMode=Qi):r.shadowUpdateMode===$s&&r.castShadows&&(r.getRenderData(null,0).shadowCamera.renderTarget||(r.shadowUpdateMode=Qi)),r.visibleThisFrame&&r.castShadows&&r.shadowUpdateMode!==$s&&this._shadowRendererLocal.cull(r,t))}this.cameraDirShadowLights.clear();let s=t.cameras;for(let i=0;i<s.length;i++){let r=s[i];if(r.enabled){let a=r.camera,o,l=a.layers;for(let h=0;h<l.length;h++){let f=t.getLayerById(l[h]);if(f){let u=f.splitLights[Ce];for(let d=0;d<u.length;d++){let p=u[d];p.castShadows&&!kp.has(p)&&(kp.add(p),o=o??[],o.push(p),this._shadowRendererDirectional.cull(p,t,a))}}}o&&this.cameraDirShadowLights.set(a,o),kp.clear()}}}cullComposition(t){let{scene:e}=this;this.processingMeshInstances.clear();let s=t.cameras.length;this._camerasRendered+=s;for(let i=0;i<s;i++){let r=t.cameras[i],a=r.renderTarget;r.frameUpdate(a),this.updateCameraFrustum(r.camera),e?.fire(tS,r);let o=r.layers;for(let l=0;l<o.length;l++){let h=t.getLayerById(o[l]);if(h&&h.enabled){this.cullLights(r.camera,h._lights);let f=h.getCulledInstances(r.camera);this.cull(r.camera,h.meshInstances,f)}}e?.fire(sS,r)}e.clusteredLightingEnabled&&this.updateLightTextureAtlas(),this.cullShadowmaps(t),e?.fire(Pw)}updateShaders(t,e){let s=t.length;for(let i=0;i<s;i++){let r=t[i].material;if(r&&!kp.has(r)&&(kp.add(r),r.getShaderVariant!==Us.prototype.getShaderVariant)){if(e&&(!r.useLighting||r.emitter&&!r.emitter.lighting))continue;r.clearVariants()}}kp.clear()}updateFrameUniforms(){this.blueNoiseTextureId.setValue(jL(this.device))}beginFrame(t){let e=this.scene,s=e.updateShaders||this.device._shadersDirty,i=0,r=t.layerList,a=r.length;for(let h=0;h<a;h++){let u=r[h].meshInstances,d=u.length;i+=d;for(let p=0;p<d;p++){let m=u[p];m.visibleThisFrame=!1,s&&rI.push(m),m.skinInstance&&aI.push(m)}}if(s){let h=!e.updateShaders||!this.device._shadersDirty;this.updateShaders(rI,h),e.updateShaders=!1,this.device._shadersDirty=!1,e._shaderVersion++}this.updateFrameUniforms(),this.updateCpuSkinMatrices(aI),rI.length=0,aI.length=0;let o=this.lights,l=o.length;for(let h=0;h<l;h++)o[h].beginFrame()}updateLightTextureAtlas(){this.lightTextureAtlas.update(this.localLights,this.scene.lighting)}updateLayerComposition(t){let e=t.layerList.length,i=this.scene._shaderVersion;for(let r=0;r<e;r++){let a=t.layerList[r];a._shaderVersion=i}t._update()}frameUpdate(){this.clustersDebugRendered=!1,this.initViewBindGroupFormat(this.scene.clusteredLightingEnabled),this.dirLightShadows.clear()}};var zp=class{constructor(){n(this,"camera",null);this.layer=null,this.transparent=!1,this.renderTarget=null,this.lightClusters=null,this.clearColor=!1,this.clearDepth=!1,this.clearStencil=!1,this.triggerPostprocess=!1,this.firstCameraUse=!1,this.lastCameraUse=!1,this.viewBindGroups=[],this.useCameraPasses=!1}destroy(){this.viewBindGroups.forEach(t=>{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<l.length;){let d=l[u],p=h[u];if(s.camera.layersSet.has(d.id)&&(this.addLayer(s,d,p,f),f=!1),u++,d.id===a&&p===o)break}return u}updateCameraBeforePasses(){for(let e=0;e<this.renderActions.length;e++){let s=this.renderActions[e];if(s.firstCameraUse){let i=s.camera?.camera;if(i){let{beforePasses:r}=i;for(let a=0;a<r.length;a++)this.beforePasses.push(r[a])}}}}updateDirectionalShadows(){let{renderer:e,renderActions:s}=this;for(let i=0;i<s.length;i++){let o=s[i].camera.camera,l=this.renderer.cameraDirShadowLights.get(o);if(l)for(let h=0;h<l.length;h++){let f=l[h];if(e.dirLightShadows.get(f)!==o){e.dirLightShadows.set(f,o);let u=e._shadowRendererDirectional.getLightRenderPass(f,o);u&&this.beforePasses.push(u)}}}}updateClears(){let e=this.renderActions[0];if(e){let i=e.camera.camera,r=i.fullSizeClearRect;this.setClearColor(r&&e.clearColor?i.clearColor:void 0),this.setClearDepth(r&&e.clearDepth&&!this.noDepthClear?i.clearDepth:void 0),this.setClearStencil(r&&e.clearStencil?i.clearStencil:void 0)}}frameUpdate(){super.frameUpdate(),this.updateCameraBeforePasses(),this.updateDirectionalShadows(),this.updateClears()}before(){let{renderActions:e}=this;for(let s=0;s<e.length;s++){let i=e[s];i.firstCameraUse&&this.scene.fire(yw,i.camera)}}execute(){let{layerComposition:e,renderActions:s}=this;for(let i=0;i<s.length;i++){let r=s[i],a=r.layer;e.isEnabled(a,r.transparent)&&this.renderRenderAction(r,i===0)}}after(){for(let e=0;e<this.renderActions.length;e++){let s=this.renderActions[e];s.lastCameraUse&&this.scene.fire(Ew,s.camera)}this.beforePasses.length=0}renderRenderAction(e,s){let{renderer:i,scene:r}=this,a=i.device,{layer:o,transparent:l,camera:h}=e;if(h){let f=h.gammaCorrection,u=h.toneMapping;this.gammaCorrection!==void 0&&(h.gammaCorrection=this.gammaCorrection),this.toneMapping!==void 0&&(h.toneMapping=this.toneMapping),r.fire(Aw,h,o,l);let d={lightClusters:e.lightClusters},p=h.camera.shaderPassInfo?.index??Sr;(!s||!h.camera.fullSizeClearRect)&&(d.clearColor=e.clearColor,d.clearDepth=e.clearDepth,d.clearStencil=e.clearStencil);let m=e.renderTarget??a.backBuffer;i.renderForwardLayer(h.camera,m,o,l,p,e.viewBindGroups,d),a.setBlendState(Oe.NOBLEND),a.setStencilState(null,null),a.setAlphaToCoverage(!1),r.fire(Cw,h,o,l),this.gammaCorrection!==void 0&&(h.gammaCorrection=f),this.toneMapping!==void 0&&(h.toneMapping=u)}}};var ay=class extends Nt{constructor(t,e,s){super(t),this.renderer=e,this.renderAction=s}execute(){this.renderAction.camera.onPostprocessing()}};var h6=[[],[],[]],Nc=new F,Qf={drawCalls:[],shaderInstances:[],isNewMaterial:[],lightMaskChanged:[],clear:function(){this.drawCalls.length=0,this.shaderInstances.length=0,this.isNewMaterial.length=0,this.lightMaskChanged.length=0}};function f6(c){let t=[];for(let e=0;e<c;++e){let s=Math.sqrt(e+.5)/Math.sqrt(c);t.push(s)}return t}function u6(c){let t=[];for(let e=0;e<c;e++){let s=e/c,i=Math.sqrt(s*s);t.push(i)}return t}var Bc=class extends ry{constructor(t,e){super(t,e);let s=this.device;this._forwardDrawCalls=0,this._materialSwitches=0,this._depthMapTime=0,this._forwardTime=0,this._sortTime=0;let i=s.scope;this.fogColorId=i.resolve("fog_color"),this.fogStartId=i.resolve("fog_start"),this.fogEndId=i.resolve("fog_end"),this.fogDensityId=i.resolve("fog_density"),this.ambientId=i.resolve("light_globalAmbient"),this.skyboxIntensityId=i.resolve("skyboxIntensity"),this.cubeMapRotationMatrixId=i.resolve("cubeMapRotationMatrix"),this.pcssDiskSamplesId=i.resolve("pcssDiskSamples[0]"),this.pcssSphereSamplesId=i.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=i.resolve("uScreenSize"),this._screenSize=new Float32Array(4),this.fogColor=new Float32Array(3),this.ambientColor=new Float32Array(3),this.pcssDiskSamples=f6(16),this.pcssSphereSamples=u6(16)}destroy(){super.destroy()}dispatchGlobalLights(t){let e=this.ambientColor;if(Nc.linear(t.ambientLight),e[0]=Nc.r,e[1]=Nc.g,e[2]=Nc.b,t.physicalUnits)for(let s=0;s<3;s++)e[s]*=t.ambientLuminance;this.ambientId.setValue(e),this.skyboxIntensityId.setValue(t.physicalUnits?t.skyboxLuminance:t.skyboxIntensity),this.cubeMapRotationMatrixId.setValue(t._skyboxRotationMat3.data)}_resolveLight(t,e){let s=`light${e}`;this.lightColorId[e]=t.resolve(`${s}_color`),this.lightDir[e]=new Float32Array(3),this.lightDirId[e]=t.resolve(`${s}_direction`),this.lightShadowMapId[e]=t.resolve(`${s}_shadowMap`),this.lightShadowMatrixId[e]=t.resolve(`${s}_shadowMatrix`),this.lightShadowParamsId[e]=t.resolve(`${s}_shadowParams`),this.lightShadowIntensity[e]=t.resolve(`${s}_shadowIntensity`),this.lightShadowSearchAreaId[e]=t.resolve(`${s}_shadowSearchArea`),this.lightRadiusId[e]=t.resolve(`${s}_radius`),this.lightPos[e]=new Float32Array(3),this.lightPosId[e]=t.resolve(`${s}_position`),this.lightWidth[e]=new Float32Array(3),this.lightWidthId[e]=t.resolve(`${s}_halfWidth`),this.lightHeight[e]=new Float32Array(3),this.lightHeightId[e]=t.resolve(`${s}_halfHeight`),this.lightInAngleId[e]=t.resolve(`${s}_innerConeAngle`),this.lightOutAngleId[e]=t.resolve(`${s}_outerConeAngle`),this.lightCookieId[e]=t.resolve(`${s}_cookie`),this.lightCookieIntId[e]=t.resolve(`${s}_cookieIntensity`),this.lightCookieMatrixId[e]=t.resolve(`${s}_cookieMatrix`),this.lightCookieOffsetId[e]=t.resolve(`${s}_cookieOffset`),this.lightCameraParamsId[e]=t.resolve(`${s}_cameraParams`),this.lightSoftShadowParamsId[e]=t.resolve(`${s}_softShadowParams`),this.shadowMatrixPaletteId[e]=t.resolve(`${s}_shadowMatrixPalette[0]`),this.shadowCascadeDistancesId[e]=t.resolve(`${s}_shadowCascadeDistances`),this.shadowCascadeCountId[e]=t.resolve(`${s}_shadowCascadeCount`),this.shadowCascadeBlendId[e]=t.resolve(`${s}_shadowCascadeBlend`)}setLTCDirectionalLight(t,e,s,i,r){this.lightPos[e][0]=i.x-s.x*r,this.lightPos[e][1]=i.y-s.y*r,this.lightPos[e][2]=i.z-s.z*r,this.lightPosId[e].setValue(this.lightPos[e]);let a=t.transformVector(new x(-.5,0,0));this.lightWidth[e][0]=a.x*r,this.lightWidth[e][1]=a.y*r,this.lightWidth[e][2]=a.z*r,this.lightWidthId[e].setValue(this.lightWidth[e]);let o=t.transformVector(new x(0,0,.5));this.lightHeight[e][0]=o.x*r,this.lightHeight[e][1]=o.y*r,this.lightHeight[e][2]=o.z*r,this.lightHeightId[e].setValue(this.lightHeight[e])}dispatchDirectLights(t,e,s){let i=0,r=this.device.scope;for(let a=0;a<t.length;a++){if(!(t[a].mask&e))continue;let o=t[a],l=o._node.getWorldTransform();if(this.lightColorId[i]||this._resolveLight(r,i),this.lightColorId[i].setValue(o._colorLinear),l.getY(o._direction).mulScalar(-1),o._direction.normalize(),this.lightDir[i][0]=o._direction.x,this.lightDir[i][1]=o._direction.y,this.lightDir[i][2]=o._direction.z,this.lightDirId[i].setValue(this.lightDir[i]),o.shape!==$i&&this.setLTCDirectionalLight(l,i,o._direction,s._node.getPosition(),s.farClip),o.castShadows){let h=o.getRenderData(s,0),f=o._getUniformBiasValues(h);this.lightShadowMapId[i].setValue(h.shadowBuffer),this.lightShadowMatrixId[i].setValue(h.shadowMatrix.data),this.shadowMatrixPaletteId[i].setValue(o._shadowMatrixPalette),this.shadowCascadeDistancesId[i].setValue(o._shadowCascadeDistances),this.shadowCascadeCountId[i].setValue(o.numCascades),this.shadowCascadeBlendId[i].setValue(1-o.cascadeBlend),this.lightShadowIntensity[i].setValue(o.shadowIntensity),this.lightSoftShadowParamsId[i].setValue(o._softShadowParams),h.shadowCamera.renderTarget&&this.lightShadowSearchAreaId[i].setValue(o.penumbraSize/h.shadowCamera.renderTarget.width*h.projectionCompensation);let d=o._shadowCameraParams;d.length=4,d[0]=0,d[1]=h.shadowCamera._farClip,d[2]=h.shadowCamera._nearClip,d[3]=1,this.lightCameraParamsId[i].setValue(d);let p=o._shadowRenderParams;p.length=4,p[0]=o._shadowResolution,p[1]=f.normalBias,p[2]=f.bias,p[3]=0,this.lightShadowParamsId[i].setValue(p)}i++}return i}setLTCPositionalLight(t,e){let s=t.transformVector(new x(-.5,0,0));this.lightWidth[e][0]=s.x,this.lightWidth[e][1]=s.y,this.lightWidth[e][2]=s.z,this.lightWidthId[e].setValue(this.lightWidth[e]);let i=t.transformVector(new x(0,0,.5));this.lightHeight[e][0]=i.x,this.lightHeight[e][1]=i.y,this.lightHeight[e][2]=i.z,this.lightHeightId[e].setValue(this.lightHeight[e])}dispatchOmniLight(t,e,s){let i=e._node.getWorldTransform();if(this.lightColorId[s]||this._resolveLight(t,s),this.lightRadiusId[s].setValue(e.attenuationEnd),this.lightColorId[s].setValue(e._colorLinear),i.getTranslation(e._position),this.lightPos[s][0]=e._position.x,this.lightPos[s][1]=e._position.y,this.lightPos[s][2]=e._position.z,this.lightPosId[s].setValue(this.lightPos[s]),e.shape!==$i&&this.setLTCPositionalLight(i,s),e.castShadows){let r=e.getRenderData(null,0);this.lightShadowMapId[s].setValue(r.shadowBuffer);let a=e._getUniformBiasValues(r),o=e._shadowRenderParams;o.length=4,o[0]=e._shadowResolution,o[1]=a.normalBias,o[2]=a.bias,o[3]=1/e.attenuationEnd,this.lightShadowParamsId[s].setValue(o),this.lightShadowIntensity[s].setValue(e.shadowIntensity);let l=e.penumbraSize/r.shadowCamera.renderTarget.width;this.lightShadowSearchAreaId[s].setValue(l);let h=e._shadowCameraParams;h.length=4,h[0]=0,h[1]=r.shadowCamera._farClip,h[2]=r.shadowCamera._nearClip,h[3]=0,this.lightCameraParamsId[s].setValue(h)}e._cookie&&(this.lightCookieId[s].setValue(e._cookie),this.lightShadowMatrixId[s].setValue(i.data),this.lightCookieIntId[s].setValue(e.cookieIntensity))}dispatchSpotLight(t,e,s){let i=e._node.getWorldTransform();if(this.lightColorId[s]||this._resolveLight(t,s),this.lightInAngleId[s].setValue(e._innerConeAngleCos),this.lightOutAngleId[s].setValue(e._outerConeAngleCos),this.lightRadiusId[s].setValue(e.attenuationEnd),this.lightColorId[s].setValue(e._colorLinear),i.getTranslation(e._position),this.lightPos[s][0]=e._position.x,this.lightPos[s][1]=e._position.y,this.lightPos[s][2]=e._position.z,this.lightPosId[s].setValue(this.lightPos[s]),e.shape!==$i&&this.setLTCPositionalLight(i,s),i.getY(e._direction).mulScalar(-1),e._direction.normalize(),this.lightDir[s][0]=e._direction.x,this.lightDir[s][1]=e._direction.y,this.lightDir[s][2]=e._direction.z,this.lightDirId[s].setValue(this.lightDir[s]),e.castShadows){let r=e.getRenderData(null,0);this.lightShadowMapId[s].setValue(r.shadowBuffer),this.lightShadowMatrixId[s].setValue(r.shadowMatrix.data);let a=e._getUniformBiasValues(r),o=e._shadowRenderParams;o.length=4,o[0]=e._shadowResolution,o[1]=a.normalBias,o[2]=a.bias,o[3]=1/e.attenuationEnd,this.lightShadowParamsId[s].setValue(o),this.lightShadowIntensity[s].setValue(e.shadowIntensity);let l=e.penumbraSize/r.shadowCamera.renderTarget.width,h=r.shadowCamera._fov*R.DEG_TO_RAD,f=1/Math.tan(h/2);this.lightShadowSearchAreaId[s].setValue(l*f);let u=e._shadowCameraParams;u.length=4,u[0]=0,u[1]=r.shadowCamera._farClip,u[2]=r.shadowCamera._nearClip,u[3]=0,this.lightCameraParamsId[s].setValue(u)}if(e._cookie){if(!e.castShadows){let r=Wo.evalSpotCookieMatrix(e);this.lightShadowMatrixId[s].setValue(r.data)}this.lightCookieId[s].setValue(e._cookie),this.lightCookieIntId[s].setValue(e.cookieIntensity),e._cookieTransform&&(e._cookieTransformUniform[0]=e._cookieTransform.x,e._cookieTransformUniform[1]=e._cookieTransform.y,e._cookieTransformUniform[2]=e._cookieTransform.z,e._cookieTransformUniform[3]=e._cookieTransform.w,this.lightCookieMatrixId[s].setValue(e._cookieTransformUniform),e._cookieOffsetUniform[0]=e._cookieOffset.x,e._cookieOffsetUniform[1]=e._cookieOffset.y,this.lightCookieOffsetId[s].setValue(e._cookieOffsetUniform))}}dispatchLocalLights(t,e,s){let i=s,r=this.device.scope,a=t[We],o=a.length;for(let f=0;f<o;f++){let u=a[f];u.mask&e&&(this.dispatchOmniLight(r,u,i),i++)}let l=t[je],h=l.length;for(let f=0;f<h;f++){let u=l[f];u.mask&e&&(this.dispatchSpotLight(r,u,i),i++)}}renderForwardPrepareMaterials(t,e,s,i,r,a){let o=t.fogParams??this.scene.fog,l=t.shaderParams;l.fog=o.type,l.srgbRenderTarget=e?.isColorBufferSrgb(0)??!1;let h=(T,C,v,E)=>{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<g;T++){let C=s[T],v=C.instancingData;if(v&&v.count<=0)continue;C.ensureMaterial(f);let E=C.material,y=C._shaderDefs,P=C.mask;E&&E===m&&y!==_&&(m=null),E!==m&&(this._materialSwitches++,E._scene=u,E.dirty&&(E.updateUniforms(f,u),E.dirty=!1));let A=C.getShaderInstance(a,p,u,l,this.viewUniformFormat,this.viewBindGroupFormat,i);h(C,A,E!==m,!m||P!==S),m=E,_=y,S=P}return Qf}renderForwardInternal(t,e,s,i,r,a,o){let l=this.device,h=this.scene,f=1<<i,u=a?-1:1,d=h.clusteredLightingEnabled,p=t.xr?.session&&t.xr.views.list.length?t.xr.views.list:null,m=l.xrCurrentViewIndex??-1,_=p&&m>=0?m:0,S=p&&m>=0?m+1:p?p.length:0,g=e.drawCalls.length;for(let T=0;T<g;T++){let C=e.drawCalls[T],v=e.isNewMaterial[T],E=e.lightMaskChanged[T],y=e.shaderInstances[T],P=C.material,A=C.mask;if(y.shader.failed)continue;if(v){if(l.setShader(y.shader,!1),P.setParameters(l),E){let L=this.dispatchDirectLights(s[Ce],A,t);d||this.dispatchLocalLights(s,A,L)}this.alphaTestId.setValue(P.alphaTest),l.setBlendState(P.blendState),l.setDepthState(P.depthState),l.setAlphaToCoverage(P.alphaToCoverage)}this.setupCullModeAndFrontFace(t._cullFaces,u,C);let w=C.stencilFront??P.stencilFront,I=C.stencilBack??P.stencilBack;l.setStencilState(w,I),C.setParameters(l,f),l.scope.resolve("meshInstanceId").setValue(C.id);let D=C.mesh;this.setVertexBuffers(l,D),this.setMorphing(l,C.morphInstance),this.setSkinning(l,C);let O=C.instancingData;O&&l.setVertexBuffer(O.vertexBuffer),this.setMeshInstanceMatrices(C,!0),this.setupMeshUniformBuffers(y);let G=C.renderStyle,M=D.indexBuffer[G];r?.(C,T);let H=C.getDrawCommands(t);if(p)for(let U=_;U<S;U++){let L=p[U];if(l.setViewport(L.viewport.x,L.viewport.y,L.viewport.z,L.viewport.w),l.supportsUniformBuffers){let k=o[U];l.setBindGroup(Io,k)}else this.setupViewUniforms(L,U);let b=U===_,N=U===S-1;l.draw(D.primitive[G],M,O?.count,H,b,N),this._forwardDrawCalls++,C.instancingData&&this._instancedDrawCalls++}else l.draw(D.primitive[G],M,O?.count,H),this._forwardDrawCalls++,C.instancingData&&this._instancedDrawCalls++;T<g-1&&!e.isNewMaterial[T+1]&&P.setParameters(l,C.parameters)}}renderForward(t,e,s,i,r,a,o,l,h){let f=this.renderForwardPrepareMaterials(t,e,s,i,o,r);this.renderForwardInternal(t,f,i,r,a,l,h),Qf.clear()}renderForwardLayer(t,e,s,i,r,a,o={}){let{scene:l,device:h}=this,f=l.clusteredLightingEnabled;this.setupViewport(t,e);let u,d;if(s){s.sortVisible(t,i);let v=s.getCulledInstances(t);u=i?v.transparent:v.opaque,l.immediate.onPreRenderLayer(s,u,i),s.requiresLightCube&&(this.lightCube.update(l.ambientLight,s._lights),this.constantLightCube.setValue(this.lightCube.colors)),d=s.splitLights}else u=o.meshInstances,d=o.splitLights??h6;f&&((o.lightClusters??this.worldClustersAllocator.empty).activate(),s&&!this.clustersDebugRendered&&l.lighting.debugLayer===s.id&&(this.clustersDebugRendered=!0)),l._activeCamera=t;let p=t.fogParams??this.scene.fog;this.setFogConstants(p);let m=this.setCameraUniforms(t,e);h.supportsUniformBuffers&&this.setupViewUniformBuffers(a,this.viewUniformFormat,this.viewBindGroupFormat,m);let _=o.clearColor??!1,S=o.clearDepth??!1,g=o.clearStencil??!1;(_||S||g)&&this.clear(t,_,S,g);let T=!!(t._flipFaces^e?.flipY),C=this._forwardDrawCalls;this.renderForward(t,e,u,d,r,null,s,T,a),s&&(s._forwardDrawCalls+=this._forwardDrawCalls-C)}setFogConstants(t){if(t.type!==Mi){Nc.linear(t.color);let e=this.fogColor;e[0]=Nc.r,e[1]=Nc.g,e[2]=Nc.b,this.fogColorId.setValue(e),t.type===rw?(this.fogStartId.setValue(t.start),this.fogEndId.setValue(t.end)):this.fogDensityId.setValue(t.density)}}setSceneConstants(){let t=this.scene;this.dispatchGlobalLights(t);let e=this.device;this._screenSize[0]=e.width,this._screenSize[1]=e.height,this._screenSize[2]=1/e.width,this._screenSize[3]=1/e.height,this.screenSizeId.setValue(this._screenSize),this.pcssDiskSamplesId.setValue(this.pcssDiskSamples),this.pcssSphereSamplesId.setValue(this.pcssSphereSamples)}buildFrameGraph(t,e){let s=this.scene;if(t.reset(),s.clusteredLightingEnabled){let{shadowsEnabled:l,cookiesEnabled:h}=s.lighting;this._renderPassUpdateClustered.update(t,l,h,this.lights,this.localLights),t.addRenderPass(this._renderPassUpdateClustered)}else this._shadowRendererLocal.buildNonClusteredRenderPasses(t,this.localLights);let i=0,r=!0,a=null,o=e._renderActions;for(let l=i;l<o.length;l++){let h=o[l],{layer:f,camera:u}=h,d=this._isMultiview(u);if(h.useCameraPasses)d&&t.beginMultiView(this.device),u.camera.framePasses.forEach(p=>{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;r<t.length;r++){let a=t[r];i.has(a)||(s.push(a),i.add(a),oy.add(a.material))}if(e||this.addShadowCasters(t),oy.size>0){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<t.length;r++){let a=t[r];if(i.has(a)){i.delete(a);let o=s.indexOf(a);o>=0&&s.splice(o,1)}}e||this.removeShadowCasters(t)}addShadowCasters(t){let e=this.shadowCasters,s=this.shadowCastersSet;for(let i=0;i<t.length;i++){let r=t[i];r.castShadow&&!s.has(r)&&(s.add(r),e.push(r))}}removeShadowCasters(t){let e=this.shadowCasters,s=this.shadowCastersSet;for(let i=0;i<t.length;i++){let r=t[i];if(s.has(r)){s.delete(r);let a=e.indexOf(r);a>=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;s<t.length;s++)t[s].length=0;let e=this._lights;for(let s=0;s<e.length;s++){let i=e[s];i.enabled&&t[i._type].push(i)}for(let s=0;s<t.length;s++)t[s].sort((i,r)=>i.key-r.key)}return this._splitLights}evaluateLightHash(t,e,s){let i=0,r=this._lights;for(let a=0;a<r.length;a++){let o=r[a].type!==Ce;(t&&o||e&&!o)&&_S.push(s?r[a].id:r[a].key)}return _S.length>0&&(_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;u<i;u++){let d=t[u],p;if(d.calculateSortDistance)p=d.calculateSortDistance(d,e,s);else{let _=d.aabb.center;p=(_.x-r)*l+(_.y-a)*h+(_.z-o)*f}let m=d._drawBucket*1e9;d._sortKeyDynamic=m+p}}getCulledInstances(t){let e=this._visibleInstances.get(t);return e||(e=new nI,this._visibleInstances.set(t,e)),e}sortVisible(t,e){let s=e?this.transparentSortMode:this.opaqueSortMode;if(s===Ho)return;let i=this.getCulledInstances(t),r=e?i.transparent:i.opaque,a=t.node;if(s===xw){let o=a.getPosition(),l=a.forward;this.customCalculateSortValues&&this.customCalculateSortValues(r,r.length,o,l),this.customSortCallback&&r.sort(this.customSortCallback)}else{if(s===Jg||s===Sw){let o=a.getPosition(),l=a.forward;this._calculateSortDistances(r,o,l)}r.sort(g6[s])}}};var S6=(c,t)=>c.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;s<e;s++)if(this.layerList[s]._dirtyComposition){this._dirty=!0;break}}if(this._dirty){this._dirty=!1,this.cameras.length=0,this.camerasSet.clear();for(let r=0;r<e;r++){let a=this.layerList[r];a._dirtyComposition=!1;for(let o=0;o<a.cameras.length;o++){let l=a.cameras[o];this.camerasSet.has(l.camera)||(this.camerasSet.add(l.camera),this.cameras.push(l))}}this.cameras.length>1&&Uc(this.cameras);let s=[],i=0;this.destroyRenderActions();for(let r=0;r<this.cameras.length;r++){let a=this.cameras[r];if(s.length=0,a.camera.framePasses.length>0){this.addDummyRenderAction(i,a),i++;continue}let o=!0,l=i,h=null,f=!1;for(let u=0;u<e;u++){let d=this.layerList[u];if(d.enabled&&this.subLayerEnabled[u]&&d.cameras.length>0&&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<i&&(h.lastCameraUse=!0),!f&&h&&(h.triggerPostprocess=!0),a.renderTarget&&a.postEffectsEnabled&&this.propagateRenderTarget(l-1,a)}this._logRenderActions()}}getNextRenderAction(e){let s=new zp;return this._renderActions.push(s),s}addDummyRenderAction(e,s){let i=this.getNextRenderAction(e);i.camera=s,i.useCameraPasses=!0}addRenderAction(e,s,i,r,a,o){let l=s.id!==Zt?r.renderTarget:null,h=!1,f=this._renderActions;for(let m=e-1;m>=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<i;s++)if(this.layerList[s]===e&&!this.subLayerList[s]){this.layerList.splice(s,1),this.subLayerList.splice(s,1),i--,this._updateOpaqueOrder(s,i-1),this.subLayerEnabled.splice(s,1),this._dirty=!0,this.layerList.indexOf(e)<0&&this.fire("remove",e);break}this._updateLayerMaps()}pushTransparent(e){this._isSublayerAdded(e,!0)||(this.layerList.push(e),this._transparentOrder[e.id]=this.subLayerList.push(!0)-1,this.subLayerEnabled.push(!0),this._updateLayerMaps(),this._dirty=!0,this.fire("add",e))}insertTransparent(e,s){if(this._isSublayerAdded(e,!0))return;this.layerList.splice(s,0,e),this.subLayerList.splice(s,0,!0);let i=this.subLayerList.length;this._updateTransparentOrder(s,i-1),this.subLayerEnabled.splice(s,0,!0),this._updateLayerMaps(),this._dirty=!0,this.fire("add",e)}removeTransparent(e){for(let s=0,i=this.layerList.length;s<i;s++)if(this.layerList[s]===e&&this.subLayerList[s]){this.layerList.splice(s,1),this.subLayerList.splice(s,1),i--,this._updateTransparentOrder(s,i-1),this.subLayerEnabled.splice(s,1),this._dirty=!0,this.layerList.indexOf(e)<0&&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,s){if(e.enabled){let i=s?this.getTransparentIndex(e):this.getOpaqueIndex(e);if(i>=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<this.layerList.length;e++){let s=this.layerList[e];this.layerIdMap.set(s.id,s),this.layerNameMap.set(s.name,s),(this.subLayerList[e]?this.layerTransparentIndexMap:this.layerOpaqueIndexMap).set(s,e)}}getLayerById(e){return this.layerIdMap.get(e)??null}getLayerByName(e){return this.layerNameMap.get(e)??null}_updateOpaqueOrder(e,s){for(let i=e;i<=s;i++)this.subLayerList[i]===!1&&(this._opaqueOrder[this.layerList[i].id]=i)}_updateTransparentOrder(e,s){for(let i=e;i<=s;i++)this.subLayerList[i]===!0&&(this._transparentOrder[this.layerList[i].id]=i)}_sortLayersDescending(e,s,i){let r=-1,a=-1;for(let o=0,l=e.length;o<l;o++){let h=e[o];i.hasOwnProperty(h)&&(r=Math.max(r,i[h]))}for(let o=0,l=s.length;o<l;o++){let h=s[o];i.hasOwnProperty(h)&&(a=Math.max(a,i[h]))}return r===-1&&a!==-1?1:a===-1&&r!==-1?-1:a-r}sortTransparentLayers(e,s){return this._sortLayersDescending(e,s,this._transparentOrder)}sortOpaqueLayers(e,s){return this._sortLayersDescending(e,s,this._opaqueOrder)}};var ny=new x,nl={bias:0,normalBias:0},gS=new F,lI={r:0,g:1,b:2,a:3},ly={directional:Ce,omni:We,point:We,spot:je},x6=[[new Q(0,0,1,1)],[new Q(0,0,.5,.5),new Q(0,.5,.5,.5)],[new Q(0,0,.5,.5),new Q(0,.5,.5,.5),new Q(.5,0,.5,.5)],[new Q(0,0,.5,.5),new Q(0,.5,.5,.5),new Q(.5,0,.5,.5),new Q(.5,.5,.5,.5)]],v6={rrr:1,ggg:2,bbb:4,aaa:8,rgb:7},T6=0,cI=class{constructor(t,e,s){this.light=s,this.camera=t,this.shadowCamera=Np.createShadowCamera(s.device,s._shadowType,s._type,e),this.shadowMatrix=new W,this.shadowViewport=new Q(0,0,1,1),this.shadowScissor=new Q(0,0,1,1),this.projectionCompensation=0,this.face=e,this.visibleCasters=[],this.viewBindGroups=[]}destroy(){this.viewBindGroups.forEach(t=>{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;t<this._renderData.length;t++)this._renderData[t].destroy();this._renderData.length=0}}addLayer(t){this.layers.add(t)}removeLayer(t){this.layers.delete(t)}set shadowSamples(t){this._softShadowParams[0]=t}get shadowSamples(){return this._softShadowParams[0]}set shadowBlockerSamples(t){this._softShadowParams[1]=t}get shadowBlockerSamples(){return this._softShadowParams[1]}set shadowBias(t){this._shadowBias!==t&&(this._shadowBias=t,this._updateShadowBias())}get shadowBias(){return this._shadowBias}set numCascades(t){(!this.cascades||this.numCascades!==t)&&(this.cascades=x6[t-1],this._shadowMatrixPalette=new Float32Array(64),this._shadowCascadeDistances=new Float32Array(4),this._destroyShadowMap(),this.updateKey())}get numCascades(){return this.cascades.length}set cascadeBlend(t){this._cascadeBlend!==t&&(this._cascadeBlend=t,this.updateKey())}get cascadeBlend(){return this._cascadeBlend}set shadowMap(t){this._shadowMap!==t&&(this._destroyShadowMap(),this._shadowMap=t)}get shadowMap(){return this._shadowMap}set mask(t){this._mask!==t&&(this._mask=t,this.updateKey(),this.updateClusteredFlags())}get mask(){return this._mask}get numShadowFaces(){let t=this._type;return t===Ce?this.numCascades:t===We?6:1}set type(t){if(this._type===t)return;this._type=t,this._destroyShadowMap(),this._updateShadowBias(),this.updateKey(),this.updateClusteredFlags();let e=this._shadowType;this._shadowType=null,this.shadowUpdateOverrides=null,this.shadowType=e}get type(){return this._type}set shape(t){if(this._shape===t)return;this._shape=t,this._destroyShadowMap(),this.updateKey(),this.updateClusteredFlags();let e=this._shadowType;this._shadowType=null,this.shadowType=e}get shape(){return this._shape}set usePhysicalUnits(t){this._usePhysicalUnits!==t&&(this._usePhysicalUnits=t,this._updateLinearColor())}get usePhysicalUnits(){return this._usePhysicalUnits}set shadowType(t){if(this._shadowType===t)return;let e=Fi.get(t);e||(t=Oi);let s=this.device;t===xc&&(!s.textureFloatRenderable||!s.textureFloatFilterable)&&(t=Oi),this._type===We&&t!==pT&&t!==Oi&&t!==mT&&t!==_T&&t!==xc&&(t=Oi),t===fp&&(!s.textureFloatRenderable||!s.textureFloatFilterable)&&(t=Yg),t===Yg&&!s.textureHalfFloatRenderable&&(t=Oi),e=Fi.get(t),this._isVsm=e?.vsm??!1,this._isPcf=e?.pcf??!1,this._shadowType=t,this._destroyShadowMap(),this.updateKey()}get shadowType(){return this._shadowType}set enabled(t){this._enabled!==t&&(this._enabled=t,this.layersDirty())}get enabled(){return this._enabled}set castShadows(t){this._castShadows!==t&&(this._castShadows=t,this._destroyShadowMap(),this.layersDirty(),this.updateKey())}get castShadows(){return this._castShadows&&this._mask!==vi&&this._mask!==0}set shadowIntensity(t){this._shadowIntensity!==t&&(this._shadowIntensity=t,this.updateKey())}get shadowIntensity(){return this._shadowIntensity}get bakeShadows(){return this._castShadows&&this._mask===vi}set shadowResolution(t){this._shadowResolution!==t&&(this._type===We?t=Math.min(t,this.device.maxCubeMapSize):t=Math.min(t,this.device.maxTextureSize),this._shadowResolution=t,this._destroyShadowMap())}get shadowResolution(){return this._shadowResolution}set vsmBlurSize(t){this._vsmBlurSize!==t&&(t%2===0&&t++,this._vsmBlurSize=t)}get vsmBlurSize(){return this._vsmBlurSize}set normalOffsetBias(t){if(this._normalOffsetBias!==t){let e=!this._normalOffsetBias&&t||this._normalOffsetBias&&!t;this._normalOffsetBias=t,e&&this.updateKey()}}get normalOffsetBias(){return this._normalOffsetBias}set falloffMode(t){this._falloffMode!==t&&(this._falloffMode=t,this.updateKey(),this.updateClusteredFlags())}get falloffMode(){return this._falloffMode}set innerConeAngle(t){this._innerConeAngle!==t&&(this._innerConeAngle=t,this._innerConeAngleCos=Math.cos(t*R.DEG_TO_RAD),this.updateClusterData(!1,!0),this._usePhysicalUnits&&this._updateLinearColor())}get innerConeAngle(){return this._innerConeAngle}set outerConeAngle(t){this._outerConeAngle!==t&&(this._outerConeAngle=t,this._updateOuterAngle(t),this._usePhysicalUnits&&this._updateLinearColor())}get outerConeAngle(){return this._outerConeAngle}set penumbraSize(t){this._penumbraSize=t,this._softShadowParams[2]=t}get penumbraSize(){return this._penumbraSize}set penumbraFalloff(t){this._softShadowParams[3]=t}get penumbraFalloff(){return this._softShadowParams[3]}_updateOuterAngle(t){let e=t*R.DEG_TO_RAD;this._outerConeAngleCos=Math.cos(e),this._outerConeAngleSin=Math.sin(e),this.updateClusterData(!1,!0)}set intensity(t){this._intensity!==t&&(this._intensity=t,this._updateLinearColor())}get intensity(){return this._intensity}set affectSpecularity(t){this._type===Ce&&(this._affectSpecularity=t,this.updateKey())}get affectSpecularity(){return this._affectSpecularity}set luminance(t){this._luminance!==t&&(this._luminance=t,this._updateLinearColor())}get luminance(){return this._luminance}get cookieMatrix(){return this._cookieMatrix||(this._cookieMatrix=new W),this._cookieMatrix}get atlasViewport(){return this._atlasViewport||(this._atlasViewport=new Q(0,0,1,1)),this._atlasViewport}set cookie(t){this._cookie!==t&&(this._cookie=t,this.updateKey())}get cookie(){return this._cookie}set cookieFalloff(t){this._cookieFalloff!==t&&(this._cookieFalloff=t,this.updateKey())}get cookieFalloff(){return this._cookieFalloff}set cookieChannel(t){if(this._cookieChannel!==t){if(t.length<3){let e=t.charAt(t.length-1),s=3-t.length;for(let i=0;i<s;i++)t+=e}this._cookieChannel=t,this.updateKey(),this.updateClusteredFlags()}}get cookieChannel(){return this._cookieChannel}set cookieTransform(t){this._cookieTransform!==t&&(this._cookieTransform=t,this._cookieTransformSet=!!t,t&&!this._cookieOffset&&(this.cookieOffset=new B,this._cookieOffsetSet=!1),this.updateKey())}get cookieTransform(){return this._cookieTransform}set cookieOffset(t){if(this._cookieOffset===t)return;!!(this._cookieTransformSet||t)&&!t&&this._cookieOffset?this._cookieOffset.set(0,0):this._cookieOffset=t,this._cookieOffsetSet=!!t,t&&!this._cookieTransform&&(this.cookieTransform=new Q(1,1,0,0),this._cookieTransformSet=!1),this.updateKey()}get cookieOffset(){return this._cookieOffset}beginFrame(){this.visibleThisFrame=this._type===Ce&&this._enabled,this.maxScreenSize=0,this.atlasViewportAllocated=!1,this.atlasSlotUpdated=!1}_destroyShadowMap(){if(this.releaseRenderData(),this._shadowMap&&(this._shadowMap.cached||this._shadowMap.destroy(),this._shadowMap=null),this.shadowUpdateMode===$s&&(this.shadowUpdateMode=Qi),this.shadowUpdateOverrides)for(let t=0;t<this.shadowUpdateOverrides.length;t++)this.shadowUpdateOverrides[t]===$s&&(this.shadowUpdateOverrides[t]=Qi)}getRenderData(t,e){for(let i=0;i<this._renderData.length;i++){let r=this._renderData[i];if(r.camera===t&&r.face===e)return r}let s=new cI(t,e,this);return this._renderData.push(s),s}clone(){let t=new c(this.device,this.clusteredLighting);return t.type=this._type,t.setColor(this._color),t.intensity=this._intensity,t.affectSpecularity=this._affectSpecularity,t.luminance=this._luminance,t.castShadows=this.castShadows,t._enabled=this._enabled,t.attenuationStart=this.attenuationStart,t.attenuationEnd=this.attenuationEnd,t.falloffMode=this._falloffMode,t.shadowType=this._shadowType,t.vsmBlurSize=this._vsmBlurSize,t.vsmBlurMode=this.vsmBlurMode,t.vsmBias=this.vsmBias,t.shadowUpdateMode=this.shadowUpdateMode,t.mask=this.mask,this.shadowUpdateOverrides&&(t.shadowUpdateOverrides=this.shadowUpdateOverrides.slice()),t.innerConeAngle=this._innerConeAngle,t.outerConeAngle=this._outerConeAngle,t.numCascades=this.numCascades,t.cascadeDistribution=this.cascadeDistribution,t.cascadeBlend=this._cascadeBlend,t.shape=this._shape,t.shadowDepthState.copy(this.shadowDepthState),t.shadowBias=this.shadowBias,t.normalOffsetBias=this._normalOffsetBias,t.shadowResolution=this._shadowResolution,t.shadowDistance=this.shadowDistance,t.shadowIntensity=this.shadowIntensity,t.shadowSamples=this.shadowSamples,t.shadowBlockerSamples=this.shadowBlockerSamples,t.penumbraSize=this.penumbraSize,t.penumbraFalloff=this.penumbraFalloff,t}static getLightUnitConversion(t,e=Math.PI/4,s=0){switch(t){case je:{let i=Math.cos(e),r=Math.cos(s);return 2*Math.PI*(1-r+(r-i)/2)}case We:return 4*Math.PI;case Ce:return 1}}_getUniformBiasValues(t){let e=t.shadowCamera._farClip;switch(this._type){case We:nl.bias=this.shadowBias,nl.normalBias=this._normalOffsetBias;break;case je:this._isVsm?nl.bias=-1e-5*20:nl.bias=this.shadowBias*20,nl.normalBias=this._isVsm?this.vsmBias/(this.attenuationEnd/7):this._normalOffsetBias;break;case Ce:this._isVsm?nl.bias=-1e-5*20:nl.bias=this.shadowBias/e*100,nl.normalBias=this._isVsm?this.vsmBias/(e/7):this._normalOffsetBias;break}return nl}getColor(){return this._color}getBoundingSphere(t){if(this._type===je){let e=this.attenuationEnd,s=this._outerConeAngle,i=this._outerConeAngleCos,r=this._node;ny.copy(r.up),s>45?(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<t._targets.length;a++){let o=t._targets[a];o.name&&this._weightMap.set(o.name,a),this.setWeight(a,o.defaultWeight)}this._shaderMorphWeights=new Float32Array(e),this._shaderMorphIndex=new Uint32Array(e);let s=(a,o)=>(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;a<t.length;a++)Math.abs(this.getWeight(a))>e&&(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;e<this.meshInstances.length;e++){let s=this.meshInstances[e];t.indexOf(s.material)===-1&&t.push(s.material)}return t}clone(){let t=[],e=[],s=function(h){let f=h.clone();t.push(h),e.push(f);for(let u=0;u<h._children.length;u++)f.addChild(s(h._children[u]));return f},i=s(this.graph),r=[],a=[],o=[];for(let h=0;h<this.skinInstances.length;h++){let f=this.skinInstances[h].skin,u=new er(f),d=[];for(let p=0;p<f.boneNames.length;p++){let m=f.boneNames[p],_=i.findByName(m);d.push(_)}u.bones=d,a.push(u)}for(let h=0;h<this.morphInstances.length;h++){let f=this.morphInstances[h].morph,u=new Ar(f);o.push(u)}for(let h=0;h<this.meshInstances.length;h++){let f=this.meshInstances[h],u=t.indexOf(f.node),d=new we(f.mesh,f.material,e[u]);if(f.skinInstance){let p=this.skinInstances.indexOf(f.skinInstance);d.skinInstance=a[p]}if(f.morphInstance){let p=this.morphInstances.indexOf(f.morphInstance);d.morphInstance=o[p]}r.push(d)}let l=new c;return l.graph=i,l.meshInstances=r,l.skinInstances=a,l.morphInstances=o,l.getGraph().syncHierarchy(),l}destroy(){let t=this.meshInstances;for(let e=0;e<t.length;e++)t[e].destroy();this.meshInstances.length=0}generateWireframe(){we._prepareRenderStyleForArray(this.meshInstances,Fo)}};var Ko=class extends Mo{constructor(e,s,{preferHighPrecision:i=!1}={}){super();n(this,"_aabb");n(this,"preferHighPrecision");this.device=s;let r=s;this.preferHighPrecision=i,this._targets=e.slice();let a=r.textureHalfFloatRenderable?Me:void 0,o=r.textureFloatRenderable?ke:void 0;this._renderTextureFormat=this.preferHighPrecision?o??a:a??o,this._renderTextureFormat=this._renderTextureFormat??Rs,this.intRenderFormat=ur(this._renderTextureFormat),this._textureFormat=this.preferHighPrecision?ke:Me,this._init(),this._updateMorphFlags()}destroy(){this.vertexBufferIds?.destroy(),this.vertexBufferIds=null,this.targetsTexturePositions?.destroy(),this.targetsTexturePositions=null,this.targetsTextureNormals?.destroy(),this.targetsTextureNormals=null}get aabb(){if(!this._aabb){let e=new x,s=new x;for(let i=0;i<this._targets.length;i++){let r=this._targets[i].aabb;e.min(r.getMin()),s.max(r.getMax())}this._aabb=new ge,this._aabb.setMinMax(e,s)}return this._aabb}get morphPositions(){return this._morphPositions}get morphNormals(){return this._morphNormals}_init(){this._initTextureBased();for(let e=0;e<this._targets.length;e++)this._targets[e]._postInit()}_findSparseSet(e,s,i){let r=1,a=e[0].length;for(let o=0;o<a;o+=3){let l=!1;for(let h=0;h<e.length;h++){let f=e[h];if(f[o]!==0||f[o+1]!==0||f[o+2]!==0){l=!0;break}}l?(s.push(r),i.push(o/3),r++):s.push(0)}return r}_initTextureBased(){let e=[],s=[],i=this._targets;for(let g=0;g<i.length;g++){let T=i[g];T.options.deltaPositions&&(e.push(T.options.deltaPositions),s.push(!0)),T.options.deltaNormals&&(e.push(T.options.deltaNormals),s.push(!1))}let r=[],a=[],o=this._findSparseSet(e,r,a),l=this.device.maxTextureSize,h=Math.ceil(Math.sqrt(o));h=Math.min(h,l);let f=Math.ceil(o/h);if(f>l)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;g<e.length;g++){let T=e[g],C=this._textureFormat===Me?new Uint16Array(_):new Float32Array(_);if((s[g]?p:m).push(C),u)for(let v=0;v<a.length;v++){let E=a[v]*3,y=v*4+4;C[y]=d(T[E]),C[y+1]=d(T[E+1]),C[y+2]=d(T[E+2])}else for(let v=0;v<a.length;v++){let E=a[v]*3,y=v*4+4;C[y]=T[E],C[y+1]=T[E+1],C[y+2]=T[E+2]}}p.length>0&&(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<this._targets.length;e++){let s=this._targets[e];s.morphPositions&&(this._morphPositions=!0),s.morphNormals&&(this._morphNormals=!0)}}_createTexture(e,s,i,r){return new Z(this.device,{levels:r,arrayLength:i,width:this.morphTextureWidth,height:this.morphTextureHeight,format:s,cubemap:!1,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1,name:e})}};var Gc=class c{constructor(t){n(this,"used",!1);this.options=t,this._name=t.name,this._defaultWeight=t.defaultWeight||0,this._aabb=t.aabb,this.deltaPositions=t.deltaPositions,this.morphPositions=!!t.deltaPositions,this.morphNormals=!!t.deltaNormals}get name(){return this._name}get defaultWeight(){return this._defaultWeight}get aabb(){return this._aabb||(this._aabb=new ge,this.deltaPositions&&this._aabb.compute(this.deltaPositions)),this._aabb}clone(){return new c(this.options)}_postInit(){this.options.preserveData||(this.options=null),this.used=!0}};var ll,sM=1,Ae=4,hI=new W,fI=new W,jo=new x,Wt=new x,Ka=new x,Gp=new x,Cr=new x,fs=new x,Vp=new x,Hp=new x,SS=new x,iM=new x,Ai=new x,cy=new x,Jf=new x;function Wp(c){return c-Math.floor(c)}function y6(c){return Math.max(Math.min(c,1),0)}function uI(c,t){return c-t*Math.floor(c/t)}function E6(c){let t=Wp(c),e=Wp(255*c),s=Wp(65025*c),i=Wp(160581375*c);return t-=e/255,e-=s/255,s-=i/255,i-=i/255,[t,e,s,i]}function hy(c){let t=Wp(c),e=Wp(255*c);return t-=e/255,e-=e/255,[t,e]}var fy=class{constructor(t){this._emitter=t}calcSpawnPosition(t,e,s,i,r){let a=this._emitter,o=Math.random(),l=Math.random(),h=Math.random(),f=Math.random();if(a.useCpu&&(t[r*Ae+0+a.numParticlesPot*2*Ae]=o,t[r*Ae+1+a.numParticlesPot*2*Ae]=l,t[r*Ae+2+a.numParticlesPot*2*Ae]=h),Wt.x=o-.5,Wt.y=l-.5,Wt.z=h-.5,a.emitterShape===Ni){let p=Math.max(Math.abs(Wt.x),Math.max(Math.abs(Wt.y),Math.abs(Wt.z))),m=p+(.5-p)*s[0],_=p+(.5-p)*s[1],S=p+(.5-p)*s[2];Wt.x=m*(p===Math.abs(Wt.x)?Math.sign(Wt.x):2*Wt.x),Wt.y=_*(p===Math.abs(Wt.y)?Math.sign(Wt.y):2*Wt.y),Wt.z=S*(p===Math.abs(Wt.z)?Math.sign(Wt.z):2*Wt.z),a.localSpace?jo.copy(e.transformPoint(Wt)):jo.copy(i).add(e.transformPoint(Wt))}else{Wt.normalize();let p=a.emitterRadius===0?0:a.emitterRadiusInner/a.emitterRadius,m=f*(1-p)+p;a.localSpace?jo.copy(Wt.mulScalar(m*a.emitterRadius)):jo.copy(i).add(Wt.mulScalar(m*a.emitterRadius))}let d=-R.lerp(a.rate,a.rate2,o)*r;if(a.pack8){let p=(jo.x-a.worldBounds.center.x)/a.worldBoundsSize.x+.5,m=(jo.y-a.worldBounds.center.y)/a.worldBoundsSize.y+.5,_=(jo.z-a.worldBounds.center.z)/a.worldBoundsSize.z+.5,S=R.lerp(a.startAngle*R.DEG_TO_RAD,a.startAngle2*R.DEG_TO_RAD,o);S=S%(Math.PI*2)/(Math.PI*2);let g=hy(p);t[r*Ae]=g[0],t[r*Ae+1]=g[1];let T=hy(m);t[r*Ae+2]=T[0],t[r*Ae+3]=T[1];let C=hy(_);t[r*Ae+0+a.numParticlesPot*Ae]=C[0],t[r*Ae+1+a.numParticlesPot*Ae]=C[1];let v=hy(S);t[r*Ae+2+a.numParticlesPot*Ae]=v[0],t[r*Ae+3+a.numParticlesPot*Ae]=v[1];let E=1;t[r*Ae+3+a.numParticlesPot*Ae*2]=E;let y=Math.max(a.lifetime,a.numParticles*Math.max(a.rate,a.rate2)),P=a.lifetime+1;d=(d+y)/(y+P);let A=E6(d);t[r*Ae+0+a.numParticlesPot*Ae*3]=A[0],t[r*Ae+1+a.numParticlesPot*Ae*3]=A[1],t[r*Ae+2+a.numParticlesPot*Ae*3]=A[2],t[r*Ae+3+a.numParticlesPot*Ae*3]=A[3]}else t[r*Ae]=jo.x,t[r*Ae+1]=jo.y,t[r*Ae+2]=jo.z,t[r*Ae+3]=R.lerp(a.startAngle*R.DEG_TO_RAD,a.startAngle2*R.DEG_TO_RAD,o),t[r*Ae+3+a.numParticlesPot*Ae]=d}update(t,e,s,i,r,a,o,l){let h,f,u,d=this._emitter;if(d.meshInstance.node){let w=d.meshInstance.node.worldTransform;for(let I=0;I<12;I++)hI.data[I]=w.data[I];fI.copy(hI),fI.invert(),ll=d.meshInstance.node.localScale,sM=Math.max(Math.max(ll.x,ll.y),ll.z)}a=d.meshInstance.node===null||d.localSpace?x.ZERO:d.meshInstance.node.getPosition();let p=d.camera?d.camera._node.getPosition():x.ZERO,m=d.useMesh?17:15,_,S,g,T,C,v,E,y,P,A=d.precision-1;for(let w=0;w<d.numParticles;w++){let I=Math.floor(d.vbCPU[w*d.numParticleVerts*(d.useMesh?6:4)+3]),D=s[I*Ae+0+d.numParticlesPot*2*Ae];Ka.x=D,Ka.y=s[I*Ae+1+d.numParticlesPot*2*Ae],Ka.z=s[I*Ae+2+d.numParticlesPot*2*Ae];let O=d.rate+(d.rate2-d.rate)*D,G=d.lifetime,M=s[I*Ae+3+d.numParticlesPot*Ae]+o,H=y6(M/G),U=0,L=0,b=0;(M-o<=0||M>=G)&&this.calcSpawnPosition(s,i,r,a,I);let k=M>0&&M<G;k&&(u=H*A,_=Math.floor(u),S=Math.ceil(u),u%=1,h=d.qRotSpeed[_],f=d.qRotSpeed[S],g=h+(f-h)*u,h=d.qRotSpeed2[_],f=d.qRotSpeed2[S],T=h+(f-h)*u,h=d.qScale[_],f=d.qScale[S],U=h+(f-h)*u,h=d.qScale2[_],f=d.qScale2[S],C=h+(f-h)*u,h=d.qAlpha[_],f=d.qAlpha[S],v=h+(f-h)*u,h=d.qAlpha2[_],f=d.qAlpha2[S],E=h+(f-h)*u,h=d.qRadialSpeed[_],f=d.qRadialSpeed[S],y=h+(f-h)*u,h=d.qRadialSpeed2[_],f=d.qRadialSpeed2[S],P=h+(f-h)*u,y+=(P-y)*(D*100%1),Gp.x=s[I*Ae],Gp.y=s[I*Ae+1],Gp.z=s[I*Ae+2],d.localSpace?SS.copy(Gp):SS.copy(Gp).sub(a),SS.normalize().mulScalar(y),_*=3,S*=3,h=d.qLocalVelocity[_],f=d.qLocalVelocity[S],fs.x=h+(f-h)*u,h=d.qLocalVelocity[_+1],f=d.qLocalVelocity[S+1],fs.y=h+(f-h)*u,h=d.qLocalVelocity[_+2],f=d.qLocalVelocity[S+2],fs.z=h+(f-h)*u,h=d.qLocalVelocity2[_],f=d.qLocalVelocity2[S],Hp.x=h+(f-h)*u,h=d.qLocalVelocity2[_+1],f=d.qLocalVelocity2[S+1],Hp.y=h+(f-h)*u,h=d.qLocalVelocity2[_+2],f=d.qLocalVelocity2[S+2],Hp.z=h+(f-h)*u,h=d.qVelocity[_],f=d.qVelocity[S],Cr.x=h+(f-h)*u,h=d.qVelocity[_+1],f=d.qVelocity[S+1],Cr.y=h+(f-h)*u,h=d.qVelocity[_+2],f=d.qVelocity[S+2],Cr.z=h+(f-h)*u,h=d.qVelocity2[_],f=d.qVelocity2[S],Vp.x=h+(f-h)*u,h=d.qVelocity2[_+1],f=d.qVelocity2[S+1],Vp.y=h+(f-h)*u,h=d.qVelocity2[_+2],f=d.qVelocity2[S+2],Vp.z=h+(f-h)*u,fs.x+=(Hp.x-fs.x)*Ka.x,fs.y+=(Hp.y-fs.y)*Ka.y,fs.z+=(Hp.z-fs.z)*Ka.z,d.initialVelocity>0&&(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;z<d.numParticleVerts;z++){let V=(w*d.numParticleVerts+z)*(d.useMesh?6:4),q=d.vbCPU[V],re=d.vbCPU[V+1],te=d.vbCPU[V+2];k||(q=re=te=0);let j=w*d.numParticleVerts*m+z*m;t[j]=Ai.x,t[j+1]=Ai.y,t[j+2]=Ai.z,t[j+3]=H,t[j+4]=d.alignToMotion?b:s[I*Ae+3],t[j+5]=U,t[j+6]=L,t[j+7]=cy.x,t[j+8]=q,t[j+9]=re,t[j+10]=te,t[j+11]=cy.y,t[j+12]=I,t[j+13]=cy.z,t[j+14]=d.vbCPU[V+3],d.useMesh&&(t[j+15]=d.vbCPU[V+4],t[j+16]=d.vbCPU[V+5])}}if(d.sort>up&&d.camera){let w=d.useMesh?6:4,I=d.particleDistance;for(let D=0;D<d.numParticles;D++)e[D][0]=D,e[D][1]=I[Math.floor(d.vbCPU[D*d.numParticleVerts*w+3])];d.vbOld.set(d.vbCPU),e.sort((D,O)=>D[1]-O[1]);for(let D=0;D<d.numParticles;D++){let O=e[D][0]*d.numParticleVerts*w,G=D*d.numParticleVerts*w;for(let M=0;M<d.numParticleVerts*w;M++)d.vbCPU[G+M]=d.vbOld[O+M]}}}};var rM=new Ws,aM=new Ws,oM=new Ws,uy=class{constructor(t,e){this._emitter=t,this.frameRandomUniform=new Float32Array(3),this.emitterPosUniform=new Float32Array(3),this.emitterScaleUniform=new Float32Array([1,1,1]),this.worldBoundsMulUniform=new Float32Array(3),this.worldBoundsAddUniform=new Float32Array(3),this.inBoundsSizeUniform=new Float32Array(3),this.inBoundsCenterUniform=new Float32Array(3),this.constantParticleTexIN=e.scope.resolve("particleTexIN"),this.constantParticleTexOUT=e.scope.resolve("particleTexOUT"),this.constantEmitterPos=e.scope.resolve("emitterPos"),this.constantEmitterScale=e.scope.resolve("emitterScale"),this.constantSpawnBounds=e.scope.resolve("spawnBounds"),this.constantSpawnPosInnerRatio=e.scope.resolve("spawnPosInnerRatio"),this.constantSpawnBoundsSphere=e.scope.resolve("spawnBoundsSphere"),this.constantSpawnBoundsSphereInnerRatio=e.scope.resolve("spawnBoundsSphereInnerRatio"),this.constantInitialVelocity=e.scope.resolve("initialVelocity"),this.constantFrameRandom=e.scope.resolve("frameRandom"),this.constantDelta=e.scope.resolve("delta"),this.constantRate=e.scope.resolve("rate"),this.constantRateDiv=e.scope.resolve("rateDiv"),this.constantLifetime=e.scope.resolve("lifetime"),this.constantGraphSampleSize=e.scope.resolve("graphSampleSize"),this.constantGraphNumSamples=e.scope.resolve("graphNumSamples"),this.constantInternalTex0=e.scope.resolve("internalTex0"),this.constantInternalTex1=e.scope.resolve("internalTex1"),this.constantInternalTex2=e.scope.resolve("internalTex2"),this.constantInternalTex3=e.scope.resolve("internalTex3"),this.constantEmitterMatrix=e.scope.resolve("emitterMatrix"),this.constantEmitterMatrixInv=e.scope.resolve("emitterMatrixInv"),this.constantNumParticles=e.scope.resolve("numParticles"),this.constantNumParticlesPot=e.scope.resolve("numParticlesPot"),this.constantLocalVelocityDivMult=e.scope.resolve("localVelocityDivMult"),this.constantVelocityDivMult=e.scope.resolve("velocityDivMult"),this.constantRotSpeedDivMult=e.scope.resolve("rotSpeedDivMult"),this.constantSeed=e.scope.resolve("seed"),this.constantStartAngle=e.scope.resolve("startAngle"),this.constantStartAngle2=e.scope.resolve("startAngle2"),this.constantOutBoundsMul=e.scope.resolve("outBoundsMul"),this.constantOutBoundsAdd=e.scope.resolve("outBoundsAdd"),this.constantInBoundsSize=e.scope.resolve("inBoundsSize"),this.constantInBoundsCenter=e.scope.resolve("inBoundsCenter"),this.constantMaxVel=e.scope.resolve("maxVel"),this.constantFaceTangent=e.scope.resolve("faceTangent"),this.constantFaceBinorm=e.scope.resolve("faceBinorm"),this.constantRadialSpeedDivMult=e.scope.resolve("radialSpeedDivMult")}_setInputBounds(){this.inBoundsSizeUniform[0]=this._emitter.prevWorldBoundsSize.x,this.inBoundsSizeUniform[1]=this._emitter.prevWorldBoundsSize.y,this.inBoundsSizeUniform[2]=this._emitter.prevWorldBoundsSize.z,this.constantInBoundsSize.setValue(this.inBoundsSizeUniform),this.inBoundsCenterUniform[0]=this._emitter.prevWorldBoundsCenter.x,this.inBoundsCenterUniform[1]=this._emitter.prevWorldBoundsCenter.y,this.inBoundsCenterUniform[2]=this._emitter.prevWorldBoundsCenter.z,this.constantInBoundsCenter.setValue(this.inBoundsCenterUniform)}randomize(){this.frameRandomUniform[0]=Math.random(),this.frameRandomUniform[1]=Math.random(),this.frameRandomUniform[2]=Math.random()}update(t,e,s,i,r){let a=this._emitter;t.setDrawStates(),this.randomize(),this.constantRadialSpeedDivMult.setValue(a.material.getParameter("radialSpeedDivMult").data),this.constantGraphSampleSize.setValue(1/a.precision),this.constantGraphNumSamples.setValue(a.precision),this.constantNumParticles.setValue(a.numParticles),this.constantNumParticlesPot.setValue(a.numParticlesPot),this.constantInternalTex0.setValue(a.internalTex0),this.constantInternalTex1.setValue(a.internalTex1),this.constantInternalTex2.setValue(a.internalTex2),this.constantInternalTex3.setValue(a.internalTex3);let o=a.meshInstance.node,l=o===null?x.ONE:o.localScale;if(a.pack8){this.worldBoundsMulUniform[0]=a.worldBoundsMul.x,this.worldBoundsMulUniform[1]=a.worldBoundsMul.y,this.worldBoundsMulUniform[2]=a.worldBoundsMul.z,this.constantOutBoundsMul.setValue(this.worldBoundsMulUniform),this.worldBoundsAddUniform[0]=a.worldBoundsAdd.x,this.worldBoundsAddUniform[1]=a.worldBoundsAdd.y,this.worldBoundsAddUniform[2]=a.worldBoundsAdd.z,this.constantOutBoundsAdd.setValue(this.worldBoundsAddUniform),this._setInputBounds();let p=a.maxVel*Math.max(Math.max(l.x,l.y),l.z);p=Math.max(p,1),this.constantMaxVel.setValue(p)}let h=o===null||a.localSpace?x.ZERO:o.getPosition(),f=o===null?W.IDENTITY:o.getWorldTransform();a.emitterShape===Ni?(rM.setFromMat4(e),this.constantSpawnBounds.setValue(rM.data),this.constantSpawnPosInnerRatio.setValue(s)):(this.constantSpawnBoundsSphere.setValue(a.emitterRadius),this.constantSpawnBoundsSphereInnerRatio.setValue(a.emitterRadius===0?0:a.emitterRadiusInner/a.emitterRadius)),this.constantInitialVelocity.setValue(a.initialVelocity),aM.setFromMat4(f),oM.invertMat4(f),this.emitterPosUniform[0]=h.x,this.emitterPosUniform[1]=h.y,this.emitterPosUniform[2]=h.z,this.constantEmitterPos.setValue(this.emitterPosUniform),this.constantFrameRandom.setValue(this.frameRandomUniform),this.constantDelta.setValue(i),this.constantRate.setValue(a.rate),this.constantRateDiv.setValue(a.rate2-a.rate),this.constantStartAngle.setValue(a.startAngle*R.DEG_TO_RAD),this.constantStartAngle2.setValue(a.startAngle2*R.DEG_TO_RAD),this.constantSeed.setValue(a.seed),this.constantLifetime.setValue(a.lifetime),this.emitterScaleUniform[0]=l.x,this.emitterScaleUniform[1]=l.y,this.emitterScaleUniform[2]=l.z,this.constantEmitterScale.setValue(this.emitterScaleUniform),this.constantEmitterMatrix.setValue(aM.data),this.constantEmitterMatrixInv.setValue(oM.data),this.constantLocalVelocityDivMult.setValue(a.localVelocityUMax),this.constantVelocityDivMult.setValue(a.velocityUMax),this.constantRotSpeedDivMult.setValue(a.rotSpeedUMax[0]);let u=a.swapTex?a.particleTexOUT:a.particleTexIN;u=a.beenReset?a.particleTexStart:u;let d=a.swapTex?a.particleTexIN:a.particleTexOUT;this.constantParticleTexIN.setValue(u),Qt(t,a.swapTex?a.rtParticleTexIN:a.rtParticleTexOUT,r?a.shaderParticleUpdateOnStop:a.loop?a.shaderParticleUpdateRespawn:a.shaderParticleUpdateNoRespawn),a.material.setParameter("particleTexOUT",u),a.material.setParameter("particleTexIN",d),a.beenReset=!1,a.swapTex=!a.swapTex,a.prevWorldBoundsSize.copy(a.worldBoundsSize),a.prevWorldBoundsCenter.copy(a.worldBounds.center),a.pack8&&this._setInputBounds()}};var nM=["NONE","VERTEX","MAP"],dI=class extends yi{generateKey(t){let s=`particle_${yi.definesHash(t.defines)}_`;for(let i in t)t.hasOwnProperty(i)&&(s+=t[i]);return s}createVertexDefines(t,e){let s=new Map(t.defines);return t.mesh&&s.set("USE_MESH",""),t.meshUv&&s.set("USE_MESH_UV",""),t.localSpace&&s.set("LOCAL_SPACE",""),t.screenSpace&&s.set("SCREEN_SPACE",""),t.animTex&&s.set("ANIMTEX",""),t.soft>0&&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;u<s.length;u++)f[u]=s[u]*r*255;s=f}return h.set(s),l.unlock(),l}function hM(c){return Math.max(Math.min(c,1),0)}var fM=new Ps([0,0,1,0]),uM=new Ps([0,1,1,1]),dM=new ki([0,0,1,0],[0,0,1,0],[0,0,1,0]),A6=new ki([0,1,1,1],[0,1,1,1],[0,1,1,1]),cl=2,py=4,hl=new Float32Array(3),eu=new W,pM=new x,my=new x,_y=new x,gy,xS;function Ie(c,t){xS[c]!==void 0&&xS[c]!==null?gy[c]=xS[c]:gy[c]=t}function _M(c,t,e){return(c*255<<16|t*255<<8|e*255)/(1<<24)}function mM(c,t){let e=c.length/3,s=new Array(e*4);for(let i=0;i<e;i++)s[i*4]=c[i*3],s[i*4+1]=c[i*3+1],s[i*4+2]=c[i*3+2],s[i*4+3]=_M(t[i*3],t[i*3+1],t[i*3+2]);return s}function C6(c,t){let e=new Array(t.length*4);for(let s=0;s<t.length;s++)e[s*4]=c[s*3],e[s*4+1]=c[s*3+1],e[s*4+2]=c[s*3+2],e[s*4+3]=t[s];return e}function P6(c,t,e,s,i){let r=new Array(c.length*4);for(let a=0;a<c.length;a++)r[a*4]=c[a],r[a*4+1]=t[a],r[a*4+2]=0,r[a*4+3]=_M(e[a],s[a],i[a]);return r}function w6(c,t){let e=new Array(c.length*4);for(let s=0;s<c.length;s++)e[s*4]=c[s],e[s*4+1]=t[s],e[s*4+2]=0,e[s*4+3]=0;return e}function I6(c){let t=Math.max(c.rate,c.rate2)*c.numParticles+c.lifetime;return Date.now()+t*1e3}function R6(c,t){let e=new Float32Array(c.length);for(let s=0;s<c.length;s++)e[s]=c[s]-t[s];return e}function su(c,t){let e=t.length,s=c.length/e;for(let i=0;i<s;i++)for(let r=0;r<e;r++){let a=Math.abs(c[i*e+r]);t[r]=Math.max(t[r],a)}}function b6(c,t){let e=t.length,s=c.length/e;for(let i=0;i<s;i++)for(let r=0;r<e;r++)c[i*e+r]/=t[r]===0?1:t[r],c[i*e+r]*=.5,c[i*e+r]+=.5}function tu(c,t,e){let s=R6(t,c);return su(s,e),b6(s,e),s}var D6=new et,Xp=class{constructor(t,e){n(this,"material",null);n(this,"internalTex0",null);n(this,"internalTex1",null);n(this,"internalTex2",null);n(this,"colorParam",null);this.graphicsDevice=t;let s=t,i=32;this.precision=i,this._addTimeTime=0,gy=this,xS=e,Ie("numParticles",1),this.numParticles>t.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;E<this.precision+1;E++){let y=Math.min(E,this.precision-1);for(let P=0;P<2;P++)g=u[P][y*3+0]*h+d[P],T=u[P][y*3+1]*h+p[P],C=u[P][y*3+2]*h+m[P],t=Math.min(g,t),e=Math.min(T,e),s=Math.min(C,s),i=Math.max(g,i),r=Math.max(T,r),a=Math.max(C,a),d[P]=g,p[P]=T,m[P]=C;for(let P=0;P<2;P++)S[P]+=h*Math.sqrt(f[P][y*3+0]*f[P][y*3+0]+f[P][y*3+1]*f[P][y*3+1]+f[P][y*3+2]*f[P][y*3+2]);_[0]+=this.qRadialSpeed[y]*h,_[1]+=this.qRadialSpeed2[y]*h,o=Math.max(o,Math.max(Math.abs(_[0]),Math.abs(_[1]))),l=Math.max(l,this.qScale[y])}this.emitterShape===Ni?(g=this.emitterExtents.x*.5,T=this.emitterExtents.y*.5,C=this.emitterExtents.z*.5):(g=this.emitterRadius,T=this.emitterRadius,C=this.emitterRadius);let v=Math.max(S[0],S[1]);my.x=t-l-g-o-v,my.y=e-l-T-o-v,my.z=s-l-C-o-v,_y.x=i+l+g+o+v,_y.y=r+l+T+o+v,_y.z=a+l+C+o+v,this.localBounds.setMinMax(my,_y)}rebuild(){let t=this.graphicsDevice;this.colorMap===null&&(this.colorMap=this.defaultParamTexture),this.spawnBounds=this.emitterShape===Ni?this.emitterExtents:this.emitterRadius,this.useCpu=this.useCpu||this.sort>up||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<this.numParticles;l++)this.vbToSort[l]=[0,0];this.particleDistance=new Float32Array(this.numParticles),this._gpuUpdater.randomize(),this.particleTex=new Float32Array(this.numParticlesPot*cl*py);let s=this.node===null||this.localSpace?x.ZERO:this.node.getPosition();this.emitterShape===Ni&&(this.node===null||this.localSpace?eu.setTRS(x.ZERO,$.IDENTITY,this.spawnBounds):eu.setTRS(x.ZERO,this.node.getRotation(),pM.copy(this.spawnBounds).mul(this.node.localScale)),hl[0]=this.emitterExtents.x!==0?this.emitterExtentsInner.x/this.emitterExtents.x:0,hl[1]=this.emitterExtents.y!==0?this.emitterExtentsInner.y/this.emitterExtents.y:0,hl[2]=this.emitterExtents.z!==0?this.emitterExtentsInner.z/this.emitterExtents.z:0);for(let l=0;l<this.numParticles;l++)this._cpuUpdater.calcSpawnPosition(this.particleTex,eu,hl,s,l),this.useCpu&&(this.particleTex[l*py+3+this.numParticlesPot*2*py]=1);this.particleTexStart=new Float32Array(this.numParticlesPot*cl*py);for(let l=0;l<this.particleTexStart.length;l++)this.particleTexStart[l]=this.particleTex[l];this.useCpu||(this.pack8?(this.particleTexIN=na(t,this.numParticlesPot,cl,this.particleTex,ce,1,!1),this.particleTexOUT=na(t,this.numParticlesPot,cl,this.particleTex,ce,1,!1),this.particleTexStart=na(t,this.numParticlesPot,cl,this.particleTexStart,ce,1,!1)):(this.particleTexIN=na(t,this.numParticlesPot,cl,this.particleTex),this.particleTexOUT=na(t,this.numParticlesPot,cl,this.particleTex),this.particleTexStart=na(t,this.numParticlesPot,cl,this.particleTexStart)),this.rtParticleTexIN=new me({colorBuffer:this.particleTexIN,depth:!1}),this.rtParticleTexOUT=new me({colorBuffer:this.particleTexOUT,depth:!1}),this.swapTex=!1);let i=new Map;this.localSpace&&i.set("LOCAL_SPACE",""),this.pack8&&i.set("PACK8",""),this.emitterShape===Ni&&i.set("EMITTERSHAPE_BOX","");let r=`Shape:${this.emitterShape}-Pack:${this.pack8}-Local:${this.localSpace}`,a={attributes:{vertex_position:ee},vertexChunk:"fullscreenQuadVS",fragmentChunk:"particle_simulationPS",fragmentDefines:i};a.uniqueName=`ParticleUpdateRespawn-${r}`,i.set("RESPAWN",""),this.shaderParticleUpdateRespawn=Se.createShader(t,a),i.delete("RESPAWN"),a.uniqueName=`ParticleUpdateNoRespawn-${r}`,i.set("NO_RESPAWN",""),this.shaderParticleUpdateNoRespawn=Se.createShader(t,a),i.delete("NO_RESPAWN"),a.uniqueName=`ParticleUpdateStop-${r}`,i.set("ON_STOP",""),this.shaderParticleUpdateOnStop=Se.createShader(t,a),this.numParticleVerts=this.useMesh?this.mesh.vertexBuffer.numVertices:4,this.numParticleIndices=this.useMesh?this.mesh.indexBuffer[0].numIndices:6,this._allocate(this.numParticles);let o=new _e(t);o.vertexBuffer=this.vertexBuffer,o.indexBuffer[0]=this.indexBuffer,o.primitive[0].type=Yt,o.primitive[0].base=0,o.primitive[0].count=this.numParticles*this.numParticleIndices,o.primitive[0].indexed=!0,this.material=this._createMaterial(),this.resetMaterial(),this.meshInstance=new we(o,this.material,this.node),this.meshInstance.pick=!1,this.meshInstance.updateKey(),this.meshInstance.cull=!0,this.localSpace?this.meshInstance.aabb.setFromTransformedAabb(this.worldBounds,this.node.getWorldTransform()):this.meshInstance.aabb.copy(this.worldBounds),this.meshInstance._updateAabb=!1,this.meshInstance.visible=e,this._setMaterialTextures(),this.resetTime(),this.addTime(0,!1),this.preWarm&&this.prewarm(this.lifetime)}_isAnimated(){return this.animNumFrames>=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;s<t;s++)this.qRotSpeed[s]*=R.DEG_TO_RAD,this.qRotSpeed2[s]*=R.DEG_TO_RAD;if(this.localVelocityUMax=new Float32Array(3),this.velocityUMax=new Float32Array(3),this.colorUMax=new Float32Array(3),this.rotSpeedUMax=[0],this.scaleUMax=[0],this.alphaUMax=[0],this.radialSpeedUMax=[0],this.qLocalVelocityDiv=tu(this.qLocalVelocity,this.qLocalVelocity2,this.localVelocityUMax),this.qVelocityDiv=tu(this.qVelocity,this.qVelocity2,this.velocityUMax),this.qColorDiv=tu(this.qColor,this.qColor2,this.colorUMax),this.qRotSpeedDiv=tu(this.qRotSpeed,this.qRotSpeed2,this.rotSpeedUMax),this.qScaleDiv=tu(this.qScale,this.qScale2,this.scaleUMax),this.qAlphaDiv=tu(this.qAlpha,this.qAlpha2,this.alphaUMax),this.qRadialSpeedDiv=tu(this.qRadialSpeed,this.qRadialSpeed2,this.radialSpeedUMax),this.pack8){let s=[0,0,0];su(this.qVelocity,s);let i=[0,0,0];su(this.qVelocity2,i);let r=[0,0,0];su(this.qLocalVelocity,r);let a=[0,0,0];su(this.qLocalVelocity2,a);let o=[0];su(this.qRadialSpeed,o);let l=[0];su(this.qRadialSpeed2,l);let h=Math.max(s[0],i[0]);h=Math.max(h,s[1]),h=Math.max(h,i[1]),h=Math.max(h,s[2]),h=Math.max(h,i[2]);let f=Math.max(r[0],a[0]);f=Math.max(f,r[1]),f=Math.max(f,a[1]),f=Math.max(f,r[2]),f=Math.max(f,a[2]);let u=Math.max(o[0],l[0]);this.maxVel=h+f+u}this.useCpu||(this.internalTex0=na(e,t,1,mM(this.qLocalVelocity,this.qLocalVelocityDiv)),this.internalTex1=na(e,t,1,mM(this.qVelocity,this.qVelocityDiv)),this.internalTex2=na(e,t,1,P6(this.qRotSpeed,this.qScale,this.qScaleDiv,this.qRotSpeedDiv,this.qAlphaDiv)),this.internalTex3=na(e,t,1,w6(this.qRadialSpeed,this.qRadialSpeedDiv))),this.colorParam=na(e,t,1,C6(this.qColor,this.qAlpha),st,1,!0)}_setMaterialTextures(){this.colorMap&&(this.material.setParameter("colorMap",this.colorMap),this.lighting&&this.normalMap&&this.material.setParameter("normalMap",this.normalMap))}_createMaterial(){let t=new dy(this);return t.name=`EmitterMaterial:${this.node.name}`,t.cull=0,t.alphaWrite=!1,t.blendType=this.blendType,t.depthWrite=this.depthWrite,t}resetMaterial(){let t=this.material;t.setParameter("stretch",this.stretch),this._isAnimated()&&(t.setParameter("animTexTilesParams",this.animTilesParams),t.setParameter("animTexParams",this.animParams),t.setParameter("animTexIndexParams",this.animIndexParams)),t.setParameter("colorMult",this.intensity),this.useCpu||(t.setParameter("internalTex0",this.internalTex0),t.setParameter("internalTex1",this.internalTex1),t.setParameter("internalTex2",this.internalTex2),t.setParameter("internalTex3",this.internalTex3)),t.setParameter("colorParam",this.colorParam),t.setParameter("numParticles",this.numParticles),t.setParameter("numParticlesPot",this.numParticlesPot),t.setParameter("lifetime",this.lifetime),t.setParameter("rate",this.rate),t.setParameter("rateDiv",this.rate2-this.rate),t.setParameter("seed",this.seed),t.setParameter("scaleDivMult",this.scaleUMax[0]),t.setParameter("alphaDivMult",this.alphaUMax[0]),t.setParameter("radialSpeedDivMult",this.radialSpeedUMax[0]),t.setParameter("graphNumSamples",this.precision),t.setParameter("graphSampleSize",1/this.precision),t.setParameter("emitterScale",new Float32Array([1,1,1])),this.pack8&&(this._gpuUpdater._setInputBounds(),t.setParameter("inBoundsSize",this._gpuUpdater.inBoundsSizeUniform),t.setParameter("inBoundsCenter",this._gpuUpdater.inBoundsCenterUniform),t.setParameter("maxVel",this.maxVel)),this.wrap&&this.wrapBounds&&(this.wrapBoundsUniform[0]=this.wrapBounds.x,this.wrapBoundsUniform[1]=this.wrapBounds.y,this.wrapBoundsUniform[2]=this.wrapBounds.z,t.setParameter("wrapBounds",this.wrapBoundsUniform)),this._setMaterialTextures(),this.depthSoftening>0&&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;d<this.mesh.vertexBuffer.format.elements.length;d++)if(this.mesh.vertexBuffer.format.elements[d].name===_t){h=this.mesh.vertexBuffer.format.elements[d].offset/4;break}}for(let d=0;d<e;d++){let p=Math.floor(d/this.numParticleVerts);if(this.useMesh){let m=d%this.numParticleVerts;a[d*6]=o[m*l],a[d*6+1]=o[m*l+1],a[d*6+2]=o[m*l+2],a[d*6+3]=p,a[d*6+4]=o[m*l+h+0],a[d*6+5]=1-o[m*l+h+1]}else{let m=d%4;a[d*4]=cM[m][0],a[d*4+1]=cM[m][1],a[d*4+2]=0,a[d*4+3]=p}}this.useCpu&&(this.vbCPU=new Float32Array(a),this.vbOld=new Float32Array(this.vbCPU.length)),this.vertexBuffer.unlock(),this.useMesh&&this.mesh.vertexBuffer.unlock();let f=0,u=new Uint32Array(this.indexBuffer.lock());if(this.useMesh){let d=this.mesh.indexBuffer[0];o=new Ef[d.format](d.lock())}for(let d=0;d<t;d++)if(this.useMesh)for(let p=0;p<this.numParticleIndices;p++)u[d*this.numParticleIndices+p]=o[p]+d*this.numParticleVerts;else{let p=d*4;u[f++]=p,u[f++]=p+1,u[f++]=p+2,u[f++]=p,u[f++]=p+2,u[f++]=p+3}this.indexBuffer.unlock(),this.useMesh&&this.mesh.indexBuffer[0].unlock()}}reset(){if(this.beenReset=!0,this.seed=Math.random(),this.material.setParameter("seed",this.seed),this.useCpu)for(let e=0;e<this.particleTexStart.length;e++)this.particleTex[e]=this.particleTexStart[e];else this._setMaterialTextures();this.resetWorldBounds(),this.resetTime();let t=this.loop;this.loop=!0,this.addTime(0,!1),this.loop=t,this.preWarm&&this.prewarm(this.lifetime)}prewarm(t){let e=t/this.lifetime,s=Math.min(Math.floor(e*this.precision),this.precision),i=t/s;for(let r=0;r<s;r++)this.addTime(i,!1)}resetTime(){this.endTime=I6(this)}finishFrame(){this.useCpu&&this.vertexBuffer.unlock()}addTime(t,e){let s=this.graphicsDevice;if(this.simTimeTotal+=t,this.calculateWorldBounds(),this._isAnimated()){let a=this.animTilesParams;a[0]=1/this.animTilesX,a[1]=1/this.animTilesY;let o=this.animParams;o[0]=this.animStartFrame,o[1]=this.animNumFrames*this.animSpeed,o[2]=this.animNumFrames-1,o[3]=this.animNumAnimations-1;let l=this.animIndexParams;l[0]=this.animIndex,l[1]=this.randomizeAnimIndex}this.scene&&this.camera!==this.scene._activeCamera&&(this.camera=this.scene._activeCamera,this.onChangeCamera()),this.emitterShape===Ni&&(hl[0]=this.emitterExtents.x!==0?this.emitterExtentsInner.x/this.emitterExtents.x:0,hl[1]=this.emitterExtents.y!==0?this.emitterExtentsInner.y/this.emitterExtents.y:0,hl[2]=this.emitterExtents.z!==0?this.emitterExtentsInner.z/this.emitterExtents.z:0,this.meshInstance.node===null?eu.setTRS(x.ZERO,$.IDENTITY,this.emitterExtents):eu.setTRS(x.ZERO,this.meshInstance.node.getRotation(),pM.copy(this.emitterExtents).mul(this.meshInstance.node.localScale)));let i,r=this.meshInstance.node===null?x.ONE:this.meshInstance.node.localScale;if(this.emitterScaleUniform[0]=r.x,this.emitterScaleUniform[1]=r.y,this.emitterScaleUniform[2]=r.z,this.material.setParameter("emitterScale",this.emitterScaleUniform),this.localSpace&&this.meshInstance.node&&(i=this.meshInstance.node.getPosition(),this.emitterPosUniform[0]=i.x,this.emitterPosUniform[1]=i.y,this.emitterPosUniform[2]=i.z,this.material.setParameter("emitterPos",this.emitterPosUniform)),this._compParticleFaceParams(),!this.useCpu)this._gpuUpdater.update(s,eu,hl,t,e);else{let a=new Float32Array(this.vertexBuffer.lock());this._cpuUpdater.update(a,this.vbToSort,this.particleTex,eu,hl,i,t,e)}this.loop||Date.now()>this.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); }
`;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); }
`;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); }
`;var mI=`
void write{funcName}({returnType} value) {
#if {defineGuard}
pcFragColor{index} = value;
#endif
}
`;var _I=`
fn write{funcName}(value: {returnType}) {
#if {defineGuard}
processOutput.{colorSlot} = value;
#endif
}
`;var Sy=`
vec3 getCenter() { return loadDataCenter().xyz; }
vec4 getColor() { return loadDataColor(); }
vec3 getScale() { return loadDataScale().xyz; }
vec4 getRotation() { return loadDataRotation(); }
`;var xy=`
fn getCenter() -> vec3f { return loadDataCenter().xyz; }
fn getColor() -> vec4f { return loadDataColor(); }
fn getScale() -> vec3f { return loadDataScale().xyz; }
fn getRotation() -> vec4f { return loadDataRotation(); }
`;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); }
`;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); }
`;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<uff>");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<i.length;r++){let a=i[r],o=Ad(a.format),l=a.name.charAt(0).toUpperCase()+a.name.slice(1),h=o.textureType??"";a.format===ke&&(h="texture_2d<uff>");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;a<t.length;a++){let o=t[a],l=r(o.format),h=o.name.charAt(0).toUpperCase()+o.name.slice(1),f=a===0?"color":`color${a}`,u=i.replace(Ty,h).replace(vy,l.returnType).replace(O6,String(a)).replace(F6,f).replace(PM,"1");s.push(u)}return s.join(`
`)}getOutputStubs(t){let e=this._device.isWebGPU,s=[],i=e?_I:mI,r=e?Ad:An;for(let a of t){let o=r(a.format),l=a.name.charAt(0).toUpperCase()+a.name.slice(1),h=i.replace(Ty,l).replace(vy,o.returnType).replace(PM,"0");s.push(h)}return s.join(`
`)}getStream(t){let e=this.streams.find(s=>s.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();
return vec3(uintBitsToFloat(cachedTransformA.r), uintBitsToFloat(cachedTransformA.g), uintBitsToFloat(cachedTransformA.b));
}
float getOpacity() {
return float(cachedTransformA.a >> 24u) / 255.0;
}
vec3 getColor() {
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 data = loadDataTransformB().x;
vec3 p = vec3(
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 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(
sx == 0.0 ? 0.0 : exp(sx * logRange + logMin),
sy == 0.0 ? 0.0 : exp(sy * logRange + logMin),
sz == 0.0 ? 0.0 : exp(sz * logRange + logMin)
);
}
`;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);
uint gBits = uint(rgb.g * (2047.0 / 4.0) + 0.5);
uint bBits = uint(rgb.b * (1023.0 / 4.0) + 0.5);
writeDataColor(uvec4(rBits | (gBits << 11u) | (bBits << 22u), 0u, 0u, 0u));
#ifndef GSPLAT_COLOR_ONLY
vec4 q = rotation;
if (q.w < 0.0) q = -q;
vec3 p = q.xyz * inversesqrt(1.0 + q.w);
uint aBitsQ = uint(clamp((p.x * 0.5 + 0.5) * 2047.0 + 0.5, 0.0, 2047.0));
uint bBitsQ = uint(clamp((p.y * 0.5 + 0.5) * 2047.0 + 0.5, 0.0, 2047.0));
uint cBitsQ = uint(clamp((p.z * 0.5 + 0.5) * 1023.0 + 0.5, 0.0, 1023.0));
uint packedQuat = aBitsQ | (bBitsQ << 11u) | (cBitsQ << 22u);
const float invLogRange = 255.0 / 21.0;
const float logMin = -12.0;
uint sxBits = scale.x < 1e-10 ? 0u : uint(clamp((log(scale.x) - logMin) * invLogRange + 0.5, 1.0, 255.0));
uint syBits = scale.y < 1e-10 ? 0u : uint(clamp((log(scale.y) - logMin) * invLogRange + 0.5, 1.0, 255.0));
uint szBits = scale.z < 1e-10 ? 0u : uint(clamp((log(scale.z) - logMin) * invLogRange + 0.5, 1.0, 255.0));
uint alphaBits = uint(clamp(color.a, 0.0, 1.0) * 255.0 + 0.5);
uint packedScaleAlpha = sxBits | (syBits << 8u) | (szBits << 16u) | (alphaBits << 24u);
writeDataTransformA(uvec4(floatBitsToUint(center.x), floatBitsToUint(center.y), floatBitsToUint(center.z), packedScaleAlpha));
writeDataTransformB(uvec4(packedQuat, 0u, 0u, 0u));
#endif
}
`;var RM=`
uvec4 cachedTransformA;
uvec2 cachedTransformB;
vec4 cachedColor;
vec3 getCenter() {
cachedTransformA = loadDataTransformA();
cachedTransformB = loadDataTransformB().xy;
return vec3(uintBitsToFloat(cachedTransformA.r), uintBitsToFloat(cachedTransformA.g), uintBitsToFloat(cachedTransformA.b));
}
float getOpacity() {
#ifdef GSPLAT_COLOR_FLOAT
cachedColor = loadDataColor();
#else
uvec4 packedColor = loadDataColor();
uint packed_rg = packedColor.r | (packedColor.g << 16u);
uint packed_ba = packedColor.b | (packedColor.a << 16u);
cachedColor = vec4(unpackHalf2x16(packed_rg), unpackHalf2x16(packed_ba));
#endif
return cachedColor.a;
}
vec3 getColor() {
return cachedColor.rgb;
}
vec4 getRotation() {
vec2 rotXY = unpackHalf2x16(cachedTransformA.a);
vec2 rotZscaleX = unpackHalf2x16(cachedTransformB.x);
vec3 rotXYZ = vec3(rotXY, rotZscaleX.x);
return vec4(rotXYZ, sqrt(max(0.0, 1.0 - dot(rotXYZ, rotXYZ)))).wxyz;
}
vec3 getScale() {
vec2 rotZscaleX = unpackHalf2x16(cachedTransformB.x);
vec2 scaleYZ = unpackHalf2x16(cachedTransformB.y);
return vec3(rotZscaleX.y, scaleYZ);
}
`;var bM=`
void writeSplat(vec3 center, vec4 rotation, vec3 scale, vec4 color) {
#ifdef GSPLAT_COLOR_UINT
uint packed_rg = packHalf2x16(color.rg);
uint packed_ba = packHalf2x16(color.ba);
writeDataColor(uvec4(
packed_rg & 0xFFFFu,
packed_rg >> 16u,
packed_ba & 0xFFFFu,
packed_ba >> 16u
));
#else
writeDataColor(color);
#endif
#ifndef GSPLAT_COLOR_ONLY
writeDataTransformA(uvec4(floatBitsToUint(center.x), floatBitsToUint(center.y), floatBitsToUint(center.z), packHalf2x16(rotation.xy)));
writeDataTransformB(uvec4(packHalf2x16(vec2(rotation.z, scale.x)), packHalf2x16(scale.yz), 0u, 0u));
#endif
}
`;var DM=`
var<private> cachedTransformA: vec4u;
fn getCenter() -> vec3f {
cachedTransformA = loadDataTransformA();
return vec3f(bitcast<f32>(cachedTransformA.r), bitcast<f32>(cachedTransformA.g), bitcast<f32>(cachedTransformA.b));
}
fn getOpacity() -> f32 {
return f32(cachedTransformA.a >> 24u) / 255.0;
}
fn getColor() -> vec3f {
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 data = loadDataTransformB().x;
let p = vec3f(
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 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(
select(exp(sx * logRange + logMin), 0.0, sx == 0.0),
select(exp(sy * logRange + logMin), 0.0, sy == 0.0),
select(exp(sz * logRange + logMin), 0.0, sz == 0.0)
);
}
`;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);
let gBits = u32(rgb.g * (2047.0 / 4.0) + 0.5);
let bBits = u32(rgb.b * (1023.0 / 4.0) + 0.5);
writeDataColor(vec4u(rBits | (gBits << 11u) | (bBits << 22u), 0u, 0u, 0u));
#ifndef GSPLAT_COLOR_ONLY
var q = rotation;
if (q.w < 0.0) { q = -q; }
let p = q.xyz * inverseSqrt(1.0 + q.w);
let aBitsQ = u32(clamp(p.x * 0.5 + 0.5, 0.0, 1.0) * 2047.0 + 0.5);
let bBitsQ = u32(clamp(p.y * 0.5 + 0.5, 0.0, 1.0) * 2047.0 + 0.5);
let cBitsQ = u32(clamp(p.z * 0.5 + 0.5, 0.0, 1.0) * 1023.0 + 0.5);
let packedQuat = aBitsQ | (bBitsQ << 11u) | (cBitsQ << 22u);
let invLogRange = 255.0 / 21.0;
let logMin = -12.0;
let sxBits = select(u32(clamp((log(scale.x) - logMin) * invLogRange + 0.5, 1.0, 255.0)), 0u, scale.x < 1e-10);
let syBits = select(u32(clamp((log(scale.y) - logMin) * invLogRange + 0.5, 1.0, 255.0)), 0u, scale.y < 1e-10);
let szBits = select(u32(clamp((log(scale.z) - logMin) * invLogRange + 0.5, 1.0, 255.0)), 0u, scale.z < 1e-10);
let alphaBits = u32(clamp(color.a, 0.0, 1.0) * 255.0 + 0.5);
let packedScaleAlpha = sxBits | (syBits << 8u) | (szBits << 16u) | (alphaBits << 24u);
writeDataTransformA(vec4u(bitcast<u32>(center.x), bitcast<u32>(center.y), bitcast<u32>(center.z), packedScaleAlpha));
writeDataTransformB(vec4u(packedQuat, 0u, 0u, 0u));
#endif
}
`;var MM=`
var<private> cachedTransformA: vec4u;
var<private> cachedTransformB: vec2u;
var<private> cachedColor: vec4f;
fn getCenter() -> vec3f {
cachedTransformA = loadDataTransformA();
cachedTransformB = loadDataTransformB().xy;
return vec3f(bitcast<f32>(cachedTransformA.r), bitcast<f32>(cachedTransformA.g), bitcast<f32>(cachedTransformA.b));
}
fn getOpacity() -> f32 {
#ifdef GSPLAT_COLOR_FLOAT
cachedColor = loadDataColor();
#else
let packedColor = loadDataColor();
let packed_rg = packedColor.r | (packedColor.g << 16u);
let packed_ba = packedColor.b | (packedColor.a << 16u);
cachedColor = vec4f(unpack2x16float(packed_rg), unpack2x16float(packed_ba));
#endif
return cachedColor.a;
}
fn getColor() -> vec3f {
return cachedColor.rgb;
}
fn getRotation() -> vec4f {
let rotXY = unpack2x16float(cachedTransformA.a);
let rotZscaleX = unpack2x16float(cachedTransformB.x);
let rotXYZ = vec3f(rotXY, rotZscaleX.x);
return vec4f(rotXYZ, sqrt(max(0.0, 1.0 - dot(rotXYZ, rotXYZ)))).wxyz;
}
fn getScale() -> vec3f {
let rotZscaleX = unpack2x16float(cachedTransformB.x);
let scaleYZ = unpack2x16float(cachedTransformB.y);
return vec3f(rotZscaleX.y, scaleYZ);
}
`;var OM=`
fn writeSplat(center: vec3f, rotation: vec4f, scale: vec3f, color: vec4f) {
writeDataColor(color);
#ifndef GSPLAT_COLOR_ONLY
writeDataTransformA(vec4u(bitcast<u32>(center.x), bitcast<u32>(center.y), bitcast<u32>(center.z), pack2x16float(rotation.xy)));
writeDataTransformB(vec4u(pack2x16float(vec2f(rotation.z, scale.x)), pack2x16float(scale.yz), 0u, 0u));
#endif
}
`;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<c.length;u++)f[u]=0;for(let u=0;u<e;u++){let d=t[u*3],p=t[u*3+1],m=t[u*3+2];i.set(c[d*3],c[d*3+1],c[d*3+2]),r.set(c[p*3],c[p*3+1],c[p*3+2]),a.set(c[m*3],c[m*3+1],c[m*3+2]),o.sub2(r,i),l.sub2(a,i),h.cross(o,l).normalize(),f[d*3]+=h.x,f[d*3+1]+=h.y,f[d*3+2]+=h.z,f[p*3]+=h.x,f[p*3+1]+=h.y,f[p*3+2]+=h.z,f[m*3]+=h.x,f[m*3+1]+=h.y,f[m*3+2]+=h.z}for(let u=0;u<s;u++){let d=f[u*3],p=f[u*3+1],m=f[u*3+2],_=1/Math.sqrt(d*d+p*p+m*m);f[u*3]*=_,f[u*3+1]*=_,f[u*3+2]*=_}return f},Zs=(c,t,e,s)=>{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<i;E++){let y=s[E*3],P=s[E*3+1],A=s[E*3+2];a.set(c[y*3],c[y*3+1],c[y*3+2]),o.set(c[P*3],c[P*3+1],c[P*3+2]),l.set(c[A*3],c[A*3+1],c[A*3+2]),h.set(e[y*2],e[y*2+1]),f.set(e[P*2],e[P*2+1]),u.set(e[A*2],e[A*2+1]);let w=o.x-a.x,I=l.x-a.x,D=o.y-a.y,O=l.y-a.y,G=o.z-a.z,M=l.z-a.z,H=f.x-h.x,U=u.x-h.x,L=f.y-h.y,b=u.y-h.y,N=H*b-U*L;if(N===0)d.set(0,1,0),p.set(1,0,0);else{let k=1/N;d.set((b*w-L*I)*k,(b*D-L*O)*k,(b*G-L*M)*k),p.set((H*I-U*w)*k,(H*O-U*D)*k,(H*M-U*G)*k)}m[y*3+0]+=d.x,m[y*3+1]+=d.y,m[y*3+2]+=d.z,m[P*3+0]+=d.x,m[P*3+1]+=d.y,m[P*3+2]+=d.z,m[A*3+0]+=d.x,m[A*3+1]+=d.y,m[A*3+2]+=d.z,_[y*3+0]+=p.x,_[y*3+1]+=p.y,_[y*3+2]+=p.z,_[P*3+0]+=p.x,_[P*3+1]+=p.y,_[P*3+2]+=p.z,_[A*3+0]+=p.x,_[A*3+1]+=p.y,_[A*3+2]+=p.z}let g=new x,T=new x,C=new x,v=new x;for(let E=0;E<r;E++){C.set(t[E*3],t[E*3+1],t[E*3+2]),g.set(m[E*3],m[E*3+1],m[E*3+2]),T.set(_[E*3],_[E*3+1],_[E*3+2]);let y=C.dot(g);v.copy(C).mulScalar(y),v.sub2(g,v).normalize(),S[E*4]=v.x,S[E*4+1]=v.y,S[E*4+2]=v.z,v.cross(C,g),S[E*4+3]=v.dot(T)<0?-1:1}return S};var Jt=class{constructor(){n(this,"positions");n(this,"normals");n(this,"colors");n(this,"uvs");n(this,"uvs1");n(this,"blendIndices");n(this,"blendWeights");n(this,"tangents");n(this,"indices")}calculateNormals(){this.normals=Kp(this.positions,this.indices)}calculateTangents(){this.tangents=Zs(this.positions,this.normals,this.uvs,this.indices)}};var gI=8/64,FM=1-gI*2,ci=class extends Jt{constructor(t={}){super();let e=t.halfExtents??new x(.5,.5,.5),s=t.widthSegments??1,i=t.lengthSegments??1,r=t.heightSegments??1,a=t.yOffset??0,o=-e.y+a,l=e.y+a,h=[new x(-e.x,o,e.z),new x(e.x,o,e.z),new x(e.x,l,e.z),new x(-e.x,l,e.z),new x(e.x,o,-e.z),new x(-e.x,o,-e.z),new x(-e.x,l,-e.z),new x(e.x,l,-e.z)],f=[[0,1,3],[4,5,7],[3,2,6],[1,0,4],[1,4,2],[5,0,6]],u=[[0,0,1],[0,0,-1],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0]],d={FRONT:0,BACK:1,TOP:2,BOTTOM:3,RIGHT:4,LEFT:5},p=[],m=[],_=[],S=[],g=[],T=0,C=(v,E,y)=>{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),D<E&&O<y&&(g.push(T+y+1,T+1,T),g.push(T+y+1,T+y+2,T+1)),T++}};C(d.FRONT,s,r),C(d.BACK,s,r),C(d.TOP,s,i),C(d.BOTTOM,s,i),C(d.RIGHT,i,r),C(d.LEFT,i,r),this.positions=p,this.normals=m,this.uvs=_,this.uvs1=S,this.indices=g,t.calculateTangents&&(this.tangents=Zs(p,m,_,g))}};var wr=class extends Jt{constructor(t={}){super();let e=t.radius??.5,s=t.latitudeBands??16,i=t.longitudeBands??16,r=[],a=[],o=[],l=[];for(let h=0;h<=s;h++){let f=h*Math.PI/s,u=Math.sin(f),d=Math.cos(f);for(let p=0;p<=i;p++){let m=p*2*Math.PI/i-Math.PI/2,_=Math.sin(m),g=Math.cos(m)*u,T=d,C=_*u,v=1-p/i,E=1-h/s;r.push(g*e,T*e,C*e),a.push(g,T,C),o.push(v,1-E)}}for(let h=0;h<s;++h)for(let f=0;f<i;++f){let u=h*(i+1)+f,d=u+i+1;l.push(u+1,d,u),l.push(u+1,d+1,d)}this.positions=r,this.normals=a,this.uvs=o,this.uvs1=o,this.indices=l,t.calculateTangents&&(this.tangents=Zs(r,a,o,l))}};var jp=class extends wr{constructor(t={}){let s=t.latitudeBands??16,i=t.longitudeBands??16;super({radius:.5,latitudeBands:s,longitudeBands:i});let r=.1,a=.95,o=a*a,l=this.positions;for(let h=0;h<l.length;h+=3){let f=l[h]/.5,u=l[h+1]/.5,d=l[h+2]/.5;u<0&&(u*=.3,f*f+d*d<o&&(u=-r)),u+=r,u*=.5,l[h+1]=u}}};var Ey=class c{static create(t,e){switch(e){case vw:return c.box(t);case Tw:return c.dome(t)}return c.infinite(t)}static infinite(t){return _e.fromGeometry(t,new ci(t))}static box(t){return _e.fromGeometry(t,new ci({yOffset:.5}))}static dome(t){let e=new jp({latitudeBands:50,longitudeBands:50});return e.normals=void 0,e.uvs=void 0,_e.fromGeometry(t,e)}};var Ay=class{constructor(t,e,s,i,r){n(this,"meshInstance",null);n(this,"_depthWrite",!1);let a=new ct({uniqueName:"SkyMaterial",vertexGLSL:ne.get(t,fe).get("skyboxVS"),fragmentGLSL:ne.get(t,fe).get("skyboxPS"),vertexWGSL:ne.get(t,se).get("skyboxVS"),fragmentWGSL:ne.get(t,se).get("skyboxPS"),attributes:{aPosition:ee}});a.setDefine("{SKYBOX_DECODE_FNC}",li.decodeFunc(i.encoding)),r!==Jn&&a.setDefine("SKYMESH",""),i.cubemap&&a.setDefine("SKY_CUBEMAP",""),a.setParameter("skyboxHighlightMultiplier",e.skyboxHighlightMultiplier),i.cubemap?a.setParameter("texture_cubeMap",i):(a.setParameter("texture_envAtlas",i),a.setParameter("mipLevel",e.skyboxMip)),a.cull=2,a.depthWrite=this._depthWrite;let o=e.layers.getLayerById($n);if(o){let l=Ey.create(t,r),h=new we(l,a,s);this.meshInstance=h,h.cull=!1,h.pick=!1,o.addMeshInstances([h]),this.skyLayer=o}}destroy(){this.meshInstance&&(this.skyLayer&&this.skyLayer.removeMeshInstances([this.meshInstance]),this.meshInstance.destroy(),this.meshInstance=null)}set depthWrite(t){this._depthWrite=t,this.meshInstance&&(this.meshInstance.material.depthWrite=t)}get depthWrite(){return this._depthWrite}};var qp=class{constructor(t){n(this,"_type",Jn);n(this,"_center",new x(0,1,0));n(this,"skyMesh",null);n(this,"_depthWrite",!1);n(this,"_fisheye",0);n(this,"_fisheyeProj",null);n(this,"node",new Pe("SkyMeshNode"));this.device=t.device,this.scene=t,this.center=new x(0,1,0),this.centerArray=new Float32Array(3),this.projectedSkydomeCenterId=this.device.scope.resolve("projectedSkydomeCenter"),this._preRenderEvt=t.on("prerender",this._onPreRender,this)}destroy(){this._preRenderEvt.off(),this.resetSkyMesh()}applySettings(t){this.type=t.skyType??Jn,this.node.setLocalPosition(new x(t.skyMeshPosition??[0,0,0])),this.node.setLocalEulerAngles(new x(t.skyMeshRotation??[0,0,0])),this.node.setLocalScale(new x(t.skyMeshScale??[1,1,1])),t.skyCenter&&(this._center=new x(t.skyCenter))}set type(t){this._type!==t&&(this._type=t,this.scene.updateShaders=!0,this.updateSkyMesh())}get type(){return this._type}set center(t){this._center.copy(t)}get center(){return this._center}set depthWrite(t){this._depthWrite!==t&&(this._depthWrite=t,this.skyMesh&&(this.skyMesh.depthWrite=t))}get depthWrite(){return this._depthWrite}set fisheye(t){if(this._fisheye!==t){let e=this._fisheye>0;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;a<i;a++){let o=t[a];s.push(o.x,o.y,o.z)}let r=this.colors;if(e.length)for(let a=0;a<i;a++){let o=e[a];r.push(o.r,o.g,o.b,o.a)}else for(let a=0;a<i;a++)r.push(e.r,e.g,e.b,e.a)}addLinesArrays(t,e){let s=this.positions;for(let r=0;r<t.length;r+=3)s.push(t[r],t[r+1],t[r+2]);let i=this.colors;if(e.length)for(let r=0;r<e.length;r+=4)i.push(e[r],e[r+1],e[r+2],e[r+3]);else{let r=t.length/3;for(let a=0;a<r;a++)i.push(e.r,e.g,e.b,e.a)}}onPreRender(t,e){this.positions.length>0&&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;
void main(void) {
gl_Position = matrix_model * vec4(vertex_position, 0, 1);
uv0 = vertex_position.xy + 0.5;
}
`,vertexWGSL:`
attribute vertex_position: vec2f;
uniform matrix_model: mat4x4f;
varying uv0: vec2f;
@vertex fn vertexMain(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
output.position = uniform.matrix_model * vec4f(input.vertex_position, 0.0, 1.0);
output.uv0 = input.vertex_position.xy + vec2f(0.5);
return output;
}
`,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 = ${e}(texture2D(colorMap, uv0));
gl_FragColor = vec4(gammaCorrectOutput(linearColor), 1);
}
`,`
#include "gammaPS"
varying uv0: vec2f;
var colorMap: texture_2d<f32>;
var colorMapSampler: sampler;
@fragment fn fragmentMain(input : FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let sampledTex = textureSample(colorMap, colorMapSampler, input.uv0);
let linearColor: vec3f = ${e}(sampledTex);
output.color = vec4f(gammaCorrectOutput(linearColor), 1.0);
return output;
}
`)}getUnfilterableTextureShaderDesc(){return this.getShaderDesc("textureShaderUnfilterable",`
varying vec2 uv0;
uniform highp sampler2D colorMap;
void main (void) {
ivec2 uv = ivec2(uv0 * textureSize(colorMap, 0));
gl_FragColor = vec4(texelFetch(colorMap, uv, 0).xyz, 1);
}
`,`
varying uv0: vec2f;
var colorMap: texture_2d<uff>;
@fragment fn fragmentMain(input : FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let uv : vec2<i32> = vec2<i32>(input.uv0 * vec2f(textureDimensions(colorMap, 0)));
let fetchedColor : vec4f = textureLoad(colorMap, uv, 0);
output.color = vec4f(fetchedColor.xyz, 1.0);
return output;
}
`)}getDepthTextureShaderDesc(){return this.getShaderDesc("depthTextureShader",`
#include "screenDepthPS"
#include "gammaPS"
varying vec2 uv0;
void main() {
float depth = getLinearScreenDepth(getImageEffectUV(uv0)) * camera_params.x;
gl_FragColor = vec4(gammaCorrectOutput(vec3(depth)), 1.0);
}
`,`
#include "screenDepthPS"
#include "gammaPS"
varying uv0: vec2f;
@fragment fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let depth: f32 = getLinearScreenDepth(getImageEffectUV(input.uv0)) * uniform.camera_params.x;
output.color = vec4f(gammaCorrectOutput(vec3f(depth)), 1.0);
return output;
}
`)}getQuadMesh(){return this.quadMesh||(this.quadMesh=new _e(this.device),this.quadMesh.setPositions([-.5,-.5,0,.5,-.5,0,-.5,.5,0,.5,.5,0]),this.quadMesh.update(Ks)),this.quadMesh}drawMesh(t,e,s,i,r){if(!i){let o=this.getGraphNode(e);i=new we(s,t,o)}let a=this.layerMeshInstances.get(r);a||(a=[],this.layerMeshInstances.set(r,a)),a.push(i)}drawWireAlignedBox(t,e,s,i,r,a){if(a){let l=(h,f,u)=>{$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<i;f++){let u=Math.sin(l),d=Math.cos(l);l+=o;let p=Math.sin(l),m=Math.cos(l);la.push(t.x+e*u,t.y,t.z+e*d),la.push(t.x+e*p,t.y,t.z+e*m),la.push(t.x+e*u,t.y+e*d,t.z),la.push(t.x+e*p,t.y+e*m,t.z),la.push(t.x,t.y+e*u,t.z+e*d),la.push(t.x,t.y+e*p,t.z+e*m)}this.getBatch(a,r).addLinesArrays(la,s),la.length=0}getGraphNode(t){let e=new Pe("ImmediateDebug");return e.worldTransform=t,e._dirtyWorld=e._dirtyNormal=!1,e}onPreRenderLayer(t,e,s){if(this.batchesMap.forEach((i,r)=>{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;r<i.length;r++)e.push(i[r]);i.length=0}}}onPostRender(){this.allBatches.forEach(t=>t.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<t;i++){let r=this._meshes[i];r&&r.destroy()}let e=this._frameKeys.length;this._meshes=new Array(e);let s=this.renderMode===It||this._renderMode===Rt?this._create9SliceMesh:this._createSimpleMesh;for(let i=0;i<e;i++){let r=this._atlas.frames[this._frameKeys[i]];this._meshes[i]=r?s.call(this,r):null}this.fire("set:meshes")}_createSimpleMesh(t){let e=t.rect,s=this._atlas.texture.width,i=this._atlas.texture.height,r=e.z/this._pixelsPerUnit,a=e.w/this._pixelsPerUnit,o=t.pivot.x,l=t.pivot.y,h=[-o*r,-l*a,0,(1-o)*r,-l*a,0,(1-o)*r,(1-l)*a,0,-o*r,(1-l)*a,0],f=e.x/s,u=1-e.y/i,d=(e.x+e.z)/s,p=1-(e.y+e.w)/i,m=[f,u,d,u,d,p,f,p],_=new Jt;return _.positions=h,_.normals=N6,_.uvs=m,_.indices=B6,_e.fromGeometry(this._device,_)}_create9SliceMesh(){let t=B.ONE,e=3,s=3,i=[],r=[],a=[],o=[],l=0;for(let f=0;f<=e;f++){let u=f===0||f===e?0:1;for(let d=0;d<=s;d++){let p=-t.x+2*t.x*(f<=1?0:3)/e,m=0,_=-(-t.y+2*t.y*(d<=1?0:3)/s),S=d===0||d===s?0:1;i.push(-p,m,_),r.push(0,1,0),a.push(u,S),f<e&&d<s&&(o.push(l+s+1,l+1,l),o.push(l+s+1,l+s+2,l+1)),l++}}let h=new Jt;return h.positions=i,h.normals=r,h.uvs=a,h.indices=o,_e.fromGeometry(this._device,h)}_onSetFrames(t){this._updatingProperties?this._meshesDirty=!0:this._createMeshes()}_onFrameChanged(t,e){let s=this._frameKeys.indexOf(t);s<0||(e?this.renderMode===Ti&&(this._meshes[s]=this._createSimpleMesh(e)):this._meshes[s]=null,this.fire("set:meshes"))}_onFrameRemoved(t){let e=this._frameKeys.indexOf(t);e<0||(this._meshes[e]=null,this.fire("set:meshes"))}startUpdate(){this._updatingProperties=!0,this._meshesDirty=!1}endUpdate(){this._updatingProperties=!1,this._meshesDirty&&this._atlas&&this._frameKeys&&this._createMeshes(),this._meshesDirty=!1}destroy(){for(let t of this._meshes)t&&t.destroy();this._meshes.length=0}};var Jp=class extends J{constructor(){super(),this._texture=null,this._frames=null}set texture(t){this._texture=t,this.fire("set:texture",t)}get texture(){return this._texture}set frames(t){this._frames=t,this.fire("set:frames",t)}get frames(){return this._frames}setFrame(t,e){let s=this._frames[t];s?(s.rect.copy(e.rect),s.pivot.copy(e.pivot),s.border.copy(e.border)):(s={rect:e.rect.clone(),pivot:e.pivot.clone(),border:e.border.clone()},this._frames[t]=s),this.fire("set:frame",t.toString(),s)}removeFrame(t){let e=this._frames[t];e&&(delete this._frames[t],this.fire("remove:frame",t.toString(),e))}destroy(){this._texture&&this._texture.destroy()}};var fl=class{constructor(t,e,s,i){this.time=t,this.position=e,this.rotation=s,this.scale=i}},ul=class{constructor(){this._name="",this._keys=[]}},iu=class{constructor(){n(this,"name","");n(this,"duration",0);this._nodes=[],this._nodeDict={}}getNode(t){return this._nodeDict[t]}addNode(t){this._nodes.push(t),this._nodeDict[t._name]=t}get nodes(){return this._nodes}};var SI=class{constructor(){this._written=!1,this._name="",this._keyFrames=[],this._quat=new $,this._pos=new x,this._scale=new x,this._targetNode=null}getTarget(){return this._targetNode}setTarget(t){this._targetNode=t}},Hc=class{constructor(t){n(this,"looping",!0);this._animation=null,this._time=0,this._interpolatedKeys=[],this._interpolatedKeyDict={},this._currKeyIndices={},this.graph=null;let e=s=>{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;r<s._children.length;r++)e(s._children[r])};e(t)}set animation(t){this._animation=t,this.currentTime=0}get animation(){return this._animation}set currentTime(t){this._time=t;let e=this._interpolatedKeys.length;for(let s=0;s<e;s++){let r=this._interpolatedKeys[s]._name;this._currKeyIndices[r]=0}this.addTime(0),this.updateGraph()}get currentTime(){return this._time}get numNodes(){return this._interpolatedKeys.length}addTime(t){if(this._animation!==null){let e=this._animation._nodes,s=this._animation.duration;if(this._time===s&&!this.looping)return;if(this._time+=t,this._time>s){this._time=this.looping?0:s;for(let r=0;r<e.length;r++){let o=e[r]._name;this._currKeyIndices[o]=0}}else if(this._time<0){this._time=this.looping?s:0;for(let r=0;r<e.length;r++){let a=e[r],o=a._name;this._currKeyIndices[o]=a._keys.length-2}}let i=t>=0?1:-1;for(let r=0;r<e.length;r++){let a=e[r],o=a._name,l=a._keys,h=this._interpolatedKeyDict[o];if(h===void 0)continue;let f=!1;if(l.length!==1)for(let u=this._currKeyIndices[o];u<l.length-1&&u>=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<i;r++){let a=t._interpolatedKeys[r],o=e._interpolatedKeys[r],l=this._interpolatedKeys[r];a._written&&o._written?(l._quat.slerp(a._quat,e._interpolatedKeys[r]._quat,s),l._pos.lerp(a._pos,e._interpolatedKeys[r]._pos,s),l._scale.lerp(a._scale,o._scale,s),l._written=!0):a._written?(l._quat.copy(a._quat),l._pos.copy(a._pos),l._scale.copy(a._scale),l._written=!0):o._written&&(l._quat.copy(o._quat),l._pos.copy(o._pos),l._scale.copy(o._scale),l._written=!0)}}setGraph(t){if(this.graph=t,t)for(let e=0;e<this._interpolatedKeys.length;e++){let s=this._interpolatedKeys[e],i=t.findByName(s._name);this._interpolatedKeys[e].setTarget(i)}else for(let e=0;e<this._interpolatedKeys.length;e++)this._interpolatedKeys[e].setTarget(null)}updateGraph(){if(this.graph)for(let t=0;t<this._interpolatedKeys.length;t++){let e=this._interpolatedKeys[t];if(e._written){let s=e.getTarget();s.localPosition.copy(e._pos),s.localRotation.copy(e._quat),s.localScale.copy(e._scale),s._dirtyLocal||s._dirtifyLocal(),e._written=!1}}}};var NM=`
@group(0) @binding(0) var<storage, read_write> items: array<u32>;
@group(0) @binding(1) var<storage, read_write> blockSums: array<u32>;
struct PrefixSumUniforms {
elementCount: u32
};
@group(0) @binding(2) var<uniform> uniforms: PrefixSumUniforms;
const WORKGROUP_SIZE_X: u32 = {WORKGROUP_SIZE_X}u;
const WORKGROUP_SIZE_Y: u32 = {WORKGROUP_SIZE_Y}u;
const THREADS_PER_WORKGROUP: u32 = {THREADS_PER_WORKGROUP}u;
const ITEMS_PER_WORKGROUP: u32 = {ITEMS_PER_WORKGROUP}u;
var<workgroup> temp: array<u32, ITEMS_PER_WORKGROUP * 2>;
@compute @workgroup_size(WORKGROUP_SIZE_X, WORKGROUP_SIZE_Y, 1)
fn reduce_downsweep(
@builtin(workgroup_id) w_id: vec3<u32>,
@builtin(num_workgroups) w_dim: vec3<u32>,
@builtin(local_invocation_index) TID: u32,
) {
let WORKGROUP_ID = w_id.x + w_id.y * w_dim.x;
let WID = WORKGROUP_ID * THREADS_PER_WORKGROUP;
let GID = WID + TID;
let ELM_TID = TID * 2;
let ELM_GID = GID * 2;
temp[ELM_TID] = select(items[ELM_GID], 0u, ELM_GID >= uniforms.elementCount);
temp[ELM_TID + 1u] = select(items[ELM_GID + 1u], 0u, ELM_GID + 1u >= uniforms.elementCount);
var offset: u32 = 1u;
for (var d: u32 = ITEMS_PER_WORKGROUP >> 1u; d > 0u; d >>= 1u) {
workgroupBarrier();
if (TID < d) {
var ai: u32 = offset * (ELM_TID + 1u) - 1u;
var bi: u32 = offset * (ELM_TID + 2u) - 1u;
temp[bi] += temp[ai];
}
offset *= 2u;
}
if (TID == 0u) {
let last_offset = ITEMS_PER_WORKGROUP - 1u;
blockSums[WORKGROUP_ID] = temp[last_offset];
temp[last_offset] = 0u;
}
for (var d: u32 = 1u; d < ITEMS_PER_WORKGROUP; d *= 2u) {
offset >>= 1u;
workgroupBarrier();
if (TID < d) {
var ai: u32 = offset * (ELM_TID + 1u) - 1u;
var bi: u32 = offset * (ELM_TID + 2u) - 1u;
let t: u32 = temp[ai];
temp[ai] = temp[bi];
temp[bi] += t;
}
}
workgroupBarrier();
if (ELM_GID < uniforms.elementCount) {
items[ELM_GID] = temp[ELM_TID];
}
if (ELM_GID + 1u < uniforms.elementCount) {
items[ELM_GID + 1u] = temp[ELM_TID + 1u];
}
}
@compute @workgroup_size(WORKGROUP_SIZE_X, WORKGROUP_SIZE_Y, 1)
fn add_block_sums(
@builtin(workgroup_id) w_id: vec3<u32>,
@builtin(num_workgroups) w_dim: vec3<u32>,
@builtin(local_invocation_index) TID: u32,
) {
let WORKGROUP_ID = w_id.x + w_id.y * w_dim.x;
let WID = WORKGROUP_ID * THREADS_PER_WORKGROUP;
let GID = WID + TID;
let ELM_ID = GID * 2u;
if (ELM_ID >= uniforms.elementCount) {
return;
}
let blockSum = blockSums[WORKGROUP_ID];
items[ELM_ID] += blockSum;
if (ELM_ID + 1u >= uniforms.elementCount) {
return;
}
items[ELM_ID + 1u] += blockSum;
}
`;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;a<this.passes.length;a++){let o=Math.ceil(r/Ry),{x:l,y:h}=this.findOptimalDispatchSize(o);if(this.passes[a].count=r,this.passes[a].dispatchX=l,this.passes[a].dispatchY=h,r=o,o<=1)break}}destroyPasses(){for(let t of this.passes)t.blockSumBuffer?.destroy();this.passes.length=0}_countPassesNeeded(t){let e=0,s=t;for(;s>0;){e++;let i=Math.ceil(s/Ry);if(i<=1)break;s=i}return e}dispatch(t){for(let e=0;e<this.passes.length;e++){let s=this.passes[e];s.scanCompute.setParameter("elementCount",s.count),s.scanCompute.setupDispatch(s.dispatchX,s.dispatchY,1),t.computeDispatch([s.scanCompute],"PrefixSumScan")}for(let e=this.passes.length-1;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<storage, read> input: array<u32>;
@group(0) @binding(1) var<storage, read_write> block_sums: array<u32>;
struct RadixSortUniforms {
workgroupCount: u32,
elementCount: u32
};
@group(0) @binding(2) var<uniform> uniforms: RadixSortUniforms;
#ifdef USE_INDIRECT_SORT
@group(0) @binding(3) var<storage, read> sortElementCount: array<u32>;
#endif
const THREADS_PER_WORKGROUP: u32 = {THREADS_PER_WORKGROUP}u;
const WORKGROUP_SIZE_X: u32 = {WORKGROUP_SIZE_X}u;
const WORKGROUP_SIZE_Y: u32 = {WORKGROUP_SIZE_Y}u;
const CURRENT_BIT: u32 = {CURRENT_BIT}u;
const ELEMENTS_PER_THREAD: u32 = {ELEMENTS_PER_THREAD}u;
const ELEMENTS_PER_WORKGROUP: u32 = THREADS_PER_WORKGROUP * ELEMENTS_PER_THREAD;
var<workgroup> histogram: array<atomic<u32>, 16>;
@compute @workgroup_size(WORKGROUP_SIZE_X, WORKGROUP_SIZE_Y, 1)
fn main(
@builtin(workgroup_id) w_id: vec3<u32>,
@builtin(num_workgroups) w_dim: vec3<u32>,
@builtin(local_invocation_index) TID: u32,
) {
let WORKGROUP_ID = w_id.x + w_id.y * w_dim.x;
let WID = WORKGROUP_ID * ELEMENTS_PER_WORKGROUP;
if (TID < 16u) {
atomicStore(&histogram[TID], 0u);
}
workgroupBarrier();
#ifdef USE_INDIRECT_SORT
let elementCount = sortElementCount[0];
#else
let elementCount = uniforms.elementCount;
#endif
for (var r = 0u; r < ELEMENTS_PER_THREAD; r++) {
let GID = WID + r * THREADS_PER_WORKGROUP + TID;
let is_valid = GID < elementCount && WORKGROUP_ID < uniforms.workgroupCount;
if (is_valid) {
let elm = input[GID];
let digit = (elm >> CURRENT_BIT) & 0xFu;
atomicAdd(&histogram[digit], 1u);
}
}
workgroupBarrier();
if (TID < 16u && WORKGROUP_ID < uniforms.workgroupCount) {
block_sums[TID * uniforms.workgroupCount + WORKGROUP_ID] = atomicLoad(&histogram[TID]);
}
}
`;var GM=`
@group(0) @binding(0) var<storage, read> inputKeys: array<u32>;
@group(0) @binding(1) var<storage, read_write> outputKeys: array<u32>;
@group(0) @binding(2) var<storage, read> prefix_block_sum: array<u32>;
@group(0) @binding(3) var<storage, read> inputValues: array<u32>;
@group(0) @binding(4) var<storage, read_write> outputValues: array<u32>;
struct RadixSortUniforms {
workgroupCount: u32,
elementCount: u32
};
@group(0) @binding(5) var<uniform> uniforms: RadixSortUniforms;
#ifdef USE_INDIRECT_SORT
@group(0) @binding(6) var<storage, read> sortElementCount: array<u32>;
#endif
const THREADS_PER_WORKGROUP: u32 = {THREADS_PER_WORKGROUP}u;
const WORKGROUP_SIZE_X: u32 = {WORKGROUP_SIZE_X}u;
const WORKGROUP_SIZE_Y: u32 = {WORKGROUP_SIZE_Y}u;
const CURRENT_BIT: u32 = {CURRENT_BIT}u;
const IS_FIRST_PASS: u32 = {IS_FIRST_PASS}u;
const IS_LAST_PASS: u32 = {IS_LAST_PASS}u;
const ELEMENTS_PER_THREAD: u32 = {ELEMENTS_PER_THREAD}u;
const ELEMENTS_PER_WORKGROUP: u32 = THREADS_PER_WORKGROUP * ELEMENTS_PER_THREAD;
var<workgroup> digit_masks: array<atomic<u32>, 128>;
var<workgroup> digit_offsets: array<u32, 16>;
@compute @workgroup_size(WORKGROUP_SIZE_X, WORKGROUP_SIZE_Y, 1)
fn main(
@builtin(workgroup_id) w_id: vec3<u32>,
@builtin(num_workgroups) w_dim: vec3<u32>,
@builtin(local_invocation_index) TID: u32,
) {
let WORKGROUP_ID = w_id.x + w_id.y * w_dim.x;
let WID = WORKGROUP_ID * ELEMENTS_PER_WORKGROUP;
let word_idx = TID >> 5u;
let bit_idx = TID & 31u;
if (TID < 16u) {
digit_offsets[TID] = 0u;
}
if (TID < 128u) {
atomicStore(&digit_masks[TID], 0u);
}
workgroupBarrier();
#ifdef USE_INDIRECT_SORT
let elementCount = sortElementCount[0];
#else
let elementCount = uniforms.elementCount;
#endif
for (var round = 0u; round < ELEMENTS_PER_THREAD; round++) {
let GID = WID + round * THREADS_PER_WORKGROUP + TID;
let is_valid = GID < elementCount;
let k = select(0u, inputKeys[GID], is_valid);
let digit = select(16u, (k >> CURRENT_BIT) & 0xFu, is_valid);
let v = select(0u, select(inputValues[GID], GID, IS_FIRST_PASS == 1u), is_valid);
if (is_valid) {
atomicOr(&digit_masks[digit * 8u + word_idx], 1u << bit_idx);
}
workgroupBarrier();
if (is_valid) {
let base = digit * 8u;
var local_prefix = digit_offsets[digit];
for (var w = 0u; w < word_idx; w++) {
local_prefix += countOneBits(atomicLoad(&digit_masks[base + w]));
}
local_prefix += countOneBits(atomicLoad(&digit_masks[base + word_idx]) & ((1u << bit_idx) - 1u));
let pid = digit * uniforms.workgroupCount + WORKGROUP_ID;
let sorted_position = prefix_block_sum[pid] + local_prefix;
if (IS_LAST_PASS == 0u) {
outputKeys[sorted_position] = k;
}
outputValues[sorted_position] = v;
}
if (round < ELEMENTS_PER_THREAD - 1u) {
workgroupBarrier();
if (TID < 16u) {
var count = 0u;
for (var w = 0u; w < 8u; w++) {
let idx = TID * 8u + w;
count += countOneBits(atomicLoad(&digit_masks[idx]));
atomicStore(&digit_masks[idx], 0u);
}
digit_offsets[TID] += count;
}
workgroupBarrier();
}
}
}
`;var em=class{constructor(t,e=!1){n(this,"device");n(this,"_indirect",!1);n(this,"capacity",0);n(this,"_elementCount",0);n(this,"_numBits",0);n(this,"_hasInitialValues",!1);n(this,"_skipLastPassKeyWrite",!1);n(this,"_destructiveKeys",!1);n(this,"_keys0",null);n(this,"_keys1",null);n(this,"_values0",null);n(this,"_values1",null);n(this,"_indirectInfo",new Uint32Array(4));this.device=t,this._indirect=e}get sortedIndices(){return this._values0?this._numBits/this.radixBits%2===1?this._values1:this._values0:null}get sortedKeys(){if(!this._keys0)return null;let t=this.radixBits;return this._numBits/t%2===0?this._keys1:this._keys0}get radixBits(){return 0}sort(t,e,s,i,r,a){return null}sortIndirect(t,e,s,i,r,a,o,l){return null}prepareIndirect(){return this._indirectInfo}_allocatePingPongElementBuffers(t){let e=t*4,s=12,i=this.device;this._keys0=new Ee(i,e,s),this._destructiveKeys||(this._keys1=new Ee(i,e,s)),this._values0=new Ee(i,e,s),this._values1=new Ee(i,e,s)}_destroyPingPongBuffers(){this._keys0?.destroy(),this._destructiveKeys||this._keys1?.destroy(),this._values0?.destroy(),this._values1?.destroy(),this._keys0=null,this._keys1=null,this._values0=null,this._values1=null}destroy(){}};var HM=16,WM=16,XM=HM*WM,YM=8,xI=XM*YM,by=4,VM=16,Dy=class extends em{constructor(e,s=!1){super(e,s);n(this,"_workgroupCount",0);n(this,"_allocatedWorkgroupCount",0);n(this,"_blockSums",null);n(this,"_prefixSumKernel",null);n(this,"_dispatchSize",new B(1,1));n(this,"_histogramBindGroupFormat",null);n(this,"_reorderBindGroupFormat",null);n(this,"_uniformBufferFormat",null);n(this,"_passes",[]);let i=this._indirectInfo;i[0]=1,i[1]=xI,this._uniformBufferFormat=new Xe(e,[new Y("workgroupCount",pe),new Y("elementCount",pe)]);let r=[new K("input",X,!0),new K("block_sums",X,!1),new Qe("uniforms",X)],a=[new K("inputKeys",X,!0),new K("outputKeys",X,!1),new K("prefix_block_sum",X,!0),new K("inputValues",X,!0),new K("outputValues",X,!1),new Qe("uniforms",X)];s&&(r.push(new K("sortElementCount",X,!0)),a.push(new K("sortElementCount",X,!0))),this._histogramBindGroupFormat=new Ue(e,r),this._reorderBindGroupFormat=new Ue(e,a)}destroy(){this._destroyBuffers(),this._destroyPasses(),this._histogramBindGroupFormat?.destroy(),this._reorderBindGroupFormat?.destroy(),this._histogramBindGroupFormat=null,this._reorderBindGroupFormat=null,this._uniformBufferFormat=null,super.destroy()}_destroyPasses(){for(let e of this._passes)e.histogramCompute.shader?.destroy(),e.reorderCompute.shader?.destroy();this._passes.length=0,this._numBits=0}_destroyBuffers(){this._destroyPingPongBuffers(),this._blockSums?.destroy(),this._prefixSumKernel?.destroy(),this._blockSums=null,this._prefixSumKernel=null,this._workgroupCount=0,this._allocatedWorkgroupCount=0}get radixBits(){return by}_createPasses(e,s,i){this._destroyPasses(),this._numBits=e,this._hasInitialValues=s,this._skipLastPassKeyWrite=i;let r=e/by,a=this._indirect?"-Indirect":"";for(let o=0;o<r;o++){let l=o*by,h=o===0&&!s,f=i&&o===r-1,u=this._createShader(`RadixSort4bit-Histogram${a}-${l}`,zM,l,!1,!1,this._histogramBindGroupFormat),d=this._createShader(`RadixSort4bit-Reorder${a}-${l}`,GM,l,h,f,this._reorderBindGroupFormat),p=new Ye(this.device,u,`RadixSort4bit-Histogram${a}-${l}`),m=new Ye(this.device,d,`RadixSort4bit-Reorder${a}-${l}`);this._passes.push({histogramCompute:p,reorderCompute:m})}}_allocateBuffers(e,s,i,r,a=!1){let o=Math.max(e,this.capacity),l=Math.ceil(o/xI),h=Math.max(1,Math.ceil(e/xI)),f=a||l!==this._allocatedWorkgroupCount||!this._keys0,u=s!==this._numBits||i!==this._hasInitialValues||r!==this._skipLastPassKeyWrite;if(f){this._destroyBuffers(),this._allocatedWorkgroupCount=l,this.capacity=o;let d=VM*l*4;this._allocatePingPongElementBuffers(o),this._blockSums=new Ee(this.device,d,12),this._prefixSumKernel=new Wc(this.device)}this._workgroupCount=h,Ye.calcDispatchSize(h,this._dispatchSize,this.device.limits.maxComputeWorkgroupsPerDimension||65535),this._prefixSumKernel.resize(this._blockSums,VM*h),u&&this._createPasses(s,i,r)}_createShader(e,s,i,r,a,o){let l=new Map;return l.set("{WORKGROUP_SIZE_X}",HM),l.set("{WORKGROUP_SIZE_Y}",WM),l.set("{THREADS_PER_WORKGROUP}",XM),l.set("{ELEMENTS_PER_THREAD}",YM),l.set("{CURRENT_BIT}",i),l.set("{IS_FIRST_PASS}",r?1:0),l.set("{IS_LAST_PASS}",a?1:0),this._indirect&&l.set("USE_INDIRECT_SORT",""),new Be(this.device,{name:e,shaderLanguage:se,cshader:s,cdefines:l,computeBindGroupFormat:o,computeUniformBufferFormats:{uniforms:this._uniformBufferFormat}})}sort(e,s,i=16,r,a=!1,o=!1){return this._execute(e,s,i,-1,null,r,a,o)}sortIndirect(e,s,i,r,a,o,l=!1,h=!1){return this._execute(e,s,i,r,a,o,l,h)}_execute(e,s,i,r,a,o,l=!1,h=!1){this._elementCount=s;let f=!!o,u=this._destructiveKeys;this._destructiveKeys=h,this._allocateBuffers(s,i,f,l,h!==u),h&&(this._keys1=e);let d=this.device,p=i/by,m=this._indirect?"-Indirect":"",_=e,S=o??this._values0,g=this._keys0,T=this._values1;for(let C=0;C<p;C++){let{histogramCompute:v,reorderCompute:E}=this._passes[C],y=C===p-1;if(this._indirect&&this._blockSums.clear(),v.setParameter("input",_),v.setParameter("block_sums",this._blockSums),v.setParameter("workgroupCount",this._workgroupCount),v.setParameter("elementCount",s),this._indirect?(v.setParameter("sortElementCount",a),v.setupIndirectDispatch(r)):v.setupDispatch(this._dispatchSize.x,this._dispatchSize.y,1),d.computeDispatch([v],`RadixSort4bit-Histogram${m}`),this._prefixSumKernel.dispatch(d),E.setParameter("inputKeys",_),E.setParameter("outputKeys",g),E.setParameter("prefix_block_sum",this._blockSums),E.setParameter("inputValues",S),E.setParameter("outputValues",T),E.setParameter("workgroupCount",this._workgroupCount),E.setParameter("elementCount",s),this._indirect?(E.setParameter("sortElementCount",a),E.setupIndirectDispatch(r)):E.setupDispatch(this._dispatchSize.x,this._dispatchSize.y,1),d.computeDispatch([E],`RadixSort4bit-Reorder${m}`),!y){_=g,g=_===this._keys0?this._keys1:this._keys0;let P=S;S=T,T=P}}return this.sortedIndices}};var KM=`
@group(0) @binding(0) var<storage, read> b_sort: array<vec4<u32>>;
@group(0) @binding(1) var<storage, read_write> b_globalHist: array<atomic<u32>>;
struct OneSweepUniforms {
numKeys: u32,
threadBlocks: u32,
numPasses: u32,
_pad: u32
};
@group(0) @binding(2) var<uniform> uniforms: OneSweepUniforms;
#ifdef USE_INDIRECT_SORT
@group(0) @binding(3) var<storage, read> b_sortElementCount: array<u32>;
#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<workgroup> g_gHist: array<atomic<u32>, 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<u32>,
@builtin(num_workgroups) nwg: vec3<u32>,
) {
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<storage, read> b_globalHist: array<u32>;
@group(0) @binding(1) var<storage, read_write> b_passHist: array<atomic<u32>>;
struct OneSweepScanUniforms {
threadBlocks: u32,
_pad0: u32,
_pad1: u32,
_pad2: u32
};
@group(0) @binding(2) var<uniform> uniforms: OneSweepScanUniforms;
#ifdef USE_INDIRECT_SORT
@group(0) @binding(3) var<storage, read> b_sortElementCount: array<u32>;
#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<workgroup> g_scan: array<u32, RADIX>;
var<workgroup> sg_totals: array<u32, MAX_SUBGROUPS>;
@compute @workgroup_size(RADIX, 1, 1)
fn main(
@builtin(local_invocation_index) gtid: u32,
@builtin(workgroup_id) gid: vec3<u32>,
@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<storage, read> inputKeys: array<u32>;
@group(0) @binding(1) var<storage, read_write> outputKeys: array<u32>;
@group(0) @binding(2) var<storage, read> inputValues: array<u32>;
@group(0) @binding(3) var<storage, read_write> outputValues: array<u32>;
@group(0) @binding(4) var<storage, read_write> b_passHist: array<atomic<u32>>;
@group(0) @binding(5) var<storage, read_write> b_index: array<atomic<u32>>;
struct OneSweepBinningUniforms {
numKeys: u32,
threadBlocks: u32,
pass_: u32,
flags: u32
};
@group(0) @binding(6) var<uniform> uniforms: OneSweepBinningUniforms;
#ifdef USE_INDIRECT_SORT
@group(0) @binding(7) var<storage, read> b_sortElementCount: array<u32>;
#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<workgroup> g_d: array<atomic<u32>, G_D_SIZE>;
var<workgroup> digit_base: array<u32, RADIX>;
var<workgroup> sg_totals: array<u32, MAX_SUBGROUPS>;
var<workgroup> 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<u32, {KEYS_PER_THREAD}>;
var values: array<u32, {KEYS_PER_THREAD}>;
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<u32, {KEYS_PER_THREAD}>;
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<u32, {KEYS_PER_THREAD}>;
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));
}
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<u32, {KEYS_PER_THREAD}>;
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.length<e;)this._binningComputes.push(new Ye(this.device,this._binningShader,`OneSweepBinning-${this._binningComputes.length}`))}_allocateBuffers(e,s=!1){let i=Math.max(e,this.capacity),r=Math.max(1,Math.ceil(i/Ly)),a=Math.max(1,Math.ceil(e/Ly));if(s||r!==this._allocatedThreadBlocks||!this._keys0){this._destroyBuffers(),this._allocatedThreadBlocks=r,this.capacity=i;let f=this.device;this._allocatePingPongElementBuffers(i),this._globalHist=new Ee(f,vS*My*4,8),this._passHist=new Ee(f,vS*r*My*4,8),this._index=new Ee(f,vS*4,8)}this._threadBlocks=a;let l=this.device.limits.maxComputeWorkgroupsPerDimension||65535;Ye.calcDispatchSize(a,this._binningDispatchSize,l);let h=Math.max(1,Math.ceil(e/vI));Ye.calcDispatchSize(h,this._globalHistDispatchSize,l)}sort(e,s,i=16,r,a=!1,o=!1){let l=i/8,h=!!r;this._elementCount=s,this._numBits=i,this._hasInitialValues=h,this._skipLastPassKeyWrite=a;let f=this._destructiveKeys;this._destructiveKeys=o,this._allocateBuffers(s,o!==f),this._ensureBinningComputes(l),o&&(this._keys1=e);let u=this.device;this._globalHist.clear(),this._passHist.clear(0,vS*this._threadBlocks*My*4),this._index.clear();let d=this._globalHistCompute;d.setParameter("b_sort",e),d.setParameter("b_globalHist",this._globalHist),d.setParameter("numKeys",s),d.setParameter("threadBlocks",this._threadBlocks),d.setParameter("numPasses",l),d.setParameter("_pad",0),d.setupDispatch(this._globalHistDispatchSize.x,this._globalHistDispatchSize.y,1),u.computeDispatch([d],"OneSweep-GlobalHist");let p=this._scanCompute;p.setParameter("b_globalHist",this._globalHist),p.setParameter("b_passHist",this._passHist),p.setParameter("threadBlocks",this._threadBlocks),p.setParameter("_pad0",0),p.setParameter("_pad1",0),p.setParameter("_pad2",0),p.setupDispatch(l,1,1),u.computeDispatch([p],"OneSweep-Scan");let m=e,_=r??this._values0,S=this._keys0,g=this._values1;for(let T=0;T<l;T++){let C=T===0&&!h,v=T===l-1,E=(C?1:0)|(v&&a?2:0),y=this._binningComputes[T];if(y.setParameter("inputKeys",m),y.setParameter("outputKeys",S),y.setParameter("inputValues",_),y.setParameter("outputValues",g),y.setParameter("b_passHist",this._passHist),y.setParameter("b_index",this._index),y.setParameter("numKeys",s),y.setParameter("threadBlocks",this._threadBlocks),y.setParameter("pass_",T),y.setParameter("flags",E),y.setupDispatch(this._binningDispatchSize.x,this._binningDispatchSize.y,1),u.computeDispatch([y],`OneSweep-Binning-${T}`),!v){m=S,S=m===this._keys0?this._keys1:this._keys0;let P=_;_=g,g=P}}return this.sortedIndices}sortIndirect(e,s,i,r,a,o,l=!1,h=!1){let f=i/8,u=!!o;this._elementCount=s,this._numBits=i,this._hasInitialValues=u,this._skipLastPassKeyWrite=l;let d=this._destructiveKeys;this._destructiveKeys=h,this._allocateBuffers(s,h!==d),this._ensureBinningComputes(f),h&&(this._keys1=e);let p=this.device;this._globalHist.clear(),this._passHist.clear(0,vS*this._allocatedThreadBlocks*My*4),this._index.clear();let m=this._globalHistCompute;m.setParameter("b_sort",e),m.setParameter("b_globalHist",this._globalHist),m.setParameter("b_sortElementCount",a),m.setParameter("numKeys",0),m.setParameter("threadBlocks",0),m.setParameter("numPasses",f),m.setParameter("_pad",0),m.setupIndirectDispatch(r+1),p.computeDispatch([m],"OneSweep-GlobalHistIndirect");let _=this._scanCompute;_.setParameter("b_globalHist",this._globalHist),_.setParameter("b_passHist",this._passHist),_.setParameter("b_sortElementCount",a),_.setParameter("threadBlocks",0),_.setParameter("_pad0",0),_.setParameter("_pad1",0),_.setParameter("_pad2",0),_.setupDispatch(f,1,1),p.computeDispatch([_],"OneSweep-ScanIndirect");let S=e,g=o??this._values0,T=this._keys0,C=this._values1;for(let v=0;v<f;v++){let E=v===0&&!u,y=v===f-1,P=(E?1:0)|(y&&l?2:0),A=this._binningComputes[v];if(A.setParameter("inputKeys",S),A.setParameter("outputKeys",T),A.setParameter("inputValues",g),A.setParameter("outputValues",C),A.setParameter("b_passHist",this._passHist),A.setParameter("b_index",this._index),A.setParameter("b_sortElementCount",a),A.setParameter("numKeys",0),A.setParameter("threadBlocks",0),A.setParameter("pass_",v),A.setParameter("flags",P),A.setupIndirectDispatch(r),p.computeDispatch([A],`OneSweep-BinningIndirect-${v}`),!y){S=T,T=S===this._keys0?this._keys1:this._keys0;let w=g;g=C,C=w}}return this.sortedIndices}};var tm=class{constructor(t,e={}){n(this,"_impl");let s=e.kind??PT,i=e.indirect??!1,r=s;s===PT&&(r=this._canUseOneSweep(t)?wT:bw),r===wT?(this._canUseOneSweep(t),this._impl=new Oy(t,i)):this._impl=new Dy(t,i)}_canUseOneSweep(t){return!(!t.supportsCompute||!t.supportsSubgroups||t.gpuAdapter?.info?.vendor?.toLowerCase?.()!=="nvidia"||t.minSubgroupSize>32)}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;
uniform int elementCount;
uniform int imageElementsLog2;
uniform int currentBit;
varying vec2 uv0;
uint interleaveWithZero(uint word) {
word = (word ^ (word << 8u)) & 0x00ff00ffu;
word = (word ^ (word << 4u)) & 0x0f0f0f0fu;
word = (word ^ (word << 2u)) & 0x33333333u;
word = (word ^ (word << 1u)) & 0x55555555u;
return word;
}
uint deinterleaveWithZero(uint word) {
word &= 0x55555555u;
word = (word | (word >> 1u)) & 0x33333333u;
word = (word | (word >> 2u)) & 0x0f0f0f0fu;
word = (word | (word >> 4u)) & 0x00ff00ffu;
word = (word | (word >> 8u)) & 0x0000ffffu;
return word;
}
ivec2 indexToUV(uint index) {
return ivec2(deinterleaveWithZero(index), deinterleaveWithZero(index >> 1u));
}
uint uvToIndex(ivec2 uv) {
return interleaveWithZero(uint(uv.x)) | (interleaveWithZero(uint(uv.y)) << 1u);
}
void main() {
ivec2 pixel = ivec2(gl_FragCoord.xy);
uint morton = uvToIndex(pixel);
uint elementsLog2 = uint(imageElementsLog2);
uint groupsLog2 = elementsLog2 - uint(groupSize);
uint digitIndex = morton >> groupsLog2;
uint keyIndex = (morton - (digitIndex << groupsLog2)) << uint(groupSize);
uint elemCount = uint(elementCount);
if (keyIndex >= elemCount) {
pcFragColor0 = 0.0;
return;
}
uint count = 0u;
uint mask = (1u << uint(bitsPerStep)) - 1u;
uint cBit = uint(currentBit);
uvec4 digitIdx4 = uvec4(digitIndex);
uvec4 mask4 = uvec4(mask);
uvec4 elemCount4 = uvec4(elemCount);
const uvec4 QUAD_OFFSETS = uvec4(0u, 1u, 2u, 3u);
bool isPartialGroup = (keyIndex + 16u) > elemCount;
#ifdef SOURCE_LINEAR
int sw = int(textureSize(keysTexture, 0).x);
#endif
#define QUAD_COUNT 4
if (isPartialGroup) {
#define BOUNDS_CHECK
#include "radixSortCountQuad, QUAD_COUNT"
#undef BOUNDS_CHECK
} else {
#include "radixSortCountQuad, QUAD_COUNT"
}
pcFragColor0 = float(count);
}
`;var JM=`
{
uint base = {i}u * 4u;
uvec4 mi4 = (keyIndex + base) + QUAD_OFFSETS;
#ifdef SOURCE_LINEAR
uvec4 y4 = mi4 / uint(sw);
uvec4 x4 = mi4 - y4 * uint(sw);
uvec4 keys = uvec4(
texelFetch(keysTexture, ivec2(x4.x, y4.x), 0).r,
texelFetch(keysTexture, ivec2(x4.y, y4.y), 0).r,
texelFetch(keysTexture, ivec2(x4.z, y4.z), 0).r,
texelFetch(keysTexture, ivec2(x4.w, y4.w), 0).r
);
#else
uvec4 keys = uvec4(
texelFetch(keysTexture, indexToUV(mi4.x), 0).r,
texelFetch(keysTexture, indexToUV(mi4.y), 0).r,
texelFetch(keysTexture, indexToUV(mi4.z), 0).r,
texelFetch(keysTexture, indexToUV(mi4.w), 0).r
);
#endif
uvec4 digits = (keys >> cBit) & mask4;
uvec4 m4 = uvec4(equal(digits, digitIdx4));
#ifdef BOUNDS_CHECK
m4 *= uvec4(lessThan(mi4, elemCount4));
#endif
count += m4.x + m4.y + m4.z + m4.w;
}
`;var e2=`
var keysTexture: texture_2d<u32>;
uniform bitsPerStep: i32;
uniform groupSize: i32;
uniform elementCount: i32;
uniform imageElementsLog2: i32;
uniform currentBit: i32;
varying uv0: vec2f;
fn interleaveWithZero(word_in: u32) -> u32 {
var word = word_in;
word = (word ^ (word << 8u)) & 0x00ff00ffu;
word = (word ^ (word << 4u)) & 0x0f0f0f0fu;
word = (word ^ (word << 2u)) & 0x33333333u;
word = (word ^ (word << 1u)) & 0x55555555u;
return word;
}
fn deinterleaveWithZero(word_in: u32) -> u32 {
var word = word_in & 0x55555555u;
word = (word | (word >> 1u)) & 0x33333333u;
word = (word | (word >> 2u)) & 0x0f0f0f0fu;
word = (word | (word >> 4u)) & 0x00ff00ffu;
word = (word | (word >> 8u)) & 0x0000ffffu;
return word;
}
fn indexToUV(index: u32) -> vec2i {
return vec2i(i32(deinterleaveWithZero(index)), i32(deinterleaveWithZero(index >> 1u)));
}
fn uvToIndex(uv: vec2i) -> u32 {
return interleaveWithZero(u32(uv.x)) | (interleaveWithZero(u32(uv.y)) << 1u);
}
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let pixel = vec2i(input.position.xy);
let morton = uvToIndex(pixel);
let elementsLog2 = u32(uniform.imageElementsLog2);
let groupsLog2 = elementsLog2 - u32(uniform.groupSize);
let digitIndex = morton >> groupsLog2;
let keyIndex = (morton - (digitIndex << groupsLog2)) << u32(uniform.groupSize);
let elemCount = u32(uniform.elementCount);
if (keyIndex >= elemCount) {
output.color = 0.0;
return output;
}
var count: u32 = 0u;
let mask = (1u << u32(uniform.bitsPerStep)) - 1u;
let cBit = u32(uniform.currentBit);
let digitIdx4 = vec4u(digitIndex);
let mask4 = vec4u(mask);
let elemCount4 = vec4u(elemCount);
let QUAD_OFFSETS = vec4u(0u, 1u, 2u, 3u);
let isPartialGroup = (keyIndex + 16u) > elemCount;
#ifdef SOURCE_LINEAR
let sw = i32(textureDimensions(keysTexture, 0).x);
#endif
#define QUAD_COUNT 4
if (isPartialGroup) {
#define BOUNDS_CHECK
#include "radixSortCountQuad, QUAD_COUNT"
#undef BOUNDS_CHECK
} else {
#include "radixSortCountQuad, QUAD_COUNT"
}
output.color = f32(count);
return output;
}
`;var t2=`
{
let base = {i}u * 4u;
var mi4 = (keyIndex + base) + QUAD_OFFSETS;
#ifdef SOURCE_LINEAR
var y4 = vec4i(mi4) / sw;
var x4 = vec4i(mi4) - y4 * sw;
var keys = vec4u(
textureLoad(keysTexture, vec2i(x4.x, y4.x), 0).r,
textureLoad(keysTexture, vec2i(x4.y, y4.y), 0).r,
textureLoad(keysTexture, vec2i(x4.z, y4.z), 0).r,
textureLoad(keysTexture, vec2i(x4.w, y4.w), 0).r
);
#else
var keys = vec4u(
textureLoad(keysTexture, indexToUV(mi4.x), 0).r,
textureLoad(keysTexture, indexToUV(mi4.y), 0).r,
textureLoad(keysTexture, indexToUV(mi4.z), 0).r,
textureLoad(keysTexture, indexToUV(mi4.w), 0).r
);
#endif
var digits = (keys >> vec4u(cBit)) & mask4;
var m4 = select(vec4u(0u), vec4u(1u), digits == digitIdx4);
#ifdef BOUNDS_CHECK
m4 = select(m4, vec4u(0u), mi4 >= elemCount4);
#endif
count += m4.x + m4.y + m4.z + m4.w;
}
`;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
#else
uniform highp usampler2D indicesTexture;
#endif
uniform highp sampler2D prefixSums;
uniform int bitsPerStep;
uniform int groupSize;
uniform int elementCount;
uniform int imageElementsLog2;
uniform int currentBit;
uniform int imageSize;
varying vec2 uv0;
uint interleaveWithZero(uint word) {
word = (word ^ (word << 8u)) & 0x00ff00ffu;
word = (word ^ (word << 4u)) & 0x0f0f0f0fu;
word = (word ^ (word << 2u)) & 0x33333333u;
word = (word ^ (word << 1u)) & 0x55555555u;
return word;
}
uint deinterleaveWithZero(uint word) {
word &= 0x55555555u;
word = (word | (word >> 1u)) & 0x33333333u;
word = (word | (word >> 2u)) & 0x0f0f0f0fu;
word = (word | (word >> 4u)) & 0x00ff00ffu;
word = (word | (word >> 8u)) & 0x0000ffffu;
return word;
}
ivec2 indexToUV(uint index) {
return ivec2(deinterleaveWithZero(index), deinterleaveWithZero(index >> 1u));
}
uint uvToIndex(ivec2 uv) {
return interleaveWithZero(uint(uv.x)) | (interleaveWithZero(uint(uv.y)) << 1u);
}
float countActiveTexels(ivec3 uv, ivec2 offset) {
float scale = float(1u << (uint(uv.z) * 2u));
return scale * texelFetch(prefixSums, uv.xy + offset, uv.z).r;
}
ivec2 activeTexelIndexToUV(float prefixWidth, float index, out float activePrevTexelSum) {
float maxLod = round(log2(prefixWidth));
ivec3 uv = ivec3(0, 0, int(maxLod));
float countTotal = countActiveTexels(uv, ivec2(0, 0));
activePrevTexelSum = 0.0;
if (index >= countTotal) {
activePrevTexelSum = countTotal;
return ivec2(-1, -1);
}
while (uv.z >= 1) {
uv = ivec3(uv.xy * 2, uv.z - 1);
float count00 = countActiveTexels(uv, ivec2(0, 0));
float count01 = countActiveTexels(uv, ivec2(1, 0));
float count10 = countActiveTexels(uv, ivec2(0, 1));
float sum00 = activePrevTexelSum + count00;
float sum01 = sum00 + count01;
float sum10 = sum01 + count10;
bool in00 = index < sum00;
bool in01 = index < sum01;
bool in10 = index < sum10;
if (in00) {
} else if (in01) {
uv.xy += ivec2(1, 0);
activePrevTexelSum += count00;
} else if (in10) {
uv.xy += ivec2(0, 1);
activePrevTexelSum += count00 + count01;
} else {
uv.xy += ivec2(1, 1);
activePrevTexelSum += count00 + count01 + count10;
}
}
return uv.xy;
}
void main() {
ivec2 pixel = ivec2(gl_FragCoord.xy);
#ifdef OUTPUT_LINEAR
uint index = uint(pixel.y) * uint(imageSize) + uint(pixel.x);
#else
uint index = uvToIndex(pixel);
#endif
if (index >= uint(elementCount)) {
pcFragColor0 = uvec4(0xFFFFFFFFu, 0u, 0u, 1u);
pcFragColor1 = uvec4(0xFFFFFFFFu, 0u, 0u, 1u);
return;
}
float prefixWidth = float(imageSize * (1 << (bitsPerStep >> 1))) / float(1 << (groupSize >> 1));
float count;
ivec2 activePixel = activeTexelIndexToUV(prefixWidth, float(index), count);
if (activePixel.x < 0) {
pcFragColor0 = uvec4(0xFFFFFFFFu, 0u, 0u, 1u);
pcFragColor1 = uvec4(0xFFFFFFFFu, 0u, 0u, 1u);
return;
}
uint activeIndex = uvToIndex(activePixel);
uint elementsLog2 = uint(imageElementsLog2);
uint groupsLog2 = elementsLog2 - uint(groupSize);
uint digitIndex = activeIndex >> groupsLog2;
uint keyIndex = (activeIndex - (digitIndex << groupsLog2)) << uint(groupSize);
uint outKey = 0u;
uint mask = (1u << uint(bitsPerStep)) - 1u;
uint localIndexU = uint(float(index) - count);
uint localCountU = 0u;
uint foundMortonIndex = keyIndex;
#ifdef SOURCE_LINEAR
uint sw = uint(textureSize(keysTexture, 0).x);
uint baseY = keyIndex / sw;
uint baseX = keyIndex - baseY * sw;
uint x = baseX;
uint y = baseY;
for (uint i = 0u; i < 16u; ++i) {
ivec2 groupPixel = ivec2(int(x), int(y));
outKey = texelFetch(keysTexture, groupPixel, 0).r;
uint digit = (outKey >> uint(currentBit)) & mask;
if (digit == digitIndex) {
localCountU++;
if (localCountU > localIndexU) {
foundMortonIndex = keyIndex + i;
break;
}
}
x++;
if (x >= sw) {
x = 0u;
y++;
}
}
#else
for (uint i = 0u; i < 16u; ++i) {
uint mortonIndex = keyIndex + i;
ivec2 groupPixel = indexToUV(mortonIndex);
outKey = texelFetch(keysTexture, groupPixel, 0).r;
uint digit = (outKey >> uint(currentBit)) & mask;
if (digit == digitIndex) {
localCountU++;
if (localCountU > localIndexU) {
foundMortonIndex = mortonIndex;
break;
}
}
}
#endif
#ifdef FIRST_PASS
uint outIndex = foundMortonIndex;
#else
ivec2 indicesPixel = indexToUV(foundMortonIndex);
uint outIndex = texelFetch(indicesTexture, indicesPixel, 0).r;
#endif
pcFragColor0 = uvec4(outKey, 0u, 0u, 1u);
pcFragColor1 = uvec4(outIndex, 0u, 0u, 1u);
}
`;var i2=`
var keysTexture: texture_2d<u32>;
#ifdef SOURCE_LINEAR
#define FIRST_PASS
#else
var indicesTexture: texture_2d<u32>;
#endif
var prefixSums: texture_2d<f32>;
uniform bitsPerStep: i32;
uniform groupSize: i32;
uniform elementCount: i32;
uniform imageElementsLog2: i32;
uniform currentBit: i32;
uniform imageSize: i32;
varying uv0: vec2f;
fn interleaveWithZero(word_in: u32) -> u32 {
var word = word_in;
word = (word ^ (word << 8u)) & 0x00ff00ffu;
word = (word ^ (word << 4u)) & 0x0f0f0f0fu;
word = (word ^ (word << 2u)) & 0x33333333u;
word = (word ^ (word << 1u)) & 0x55555555u;
return word;
}
fn deinterleaveWithZero(word_in: u32) -> u32 {
var word = word_in & 0x55555555u;
word = (word | (word >> 1u)) & 0x33333333u;
word = (word | (word >> 2u)) & 0x0f0f0f0fu;
word = (word | (word >> 4u)) & 0x00ff00ffu;
word = (word | (word >> 8u)) & 0x0000ffffu;
return word;
}
fn indexToUV(index: u32) -> vec2i {
return vec2i(i32(deinterleaveWithZero(index)), i32(deinterleaveWithZero(index >> 1u)));
}
fn uvToIndex(uv: vec2i) -> u32 {
return interleaveWithZero(u32(uv.x)) | (interleaveWithZero(u32(uv.y)) << 1u);
}
fn countActiveTexels(uv: vec3i, offset: vec2i) -> f32 {
let scale = f32(1u << (u32(uv.z) * 2u));
return scale * textureLoad(prefixSums, uv.xy + offset, uv.z).r;
}
struct BinarySearchResult {
pixel: vec2i,
prefixSum: f32
}
fn activeTexelIndexToUV(prefixWidth: f32, index: f32) -> BinarySearchResult {
var result: BinarySearchResult;
let maxLod = i32(round(log2(prefixWidth)));
var uv = vec3i(0, 0, maxLod);
let countTotal = countActiveTexels(uv, vec2i(0, 0));
result.prefixSum = 0.0;
if (index >= countTotal) {
result.prefixSum = countTotal;
result.pixel = vec2i(-1, -1);
return result;
}
while (uv.z >= 1) {
uv = vec3i(uv.xy * 2, uv.z - 1);
let count00 = countActiveTexels(uv, vec2i(0, 0));
let count01 = countActiveTexels(uv, vec2i(1, 0));
let count10 = countActiveTexels(uv, vec2i(0, 1));
let in00 = index < (result.prefixSum + count00);
let in01 = index < (result.prefixSum + count00 + count01);
let in10 = index < (result.prefixSum + count00 + count01 + count10);
if (in00) {
} else if (in01) {
uv = vec3i(uv.x + 1, uv.y, uv.z);
result.prefixSum += count00;
} else if (in10) {
uv = vec3i(uv.x, uv.y + 1, uv.z);
result.prefixSum += count00 + count01;
} else {
uv = vec3i(uv.x + 1, uv.y + 1, uv.z);
result.prefixSum += count00 + count01 + count10;
}
}
result.pixel = uv.xy;
return result;
}
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let pixel = vec2i(input.position.xy);
#ifdef OUTPUT_LINEAR
let index = u32(pixel.y) * u32(uniform.imageSize) + u32(pixel.x);
#else
let index = uvToIndex(pixel);
#endif
if (index >= u32(uniform.elementCount)) {
output.color = vec4u(0xFFFFFFFFu, 0u, 0u, 1u);
output.color1 = vec4u(0xFFFFFFFFu, 0u, 0u, 1u);
return output;
}
let prefixWidth = f32(uniform.imageSize * (1i << u32(uniform.bitsPerStep >> 1))) / f32(1i << u32(uniform.groupSize >> 1));
let searchResult = activeTexelIndexToUV(prefixWidth, f32(index));
if (searchResult.pixel.x < 0) {
output.color = vec4u(0xFFFFFFFFu, 0u, 0u, 1u);
output.color1 = vec4u(0xFFFFFFFFu, 0u, 0u, 1u);
return output;
}
let activeIndex = uvToIndex(searchResult.pixel);
let elementsLog2 = u32(uniform.imageElementsLog2);
let groupsLog2 = elementsLog2 - u32(uniform.groupSize);
let digitIndex = activeIndex >> groupsLog2;
let keyIndex = (activeIndex - (digitIndex << groupsLog2)) << u32(uniform.groupSize);
var outKey: u32 = 0u;
let mask = (1u << u32(uniform.bitsPerStep)) - 1u;
let localIndexU = u32(f32(index) - searchResult.prefixSum);
var localCountU: u32 = 0u;
var foundMortonIndex: u32 = keyIndex;
#ifdef SOURCE_LINEAR
let sw = textureDimensions(keysTexture, 0).x;
let baseY = keyIndex / sw;
let baseX = keyIndex - baseY * sw;
var x = baseX;
var y = baseY;
for (var i: u32 = 0u; i < 16u; i = i + 1u) {
let groupPixel = vec2i(i32(x), i32(y));
outKey = textureLoad(keysTexture, groupPixel, 0).r;
let digit = (outKey >> u32(uniform.currentBit)) & mask;
if (digit == digitIndex) {
localCountU = localCountU + 1u;
if (localCountU > localIndexU) {
foundMortonIndex = keyIndex + i;
break;
}
}
x = x + 1u;
if (x >= sw) {
x = 0u;
y = y + 1u;
}
}
#else
for (var i: u32 = 0u; i < 16u; i = i + 1u) {
let mortonIndex = keyIndex + i;
let groupPixel = indexToUV(mortonIndex);
outKey = textureLoad(keysTexture, groupPixel, 0).r;
let digit = (outKey >> u32(uniform.currentBit)) & mask;
if (digit == digitIndex) {
localCountU = localCountU + 1u;
if (localCountU > localIndexU) {
foundMortonIndex = mortonIndex;
break;
}
}
}
#endif
#ifdef FIRST_PASS
let outIndex = foundMortonIndex;
#else
let indicesPixel = indexToUV(foundMortonIndex);
let outIndex = textureLoad(indicesTexture, indicesPixel, 0).r;
#endif
output.color = vec4u(outKey, 0u, 0u, 1u);
output.color1 = vec4u(outIndex, 0u, 0u, 1u);
return output;
}
`;var Ny=class extends Ut{constructor(e,s,i,r,a,o){super(e);n(this,"sourceLinear",!1);n(this,"outputLinear",!1);n(this,"bitsPerStep",0);n(this,"groupSize",0);n(this,"currentBit",0);n(this,"_dynamicParams",{elementCount:0,imageElementsLog2:0,imageSize:0});this.sourceLinear=s,this.outputLinear=i,this.bitsPerStep=r,this.groupSize=a,this.currentBit=o,ne.get(e,fe).set("radixSortReorderPS",s2),ne.get(e,se).set("radixSortReorderPS",i2);let l=new Map;s&&l.set("SOURCE_LINEAR",""),i&&l.set("OUTPUT_LINEAR","");let h="RadixSortReorderShader";s&&(h+="SourceLinear"),i&&(h+="OutputLinear"),this.shader=Se.createShader(e,{uniqueName:h,attributes:{aPosition:ee},vertexChunk:"quadVS",fragmentChunk:"radixSortReorderPS",fragmentDefines:l,fragmentOutputTypes:["uvec4","uvec4"]}),this.keysTextureId=e.scope.resolve("keysTexture"),s||(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")}setKeysTexture(e){this._keysTexture=e}setIndicesTexture(e){this._indicesTexture=e}setPrefixSumsTexture(e){this._prefixSums=e}setDynamicParams(e,s,i){this._dynamicParams.elementCount=e,this._dynamicParams.imageElementsLog2=s,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()}};var yS=4,TI=4,By=class extends Nt{constructor(e){super(e);n(this,"_currentIndices",null);n(this,"_numPasses",0);n(this,"_internalSize",0);n(this,"_keys0",null);n(this,"_keys1",null);n(this,"_indices0",null);n(this,"_indices1",null);n(this,"_prefixSums",null);n(this,"_sortRT0",null);n(this,"_sortRT1",null);n(this,"_prefixSumsRT",null);n(this,"_countPasses",[]);n(this,"_reorderPasses",[]);n(this,"_elementCount",0);n(this,"_keysTexture",null)}destroy(){this._destroyPasses(),this._destroyInternalTextures(),super.destroy()}get sortedIndices(){return this._currentIndices}setup(e,s,i=16){this._keysTexture=e,this._elementCount=s;let r=Math.ceil(i/yS);r!==this._numPasses&&(this._destroyPasses(),this._numPasses=r);let a=this._calculateInternalSize(s);a!==this._internalSize&&(this._destroyPasses(),this._resizeInternalTextures(a),this._internalSize=a),this._countPasses.length===0&&this._createPasses()}_calculateInternalSize(e){let s=Math.ceil(Math.sqrt(e));return Math.pow(2,Math.ceil(Math.log2(s)))}_resizeInternalTextures(e){this._destroyInternalTextures(),this._keys0=this._createTexture("RadixSortKeys0",e,zt),this._keys1=this._createTexture("RadixSortKeys1",e,zt),this._indices0=this._createTexture("RadixSortIndices0",e,zt),this._indices1=this._createTexture("RadixSortIndices1",e,zt);let s=e*Math.pow(2,yS/2)/Math.pow(2,TI/2);this._prefixSums=this._createTexture("RadixSortPrefixSums",s,Mt,!0),this._sortRT0=new me({name:"RadixSortRT0",colorBuffers:[this._keys0,this._indices0],depth:!1}),this._sortRT1=new me({name:"RadixSortRT1",colorBuffers:[this._keys1,this._indices1],depth:!1}),this._prefixSumsRT=new me({name:"RadixSortPrefixSumsRT",colorBuffer:this._prefixSums,depth:!1})}_createTexture(e,s,i,r=!1){return new Z(this.device,{name:e,width:s,height:s,format:i,mipmaps:r,minFilter:r?2:0,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,s=this._numPasses,i=this._sortRT1;for(let r=0;r<s;r++){let a=r===0,o=r===s-1,l=r*yS,h=new Fy(e,a,yS,TI,l);h.init(this._prefixSumsRT),h.setClearColor(new F(0,0,0,0)),this._countPasses.push(h),this.beforePasses.push(h);let f=new Ny(e,a,o,yS,TI,l);f.setPrefixSumsTexture(this._prefixSums),f.init(i),this._reorderPasses.push(f),this.beforePasses.push(f),i=i===this._sortRT1?this._sortRT0:this._sortRT1}this._currentIndices=s%2===1?this._indices1:this._indices0}_destroyPasses(){for(let e of this.beforePasses)e.destroy();this.beforePasses.length=0,this._countPasses.length=0,this._reorderPasses.length=0}frameUpdate(){if(super.frameUpdate(),!this._keysTexture||this._countPasses.length===0)return;let e=this._countPasses.length,s=this._elementCount,i=Math.log2(this._internalSize*this._internalSize),r=this._internalSize,a=this._keys0,o=this._indices0;for(let l=0;l<e;l++){let h=l===0,f=this._countPasses[l],u=this._reorderPasses[l];h?f.setKeysTexture(this._keysTexture):f.setKeysTexture(a),f.setDynamicParams(s,i),h?u.setKeysTexture(this._keysTexture):(u.setKeysTexture(a),u.setIndicesTexture(o)),u.setDynamicParams(s,i,r),a=a===this._keys0?this._keys1:this._keys0,o=o===this._indices0?this._indices1:this._indices0}}sort(e,s,i=16){this.setup(e,s,i),this.frameUpdate();for(let r of this.beforePasses)r.render();return this.sortedIndices}};var Uy=class{constructor(){n(this,"usedUvs");n(this,"shaderChunkGLSL");n(this,"shaderChunkWGSL");n(this,"litOptions",new Xa)}};var z6=[0,1,2,3,4,5,6,7],yI=class extends yi{generateKey(t){let e=yi.definesHash(t.defines),s=xt(t.shaderChunkGLSL??""),i=xt(t.shaderChunkWGSL??""),r=cS.generateKey(t.litOptions),a=`${z6.map((o,l)=>t.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),C<i&&v<r){let D=C*(r+1)+v,O=C*(r+1)+(v+1),G=(C+1)*(r+1)+v,M=(C+1)*(r+1)+(v+1);g.push(D,O,G),g.push(O,M,G)}}if(a){let C=Math.floor(r/2),v=r,E=s/2;for(let y=0;y<=C;y++){let P=y*Math.PI*.5/C,A=Math.sin(P),w=Math.cos(P);for(let I=0;I<=v;I++){let D=I*2*Math.PI/v-Math.PI/2,O=Math.sin(D),M=Math.cos(D)*A,H=w,U=O*A,L=1-I/v,b=1-y/C;p.push(M*e,H*e+E,U*e),m.push(M,H,U),_.push(L,1-b),L=L*qo+ja,b=b*qo+ja,L/=3,b/=3,L+=1/3,S.push(L,1-b)}}T=(i+1)*(r+1);for(let y=0;y<C;++y)for(let P=0;P<v;++P){let A=y*(v+1)+P,w=A+v+1;g.push(T+A+1,T+w,T+A),g.push(T+A+1,T+w+1,T+w)}for(let y=0;y<=C;y++){let P=Math.PI*.5+y*Math.PI*.5/C,A=Math.sin(P),w=Math.cos(P);for(let I=0;I<=v;I++){let D=I*2*Math.PI/v-Math.PI/2,O=Math.sin(D),M=Math.cos(D)*A,H=w,U=O*A,L=1-I/v,b=1-y/C;p.push(M*e,H*e-E,U*e),m.push(M,H,U),_.push(L,1-b),L=L*qo+ja,b=b*qo+ja,L/=3,b/=3,L+=2/3,S.push(L,1-b)}}T=(i+1)*(r+1)+(v+1)*(C+1);for(let y=0;y<C;++y)for(let P=0;P<v;++P){let A=y*(v+1)+P,w=A+v+1;g.push(T+A+1,T+w,T+A),g.push(T+A+1,T+w+1,T+w)}}else{if(T=(i+1)*(r+1),t>0)for(let C=0;C<r;C++){let v=C/r*2*Math.PI,E=Math.sin(v),y=-s/2,P=Math.cos(v),A=1-(E+1)/2,w=(P+1)/2;p.push(E*t,y,P*t),m.push(0,-1,0),_.push(A,1-w),A=A*qo+ja,w=w*qo+ja,A/=3,w/=3,A+=1/3,S.push(A,1-w),C>1&&g.push(T,T+C,T+C-1)}if(T+=r,e>0)for(let C=0;C<r;C++){let v=C/r*2*Math.PI,E=Math.sin(v),y=s/2,P=Math.cos(v),A=1-(E+1)/2,w=(P+1)/2;p.push(E*e,y,P*e),m.push(0,1,0),_.push(A,1-w),A=A*qo+ja,w=w*qo+ja,A/=3,w/=3,A+=2/3,S.push(A,1-w),C>1&&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<s&&u<i&&(l.push(h+i+1,h+1,h),l.push(h+i+1,h+i+2,h+1)),h++}this.positions=r,this.normals=a,this.uvs=o,this.uvs1=o,this.indices=l,t.calculateTangents&&(this.tangents=Zs(r,a,o,l))}};var Za=class extends Jt{constructor(t={}){super();let e=t.tubeRadius??.2,s=t.ringRadius??.3,i=(t.sectorAngle??360)*R.DEG_TO_RAD,r=t.segments??30,a=t.sides??20,o=[],l=[],h=[],f=[];for(let u=0;u<=a;u++)for(let d=0;d<=r;d++){let p=Math.cos(i*d/r)*(s+e*Math.cos(2*Math.PI*u/a)),m=Math.sin(2*Math.PI*u/a)*e,_=Math.sin(i*d/r)*(s+e*Math.cos(2*Math.PI*u/a)),S=Math.cos(i*d/r)*Math.cos(2*Math.PI*u/a),g=Math.sin(2*Math.PI*u/a),T=Math.sin(i*d/r)*Math.cos(2*Math.PI*u/a),C=u/a,v=1-d/r;if(o.push(p,m,_),l.push(S,g,T),h.push(C,1-v),u<a&&d<r){let E=u*(r+1)+d,y=(u+1)*(r+1)+d,P=u*(r+1)+(d+1),A=(u+1)*(r+1)+(d+1);f.push(E,y,P),f.push(y,A,P)}}this.positions=o,this.normals=l,this.uvs=h,this.uvs1=h,this.indices=f,t.calculateTangents&&(this.tangents=Zs(o,l,h,f))}};var im=class{constructor(t,e){n(this,"processedCache",new Map);n(this,"definitionsCache",new Map);n(this,"_generators",new Map);this._device=t,this._isClearingCache=!1,this._precached=!1,this._programsCollection=[],this._defaultStdMatOption=new tr,this._defaultStdMatOptionMin=new tr;let s=new bp;e.shaderOptBuilder.updateRef(this._defaultStdMatOption,{},s,e,null,[],Sr,null),e.shaderOptBuilder.updateMinRef(this._defaultStdMatOptionMin,{},e,null,kf,null),t.on("destroy:shader",i=>{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<this._programsCollection.length;++s)t+=`,
${this._programsCollection[s]}`;t+=`
];
`,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<t.length;s++){if(t[s].name==="standard"){let i=t[s].options,r=this._getDefaultStdMatOptions(i.pass);for(let a in r)r.hasOwnProperty(a)&&i[a]===void 0&&(i[a]=r[a])}e[s]=this.getProgram(t[s].name,t[s].options)}}this._precached=!0}};var rm=class{constructor(t,e=!1){n(this,"_deviceLostEvent",null);this.device=t,this.useSingleBuffer=e,this.impl=t.createUploadStreamImpl(this),this._deviceLostEvent=this.device.on("devicelost",this._onDeviceLost,this)}destroy(){this._deviceLostEvent?.off(),this._deviceLostEvent=null,this.impl?.destroy(),this.impl=null}upload(t,e,s=0,i=t.length){this.impl?.upload(t,e,s,i)}_onDeviceLost(){this.impl?._onDeviceLost?.()}};var a2=`
#define GSPLAT_CENTER_NOPROJ
#include "gsplatHelpersVS"
#include "gsplatFormatVS"
#include "gsplatStructsVS"
#include "gsplatDeclarationsVS"
#include "gsplatCenterVS"
#include "gsplatEvalSHVS"
#include "gsplatQuatToMat3VS"
#include "gsplatReadVS"
#include "gsplatWorkBufferOutputVS"
#include "gsplatWriteVS"
#include "gsplatModifyVS"
flat varying ivec4 vSubDraw;
uniform vec3 uColorMultiply;
uniform vec3 model_scale;
uniform vec4 model_rotation;
#ifdef GSPLAT_ID
uniform uint uId;
#endif
void main(void) {
int localRow = int(gl_FragCoord.y) - vSubDraw.w;
int localCol = int(gl_FragCoord.x) - vSubDraw.y;
uint originalIndex = uint(vSubDraw.x + localRow * vSubDraw.z + localCol);
setSplat(originalIndex);
vec3 modelCenter = getCenter();
vec3 worldCenter = (matrix_model * vec4(modelCenter, 1.0)).xyz;
SplatCenter center;
initCenter(modelCenter, center);
vec4 srcRotation = getRotation().yzwx;
vec3 srcScale = getScale();
vec4 worldRotation = quatMul(model_rotation, srcRotation);
if (worldRotation.w < 0.0) {
worldRotation = -worldRotation;
}
vec3 worldScale = model_scale * srcScale;
vec3 originalCenter = worldCenter;
modifySplatCenter(worldCenter);
modifySplatRotationScale(originalCenter, worldCenter, worldRotation, worldScale);
vec4 color = getColor();
#if SH_BANDS > 0
vec3 dir = normalize(center.view * mat3(center.modelView));
vec3 sh[SH_COEFFS];
float scale;
readSHData(sh, scale);
color.xyz += evalSH(sh, dir) * scale;
#endif
modifySplatColor(worldCenter, color);
color.xyz *= uColorMultiply;
writeSplat(worldCenter, worldRotation, worldScale, color);
#ifdef GSPLAT_ID
writePcId(uvec4(uId, 0u, 0u, 0u));
#endif
}
`;var o2=`
#define GSPLAT_CENTER_NOPROJ
#include "gsplatHelpersVS"
#include "gsplatFormatVS"
#include "gsplatStructsVS"
#include "gsplatDeclarationsVS"
#include "gsplatCenterVS"
#include "gsplatEvalSHVS"
#include "gsplatQuatToMat3VS"
#include "gsplatReadVS"
var<private> processOutput: FragmentOutput;
#include "gsplatWorkBufferOutputVS"
#include "gsplatWriteVS"
#include "gsplatModifyVS"
varying @interpolate(flat) vSubDraw: vec4i;
uniform uColorMultiply: vec3f;
uniform model_scale: vec3f;
uniform model_rotation: vec4f;
#ifdef GSPLAT_ID
uniform uId: u32;
#endif
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
let localRow = i32(input.position.y) - input.vSubDraw.w;
let localCol = i32(input.position.x) - input.vSubDraw.y;
let originalIndex = u32(input.vSubDraw.x + localRow * input.vSubDraw.z + localCol);
setSplat(originalIndex);
var modelCenter = getCenter();
var worldCenter = (uniform.matrix_model * vec4f(modelCenter, 1.0)).xyz;
var center: SplatCenter;
initCenter(modelCenter, &center);
let srcRotation = getRotation().yzwx;
let srcScale = getScale();
var worldRotation = vec4f(quatMul(half4(uniform.model_rotation), half4(srcRotation)));
if (worldRotation.w < 0.0) {
worldRotation = -worldRotation;
}
var worldScale = uniform.model_scale * srcScale;
let originalCenter = worldCenter;
modifySplatCenter(&worldCenter);
modifySplatRotationScale(originalCenter, worldCenter, &worldRotation, &worldScale);
var color = getColor();
#if SH_BANDS > 0
let dir = normalize(center.view * mat3x3f(center.modelView[0].xyz, center.modelView[1].xyz, center.modelView[2].xyz));
var sh: array<half3, SH_COEFFS>;
var scale: f32;
readSHData(&sh, &scale);
color = vec4f(color.xyz + vec3f(evalSH(&sh, dir) * half(scale)), color.w);
#endif
modifySplatColor(worldCenter, &color);
color = vec4f(color.xyz * uniform.uColorMultiply, color.w);
writeSplat(worldCenter, worldRotation, worldScale, color);
#ifdef GSPLAT_ID
writePcId(vec4u(uniform.uId, 0u, 0u, 0u));
#endif
return processOutput;
}
`;var n2=`
attribute vec2 vertex_position;
precision highp usampler2D;
uniform usampler2D uSubDrawData;
uniform ivec2 uTextureSize;
uniform int uSubDrawBase;
flat varying ivec4 vSubDraw;
void main(void) {
int subDrawWidth = textureSize(uSubDrawData, 0).x;
int idx = gl_InstanceID + uSubDrawBase;
uvec4 data = texelFetch(uSubDrawData, ivec2(idx % subDrawWidth, idx / subDrawWidth), 0);
int rowStart = int(data.r & 0xFFFFu);
int numRows = int(data.r >> 16u);
int colStart = int(data.g);
int colEnd = int(data.b);
int sourceBase = int(data.a);
float u = float(gl_VertexID & 1);
float v = float(gl_VertexID >> 1);
vec4 ndc = vec4(colStart, colEnd, rowStart, rowStart + numRows) / vec4(uTextureSize.x, uTextureSize.x, uTextureSize.y, uTextureSize.y) * 2.0 - 1.0;
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);
}
`;var l2=`
attribute vertex_position: vec2f;
var uSubDrawData: texture_2d<u32>;
uniform uTextureSize: vec2i;
uniform uSubDrawBase: i32;
varying @interpolate(flat) vSubDraw: vec4i;
@vertex
fn vertexMain(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
let subDrawWidth = i32(textureDimensions(uSubDrawData, 0).x);
let instIdx = i32(input.instanceIndex) + uniform.uSubDrawBase;
let data = textureLoad(uSubDrawData, vec2i(instIdx % subDrawWidth, instIdx / subDrawWidth), 0);
let rowStart = i32(data.r & 0xFFFFu);
let numRows = i32(data.r >> 16u);
let colStart = i32(data.g);
let colEnd = i32(data.b);
let sourceBase = i32(data.a);
let u = f32(i32(input.vertexIndex) & 1);
let v = f32(i32(input.vertexIndex) >> 1u);
let ndc = vec4f(f32(colStart), f32(colEnd), f32(rowStart), f32(rowStart + numRows)) / vec4f(f32(uniform.uTextureSize.x), f32(uniform.uTextureSize.x), f32(uniform.uTextureSize.y), f32(uniform.uTextureSize.y)) * 2.0 - 1.0;
output.position = vec4f(mix(ndc.x, ndc.y, u), mix(-ndc.z, -ndc.w, v), 0.5, 1.0);
output.vSubDraw = vec4i(sourceBase, colStart, colEnd - colStart, rowStart);
return output;
}
`;var c2=new W,h2=new So,EI=8,zy=class{constructor(t){n(this,"device");n(this,"boundsBuffer",null);n(this,"totalBoundsEntries",0);n(this,"_allocatedBoundsEntries",0);n(this,"_boundsFloatView",null);n(this,"_boundsUintView",null);n(this,"_tmpSpheres",null);n(this,"transformsBuffer",null);n(this,"_allocatedTransformCount",0);n(this,"_transformsData",null);n(this,"frustumPlanes",new Float32Array(24));n(this,"fisheyeCameraPos",new Float32Array(3));n(this,"fisheyeCameraForward",new Float32Array(3));n(this,"fisheyeMaxTheta",Math.PI);this.device=t}destroy(){this.boundsBuffer?.destroy(),this.transformsBuffer?.destroy()}updateBoundsData(t){let e=0;for(let a=0;a<t.length;a++)e+=t[a].numBoundsEntries;if(this.totalBoundsEntries=e,e===0)return;if(e>this._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;a<t.length;a++){let o=t[a],l=o.boundsBaseIndex,h=o.numBoundsEntries;o.splat.writeBoundsSpheres(r,l*4);for(let f=0;f<h;f++){let u=(l+f)*4,d=(l+f)*EI;s[d+0]=r[u+0],s[d+1]=r[u+1],s[d+2]=r[u+2],s[d+3]=r[u+3],i[d+4]=a}}this.boundsBuffer.write(0,s)}updateTransformsData(t){let e=t.length;if(e===0)return;e>this._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;r<t.length;r++){let a=t[r].splat.node.getWorldTransform().data;s[i++]=a[0],s[i++]=a[4],s[i++]=a[8],s[i++]=a[12],s[i++]=a[1],s[i++]=a[5],s[i++]=a[9],s[i++]=a[13],s[i++]=a[2],s[i++]=a[6],s[i++]=a[10],s[i++]=a[14]}this.transformsBuffer.write(0,s)}computeFrustumPlanes(t,e){c2.mul2(t,e),h2.setFromMat4(c2);let s=this.frustumPlanes;for(let i=0;i<6;i++){let r=h2.planes[i];s[i*4+0]=r.normal.x,s[i*4+1]=r.normal.y,s[i*4+2]=r.normal.z,s[i*4+3]=r.distance}}setFisheyeData(t,e,s){this.fisheyeCameraPos[0]=t.x,this.fisheyeCameraPos[1]=t.y,this.fisheyeCameraPos[2]=t.z,this.fisheyeCameraForward[0]=e.x,this.fisheyeCameraForward[1]=e.y,this.fisheyeCameraForward[2]=e.z,this.fisheyeMaxTheta=s}};var G6=new W,Gy=new x,ru=new $,AI=new B,V6=[1,1,1],ES=class extends yt{constructor(e,s,i=!1){super(e);n(this,"splats",[]);n(this,"colorsByLod");n(this,"cameraNode",null);n(this,"workBuffer");n(this,"colorOnly");n(this,"_modelScaleData",new Float32Array(3));n(this,"_modelRotationData",new Float32Array(4));n(this,"_textureSize",new Int32Array(2));n(this,"_subDrawTexture");n(this,"_partialData",[]);this.workBuffer=s,this.colorOnly=i,this._subDrawTexture=Z.createDataTexture2D(e,"GsplatSubDrawData",1,1,At)}destroy(){this.splats.length=0,this._subDrawTexture.destroy(),super.destroy()}init(e){super.init(e),this.colorOps.clear=!1,this.depthStencilOps.clearDepth=!1}update(e,s,i,r=null){this.splats.length=0,this._partialData.length=0,this.colorsByLod=i;let a=this.workBuffer.textureSize;if(r){let o=r.size*3;this._subDrawTexture.width*this._subDrawTexture.height<o&&(gt.calcTextureSize(o,AI),this._subDrawTexture.resize(AI.x,AI.y));let l=this._subDrawTexture.lock(),h=0;for(let f=0;f<e.length;f++){let u=e[f];if(u.activeSplats<=0)continue;let d=u.intervals,p=d.length/2;if(p===0)r.has(u.allocId)&&(this.splats.push(u),this._partialData.push(0,0));else{let m=h,_=u.intervalAllocIds;for(let g=0;g<p;g++)r.has(_[g])&&(h=u.appendSubDraws(l,h,d[g*2],d[g*2+1]-d[g*2],u.intervalOffsets[g],a));let S=h-m;S>0&&(this.splats.push(u),this._partialData.push(m,S))}}this._subDrawTexture.unlock()}else for(let o=0;o<e.length;o++){let l=e[o];l.activeSplats>0&&(this.splats.push(l),this._partialData.push(0,0))}for(let o=0;o<this.splats.length;o++)this._partialData[o*2+1]===0&&this.splats[o].ensureSubDrawTexture(a);return this.cameraNode=s,this.splats.length>0}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;l<s.length;l++){let h=r[l*2+1];h>0?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.byteSize<e&&(this.orderBuffer.destroy(),this.orderBuffer=new Ee(this.device,e,8))}else this.orderTexture.resize(t,t)}render(t,e,s,i=null){this.renderPass.update(t,e,s,i)&&this.renderPass.render()}renderColor(t,e,s,i=null){this.colorRenderPass.update(t,e,s,i)&&this.colorRenderPass.render()}};var CS=class CS{constructor(){n(this,"_pendingDestroy",new Set)}static queueDestroy(t,e){this._cache.get(t,()=>new 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;a<e;++a){s.set([-1,-1,a,1,-1,a,1,1,a,-1,1,a],a*12);let o=a*4;i.set([0+o,1+o,2+o,0+o,2+o,3+o],a*6)}let r=new _e(t);return r.setPositions(s,3),r.setIndices(i),r.update(),r}static get instanceSize(){return 128}get numSplats(){return this.gsplatData.numSplats}get format(){return this._format}getTexture(t){return this.streams.getTexture(t)??null}get textureDimensions(){return this.streams.textureDimensions}configureMaterial(t,e,s){this.configureMaterialDefines(t.defines),this.streams.syncWithFormat(this.format);let i=this.device.isWebGPU?t.shaderChunks.wgsl:t.shaderChunks.glsl;i.set("gsplatDeclarationsVS",s),i.set("gsplatReadVS",this.format.getReadCode()),e?.code&&i.set("gsplatModifyVS",e.code);for(let[r,a]of this.streams.textures)t.setParameter(r,a);for(let[r,a]of this.parameters)t.setParameter(r,a);this.textureDimensions.x>0&&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<this.numSplats;++S){if(e&&!e(S))continue;let g=f[S],T=u[S],C=d[S],v=Math.max(p[S],m[S],_[S]);if(!isFinite(g)||!isFinite(T)||!isFinite(C)||!isFinite(v))continue;let E=2*Math.exp(v);h?(h=!1,s=g-E,i=T-E,r=C-E,a=g+E,o=T+E,l=C+E):(s=Math.min(s,g-E),i=Math.min(i,T-E),r=Math.min(r,C-E),a=Math.max(a,g+E),o=Math.max(o,T+E),l=Math.max(l,C+E))}return h||(t.center.set((s+a)*.5,(i+o)*.5,(r+l)*.5),t.halfExtents.set((a-s)*.5,(o-i)*.5,(l-r)*.5)),!h}calcAabbExact(t,e){let s=new x,i=new $,r=new x,a=this.createIter(s,i,r),o=!0;for(let l=0;l<this.numSplats;++l)e&&!e(l)||(a.read(l),o?(o=!1,c.calcSplatAabb(t,s,i,r)):(c.calcSplatAabb(u2,s,i,r),t.add(u2)));return!o}getCenters(){let t=this.getProp("x"),e=this.getProp("y"),s=this.getProp("z"),i=new Float32Array(this.numSplats*3);for(let r=0;r<this.numSplats;++r)i[r*3+0]=t[r],i[r*3+1]=e[r],i[r*3+2]=s[r];return i}calcFocalPoint(t,e){let s=this.getProp("x"),i=this.getProp("y"),r=this.getProp("z"),a=this.getProp("scale_0"),o=this.getProp("scale_1"),l=this.getProp("scale_2");t.x=0,t.y=0,t.z=0;let h=0;for(let f=0;f<this.numSplats;++f){if(e&&!e(f))continue;let u=s[f],d=i[f],p=r[f];if(!isFinite(u)||!isFinite(d)||!isFinite(p))continue;let m=1/(1+Math.exp(Math.max(a[f],o[f],l[f])));t.x+=u*m,t.y+=d*m,t.z+=p*m,h+=m}t.mulScalar(1/h)}renderWireframeBounds(t,e){let s=new x,i=new $,r=new x,a=new x,o=new x,l=this.createIter(s,i,r);for(let h=0;h<this.numSplats;++h)l.read(h),d2(nm,s,i),nm.mul2(e,nm),a.set(r.x*-2,r.y*-2,r.z*-2),o.set(r.x*2,r.y*2,r.z*2),t.immediate.drawWireAlignedBox(a,o,X6,!0,t.defaultDrawLayer,nm)}get isCompressed(){return!1}get shBands(){return{9:1,24:2,45:3}[(()=>{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;y<C.length;y++)C[y]<v&&(v=C[y]),C[y]>E&&(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;C<this.numSplats;C++){let v=Math.min(1023,Math.floor((s[C]-a)*d)),E=Math.min(1023,Math.floor((i[C]-l)*p)),y=Math.min(1023,Math.floor((r[C]-f)*m)),P=e(v,E,y),A=_.get(P);A?A.push(C):_.set(P,[C])}let S=Array.from(_.keys()).sort((C,v)=>C-v),g=new Uint32Array(this.numSplats),T=0;for(let C=0;C<S.length;++C){let v=_.get(S[C]);for(let E=0;E<v.length;++E)g[T++]=v[E]}return g}reorder(t){let e=new Map,s=a=>{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<t.length;l++)o[l]=a[t[l]];return i(a.buffer),o};this.elements.forEach(a=>{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);
}
`,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));
uint bits = (vb.x << 21) | (vb.y << 10) | vb.z;
return vec4((uvec4(bits) >> uvec4(24, 16, 8, 0)) & uvec4(0xff)) / vec4(255.0);
}
uniform mediump vec3 dir;
uniform mediump sampler2D centroids;
uniform mediump float shN_mins;
uniform mediump float shN_maxs;
void main(void) {
ivec2 uv = ivec2(gl_FragCoord.xy) * ivec2(SH_COEFFS, 1);
mediump vec3 coefficients[SH_COEFFS];
for (int i = 0; i < SH_COEFFS; i++) {
vec3 s = texelFetch(centroids, ivec2(uv.x + i, uv.y), 0).xyz;
coefficients[i] = mix(vec3(shN_mins), vec3(shN_maxs), s);
}
gl_FragColor = packRgb(evalSH(coefficients, dir) * 0.25 + 0.5);
}
`,j6=`
attribute vertex_position: vec2f;
@vertex
fn vertexMain(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
output.position = vec4f(vertex_position, 0.0, 1.0);
return output;
}
`,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));
let bits = dot(vb, vec3u(1 << 21, 1 << 10, 1));
return vec4f((vec4u(bits) >> vec4u(24, 16, 8, 0)) & vec4u(0xff)) / vec4f(255.0);
}
uniform dir: vec3f;
uniform shN_mins: f32;
uniform shN_maxs: f32;
var centroids: texture_2d<f32>;
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
var uv = vec2i(input.position.xy) * vec2i(SH_COEFFS, 1);
var coefficients: array<vec3f, SH_COEFFS>;
for (var i: i32 = 0; i < SH_COEFFS; i++) {
let s: vec3f = textureLoad(centroids, vec2i(uv.x + i, uv.y), 0).xyz;
coefficients[i] = mix(vec3f(uniform.shN_mins), vec3f(uniform.shN_maxs), s);
}
output.color = packRgb(evalSH(&coefficients, uniform.dir) * 0.25 + 0.5);
return output;
}
`,$6=`
uniform mediump sampler2D sh0;
uniform highp sampler2D sh_labels;
uniform mediump sampler2D sh_result;
uniform vec4 sh0_mins;
uniform vec4 sh0_maxs;
float SH_C0 = 0.28209479177387814;
vec3 unpackRgb(vec4 v) {
uvec4 uv = uvec4(v * 255.0);
uint bits = (uv.x << 24) | (uv.y << 16) | (uv.z << 8) | uv.w;
uvec3 vb = (uvec3(bits) >> uvec3(21, 10, 0)) & uvec3(0x7ffu, 0x7ffu, 0x3ffu);
return vec3(vb) / vec3(2047.0, 2047.0, 1023.0);
}
vec4 getColor(in SplatSource source) {
vec4 baseSample = mix(sh0_mins, sh0_maxs, texelFetch(sh0, source.uv, 0));
vec4 base = vec4(vec3(0.5) + baseSample.xyz * SH_C0, 1.0 / (1.0 + exp(-baseSample.w)));
ivec2 labelSample = ivec2(texelFetch(sh_labels, source.uv, 0).xy * 255.0);
int n = labelSample.x + labelSample.y * 256;
vec4 shSample = texelFetch(sh_result, ivec2(n % 64, n / 64), 0);
vec3 sh = (unpackRgb(shSample) - vec3(0.5)) * 4.0;
return vec4(base.xyz + sh, base.w);
}
`,Z6=`
var sh0: texture_2d<f32>;
var sh_labels: texture_2d<f32>;
var sh_result: texture_2d<f32>;
uniform sh0_mins: vec4f;
uniform sh0_maxs: vec4f;
const SH_C0: f32 = 0.28209479177387814;
fn unpackRgb(v: vec4f) -> vec3f {
let bits = dot(vec4u(v * 255.0), vec4u(1u << 24, 1u << 16, 1u << 8, 1u));
let vb = (vec3u(bits) >> vec3u(21, 10, 0)) & vec3u(0x7ffu, 0x7ffu, 0x3ffu);
return vec3f(vb) / vec3f(2047.0, 2047.0, 1023.0);
}
fn getColor(source: ptr<function, SplatSource>) -> vec4f {
let baseSample: vec4f = mix(uniform.sh0_mins, uniform.sh0_maxs, textureLoad(sh0, source.uv, 0));
let base = vec4f(vec3f(0.5) + baseSample.xyz * SH_C0, 1.0 / (1.0 + exp(-baseSample.w)));
let labelSample: vec2i = vec2i(textureLoad(sh_labels, source.uv, 0).xy * 255.0);
let n = labelSample.x + labelSample.y * 256;
let shSample: vec4f = textureLoad(sh_result, vec2i(n % 64, n / 64), 0);
let sh: vec3f = (unpackRgb(shSample) - vec3f(0.5)) * 4.0;
return vec4f(base.xyz + sh, base.w);
}
`,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)<D&&Math.abs(y-l.y)<D&&Math.abs(P-l.z)<D&&Math.abs(A-h.x)<D&&Math.abs(w-h.y)<D&&Math.abs(I-h.z)<D)return;o=!1,l.x=E,l.y=y,l.z=P,h.x=A,h.y=w,h.z=I;let O,G;for(let V=0;V<8;++V){let q=V&1?f.x:u.x,re=V&2?f.y:u.y,te=V&4?f.z:u.z,j=q*A+re*w+te*I;V===0?O=G=j:(O=Math.min(O,j),G=Math.max(G,j))}let M=e.length/3,U=2**Math.max(10,Math.min(20,Math.round(Math.log2(M/4))))+1;d?.length!==M&&(d=new Uint32Array(M)),!p||p.length!==U?p=new Uint32Array(U):p.fill(0);let L=G-O;if(L<1e-6)for(let V=0;V<M;++V)d[V]=0,p[0]++;else{let V=s.length/4;_.fill(0);for(let j=0;j<V;++j){let oe=s[j*4+0],be=s[j*4+1],qe=s[j*4+2],ot=s[j*4+3],Ve=oe*A+be*w+qe*I-O,Lt=Math.max(0,Math.floor((Ve-ot)*m/L)),Vs=Math.min(m,Math.ceil((Ve+ot)*m/L));for(let ds=Lt;ds<Vs;++ds)_[ds]++}let q=_.reduce((j,oe)=>j+oe,0);for(let j=0;j<m;++j)g[j]=_[j]/q*U>>>0;for(let j=0;j<m;++j)S[j]=j===0?0:S[j-1]+g[j-1];let re=L/m,te=0;for(let j=0;j<M;++j){let oe=e[te++],be=e[te++],qe=e[te++],ot=(oe*A+be*w+qe*I-O)/re,Ve=ot>>>0,Lt=S[Ve]+g[Ve]*(ot-Ve)>>>0;d[j]=Lt,p[Lt]++}}for(let V=1;V<U;V++)p[V]+=p[V-1];for(let V=0;V<M;V++){let q=d[V],re=--p[q];t[re]=V}let b=E*A+y*w+P*I,N=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<M;++V)t[V]=i[t[V]];c.postMessage({order:t.buffer,count:z,sortTime:performance.now()-v},[t.buffer]),t=null};c.addEventListener("message",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;P<y.length/6;++P){let A=y[P*6+0],w=y[P*6+1],I=y[P*6+2],D=y[P*6+3],O=y[P*6+4],G=y[P*6+5];s[P*4+0]=(A+D)*.5,s[P*4+1]=(w+O)*.5,s[P*4+2]=(I+G)*.5,s[P*4+3]=Math.sqrt((D-A)**2+(O-w)**2+(G-I)**2)*.5,A<f.x&&(f.x=A),w<f.y&&(f.y=w),I<f.z&&(f.z=I),D>u.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;M<P;++M){A=w=I=1/0,D=O=G=-1/0;let H=M*256,U=Math.min(y,(M+1)*256);for(let L=H;L<U;++L){let b=e[L*3+0],N=e[L*3+1],k=e[L*3+2],z=Number.isFinite(b),V=Number.isFinite(N),q=Number.isFinite(k);z||(e[L*3+0]=0),V||(e[L*3+1]=0),q||(e[L*3+2]=0),!(!z||!V||!q)&&(b<A?A=b:b>D&&(D=b),N<w?w=N:N>O&&(O=N),k<I?I=k:k>G&&(G=k),b<f.x?f.x=b:b>u.x&&(u.x=b),N<f.y?f.y=N:N>u.y&&(u.y=N),k<f.z?f.z=k:k>u.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<s;++h)a[h]=h;this.orderData=new ArrayBuffer(s*4);let o={order:a.buffer,centers:i.buffer,chunks:r?.buffer},l=[a.buffer,i.buffer].concat(r?[r.buffer]:[]);this.worker.postMessage(o,l)}applyPendingSorted(){if(this.pendingSorted){let{count:e,data:s}=this.pendingSorted;return this.pendingSorted=null,this.uploadStream.upload(s,this.target),e}return-1}setMapping(e){if(e){let s=new Float32Array(e.length*3);for(let i=0;i<e.length;++i){let r=e[i]*3,a=i*3;s[a+0]=this.centers[r+0],s[a+1]=this.centers[r+1],s[a+2]=this.centers[r+2]}this.worker.postMessage({centers:s.buffer,mapping:e.buffer},[s.buffer,e.buffer])}else{let s=this.centers.slice();this.worker.postMessage({centers:s.buffer,mapping:null},[s.buffer])}}setCamera(e,s){this.worker.postMessage({cameraPosition:{x:e.x,y:e.y,z:e.z},cameraDirection:{x:s.x,y:s.y,z:s.z}})}};var _2=`
#include "gsplatPackingPS"
uniform highp sampler2D means_l;
uniform highp sampler2D means_u;
uniform highp uint numSplats;
uniform highp vec3 means_mins;
uniform highp vec3 means_maxs;
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 l = texelFetch(means_l, uv, 0).xyz;
vec3 u = texelFetch(means_u, uv, 0).xyz;
vec3 n = (l + u * 256.0) / 257.0;
vec3 v = mix(means_mins, means_maxs, n);
vec3 center = sign(v) * (exp(abs(v)) - 1.0);
pcFragColor0 = uvec4(floatBitsToUint(center), 0u);
}
`;var g2=`
var means_l: texture_2d<f32>;
var means_u: texture_2d<f32>;
uniform numSplats: u32;
uniform means_mins: vec3f;
uniform means_maxs: vec3f;
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let w: u32 = textureDimensions(means_l, 0).x;
let uv: vec2<i32> = vec2<i32>(input.position.xy);
if (u32(uv.x + uv.y * i32(w)) >= uniform.numSplats) {
discard;
return output;
}
let l: vec3f = textureLoad(means_l, uv, 0).xyz;
let u: vec3f = textureLoad(means_u, uv, 0).xyz;
let n: vec3f = (l + u * 256.0) / 257.0;
let v: vec3f = mix(uniform.means_mins, uniform.means_maxs, n);
let center: vec3f = sign(v) * (exp(abs(v)) - 1.0);
let packed: vec4<u32> = bitcast<vec4<u32>>(vec4f(center, 0.0));
output.color = packed;
return output;
}
`;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;O<y;++O)a[D*15+O]=p.codebook[v[(w+O)*4+D+I*t.sh_centroids.width*4]];else for(let D=0;D<3;++D)for(let O=0;O<y;++O)a[D*15+O]=o(p.mins,p.maxs,v[(w+O)*4+D+I*t.sh_centroids.width*4]/255)}}}},ca=class{constructor(){n(this,"meta");n(this,"numSplats");n(this,"means_l");n(this,"means_u");n(this,"quats");n(this,"scales");n(this,"sh0");n(this,"sh_centroids");n(this,"sh_labels");n(this,"codebookTexture",null);n(this,"url","");n(this,"_centers",null);n(this,"destroyed",!1);n(this,"shBands",0)}_destroyGpuResources(){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.codebookTexture?.destroy(),this.codebookTexture=null}static calcBands(t){return{192:1,512:2,960:3}[t]??0}destroy(){this.destroyed=!0,this._destroyGpuResources()}createIter(t,e,s,i,r){return new RI(this,t,e,s,i,r)}calcAabb(t){let{mins:e,maxs:s}=this.meta.means,i=r=>Math.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<this.numSplats;++g)if(S.read(g),f.x[g]=u.x,f.y[g]=u.y,f.z[g]=u.z,f.rot_1[g]=d.x,f.rot_2[g]=d.y,f.rot_3[g]=d.z,f.rot_0[g]=d.w,f.scale_0[g]=p.x,f.scale_1[g]=p.y,f.scale_2[g]=p.z,f.f_dc_0[g]=(m.x-.5)/pl,f.f_dc_1[g]=(m.y-.5)/pl,f.f_dc_2[g]=(m.z-.5)/pl,f.opacity[g]=m.w<=0?-40:m.w>=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<this.numSplats;p++){let m=p*4;d[p*3+0]=u[m+0],d[p*3+1]=u[m+1],d[p*3+2]=u[m+2]}this._centers=d,r.destroy()}_createCodebookTexture(){let t=this.means_l.device,{scales:e,sh0:s,shN:i}=this.meta,r=e.codebook,a=s.codebook,o=i?.codebook,l=new Float32Array(256*4);for(let f=0;f<256;f++)l[f*4]=r[f];for(let f=0;f<256;f++)l[f*4+1]=a[f];if(o)for(let f=0;f<256;f++)l[f*4+2]=o[f];let h=this.url?`_${this.url}`:"";this.codebookTexture=new Z(t,{name:`sogCodebook${h}`,width:256,height:1,format:ke,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1,levels:[l]})}_patchCodebooks(){["scales","sh0","shN"].forEach(t=>{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;
uniform uint dstNumSplats;
#include "gsplatSplatVS"
#include "gsplatProcessInputVS"
#include "gsplatProcessOutputVS"
#include "gsplatProcessReadVS"
#include "gsplatProcessChunk"
void main(void) {
ivec2 fragCoords = ivec2(gl_FragCoord.xy);
uint splatIndex = uint(fragCoords.y * int(dstTextureSize) + fragCoords.x);
if (splatIndex >= dstNumSplats) discard;
setSplat(splatIndex);
process();
}
`;var x2=`
uniform splatTextureSize: u32;
uniform dstTextureSize: u32;
uniform srcNumSplats: u32;
uniform dstNumSplats: u32;
#include "gsplatSplatVS"
#include "gsplatProcessInputVS"
var<private> processOutput: FragmentOutput;
#include "gsplatProcessOutputVS"
#include "gsplatProcessReadVS"
#include "gsplatProcessChunk"
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
let fragCoords = vec2i(input.position.xy);
let splatIndex = u32(fragCoords.y * i32(uniform.dstTextureSize) + fragCoords.x);
if (splatIndex >= uniform.dstNumSplats) {
discard;
}
setSplat(splatIndex);
process();
return processOutput;
}
`;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;s<t;++s)e.push(c.getProp(`f_rest_${s}`));return e},$o=class extends rt{constructor(e,s,i={}){super(e,s,i);n(this,"shBands");let r=s.numSplats;this.shBands=s.shBands;let a=[{name:"splatColor",format:Me},{name:"transformA",format:At},{name:"transformB",format:Me}];this.shBands>0&&(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;u<this.numSplats;++u){let d=a[u]*f+.5,p=o[u]*f+.5,m=l[u]*f+.5,_=1/(1+Math.exp(-h[u]));r[u*4+0]=i(d),r[u*4+1]=i(p),r[u*4+2]=i(m),r[u*4+3]=i(_)}s.unlock()}updateTransformData(e){let s=Hs.float2Half,i=this.streams.getTexture("transformA"),r=this.streams.getTexture("transformB");if(!i)return;let a=i.lock(),o=new Float32Array(a.buffer),l=r.lock(),h=new x,f=new $,u=new x,d=e.createIter(h,f,u);for(let p=0;p<this.numSplats;p++)d.read(p),f.normalize(),f.w<0&&f.mulScalar(-1),o[p*4+0]=h.x,o[p*4+1]=h.y,o[p*4+2]=h.z,a[p*4+3]=s(f.x)|s(f.y)<<16,l[p*4+0]=s(u.x),l[p*4+1]=s(u.y),l[p*4+2]=s(u.z),l[p*4+3]=s(f.z);i.unlock(),r.unlock()}updateSHData(e){let s=this.streams.getTexture("splatSH_1to3"),i=this.streams.getTexture("splatSH_4to7"),r=this.streams.getTexture("splatSH_8to11"),a=this.streams.getTexture("splatSH_12to15"),o=s.lock(),l=i?.lock(),h=r?.lock(),f=a?.lock(),u={1:3,2:8,3:15}[this.shBands],d=t8(e,u*3),p=2047,m=1023,_=new Float32Array(1),S=new Uint32Array(_.buffer),g=new Array(u*3).fill(0);for(let T=0;T<e.numSplats;++T){for(let v=0;v<u;++v)g[v*3]=d[v][T],g[v*3+1]=d[v+u][T],g[v*3+2]=d[v+u*2][T];let C=g[0];for(let v=1;v<u*3;++v)C=Math.max(C,Math.abs(g[v]));if(C!==0){for(let v=0;v<u;++v)g[v*3+0]=Math.max(0,Math.min(p,Math.floor((g[v*3+0]/C*.5+.5)*p+.5))),g[v*3+1]=Math.max(0,Math.min(m,Math.floor((g[v*3+1]/C*.5+.5)*m+.5))),g[v*3+2]=Math.max(0,Math.min(p,Math.floor((g[v*3+2]/C*.5+.5)*p+.5)));_[0]=C,o[T*4+0]=S[0],o[T*4+1]=g[0]<<21|g[1]<<11|g[2],o[T*4+2]=g[3]<<21|g[4]<<11|g[5],o[T*4+3]=g[6]<<21|g[7]<<11|g[8],this.shBands>1&&(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;i<e.length;i++){let r=e[i];r.enabled&&this.addRenderPass(r)}t.enabled&&(this.multiview?this.multiview.addChild(t):this.renderPasses.push(t));let s=t.afterPasses;for(let i=0;i<s.length;i++){let r=s[i];r.enabled&&this.addRenderPass(r)}}reset(){this.renderPasses.length=0}compile(){this._compilePasses(this.renderPasses);for(let t=0;t<this.renderPasses.length;t++){let e=this.renderPasses[t];e instanceof Zf&&this._compilePasses(e.children)}}_compilePasses(t){let e=this.renderTargetMap;for(let r=0;r<t.length;r++){let a=t[r];a._skipStart=!1,a._skipEnd=!1;let o=a.renderTarget;if(o!==void 0){let l=e.get(o);if(l){let h=a.colorArrayOps.length;for(let f=0;f<h;f++)a.colorArrayOps[f].clear||(l.colorArrayOps[f].store=!0);a.depthStencilOps.clearDepth||(l.depthStencilOps.storeDepth=!0),a.depthStencilOps.clearStencil||(l.depthStencilOps.storeStencil=!0)}e.set(o,a)}}for(let r=0;r<t.length-1;r++){let a=t[r],o=a.renderTarget,l=t[r+1],h=l.renderTarget;o!==h||o===void 0||l.depthStencilOps.clearDepth||l.depthStencilOps.clearStencil||l.colorArrayOps.some(f=>f.clear)||a.afterPasses.length>0||l.beforePasses.length>0||(a._skipEnd=!0,l._skipStart=!0)}let s=null,i=null;for(let r=0;r<t.length;r++){let a=t[r],o=a.renderTarget,l=o?.colorBuffer;if(l?.cubemap){if(s===l){let h=i.colorArrayOps.length;for(let f=0;f<h;f++)i.colorArrayOps[f].mipmaps=!1}s=o.colorBuffer,i=a}else a.requiresCubemaps&&(s=null,i=null)}e.clear()}render(t){this.compile();let e=this.renderPasses;for(let s=0;s<e.length;s++)e[s].render()}};var LI=class{constructor(t,e){this.texture0=t,this.texture1=e}destroy(){this.texture0?.destroy(),this.texture1?.destroy()}},y2=new et,wS=class c{static createTexture(t,e,s,i=""){return new Z(t,{name:`AreaLightLUT${i}`,width:s,height:s,format:e,addressU:1,addressV:1,type:Gt,magFilter:1,minFilter:0,anisotropy:1,mipmaps:!1})}static applyTextures(t,e,s){y2.remove(t),y2.get(t,()=>new 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;S<p;S++)m[S]=_(d[S]);return m}let a=e,o=s,l=r(a),h=r(o),f=i(t,l,Me),u=i(t,h,Me);c.applyTextures(t,f,u)}};var um="en-US",dm={en:"en-US",es:"en-ES",zh:"zh-CN","zh-HK":"zh-TW","zh-TW":"zh-HK","zh-MO":"zh-HK",fr:"fr-FR",de:"de-DE",it:"it-IT",ru:"ru-RU",ja:"ja-JP"};var MI={};function qc(c,t){for(let e=0,s=c.length;e<s;e++)MI[c[e]]=t}function Zo(c){let t=c.indexOf("-");return t!==-1?c.substring(0,t):c}function E2(c,t){let e=c.indexOf("-");return e!==-1?t+c.substring(e):t}function Zy(c,t){if(t[c])return c;let e=dm[c];if(e&&t[e])return e;let s=Zo(c);return e=dm[s],t[e]?e:t[s]?s:um}qc(["ja","ko","th","vi","zh","id"],c=>0);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;o<l;o++){let h=A2[o];if(e.variants[h]&&a[v8[h]]){e=e.variants[h];break}if(r.enableBundles){let f=r.bundles.listBundlesForAsset(this);if(f&&f.find(u=>u?.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<e.length;++s)e[s]?.destroy?.()}static fetchArrayBuffer(e,s,i,r=0){i?.file?.contents?setTimeout(()=>{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;f<t.length;f++){if(r=t[f],r instanceof Array){if(r.length===0)continue;if(r.length===1)r=r[0];else{l=!1;for(let u=0;u<r.length;u++)if(!this._index[r[u]]){l=!0;break}if(l)continue;a=r.slice(0).sort(h),o=a.slice(1),o.length===1&&(o=o[0]);for(let u=0;u<this._index[a[0]].list.length;u++)i=this._index[a[0]].list[u],(this._key?!e[i[this._key]]:s.indexOf(i)===-1)&&i.tags.has(o)&&(this._key&&(e[i[this._key]]=!0),s.push(i));continue}}if(r&&typeof r=="string"&&this._index[r])for(let u=0;u<this._index[r].list.length;u++)i=this._index[r].list[u],this._key?e[i[this._key]]||(e[i[this._key]]=!0,s.push(i)):s.indexOf(i)===-1&&s.push(i)}return s}};var ha=class extends J{constructor(e){super();n(this,"_assets",new Set);n(this,"_loader");n(this,"_idToAsset",new Map);n(this,"_urlToAsset",new Map);n(this,"_nameToAsset",new Map);n(this,"_tags",new e0("id"));n(this,"prefix",null);n(this,"bundles",null);this._loader=e}get loader(){return this._loader}list(e={}){let s=Array.from(this._assets);return e.preload!==void 0?s.filter(i=>i.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<h.length;f++){let u=this._idToAsset.get(h[f]);u&&!u.loaded&&this.load(u,{force:!0})}e.resource.loaded?r():(this.fire("load:start",e),this.fire(`load:start:${e.id}`,e),i&&i.url&&this.fire(`load:start:url:${i.url}`,e),e.fire("load:start",e),e.resource.on("load",r))}else r()},o=(l,h,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<h.length;f++){let u=this._idToAsset.get(h[f]);u&&(u.loaded||u.resource||u.loading||(u.loading=!0))}}this._loader.load(l,e.type,o,e,s)}else{let l=this._loader.open(e.type,e.data);e.loaded=!0,a(l)}}loadFromUrl(e,s,i){this.loadFromUrlAndFilename(e,null,s,i)}loadFromUrlAndFilename(e,s,i,r){let a=xe.getBasename(s||e),o={filename:s||a,url:e},l=this.getByUrl(e);if(!l)l=new ae(a,i,o),this.add(l);else if(l.loaded){r(l.loadFromUrlError||null,l);return}let h=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<s.mapping.length;l++){let h=s.mapping[l].path;if(h){a++;let f=e.getAbsoluteUrl(h);this.loadFromUrl(f,"material",o)}}a===0&&i(null,r)}_loadTextures(e,s){let i=[],r=0,a=e.data;if(a.mappingFormat!=="path"){s(null,i);return}let o=(h,f)=>{i.push(f),i.length===r&&s(null,i)},l=qf;for(let h=0;h<l.length;h++){let f=a[l[h]];if(f&&typeof f=="string"){r++;let u=e.getAbsoluteUrl(f);this.loadFromUrl(u,"texture",o)}}r===0&&s(null,i)}_onTagAdd(e,s){this._tags.add(e,s)}_onTagRemove(e,s){this._tags.remove(e,s)}_onNameChange(e,s,i){if(this._nameToAsset.has(i)){let r=this._nameToAsset.get(i);r.delete(e),r.size===0&&this._nameToAsset.delete(i)}this._nameToAsset.has(e.name)||this._nameToAsset.set(e.name,new Set),this._nameToAsset.get(e.name).add(e)}findByTag(...e){return this._tags.find(e)}filter(e){return Array.from(this._assets).filter(s=>e(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<e.length;s++)this._indexAssetInBundle(e[s],t)}else this._assetToBundles.has(t.id)&&this._indexAssetFileUrls(t)}_unbindAssetEvents(t){this._assets.off(`load:start:${t}`,this._onBundleLoadStart,this),this._assets.off(`load:${t}`,this._onBundleLoad,this),this._assets.off(`error:${t}`,this._onBundleError,this)}_indexAssetInBundle(t,e){let s=this._assetToBundles.get(t);s||(s=new Set,this._assetToBundles.set(t,s)),s.add(e);let i=this._assets.get(t);i&&this._indexAssetFileUrls(i)}_indexAssetFileUrls(t){let e=this._getAssetFileUrls(t);if(e)for(let s=0;s<e.length;s++){let i=this._assetToBundles.get(t.id);i&&this._urlsToBundles.set(e[s],i)}}_getAssetFileUrls(t){let e=t.getFileUrl();if(!e)return null;e=e.split("?")[0];let s=[e];if(t.type==="font"){let i=t.data.info.maps.length;for(let r=1;r<i;r++)s.push(e.replace(".png",`${r}.png`))}return s}_onAssetRemove(t){if(t.type==="bundle"){this._idToBundle.delete(t.id),this._unbindAssetEvents(t.id);let e=t.data.assets;for(let s=0;s<e.length;s++){let i=this._assetToBundles.get(e[s]);if(i&&(i.delete(t),i.size===0)){this._assetToBundles.delete(e[s]);for(let[r,a]of this._urlsToBundles)a===i&&this._urlsToBundles.delete(r)}}this._onBundleError(`Bundle ${t.id} was removed`)}else{if(!this._assetToBundles.get(t.id))return;this._assetToBundles.delete(t.id);let s=this._getAssetFileUrls(t);if(!s)return;for(let i=0;i<s.length;i++)this._urlsToBundles.delete(s[i])}}_onBundleLoadStart(t){t.resource.on("add",(e,s)=>{let i=this._fileRequests.get(e);if(i){for(let r=0;r<i.length;r++)i[r](null,s);this._fileRequests.delete(e)}})}_onBundleLoad(t){if(!t.resource){this._onBundleError(`Bundle ${t.id} failed to load`);return}if(this._fileRequests)for(let[e,s]of this._fileRequests){let i=this._urlsToBundles.get(e);if(!i||!i.has(t))continue;let r=decodeURIComponent(e),a,o;if(t.resource.has(r))o=t.resource.get(r);else if(t.resource.loaded)a=`Bundle ${t.id} does not contain URL ${e}`;else continue;for(let l=0;l<s.length;l++)s[l](a,a||o);this._fileRequests.delete(e)}}_onBundleError(t){for(let[e,s]of this._fileRequests)if(!this._findLoadedOrLoadingBundleForUrl(e)){for(let r=0;r<s.length;r++)s[r](t);this._fileRequests.delete(e)}}_findLoadedOrLoadingBundleForUrl(t){let e=this._urlsToBundles.get(t);if(!e)return null;let s=null;for(let i of e){if(i.loaded&&i.resource)return i;i.loading&&(s=i)}return s}listBundlesForAsset(t){let e=this._assetToBundles.get(t.id);return e?Array.from(e):null}list(){return Array.from(this._idToBundle.values())}hasUrl(t){return this._urlsToBundles.has(t)}urlIsLoadedOrLoading(t){return!!this._findLoadedOrLoadingBundleForUrl(t)}loadUrl(t,e){let s=this._findLoadedOrLoadingBundleForUrl(t);if(!s){e(`URL ${t} not found in any bundles`);return}if(s.loaded){let r=decodeURIComponent(t);if(s.resource.has(r)){e(null,s.resource.get(r));return}else if(s.resource.loaded){e(`Bundle ${s.id} does not contain URL ${t}`);return}}let i=this._fileRequests.get(t);i||(i=[],this._fileRequests.set(t,i)),i.push(e)}destroy(){this._assets.off("add",this._onAssetAdd,this),this._assets.off("remove",this._onAssetRemove,this);for(let t of this._idToBundle.keys())this._unbindAssetEvents(t);this._assets=null,this._idToBundle.clear(),this._idToBundle=null,this._assetToBundles.clear(),this._assetToBundles=null,this._urlsToBundles.clear(),this._urlsToBundles=null,this._fileRequests.clear(),this._fileRequests=null}};var mm=class extends J{constructor(){super();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,"joint");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,"zone");this.list=[]}add(e){let s=e.id;if(this[s])throw new Error(`ComponentSystem name '${s}' already registered or not allowed`);this[s]=e,this.list.push(e)}remove(e){let s=e.id;if(!this[s])throw new Error(`No ComponentSystem named '${s}' registered`);delete this[s];let i=this.list.indexOf(this[s]);i!==-1&&this.list.splice(i,1)}destroy(){this.off();for(let e=0;e<this.list.length;e++)this.list[e].destroy()}};var $c=class extends J{constructor(){super(...arguments);n(this,"_index",new Map);n(this,"_loaded",!1)}addFile(e,s){this._index.has(e)||(this._index.set(e,s),this.fire("add",e,s))}has(e){return this._index.has(e)}get(e){return this._index.get(e)||null}destroy(){this._index.clear()}set loaded(e){!e||this._loaded||(this._loaded=!0,this.fire("load"))}get loaded(){return this._loaded}};n($c,"EVENT_ADD","add"),n($c,"EVENT_LOAD","load");var t0=class extends J{constructor(e,s=""){super();n(this,"headerSize",512);n(this,"paddingSize",512);n(this,"bytesRead",0);n(this,"bytesReceived",0);n(this,"headerRead",!1);n(this,"reader",null);n(this,"data",new Uint8Array(0));n(this,"decoder",null);n(this,"prefix","");n(this,"fileName","");n(this,"fileSize",0);n(this,"fileType","");n(this,"ustarFormat","");this.prefix=s||"",this.reader=e.body.getReader(),this.reader.read().then(i=>{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<this.bytesRead+this.fileSize)return!1;if(this.fileType===""||this.fileType==="0"){let s=new DataView(this.data.buffer,this.bytesRead,this.fileSize),i={name:this.prefix+this.fileName,size:this.fileSize,data:s};this.fire("file",i)}this.bytesRead+=this.fileSize,this.headerRead=!1;let e=this.bytesRead%this.paddingSize;return e!==0&&(this.bytesRead+=this.paddingSize-e),!0}return!1}};var Re=class{constructor(t,e){n(this,"handlerType","");n(this,"_app");n(this,"_maxRetries",0);this._app=t,this.handlerType=e}set maxRetries(t){this._maxRetries=t}get maxRetries(){return this._maxRetries}load(t,e,s){}open(t,e,s){return e}patch(t,e){}};var _m=class extends Re{constructor(t){super(t,"bundle"),this._assets=t.assets}_fetchRetries(t,e,s=0){return new Promise((i,r)=>{let a=()=>{fetch(t,e).then(i).catch(o=>{s++,s<this.maxRetries?a():r(o)})};a()})}load(t,e){typeof t=="string"&&(t={load:t,original:t}),this._fetchRetries(t.load,{mode:"cors"},this.maxRetries).then(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;i<this._requests[t].length;i++)this._requests[t][i](null,e,s);delete this._requests[t]}_onFailure(t,e){if(this._requests[t]){for(let s=0;s<this._requests[t].length;s++)this._requests[t][s](e);delete this._requests[t]}}open(t,e){let s=this._handlers[t];return s?s.open(null,e):e}patch(t,e){let s=this._handlers[t.type];s&&s.patch&&s.patch(t,e)}clearCache(t,e){let s=c.makeKey(t,e);delete this._cache[s]}getFromCache(t,e){let s=c.makeKey(t,e);if(this._cache[s])return this._cache[s]}enableRetry(t=5){t=Math.max(0,Math.floor(t))||0;for(let e in this._handlers)this._handlers[e].maxRetries=t}disableRetry(){for(let t in this._handlers)this._handlers[t].maxRetries=0}destroy(){this._handlers={},this._requests={},this._cache={}}};var s0=class{_validate(t){if(!t.header)throw new Error('pc.I18n#addData: Missing "header" field');if(!t.header.version)throw new Error('pc.I18n#addData: Missing "header.version" field');if(t.header.version!==1)throw new Error('pc.I18n#addData: Invalid "header.version" field');if(t.data){if(!Array.isArray(t.data))throw new Error('pc.I18n#addData: "data" field must be an array')}else throw new Error('pc.I18n#addData: Missing "data" field');for(let e=0,s=t.data.length;e<s;e++){let i=t.data[e];if(!i.info)throw new Error(`pc.I18n#addData: missing "data[${e}].info" field`);if(!i.info.locale)throw new Error(`pc.I18n#addData: missing "data[${e}].info.locale" field`);if(typeof i.info.locale!="string")throw new Error(`pc.I18n#addData: "data[${e}].info.locale" must be a string`);if(!i.messages)throw new Error(`pc.I18n#addData: missing "data[${e}].messages" field`)}}parse(t){return t.data}};var i0=class i0 extends J{constructor(t){super(),this.locale=um,this._translations={},this._availableLangs={},this._app=t,this._assets=[],this._parser=new s0}set assets(t){let e={};for(let i=0,r=t.length;i<r;i++){let a=t[i]instanceof ae?t[i].id:t[i];e[a]=!0}let s=this._assets.length;for(;s--;){let i=this._assets[s];if(!e[i]){this._app.assets.off(`add:${i}`,this._onAssetAdd,this);let r=this._app.assets.get(i);r&&this._onAssetRemove(r),this._assets.splice(s,1)}}for(let i in e){let r=parseInt(i,10);if(this._assets.indexOf(r)!==-1)continue;this._assets.push(r);let a=this._app.assets.get(r);a?this._onAssetAdd(a):this._app.assets.once(`add:${r}`,this._onAssetAdd,this)}}get assets(){return this._assets}set locale(t){if(this._locale===t)return;let e=Zo(t);if(e==="in"&&(e="id",t=E2(t,e),this._locale===t))return;let s=this._locale;this._locale=t,this._lang=e,this._pluralFn=Qy(this._lang),this.fire(i0.EVENT_CHANGE,t,s)}get locale(){return this._locale}static findAvailableLocale(t,e){return Zy(t,e)}findAvailableLocale(t){if(this._translations[t])return t;let e=Zo(t);return this._findFallbackLocale(t,e)}getText(t,e){let s=t,i;e||(e=this._locale,i=this._lang);let r=this._translations[e];return r||(i||(i=Zo(e)),e=this._findFallbackLocale(e,i),r=this._translations[e]),r&&r.hasOwnProperty(t)&&(s=r[t],Array.isArray(s)&&(s=s[0]),s==null&&(s=t)),s}getPluralText(t,e,s){let i=t,r,a;s?(r=Zo(s),a=Qy(r)):(s=this._locale,r=this._lang,a=this._pluralFn);let o=this._translations[s];if(o||(s=this._findFallbackLocale(s,r),r=Zo(s),a=Qy(r),o=this._translations[s]),o&&o[t]&&a){let l=a(e);i=o[t][l],i==null&&(i=t)}return i}addData(t){let e;try{e=this._parser.parse(t)}catch{return}for(let s=0,i=e.length;s<i;s++){let r=e[s],a=r.info.locale,o=r.messages;if(!this._translations[a]){this._translations[a]={};let l=Zo(a);this._availableLangs[l]||(this._availableLangs[l]=a)}Object.assign(this._translations[a],o),this.fire("data:add",a,o)}}removeData(t){let e;try{e=this._parser.parse(t)}catch{return}for(let s=0,i=e.length;s<i;s++){let r=e[s],a=r.info.locale,o=this._translations[a];if(!o)continue;let l=r.messages;for(let h in l)delete o[h];Object.keys(o).length===0&&(delete this._translations[a],delete this._availableLangs[Zo(a)]),this.fire("data:remove",a,l)}}destroy(){this._translations=null,this._availableLangs=null,this._assets=null,this._parser=null,this.off()}_findFallbackLocale(t,e){let s=dm[t];return s&&this._translations[s]||(s=dm[e],s&&this._translations[s])||(s=this._availableLangs[e],s&&this._translations[s])?s:um}_onAssetAdd(t){t.on("load",this._onAssetLoad,this),t.on("change",this._onAssetChange,this),t.on("remove",this._onAssetRemove,this),t.on("unload",this._onAssetUnload,this),t.resource&&this._onAssetLoad(t)}_onAssetLoad(t){this.addData(t.resource)}_onAssetChange(t){t.resource&&this.addData(t.resource)}_onAssetRemove(t){t.off("load",this._onAssetLoad,this),t.off("change",this._onAssetChange,this),t.off("remove",this._onAssetRemove,this),t.off("unload",this._onAssetUnload,this),t.resource&&this.removeData(t.resource),this._app.assets.once(`add:${t.id}`,this._onAssetAdd,this)}_onAssetUnload(t){t.resource&&this.removeData(t.resource)}};n(i0,"EVENT_CHANGE","change");var fa=i0;var IS="initialize",RS="postInitialize",C2="update",P2="postUpdate",w2="swap",gm=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"]);var ks=class extends J{constructor(e){super();n(this,"app");n(this,"entity");n(this,"_enabled");n(this,"_enabledOld");n(this,"_initialized");n(this,"_postInitialized");n(this,"__destroyed");n(this,"__scriptType");n(this,"__executionOrder");this.initScript(e)}set enabled(e){this._enabled=!!e,this.enabled!==this._enabledOld&&(this._enabledOld=this.enabled,this.fire(this.enabled?"enable":"disable"),this.fire("state",this.enabled),!this._initialized&&this.enabled&&(this._initialized=!0,this.fire("preInitialize"),this.initialize&&this.entity.script._scriptMethod(this,IS)),this._initialized&&!this._postInitialized&&this.enabled&&!this.entity.script._beingEnabled&&(this._postInitialized=!0,this.postInitialize&&this.entity.script._scriptMethod(this,RS)))}get enabled(){return this._enabled&&!this._destroyed&&this.entity.script.enabled&&this.entity.enabled}initScript(e){let s=this.constructor;this.app=e.app,this.entity=e.entity,this._enabled=typeof e.enabled=="boolean"?e.enabled:!0,this._enabledOld=this.enabled,this.__destroyed=!1,this.__scriptType=s,this.__executionOrder=-1}static set scriptName(e){this.__name=e}static get scriptName(){return this.__name}};n(ks,"EVENT_ENABLE","enable"),n(ks,"EVENT_DISABLE","disable"),n(ks,"EVENT_STATE","state"),n(ks,"EVENT_DESTROY","destroy"),n(ks,"EVENT_ATTR","attr"),n(ks,"EVENT_ERROR","error"),n(ks,"__name",null),n(ks,"__getScriptName",r0);var T8=/^\s*function(?:\s|\s*\/\*.*\*\/\s*)+([^(\s\/]*)\s*/,y8=c=>c&&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.loopIndex<i.length;i.loopIndex++){let l=i.items[i.loopIndex];if(l._scriptsIndex[s]&&l._scriptsIndex[s].awaiting){l._scriptsData&&l._scriptsData[s]&&(r=l._scriptsData[s].attributes);let h=l.create(s,{preloading:!0,ind:l._scriptsIndex[s].ind,attributes:r});h&&a.push(h);for(let f of l.scripts)l.initializeAttributes(f)}}for(let l=0;l<a.length;l++)a[l].enabled&&(a[l]._initialized=!0,o.push(a[l]),a[l].initialize&&a[l].initialize());for(let l=0;l<o.length;l++)!o[l].enabled||o[l]._postInitialized||(o[l]._postInitialized=!0,o[l].postInitialize&&o[l].postInitialize())}),!0))}remove(e){let s=e,i=e;if(typeof i!="string"?i=s.__name:s=this.get(i),this.get(i)!==s)return!1;this._scripts.delete(i);let r=this._list.indexOf(s);return this._list.splice(r,1),this.fire("remove",i,s),this.fire(`remove:${i}`,s),!0}get(e){return this._scripts.get(e)||null}has(e){if(typeof e=="string")return this._scripts.has(e);if(!e)return!1;let s=e.__name;return this._scripts.get(s)===e}list(){return this._list}};var E8=(c,t)=>c.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;a<o;a++)r[a]._enabled&&this._notifyHierarchyStateChanged(r[a],s);if(e._beingEnabled=!1,i){for(let a=0;a<bS.length;a++)bS[a]._onHierarchyStatePostChanged();bS.length=0}}_onHierarchyStateChanged(e){super._onHierarchyStateChanged(e);let s=this._getSortedComponents();for(let i=0;i<s.length;i++){let r=s[i];r.enabled&&(e?r.onEnable():r.onDisable())}I2(s)}_onHierarchyStatePostChanged(){let e=this._getSortedComponents();for(let s=0;s<e.length;s++)e[s].onPostStateChange();I2(e)}findByGuid(e){if(this._guid===e)return this;let s=this._app._entityIndex[e];return s&&(s===this||s.isDescendantOf(this))?s:null}destroy(){this._destroying=!0;for(let e in this.c)this.c[e].enabled=!1;for(let e in this.c)this.c[e].system.removeComponent(this);super.destroy(),this._guid&&delete this._app._entityIndex[this._guid],this._destroying=!1}clone(){let e={},s=this._cloneRecursively(e);return e[this.guid]=s,b2(this,this,s,e),s}_getSortedComponents(){let e=this.c,s=C8(),i=0;for(let r in e)if(e.hasOwnProperty(r)){let a=e[r];i|=a.constructor.order!==0,s.push(a)}return i&&s.length>1&&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;i<this._children.length;i++){let r=this._children[i];if(r instanceof a0){let a=r._cloneRecursively(e);s.addChild(a),e[r.guid]=a}}return s}};n(a0,"EVENT_DESTROY","destroy");var Ne=a0;function b2(c,t,e,s){if(t instanceof Ne){let i=t.c;for(let o in i){let l=i[o],h=l.system.getPropertiesOfType("entity");for(let f=0,u=h.length;f<u;f++){let p=h[f].name,m=l[p];if(!!c.findByGuid(m)){let S=s[m].guid;S&&(e.c[o][p]=S)}}}i.script&&e.script.resolveDuplicatedEntityReferenceProperties(i.script,s),i.render&&e.render.resolveDuplicatedEntityReferenceProperties(i.render,s),i.button&&e.button.resolveDuplicatedEntityReferenceProperties(i.button,s),i.scrollview&&e.scrollview.resolveDuplicatedEntityReferenceProperties(i.scrollview,s),i.scrollbar&&e.scrollbar.resolveDuplicatedEntityReferenceProperties(i.scrollbar,s),i.anim&&e.anim.resolveDuplicatedEntityReferenceProperties(i.anim,s);let r=t.children.filter(o=>o instanceof Ne),a=e.children.filter(o=>o instanceof Ne);for(let o=0,l=r.length;o<l;o++)b2(c,r[o],a[o],s)}}var au=class{constructor(t,e){n(this,"name");n(this,"url");n(this,"data",null);n(this,"_loading",!1);n(this,"_onLoadedCallbacks",[]);this.name=t,this.url=e}get loaded(){return!!this.data}get loading(){return this._loading}};var xm=class{constructor(t){n(this,"_app");n(this,"_list",[]);n(this,"_index",{});n(this,"_urlIndex",{});this._app=t}destroy(){this._app=null}list(){return this._list}add(t,e){if(this._index.hasOwnProperty(t))return!1;let s=new au(t,e),i=this._list.push(s);return this._index[s.name]=i-1,this._urlIndex[s.url]=i-1,!0}find(t){return this._index.hasOwnProperty(t)?this._list[this._index[t]]:null}findByUrl(t){return this._urlIndex.hasOwnProperty(t)?this._list[this._urlIndex[t]]:null}remove(t){if(this._index.hasOwnProperty(t)){let e=this._index[t],s=this._list[e];delete this._urlIndex[s.url],delete this._index[t],this._list.splice(e,1);for(let i=0;i<this._list.length;i++)s=this._list[i],this._index[s.name]=i,this._urlIndex[s.url]=i}}_loadSceneData(t,e,s){let i=this._app,r=t;if(typeof t=="string"&&(t=this.findByUrl(r)||this.find(r)||new au("Untitled",r)),r=t.url,!r){s("Cannot find scene to load");return}if(t.loaded){s(null,t);return}i.assets&&i.assets.prefix&&!Ja.test(r)&&(r=xe.join(i.assets.prefix,r)),t._onLoadedCallbacks.push(s),t._loading||i.loader.getHandler("hierarchy").load(r,(o,l)=>{t.data=l,t._loading=!1;for(let h=0;h<t._onLoadedCallbacks.length;h++)t._onLoadedCallbacks[h](o,t);e||(t.data=null),t._onLoadedCallbacks.length=0}),t._loading=!0}loadSceneData(t,e){this._loadSceneData(t,!0,e)}unloadSceneData(t){typeof t=="string"&&(t=this.findByUrl(t)),t&&(t.data=null)}_loadSceneHierarchy(t,e,s){this._loadSceneData(t,!1,(i,r)=>{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<i.length;r++)r<Yt&&(s.otherPrimitives+=i[r]),i[r]=0;t._camerasRendered=0,t._materialSwitches=0,t._shadowMapUpdates=0,e._shaderSwitchesPerFrame=0,t._cullTime=0,t._layerCompositionUpdateTime=0,t._lightClustersTime=0,t._sortTime=0,t._skinTime=0,t._morphTime=0,t._shadowMapTime=0,t._depthMapTime=0,t._forwardTime=0,s=this.drawCalls,s.forward=t._forwardDrawCalls,s.culled=t._numDrawCallsCulled,s.depth=0,s.shadow=t._shadowDrawCalls,s.skinned=t._skinDrawCalls,s.immediate=0,s.instanced=0,s.removedByInstancing=0,s.misc=s.total-(s.forward+s.shadow),t._depthDrawCalls=0,t._shadowDrawCalls=0,t._forwardDrawCalls=0,t._numDrawCallsCulled=0,t._skinDrawCalls=0,t._immediateRendered=0,t._instancedDrawCalls=0,this.misc.renderTargetCreationTime=e.renderTargetCreationTime,s=this.particles,s.updatesPerFrame=s._updatesPerFrame,s.frameTime=s._frameTime,s._updatesPerFrame=0,s._frameTime=0}frameEnd(){this.frame.gsplatSort=0}};var D2=`
uniform float alpha_ref;
void alphaTest(float a) {
if (a < alpha_ref) discard;
}
`;var L2=`
#ifdef LIT_AMBIENT_SOURCE == AMBIENTSH
uniform vec3 ambientSH[9];
#endif
#if LIT_AMBIENT_SOURCE == ENVALATLAS
#include "envAtlasPS"
#ifndef ENV_ATLAS
#define ENV_ATLAS
uniform sampler2D texture_envAtlas;
#endif
#endif
void addAmbient(vec3 worldNormal) {
#ifdef LIT_AMBIENT_SOURCE == AMBIENTSH
vec3 n = cubeMapRotate(worldNormal);
vec3 color =
ambientSH[0] +
ambientSH[1] * n.x +
ambientSH[2] * n.y +
ambientSH[3] * n.z +
ambientSH[4] * n.x * n.z +
ambientSH[5] * n.z * n.y +
ambientSH[6] * n.y * n.x +
ambientSH[7] * (3.0 * n.z * n.z - 1.0) +
ambientSH[8] * (n.x * n.x - n.y * n.y);
dDiffuseLight += processEnvironment(max(color, vec3(0.0)));
#endif
#if LIT_AMBIENT_SOURCE == ENVALATLAS
vec3 dir = normalize(cubeMapRotate(worldNormal) * vec3(-1.0, 1.0, 1.0));
vec2 uv = mapUv(toSphericalUv(dir), vec4(128.0, 256.0 + 128.0, 64.0, 32.0) / atlasSize);
vec4 raw = texture2D(texture_envAtlas, uv);
vec3 linear = {ambientDecode}(raw);
dDiffuseLight += processEnvironment(linear);
#endif
#if LIT_AMBIENT_SOURCE == CONSTANT
dDiffuseLight += light_globalAmbient;
#endif
}
`;var M2=`
#ifdef LIT_GGX_SPECULAR
uniform float material_anisotropyIntensity;
uniform vec2 material_anisotropyRotation;
#endif
void getAnisotropy() {
dAnisotropy = 0.0;
dAnisotropyRotation = vec2(1.0, 0.0);
#ifdef LIT_GGX_SPECULAR
dAnisotropy = material_anisotropyIntensity;
dAnisotropyRotation = material_anisotropyRotation;
#endif
#ifdef STD_ANISOTROPY_TEXTURE
vec3 anisotropyTex = texture2DBias({STD_ANISOTROPY_TEXTURE_NAME}, {STD_ANISOTROPY_TEXTURE_UV}, textureBias).rgb;
dAnisotropy *= anisotropyTex.b;
vec2 anisotropyRotationFromTex = anisotropyTex.rg * 2.0 - vec2(1.0);
mat2 rotationMatrix = mat2(dAnisotropyRotation.x, dAnisotropyRotation.y, -dAnisotropyRotation.y, dAnisotropyRotation.x);
dAnisotropyRotation = rotationMatrix * anisotropyRotationFromTex;
#endif
dAnisotropy = clamp(dAnisotropy, 0.0, 1.0);
}
`;var O2=`
#if defined(STD_AO_TEXTURE) || defined(STD_AO_VERTEX)
uniform float material_aoIntensity;
#endif
#ifdef STD_AODETAIL_TEXTURE
#include "detailModesPS"
#endif
void getAO() {
dAo = 1.0;
#ifdef STD_AO_TEXTURE
float aoBase = texture2DBias({STD_AO_TEXTURE_NAME}, {STD_AO_TEXTURE_UV}, textureBias).{STD_AO_TEXTURE_CHANNEL};
#ifdef STD_AODETAIL_TEXTURE
float aoDetail = texture2DBias({STD_AODETAIL_TEXTURE_NAME}, {STD_AODETAIL_TEXTURE_UV}, textureBias).{STD_AODETAIL_TEXTURE_CHANNEL};
aoBase = detailMode_{STD_AODETAIL_DETAILMODE}(vec3(aoBase), vec3(aoDetail)).r;
#endif
dAo *= aoBase;
#endif
#ifdef STD_AO_VERTEX
dAo *= saturate(vVertexColor.{STD_AO_VERTEX_CHANNEL});
#endif
#if defined(STD_AO_TEXTURE) || defined(STD_AO_VERTEX)
dAo = mix(1.0, dAo, material_aoIntensity);
#endif
}
`;var F2=`
void occludeDiffuse(float ao) {
dDiffuseLight *= ao;
}
`;var N2=`
#if LIT_OCCLUDE_SPECULAR != NONE
#ifdef LIT_OCCLUDE_SPECULAR_FLOAT
uniform float material_occludeSpecularIntensity;
#endif
#endif
void occludeSpecular(float gloss, float ao, vec3 worldNormal, vec3 viewDir) {
#if LIT_OCCLUDE_SPECULAR == AO
#ifdef LIT_OCCLUDE_SPECULAR_FLOAT
float specOcc = mix(1.0, ao, material_occludeSpecularIntensity);
#else
float specOcc = ao;
#endif
#endif
#if LIT_OCCLUDE_SPECULAR == GLOSSDEPENDENT
float specPow = exp2(gloss * 11.0);
float specOcc = saturate(pow(dot(worldNormal, viewDir) + ao, 0.01 * specPow) - 1.0 + ao);
#ifdef LIT_OCCLUDE_SPECULAR_FLOAT
specOcc = mix(1.0, specOcc, material_occludeSpecularIntensity);
#endif
#endif
#if LIT_OCCLUDE_SPECULAR != NONE
dSpecularLight *= specOcc;
dReflection *= specOcc;
#ifdef LIT_SHEEN
sSpecularLight *= specOcc;
sReflection *= specOcc;
#endif
#endif
}
`;var B2=`
vec4 dirLm = texture2D(texture_dirLightMap, vUv1);
if (bakeDir > 0.5) {
if (dAtten > 0.00001) {
dirLm.xyz = dirLm.xyz * 2.0 - vec3(1.0);
dAtten = saturate(dAtten);
gl_FragColor.rgb = normalize(dLightDirNormW.xyz*dAtten + dirLm.xyz*dirLm.w) * 0.5 + vec3(0.5);
gl_FragColor.a = dirLm.w + dAtten;
gl_FragColor.a = max(gl_FragColor.a, 1.0 / 255.0);
} else {
gl_FragColor = dirLm;
}
} else {
gl_FragColor.rgb = dirLm.xyz;
gl_FragColor.a = max(dirLm.w, dAtten > 0.00001 ? (1.0/255.0) : 0.0);
}
`;var U2=`
#ifdef LIT_LIGHTMAP_BAKING_ADD_AMBIENT
dDiffuseLight = ((dDiffuseLight - 0.5) * max(ambientBakeOcclusionContrast + 1.0, 0.0)) + 0.5;
dDiffuseLight += vec3(ambientBakeOcclusionBrightness);
dDiffuseLight = saturate(dDiffuseLight);
dDiffuseLight *= dAmbientLight;
#endif
#ifdef LIGHTMAP_RGBM
gl_FragColor.rgb = dDiffuseLight;
gl_FragColor.rgb = pow(gl_FragColor.rgb, vec3(0.5));
gl_FragColor.rgb /= 8.0;
gl_FragColor.a = clamp( max( max( gl_FragColor.r, gl_FragColor.g ), max( gl_FragColor.b, 1.0 / 255.0 ) ), 0.0,1.0 );
gl_FragColor.a = ceil(gl_FragColor.a * 255.0) / 255.0;
gl_FragColor.rgb /= gl_FragColor.a;
#else
gl_FragColor = vec4(dDiffuseLight, 1.0);
#endif
`;var k2=`
uniform vec3 view_position;
uniform vec3 light_globalAmbient;
float square(float x) {
return x*x;
}
float saturate(float x) {
return clamp(x, 0.0, 1.0);
}
vec3 saturate(vec3 x) {
return clamp(x, vec3(0.0), vec3(1.0));
}
`;var z2=`
#define NINESLICED
varying vec2 vMask;
varying vec2 vTiledUv;
uniform mediump vec4 innerOffset;
uniform mediump vec2 outerScale;
uniform mediump vec4 atlasRect;
vec2 nineSlicedUv;
`;var G2=`
#define NINESLICED
#define NINESLICETILED
varying vec2 vMask;
varying vec2 vTiledUv;
uniform mediump vec4 innerOffset;
uniform mediump vec2 outerScale;
uniform mediump vec4 atlasRect;
vec2 nineSlicedUv;
`;var V2=`
float bayer2(vec2 p) {
return mod(2.0 * p.y + p.x + 1.0, 4.0);
}
float bayer4(vec2 p) {
vec2 p1 = mod(p, 2.0);
vec2 p2 = floor(0.5 * mod(p, 4.0));
return 4.0 * bayer2(p1) + bayer2(p2);
}
float bayer8(vec2 p) {
vec2 p1 = mod(p, 2.0);
vec2 p2 = floor(0.5 * mod(p, 4.0));
vec2 p4 = floor(0.25 * mod(p, 8.0));
return 4.0 * (4.0 * bayer2(p1) + bayer2(p2)) + bayer2(p4);
}
`;var H2=`
varying vec2 vUv0;
uniform sampler2D source;
uniform vec2 pixelOffset;
#ifdef GAUSS
uniform float weight[{SAMPLES}];
#endif
void main(void) {
vec3 moments = vec3(0.0);
vec2 uv = vUv0 - pixelOffset * (float({SAMPLES}) * 0.5);
for (int i = 0; i < {SAMPLES}; i++) {
vec4 c = texture2D(source, uv + pixelOffset * float(i));
#ifdef GAUSS
moments += c.xyz * weight[i];
#else
moments += c.xyz;
#endif
}
#ifndef GAUSS
moments *= 1.0 / float({SAMPLES});
#endif
gl_FragColor = vec4(moments.x, moments.y, moments.z, 1.0);
}
`;var W2=`
uniform float material_clearCoat;
void getClearCoat() {
ccSpecularity = material_clearCoat;
#ifdef STD_CLEARCOAT_TEXTURE
ccSpecularity *= texture2DBias({STD_CLEARCOAT_TEXTURE_NAME}, {STD_CLEARCOAT_TEXTURE_UV}, textureBias).{STD_CLEARCOAT_TEXTURE_CHANNEL};
#endif
#ifdef STD_CLEARCOAT_VERTEX
ccSpecularity *= saturate(vVertexColor.{STD_CLEARCOAT_VERTEX_CHANNEL});
#endif
}
`;var X2=`
uniform float material_clearCoatGloss;
void getClearCoatGlossiness() {
ccGlossiness = material_clearCoatGloss;
#ifdef STD_CLEARCOATGLOSS_TEXTURE
ccGlossiness *= texture2DBias({STD_CLEARCOATGLOSS_TEXTURE_NAME}, {STD_CLEARCOATGLOSS_TEXTURE_UV}, textureBias).{STD_CLEARCOATGLOSS_TEXTURE_CHANNEL};
#endif
#ifdef STD_CLEARCOATGLOSS_VERTEX
ccGlossiness *= saturate(vVertexColor.{STD_CLEARCOATGLOSS_VERTEX_CHANNEL});
#endif
#ifdef STD_CLEARCOATGLOSS_INVERT
ccGlossiness = 1.0 - ccGlossiness;
#endif
ccGlossiness += 0.0000001;
}
`;var Y2=`
#ifdef STD_CLEARCOATNORMAL_TEXTURE
uniform float material_clearCoatBumpiness;
#endif
void getClearCoatNormal() {
#ifdef STD_CLEARCOATNORMAL_TEXTURE
vec3 normalMap = {STD_CLEARCOATNORMAL_TEXTURE_DECODE}(texture2DBias({STD_CLEARCOATNORMAL_TEXTURE_NAME}, {STD_CLEARCOATNORMAL_TEXTURE_UV}, textureBias));
normalMap = mix(vec3(0.0, 0.0, 1.0), normalMap, material_clearCoatBumpiness);
ccNormalW = normalize(dTBN * normalMap);
#else
ccNormalW = dVertexNormalW;
#endif
}
`;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;
return isRgb ? pixel.rgb : vec3(dot(pixel, cookieChannel));
}
vec3 getCookie2DClustered(TEXTURE_ACCEPT(tex), mat4 transform, vec3 worldPosition, float intensity, vec4 cookieChannel) {
vec4 projPos = transform * vec4(worldPosition, 1.0);
return _getCookieClustered(TEXTURE_PASS(tex), projPos.xy / projPos.w, intensity, cookieChannel);
}
vec3 getCookieCubeClustered(TEXTURE_ACCEPT(tex), vec3 dir, float intensity, vec4 cookieChannel, float shadowTextureResolution, float shadowEdgePixels, vec3 omniAtlasViewport) {
vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir);
return _getCookieClustered(TEXTURE_PASS(tex), uv, intensity, cookieChannel);
}
`;var q2=`
vec3 _getShadowCoordPerspZbuffer(mat4 shadowMatrix, vec4 shadowParams, vec3 wPos) {
vec4 projPos = shadowMatrix * vec4(wPos, 1.0);
projPos.xyz /= projPos.w;
return projPos.xyz;
}
vec3 getShadowCoordPerspZbufferNormalOffset(mat4 shadowMatrix, vec4 shadowParams, vec3 normal) {
vec3 wPos = vPositionW + normal * shadowParams.y;
return _getShadowCoordPerspZbuffer(shadowMatrix, shadowParams, wPos);
}
vec3 normalOffsetPointShadow(vec4 shadowParams, vec3 lightPos, vec3 lightDir, vec3 lightDirNorm, vec3 normal) {
float distScale = length(lightDir);
vec3 wPos = vPositionW + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;
vec3 dir = wPos - lightPos;
return dir;
}
#if defined(CLUSTER_SHADOW_TYPE_PCF1)
float getShadowOmniClusteredPCF1(SHADOWMAP_ACCEPT(shadowMap), vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {
float shadowTextureResolution = shadowParams.x;
vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);
float shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;
return textureShadow(shadowMap, vec3(uv, shadowZ));
}
#endif
#if defined(CLUSTER_SHADOW_TYPE_PCF3)
float getShadowOmniClusteredPCF3(SHADOWMAP_ACCEPT(shadowMap), vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {
float shadowTextureResolution = shadowParams.x;
vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);
float shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;
vec3 shadowCoord = vec3(uv, shadowZ);
return getShadowPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams);
}
#endif
#if defined(CLUSTER_SHADOW_TYPE_PCF5)
float getShadowOmniClusteredPCF5(SHADOWMAP_ACCEPT(shadowMap), vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) {
float shadowTextureResolution = shadowParams.x;
vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);
float shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;
vec3 shadowCoord = vec3(uv, shadowZ);
return getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams);
}
#endif
#if defined(CLUSTER_SHADOW_TYPE_PCF1)
float getShadowSpotClusteredPCF1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {
return textureShadow(shadowMap, shadowCoord);
}
#endif
#if defined(CLUSTER_SHADOW_TYPE_PCF3)
float getShadowSpotClusteredPCF3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {
return getShadowSpotPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams);
}
#endif
#if defined(CLUSTER_SHADOW_TYPE_PCF5)
float getShadowSpotClusteredPCF5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {
return getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams);
}
#endif
`;var $2=`
#include "lightBufferDefinesPS"
#include "clusteredLightUtilsPS"
#ifdef CLUSTER_COOKIES
#include "clusteredLightCookiesPS"
#endif
#ifdef CLUSTER_SHADOWS
#include "clusteredLightShadowsPS"
#endif
uniform highp usampler2D clusterWorldTexture;
uniform highp sampler2D lightsTexture;
#ifdef CLUSTER_SHADOWS
uniform sampler2DShadow shadowAtlasTexture;
#endif
#ifdef CLUSTER_COOKIES
uniform sampler2D cookieAtlasTexture;
#endif
uniform int clusterMaxCells;
uniform int numClusteredLights;
uniform int clusterTextureWidth;
uniform vec3 clusterCellsCountByBoundsSize;
uniform vec3 clusterBoundsMin;
uniform vec3 clusterBoundsDelta;
uniform ivec3 clusterCellsDot;
uniform ivec3 clusterCellsMax;
uniform vec2 shadowAtlasParams;
struct ClusterLightData {
vec3 position;
int lightIndex;
vec3 direction;
uint shape;
vec3 color;
float shadowIntensity;
float range;
float biasesData;
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(int lightIndex, int index) {
return texelFetch(lightsTexture, ivec2(index, lightIndex), 0);
}
ClusterLightData decodeClusterLightCore(int lightIndex) {
ClusterLightData clusterLightData;
clusterLightData.lightIndex = lightIndex;
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(lightIndex, {CLUSTER_TEXTURE_POSITION_RANGE});
clusterLightData.position = lightPosRange.xyz;
clusterLightData.range = lightPosRange.w;
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;
clusterLightData.shape = (clusterLightData_flags >> 28u) & 0x3u;
clusterLightData.falloffModeLinear = (clusterLightData_flags & (1u << 27u)) == 0u;
clusterLightData.shadowIntensity = float((clusterLightData_flags >> 0u) & 0xFFu) / 255.0;
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;
}
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);
return ClusterLightSpotData(
mix(innerVal, 1.0 - innerVal, innerIsVersine),
mix(outerVal, 1.0 - outerVal, outerIsVersine)
);
}
vec3 decodeClusterLightOmniAtlasViewport(int lightIndex) {
return sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_0}).xyz;
}
ClusterLightAreaData decodeClusterLightAreaData(int lightIndex) {
return ClusterLightAreaData(
sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_AREA_DATA_WIDTH}).xyz,
sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_AREA_DATA_HEIGHT}).xyz
);
}
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);
}
ClusterLightShadowData decodeClusterLightShadowData(float biasesData) {
vec2 biases = unpackHalf2x16(floatBitsToUint(biasesData));
return ClusterLightShadowData(biases.x, biases.y);
}
vec4 decodeClusterLightCookieData() {
uint cookieFlags = (clusterLightData_flags >> 23u) & 0x0Fu;
vec4 mask = vec4(uvec4(cookieFlags) & uvec4(1u, 2u, 4u, 8u));
return step(1.0, mask);
}
void evaluateLight(
ClusterLightData light,
vec3 worldNormal,
vec3 viewDir,
vec3 reflectionDir,
#if defined(LIT_CLEARCOAT)
vec3 clearcoatReflectionDir,
#endif
float gloss,
vec3 specularity,
vec3 geometricNormal,
mat3 tbn,
#if defined(LIT_IRIDESCENCE)
vec3 iridescenceFresnel,
#endif
vec3 clearcoat_worldNormal,
float clearcoat_gloss,
float sheen_gloss,
float iridescence_intensity
) {
vec3 cookieAttenuation = vec3(1.0);
float diffuseAttenuation = 1.0;
float falloffAttenuation = 1.0;
vec3 lightDirW = evalOmniLight(light.position);
vec3 lightDirNormW = normalize(lightDirW);
#ifdef CLUSTER_AREALIGHTS
if (light.shape != {LIGHTSHAPE_PUNCTUAL}) {
ClusterLightAreaData areaData = decodeClusterLightAreaData(light.lightIndex);
if (light.shape == {LIGHTSHAPE_RECT}) {
calcRectLightValues(light.position, areaData.halfWidth, areaData.halfHeight);
} else if (light.shape == {LIGHTSHAPE_DISK}) {
calcDiskLightValues(light.position, areaData.halfWidth, areaData.halfHeight);
} else {
calcSphereLightValues(light.position, areaData.halfWidth, areaData.halfHeight);
}
falloffAttenuation = getFalloffWindow(light.range, lightDirW);
} else
#endif
{
if (light.falloffModeLinear)
falloffAttenuation = getFalloffLinear(light.range, lightDirW);
else
falloffAttenuation = getFalloffInvSquared(light.range, lightDirW);
}
if (falloffAttenuation > 0.00001) {
#ifdef CLUSTER_AREALIGHTS
if (light.shape != {LIGHTSHAPE_PUNCTUAL}) {
if (light.shape == {LIGHTSHAPE_RECT}) {
diffuseAttenuation = getRectLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0;
} else if (light.shape == {LIGHTSHAPE_DISK}) {
diffuseAttenuation = getDiskLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0;
} else {
diffuseAttenuation = getSphereLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0;
}
} else
#endif
{
falloffAttenuation *= getLightDiffuse(worldNormal, viewDir, lightDirNormW);
}
if (light.isSpot) {
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) {
lightProjectionMatrix = decodeClusterLightProjectionMatrixData(light.lightIndex);
} else {
omniAtlasViewport = decodeClusterLightOmniAtlasViewport(light.lightIndex);
}
float shadowTextureResolution = shadowAtlasParams.x;
float shadowEdgePixels = shadowAtlasParams.y;
#ifdef CLUSTER_COOKIES
if (light.cookieIntensity > 0.0) {
vec4 cookieChannelMask = decodeClusterLightCookieData();
if (light.isSpot) {
cookieAttenuation = getCookie2DClustered(TEXTURE_PASS(cookieAtlasTexture), lightProjectionMatrix, vPositionW, light.cookieIntensity, cookieChannelMask);
} else {
cookieAttenuation = getCookieCubeClustered(TEXTURE_PASS(cookieAtlasTexture), lightDirW, light.cookieIntensity, cookieChannelMask, shadowTextureResolution, shadowEdgePixels, omniAtlasViewport);
}
}
#endif
#ifdef CLUSTER_SHADOWS
if (light.shadowIntensity > 0.0) {
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);
#if defined(CLUSTER_SHADOW_TYPE_PCF1)
float shadow = getShadowSpotClusteredPCF1(SHADOWMAP_PASS(shadowAtlasTexture), shadowCoord, shadowParams);
#elif defined(CLUSTER_SHADOW_TYPE_PCF3)
float shadow = getShadowSpotClusteredPCF3(SHADOWMAP_PASS(shadowAtlasTexture), shadowCoord, shadowParams);
#elif defined(CLUSTER_SHADOW_TYPE_PCF5)
float shadow = getShadowSpotClusteredPCF5(SHADOWMAP_PASS(shadowAtlasTexture), shadowCoord, shadowParams);
#elif defined(CLUSTER_SHADOW_TYPE_PCSS)
float shadow = getShadowSpotClusteredPCSS(SHADOWMAP_PASS(shadowAtlasTexture), shadowCoord, shadowParams);
#endif
falloffAttenuation *= mix(1.0, shadow, light.shadowIntensity);
} else {
vec3 dir = normalOffsetPointShadow(shadowParams, light.position, lightDirW, lightDirNormW, geometricNormal);
#if defined(CLUSTER_SHADOW_TYPE_PCF1)
float shadow = getShadowOmniClusteredPCF1(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, omniAtlasViewport, shadowEdgePixels, dir);
#elif defined(CLUSTER_SHADOW_TYPE_PCF3)
float shadow = getShadowOmniClusteredPCF3(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, omniAtlasViewport, shadowEdgePixels, dir);
#elif defined(CLUSTER_SHADOW_TYPE_PCF5)
float shadow = getShadowOmniClusteredPCF5(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, omniAtlasViewport, shadowEdgePixels, dir);
#endif
falloffAttenuation *= mix(1.0, shadow, light.shadowIntensity);
}
}
#endif
}
}
#endif
#ifdef CLUSTER_AREALIGHTS
if (light.shape != {LIGHTSHAPE_PUNCTUAL}) {
{
vec3 areaDiffuse = (diffuseAttenuation * falloffAttenuation) * light.color * cookieAttenuation;
#if defined(LIT_SPECULAR)
areaDiffuse = mix(areaDiffuse, vec3(0), dLTCSpecFres);
#endif
dDiffuseLight += areaDiffuse;
}
#ifdef LIT_SPECULAR
float areaLightSpecular;
if (light.shape == {LIGHTSHAPE_RECT}) {
areaLightSpecular = getRectLightSpecular(worldNormal, viewDir);
} else if (light.shape == {LIGHTSHAPE_DISK}) {
areaLightSpecular = getDiskLightSpecular(worldNormal, viewDir);
} else {
areaLightSpecular = getSphereLightSpecular(worldNormal, viewDir);
}
dSpecularLight += dLTCSpecFres * areaLightSpecular * falloffAttenuation * light.color * cookieAttenuation;
#ifdef LIT_CLEARCOAT
float areaLightSpecularCC;
if (light.shape == {LIGHTSHAPE_RECT}) {
areaLightSpecularCC = getRectLightSpecular(clearcoat_worldNormal, viewDir);
} else if (light.shape == {LIGHTSHAPE_DISK}) {
areaLightSpecularCC = getDiskLightSpecular(clearcoat_worldNormal, viewDir);
} else {
areaLightSpecularCC = getSphereLightSpecular(clearcoat_worldNormal, viewDir);
}
ccSpecularLight += ccLTCSpecFres * areaLightSpecularCC * falloffAttenuation * light.color * cookieAttenuation;
#endif
#endif
} else
#endif
{
{
vec3 punctualDiffuse = falloffAttenuation * light.color * cookieAttenuation;
#if defined(CLUSTER_AREALIGHTS)
#if defined(LIT_SPECULAR)
punctualDiffuse = mix(punctualDiffuse, vec3(0), specularity);
#endif
#endif
dDiffuseLight += punctualDiffuse;
}
#ifdef LIT_SPECULAR
vec3 halfDir = normalize(-lightDirNormW + viewDir);
#ifdef LIT_SPECULAR_FRESNEL
dSpecularLight +=
getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, lightDirNormW, gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation *
getFresnel(
dot(viewDir, halfDir),
gloss,
specularity
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
iridescence_intensity
#endif
);
#else
dSpecularLight += getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, lightDirNormW, gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * specularity;
#endif
#ifdef LIT_CLEARCOAT
#ifdef LIT_SPECULAR_FRESNEL
ccSpecularLight += getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat_worldNormal, viewDir, lightDirNormW, clearcoat_gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * getFresnelCC(dot(viewDir, halfDir));
#else
ccSpecularLight += getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat_worldNormal, viewDir, lightDirNormW, clearcoat_gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation;
#endif
#endif
#ifdef LIT_SHEEN
sSpecularLight += getLightSpecularSheen(halfDir, worldNormal, viewDir, lightDirNormW, sheen_gloss) * falloffAttenuation * light.color * cookieAttenuation;
#endif
#endif
}
}
dAtten = falloffAttenuation;
dLightDirNormW = lightDirNormW;
}
void evaluateClusterLight(
int lightIndex,
vec3 worldNormal,
vec3 viewDir,
vec3 reflectionDir,
#if defined(LIT_CLEARCOAT)
vec3 clearcoatReflectionDir,
#endif
float gloss,
vec3 specularity,
vec3 geometricNormal,
mat3 tbn,
#if defined(LIT_IRIDESCENCE)
vec3 iridescenceFresnel,
#endif
vec3 clearcoat_worldNormal,
float clearcoat_gloss,
float sheen_gloss,
float iridescence_intensity
) {
ClusterLightData clusterLightData = decodeClusterLightCore(lightIndex);
#ifdef CLUSTER_MESH_DYNAMIC_LIGHTS
bool acceptLightMask = clusterLightData.isDynamic;
#else
bool acceptLightMask = clusterLightData.isLightmapped;
#endif
if (acceptLightMask)
evaluateLight(
clusterLightData,
worldNormal,
viewDir,
reflectionDir,
#if defined(LIT_CLEARCOAT)
clearcoatReflectionDir,
#endif
gloss,
specularity,
geometricNormal,
tbn,
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel,
#endif
clearcoat_worldNormal,
clearcoat_gloss,
sheen_gloss,
iridescence_intensity
);
}
void addClusteredLights(
vec3 worldNormal,
vec3 viewDir,
vec3 reflectionDir,
#if defined(LIT_CLEARCOAT)
vec3 clearcoatReflectionDir,
#endif
float gloss,
vec3 specularity,
vec3 geometricNormal,
mat3 tbn,
#if defined(LIT_IRIDESCENCE)
vec3 iridescenceFresnel,
#endif
vec3 clearcoat_worldNormal,
float clearcoat_gloss,
float sheen_gloss,
float iridescence_intensity
) {
if (numClusteredLights <= 1)
return;
ivec3 cellCoords = ivec3(floor((vPositionW - clusterBoundsMin) * clusterCellsCountByBoundsSize));
if (!(any(lessThan(cellCoords, ivec3(0))) || any(greaterThanEqual(cellCoords, clusterCellsMax)))) {
int cellIndex = cellCoords.x * clusterCellsDot.x + cellCoords.y * clusterCellsDot.y + cellCoords.z * clusterCellsDot.z;
int clusterV = cellIndex / clusterTextureWidth;
int clusterU = cellIndex - clusterV * clusterTextureWidth;
for (int lightCellIndex = 0; lightCellIndex < clusterMaxCells; lightCellIndex++) {
uint lightIndex = texelFetch(clusterWorldTexture, ivec2(clusterU + lightCellIndex, clusterV), 0).x;
if (lightIndex == 0u)
break;
evaluateClusterLight(
int(lightIndex),
worldNormal,
viewDir,
reflectionDir,
#if defined(LIT_CLEARCOAT)
clearcoatReflectionDir,
#endif
gloss,
specularity,
geometricNormal,
tbn,
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel,
#endif
clearcoat_worldNormal,
clearcoat_gloss,
sheen_gloss,
iridescence_intensity
);
}
}
}
`;var Z2=`
vec3 combineColor(vec3 albedo, vec3 sheenSpecularity, float clearcoatSpecularity) {
vec3 ret = vec3(0);
#ifdef LIT_OLD_AMBIENT
ret += (dDiffuseLight - light_globalAmbient) * albedo + material_ambient * light_globalAmbient;
#else
ret += albedo * dDiffuseLight;
#endif
#ifdef LIT_SPECULAR
ret += dSpecularLight;
#endif
#ifdef LIT_REFLECTIONS
ret += dReflection.rgb * dReflection.a;
#endif
#ifdef LIT_SHEEN
float sheenScaling = 1.0 - max(max(sheenSpecularity.r, sheenSpecularity.g), sheenSpecularity.b) * 0.157;
ret = ret * sheenScaling + (sSpecularLight + sReflection.rgb) * sheenSpecularity;
#endif
#ifdef LIT_CLEARCOAT
float clearCoatScaling = 1.0 - ccFresnel * clearcoatSpecularity;
ret = ret * clearCoatScaling + (ccSpecularLight + ccReflection) * clearcoatSpecularity;
#endif
return ret;
}
`;var Q2=`
varying vec2 uv0;
uniform sampler2D blitTexture;
void main(void) {
gl_FragColor = texture2D(blitTexture, uv0);
}
`;var J2=`
varying vec2 uv0;
uniform samplerCube blitTexture;
uniform mat4 invViewProj;
void main(void) {
vec4 projPos = vec4(uv0 * 2.0 - 1.0, 0.5, 1.0);
vec4 worldPos = invViewProj * projPos;
gl_FragColor = textureCube(blitTexture, worldPos.xyz);
}
`;var e1=`
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;
#ifndef WEBGPU
uv0.y = 1.0 - uv0.y;
#endif
}
`;var t1=`
vec4 getCookie2D(sampler2D tex, mat4 transform, float intensity) {
vec4 projPos = transform * vec4(vPositionW, 1.0);
projPos.xy /= projPos.w;
return mix(vec4(1.0), texture2D(tex, projPos.xy), intensity);
}
vec4 getCookie2DClip(sampler2D tex, mat4 transform, float intensity) {
vec4 projPos = transform * vec4(vPositionW, 1.0);
projPos.xy /= projPos.w;
if (projPos.x < 0.0 || projPos.x > 1.0 || projPos.y < 0.0 || projPos.y > 1.0 || projPos.z < 0.0) return vec4(0.0);
return mix(vec4(1.0), texture2D(tex, projPos.xy), intensity);
}
vec4 getCookie2DXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) {
vec4 projPos = transform * vec4(vPositionW, 1.0);
projPos.xy /= projPos.w;
projPos.xy += cookieOffset;
vec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5);
return mix(vec4(1.0), texture2D(tex, uv), intensity);
}
vec4 getCookie2DClipXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) {
vec4 projPos = transform * vec4(vPositionW, 1.0);
projPos.xy /= projPos.w;
projPos.xy += cookieOffset;
if (projPos.x < 0.0 || projPos.x > 1.0 || projPos.y < 0.0 || projPos.y > 1.0 || projPos.z < 0.0) return vec4(0.0);
vec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5);
return mix(vec4(1.0), texture2D(tex, uv), intensity);
}
vec4 getCookieCube(samplerCube tex, mat4 transform, float intensity) {
return mix(vec4(1.0), textureCube(tex, dLightDirNormW * mat3(transform)), intensity);
}
`;var s1=`
#if LIT_CUBEMAP_PROJECTION == BOX
uniform vec3 envBoxMin;
uniform vec3 envBoxMax;
#endif
vec3 cubeMapProject(vec3 nrdir) {
#if LIT_CUBEMAP_PROJECTION == NONE
return cubeMapRotate(nrdir);
#endif
#if LIT_CUBEMAP_PROJECTION == BOX
nrdir = cubeMapRotate(nrdir);
vec3 rbmax = (envBoxMax - vPositionW) / nrdir;
vec3 rbmin = (envBoxMin - vPositionW) / nrdir;
vec3 rbminmax = mix(rbmin, rbmax, vec3(greaterThan(nrdir, vec3(0.0))));
float fa = min(min(rbminmax.x, rbminmax.y), rbminmax.z);
vec3 posonbox = vPositionW + nrdir * fa;
vec3 envBoxPos = (envBoxMin + envBoxMax) * 0.5;
return normalize(posonbox - envBoxPos);
#endif
}
`;var i1=`
#ifdef CUBEMAP_ROTATION
uniform mat3 cubeMapRotationMatrix;
#endif
vec3 cubeMapRotate(vec3 refDir) {
#ifdef CUBEMAP_ROTATION
return refDir * cubeMapRotationMatrix;
#else
return refDir;
#endif
}
`;var r1=`
#ifdef DEBUG_ALBEDO_PASS
gl_FragColor = vec4(gammaCorrectOutput(dAlbedo), 1.0);
#endif
#ifdef DEBUG_UV0_PASS
gl_FragColor = vec4(litArgs_albedo , 1.0);
#endif
#ifdef DEBUG_WORLD_NORMAL_PASS
gl_FragColor = vec4(litArgs_worldNormal * 0.5 + 0.5, 1.0);
#endif
#ifdef DEBUG_OPACITY_PASS
gl_FragColor = vec4(vec3(litArgs_opacity) , 1.0);
#endif
#ifdef DEBUG_SPECULARITY_PASS
gl_FragColor = vec4(litArgs_specularity, 1.0);
#endif
#ifdef DEBUG_GLOSS_PASS
gl_FragColor = vec4(vec3(litArgs_gloss) , 1.0);
#endif
#ifdef DEBUG_METALNESS_PASS
gl_FragColor = vec4(vec3(litArgs_metalness) , 1.0);
#endif
#ifdef DEBUG_AO_PASS
gl_FragColor = vec4(vec3(litArgs_ao) , 1.0);
#endif
#ifdef DEBUG_EMISSION_PASS
gl_FragColor = vec4(gammaCorrectOutput(litArgs_emission), 1.0);
#endif
`;var a1=`
#ifdef DEBUG_LIGHTING_PASS
litArgs_albedo = vec3(0.5);
#endif
#ifdef DEBUG_UV0_PASS
#ifdef VARYING_VUV0
litArgs_albedo = vec3(vUv0, 0);
#else
litArgs_albedo = vec3(0);
#endif
#endif
`;var o1=`
#ifndef _DECODE_INCLUDED_
#define _DECODE_INCLUDED_
vec3 decodeLinear(vec4 raw) {
return raw.rgb;
}
float decodeGamma(float raw) {
return pow(raw, 2.2);
}
vec3 decodeGamma(vec3 raw) {
return pow(raw, vec3(2.2));
}
vec3 decodeGamma(vec4 raw) {
return pow(raw.xyz, vec3(2.2));
}
vec3 decodeRGBM(vec4 raw) {
vec3 color = (8.0 * raw.a) * raw.rgb;
return color * color;
}
vec3 decodeRGBP(vec4 raw) {
vec3 color = raw.rgb * (-raw.a * 7.0 + 8.0);
return color * color;
}
vec3 decodeRGBE(vec4 raw) {
if (raw.a == 0.0) {
return vec3(0.0, 0.0, 0.0);
} else {
return raw.xyz * pow(2.0, raw.w * 255.0 - 128.0);
}
}
vec4 passThrough(vec4 raw) {
return raw;
}
vec3 unpackNormalXYZ(vec4 nmap) {
return nmap.xyz * 2.0 - 1.0;
}
vec3 unpackNormalXY(vec4 nmap) {
vec3 normal;
normal.xy = nmap.wy * 2.0 - 1.0;
normal.z = sqrt(1.0 - clamp(dot(normal.xy, normal.xy), 0.0, 1.0));
return normal;
}
#endif
`;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() {
dEmission = material_emissive * material_emissiveIntensity;
#ifdef STD_EMISSIVE_TEXTURE
dEmission *= {STD_EMISSIVE_TEXTURE_DECODE}(texture2DBias({STD_EMISSIVE_TEXTURE_NAME}, {STD_EMISSIVE_TEXTURE_UV}, textureBias)).{STD_EMISSIVE_TEXTURE_CHANNEL};
#endif
#ifdef STD_EMISSIVE_VERTEX
dEmission *= saturate(vVertexColor.{STD_EMISSIVE_VERTEX_CHANNEL});
#endif
}
`;var h1=`
vec4 encodeLinear(vec3 source) {
return vec4(source, 1.0);
}
vec4 encodeGamma(vec3 source) {
return vec4(pow(source + 0.0000001, vec3(1.0 / 2.2)), 1.0);
}
vec4 encodeRGBM(vec3 source) {
vec4 result;
result.rgb = pow(source.rgb, vec3(0.5));
result.rgb *= 1.0 / 8.0;
result.a = saturate( max( max( result.r, result.g ), max( result.b, 1.0 / 255.0 ) ) );
result.a = ceil(result.a * 255.0) / 255.0;
result.rgb /= result.a;
return result;
}
vec4 encodeRGBP(vec3 source) {
vec3 gamma = pow(source, vec3(0.5));
float maxVal = min(8.0, max(1.0, max(gamma.x, max(gamma.y, gamma.z))));
float v = 1.0 - ((maxVal - 1.0) / 7.0);
v = ceil(v * 255.0) / 255.0;
return vec4(gamma / (-v * 7.0 + 8.0), v);
}
vec4 encodeRGBE(vec3 source) {
float maxVal = max(source.x, max(source.y, source.z));
if (maxVal < 1e-32) {
return vec4(0, 0, 0, 0);
} else {
float e = ceil(log2(maxVal));
return vec4(source / pow(2.0, e), (e + 128.0) / 255.0);
}
}
`;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);
`;var u1=`
#ifndef _ENVATLAS_INCLUDED_
#define _ENVATLAS_INCLUDED_
const float atlasSize = 512.0;
const float seamSize = 1.0 / atlasSize;
vec2 mapUv(vec2 uv, vec4 rect) {
return vec2(mix(rect.x + seamSize, rect.x + rect.z - seamSize, uv.x),
mix(rect.y + seamSize, rect.y + rect.w - seamSize, uv.y));
}
vec2 mapRoughnessUv(vec2 uv, float level) {
float t = 1.0 / exp2(level);
return mapUv(uv, vec4(0, 1.0 - t, t, t * 0.5));
}
vec2 mapShinyUv(vec2 uv, float level) {
float t = 1.0 / exp2(level);
return mapUv(uv, vec4(1.0 - t, 1.0 - t, t, t * 0.5));
}
#endif
`;var d1=`
#ifdef LIT_SKYBOX_INTENSITY
uniform float skyboxIntensity;
#endif
vec3 processEnvironment(vec3 color) {
#ifdef LIT_SKYBOX_INTENSITY
return color * skyboxIntensity;
#else
return color;
#endif
}
`;var p1=`
float getFalloffWindow(float lightRadius, vec3 lightDir) {
float sqrDist = dot(lightDir, lightDir);
float invRadius = 1.0 / lightRadius;
return square(saturate(1.0 - square(sqrDist * square(invRadius))));
}
float getFalloffInvSquared(float lightRadius, vec3 lightDir) {
float sqrDist = dot(lightDir, lightDir);
float falloff = 1.0 / (sqrDist + 1.0);
float invRadius = 1.0 / lightRadius;
falloff *= 16.0;
falloff *= square(saturate(1.0 - square(sqrDist * square(invRadius))));
return falloff;
}
`;var m1=`
float getFalloffLinear(float lightRadius, vec3 lightDir) {
float d = length(lightDir);
return max(((lightRadius - d) / lightRadius), 0.0);
}
`;var _1=`
#ifndef FLOAT_AS_UINT
#define FLOAT_AS_UINT
vec4 float2uint(float value) {
uint intBits = floatBitsToUint(value);
return vec4(
float((intBits >> 24u) & 0xFFu) / 255.0,
float((intBits >> 16u) & 0xFFu) / 255.0,
float((intBits >> 8u) & 0xFFu) / 255.0,
float(intBits & 0xFFu) / 255.0
);
}
float uint2float(vec4 value) {
uint intBits =
(uint(value.r * 255.0) << 24u) |
(uint(value.g * 255.0) << 16u) |
(uint(value.b * 255.0) << 8u) |
uint(value.a * 255.0);
return uintBitsToFloat(intBits);
}
vec4 float2vec4(float value) {
#if defined(CAPS_TEXTURE_FLOAT_RENDERABLE)
return vec4(value, 1.0, 1.0, 1.0);
#else
return float2uint(value);
#endif
}
#endif
`;var g1=`
float dBlendModeFogFactor = 1.0;
#if (FOG != NONE)
uniform vec3 fog_color;
#if (FOG == LINEAR)
uniform float fog_start;
uniform float fog_end;
#else
uniform float fog_density;
#endif
#endif
#ifdef VERTEXSHADER
float getFogFactor(float depth) {
#else
float getFogFactor() {
float depth = gl_FragCoord.z / gl_FragCoord.w;
#endif
float fogFactor = 0.0;
#if (FOG == LINEAR)
fogFactor = (fog_end - depth) / (fog_end - fog_start);
#elif (FOG == EXP)
fogFactor = exp(-depth * fog_density);
#elif (FOG == EXP2)
fogFactor = exp(-depth * depth * fog_density * fog_density);
#endif
return clamp(fogFactor, 0.0, 1.0);
}
#ifdef VERTEXSHADER
vec3 addFog(vec3 color, float depth) {
#if (FOG != NONE)
return mix(fog_color * dBlendModeFogFactor, color, getFogFactor(depth));
#endif
return color;
}
#else
vec3 addFog(vec3 color) {
#if (FOG != NONE)
return mix(fog_color * dBlendModeFogFactor, color, getFogFactor());
#endif
return color;
}
#endif
`;var S1=`
float pow5(float x) {
float x2 = x * x;
return x2 * x2 * x;
}
vec3 getFresnel(
float cosTheta,
float gloss,
vec3 specularity
#if defined(LIT_IRIDESCENCE)
, vec3 iridescenceFresnel,
float iridescenceIntensity
#endif
) {
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;
#if defined(LIT_IRIDESCENCE)
return mix(ret, iridescenceFresnel, iridescenceIntensity);
#else
return ret;
#endif
}
float getFresnelCC(float cosTheta) {
float fresnel = pow5(1.0 - saturate(cosTheta));
return 0.04 + (1.0 - 0.04) * fresnel;
}
`;var x1=`
attribute vec2 vertex_position;
varying vec2 vUv0;
void main(void)
{
gl_Position = vec4(vertex_position, 0.5, 1.0);
vUv0 = vertex_position.xy * 0.5 + 0.5;
}
`;var v1=`
#include "decodePS"
#if (GAMMA == SRGB)
float gammaCorrectInput(float color) {
return decodeGamma(color);
}
vec3 gammaCorrectInput(vec3 color) {
return decodeGamma(color);
}
vec4 gammaCorrectInput(vec4 color) {
return vec4(decodeGamma(color.xyz), color.w);
}
vec3 gammaCorrectOutput(vec3 color) {
return pow(color + 0.0000001, vec3(1.0 / 2.2));
}
#else
float gammaCorrectInput(float color) {
return color;
}
vec3 gammaCorrectInput(vec3 color) {
return color;
}
vec4 gammaCorrectInput(vec4 color) {
return color;
}
vec3 gammaCorrectOutput(vec3 color) {
return color;
}
#endif
`;var T1=`
#ifdef STD_GLOSS_CONSTANT
uniform float material_gloss;
#endif
void getGlossiness() {
dGlossiness = 1.0;
#ifdef STD_GLOSS_CONSTANT
dGlossiness *= material_gloss;
#endif
#ifdef STD_GLOSS_TEXTURE
dGlossiness *= texture2DBias({STD_GLOSS_TEXTURE_NAME}, {STD_GLOSS_TEXTURE_UV}, textureBias).{STD_GLOSS_TEXTURE_CHANNEL};
#endif
#ifdef STD_GLOSS_VERTEX
dGlossiness *= saturate(vVertexColor.{STD_GLOSS_VERTEX_CHANNEL});
#endif
#ifdef STD_GLOSS_INVERT
dGlossiness = 1.0 - dGlossiness;
#endif
dGlossiness += 0.0000001;
}
`;var y1=`
attribute vec2 aPosition;
varying vec2 uv0;
void main(void)
{
gl_Position = vec4(aPosition, 0.0, 1.0);
uv0 = getImageEffectUV((aPosition.xy + 1.0) * 0.5);
}
`;var E1=`
#include "gammaPS"
varying vec4 color;
void main(void) {
gl_FragColor = vec4(gammaCorrectOutput(decodeGamma(color.rgb)), color.a);
}
`;var A1=`
attribute vec4 vertex_position;
attribute vec4 vertex_color;
uniform mat4 matrix_model;
uniform mat4 matrix_viewProjection;
varying vec4 color;
void main(void) {
color = vertex_color;
gl_Position = matrix_viewProjection * matrix_model * vertex_position;
}
`;var C1=`
uniform float material_iridescenceRefractionIndex;
float iridescence_iorToFresnel(float transmittedIor, float incidentIor) {
return pow((transmittedIor - incidentIor) / (transmittedIor + incidentIor), 2.0);
}
vec3 iridescence_iorToFresnel(vec3 transmittedIor, float incidentIor) {
return pow((transmittedIor - vec3(incidentIor)) / (transmittedIor + vec3(incidentIor)), vec3(2.0));
}
vec3 iridescence_fresnelToIor(vec3 f0) {
vec3 sqrtF0 = sqrt(f0);
return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0);
}
vec3 iridescence_sensitivity(float opd, vec3 shift) {
float PI = 3.141592653589793;
float phase = 2.0 * PI * opd * 1.0e-9;
const vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13);
const vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06);
const vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09);
vec3 xyz = val * sqrt(2.0 * PI * var) * cos(pos * phase + shift) * exp(-pow(phase, 2.0) * var);
xyz.x += 9.7470e-14 * sqrt(2.0 * PI * 4.5282e+09) * cos(2.2399e+06 * phase + shift[0]) * exp(-4.5282e+09 * pow(phase, 2.0));
xyz /= vec3(1.0685e-07);
const mat3 XYZ_TO_REC709 = mat3(
3.2404542, -0.9692660, 0.0556434,
-1.5371385, 1.8760108, -0.2040259,
-0.4985314, 0.0415560, 1.0572252
);
return XYZ_TO_REC709 * xyz;
}
float iridescence_fresnel(float cosTheta, float f0) {
float x = clamp(1.0 - cosTheta, 0.0, 1.0);
float x2 = x * x;
float x5 = x * x2 * x2;
return f0 + (1.0 - f0) * x5;
}
vec3 iridescence_fresnel(float cosTheta, vec3 f0) {
float x = clamp(1.0 - cosTheta, 0.0, 1.0);
float x2 = x * x;
float x5 = x * x2 * x2;
return f0 + (vec3(1.0) - f0) * x5;
}
vec3 calcIridescence(float outsideIor, float cosTheta, vec3 base_f0, float iridescenceThickness) {
float PI = 3.141592653589793;
float iridescenceIor = mix(outsideIor, material_iridescenceRefractionIndex, smoothstep(0.0, 0.03, iridescenceThickness));
float sinTheta2Sq = pow(outsideIor / iridescenceIor, 2.0) * (1.0 - pow(cosTheta, 2.0));
float cosTheta2Sq = 1.0 - sinTheta2Sq;
if (cosTheta2Sq < 0.0) {
return vec3(1.0);
}
float cosTheta2 = sqrt(cosTheta2Sq);
float r0 = iridescence_iorToFresnel(iridescenceIor, outsideIor);
float r12 = iridescence_fresnel(cosTheta, r0);
float r21 = r12;
float t121 = 1.0 - r12;
float phi12 = iridescenceIor < outsideIor ? PI : 0.0;
float phi21 = PI - phi12;
vec3 baseIor = iridescence_fresnelToIor(base_f0 + vec3(0.0001));
vec3 r1 = iridescence_iorToFresnel(baseIor, iridescenceIor);
vec3 r23 = iridescence_fresnel(cosTheta2, r1);
vec3 phi23 = vec3(0.0);
if (baseIor[0] < iridescenceIor) phi23[0] = PI;
if (baseIor[1] < iridescenceIor) phi23[1] = PI;
if (baseIor[2] < iridescenceIor) phi23[2] = PI;
float opd = 2.0 * iridescenceIor * iridescenceThickness * cosTheta2;
vec3 phi = vec3(phi21) + phi23;
vec3 r123Sq = clamp(r12 * r23, 1e-5, 0.9999);
vec3 r123 = sqrt(r123Sq);
vec3 rs = pow(t121, 2.0) * r23 / (1.0 - r123Sq);
vec3 c0 = r12 + rs;
vec3 i = c0;
vec3 cm = rs - t121;
for (int m = 1; m <= 2; m++) {
cm *= r123;
vec3 sm = 2.0 * iridescence_sensitivity(float(m) * opd, float(m) * phi);
i += cm * sm;
}
return max(i, vec3(0.0));
}
vec3 getIridescence(float cosTheta, vec3 specularity, float iridescenceThickness) {
return calcIridescence(1.0, cosTheta, specularity, iridescenceThickness);
}
`;var P1=`
#ifdef STD_IRIDESCENCE_CONSTANT
uniform float material_iridescence;
#endif
void getIridescence() {
float iridescence = 1.0;
#ifdef STD_IRIDESCENCE_CONSTANT
iridescence *= material_iridescence;
#endif
#ifdef STD_IRIDESCENCE_TEXTURE
iridescence *= texture2DBias({STD_IRIDESCENCE_TEXTURE_NAME}, {STD_IRIDESCENCE_TEXTURE_UV}, textureBias).{STD_IRIDESCENCE_TEXTURE_CHANNEL};
#endif
dIridescence = iridescence;
}
`;var w1=`
uniform float material_iridescenceThicknessMax;
#ifdef STD_IRIDESCENCETHICKNESS_TEXTURE
uniform float material_iridescenceThicknessMin;
#endif
void getIridescenceThickness() {
#ifdef STD_IRIDESCENCETHICKNESS_TEXTURE
float blend = texture2DBias({STD_IRIDESCENCETHICKNESS_TEXTURE_NAME}, {STD_IRIDESCENCETHICKNESS_TEXTURE_UV}, textureBias).{STD_IRIDESCENCETHICKNESS_TEXTURE_CHANNEL};
float iridescenceThickness = mix(material_iridescenceThicknessMin, material_iridescenceThicknessMax, blend);
#else
float iridescenceThickness = material_iridescenceThicknessMax;
#endif
dIridescenceThickness = iridescenceThickness;
}
`;var I1=`
#ifdef STD_IOR_CONSTANT
uniform float material_refractionIndex;
#endif
void getIor() {
#ifdef STD_IOR_CONSTANT
dIor = material_refractionIndex;
#else
dIor = 1.0 / 1.5;
#endif
}
`;var R1=`
#if defined(LIGHT{i})
uniform vec3 light{i}_color;
#if LIGHT{i}TYPE == DIRECTIONAL
uniform vec3 light{i}_direction;
#else
#define LIT_CODE_LIGHTS_POINT
uniform vec3 light{i}_position;
uniform float light{i}_radius;
#if LIGHT{i}TYPE == SPOT
#define LIT_CODE_LIGHTS_SPOT
uniform vec3 light{i}_direction;
uniform float light{i}_innerConeAngle;
uniform float light{i}_outerConeAngle;
#endif
#endif
#if LIGHT{i}SHAPE != PUNCTUAL
#define LIT_CODE_FALLOFF_SQUARED
#if LIGHT{i}TYPE == DIRECTIONAL
uniform vec3 light{i}_position;
#endif
uniform vec3 light{i}_halfWidth;
uniform vec3 light{i}_halfHeight;
#else
#if LIGHT{i}FALLOFF == LINEAR
#define LIT_CODE_FALLOFF_LINEAR
#endif
#if LIGHT{i}FALLOFF == INVERSESQUARED
#define LIT_CODE_FALLOFF_SQUARED
#endif
#endif
#if defined(LIGHT{i}CASTSHADOW)
#if LIGHT{i}TYPE != OMNI
uniform mat4 light{i}_shadowMatrix;
#endif
uniform float light{i}_shadowIntensity;
uniform vec4 light{i}_shadowParams;
#if LIGHT{i}SHADOWTYPE == PCSS_32F
uniform float light{i}_shadowSearchArea;
uniform vec4 light{i}_cameraParams;
#if LIGHT{i}TYPE == DIRECTIONAL
uniform vec4 light{i}_softShadowParams;
#endif
#endif
#if LIGHT{i}TYPE == DIRECTIONAL
uniform mat4 light{i}_shadowMatrixPalette[4];
uniform vec4 light{i}_shadowCascadeDistances;
uniform int light{i}_shadowCascadeCount;
uniform float light{i}_shadowCascadeBlend;
#endif
#if LIGHT{i}TYPE == OMNI
#if defined(LIGHT{i}SHADOW_PCF)
uniform samplerCubeShadow light{i}_shadowMap;
#else
uniform samplerCube light{i}_shadowMap;
#endif
#else
#if defined(LIGHT{i}SHADOW_PCF)
uniform sampler2DShadow light{i}_shadowMap;
#else
uniform sampler2D light{i}_shadowMap;
#endif
#endif
#endif
#if defined(LIGHT{i}COOKIE)
#define LIT_CODE_COOKIE
#if LIGHT{i}TYPE == OMNI
uniform samplerCube light{i}_cookie;
uniform float light{i}_cookieIntensity;
uniform mat4 light{i}_shadowMatrix;
#endif
#if LIGHT{i}TYPE == SPOT
uniform sampler2D light{i}_cookie;
uniform float light{i}_cookieIntensity;
#if !defined(LIGHT{i}CASTSHADOW)
uniform mat4 light{i}_shadowMatrix;
#endif
#if defined(LIGHT{i}COOKIE_TRANSFORM)
uniform vec4 light{i}_cookieMatrix;
uniform vec2 light{i}_cookieOffset;
#endif
#endif
#endif
#endif
`;var b1=`
float getLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm) {
return max(dot(worldNormal, -lightDirNorm), 0.0);
}
`;var D1=`
vec3 evalOmniLight(vec3 lightPosW) {
return vPositionW - lightPosW;
}
`;var L1=`
#if defined(LIGHT{i})
evaluateLight{i}(
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel
#endif
);
#endif
`;var M1=`
#if defined(LIGHT{i})
void evaluateLight{i}(
#if defined(LIT_IRIDESCENCE)
vec3 iridescenceFresnel
#endif
) {
vec3 lightColor = light{i}_color;
#if LIGHT{i}TYPE == DIRECTIONAL && !defined(LIT_SHADOW_CATCHER)
if (all(equal(lightColor, vec3(0.0)))) {
return;
}
#endif
#if LIGHT{i}TYPE == DIRECTIONAL
dLightDirNormW = light{i}_direction;
dAtten = 1.0;
#else
vec3 lightDirW = evalOmniLight(light{i}_position);
dLightDirNormW = normalize(lightDirW);
#if defined(LIGHT{i}COOKIE)
#if LIGHT{i}TYPE == SPOT
#ifdef LIGHT{i}COOKIE_FALLOFF
#ifdef LIGHT{i}COOKIE_TRANSFORM
vec3 cookieAttenuation = getCookie2DXform(light{i}_cookie, light{i}_shadowMatrix, light{i}_cookieIntensity, light{i}_cookieMatrix, light{i}_cookieOffset).{LIGHT{i}COOKIE_CHANNEL};
#else
vec3 cookieAttenuation = getCookie2D(light{i}_cookie, light{i}_shadowMatrix, light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL};
#endif
#else
#ifdef LIGHT{i}COOKIE_TRANSFORM
vec3 cookieAttenuation = getCookie2DClipXform(light{i}_cookie, light{i}_shadowMatrix, light{i}_cookieIntensity, light{i}_cookieMatrix, light{i}_cookieOffset).{LIGHT{i}COOKIE_CHANNEL};
#else
vec3 cookieAttenuation = getCookie2DClip(light{i}_cookie, light{i}_shadowMatrix, light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL};
#endif
#endif
#endif
#if LIGHT{i}TYPE == OMNI
vec3 cookieAttenuation = getCookieCube(light{i}_cookie, light{i}_shadowMatrix, light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL};
#endif
lightColor *= cookieAttenuation;
#endif
#if LIGHT{i}SHAPE == PUNCTUAL
#if LIGHT{i}FALLOFF == LINEAR
dAtten = getFalloffLinear(light{i}_radius, lightDirW);
#else
dAtten = getFalloffInvSquared(light{i}_radius, lightDirW);
#endif
#else
dAtten = getFalloffWindow(light{i}_radius, lightDirW);
#endif
#if LIGHT{i}TYPE == SPOT
#if !defined(LIGHT{i}COOKIE) || defined(LIGHT{i}COOKIE_FALLOFF)
dAtten *= getSpotEffect(light{i}_direction, light{i}_innerConeAngle, light{i}_outerConeAngle, dLightDirNormW);
#endif
#endif
#endif
if (dAtten < 0.00001) {
return;
}
#if LIGHT{i}SHAPE != PUNCTUAL
#if LIGHT{i}SHAPE == RECT
calcRectLightValues(light{i}_position, light{i}_halfWidth, light{i}_halfHeight);
#elif LIGHT{i}SHAPE == DISK
calcDiskLightValues(light{i}_position, light{i}_halfWidth, light{i}_halfHeight);
#elif LIGHT{i}SHAPE == SPHERE
calcSphereLightValues(light{i}_position, light{i}_halfWidth, light{i}_halfHeight);
#endif
#endif
#if LIGHT{i}SHAPE != PUNCTUAL
#if LIGHT{i}TYPE == DIRECTIONAL
float attenDiffuse = getLightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirNormW);
#else
#if LIGHT{i}SHAPE == RECT
float attenDiffuse = getRectLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0;
#elif LIGHT{i}SHAPE == DISK
float attenDiffuse = getDiskLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0;
#elif LIGHT{i}SHAPE == SPHERE
float attenDiffuse = getSphereLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0;
#endif
#endif
#else
dAtten *= getLightDiffuse(litArgs_worldNormal, vec3(0.0), dLightDirNormW);
#endif
#ifdef LIGHT{i}CASTSHADOW
#if LIGHT{i}TYPE == DIRECTIONAL
float shadow = getShadow{i}(vec3(0.0));
#else
float shadow = getShadow{i}(lightDirW);
#endif
shadow = mix(1.0, shadow, light{i}_shadowIntensity);
dAtten *= shadow;
#if defined(LIT_SHADOW_CATCHER) && LIGHT{i}TYPE == DIRECTIONAL
dShadowCatcher *= shadow;
#endif
#endif
#if LIGHT{i}SHAPE != PUNCTUAL
#ifdef LIT_SPECULAR
dDiffuseLight += ((attenDiffuse * dAtten) * lightColor) * (1.0 - dLTCSpecFres);
#else
dDiffuseLight += (attenDiffuse * dAtten) * lightColor;
#endif
#else
#if defined(AREA_LIGHTS) && defined(LIT_SPECULAR)
dDiffuseLight += (dAtten * lightColor) * (1.0 - litArgs_specularity);
#else
dDiffuseLight += dAtten * lightColor;
#endif
#endif
#ifdef LIGHT{i}AFFECT_SPECULARITY
#if LIGHT{i}SHAPE != PUNCTUAL
#ifdef LIT_CLEARCOAT
#if LIGHT{i}SHAPE == RECT
ccSpecularLight += ccLTCSpecFres * getRectLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor;
#elif LIGHT{i}SHAPE == DISK
ccSpecularLight += ccLTCSpecFres * getDiskLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor;
#elif LIGHT{i}SHAPE == SPHERE
ccSpecularLight += ccLTCSpecFres * getSphereLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor;
#endif
#endif
#ifdef LIT_SPECULAR
#if LIGHT{i}SHAPE == RECT
dSpecularLight += dLTCSpecFres * getRectLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor;
#elif LIGHT{i}SHAPE == DISK
dSpecularLight += dLTCSpecFres * getDiskLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor;
#elif LIGHT{i}SHAPE == SPHERE
dSpecularLight += dLTCSpecFres * getSphereLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor;
#endif
#endif
#else
#if LIGHT{i}TYPE == DIRECTIONAL && LIT_FRESNEL_MODEL != NONE
#define LIGHT{i}FRESNEL
#endif
#ifdef LIT_SPECULAR
vec3 halfDirW = normalize(-dLightDirNormW + dViewDirW);
#endif
#ifdef LIT_CLEARCOAT
vec3 lightspecularCC = getLightSpecular(halfDirW, ccReflDirW, litArgs_clearcoat_worldNormal, dViewDirW, dLightDirNormW, litArgs_clearcoat_gloss, dTBN) * dAtten * lightColor;
#ifdef LIGHT{i}FRESNEL
lightspecularCC *= getFresnelCC(dot(dViewDirW, halfDirW));
#endif
ccSpecularLight += lightspecularCC;
#endif
#ifdef LIT_SHEEN
sSpecularLight += getLightSpecularSheen(halfDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_sheen_gloss) * dAtten * lightColor;
#endif
#ifdef LIT_SPECULAR
vec3 lightSpecular = getLightSpecular(halfDirW, dReflDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_gloss, dTBN) * dAtten * lightColor;
#ifdef LIGHT{i}FRESNEL
#if defined(LIT_IRIDESCENCE)
lightSpecular *= getFresnel(dot(dViewDirW, halfDirW), litArgs_gloss, litArgs_specularity, iridescenceFresnel, litArgs_iridescence_intensity);
#else
lightSpecular *= getFresnel(dot(dViewDirW, halfDirW), litArgs_gloss, litArgs_specularity);
#endif
#else
lightSpecular *= litArgs_specularity;
#endif
dSpecularLight += lightSpecular;
#endif
#endif
#endif
}
#endif
`;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) {
#ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET
float distScale = length(lightDir);
vec3 surfacePosition = worldPosition + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;
lightDir = surfacePosition - lightPos;
#endif
return lightDir;
}
#endif
#ifndef LIGHT{i}_SHADOW_SAMPLE_POINT
vec3 getShadowSampleCoord{i}(mat4 shadowTransform, vec4 shadowParams, vec3 worldPosition, vec3 lightPos, inout vec3 lightDir, vec3 lightDirNorm, vec3 normal) {
vec3 surfacePosition = worldPosition;
#ifdef LIGHT{i}_SHADOW_SAMPLE_SOURCE_ZBUFFER
#ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET
surfacePosition = surfacePosition + normal * shadowParams.y;
#endif
#else
#ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET
#ifdef LIGHT{i}_SHADOW_SAMPLE_ORTHO
float distScale = 1.0;
#else
float distScale = abs(dot(vPositionW - lightPos, lightDirNorm));
#endif
surfacePosition = surfacePosition + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;
#endif
#endif
vec4 positionInShadowSpace = shadowTransform * vec4(surfacePosition, 1.0);
#ifdef LIGHT{i}_SHADOW_SAMPLE_ORTHO
positionInShadowSpace.z = saturate(positionInShadowSpace.z) - 0.0001;
#else
#ifdef LIGHT{i}_SHADOW_SAMPLE_SOURCE_ZBUFFER
positionInShadowSpace.xyz /= positionInShadowSpace.w;
#else
positionInShadowSpace.xy /= positionInShadowSpace.w;
positionInShadowSpace.z = length(lightDir) * shadowParams.w;
#endif
#endif
return positionInShadowSpace.xyz;
}
#endif
float getShadow{i}(vec3 lightDirW) {
#if LIGHT{i}TYPE == OMNI
vec3 shadowCoord = getShadowSampleCoordOmni{i}(light{i}_shadowParams, vPositionW, light{i}_position, lightDirW, dLightDirNormW, dVertexNormalW);
#else
#ifdef LIGHT{i}_SHADOW_CASCADES
int cascadeIndex = getShadowCascadeIndex(light{i}_shadowCascadeDistances, light{i}_shadowCascadeCount);
#ifdef LIGHT{i}_SHADOW_CASCADE_BLEND
cascadeIndex = ditherShadowCascadeIndex(cascadeIndex, light{i}_shadowCascadeDistances, light{i}_shadowCascadeCount, light{i}_shadowCascadeBlend);
#endif
mat4 shadowMatrix = light{i}_shadowMatrixPalette[cascadeIndex];
#else
mat4 shadowMatrix = light{i}_shadowMatrix;
#endif
#if LIGHT{i}TYPE == DIRECTIONAL
vec3 shadowCoord = getShadowSampleCoord{i}(shadowMatrix, light{i}_shadowParams, vPositionW, vec3(0.0), lightDirW, dLightDirNormW, dVertexNormalW);
#else
vec3 shadowCoord = getShadowSampleCoord{i}(shadowMatrix, light{i}_shadowParams, vPositionW, light{i}_position, lightDirW, dLightDirNormW, dVertexNormalW);
#endif
#endif
#if LIGHT{i}TYPE == DIRECTIONAL
shadowCoord = fadeShadow(shadowCoord, light{i}_shadowCascadeDistances);
#endif
#if LIGHT{i}TYPE == DIRECTIONAL
#if LIGHT{i}SHADOWTYPE == VSM_16F
return getShadowVSM16(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, 5.54);
#endif
#if LIGHT{i}SHADOWTYPE == VSM_32F
return getShadowVSM32(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, 15.0);
#endif
#if LIGHT{i}SHADOWTYPE == PCSS_32F
#if LIGHT{i}SHAPE != PUNCTUAL
vec2 shadowSearchArea = vec2(length(light{i}_halfWidth), length(light{i}_halfHeight)) * light{i}_shadowSearchArea;
return getShadowPCSS(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, light{i}_cameraParams, shadowSearchArea, lightDirW);
#else
return getShadowPCSS(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, light{i}_cameraParams, light{i}_softShadowParams, lightDirW);
#endif
#endif
#if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F
return getShadowPCF1x1(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams);
#endif
#if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F
return getShadowPCF3x3(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams);
#endif
#if LIGHT{i}SHADOWTYPE == PCF5_16F || LIGHT{i}SHADOWTYPE == PCF5_32F
return getShadowPCF5x5(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams);
#endif
#endif
#if LIGHT{i}TYPE == SPOT
#if LIGHT{i}SHADOWTYPE == VSM_16F
return getShadowSpotVSM16(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, 5.54, lightDirW);
#endif
#if LIGHT{i}SHADOWTYPE == VSM_32F
return getShadowSpotVSM32(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, 15.0, lightDirW);
#endif
#if LIGHT{i}SHADOWTYPE == PCSS_32F
#if LIGHT{i}SHAPE != PUNCTUAL
vec2 shadowSearchArea = vec2(length(light{i}_halfWidth), length(light{i}_halfHeight)) * light{i}_shadowSearchArea;
#else
vec2 shadowSearchArea = vec2(light{i}_shadowSearchArea);
#endif
return getShadowSpotPCSS(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, light{i}_cameraParams, shadowSearchArea, lightDirW);
#endif
#if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F
return getShadowSpotPCF1x1(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams);
#endif
#if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F
return getShadowSpotPCF3x3(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams);
#endif
#if LIGHT{i}SHADOWTYPE == PCF5_16F || LIGHT{i}SHADOWTYPE == PCF5_32F
return getShadowSpotPCF5x5(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams);
#endif
#endif
#if LIGHT{i}TYPE == OMNI
#if LIGHT{i}SHADOWTYPE == PCSS_32F
#if LIGHT{i}SHAPE != PUNCTUAL
vec2 shadowSearchArea = vec2(length(light{i}_halfWidth), length(light{i}_halfHeight)) * light{i}_shadowSearchArea;
#else
vec2 shadowSearchArea = vec2(light{i}_shadowSearchArea);
#endif
return getShadowOmniPCSS(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, light{i}_cameraParams, shadowSearchArea, lightDirW);
#endif
#if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F
return getShadowOmniPCF1x1(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, lightDirW);
#endif
#if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F
return getShadowOmniPCF3x3(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, lightDirW);
#endif
#endif
}
#endif
`;var F1=`
#ifdef LIT_CLUSTERED_LIGHTS
#define LIT_CODE_FALLOFF_LINEAR
#define LIT_CODE_FALLOFF_SQUARED
#define LIT_CODE_LIGHTS_POINT
#define LIT_CODE_LIGHTS_SPOT
#endif
#ifdef AREA_LIGHTS
uniform highp sampler2D areaLightsLutTex1;
uniform highp sampler2D areaLightsLutTex2;
#endif
#ifdef LIT_LIGHTING
#include "lightDiffuseLambertPS"
#if defined(AREA_LIGHTS) || defined(LIT_CLUSTERED_AREA_LIGHTS)
#include "ltcPS"
#endif
#endif
#ifdef SHADOW_DIRECTIONAL
#include "shadowCascadesPS"
#endif
#if defined(SHADOW_KIND_PCF1)
#include "shadowPCF1PS"
#endif
#if defined(SHADOW_KIND_PCF3)
#include "shadowPCF3PS"
#endif
#if defined(SHADOW_KIND_PCF5)
#include "shadowPCF5PS"
#endif
#if defined(SHADOW_KIND_PCSS)
#include "linearizeDepthPS"
#include "shadowPCSSPS"
#include "shadowSoftPS"
#endif
#if defined(SHADOW_KIND_VSM)
#include "shadowEVSMPS"
#endif
#ifdef LIT_CODE_FALLOFF_LINEAR
#include "falloffLinearPS"
#endif
#ifdef LIT_CODE_FALLOFF_SQUARED
#include "falloffInvSquaredPS"
#endif
#ifdef LIT_CODE_LIGHTS_POINT
#include "lightDirPointPS"
#endif
#ifdef LIT_CODE_LIGHTS_SPOT
#include "spotPS"
#endif
#ifdef LIT_CODE_COOKIE
#include "cookiePS"
#endif
#ifdef LIT_CLUSTERED_LIGHTS
#include "clusteredLightPS"
#endif
#ifdef LIGHT_COUNT > 0
#include "lightFunctionShadowPS, LIGHT_COUNT"
#include "lightFunctionLightPS, LIGHT_COUNT"
#endif
`;var N1=`
void addLightMap(
vec3 lightmap,
vec3 dir,
vec3 worldNormal,
vec3 viewDir,
vec3 reflectionDir,
float gloss,
vec3 specularity,
vec3 vertexNormal,
mat3 tbn
#if defined(LIT_IRIDESCENCE)
vec3 iridescenceFresnel,
float iridescenceIntensity
#endif
) {
#if defined(LIT_SPECULAR) && defined(LIT_DIR_LIGHTMAP)
if (dot(dir, dir) < 0.0001) {
dDiffuseLight += lightmap;
} else {
float vlight = saturate(dot(dir, -vertexNormal));
float flight = saturate(dot(dir, -worldNormal));
float nlight = (flight / max(vlight, 0.01)) * 0.5;
dDiffuseLight += lightmap * nlight * 2.0;
vec3 halfDir = normalize(-dir + viewDir);
vec3 specularLight = lightmap * getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, dir, gloss, tbn);
#ifdef LIT_SPECULAR_FRESNEL
specularLight *=
getFresnel(dot(viewDir, halfDir),
gloss,
specularity
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
iridescenceIntensity
#endif
);
#endif
dSpecularLight += specularLight;
}
#else
dDiffuseLight += lightmap;
#endif
}
`;var B1=`
#ifdef STD_LIGHTMAP_DIR
vec3 dLightmapDir;
uniform sampler2D texture_dirLightMap;
#endif
void getLightMap() {
dLightmap = vec3(1.0);
#ifdef STD_LIGHT_TEXTURE
dLightmap *= {STD_LIGHT_TEXTURE_DECODE}(texture2DBias({STD_LIGHT_TEXTURE_NAME}, {STD_LIGHT_TEXTURE_UV}, textureBias)).{STD_LIGHT_TEXTURE_CHANNEL};
#ifdef STD_LIGHTMAP_DIR
vec3 dir = texture2DBias(texture_dirLightMap, {STD_LIGHT_TEXTURE_UV}, textureBias).xyz * 2.0 - 1.0;
float dirDot = dot(dir, dir);
dLightmapDir = (dirDot > 0.001) ? dir / sqrt(dirDot) : vec3(0.0);
#endif
#endif
#ifdef STD_LIGHT_VERTEX
dLightmap *= saturate(vVertexColor.{STD_LIGHT_VERTEX_CHANNEL});
#endif
}
`;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);
float alphaRoughness = roughness * roughness;
float anisotropy = dAnisotropy;
vec2 direction = dAnisotropyRotation;
float at = mix(alphaRoughness, 1.0, anisotropy * anisotropy);
float ab = clamp(alphaRoughness, 0.001, 1.0);
vec3 anisotropicT = normalize(tbn * vec3(direction, 0.0));
vec3 anisotropicB = normalize(cross(tbn[2], anisotropicT));
float NoH = dot(worldNormal, h);
float ToH = dot(anisotropicT, h);
float BoH = dot(anisotropicB, h);
float a2 = at * ab;
vec3 v = vec3(ab * ToH, at * BoH, a2 * NoH);
float v2 = dot(v, v);
float w2 = a2 / v2;
float D = a2 * w2 * w2 * (1.0 / PI);
float ToV = dot(anisotropicT, viewDir);
float BoV = dot(anisotropicB, viewDir);
float ToL = dot(anisotropicT, -lightDirNorm);
float BoL = dot(anisotropicB, -lightDirNorm);
float NoV = dot(worldNormal, viewDir);
float NoL = dot(worldNormal, -lightDirNorm);
float lambdaV = NoL * length(vec3(at * ToV, ab * BoV, NoV));
float lambdaL = NoV * length(vec3(at * ToL, ab * BoL, NoL));
float G = 0.5 / (lambdaV + lambdaL);
return D * G;
}
float getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) {
return calcLightSpecular(gloss, worldNormal, viewDir, h, lightDirNorm, tbn);
}
`;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);
float alpha = roughness * roughness;
float NoH = max(dot(worldNormal, h), 0.0);
float NoV = max(dot(worldNormal, viewDir), 0.0);
float NoL = max(dot(worldNormal, -lightDirNorm), 0.0);
float NoH2 = NoH * NoH;
float denom = NoH2 * (alpha - 1.0) + 1.0;
float D = alpha / (PI * denom * denom);
float alpha2 = alpha * alpha;
float lambdaV = NoL * sqrt(NoV * NoV * (1.0 - alpha2) + alpha2);
float lambdaL = NoV * sqrt(NoL * NoL * (1.0 - alpha2) + alpha2);
float G = 0.5 / max(lambdaV + lambdaL, 0.00001);
return D * G;
}
float getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) {
return calcLightSpecular(gloss, worldNormal, viewDir, h, lightDirNorm);
}
`;var z1=`
float calcLightSpecular(float gloss, vec3 worldNormal, vec3 h) {
float nh = max( dot( h, worldNormal ), 0.0 );
float specPow = exp2(gloss * 11.0);
specPow = max(specPow, 0.0001);
return pow(nh, specPow) * (specPow + 2.0) / 8.0;
}
float getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) {
return calcLightSpecular(gloss, worldNormal, h);
}
`;var G1=`
float sheenD(vec3 normal, vec3 h, float roughness) {
const float PI = 3.141592653589793;
float invR = 1.0 / (roughness * roughness);
float cos2h = max(dot(normal, h), 0.0);
cos2h *= cos2h;
float sin2h = max(1.0 - cos2h, 0.0078125);
return (2.0 + invR) * pow(sin2h, invR * 0.5) / (2.0 * PI);
}
float sheenV(vec3 normal, vec3 viewDir, vec3 light) {
float NoV = max(dot(normal, viewDir), 0.000001);
float NoL = max(dot(normal, light), 0.000001);
return 1.0 / (4.0 * (NoL + NoV - NoL * NoV));
}
float getLightSpecularSheen(vec3 h, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float sheenGloss) {
float D = sheenD(worldNormal, h, sheenGloss);
float V = sheenV(worldNormal, viewDir, -lightDirNorm);
return D * V;
}
`;var V1=`
#ifndef LINEARIZE_DEPTH
#define LINEARIZE_DEPTH
float linearizeDepthWithParams(float z, vec4 cameraParams) {
if (cameraParams.w == 0.0)
return (cameraParams.z * cameraParams.y) / (cameraParams.y + z * (cameraParams.z - cameraParams.y));
else
return cameraParams.z + z * (cameraParams.y - cameraParams.z);
}
#ifndef CAMERAPLANES
#define CAMERAPLANES
uniform vec4 camera_params;
#endif
float linearizeDepth(float z) {
return linearizeDepthWithParams(z, camera_params);
}
#endif
`;var H1=`
void evaluateBackend() {
#ifdef LIT_SSAO
litArgs_ao *= texture2DLod(ssaoTexture, gl_FragCoord.xy * ssaoTextureSizeInv, 0.0).r;
#endif
#ifdef LIT_NEEDS_NORMAL
#ifdef LIT_SPECULAR
getReflDir(litArgs_worldNormal, dViewDirW, litArgs_gloss, dTBN);
#endif
#ifdef LIT_CLEARCOAT
ccReflDirW = normalize(-reflect(dViewDirW, litArgs_clearcoat_worldNormal));
#endif
#endif
#ifdef LIT_SPECULAR_OR_REFLECTION
#ifdef LIT_METALNESS
float f0 = 1.0 / litArgs_ior;
f0 = (f0 - 1.0) / (f0 + 1.0);
f0 *= f0;
#ifdef LIT_SPECULARITY_FACTOR
litArgs_specularity = getSpecularModulate(litArgs_specularity, litArgs_albedo, litArgs_metalness, f0, litArgs_specularityFactor);
#else
litArgs_specularity = getSpecularModulate(litArgs_specularity, litArgs_albedo, litArgs_metalness, f0, 1.0);
#endif
litArgs_albedo = getAlbedoModulate(litArgs_albedo, litArgs_metalness);
#endif
#ifdef LIT_IRIDESCENCE
vec3 iridescenceFresnel = getIridescence(saturate(dot(dViewDirW, litArgs_worldNormal)), litArgs_specularity, litArgs_iridescence_thickness);
#endif
#endif
#ifdef LIT_ADD_AMBIENT
addAmbient(litArgs_worldNormal);
#ifdef LIT_SPECULAR
dDiffuseLight = dDiffuseLight * (1.0 - litArgs_specularity);
#endif
#ifdef LIT_SEPARATE_AMBIENT
vec3 dAmbientLight = dDiffuseLight;
dDiffuseLight = vec3(0);
#endif
#endif
#ifndef LIT_OLD_AMBIENT
dDiffuseLight *= material_ambient;
#endif
#ifdef LIT_AO
#ifndef LIT_OCCLUDE_DIRECT
occludeDiffuse(litArgs_ao);
#endif
#endif
#ifdef LIT_LIGHTMAP
addLightMap(
litArgs_lightmap,
litArgs_lightmapDir,
litArgs_worldNormal,
dViewDirW,
dReflDirW,
litArgs_gloss,
litArgs_specularity,
dVertexNormalW,
dTBN
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
litArgs_iridescence_intensity
#endif
);
#endif
#ifdef LIT_LIGHTING || LIT_REFLECTIONS
#ifdef LIT_REFLECTIONS
#ifdef LIT_CLEARCOAT
addReflectionCC(ccReflDirW, litArgs_clearcoat_gloss);
#ifdef LIT_SPECULAR_FRESNEL
ccFresnel = getFresnelCC(dot(dViewDirW, litArgs_clearcoat_worldNormal));
ccReflection *= ccFresnel;
#else
ccFresnel = 0.0;
#endif
#endif
#ifdef LIT_SPECULARITY_FACTOR
ccReflection *= litArgs_specularityFactor;
#endif
#ifdef LIT_SHEEN
addReflectionSheen(litArgs_worldNormal, dViewDirW, litArgs_sheen_gloss);
#endif
addReflection(dReflDirW, litArgs_gloss);
#ifdef LIT_FRESNEL_MODEL
dReflection.rgb *= getFresnel(
dot(dViewDirW, litArgs_worldNormal),
litArgs_gloss,
litArgs_specularity
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
litArgs_iridescence_intensity
#endif
);
#else
dReflection.rgb *= litArgs_specularity;
#endif
#endif
#ifdef AREA_LIGHTS
dSpecularLight *= litArgs_specularity;
#ifdef LIT_SPECULAR
calcLTCLightValues(litArgs_gloss, litArgs_worldNormal, dViewDirW, litArgs_specularity, litArgs_clearcoat_gloss, litArgs_clearcoat_worldNormal, litArgs_clearcoat_specularity);
#endif
#endif
#ifdef LIGHT_COUNT > 0
#include "lightEvaluationPS, LIGHT_COUNT"
#endif
#ifdef LIT_CLUSTERED_LIGHTS
addClusteredLights(litArgs_worldNormal, dViewDirW, dReflDirW,
#if defined(LIT_CLEARCOAT)
ccReflDirW,
#endif
litArgs_gloss, litArgs_specularity, dVertexNormalW, dTBN,
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel,
#endif
litArgs_clearcoat_worldNormal, litArgs_clearcoat_gloss, litArgs_sheen_gloss, litArgs_iridescence_intensity
);
#endif
#ifdef AREA_LIGHTS
#ifdef LIT_CLEARCOAT
litArgs_clearcoat_specularity = 1.0;
#endif
#ifdef LIT_SPECULAR
litArgs_specularity = vec3(1);
#endif
#endif
#ifdef LIT_REFRACTION
addRefraction(
litArgs_worldNormal,
dViewDirW,
litArgs_thickness,
litArgs_gloss,
litArgs_specularity,
litArgs_albedo,
litArgs_transmission,
litArgs_ior,
litArgs_dispersion
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
litArgs_iridescence_intensity
#endif
);
#endif
#endif
#ifdef LIT_AO
#ifdef LIT_OCCLUDE_DIRECT
occludeDiffuse(litArgs_ao);
#endif
#if LIT_OCCLUDE_SPECULAR != NONE
occludeSpecular(litArgs_gloss, litArgs_ao, litArgs_worldNormal, dViewDirW);
#endif
#endif
#if !defined(LIT_OPACITY_FADES_SPECULAR)
#if LIT_BLEND_TYPE == NORMAL || LIT_BLEND_TYPE == PREMULTIPLIED
float specLum = dot((dSpecularLight + dReflection.rgb * dReflection.a), vec3( 0.2126, 0.7152, 0.0722 ));
#ifdef LIT_CLEARCOAT
specLum += dot(ccSpecularLight * litArgs_clearcoat_specularity + ccReflection * litArgs_clearcoat_specularity, vec3( 0.2126, 0.7152, 0.0722 ));
#endif
litArgs_opacity = clamp(litArgs_opacity + gammaCorrectInput(specLum), 0.0, 1.0);
#endif
litArgs_opacity *= material_alphaFade;
#endif
#ifdef LIT_LIGHTMAP_BAKING
#ifdef LIT_LIGHTMAP_BAKING_COLOR
#include "bakeLmEndPS"
#endif
#ifdef LIT_LIGHTMAP_BAKING_DIR
#include "bakeDirLmEndPS"
#endif
#else
#include "endPS"
#include "outputAlphaPS"
#endif
#ifdef LIT_MSDF
gl_FragColor = applyMsdf(gl_FragColor);
#endif
#include "outputPS"
#include "debugOutputPS"
#ifdef LIT_SHADOW_CATCHER
gl_FragColor.rgb = vec3(dShadowCatcher);
#endif
}
`;var W1=`
vec3 sReflection;
vec3 dVertexNormalW;
vec3 dTangentW;
vec3 dBinormalW;
vec3 dViewDirW;
vec3 dReflDirW;
vec3 ccReflDirW;
vec3 dLightDirNormW;
float dAtten;
mat3 dTBN;
vec4 dReflection;
vec3 dDiffuseLight;
vec3 dSpecularLight;
float ccFresnel;
vec3 ccReflection;
vec3 ccSpecularLight;
float ccSpecularityNoFres;
vec3 sSpecularLight;
#ifdef LIT_DISPERSION
uniform float material_dispersion;
#endif
#ifndef LIT_OPACITY_FADES_SPECULAR
uniform float material_alphaFade;
#endif
#ifdef LIT_SSAO
uniform sampler2D ssaoTexture;
uniform vec2 ssaoTextureSizeInv;
#endif
#ifdef LIT_SHADOW_CATCHER
float dShadowCatcher = 1.0;
#endif
#if LIGHT_COUNT > 0
#include "lightDeclarationPS, LIGHT_COUNT"
#endif
#ifdef LIT_SPECULAR
#if LIT_FRESNEL_MODEL == NONE && !defined(LIT_REFLECTIONS) && !defined(LIT_DIFFUSE_MAP)
#define LIT_OLD_AMBIENT
#endif
#endif
#ifdef STD_LIGHTMAP_DIR
uniform float bakeDir;
#endif
#ifdef LIT_LIGHTMAP_BAKING_ADD_AMBIENT
uniform float ambientBakeOcclusionContrast;
uniform float ambientBakeOcclusionBrightness;
#endif
`;var X1=`
void main(void) {
#include "litUserMainStartPS"
dReflection = vec4(0);
#ifdef LIT_CLEARCOAT
ccSpecularLight = vec3(0);
ccReflection = vec3(0);
#endif
#if LIT_NONE_SLICE_MODE == SLICED
#include "startNineSlicedPS"
#elif LIT_NONE_SLICE_MODE == TILED
#include "startNineSlicedTiledPS"
#endif
#ifdef LIT_NEEDS_NORMAL
dVertexNormalW = normalize(vNormalW);
#ifdef LIT_TANGENTS
#if defined(LIT_HEIGHTS) || defined(LIT_USE_NORMALS) || defined(LIT_USE_CLEARCOAT_NORMALS) || defined(LIT_GGX_SPECULAR)
dTangentW = vTangentW;
dBinormalW = vBinormalW;
#endif
#endif
getViewDir();
#ifdef LIT_TBN
getTBN(dTangentW, dBinormalW, dVertexNormalW);
#ifdef LIT_TWO_SIDED_LIGHTING
handleTwoSidedLighting();
#endif
#endif
#endif
evaluateFrontend();
#include "debugProcessFrontendPS"
evaluateBackend();
#include "litUserMainEndPS"
}
`;var Y1=`
#ifdef LIT_NEEDS_NORMAL
#include "cubeMapRotatePS"
#include "cubeMapProjectPS"
#include "envProcPS"
#endif
#ifdef LIT_SPECULAR_OR_REFLECTION
#ifdef LIT_METALNESS
#include "metalnessModulatePS"
#endif
#ifdef LIT_IRIDESCENCE
#include "iridescenceDiffractionPS"
#endif
#endif
#if defined(LIT_SPECULAR_OR_REFLECTION) || defined(LIT_REFRACTION)
#if LIT_FRESNEL_MODEL == SCHLICK
#include "fresnelSchlickPS"
#endif
#endif
#ifdef LIT_AO
#include "aoDiffuseOccPS"
#include "aoSpecOccPS"
#endif
#if LIT_REFLECTION_SOURCE == ENVATLASHQ
#include "envAtlasPS"
#include "reflectionEnvHQPS"
#elif LIT_REFLECTION_SOURCE == ENVATLAS
#include "envAtlasPS"
#include "reflectionEnvPS"
#elif LIT_REFLECTION_SOURCE == CUBEMAP
#include "reflectionCubePS"
#elif LIT_REFLECTION_SOURCE == SPHEREMAP
#include "reflectionSpherePS"
#endif
#ifdef LIT_REFLECTIONS
#ifdef LIT_CLEARCOAT
#include "reflectionCCPS"
#endif
#ifdef LIT_SHEEN
#include "reflectionSheenPS"
#endif
#endif
#ifdef LIT_REFRACTION
#if defined(LIT_DYNAMIC_REFRACTION)
#include "refractionDynamicPS"
#elif defined(LIT_REFLECTIONS)
#include "refractionCubePS"
#endif
#endif
#ifdef LIT_SHEEN
#include "lightSheenPS"
#endif
uniform vec3 material_ambient;
#ifdef LIT_SPECULAR
#ifdef LIT_LIGHTING
#ifdef LIT_GGX_SPECULAR
#ifdef LIT_ANISOTROPY
#include "lightSpecularAnisoGGXPS"
#else
#include "lightSpecularGGXPS"
#endif
#else
#include "lightSpecularBlinnPS"
#endif
#endif
#endif
#include "combinePS"
#ifdef LIT_LIGHTMAP
#include "lightmapAddPS"
#endif
#ifdef LIT_ADD_AMBIENT
#include "ambientPS"
#endif
#ifdef LIT_MSDF
#include "msdfPS"
#endif
#ifdef LIT_NEEDS_NORMAL
#include "viewDirPS"
#ifdef LIT_SPECULAR
#ifdef LIT_ANISOTROPY
#include "reflDirAnisoPS"
#else
#include "reflDirPS"
#endif
#endif
#endif
#include "lightingPS"
`;var K1=`
#include "basePS"
#include "sphericalPS"
#include "decodePS"
#include "gammaPS"
#include "tonemappingPS"
#include "fogPS"
#if LIT_NONE_SLICE_MODE == SLICED
#include "baseNineSlicedPS"
#elif LIT_NONE_SLICE_MODE == TILED
#include "baseNineSlicedTiledPS"
#endif
#ifdef LIT_TBN
#include "TBNPS"
#ifdef LIT_TWO_SIDED_LIGHTING
#include "twoSidedLightingPS"
#endif
#endif
`;var j1=`
#include "varyingsPS"
#include "litUserDeclarationPS"
#include "frontendDeclPS"
#if defined(PICK_PASS) || defined(PREPASS_PASS)
#include "frontendCodePS"
#include "litUserCodePS"
#include "litOtherMainPS"
#elif defined(SHADOW_PASS)
#include "frontendCodePS"
#include "litUserCodePS"
#include "litShadowMainPS"
#else
#include "litForwardDeclarationPS"
#include "litForwardPreCodePS"
#include "frontendCodePS"
#include "litForwardPostCodePS"
#include "litForwardBackendPS"
#include "litUserCodePS"
#include "litForwardMainPS"
#endif
`;var q1=`
#include "varyingsVS"
#include "litUserDeclarationVS"
#ifdef VERTEX_COLOR
attribute vec4 vertex_color;
#endif
#ifdef NINESLICED
varying vec2 vMask;
varying vec2 vTiledUv;
uniform mediump vec4 innerOffset;
uniform mediump vec2 outerScale;
uniform mediump vec4 atlasRect;
#endif
vec3 dPositionW;
mat4 dModelMatrix;
#include "transformCoreVS"
#ifdef UV0
attribute vec2 vertex_texCoord0;
#include "uv0VS"
#endif
#ifdef UV1
attribute vec2 vertex_texCoord1;
#include "uv1VS"
#endif
#ifdef LINEAR_DEPTH
#ifndef VIEWMATRIX
#define VIEWMATRIX
uniform mat4 matrix_view;
#endif
#endif
#include "transformVS"
#ifdef NORMALS
#include "normalCoreVS"
#include "normalVS"
#endif
#ifdef TANGENTS
attribute vec4 vertex_tangent;
#endif
#include "uvTransformUniformsPS, UV_TRANSFORMS_COUNT"
#ifdef MSDF
#include "msdfVS"
#endif
#include "litUserCodeVS"
#ifdef VERTEX_COLOR
vec3 decodeGamma(vec3 raw) {
return pow(raw, vec3(2.2));
}
vec4 gammaCorrectInput(vec4 color) {
return vec4(decodeGamma(color.xyz), color.w);
}
#endif
void main(void) {
#include "litUserMainStartVS"
gl_PointSize = 1.0;
gl_Position = getPosition();
vPositionW = getWorldPosition();
#ifdef NORMALS
vNormalW = getNormal();
#endif
#ifdef TANGENTS
vTangentW = normalize(dNormalMatrix * vertex_tangent.xyz);
vBinormalW = cross(vNormalW, vTangentW) * vertex_tangent.w;
#elif defined(GGX_SPECULAR)
vObjectSpaceUpW = normalize(dNormalMatrix * vec3(0, 1, 0));
#endif
#ifdef UV0
vec2 uv0 = getUv0();
#ifdef UV0_UNMODIFIED
vUv0 = uv0;
#endif
#endif
#ifdef UV1
vec2 uv1 = getUv1();
#ifdef UV1_UNMODIFIED
vUv1 = uv1;
#endif
#endif
#include "uvTransformVS, UV_TRANSFORMS_COUNT"
#ifdef VERTEX_COLOR
#ifdef STD_VERTEX_COLOR_GAMMA
vVertexColor = gammaCorrectInput(vertex_color);
#else
vVertexColor = vertex_color;
#endif
#endif
#ifdef LINEAR_DEPTH
vLinearDepth = -(matrix_view * vec4(vPositionW, 1.0)).z;
#endif
#ifdef MSDF
unpackMsdfParams();
#endif
#include "litUserMainEndVS"
}
`;var $1=`
#ifdef PICK_PASS
#include "pickPS"
#endif
#ifdef PREPASS_PASS
#include "floatAsUintPS"
#endif
void main(void) {
#include "litUserMainStartPS"
evaluateFrontend();
#ifdef PICK_PASS
pcFragColor0 = getPickOutput();
#ifdef DEPTH_PICK_PASS
pcFragColor1 = getPickDepth();
#endif
#endif
#ifdef PREPASS_PASS
gl_FragColor = float2vec4(vLinearDepth);
#endif
#include "litUserMainEndPS"
}
`;var Z1=`
vec3 litArgs_albedo;
float litArgs_opacity;
vec3 litArgs_emission;
vec3 litArgs_worldNormal;
float litArgs_ao;
vec3 litArgs_lightmap;
vec3 litArgs_lightmapDir;
float litArgs_metalness;
vec3 litArgs_specularity;
float litArgs_specularityFactor;
float litArgs_gloss;
float litArgs_sheen_gloss;
vec3 litArgs_sheen_specularity;
float litArgs_transmission;
float litArgs_thickness;
float litArgs_ior;
float litArgs_dispersion;
float litArgs_iridescence_intensity;
float litArgs_iridescence_thickness;
vec3 litArgs_clearcoat_worldNormal;
float litArgs_clearcoat_specularity;
float litArgs_clearcoat_gloss;
`;var Q1=`
#if LIT_NONE_SLICE_MODE == TILED
const float textureBias = -1000.0;
#else
uniform float textureBias;
#endif
#include "litShaderArgsPS"
`;var J1=`
#if LIGHT_TYPE != DIRECTIONAL
uniform vec3 view_position;
uniform float light_radius;
#endif
#if SHADOW_TYPE == PCSS_32F
#include "linearizeDepthPS"
#endif
void main(void) {
#include "litUserMainStartPS"
evaluateFrontend();
#ifdef PERSPECTIVE_DEPTH
float depth = gl_FragCoord.z;
#if SHADOW_TYPE == PCSS_32F
#if LIGHT_TYPE != DIRECTIONAL
depth = linearizeDepthWithParams(depth, camera_params);
#endif
#endif
#else
float depth = min(distance(view_position, vPositionW) / light_radius, 0.99999);
#define MODIFIED_DEPTH
#endif
#if SHADOW_TYPE == VSM_16F || SHADOW_TYPE == VSM_32F
#if SHADOW_TYPE == VSM_32F
float exponent = 15.0;
#else
float exponent = 5.54;
#endif
depth = 2.0 * depth - 1.0;
depth = exp(exponent * depth);
gl_FragColor = vec4(depth, depth*depth, 1.0, 1.0);
#else
#if SHADOW_TYPE == PCSS_32F
gl_FragColor.r = depth;
#else
#ifdef MODIFIED_DEPTH
gl_FragDepth = depth;
#endif
gl_FragColor = vec4(1.0);
#endif
#endif
#include "litUserMainEndPS"
}
`;var e3=`
mat3 transposeMat3( const in mat3 m ) {
mat3 tmp;
tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );
tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );
tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );
return tmp;
}
vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
const float LUT_SIZE = 64.0;
const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
const float LUT_BIAS = 0.5 / LUT_SIZE;
float dotNV = saturate( dot( N, V ) );
vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
uv = uv * LUT_SCALE + LUT_BIAS;
return uv;
}
float LTC_ClippedSphereFormFactor( const in vec3 f ) {
float l = length( f );
return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
}
vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
float x = dot( v1, v2 );
float y = abs( x );
float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
float b = 3.4175940 + ( 4.1616724 + y ) * y;
float v = a / b;
float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
return cross( v1, v2 ) * theta_sintheta;
}
struct Coords {
vec3 coord0;
vec3 coord1;
vec3 coord2;
vec3 coord3;
};
float LTC_EvaluateRect( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in Coords rectCoords) {
vec3 v1 = rectCoords.coord1 - rectCoords.coord0;
vec3 v2 = rectCoords.coord3 - rectCoords.coord0;
vec3 lightNormal = cross( v1, v2 );
float factor = sign(-dot( lightNormal, P - rectCoords.coord0 ));
vec3 T1, T2;
T1 = normalize( V - N * dot( V, N ) );
T2 = factor * cross( N, T1 );
mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );
vec3 coords[ 4 ];
coords[ 0 ] = mat * ( rectCoords.coord0 - P );
coords[ 1 ] = mat * ( rectCoords.coord1 - P );
coords[ 2 ] = mat * ( rectCoords.coord2 - P );
coords[ 3 ] = mat * ( rectCoords.coord3 - P );
coords[ 0 ] = normalize( coords[ 0 ] );
coords[ 1 ] = normalize( coords[ 1 ] );
coords[ 2 ] = normalize( coords[ 2 ] );
coords[ 3 ] = normalize( coords[ 3 ] );
vec3 vectorFormFactor = vec3( 0.0 );
vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );
vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );
vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );
vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );
float result = LTC_ClippedSphereFormFactor( vectorFormFactor );
return result;
}
Coords dLTCCoords;
Coords getLTCLightCoords(vec3 lightPos, vec3 halfWidth, vec3 halfHeight){
Coords coords;
coords.coord0 = lightPos + halfWidth - halfHeight;
coords.coord1 = lightPos - halfWidth - halfHeight;
coords.coord2 = lightPos - halfWidth + halfHeight;
coords.coord3 = lightPos + halfWidth + halfHeight;
return coords;
}
float dSphereRadius;
Coords getSphereLightCoords(vec3 lightPos, vec3 halfWidth, vec3 halfHeight){
dSphereRadius = max(length(halfWidth), length(halfHeight));
vec3 f = reflect(normalize(lightPos - view_position), vNormalW);
vec3 w = normalize(cross(f, halfHeight));
vec3 h = normalize(cross(f, w));
return getLTCLightCoords(lightPos, w * dSphereRadius, h * dSphereRadius);
}
vec2 dLTCUV;
#ifdef LIT_CLEARCOAT
vec2 ccLTCUV;
#endif
vec2 getLTCLightUV(float gloss, vec3 worldNormal, vec3 viewDir)
{
float roughness = max((1.0 - gloss) * (1.0 - gloss), 0.001);
return LTC_Uv( worldNormal, viewDir, roughness );
}
vec3 dLTCSpecFres;
#ifdef LIT_CLEARCOAT
vec3 ccLTCSpecFres;
#endif
vec3 getLTCLightSpecFres(vec2 uv, vec3 specularity)
{
vec4 t2 = texture2DLod(areaLightsLutTex2, uv, 0.0);
return specularity * t2.x + ( vec3( 1.0 ) - specularity) * t2.y;
}
void calcLTCLightValues(float gloss, vec3 worldNormal, vec3 viewDir, vec3 specularity, float clearcoatGloss, vec3 clearcoatWorldNormal, float clearcoatSpecularity)
{
dLTCUV = getLTCLightUV(gloss, worldNormal, viewDir);
dLTCSpecFres = getLTCLightSpecFres(dLTCUV, specularity);
#ifdef LIT_CLEARCOAT
ccLTCUV = getLTCLightUV(clearcoatGloss, clearcoatWorldNormal, viewDir);
ccLTCSpecFres = getLTCLightSpecFres(ccLTCUV, vec3(clearcoatSpecularity));
#endif
}
void calcRectLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight) {
dLTCCoords = getLTCLightCoords(lightPos, halfWidth, halfHeight);
}
void calcDiskLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight) {
calcRectLightValues(lightPos, halfWidth, halfHeight);
}
void calcSphereLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight) {
dLTCCoords = getSphereLightCoords(lightPos, halfWidth, halfHeight);
}
vec3 SolveCubic(vec4 Coefficient)
{
float pi = 3.14159;
Coefficient.xyz /= Coefficient.w;
Coefficient.yz /= 3.0;
float A = Coefficient.w;
float B = Coefficient.z;
float C = Coefficient.y;
float D = Coefficient.x;
vec3 Delta = vec3(
-Coefficient.z * Coefficient.z + Coefficient.y,
-Coefficient.y * Coefficient.z + Coefficient.x,
dot(vec2(Coefficient.z, -Coefficient.y), Coefficient.xy)
);
float Discriminant = dot(vec2(4.0 * Delta.x, -Delta.y), Delta.zy);
vec2 xlc, xsc;
{
float A_a = 1.0;
float C_a = Delta.x;
float D_a = -2.0 * B * Delta.x + Delta.y;
float Theta = atan(sqrt(Discriminant), -D_a) / 3.0;
float x_1a = 2.0 * sqrt(-C_a) * cos(Theta);
float x_3a = 2.0 * sqrt(-C_a) * cos(Theta + (2.0 / 3.0) * pi);
float xl;
if ((x_1a + x_3a) > 2.0 * B)
xl = x_1a;
else
xl = x_3a;
xlc = vec2(xl - B, A);
}
{
float A_d = D;
float C_d = Delta.z;
float D_d = -D * Delta.y + 2.0 * C * Delta.z;
float Theta = atan(D * sqrt(Discriminant), -D_d) / 3.0;
float x_1d = 2.0 * sqrt(-C_d) * cos(Theta);
float x_3d = 2.0 * sqrt(-C_d) * cos(Theta + (2.0 / 3.0) * pi);
float xs;
if (x_1d + x_3d < 2.0 * C)
xs = x_1d;
else
xs = x_3d;
xsc = vec2(-D, xs + C);
}
float E = xlc.y * xsc.y;
float F = -xlc.x * xsc.y - xlc.y * xsc.x;
float G = xlc.x * xsc.x;
vec2 xmc = vec2(C * F - B * G, -B * F + C * E);
vec3 Root = vec3(xsc.x / xsc.y, xmc.x / xmc.y, xlc.x / xlc.y);
if (Root.x < Root.y && Root.x < Root.z)
Root.xyz = Root.yxz;
else if (Root.z < Root.x && Root.z < Root.y)
Root.xyz = Root.xzy;
return Root;
}
float LTC_EvaluateDisk(vec3 N, vec3 V, vec3 P, mat3 Minv, Coords points)
{
vec3 T1 = normalize(V - N * dot(V, N));
vec3 T2 = cross(N, T1);
mat3 R = transposeMat3( mat3( T1, T2, N ) );
vec3 L_[ 3 ];
L_[ 0 ] = R * ( points.coord0 - P );
L_[ 1 ] = R * ( points.coord1 - P );
L_[ 2 ] = R * ( points.coord2 - P );
vec3 C = 0.5 * (L_[0] + L_[2]);
vec3 V1 = 0.5 * (L_[1] - L_[2]);
vec3 V2 = 0.5 * (L_[1] - L_[0]);
C = Minv * C;
V1 = Minv * V1;
V2 = Minv * V2;
float a, b;
float d11 = dot(V1, V1);
float d22 = dot(V2, V2);
float d12 = dot(V1, V2);
if (abs(d12) / sqrt(d11 * d22) > 0.0001)
{
float tr = d11 + d22;
float det = -d12 * d12 + d11 * d22;
det = sqrt(det);
float u = 0.5 * sqrt(tr - 2.0 * det);
float v = 0.5 * sqrt(tr + 2.0 * det);
float e_max = (u + v) * (u + v);
float e_min = (u - v) * (u - v);
vec3 V1_, V2_;
if (d11 > d22)
{
V1_ = d12 * V1 + (e_max - d11) * V2;
V2_ = d12 * V1 + (e_min - d11) * V2;
}
else
{
V1_ = d12*V2 + (e_max - d22)*V1;
V2_ = d12*V2 + (e_min - d22)*V1;
}
a = 1.0 / e_max;
b = 1.0 / e_min;
V1 = normalize(V1_);
V2 = normalize(V2_);
}
else
{
a = 1.0 / dot(V1, V1);
b = 1.0 / dot(V2, V2);
V1 *= sqrt(a);
V2 *= sqrt(b);
}
vec3 V3 = normalize(cross(V1, V2));
if (dot(C, V3) < 0.0)
V3 *= -1.0;
float L = dot(V3, C);
float x0 = dot(V1, C) / L;
float y0 = dot(V2, C) / L;
float E1 = inversesqrt(a);
float E2 = inversesqrt(b);
a *= L * L;
b *= L * L;
float c0 = a * b;
float c1 = a * b * (1.0 + x0 * x0 + y0 * y0) - a - b;
float c2 = 1.0 - a * (1.0 + x0 * x0) - b * (1.0 + y0 * y0);
float c3 = 1.0;
vec3 roots = SolveCubic(vec4(c0, c1, c2, c3));
float e1 = roots.x;
float e2 = roots.y;
float e3 = roots.z;
vec3 avgDir = vec3(a * x0 / (a - e2), b * y0 / (b - e2), 1.0);
mat3 rotate = mat3(V1, V2, V3);
avgDir = rotate * avgDir;
avgDir = normalize(avgDir);
float L1 = sqrt(-e2 / e3);
float L2 = sqrt(-e2 / e1);
float formFactor = max(0.0, L1 * L2 * inversesqrt((1.0 + L1 * L1) * (1.0 + L2 * L2)));
const float LUT_SIZE = 64.0;
const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
const float LUT_BIAS = 0.5 / LUT_SIZE;
vec2 uv = vec2(avgDir.z * 0.5 + 0.5, formFactor);
uv = uv*LUT_SCALE + LUT_BIAS;
float scale = texture2DLod(areaLightsLutTex2, uv, 0.0).w;
return formFactor*scale;
}
float FixNan(float value) {
#ifdef WEBGPU
return value != value ? 0.0 : value;
#else
return isnan(value) ? 0.0 : value;
#endif
}
float getRectLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) {
return LTC_EvaluateRect( worldNormal, viewDir, vPositionW, mat3( 1.0 ), dLTCCoords );
}
float getDiskLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) {
return FixNan(LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, mat3( 1.0 ), dLTCCoords ));
}
float getSphereLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) {
float falloff = dSphereRadius / (dot(lightDir, lightDir) + dSphereRadius);
return FixNan(getLightDiffuse(worldNormal, viewDir, lightDirNorm) * falloff);
}
mat3 getLTCLightInvMat(vec2 uv)
{
vec4 t1 = texture2DLod(areaLightsLutTex1, uv, 0.0);
return mat3(
vec3( t1.x, 0, t1.y ),
vec3( 0, 1, 0 ),
vec3( t1.z, 0, t1.w )
);
}
float calcRectLightSpecular(vec3 worldNormal, vec3 viewDir, vec2 uv) {
mat3 mInv = getLTCLightInvMat(uv);
return LTC_EvaluateRect( worldNormal, viewDir, vPositionW, mInv, dLTCCoords );
}
float getRectLightSpecular(vec3 worldNormal, vec3 viewDir) {
return calcRectLightSpecular(worldNormal, viewDir, dLTCUV);
}
float calcDiskLightSpecular(vec3 worldNormal, vec3 viewDir, vec2 uv) {
mat3 mInv = getLTCLightInvMat(uv);
return LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, mInv, dLTCCoords );
}
float getDiskLightSpecular(vec3 worldNormal, vec3 viewDir) {
return calcDiskLightSpecular(worldNormal, viewDir, dLTCUV);
}
float getSphereLightSpecular(vec3 worldNormal, vec3 viewDir) {
return calcDiskLightSpecular(worldNormal, viewDir, dLTCUV);
}
`;var t3=`
#ifdef STD_METALNESS_CONSTANT
uniform float material_metalness;
#endif
void getMetalness() {
float metalness = 1.0;
#ifdef STD_METALNESS_CONSTANT
metalness *= material_metalness;
#endif
#ifdef STD_METALNESS_TEXTURE
metalness *= texture2DBias({STD_METALNESS_TEXTURE_NAME}, {STD_METALNESS_TEXTURE_UV}, textureBias).{STD_METALNESS_TEXTURE_CHANNEL};
#endif
#ifdef STD_METALNESS_VERTEX
metalness *= saturate(vVertexColor.{STD_METALNESS_VERTEX_CHANNEL});
#endif
dMetalness = metalness;
}
`;var s3=`
uniform sampler2D texture_msdfMap;
float median(float r, float g, float b) {
return max(min(r, g), min(max(r, g), b));
}
float map (float min, float max, float v) {
return (v - min) / (max - min);
}
uniform float font_sdfIntensity;
uniform float font_pxrange;
uniform float font_textureWidth;
#ifndef LIT_MSDF_TEXT_ATTRIBUTE
uniform vec4 outline_color;
uniform float outline_thickness;
uniform vec4 shadow_color;
uniform vec2 shadow_offset;
#else
varying vec4 outline_color;
varying float outline_thickness;
varying vec4 shadow_color;
varying vec2 shadow_offset;
#endif
vec4 applyMsdf(vec4 color) {
color.rgb = gammaCorrectInput(color.rgb);
vec3 tsample = texture2D(texture_msdfMap, vUv0).rgb;
vec2 uvShdw = vUv0 - shadow_offset;
vec3 ssample = texture2D(texture_msdfMap, uvShdw).rgb;
float sigDist = median(tsample.r, tsample.g, tsample.b);
float sigDistShdw = median(ssample.r, ssample.g, ssample.b);
float smoothingMax = 0.2;
vec2 w = fwidth(vUv0);
float smoothing = clamp(w.x * font_textureWidth / font_pxrange, 0.0, smoothingMax);
float mapMin = 0.05;
float mapMax = clamp(1.0 - font_sdfIntensity, mapMin, 1.0);
float sigDistInner = map(mapMin, mapMax, sigDist);
float sigDistOutline = map(mapMin, mapMax, sigDist + outline_thickness);
sigDistShdw = map(mapMin, mapMax, sigDistShdw + outline_thickness);
float center = 0.5;
float inside = smoothstep(center-smoothing, center+smoothing, sigDistInner);
float outline = smoothstep(center-smoothing, center+smoothing, sigDistOutline);
float shadow = smoothstep(center-smoothing, center+smoothing, sigDistShdw);
vec4 tcolor = (outline > inside) ? outline * vec4(outline_color.a * outline_color.rgb, outline_color.a) : vec4(0.0);
tcolor = mix(tcolor, color, inside);
vec4 scolor = (shadow > outline) ? shadow * vec4(shadow_color.a * shadow_color.rgb, shadow_color.a) : tcolor;
tcolor = mix(scolor, tcolor, outline);
tcolor.rgb = gammaCorrectOutput(tcolor.rgb);
return tcolor;
}
`;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;
varying float outline_thickness;
varying vec4 shadow_color;
varying vec2 shadow_offset;
void unpackMsdfParams() {
vec3 little = mod(vertex_outlineParameters, 256.);
vec3 big = (vertex_outlineParameters - little) / 256.;
outline_color.rb = little.xy / 255.;
outline_color.ga = big.xy / 255.;
outline_thickness = little.z / 255. * 0.2;
little = mod(vertex_shadowParameters, 256.);
big = (vertex_shadowParameters - little) / 256.;
shadow_color.rb = little.xy / 255.;
shadow_color.ga = big.xy / 255.;
shadow_offset = (vec2(little.z, big.z) / 127. - 1.) * 0.005;
}
`;var n3=`
mat3 dNormalMatrix;
vec3 getNormal() {
dNormalMatrix = getNormalMatrix(dModelMatrix);
vec3 localNormal = getLocalNormal(vertex_normal);
return normalize(dNormalMatrix * localNormal);
}
`;var l3=`
attribute vec3 vertex_normal;
uniform mat3 matrix_normal;
#ifdef MORPHING_NORMAL
#ifdef MORPHING_INT
uniform highp usampler2D morphNormalTex;
#else
uniform highp sampler2D morphNormalTex;
#endif
#endif
vec3 getLocalNormal(vec3 vertexNormal) {
vec3 localNormal = vertex_normal;
#ifdef MORPHING_NORMAL
ivec2 morphUV = getTextureMorphCoords();
#ifdef MORPHING_INT
vec3 morphNormal = vec3(texelFetch(morphNormalTex, ivec2(morphUV), 0).xyz) / 65535.0 * 2.0 - 1.0;
#else
vec3 morphNormal = texelFetch(morphNormalTex, ivec2(morphUV), 0).xyz;
#endif
localNormal += morphNormal;
#endif
return localNormal;
}
#if defined(SKIN) || defined(BATCH)
mat3 getNormalMatrix(mat4 modelMatrix) {
return mat3(modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz);
}
#elif defined(INSTANCING)
mat3 getNormalMatrix(mat4 modelMatrix) {
return mat3(modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz);
}
#else
mat3 getNormalMatrix(mat4 modelMatrix) {
return matrix_normal;
}
#endif
`;var c3=`
#ifdef STD_NORMAL_TEXTURE
uniform float material_bumpiness;
#endif
#ifdef STD_NORMALDETAIL_TEXTURE
uniform float material_normalDetailMapBumpiness;
vec3 blendNormals(vec3 n1, vec3 n2) {
n1 += vec3(0, 0, 1);
n2 *= vec3(-1, -1, 1);
return n1 * dot(n1, n2) / n1.z - n2;
}
#endif
void getNormal() {
#ifdef STD_NORMAL_TEXTURE
vec3 normalMap = {STD_NORMAL_TEXTURE_DECODE}(texture2DBias({STD_NORMAL_TEXTURE_NAME}, {STD_NORMAL_TEXTURE_UV}, textureBias));
normalMap = mix(vec3(0.0, 0.0, 1.0), normalMap, material_bumpiness);
#ifdef STD_NORMALDETAIL_TEXTURE
vec3 normalDetailMap = {STD_NORMALDETAIL_TEXTURE_DECODE}(texture2DBias({STD_NORMALDETAIL_TEXTURE_NAME}, {STD_NORMALDETAIL_TEXTURE_UV}, textureBias));
normalDetailMap = mix(vec3(0.0, 0.0, 1.0), normalDetailMap, material_normalDetailMapBumpiness);
normalMap = blendNormals(normalMap, normalDetailMap);
#endif
dNormalW = normalize(dTBN * normalMap);
#else
dNormalW = dVertexNormalW;
#endif
}
`;var h3=`
uniform float material_opacity;
uniform float material_alphaDitherScale;
void getOpacity() {
dAlpha = material_opacity;
#ifdef STD_OPACITY_TEXTURE
dAlpha *= texture2DBias({STD_OPACITY_TEXTURE_NAME}, {STD_OPACITY_TEXTURE_UV}, textureBias).{STD_OPACITY_TEXTURE_CHANNEL};
#endif
#ifdef STD_OPACITY_VERTEX
dAlpha *= clamp(vVertexColor.{STD_OPACITY_VERTEX_CHANNEL}, 0.0, 1.0);
#endif
}
`;var f3=`
#if STD_OPACITY_DITHER == BAYER8
#include "bayerPS"
#endif
uniform vec4 blueNoiseJitter;
#if STD_OPACITY_DITHER == BLUENOISE
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
#if STD_OPACITY_DITHER == BLUENOISE
vec2 uv = fract(gl_FragCoord.xy / 32.0 + blueNoiseJitter.xy + id);
float noise = texture2DLod(blueNoiseTex32, uv, 0.0).y;
#endif
#if STD_OPACITY_DITHER == IGNNOISE
vec3 magic = vec3(0.06711056, 0.00583715, 52.9829189);
float noise = fract(magic.z * fract(dot(gl_FragCoord.xy + blueNoiseJitter.xy + id, magic.xy)));
#endif
#endif
noise = pow(noise, 2.2);
if (alpha < noise)
discard;
}
`;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
gl_FragColor.rgb *= litArgs_opacity;
gl_FragColor.a = litArgs_opacity;
#else
gl_FragColor.a = 1.0;
#endif
`;var p3=`
varying vec2 vUv0;
uniform sampler2D source;
void main(void) {
gl_FragColor = texture2D(source, vUv0);
}
`;var m3=`
uniform vec3 material_sheen;
void getSheen() {
vec3 sheenColor = material_sheen;
#ifdef STD_SHEEN_TEXTURE
sheenColor *= {STD_SHEEN_TEXTURE_DECODE}(texture2DBias({STD_SHEEN_TEXTURE_NAME}, {STD_SHEEN_TEXTURE_UV}, textureBias)).{STD_SHEEN_TEXTURE_CHANNEL};
#endif
#ifdef STD_SHEEN_VERTEX
sheenColor *= saturate(vVertexColor.{STD_SHEEN_VERTEX_CHANNEL});
#endif
sSpecularity = sheenColor;
}
`;var _3=`
uniform float material_sheenGloss;
void getSheenGlossiness() {
float sheenGlossiness = material_sheenGloss;
#ifdef STD_SHEENGLOSS_TEXTURE
sheenGlossiness *= texture2DBias({STD_SHEENGLOSS_TEXTURE_NAME}, {STD_SHEENGLOSS_TEXTURE_UV}, textureBias).{STD_SHEENGLOSS_TEXTURE_CHANNEL};
#endif
#ifdef STD_SHEENGLOSS_VERTEX
sheenGlossiness *= saturate(vVertexColor.{STD_SHEENGLOSS_VERTEX_CHANNEL});
#endif
#ifdef STD_SHEENGLOSS_INVERT
sheenGlossiness = 1.0 - sheenGlossiness;
#endif
sGlossiness = sheenGlossiness + 0.0000001;
}
`;var g3=`
uniform float material_heightMapFactor;
void getParallax() {
float parallaxScale = material_heightMapFactor;
float height = texture2DBias({STD_HEIGHT_TEXTURE_NAME}, {STD_HEIGHT_TEXTURE_UV}, textureBias).{STD_HEIGHT_TEXTURE_CHANNEL};
height = height * parallaxScale - parallaxScale * 0.5;
vec3 viewDirT = dViewDirW * dTBN;
viewDirT.z += 0.42;
dUvOffset = height * (viewDirT.xy / viewDirT.z);
}
`;var S3=`
vec4 encodePickOutput(uint id) {
const vec4 inv = vec4(1.0 / 255.0);
const uvec4 shifts = uvec4(16, 8, 0, 24);
uvec4 col = (uvec4(id) >> shifts) & uvec4(0xff);
return vec4(col) * inv;
}
#ifndef PICK_CUSTOM_ID
uniform uint meshInstanceId;
vec4 getPickOutput() {
return encodePickOutput(meshInstanceId);
}
#endif
#ifdef DEPTH_PICK_PASS
#include "floatAsUintPS"
#ifndef CAMERAPLANES
#define CAMERAPLANES
uniform vec4 camera_params;
#endif
vec4 getPickDepth() {
float linearDepth;
if (camera_params.w > 0.5) {
linearDepth = gl_FragCoord.z;
} else {
float viewDist = 1.0 / gl_FragCoord.w;
linearDepth = (viewDist - camera_params.z) / (camera_params.y - camera_params.z);
}
return float2uint(linearDepth);
}
#endif
`;var x3=`
void getReflDir(vec3 worldNormal, vec3 viewDir, float gloss, mat3 tbn) {
dReflDirW = normalize(-reflect(viewDir, worldNormal));
}
`;var v3=`
void getReflDir(vec3 worldNormal, vec3 viewDir, float gloss, mat3 tbn) {
float roughness = sqrt(1.0 - min(gloss, 1.0));
vec2 direction = dAnisotropyRotation;
vec3 anisotropicT = normalize(tbn * vec3(direction, 0.0));
vec3 anisotropicB = normalize(cross(tbn[2], anisotropicT));
float anisotropy = dAnisotropy;
vec3 anisotropicDirection = anisotropicB;
vec3 anisotropicTangent = cross(anisotropicDirection, viewDir);
vec3 anisotropicNormal = cross(anisotropicTangent, anisotropicDirection);
float bendFactor = 1.0 - anisotropy * (1.0 - roughness);
float bendFactor4 = bendFactor * bendFactor * bendFactor * bendFactor;
vec3 bentNormal = normalize(mix(normalize(anisotropicNormal), normalize(worldNormal), bendFactor4));
dReflDirW = reflect(-viewDir, bentNormal);
}
`;var T3=`
#ifdef LIT_CLEARCOAT
void addReflectionCC(vec3 reflDir, float gloss) {
ccReflection += calcReflection(reflDir, gloss);
}
#endif
`;var y3=`
uniform samplerCube texture_cubeMap;
uniform float material_reflectivity;
vec3 calcReflection(vec3 reflDir, float gloss) {
vec3 lookupVec = cubeMapProject(reflDir);
lookupVec.x *= -1.0;
return {reflectionDecode}(textureCube(texture_cubeMap, lookupVec));
}
void addReflection(vec3 reflDir, float gloss) {
dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);
}
`;var E3=`
#ifndef ENV_ATLAS
#define ENV_ATLAS
uniform sampler2D texture_envAtlas;
#endif
uniform samplerCube texture_cubeMap;
uniform float material_reflectivity;
vec3 calcReflection(vec3 reflDir, float gloss) {
vec3 dir = cubeMapProject(reflDir) * vec3(-1.0, 1.0, 1.0);
vec2 uv = toSphericalUv(dir);
float level = saturate(1.0 - gloss) * 5.0;
float ilevel = floor(level);
float flevel = level - ilevel;
vec3 sharp = {reflectionCubemapDecode}(textureCube(texture_cubeMap, dir));
vec3 roughA = {reflectionDecode}(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel)));
vec3 roughB = {reflectionDecode}(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel + 1.0)));
return processEnvironment(mix(sharp, mix(roughA, roughB, flevel), min(level, 1.0)));
}
void addReflection(vec3 reflDir, float gloss) {
dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);
}
`;var A3=`
#ifndef ENV_ATLAS
#define ENV_ATLAS
uniform sampler2D texture_envAtlas;
#endif
uniform float material_reflectivity;
float shinyMipLevel(vec2 uv) {
vec2 dx = dFdx(uv);
vec2 dy = dFdy(uv);
vec2 uv2 = vec2(fract(uv.x + 0.5), uv.y);
vec2 dx2 = dFdx(uv2);
vec2 dy2 = dFdy(uv2);
float maxd = min(max(dot(dx, dx), dot(dy, dy)), max(dot(dx2, dx2), dot(dy2, dy2)));
return clamp(0.5 * log2(maxd) - 1.0 + textureBias, 0.0, 5.0);
}
vec3 calcReflection(vec3 reflDir, float gloss) {
vec3 dir = cubeMapProject(reflDir) * vec3(-1.0, 1.0, 1.0);
vec2 uv = toSphericalUv(dir);
float level = saturate(1.0 - gloss) * 5.0;
float ilevel = floor(level);
float level2 = shinyMipLevel(uv * atlasSize);
float ilevel2 = floor(level2);
vec2 uv0, uv1;
float weight;
if (ilevel == 0.0) {
uv0 = mapShinyUv(uv, ilevel2);
uv1 = mapShinyUv(uv, ilevel2 + 1.0);
weight = level2 - ilevel2;
} else {
uv0 = uv1 = mapRoughnessUv(uv, ilevel);
weight = 0.0;
}
vec3 linearA = {reflectionDecode}(texture2D(texture_envAtlas, uv0));
vec3 linearB = {reflectionDecode}(texture2D(texture_envAtlas, uv1));
vec3 linear0 = mix(linearA, linearB, weight);
vec3 linear1 = {reflectionDecode}(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel + 1.0)));
return processEnvironment(mix(linear0, linear1, level - ilevel));
}
void addReflection(vec3 reflDir, float gloss) {
dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);
}
`;var C3=`
#ifndef VIEWMATRIX
#define VIEWMATRIX
uniform mat4 matrix_view;
#endif
uniform sampler2D texture_sphereMap;
uniform float material_reflectivity;
vec3 calcReflection(vec3 reflDir, float gloss) {
vec3 reflDirV = (mat3(matrix_view) * reflDir);
float m = 2.0 * sqrt(dot(reflDirV.xy, reflDirV.xy) + (reflDirV.z + 1.0) * (reflDirV.z + 1.0));
vec2 sphereMapUv = reflDirV.xy / m + 0.5;
return {reflectionDecode}(texture2D(texture_sphereMap, sphereMapUv));
}
void addReflection(vec3 reflDir, float gloss) {
dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity);
}
`;var P3=`
void addReflectionSheen(vec3 worldNormal, vec3 viewDir, float gloss) {
float NoV = dot(worldNormal, viewDir);
float alphaG = gloss * gloss;
float a = gloss < 0.25 ? -339.2 * alphaG + 161.4 * gloss - 25.9 : -8.48 * alphaG + 14.3 * gloss - 9.95;
float b = gloss < 0.25 ? 44.0 * alphaG - 23.7 * gloss + 3.26 : 1.97 * alphaG - 3.27 * gloss + 0.72;
float DG = exp( a * NoV + b ) + ( gloss < 0.25 ? 0.0 : 0.1 * ( gloss - 0.25 ) );
sReflection += calcReflection(worldNormal, 0.0) * saturate(DG);
}
`;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);
vec3 refrVec = IOR * viewVec - (IOR * vn + sqrt(k)) * normal;
return refrVec;
}
void addRefraction(
vec3 worldNormal,
vec3 viewDir,
float thickness,
float gloss,
vec3 specularity,
vec3 albedo,
float transmission,
float refractionIndex,
float dispersion
#if defined(LIT_IRIDESCENCE)
, vec3 iridescenceFresnel,
float iridescenceIntensity
#endif
) {
vec4 tmpRefl = dReflection;
vec3 reflectionDir = refract2(-viewDir, worldNormal, refractionIndex);
dReflection = vec4(0);
addReflection(reflectionDir, gloss);
dDiffuseLight = mix(dDiffuseLight, dReflection.rgb * albedo, transmission);
dReflection = tmpRefl;
}
`;var I3=`
uniform float material_invAttenuationDistance;
uniform vec3 material_attenuation;
vec3 evalRefractionColor(vec3 refractionVector, float gloss, float refractionIndex) {
vec4 pointOfRefraction = vec4(vPositionW + refractionVector, 1.0);
vec4 projectionPoint = matrix_viewProjection * pointOfRefraction;
vec2 uv = getGrabScreenPos(projectionPoint);
float iorToRoughness = (1.0 - gloss) * clamp((1.0 / refractionIndex) * 2.0 - 2.0, 0.0, 1.0);
float refractionLod = log2(uScreenSize.x) * iorToRoughness;
vec3 refraction = texture2DLod(uSceneColorMap, uv, refractionLod).rgb;
#ifdef SCENE_COLORMAP_GAMMA
refraction = decodeGamma(refraction);
#endif
return refraction;
}
void addRefraction(
vec3 worldNormal,
vec3 viewDir,
float thickness,
float gloss,
vec3 specularity,
vec3 albedo,
float transmission,
float refractionIndex,
float dispersion
#if defined(LIT_IRIDESCENCE)
, vec3 iridescenceFresnel,
float iridescenceIntensity
#endif
) {
vec3 modelScale;
modelScale.x = length(vec3(matrix_model[0].xyz));
modelScale.y = length(vec3(matrix_model[1].xyz));
modelScale.z = length(vec3(matrix_model[2].xyz));
vec3 scale = thickness * modelScale;
vec3 refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndex)) * scale;
vec3 refraction = evalRefractionColor(refractionVector, gloss, refractionIndex);
#ifdef LIT_DISPERSION
float halfSpread = (1.0 / refractionIndex - 1.0) * 0.025 * dispersion;
float refractionIndexR = refractionIndex - halfSpread;
refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndexR)) * scale;
refraction.r = evalRefractionColor(refractionVector, gloss, refractionIndexR).r;
float refractionIndexB = refractionIndex + halfSpread;
refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndexB)) * scale;
refraction.b = evalRefractionColor(refractionVector, gloss, refractionIndexB).b;
#endif
vec3 transmittance;
if (material_invAttenuationDistance != 0.0)
{
vec3 attenuation = -log(material_attenuation) * material_invAttenuationDistance;
transmittance = exp(-attenuation * length(refractionVector));
}
else
{
transmittance = vec3(1.0);
}
vec3 fresnel = vec3(1.0) -
getFresnel(
dot(viewDir, worldNormal),
gloss,
specularity
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
iridescenceIntensity
#endif
);
dDiffuseLight = mix(dDiffuseLight, refraction * transmittance * fresnel, transmission);
}
`;var R3=`
varying vec2 vUv0;
#ifdef CUBEMAP_SOURCE
uniform samplerCube sourceCube;
#else
uniform sampler2D sourceTex;
#endif
#ifdef USE_SAMPLES_TEX
uniform sampler2D samplesTex;
uniform vec2 samplesTexInverseSize;
#endif
uniform vec3 params;
float targetFace() { return params.x; }
float targetTotalPixels() { return params.y; }
float sourceTotalPixels() { return params.z; }
float PI = 3.141592653589793;
float saturate(float x) {
return clamp(x, 0.0, 1.0);
}
#include "decodePS"
#include "encodePS"
vec3 modifySeams(vec3 dir, float scale) {
vec3 adir = abs(dir);
float M = max(max(adir.x, adir.y), adir.z);
return dir / M * vec3(
adir.x == M ? 1.0 : scale,
adir.y == M ? 1.0 : scale,
adir.z == M ? 1.0 : scale
);
}
vec2 toSpherical(vec3 dir) {
return vec2(dir.xz == vec2(0.0) ? 0.0 : atan(dir.x, dir.z), asin(dir.y));
}
vec3 fromSpherical(vec2 uv) {
return vec3(cos(uv.y) * sin(uv.x),
sin(uv.y),
cos(uv.y) * cos(uv.x));
}
vec3 getDirectionEquirect() {
return fromSpherical((vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0) * vec2(PI, PI * 0.5));
}
float signNotZero(float k){
return(k >= 0.0) ? 1.0 : -1.0;
}
vec2 signNotZero(vec2 v) {
return vec2(signNotZero(v.x), signNotZero(v.y));
}
vec3 octDecode(vec2 o) {
vec3 v = vec3(o.x, 1.0 - abs(o.x) - abs(o.y), o.y);
if (v.y < 0.0) {
v.xz = (1.0 - abs(v.zx)) * signNotZero(v.xz);
}
return normalize(v);
}
vec3 getDirectionOctahedral() {
return octDecode(vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0);
}
vec2 octEncode(in vec3 v) {
float l1norm = abs(v.x) + abs(v.y) + abs(v.z);
vec2 result = v.xz * (1.0 / l1norm);
if (v.y < 0.0) {
result = (1.0 - abs(result.yx)) * signNotZero(result.xy);
}
return result;
}
#ifdef CUBEMAP_SOURCE
vec4 sampleCubemap(vec3 dir) {
return textureCube(sourceCube, modifySeams(dir, 1.0));
}
vec4 sampleCubemap(vec2 sph) {
return sampleCubemap(fromSpherical(sph));
}
vec4 sampleCubemap(vec3 dir, float mipLevel) {
return textureCubeLod(sourceCube, modifySeams(dir, 1.0), mipLevel);
}
vec4 sampleCubemap(vec2 sph, float mipLevel) {
return sampleCubemap(fromSpherical(sph), mipLevel);
}
#else
vec4 sampleEquirect(vec2 sph) {
vec2 uv = sph / vec2(PI * 2.0, PI) + 0.5;
return texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));
}
vec4 sampleEquirect(vec3 dir) {
return sampleEquirect(toSpherical(dir));
}
vec4 sampleEquirect(vec2 sph, float mipLevel) {
vec2 uv = sph / vec2(PI * 2.0, PI) + 0.5;
return texture2DLod(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel);
}
vec4 sampleEquirect(vec3 dir, float mipLevel) {
return sampleEquirect(toSpherical(dir), mipLevel);
}
vec4 sampleOctahedral(vec3 dir) {
vec2 uv = octEncode(dir) * 0.5 + 0.5;
return texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y));
}
vec4 sampleOctahedral(vec2 sph) {
return sampleOctahedral(fromSpherical(sph));
}
vec4 sampleOctahedral(vec3 dir, float mipLevel) {
vec2 uv = octEncode(dir) * 0.5 + 0.5;
return texture2DLod(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel);
}
vec4 sampleOctahedral(vec2 sph, float mipLevel) {
return sampleOctahedral(fromSpherical(sph), mipLevel);
}
#endif
vec3 getDirectionCubemap() {
vec2 st = vUv0 * 2.0 - 1.0;
float face = targetFace();
vec3 vec;
if (face == 0.0) {
vec = vec3(1, -st.y, -st.x);
} else if (face == 1.0) {
vec = vec3(-1, -st.y, st.x);
} else if (face == 2.0) {
vec = vec3(st.x, 1, st.y);
} else if (face == 3.0) {
vec = vec3(st.x, -1, -st.y);
} else if (face == 4.0) {
vec = vec3(st.x, -st.y, 1);
} else {
vec = vec3(-st.x, -st.y, -1);
}
return normalize(modifySeams(vec, 1.0));
}
mat3 matrixFromVector(vec3 n) {
float a = 1.0 / (1.0 + n.z);
float b = -n.x * n.y * a;
vec3 b1 = vec3(1.0 - n.x * n.x * a, b, -n.x);
vec3 b2 = vec3(b, 1.0 - n.y * n.y * a, -n.y);
return mat3(b1, b2, n);
}
mat3 matrixFromVectorSlow(vec3 n) {
vec3 up = (1.0 - abs(n.y) <= 0.0000001) ? vec3(0.0, 0.0, n.y > 0.0 ? 1.0 : -1.0) : vec3(0.0, 1.0, 0.0);
vec3 x = normalize(cross(up, n));
vec3 y = cross(n, x);
return mat3(x, y, n);
}
vec4 reproject() {
if ({NUM_SAMPLES} <= 1) {
return {ENCODE_FUNC}({DECODE_FUNC}({SOURCE_FUNC}({TARGET_FUNC}())));
} else {
vec3 t = {TARGET_FUNC}();
vec3 tu = dFdx(t);
vec3 tv = dFdy(t);
vec3 result = vec3(0.0);
for (float u = 0.0; u < {NUM_SAMPLES_SQRT}; ++u) {
for (float v = 0.0; v < {NUM_SAMPLES_SQRT}; ++v) {
result += {DECODE_FUNC}({SOURCE_FUNC}(normalize(t +
tu * (u / {NUM_SAMPLES_SQRT} - 0.5) +
tv * (v / {NUM_SAMPLES_SQRT} - 0.5))));
}
}
return {ENCODE_FUNC}(result / ({NUM_SAMPLES_SQRT} * {NUM_SAMPLES_SQRT}));
}
}
vec4 unpackFloat = vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0);
#ifdef USE_SAMPLES_TEX
void unpackSample(int i, out vec3 L, out float mipLevel) {
float u = (float(i * 4) + 0.5) * samplesTexInverseSize.x;
float v = (floor(u) + 0.5) * samplesTexInverseSize.y;
vec4 raw;
raw.x = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;
raw.y = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;
raw.z = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;
raw.w = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat);
L.xyz = raw.xyz * 2.0 - 1.0;
mipLevel = raw.w * 8.0;
}
vec4 prefilterSamples() {
mat3 vecSpace = matrixFromVectorSlow({TARGET_FUNC}());
vec3 L;
float mipLevel;
vec3 result = vec3(0.0);
float totalWeight = 0.0;
for (int i = 0; i < {NUM_SAMPLES}; ++i) {
unpackSample(i, L, mipLevel);
result += {DECODE_FUNC}({SOURCE_FUNC}(vecSpace * L, mipLevel)) * L.z;
totalWeight += L.z;
}
return {ENCODE_FUNC}(result / totalWeight);
}
vec4 prefilterSamplesUnweighted() {
mat3 vecSpace = matrixFromVectorSlow({TARGET_FUNC}());
vec3 L;
float mipLevel;
vec3 result = vec3(0.0);
float totalWeight = 0.0;
for (int i = 0; i < {NUM_SAMPLES}; ++i) {
unpackSample(i, L, mipLevel);
result += {DECODE_FUNC}({SOURCE_FUNC}(vecSpace * L, mipLevel));
}
return {ENCODE_FUNC}(result / float({NUM_SAMPLES}));
}
#endif
void main(void) {
gl_FragColor = {PROCESS_FUNC}();
}
`;var b3=`
attribute vec2 vertex_position;
uniform vec4 uvMod;
varying vec2 vUv0;
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);
}
`;var D3=`
uniform highp sampler2D uSceneDepthMap;
#ifndef SCREENSIZE
#define SCREENSIZE
uniform vec4 uScreenSize;
#endif
#ifndef VIEWMATRIX
#define VIEWMATRIX
uniform mat4 matrix_view;
#endif
#ifndef LINEARIZE_DEPTH
#define LINEARIZE_DEPTH
#ifndef CAMERAPLANES
#define CAMERAPLANES
uniform vec4 camera_params;
#endif
float linearizeDepth(float z) {
if (camera_params.w == 0.0)
return (camera_params.z * camera_params.y) / (camera_params.y + z * (camera_params.z - camera_params.y));
else
return camera_params.z + z * (camera_params.y - camera_params.z);
}
#endif
float delinearizeDepth(float linearDepth) {
if (camera_params.w == 0.0) {
return (camera_params.y * (camera_params.z - linearDepth)) / (linearDepth * (camera_params.z - camera_params.y));
} else {
return (linearDepth - camera_params.z) / (camera_params.y - camera_params.z);
}
}
float getLinearScreenDepth(vec2 uv) {
#ifdef SCENE_DEPTHMAP_LINEAR
#ifdef SCENE_DEPTHMAP_FLOAT
return texture2D(uSceneDepthMap, uv).r;
#else
ivec2 textureSize = textureSize(uSceneDepthMap, 0);
ivec2 texel = ivec2(uv * vec2(textureSize));
vec4 data = texelFetch(uSceneDepthMap, texel, 0);
uint intBits =
(uint(data.r * 255.0) << 24u) |
(uint(data.g * 255.0) << 16u) |
(uint(data.b * 255.0) << 8u) |
uint(data.a * 255.0);
return uintBitsToFloat(intBits);
#endif
#else
return linearizeDepth(texture2D(uSceneDepthMap, uv).r);
#endif
}
#ifndef VERTEXSHADER
float getLinearScreenDepth() {
vec2 uv = gl_FragCoord.xy * uScreenSize.zw;
return getLinearScreenDepth(uv);
}
#endif
float getLinearDepth(vec3 pos) {
return -(matrix_view * vec4(pos, 1.0)).z;
}
`;var L3=`
int getShadowCascadeIndex(vec4 shadowCascadeDistances, int shadowCascadeCount) {
float depth = 1.0 / gl_FragCoord.w;
vec4 comparisons = step(shadowCascadeDistances, vec4(depth));
int cascadeIndex = int(dot(comparisons, vec4(1.0)));
return min(cascadeIndex, shadowCascadeCount - 1);
}
int ditherShadowCascadeIndex(int cascadeIndex, vec4 shadowCascadeDistances, int shadowCascadeCount, float blendFactor) {
if (cascadeIndex < shadowCascadeCount - 1) {
float currentRangeEnd = shadowCascadeDistances[cascadeIndex];
float transitionStart = blendFactor * currentRangeEnd;
float depth = 1.0 / gl_FragCoord.w;
if (depth > transitionStart) {
float transitionFactor = smoothstep(transitionStart, currentRangeEnd, depth);
float dither = fract(sin(dot(gl_FragCoord.xy, vec2(12.9898, 78.233))) * 43758.5453);
if (dither < transitionFactor) {
cascadeIndex += 1;
}
}
}
return cascadeIndex;
}
vec3 fadeShadow(vec3 shadowCoord, vec4 shadowCascadeDistances) {
float depth = 1.0 / gl_FragCoord.w;
if (depth > shadowCascadeDistances.w) {
shadowCoord.z = -9999999.0;
}
return shadowCoord;
}
`;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);
}
float chebyshevUpperBound(vec2 moments, float mean, float minVariance, float lightBleedingReduction) {
float variance = moments.y - (moments.x * moments.x);
variance = max(variance, minVariance);
float d = mean - moments.x;
float pMax = variance / (variance + (d * d));
pMax = reduceLightBleeding(pMax, lightBleedingReduction);
return (mean <= moments.x ? 1.0 : pMax);
}
float calculateEVSM(vec3 moments, float Z, float vsmBias, float exponent) {
Z = 2.0 * Z - 1.0;
float warpedDepth = exp(exponent * Z);
moments.xy += vec2(warpedDepth, warpedDepth*warpedDepth) * (1.0 - moments.z);
float VSMBias = vsmBias;
float depthScale = VSMBias * exponent * warpedDepth;
float minVariance1 = depthScale * depthScale;
return chebyshevUpperBound(moments.xy, warpedDepth, minVariance1, 0.1);
}
float VSM16(TEXTURE_ACCEPT(tex), vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {
vec3 moments = texture2DLod(tex, texCoords, 0.0).xyz;
return calculateEVSM(moments, Z, vsmBias, exponent);
}
float getShadowVSM16(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent) {
return VSM16(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent);
}
float getShadowSpotVSM16(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {
return VSM16(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, length(lightDir) * shadowParams.w + shadowParams.z, shadowParams.y, exponent);
}
float VSM32(TEXTURE_ACCEPT(tex), vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {
#ifdef CAPS_TEXTURE_FLOAT_FILTERABLE
vec3 moments = texture2DLod(tex, texCoords, 0.0).xyz;
#else
float pixelSize = 1.0 / resolution;
texCoords -= vec2(pixelSize);
vec3 s00 = texture2DLod(tex, texCoords, 0.0).xyz;
vec3 s10 = texture2DLod(tex, texCoords + vec2(pixelSize, 0), 0.0).xyz;
vec3 s01 = texture2DLod(tex, texCoords + vec2(0, pixelSize), 0.0).xyz;
vec3 s11 = texture2DLod(tex, texCoords + vec2(pixelSize), 0.0).xyz;
vec2 fr = fract(texCoords * resolution);
vec3 h0 = mix(s00, s10, fr.x);
vec3 h1 = mix(s01, s11, fr.x);
vec3 moments = mix(h0, h1, fr.y);
#endif
return calculateEVSM(moments, Z, vsmBias, exponent);
}
float getShadowVSM32(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent) {
return VSM32(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent);
}
float getShadowSpotVSM32(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) {
float Z = length(lightDir) * shadowParams.w + shadowParams.z;
return VSM32(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, Z, shadowParams.y, exponent);
}
`;var O3=`
float getShadowPCF1x1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {
return textureShadow(shadowMap, shadowCoord);
}
float getShadowSpotPCF1x1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {
return textureShadow(shadowMap, shadowCoord);
}
#ifndef WEBGPU
float getShadowOmniPCF1x1(samplerCubeShadow shadowMap, vec3 shadowCoord, vec4 shadowParams, vec3 lightDir) {
float shadowZ = length(lightDir) * shadowParams.w + shadowParams.z;
return texture(shadowMap, vec4(lightDir, shadowZ));
}
#endif
`;var F3=`
float _getShadowPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec3 shadowParams) {
float z = shadowCoord.z;
vec2 uv = shadowCoord.xy * shadowParams.x;
float shadowMapSizeInv = 1.0 / shadowParams.x;
vec2 base_uv = floor(uv + 0.5);
float s = (uv.x + 0.5 - base_uv.x);
float t = (uv.y + 0.5 - base_uv.y);
base_uv -= vec2(0.5);
base_uv *= shadowMapSizeInv;
float sum = 0.0;
float uw0 = (3.0 - 2.0 * s);
float uw1 = (1.0 + 2.0 * s);
float u0 = (2.0 - s) / uw0 - 1.0;
float u1 = s / uw1 + 1.0;
float vw0 = (3.0 - 2.0 * t);
float vw1 = (1.0 + 2.0 * t);
float v0 = (2.0 - t) / vw0 - 1.0;
float v1 = t / vw1 + 1.0;
u0 = u0 * shadowMapSizeInv + base_uv.x;
v0 = v0 * shadowMapSizeInv + base_uv.y;
u1 = u1 * shadowMapSizeInv + base_uv.x;
v1 = v1 * shadowMapSizeInv + base_uv.y;
sum += uw0 * vw0 * textureShadow(shadowMap, vec3(u0, v0, z));
sum += uw1 * vw0 * textureShadow(shadowMap, vec3(u1, v0, z));
sum += uw0 * vw1 * textureShadow(shadowMap, vec3(u0, v1, z));
sum += uw1 * vw1 * textureShadow(shadowMap, vec3(u1, v1, z));
sum *= 1.0f / 16.0;
return sum;
}
float getShadowPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {
return _getShadowPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);
}
float getShadowSpotPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {
return _getShadowPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);
}
#ifndef WEBGPU
float getShadowOmniPCF3x3(samplerCubeShadow shadowMap, vec4 shadowParams, vec3 dir) {
float shadowZ = length(dir) * shadowParams.w + shadowParams.z;
float z = 1.0 / float(textureSize(shadowMap, 0));
vec3 tc = normalize(dir);
mediump vec4 shadows;
shadows.x = texture(shadowMap, vec4(tc + vec3( z, z, z), shadowZ));
shadows.y = texture(shadowMap, vec4(tc + vec3(-z,-z, z), shadowZ));
shadows.z = texture(shadowMap, vec4(tc + vec3(-z, z,-z), shadowZ));
shadows.w = texture(shadowMap, vec4(tc + vec3( z,-z,-z), shadowZ));
return dot(shadows, vec4(0.25));
}
float getShadowOmniPCF3x3(samplerCubeShadow shadowMap, vec3 shadowCoord, vec4 shadowParams, vec3 lightDir) {
return getShadowOmniPCF3x3(shadowMap, shadowParams, lightDir);
}
#endif
`;var N3=`
float _getShadowPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec3 shadowParams) {
float z = shadowCoord.z;
vec2 uv = shadowCoord.xy * shadowParams.x;
float shadowMapSizeInv = 1.0 / shadowParams.x;
vec2 base_uv = floor(uv + 0.5);
float s = (uv.x + 0.5 - base_uv.x);
float t = (uv.y + 0.5 - base_uv.y);
base_uv -= vec2(0.5);
base_uv *= shadowMapSizeInv;
float uw0 = (4.0 - 3.0 * s);
float uw1 = 7.0;
float uw2 = (1.0 + 3.0 * s);
float u0 = (3.0 - 2.0 * s) / uw0 - 2.0;
float u1 = (3.0 + s) / uw1;
float u2 = s / uw2 + 2.0;
float vw0 = (4.0 - 3.0 * t);
float vw1 = 7.0;
float vw2 = (1.0 + 3.0 * t);
float v0 = (3.0 - 2.0 * t) / vw0 - 2.0;
float v1 = (3.0 + t) / vw1;
float v2 = t / vw2 + 2.0;
float sum = 0.0;
u0 = u0 * shadowMapSizeInv + base_uv.x;
v0 = v0 * shadowMapSizeInv + base_uv.y;
u1 = u1 * shadowMapSizeInv + base_uv.x;
v1 = v1 * shadowMapSizeInv + base_uv.y;
u2 = u2 * shadowMapSizeInv + base_uv.x;
v2 = v2 * shadowMapSizeInv + base_uv.y;
sum += uw0 * vw0 * textureShadow(shadowMap, vec3(u0, v0, z));
sum += uw1 * vw0 * textureShadow(shadowMap, vec3(u1, v0, z));
sum += uw2 * vw0 * textureShadow(shadowMap, vec3(u2, v0, z));
sum += uw0 * vw1 * textureShadow(shadowMap, vec3(u0, v1, z));
sum += uw1 * vw1 * textureShadow(shadowMap, vec3(u1, v1, z));
sum += uw2 * vw1 * textureShadow(shadowMap, vec3(u2, v1, z));
sum += uw0 * vw2 * textureShadow(shadowMap, vec3(u0, v2, z));
sum += uw1 * vw2 * textureShadow(shadowMap, vec3(u1, v2, z));
sum += uw2 * vw2 * textureShadow(shadowMap, vec3(u2, v2, z));
sum *= 1.0f / 144.0;
sum = saturate(sum);
return sum;
}
float getShadowPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {
return _getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);
}
float getShadowSpotPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) {
return _getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz);
}
`;var B3=`
#define PCSS_SAMPLE_COUNT 16
uniform float pcssDiskSamples[PCSS_SAMPLE_COUNT];
uniform float pcssSphereSamples[PCSS_SAMPLE_COUNT];
vec2 vogelDisk(int sampleIndex, float count, float phi, float r) {
const float GoldenAngle = 2.4;
float theta = float(sampleIndex) * GoldenAngle + phi;
float sine = sin(theta);
float cosine = cos(theta);
return vec2(r * cosine, r * sine);
}
vec3 vogelSphere(int sampleIndex, float count, float phi, float r) {
const float GoldenAngle = 2.4;
float theta = float(sampleIndex) * GoldenAngle + phi;
float weight = float(sampleIndex) / count;
return vec3(cos(theta) * r, weight, sin(theta) * r);
}
float noise(vec2 screenPos) {
const float PHI = 1.61803398874989484820459;
return fract(sin(dot(screenPos * PHI, screenPos)) * screenPos.x);
}
float viewSpaceDepth(float depth, mat4 invProjection) {
float z = depth * 2.0 - 1.0;
vec4 clipSpace = vec4(0.0, 0.0, z, 1.0);
vec4 viewSpace = invProjection * clipSpace;
return viewSpace.z;
}
float PCSSBlockerDistance(TEXTURE_ACCEPT(shadowMap), vec2 sampleCoords[PCSS_SAMPLE_COUNT], vec2 shadowCoords, vec2 searchSize, float z, vec4 cameraParams) {
float blockers = 0.0;
float averageBlocker = 0.0;
for (int i = 0; i < PCSS_SAMPLE_COUNT; i++) {
vec2 offset = sampleCoords[i] * searchSize;
vec2 sampleUV = shadowCoords + offset;
float blocker = texture2DLod(shadowMap, sampleUV, 0.0).r;
float isBlocking = step(blocker, z);
blockers += isBlocking;
averageBlocker += blocker * isBlocking;
}
if (blockers > 0.0)
return averageBlocker / blockers;
return -1.0;
}
float PCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoords, vec4 cameraParams, vec2 shadowSearchArea) {
float receiverDepth = linearizeDepthWithParams(shadowCoords.z, cameraParams);
vec2 samplePoints[PCSS_SAMPLE_COUNT];
const float PI = 3.141592653589793;
float noise = noise( gl_FragCoord.xy ) * 2.0 * PI;
for (int i = 0; i < PCSS_SAMPLE_COUNT; i++) {
float pcssPresample = pcssDiskSamples[i];
samplePoints[i] = vogelDisk(i, float(PCSS_SAMPLE_COUNT), noise, pcssPresample);
}
float averageBlocker = PCSSBlockerDistance(TEXTURE_PASS(shadowMap), samplePoints, shadowCoords.xy, shadowSearchArea, receiverDepth, cameraParams);
if (averageBlocker == -1.0) {
return 1.0;
} else {
float depthDifference = (receiverDepth - averageBlocker) / 3.0;
vec2 filterRadius = depthDifference * shadowSearchArea;
float shadow = 0.0;
for (int i = 0; i < PCSS_SAMPLE_COUNT; i ++)
{
vec2 sampleUV = samplePoints[i] * filterRadius;
sampleUV = shadowCoords.xy + sampleUV;
float depth = texture2DLod(shadowMap, sampleUV, 0.0).r;
shadow += step(receiverDepth, depth);
}
return shadow / float(PCSS_SAMPLE_COUNT);
}
}
#ifndef WEBGPU
float PCSSCubeBlockerDistance(samplerCube shadowMap, vec3 lightDirNorm, vec3 samplePoints[PCSS_SAMPLE_COUNT], float z, float shadowSearchArea) {
float blockers = 0.0;
float averageBlocker = 0.0;
for (int i = 0; i < PCSS_SAMPLE_COUNT; i++) {
vec3 sampleDir = lightDirNorm + samplePoints[i] * shadowSearchArea;
sampleDir = normalize(sampleDir);
float blocker = textureCubeLod(shadowMap, sampleDir, 0.0).r;
float isBlocking = step(blocker, z);
blockers += isBlocking;
averageBlocker += blocker * isBlocking;
}
if (blockers > 0.0)
return averageBlocker / blockers;
return -1.0;
}
float PCSSCube(samplerCube shadowMap, vec4 shadowParams, vec3 shadowCoords, vec4 cameraParams, float shadowSearchArea, vec3 lightDir) {
vec3 samplePoints[PCSS_SAMPLE_COUNT];
const float PI = 3.141592653589793;
float noise = noise( gl_FragCoord.xy ) * 2.0 * PI;
for (int i = 0; i < PCSS_SAMPLE_COUNT; i++) {
float r = pcssSphereSamples[i];
samplePoints[i] = vogelSphere(i, float(PCSS_SAMPLE_COUNT), noise, r);
}
float receiverDepth = length(lightDir) * shadowParams.w + shadowParams.z;
vec3 lightDirNorm = normalize(lightDir);
float averageBlocker = PCSSCubeBlockerDistance(shadowMap, lightDirNorm, samplePoints, receiverDepth, shadowSearchArea);
if (averageBlocker == -1.0) {
return 1.0;
} else {
float filterRadius = ((receiverDepth - averageBlocker) / averageBlocker) * shadowSearchArea;
float shadow = 0.0;
for (int i = 0; i < PCSS_SAMPLE_COUNT; i++)
{
vec3 offset = samplePoints[i] * filterRadius;
vec3 sampleDir = lightDirNorm + offset;
sampleDir = normalize(sampleDir);
float depth = textureCubeLod(shadowMap, sampleDir, 0.0).r;
shadow += step(receiverDepth, depth);
}
return shadow / float(PCSS_SAMPLE_COUNT);
}
}
float getShadowOmniPCSS(samplerCube shadowMap, vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec2 shadowSearchArea, vec3 lightDir) {
return PCSSCube(shadowMap, shadowParams, shadowCoord, cameraParams, shadowSearchArea.x, lightDir);
}
#endif
float getShadowSpotPCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec2 shadowSearchArea, vec3 lightDir) {
return PCSS(TEXTURE_PASS(shadowMap), shadowCoord, cameraParams, shadowSearchArea);
}
`;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;
highp float dt = dot(uv.xy, vec2(a, b)), sn = mod(dt, PI);
return fract(sin(sn) * c);
}
struct VogelDiskData {
float invNumSamples;
float initialAngle;
float currentPointId;
};
void prepareDiskConstants(out VogelDiskData data, int sampleCount, float randomSeed) {
const float pi2 = 6.28318530718;
data.invNumSamples = 1.0 / float(sampleCount);
data.initialAngle = randomSeed * pi2;
data.currentPointId = 0.0;
}
vec2 generateDiskSample(inout VogelDiskData data) {
const float GOLDEN_ANGLE = 2.399963;
float r = sqrt((data.currentPointId + 0.5) * data.invNumSamples);
float theta = data.currentPointId * GOLDEN_ANGLE + data.initialAngle;
vec2 offset = vec2(cos(theta), sin(theta)) * pow(r, 1.33);
data.currentPointId += 1.0;
return offset;
}
void PCSSFindBlocker(TEXTURE_ACCEPT(shadowMap), out float avgBlockerDepth, out int numBlockers,
vec2 shadowCoords, float z, int shadowBlockerSamples, float penumbraSize, float invShadowMapSize, float randomSeed) {
VogelDiskData diskData;
prepareDiskConstants(diskData, shadowBlockerSamples, randomSeed);
float searchWidth = penumbraSize * invShadowMapSize;
float blockerSum = 0.0;
numBlockers = 0;
for( int i = 0; i < shadowBlockerSamples; ++i ) {
vec2 diskUV = generateDiskSample(diskData);
vec2 sampleUV = shadowCoords + diskUV * searchWidth;
float shadowMapDepth = texture2DLod(shadowMap, sampleUV, 0.0).r;
if ( shadowMapDepth < z ) {
blockerSum += shadowMapDepth;
numBlockers++;
}
}
avgBlockerDepth = blockerSum / float(numBlockers);
}
float PCSSFilter(TEXTURE_ACCEPT(shadowMap), vec2 uv, float receiverDepth, int shadowSamples, float filterRadius, float randomSeed) {
VogelDiskData diskData;
prepareDiskConstants(diskData, shadowSamples, randomSeed);
float sum = 0.0;
for (int i = 0; i < shadowSamples; i++) {
vec2 offsetUV = generateDiskSample(diskData) * filterRadius;
float depth = texture2DLod(shadowMap, uv + offsetUV, 0.0).r;
sum += step(receiverDepth, depth);
}
return sum / float(shadowSamples);
}
float getPenumbra(float dblocker, float dreceiver, float penumbraSize, float penumbraFalloff) {
float dist = dreceiver - dblocker;
float penumbra = 1.0 - pow(1.0 - dist, penumbraFalloff);
return penumbra * penumbraSize;
}
float PCSSDirectional(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoords, vec4 cameraParams, vec4 softShadowParams) {
float receiverDepth = shadowCoords.z;
float randomSeed = fractSinRand(gl_FragCoord.xy);
int shadowSamples = int(softShadowParams.x);
int shadowBlockerSamples = int(softShadowParams.y);
float penumbraSize = softShadowParams.z;
float penumbraFalloff = softShadowParams.w;
int shadowMapSize = textureSize(shadowMap, 0).x;
float invShadowMapSize = 1.0 / float(shadowMapSize);
invShadowMapSize *= float(shadowMapSize) / 2048.0;
float penumbra;
if (shadowBlockerSamples > 0) {
float avgBlockerDepth = 0.0;
int numBlockers = 0;
PCSSFindBlocker(TEXTURE_PASS(shadowMap), avgBlockerDepth, numBlockers, shadowCoords.xy, receiverDepth, shadowBlockerSamples, penumbraSize, invShadowMapSize, randomSeed);
if (numBlockers < 1)
return 1.0f;
penumbra = getPenumbra(avgBlockerDepth, shadowCoords.z, penumbraSize, penumbraFalloff);
} else {
penumbra = penumbraSize;
}
float filterRadius = penumbra * invShadowMapSize;
return PCSSFilter(TEXTURE_PASS(shadowMap), shadowCoords.xy, receiverDepth, shadowSamples, filterRadius, randomSeed);
}
float getShadowPCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec4 softShadowParams, vec3 lightDir) {
return PCSSDirectional(TEXTURE_PASS(shadowMap), shadowCoord, cameraParams, softShadowParams);
}
`;var k3=`
attribute float vertex_boneIndices;
uniform highp sampler2D texture_poseMap;
mat4 getBoneMatrix(const in float indexFloat) {
int width = textureSize(texture_poseMap, 0).x;
int index = int(indexFloat + 0.5) * 3;
int iy = index / width;
int ix = index % width;
vec4 v1 = texelFetch(texture_poseMap, ivec2(ix + 0, iy), 0);
vec4 v2 = texelFetch(texture_poseMap, ivec2(ix + 1, iy), 0);
vec4 v3 = texelFetch(texture_poseMap, ivec2(ix + 2, iy), 0);
return mat4(
v1.x, v2.x, v3.x, 0,
v1.y, v2.y, v3.y, 0,
v1.z, v2.z, v3.z, 0,
v1.w, v2.w, v3.w, 1
);
}
`;var z3=`
attribute vec4 vertex_boneWeights;
attribute vec4 vertex_boneIndices;
uniform highp sampler2D texture_poseMap;
void getBoneMatrix(const in int width, const in int index, out vec4 v1, out vec4 v2, out vec4 v3) {
int v = index / width;
int u = index % width;
v1 = texelFetch(texture_poseMap, ivec2(u + 0, v), 0);
v2 = texelFetch(texture_poseMap, ivec2(u + 1, v), 0);
v3 = texelFetch(texture_poseMap, ivec2(u + 2, v), 0);
}
mat4 getSkinMatrix(const in vec4 indicesFloat, const in vec4 weights) {
int width = textureSize(texture_poseMap, 0).x;
ivec4 indices = ivec4(indicesFloat + 0.5) * 3;
vec4 a1, a2, a3;
getBoneMatrix(width, indices.x, a1, a2, a3);
vec4 b1, b2, b3;
getBoneMatrix(width, indices.y, b1, b2, b3);
vec4 c1, c2, c3;
getBoneMatrix(width, indices.z, c1, c2, c3);
vec4 d1, d2, d3;
getBoneMatrix(width, indices.w, d1, d2, d3);
vec4 v1 = a1 * weights.x + b1 * weights.y + c1 * weights.z + d1 * weights.w;
vec4 v2 = a2 * weights.x + b2 * weights.y + c2 * weights.z + d2 * weights.w;
vec4 v3 = a3 * weights.x + b3 * weights.y + c3 * weights.z + d3 * weights.w;
float one = dot(weights, vec4(1.0));
return mat4(
v1.x, v2.x, v3.x, 0,
v1.y, v2.y, v3.y, 0,
v1.z, v2.z, v3.z, 0,
v1.w, v2.w, v3.w, one
);
}
`;var G3=`
#define LIT_SKYBOX_INTENSITY
#include "envProcPS"
#include "gammaPS"
#include "tonemappingPS"
#ifdef PREPASS_PASS
varying float vLinearDepth;
#include "floatAsUintPS"
#endif
varying vec3 vViewDir;
uniform float skyboxHighlightMultiplier;
#if defined(SKY_FISHEYE) && !defined(SKYMESH)
uniform float fisheye_k;
uniform float fisheye_invK;
uniform float fisheye_projMat00;
uniform float fisheye_projMat11;
uniform mat4 matrix_view;
uniform mat3 cubeMapRotationMatrix;
varying vec3 vClipXYW;
#endif
#ifdef SKY_CUBEMAP
uniform samplerCube texture_cubeMap;
#ifdef SKYMESH
varying vec3 vWorldPos;
uniform mat3 cubeMapRotationMatrix;
uniform vec3 projectedSkydomeCenter;
#endif
#else
#include "sphericalPS"
#include "envAtlasPS"
uniform sampler2D texture_envAtlas;
uniform float mipLevel;
#endif
void main(void) {
#ifdef PREPASS_PASS
gl_FragColor = float2vec4(vLinearDepth);
#else
#if defined(SKY_FISHEYE) && !defined(SKYMESH)
vec2 ndc = vClipXYW.xy / vClipXYW.z;
float px = ndc.x / fisheye_projMat00;
float py = ndc.y / fisheye_projMat11;
float r = sqrt(px * px + py * py);
float theta = fisheye_k * atan(r * fisheye_invK);
float sinT = sin(theta);
float cosT = cos(theta);
vec3 camDir = (r > 1e-6)
? vec3(px / r * sinT, py / r * sinT, -cosT)
: vec3(0.0, 0.0, -1.0);
vec3 dir = transpose(mat3(matrix_view)) * camDir;
dir = dir * cubeMapRotationMatrix;
#elif defined(SKY_CUBEMAP) && defined(SKYMESH)
vec3 envDir = normalize(vWorldPos - projectedSkydomeCenter);
vec3 dir = envDir * cubeMapRotationMatrix;
#else
vec3 dir = vViewDir;
#endif
#ifdef SKY_CUBEMAP
dir.x *= -1.0;
vec3 linear = {SKYBOX_DECODE_FNC}(textureCube(texture_cubeMap, dir));
#else
dir *= vec3(-1.0, 1.0, 1.0);
vec2 uv = toSphericalUv(normalize(dir));
vec3 linear = {SKYBOX_DECODE_FNC}(texture2D(texture_envAtlas, mapRoughnessUv(uv, mipLevel)));
#endif
if (any(greaterThanEqual(linear, vec3(64.0)))) {
linear *= skyboxHighlightMultiplier;
}
gl_FragColor = vec4(gammaCorrectOutput(toneMap(processEnvironment(linear))), 1.0);
#endif
}
`;var V3=`
attribute vec4 aPosition;
uniform mat4 matrix_view;
uniform mat4 matrix_projectionSkybox;
uniform mat3 cubeMapRotationMatrix;
varying vec3 vViewDir;
#ifdef SKY_FISHEYE
varying vec3 vClipXYW;
#endif
#ifdef PREPASS_PASS
varying float vLinearDepth;
#endif
#ifdef SKYMESH
uniform mat4 matrix_model;
varying vec3 vWorldPos;
#endif
void main(void) {
mat4 view = matrix_view;
#ifdef SKYMESH
vec4 worldPos = matrix_model * aPosition;
vWorldPos = worldPos.xyz;
gl_Position = matrix_projectionSkybox * (view * worldPos);
#ifdef PREPASS_PASS
vLinearDepth = -(matrix_view * vec4(vWorldPos, 1.0)).z;
#endif
#else
view[3][0] = view[3][1] = view[3][2] = 0.0;
vViewDir = aPosition.xyz * cubeMapRotationMatrix;
#ifdef SKY_FISHEYE
vec4 viewPos = view * aPosition;
gl_Position = vec4(viewPos.xy, 0.0, -viewPos.z);
vClipXYW = vec3(gl_Position.xy, gl_Position.w);
#else
gl_Position = matrix_projectionSkybox * (view * aPosition);
#endif
#ifdef PREPASS_PASS
vLinearDepth = -gl_Position.w;
#endif
#endif
gl_Position.z = gl_Position.w - 1.0e-7;
}
`;var H3=`
#ifdef STD_SPECULAR_CONSTANT
uniform vec3 material_specular;
#endif
void getSpecularity() {
vec3 specularColor = vec3(1,1,1);
#ifdef STD_SPECULAR_CONSTANT
specularColor *= material_specular;
#endif
#ifdef STD_SPECULAR_TEXTURE
specularColor *= {STD_SPECULAR_TEXTURE_DECODE}(texture2DBias({STD_SPECULAR_TEXTURE_NAME}, {STD_SPECULAR_TEXTURE_UV}, textureBias)).{STD_SPECULAR_TEXTURE_CHANNEL};
#endif
#ifdef STD_SPECULAR_VERTEX
specularColor *= saturate(vVertexColor.{STD_SPECULAR_VERTEX_CHANNEL});
#endif
dSpecularity = specularColor;
}
`;var W3=`
vec2 toSpherical(vec3 dir) {
return vec2(dir.xz == vec2(0.0) ? 0.0 : atan(dir.x, dir.z), asin(dir.y));
}
vec2 toSphericalUv(vec3 dir) {
const float PI = 3.141592653589793;
vec2 uv = toSpherical(dir) / vec2(PI * 2.0, PI) + 0.5;
return vec2(uv.x, 1.0 - uv.y);
}
`;var X3=`
#ifdef STD_SPECULARITYFACTOR_CONSTANT
uniform float material_specularityFactor;
#endif
void getSpecularityFactor() {
float specularityFactor = 1.0;
#ifdef STD_SPECULARITYFACTOR_CONSTANT
specularityFactor *= material_specularityFactor;
#endif
#ifdef STD_SPECULARITYFACTOR_TEXTURE
specularityFactor *= texture2DBias({STD_SPECULARITYFACTOR_TEXTURE_NAME}, {STD_SPECULARITYFACTOR_TEXTURE_UV}, textureBias).{STD_SPECULARITYFACTOR_TEXTURE_CHANNEL};
#endif
#ifdef STD_SPECULARITYFACTOR_VERTEX
specularityFactor *= saturate(vVertexColor.{STD_SPECULARITYFACTOR_VERTEX_CHANNEL});
#endif
dSpecularityFactor = specularityFactor;
}
`;var Y3=`
float getSpotEffect(vec3 lightSpotDir, float lightInnerConeAngle, float lightOuterConeAngle, vec3 lightDirNorm) {
float cosAngle = dot(lightDirNorm, lightSpotDir);
return smoothstep(lightOuterConeAngle, lightInnerConeAngle, cosAngle);
}
`;var K3=`
nineSlicedUv = vec2(vUv0.x, 1.0 - vUv0.y);
`;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);
vec2 clampedUv = mix(innerOffset.xy * 0.5, vec2(1.0) - innerOffset.zw * 0.5, fract((vTiledUv - tileSize) * tileScale));
clampedUv = clampedUv * atlasRect.zw + atlasRect.xy;
nineSlicedUv = vUv0 * tileMask + clampedUv * (vec2(1.0) - tileMask);
nineSlicedUv.y = 1.0 - nineSlicedUv.y;
`;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
uniform sampler2D texture_opacityMap;
#endif
#endif
#ifdef FORWARD_PASS
vec3 dAlbedo;
vec3 dNormalW;
vec3 dSpecularity = vec3(0.0);
float dGlossiness = 0.0;
#ifdef LIT_REFRACTION
float dTransmission;
float dThickness;
#endif
#ifdef LIT_SCENE_COLOR
uniform sampler2D uSceneColorMap;
#endif
#ifdef LIT_SCREEN_SIZE
uniform vec4 uScreenSize;
#endif
#ifdef LIT_TRANSFORMS
uniform mat4 matrix_viewProjection;
uniform mat4 matrix_model;
#endif
#ifdef STD_HEIGHT_MAP
vec2 dUvOffset;
#ifdef STD_HEIGHT_TEXTURE_ALLOCATE
uniform sampler2D texture_heightMap;
#endif
#endif
#ifdef STD_DIFFUSE_TEXTURE_ALLOCATE
uniform sampler2D texture_diffuseMap;
#endif
#ifdef STD_DIFFUSEDETAIL_TEXTURE_ALLOCATE
uniform sampler2D texture_diffuseDetailMap;
#endif
#ifdef STD_NORMAL_TEXTURE_ALLOCATE
uniform sampler2D texture_normalMap;
#endif
#ifdef STD_NORMALDETAIL_TEXTURE_ALLOCATE
uniform sampler2D texture_normalDetailMap;
#endif
#ifdef STD_THICKNESS_TEXTURE_ALLOCATE
uniform sampler2D texture_thicknessMap;
#endif
#ifdef STD_REFRACTION_TEXTURE_ALLOCATE
uniform sampler2D texture_refractionMap;
#endif
#ifdef LIT_IRIDESCENCE
float dIridescence;
float dIridescenceThickness;
#ifdef STD_IRIDESCENCE_THICKNESS_TEXTURE_ALLOCATE
uniform sampler2D texture_iridescenceThicknessMap;
#endif
#ifdef STD_IRIDESCENCE_TEXTURE_ALLOCATE
uniform sampler2D texture_iridescenceMap;
#endif
#endif
#ifdef LIT_CLEARCOAT
float ccSpecularity;
float ccGlossiness;
vec3 ccNormalW;
#endif
#ifdef LIT_GGX_SPECULAR
float dAnisotropy;
vec2 dAnisotropyRotation;
#endif
#ifdef LIT_SPECULAR_OR_REFLECTION
#ifdef LIT_SHEEN
vec3 sSpecularity;
float sGlossiness;
#ifdef STD_SHEEN_TEXTURE_ALLOCATE
uniform sampler2D texture_sheenMap;
#endif
#ifdef STD_SHEENGLOSS_TEXTURE_ALLOCATE
uniform sampler2D texture_sheenGlossMap;
#endif
#endif
#ifdef LIT_METALNESS
float dMetalness;
float dIor;
#ifdef STD_METALNESS_TEXTURE_ALLOCATE
uniform sampler2D texture_metalnessMap;
#endif
#endif
#ifdef LIT_SPECULARITY_FACTOR
float dSpecularityFactor;
#ifdef STD_SPECULARITYFACTOR_TEXTURE_ALLOCATE
uniform sampler2D texture_specularityFactorMap;
#endif
#endif
#ifdef STD_SPECULAR_COLOR
#ifdef STD_SPECULAR_TEXTURE_ALLOCATE
uniform sampler2D texture_specularMap;
#endif
#endif
#ifdef STD_GLOSS_TEXTURE_ALLOCATE
uniform sampler2D texture_glossMap;
#endif
#endif
#ifdef STD_AO
float dAo;
#ifdef STD_AO_TEXTURE_ALLOCATE
uniform sampler2D texture_aoMap;
#endif
#ifdef STD_AODETAIL_TEXTURE_ALLOCATE
uniform sampler2D texture_aoDetailMap;
#endif
#endif
vec3 dEmission;
#ifdef STD_EMISSIVE_TEXTURE_ALLOCATE
uniform sampler2D texture_emissiveMap;
#endif
#ifdef LIT_CLEARCOAT
#ifdef STD_CLEARCOAT_TEXTURE_ALLOCATE
uniform sampler2D texture_clearCoatMap;
#endif
#ifdef STD_CLEARCOATGLOSS_TEXTURE_ALLOCATE
uniform sampler2D texture_clearCoatGlossMap;
#endif
#ifdef STD_CLEARCOATNORMAL_TEXTURE_ALLOCATE
uniform sampler2D texture_clearCoatNormalMap;
#endif
#endif
#ifdef LIT_GGX_SPECULAR
#ifdef STD_ANISOTROPY_TEXTURE_ALLOCATE
uniform sampler2D texture_anisotropyMap;
#endif
#endif
#if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR)
vec3 dLightmap;
#ifdef STD_LIGHT_TEXTURE_ALLOCATE
uniform sampler2D texture_lightMap;
#endif
#endif
#endif
#include "litShaderCorePS"
`;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)
#include "alphaTestPS"
#endif
#if STD_OPACITY_DITHER != NONE
#include "opacityDitherPS"
#endif
#endif
#ifdef FORWARD_PASS
#ifdef STD_HEIGHT_MAP
#include "parallaxPS"
#endif
#include "diffusePS"
#ifdef LIT_NEEDS_NORMAL
#include "normalMapPS"
#endif
#ifdef LIT_REFRACTION
#include "transmissionPS"
#include "thicknessPS"
#endif
#ifdef LIT_IRIDESCENCE
#include "iridescencePS"
#include "iridescenceThicknessPS"
#endif
#ifdef LIT_SPECULAR_OR_REFLECTION
#ifdef LIT_SHEEN
#include "sheenPS"
#include "sheenGlossPS"
#endif
#ifdef LIT_METALNESS
#include "metalnessPS"
#include "iorPS"
#endif
#ifdef LIT_SPECULARITY_FACTOR
#include "specularityFactorPS"
#endif
#ifdef STD_SPECULAR_COLOR
#include "specularPS"
#else
void getSpecularity() {
dSpecularity = vec3(1);
}
#endif
#include "glossPS"
#endif
#ifdef STD_AO
#include "aoPS"
#endif
#include "emissivePS"
#ifdef LIT_CLEARCOAT
#include "clearCoatPS"
#include "clearCoatGlossPS"
#include "clearCoatNormalPS"
#endif
#if defined(LIT_SPECULAR) && defined(LIT_LIGHTING) && defined(LIT_GGX_SPECULAR)
#include "anisotropyPS"
#endif
#if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR)
#include "lightmapPS"
#endif
#endif
void evaluateFrontend() {
#if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE
getOpacity();
#if defined(LIT_ALPHA_TEST)
alphaTest(dAlpha);
#endif
#if STD_OPACITY_DITHER != NONE
opacityDither(dAlpha * material_alphaDitherScale, 0.0);
#endif
litArgs_opacity = dAlpha;
#endif
#ifdef FORWARD_PASS
#ifdef STD_HEIGHT_MAP
getParallax();
#endif
getAlbedo();
litArgs_albedo = dAlbedo;
#ifdef LIT_NEEDS_NORMAL
getNormal();
litArgs_worldNormal = dNormalW;
#endif
#ifdef LIT_REFRACTION
getRefraction();
litArgs_transmission = dTransmission;
getThickness();
litArgs_thickness = dThickness;
#ifdef LIT_DISPERSION
litArgs_dispersion = material_dispersion;
#endif
#endif
#ifdef LIT_IRIDESCENCE
getIridescence();
getIridescenceThickness();
litArgs_iridescence_intensity = dIridescence;
litArgs_iridescence_thickness = dIridescenceThickness;
#endif
#ifdef LIT_SPECULAR_OR_REFLECTION
#ifdef LIT_SHEEN
getSheen();
litArgs_sheen_specularity = sSpecularity;
getSheenGlossiness();
litArgs_sheen_gloss = sGlossiness;
#endif
#ifdef LIT_METALNESS
getMetalness();
litArgs_metalness = dMetalness;
getIor();
litArgs_ior = dIor;
#endif
#ifdef LIT_SPECULARITY_FACTOR
getSpecularityFactor();
litArgs_specularityFactor = dSpecularityFactor;
#endif
getGlossiness();
getSpecularity();
litArgs_specularity = dSpecularity;
litArgs_gloss = dGlossiness;
#endif
#ifdef STD_AO
getAO();
litArgs_ao = dAo;
#endif
getEmission();
litArgs_emission = dEmission;
#ifdef LIT_CLEARCOAT
getClearCoat();
getClearCoatGlossiness();
getClearCoatNormal();
litArgs_clearcoat_specularity = ccSpecularity;
litArgs_clearcoat_gloss = ccGlossiness;
litArgs_clearcoat_worldNormal = ccNormalW;
#endif
#if defined(LIT_SPECULAR) && defined(LIT_LIGHTING) && defined(LIT_GGX_SPECULAR)
getAnisotropy();
#endif
#if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR)
getLightMap();
litArgs_lightmap = dLightmap;
#ifdef STD_LIGHTMAP_DIR
litArgs_lightmapDir = dLightmapDir;
#endif
#endif
#endif
}
`;var Z3=`
#ifdef LIT_TANGENTS
#define TBN_TANGENTS
#else
#if defined(LIT_USE_NORMALS) || defined(LIT_USE_CLEARCOAT_NORMALS)
#define TBN_DERIVATIVES
#endif
#endif
#if defined(TBN_DERIVATIVES)
uniform float tbnBasis;
#endif
void getTBN(vec3 tangent, vec3 binormal, vec3 normal) {
#ifdef TBN_TANGENTS
dTBN = mat3(normalize(tangent), normalize(binormal), normalize(normal));
#elif defined(TBN_DERIVATIVES)
vec2 uv = {lightingUv};
vec3 dp1 = dFdx( vPositionW );
vec3 dp2 = dFdy( vPositionW );
vec2 duv1 = dFdx( uv );
vec2 duv2 = dFdy( uv );
vec3 dp2perp = cross( dp2, normal );
vec3 dp1perp = cross( normal, dp1 );
vec3 T = dp2perp * duv1.x + dp1perp * duv2.x;
vec3 B = dp2perp * duv1.y + dp1perp * duv2.y;
float denom = max( dot(T,T), dot(B,B) );
float invmax = (denom == 0.0) ? 0.0 : tbnBasis / sqrt( denom );
dTBN = mat3(T * invmax, -B * invmax, normal );
#else
vec3 B = cross(normal, vObjectSpaceUpW);
vec3 T = cross(normal, B);
if (dot(B,B)==0.0)
{
float major=max(max(normal.x, normal.y), normal.z);
if (normal.x == major)
{
B = cross(normal, vec3(0,1,0));
T = cross(normal, B);
}
else if (normal.y == major)
{
B = cross(normal, vec3(0,0,1));
T = cross(normal, B);
}
else if (normal.z == major)
{
B = cross(normal, vec3(1,0,0));
T = cross(normal, B);
}
}
dTBN = mat3(normalize(T), normalize(B), normalize(normal));
#endif
}
`;var Q3=`
#ifdef STD_THICKNESS_CONSTANT
uniform float material_thickness;
#endif
void getThickness() {
dThickness = 1.0;
#ifdef STD_THICKNESS_CONSTANT
dThickness *= material_thickness;
#endif
#ifdef STD_THICKNESS_TEXTURE
dThickness *= texture2DBias({STD_THICKNESS_TEXTURE_NAME}, {STD_THICKNESS_TEXTURE_UV}, textureBias).{STD_THICKNESS_TEXTURE_CHANNEL};
#endif
#ifdef STD_THICKNESS_VERTEX
dThickness *= saturate(vVertexColor.{STD_THICKNESS_VERTEX_CHANNEL});
#endif
}
`;var J3=`
#ifndef TONEMAP_NO_EXPOSURE_UNIFORM
#if TONEMAP != NONE
uniform float exposure;
float getExposure() { return exposure; }
#else
float getExposure() { return 1.0; }
#endif
#endif
#if (TONEMAP == NONE)
#include "tonemappingNonePS"
#elif TONEMAP == FILMIC
#include "tonemappingFilmicPS"
#elif TONEMAP == LINEAR
#include "tonemappingLinearPS"
#elif TONEMAP == HEJL
#include "tonemappingHejlPS"
#elif TONEMAP == ACES
#include "tonemappingAcesPS"
#elif TONEMAP == ACES2
#include "tonemappingAces2PS"
#elif TONEMAP == NEUTRAL
#include "tonemappingNeutralPS"
#endif
`;var eO=`
vec3 toneMap(vec3 color) {
float tA = 2.51;
float tB = 0.03;
float tC = 2.43;
float tD = 0.59;
float tE = 0.14;
vec3 x = color * getExposure();
return (x*(tA*x+tB))/(x*(tC*x+tD)+tE);
}
`;var tO=`
const mat3 ACESInputMat = mat3(
0.59719, 0.35458, 0.04823,
0.07600, 0.90834, 0.01566,
0.02840, 0.13383, 0.83777
);
const mat3 ACESOutputMat = mat3(
1.60475, -0.53108, -0.07367,
-0.10208, 1.10813, -0.00605,
-0.00327, -0.07276, 1.07602
);
vec3 RRTAndODTFit(vec3 v) {
vec3 a = v * (v + 0.0245786) - 0.000090537;
vec3 b = v * (0.983729 * v + 0.4329510) + 0.238081;
return a / b;
}
vec3 toneMap(vec3 color) {
color *= getExposure() / 0.6;
color = color * ACESInputMat;
color = RRTAndODTFit(color);
color = color * ACESOutputMat;
color = clamp(color, 0.0, 1.0);
return color;
}
`;var sO=`
const float A = 0.15;
const float B = 0.50;
const float C = 0.10;
const float D = 0.20;
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;
}
vec3 toneMap(vec3 color) {
color = uncharted2Tonemap(color * getExposure());
vec3 whiteScale = 1.0 / uncharted2Tonemap(vec3(W,W,W));
color = color * whiteScale;
return color;
}
`;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;
const float Scl = 1.25;
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);
}
`;var rO=`
vec3 toneMap(vec3 color) {
return color * getExposure();
}
`;var aO=`
vec3 toneMap(vec3 color) {
color *= getExposure();
float startCompression = 0.8 - 0.04;
float desaturation = 0.15;
float x = min(color.r, min(color.g, color.b));
float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;
color -= offset;
float peak = max(color.r, max(color.g, color.b));
if (peak < startCompression) return color;
float d = 1. - startCompression;
float newPeak = 1. - d * d / (peak + d - startCompression);
color *= newPeak / peak;
float g = 1. - 1. / (desaturation * (peak - newPeak) + 1.);
return mix(color, newPeak * vec3(1, 1, 1), g);
}
`;var oO=`
vec3 toneMap(vec3 color) {
return color;
}
`;var nO=`
#ifdef PIXELSNAP
uniform vec4 uScreenSize;
#endif
#ifdef SCREENSPACE
uniform float projectionFlipY;
#endif
vec4 evalWorldPosition(vec3 vertexPosition, mat4 modelMatrix) {
vec3 localPos = getLocalPosition(vertexPosition);
#ifdef NINESLICED
localPos.xz *= outerScale;
vec2 positiveUnitOffset = clamp(vertexPosition.xz, vec2(0.0), vec2(1.0));
vec2 negativeUnitOffset = clamp(-vertexPosition.xz, vec2(0.0), vec2(1.0));
localPos.xz += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy;
vTiledUv = (localPos.xz - outerScale + innerOffset.xy) * -0.5 + 1.0;
localPos.xz *= -0.5;
localPos = localPos.xzy;
#endif
vec4 posW = modelMatrix * vec4(localPos, 1.0);
#ifdef SCREENSPACE
posW.zw = vec2(0.0, 1.0);
#endif
return posW;
}
vec4 getPosition() {
dModelMatrix = getModelMatrix();
vec4 posW = evalWorldPosition(vertex_position.xyz, dModelMatrix);
dPositionW = posW.xyz;
vec4 screenPos;
#ifdef UV1LAYOUT
screenPos = vec4(vertex_texCoord1.xy * 2.0 - 1.0, 0.5, 1);
#ifdef WEBGPU
screenPos.y *= -1.0;
#endif
#else
#ifdef SCREENSPACE
screenPos = posW;
screenPos.y *= projectionFlipY;
#else
screenPos = matrix_viewProjection * posW;
#endif
#ifdef PIXELSNAP
screenPos.xy = (screenPos.xy * 0.5) + 0.5;
screenPos.xy *= uScreenSize.xy;
screenPos.xy = floor(screenPos.xy);
screenPos.xy *= uScreenSize.zw;
screenPos.xy = (screenPos.xy * 2.0) - 1.0;
#endif
#endif
return screenPos;
}
vec3 getWorldPosition() {
return dPositionW;
}
`;var lO=`
attribute vec4 vertex_position;
uniform mat4 matrix_viewProjection;
uniform mat4 matrix_model;
#ifdef MORPHING
uniform vec2 morph_tex_params;
attribute uint morph_vertex_id;
ivec2 getTextureMorphCoords() {
ivec2 textureSize = ivec2(morph_tex_params);
int morphGridV = int(morph_vertex_id) / textureSize.x;
int morphGridU = int(morph_vertex_id) - (morphGridV * textureSize.x);
#ifdef WEBGPU
morphGridV = textureSize.y - morphGridV - 1;
#endif
return ivec2(morphGridU, morphGridV);
}
#ifdef MORPHING_POSITION
#ifdef MORPHING_INT
uniform vec3 aabbSize;
uniform vec3 aabbMin;
uniform usampler2D morphPositionTex;
#else
uniform highp sampler2D morphPositionTex;
#endif
#endif
#endif
#ifdef defined(BATCH)
#include "skinBatchVS"
mat4 getModelMatrix() {
return getBoneMatrix(vertex_boneIndices);
}
#elif defined(SKIN)
#include "skinVS"
mat4 getModelMatrix() {
return matrix_model * getSkinMatrix(vertex_boneIndices, vertex_boneWeights);
}
#elif defined(INSTANCING)
#include "transformInstancingVS"
#else
mat4 getModelMatrix() {
return matrix_model;
}
#endif
vec3 getLocalPosition(vec3 vertexPosition) {
vec3 localPos = vertexPosition;
#ifdef MORPHING_POSITION
ivec2 morphUV = getTextureMorphCoords();
#ifdef MORPHING_INT
vec3 morphPos = vec3(texelFetch(morphPositionTex, ivec2(morphUV), 0).xyz) / 65535.0 * aabbSize + aabbMin;
#else
vec3 morphPos = texelFetch(morphPositionTex, ivec2(morphUV), 0).xyz;
#endif
localPos += morphPos;
#endif
return localPos;
}
`;var cO=`
attribute vec4 instance_line1;
attribute vec4 instance_line2;
attribute vec4 instance_line3;
attribute vec4 instance_line4;
mat4 getModelMatrix() {
return matrix_model * mat4(instance_line1, instance_line2, instance_line3, instance_line4);
}
`;var hO=`
#ifdef STD_REFRACTION_CONSTANT
uniform float material_refraction;
#endif
void getRefraction() {
float refraction = 1.0;
#ifdef STD_REFRACTION_CONSTANT
refraction = material_refraction;
#endif
#ifdef STD_REFRACTION_TEXTURE
refraction *= texture2DBias({STD_REFRACTION_TEXTURE_NAME}, {STD_REFRACTION_TEXTURE_UV}, textureBias).{STD_REFRACTION_TEXTURE_CHANNEL};
#endif
#ifdef STD_REFRACTION_VERTEX
refraction *= saturate(vVertexColor.{STD_REFRACTION_VERTEX_CHANNEL});
#endif
dTransmission = refraction;
}
`;var fO=`
void handleTwoSidedLighting() {
if (!gl_FrontFacing) dTBN[2] = -dTBN[2];
}
`;var uO=`
#ifdef NINESLICED
vec2 getUv0() {
vec2 uv = vertex_position.xz;
vec2 positiveUnitOffset = clamp(vertex_position.xz, vec2(0.0), vec2(1.0));
vec2 negativeUnitOffset = clamp(-vertex_position.xz, vec2(0.0), vec2(1.0));
uv += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy;
uv = uv * -0.5 + 0.5;
uv = uv * atlasRect.zw + atlasRect.xy;
vMask = vertex_texCoord0.xy;
return uv;
}
#else
vec2 getUv0() {
return vertex_texCoord0;
}
#endif
`;var dO=`
vec2 getUv1() {
return vertex_texCoord1;
}
`;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)
);
`;var mO=`
uniform vec3 {TRANSFORM_NAME_{i}}0;
uniform vec3 {TRANSFORM_NAME_{i}}1;
`;var _O=`
void getViewDir() {
dViewDirW = normalize(view_position - vPositionW);
}
`;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;
}
}
`;var xO=`
#if LIT_AMBIENT_SOURCE == AMBIENTSH
uniform ambientSH: array<vec3f, 9>;
#endif
#if LIT_AMBIENT_SOURCE == ENVALATLAS
#include "envAtlasPS"
#ifndef ENV_ATLAS
#define ENV_ATLAS
var texture_envAtlas: texture_2d<f32>;
var texture_envAtlasSampler: sampler;
#endif
#endif
fn addAmbient(worldNormal: vec3f) {
#ifdef LIT_AMBIENT_SOURCE == AMBIENTSH
let n: vec3f = cubeMapRotate(worldNormal);
let color: vec3f =
uniform.ambientSH[0] +
uniform.ambientSH[1] * n.x +
uniform.ambientSH[2] * n.y +
uniform.ambientSH[3] * n.z +
uniform.ambientSH[4] * n.x * n.z +
uniform.ambientSH[5] * n.z * n.y +
uniform.ambientSH[6] * n.y * n.x +
uniform.ambientSH[7] * (3.0 * n.z * n.z - 1.0) +
uniform.ambientSH[8] * (n.x * n.x - n.y * n.y);
dDiffuseLight += processEnvironment(max(color, vec3f(0.0)));
#endif
#if LIT_AMBIENT_SOURCE == ENVALATLAS
let dir: vec3f = normalize(cubeMapRotate(worldNormal) * vec3f(-1.0, 1.0, 1.0));
let uv: vec2f = mapUv(toSphericalUv(dir), vec4f(128.0, 256.0 + 128.0, 64.0, 32.0) / atlasSize);
let raw: vec4f = textureSample(texture_envAtlas, texture_envAtlasSampler, uv);
let linear: vec3f = {ambientDecode}(raw);
dDiffuseLight += processEnvironment(linear);
#endif
#if LIT_AMBIENT_SOURCE == CONSTANT
dDiffuseLight += uniform.light_globalAmbient;
#endif
}
`;var vO=`
#ifdef LIT_GGX_SPECULAR
uniform material_anisotropyIntensity: f32;
uniform material_anisotropyRotation: vec2f;
#endif
fn getAnisotropy() {
dAnisotropy = 0.0;
dAnisotropyRotation = vec2f(1.0, 0.0);
#ifdef LIT_GGX_SPECULAR
dAnisotropy = uniform.material_anisotropyIntensity;
dAnisotropyRotation = uniform.material_anisotropyRotation;
#endif
#ifdef STD_ANISOTROPY_TEXTURE
let anisotropyTex: vec3f = textureSampleBias({STD_ANISOTROPY_TEXTURE_NAME}, {STD_ANISOTROPY_TEXTURE_NAME}Sampler, {STD_ANISOTROPY_TEXTURE_UV}, uniform.textureBias).rgb;
dAnisotropy *= anisotropyTex.b;
let anisotropyRotationFromTex: vec2f = anisotropyTex.rg * 2.0 - vec2f(1.0);
let rotationMatrix: mat2x2f = mat2x2f(dAnisotropyRotation.x, dAnisotropyRotation.y, -dAnisotropyRotation.y, dAnisotropyRotation.x);
dAnisotropyRotation = rotationMatrix * anisotropyRotationFromTex;
#endif
dAnisotropy = clamp(dAnisotropy, 0.0, 1.0);
}
`;var TO=`
#if defined(STD_AO_TEXTURE) || defined(STD_AO_VERTEX)
uniform material_aoIntensity: f32;
#endif
#ifdef STD_AODETAIL_TEXTURE
#include "detailModesPS"
#endif
fn getAO() {
dAo = 1.0;
#ifdef STD_AO_TEXTURE
var aoBase: f32 = textureSampleBias({STD_AO_TEXTURE_NAME}, {STD_AO_TEXTURE_NAME}Sampler, {STD_AO_TEXTURE_UV}, uniform.textureBias).{STD_AO_TEXTURE_CHANNEL};
#ifdef STD_AODETAIL_TEXTURE
var aoDetail: f32 = textureSampleBias({STD_AODETAIL_TEXTURE_NAME}, {STD_AODETAIL_TEXTURE_NAME}Sampler, {STD_AODETAIL_TEXTURE_UV}, uniform.textureBias).{STD_AODETAIL_TEXTURE_CHANNEL};
aoBase = detailMode_{STD_AODETAIL_DETAILMODE}(vec3f(aoBase), vec3f(aoDetail)).r;
#endif
dAo = dAo * aoBase;
#endif
#ifdef STD_AO_VERTEX
dAo = dAo * saturate(vVertexColor.{STD_AO_VERTEX_CHANNEL});
#endif
#if defined(STD_AO_TEXTURE) || defined(STD_AO_VERTEX)
dAo = mix(1.0, dAo, uniform.material_aoIntensity);
#endif
}
`;var yO=`
fn occludeDiffuse(ao: f32) {
dDiffuseLight = dDiffuseLight * ao;
}
`;var EO=`
#if LIT_OCCLUDE_SPECULAR != NONE
#ifdef LIT_OCCLUDE_SPECULAR_FLOAT
uniform material_occludeSpecularIntensity: f32;
#endif
#endif
fn occludeSpecular(gloss: f32, ao: f32, worldNormal: vec3f, viewDir: vec3f) {
#if LIT_OCCLUDE_SPECULAR == AO
#ifdef LIT_OCCLUDE_SPECULAR_FLOAT
var specOcc: f32 = mix(1.0, ao, uniform.material_occludeSpecularIntensity);
#else
var specOcc: f32 = ao;
#endif
#endif
#if LIT_OCCLUDE_SPECULAR == GLOSSDEPENDENT
var specPow: f32 = exp2(gloss * 11.0);
var specOcc: f32 = saturate(pow(dot(worldNormal, viewDir) + ao, 0.01 * specPow) - 1.0 + ao);
#ifdef LIT_OCCLUDE_SPECULAR_FLOAT
specOcc = mix(1.0, specOcc, uniform.material_occludeSpecularIntensity);
#endif
#endif
#if LIT_OCCLUDE_SPECULAR != NONE
dSpecularLight = dSpecularLight * specOcc;
dReflection = dReflection * specOcc;
#ifdef LIT_SHEEN
sSpecularLight = sSpecularLight * specOcc;
sReflection = sReflection * specOcc;
#endif
#endif
}
`;var AO=`
let dirLm = textureSample(texture_dirLightMap, texture_dirLightMapSampler, vUv1);
if (uniform.bakeDir > 0.5) {
if (dAtten > 0.00001) {
let unpacked_dir = dirLm.xyz * 2.0 - vec3f(1.0);
dAtten = clamp(dAtten, 0.0, 1.0);
let combined_dir = dLightDirNormW.xyz * dAtten + unpacked_dir * dirLm.w;
let finalRgb = normalize(combined_dir) * 0.5 + vec3f(0.5);
let finalA = max(dirLm.w + dAtten, 1.0 / 255.0);
output.color = vec4f(finalRgb, finalA);
} else {
output.color = dirLm;
}
} else {
let alpha_min = select(0.0, 1.0 / 255.0, dAtten > 0.00001);
let finalA = max(dirLm.w, alpha_min);
output.color = vec4f(dirLm.rgb, finalA);
}
`;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);
dDiffuseLight = saturate3(dDiffuseLight);
dDiffuseLight = dDiffuseLight * dAmbientLight;
#endif
#ifdef LIGHTMAP_RGBM
var temp_color_rgbm = vec4f(dDiffuseLight, 1.0);
temp_color_rgbm = vec4f(pow(temp_color_rgbm.rgb, vec3f(0.5)), temp_color_rgbm.a);
temp_color_rgbm = vec4f(temp_color_rgbm.rgb / 8.0, temp_color_rgbm.a);
let max_g_b = max(temp_color_rgbm.g, max(temp_color_rgbm.b, 1.0 / 255.0));
let max_rgb = max(temp_color_rgbm.r, max_g_b);
temp_color_rgbm.a = clamp(max_rgb, 0.0, 1.0);
temp_color_rgbm.a = ceil(temp_color_rgbm.a * 255.0) / 255.0;
temp_color_rgbm = vec4f(temp_color_rgbm.rgb / temp_color_rgbm.a, temp_color_rgbm.a);
output.color = temp_color_rgbm;
#else
output.color = vec4f(dDiffuseLight, 1.0);
#endif
`;var PO=`
uniform view_position: vec3f;
uniform light_globalAmbient: vec3f;
fn square(x: f32) -> f32 {
return x*x;
}
fn saturate(x: f32) -> f32 {
return clamp(x, 0.0, 1.0);
}
fn saturate3(x: vec3f) -> vec3f {
return clamp(x, vec3f(0.0), vec3f(1.0));
}
`;var wO=`
#define NINESLICED
varying vMask: vec2f;
varying vTiledUv: vec2f;
uniform innerOffset: vec4f;
uniform outerScale: vec2f;
uniform atlasRect: vec4f;
var<private> nineSlicedUv: vec2f;
`;var IO=`
#define NINESLICED
#define NINESLICETILED
varying vMask: vec2f;
varying vTiledUv: vec2f;
uniform innerOffset: vec4f;
uniform outerScale: vec2f;
uniform atlasRect: vec4f;
var<private> nineSlicedUv: vec2f;
`;var RO=`
fn bayer2(p: vec2f) -> f32 {
return (2.0 * p.y + p.x + 1.0) % 4.0;
}
fn bayer4(p: vec2f) -> f32 {
let p1: vec2f = p % vec2f(2.0);
let p2: vec2f = floor(0.5 * (p % vec2f(4.0)));
return 4.0 * bayer2(p1) + bayer2(p2);
}
fn bayer8(p: vec2f) -> f32 {
let p1: vec2f = p % vec2f(2.0);
let p2: vec2f = floor(0.5 * (p % vec2f(4.0)));
let p4: vec2f = floor(0.25 * (p % vec2f(8.0)));
return 4.0 * (4.0 * bayer2(p1) + bayer2(p2)) + bayer2(p4);
}
`;var bO=`
varying vUv0: vec2f;
var source: texture_2d<f32>;
var sourceSampler: sampler;
#ifdef GAUSS
uniform weight: array<f32, {SAMPLES}>;
#endif
uniform pixelOffset: vec2f;
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
var moments: vec3f = vec3f(0.0);
let uv: vec2f = input.vUv0 - uniform.pixelOffset * (f32({SAMPLES}) * 0.5);
for (var i: i32 = 0; i < {SAMPLES}; i = i + 1) {
let c: vec4f = textureSample(source, sourceSampler, uv + uniform.pixelOffset * f32(i));
#ifdef GAUSS
moments = moments + c.xyz * uniform.weight[i].element;
#else
moments = moments + c.xyz;
#endif
}
#ifndef GAUSS
moments = moments * (1.0 / f32({SAMPLES}));
#endif
output.color = vec4f(moments, 1.0);
return output;
}
`;var DO=`
uniform material_clearCoat: f32;
fn getClearCoat() {
ccSpecularity = uniform.material_clearCoat;
#ifdef STD_CLEARCOAT_TEXTURE
ccSpecularity = ccSpecularity * textureSampleBias({STD_CLEARCOAT_TEXTURE_NAME}, {STD_CLEARCOAT_TEXTURE_NAME}Sampler, {STD_CLEARCOAT_TEXTURE_UV}, uniform.textureBias).{STD_CLEARCOAT_TEXTURE_CHANNEL};
#endif
#ifdef STD_CLEARCOAT_VERTEX
ccSpecularity = ccSpecularity * saturate(vVertexColor.{STD_CLEARCOAT_VERTEX_CHANNEL});
#endif
}
`;var LO=`
uniform material_clearCoatGloss: f32;
fn getClearCoatGlossiness() {
ccGlossiness = uniform.material_clearCoatGloss;
#ifdef STD_CLEARCOATGLOSS_TEXTURE
ccGlossiness = ccGlossiness * textureSampleBias({STD_CLEARCOATGLOSS_TEXTURE_NAME}, {STD_CLEARCOATGLOSS_TEXTURE_NAME}Sampler, {STD_CLEARCOATGLOSS_TEXTURE_UV}, uniform.textureBias).{STD_CLEARCOATGLOSS_TEXTURE_CHANNEL};
#endif
#ifdef STD_CLEARCOATGLOSS_VERTEX
ccGlossiness = ccGlossiness * saturate(vVertexColor.{STD_CLEARCOATGLOSS_VERTEX_CHANNEL});
#endif
#ifdef STD_CLEARCOATGLOSS_INVERT
ccGlossiness = 1.0 - ccGlossiness;
#endif
ccGlossiness += 0.0000001;
}
`;var MO=`
#ifdef STD_CLEARCOATNORMAL_TEXTURE
uniform material_clearCoatBumpiness: f32;
#endif
fn getClearCoatNormal() {
#ifdef STD_CLEARCOATNORMAL_TEXTURE
var normalMap: vec3f = {STD_CLEARCOATNORMAL_TEXTURE_DECODE}(textureSampleBias({STD_CLEARCOATNORMAL_TEXTURE_NAME}, {STD_CLEARCOATNORMAL_TEXTURE_NAME}Sampler, {STD_CLEARCOATNORMAL_TEXTURE_UV}, uniform.textureBias));
normalMap = mix(vec3f(0.0, 0.0, 1.0), normalMap, uniform.material_clearCoatBumpiness);
ccNormalW = normalize(dTBN * normalMap);
#else
ccNormalW = dVertexNormalW;
#endif
}
`;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<f32>, 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;
return select(vec3f(dot(pixel, cookieChannel)), pixel.rgb, isRgb);
}
fn getCookie2DClustered(tex: texture_2d<f32>, texSampler: sampler, transform: mat4x4f, worldPosition: vec3f, intensity: f32, cookieChannel: vec4f) -> vec3f {
let projPos: vec4f = transform * vec4f(worldPosition, 1.0);
return _getCookieClustered(tex, texSampler, projPos.xy / projPos.w, intensity, cookieChannel);
}
fn getCookieCubeClustered(tex: texture_2d<f32>, texSampler: sampler, dir: vec3f, intensity: f32, cookieChannel: vec4f, shadowTextureResolution: f32, shadowEdgePixels: f32, omniAtlasViewport: vec3f) -> vec3f {
let uv: vec2f = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir);
return _getCookieClustered(tex, texSampler, uv, intensity, cookieChannel);
}
`;var NO=`
fn _getShadowCoordPerspZbuffer(shadowMatrix: mat4x4f, shadowParams: vec4f, wPos: vec3f) -> vec3f {
var projPos = shadowMatrix * vec4f(wPos, 1.0);
return projPos.xyz / projPos.w;
}
fn getShadowCoordPerspZbufferNormalOffset(shadowMatrix: mat4x4f, shadowParams: vec4f, normal: vec3f) -> vec3f {
let wPos: vec3f = vPositionW + normal * shadowParams.y;
return _getShadowCoordPerspZbuffer(shadowMatrix, shadowParams, wPos);
}
fn normalOffsetPointShadow(shadowParams: vec4f, lightPos: vec3f, lightDir: vec3f, lightDirNorm: vec3f, normal: vec3f) -> vec3f {
let distScale: f32 = length(lightDir);
let wPos: vec3f = vPositionW + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;
let dir: vec3f = wPos - lightPos;
return dir;
}
#if defined(CLUSTER_SHADOW_TYPE_PCF1)
fn getShadowOmniClusteredPCF1(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowParams: vec4f, omniAtlasViewport: vec3f, shadowEdgePixels: f32, lightDir: vec3f) -> f32 {
let shadowTextureResolution: f32 = shadowParams.x;
let uv: vec2f = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);
let shadowZ: f32 = length(lightDir) * shadowParams.w + shadowParams.z;
return textureSampleCompareLevel(shadowMap, shadowMapSampler, uv, shadowZ);
}
#endif
#if defined(CLUSTER_SHADOW_TYPE_PCF3)
fn getShadowOmniClusteredPCF3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowParams: vec4f, omniAtlasViewport: vec3f, shadowEdgePixels: f32, lightDir: vec3f) -> f32 {
let shadowTextureResolution: f32 = shadowParams.x;
let uv: vec2f = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);
let shadowZ: f32 = length(lightDir) * shadowParams.w + shadowParams.z;
let shadowCoord: vec3f = vec3f(uv, shadowZ);
return getShadowPCF3x3(shadowMap, shadowMapSampler, shadowCoord, shadowParams);
}
#endif
#if defined(CLUSTER_SHADOW_TYPE_PCF5)
fn getShadowOmniClusteredPCF5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowParams: vec4f, omniAtlasViewport: vec3f, shadowEdgePixels: f32, lightDir: vec3f) -> f32 {
let shadowTextureResolution: f32 = shadowParams.x;
let uv: vec2f = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir);
let shadowZ: f32 = length(lightDir) * shadowParams.w + shadowParams.z;
let shadowCoord: vec3f = vec3f(uv, shadowZ);
return getShadowPCF5x5(shadowMap, shadowMapSampler, shadowCoord, shadowParams);
}
#endif
#if defined(CLUSTER_SHADOW_TYPE_PCF1)
fn getShadowSpotClusteredPCF1(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {
return textureSampleCompareLevel(shadowMap, shadowMapSampler, shadowCoord.xy, shadowCoord.z);
}
#endif
#if defined(CLUSTER_SHADOW_TYPE_PCF3)
fn getShadowSpotClusteredPCF3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {
return getShadowSpotPCF3x3(shadowMap, shadowMapSampler, shadowCoord, shadowParams);
}
#endif
#if defined(CLUSTER_SHADOW_TYPE_PCF5)
fn getShadowSpotClusteredPCF5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {
return getShadowPCF5x5(shadowMap, shadowMapSampler, shadowCoord, shadowParams);
}
#endif
`;var BO=`
#include "lightBufferDefinesPS"
#include "clusteredLightUtilsPS"
#ifdef CLUSTER_COOKIES
#include "clusteredLightCookiesPS"
#endif
#ifdef CLUSTER_SHADOWS
#include "clusteredLightShadowsPS"
#endif
var clusterWorldTexture: texture_2d<u32>;
var lightsTexture: texture_2d<uff>;
#ifdef CLUSTER_SHADOWS
var shadowAtlasTexture: texture_depth_2d;
var shadowAtlasTextureSampler: sampler_comparison;
#endif
#ifdef CLUSTER_COOKIES
var cookieAtlasTexture: texture_2d<f32>;
var cookieAtlasTextureSampler: sampler;
#endif
uniform clusterMaxCells: i32;
uniform numClusteredLights: i32;
uniform clusterTextureWidth: i32;
uniform clusterCellsCountByBoundsSize: vec3f;
uniform clusterBoundsMin: vec3f;
uniform clusterBoundsDelta: vec3f;
uniform clusterCellsDot: vec3i;
uniform clusterCellsMax: vec3i;
uniform shadowAtlasParams: vec2f;
struct ClusterLightData {
position: vec3f,
lightIndex: i32,
direction: vec3f,
shape: u32,
color: vec3f,
shadowIntensity: f32,
range: f32,
biasesData: 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<private> lightProjectionMatrix: mat4x4f;
var<private> clusterLightData_flags: u32;
var<private> clusterLightData_anglesData: f32;
var<private> clusterLightData_colorBFlagsData: u32;
fn sampleLightTextureF(lightIndex: i32, index: i32) -> vec4f {
return textureLoad(lightsTexture, vec2<i32>(index, lightIndex), 0);
}
fn decodeClusterLightCore(lightIndex: i32) -> ClusterLightData {
var clusterLightData: ClusterLightData;
clusterLightData.lightIndex = lightIndex;
let halfData: vec4f = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_COLOR_ANGLES_BIAS});
clusterLightData_anglesData = halfData.z;
clusterLightData.biasesData = halfData.w;
clusterLightData_colorBFlagsData = bitcast<u32>(halfData.y);
let colorRG: vec2f = unpack2x16float(bitcast<u32>(halfData.x));
let colorB_flags: vec2f = unpack2x16float(clusterLightData_colorBFlagsData);
clusterLightData.color = vec3f(colorRG, colorB_flags.x) * {LIGHT_COLOR_DIVIDER};
let lightPosRange: vec4f = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_POSITION_RANGE});
clusterLightData.position = lightPosRange.xyz;
clusterLightData.range = lightPosRange.w;
let lightDir_Flags: vec4f = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_DIRECTION_FLAGS});
clusterLightData.direction = lightDir_Flags.xyz;
clusterLightData_flags = bitcast<u32>(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() -> ClusterLightSpotData {
let angleFlags: u32 = (clusterLightData_colorBFlagsData >> 16u) & 0xFFFFu;
let angleValues: vec2f = unpack2x16float(bitcast<u32>(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;
return ClusterLightSpotData(
select(innerVal, 1.0 - innerVal, innerIsVersine),
select(outerVal, 1.0 - outerVal, outerIsVersine)
);
}
fn decodeClusterLightOmniAtlasViewport(lightIndex: i32) -> vec3f {
return sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_0}).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(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(biasesData: f32) -> ClusterLightShadowData {
let biases: vec2f = unpack2x16float(bitcast<u32>(biasesData));
return ClusterLightShadowData(biases.x, biases.y);
}
fn decodeClusterLightCookieData() -> vec4f {
let cookieFlags: u32 = (clusterLightData_flags >> 23u) & 0x0Fu;
let mask_uvec: vec4<u32> = vec4<u32>(cookieFlags) & vec4<u32>(1u, 2u, 4u, 8u);
return step(vec4f(1.0), vec4f(mask_uvec));
}
fn evaluateLight(
light: ClusterLightData,
worldNormal: vec3f,
viewDir: vec3f,
reflectionDir: vec3f,
#if defined(LIT_CLEARCOAT)
clearcoatReflectionDir: vec3f,
#endif
gloss: f32,
specularity: vec3f,
geometricNormal: vec3f,
tbn: mat3x3f,
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel: vec3f,
#endif
clearcoat_worldNormal: vec3f,
clearcoat_gloss: f32,
sheen_gloss: f32,
iridescence_intensity: f32
) {
var cookieAttenuation: vec3f = vec3f(1.0);
var diffuseAttenuation: f32 = 1.0;
var falloffAttenuation: f32 = 1.0;
let lightDirW: vec3f = evalOmniLight(light.position);
let lightDirNormW: vec3f = normalize(lightDirW);
#ifdef CLUSTER_AREALIGHTS
if (light.shape != {LIGHTSHAPE_PUNCTUAL}) {
let areaData: ClusterLightAreaData = decodeClusterLightAreaData(light.lightIndex);
if (light.shape == {LIGHTSHAPE_RECT}) {
calcRectLightValues(light.position, areaData.halfWidth, areaData.halfHeight);
} else if (light.shape == {LIGHTSHAPE_DISK}) {
calcDiskLightValues(light.position, areaData.halfWidth, areaData.halfHeight);
} else {
calcSphereLightValues(light.position, areaData.halfWidth, areaData.halfHeight);
}
falloffAttenuation = getFalloffWindow(light.range, lightDirW);
} else
#endif
{
if (light.falloffModeLinear) {
falloffAttenuation = getFalloffLinear(light.range, lightDirW);
} else {
falloffAttenuation = getFalloffInvSquared(light.range, lightDirW);
}
}
if (falloffAttenuation > 0.00001) {
#ifdef CLUSTER_AREALIGHTS
if (light.shape != {LIGHTSHAPE_PUNCTUAL}) {
if (light.shape == {LIGHTSHAPE_RECT}) {
diffuseAttenuation = getRectLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0;
} else if (light.shape == {LIGHTSHAPE_DISK}) {
diffuseAttenuation = getDiskLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0;
} else {
diffuseAttenuation = getSphereLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0;
}
} else
#endif
{
falloffAttenuation = falloffAttenuation * getLightDiffuse(worldNormal, viewDir, lightDirNormW);
}
if (light.isSpot) {
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) {
lightProjectionMatrix = decodeClusterLightProjectionMatrixData(light.lightIndex);
} else {
omniAtlasViewport = decodeClusterLightOmniAtlasViewport(light.lightIndex);
}
let shadowTextureResolution: f32 = uniform.shadowAtlasParams.x;
let shadowEdgePixels: f32 = uniform.shadowAtlasParams.y;
#ifdef CLUSTER_COOKIES
if (light.cookieIntensity > 0.0) {
let cookieChannelMask: vec4f = decodeClusterLightCookieData();
if (light.isSpot) {
cookieAttenuation = getCookie2DClustered(cookieAtlasTexture, cookieAtlasTextureSampler, lightProjectionMatrix, vPositionW, light.cookieIntensity, cookieChannelMask);
} else {
cookieAttenuation = getCookieCubeClustered(cookieAtlasTexture, cookieAtlasTextureSampler, lightDirW, light.cookieIntensity, cookieChannelMask, shadowTextureResolution, shadowEdgePixels, omniAtlasViewport);
}
}
#endif
#ifdef CLUSTER_SHADOWS
if (light.shadowIntensity > 0.0) {
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)
let shadow: f32 = getShadowSpotClusteredPCF1(shadowAtlasTexture, shadowAtlasTextureSampler, shadowCoord, shadowParams);
#elif defined(CLUSTER_SHADOW_TYPE_PCF3)
let shadow: f32 = getShadowSpotClusteredPCF3(shadowAtlasTexture, shadowAtlasTextureSampler, shadowCoord, shadowParams);
#elif defined(CLUSTER_SHADOW_TYPE_PCF5)
let shadow: f32 = getShadowSpotClusteredPCF5(shadowAtlasTexture, shadowAtlasTextureSampler, shadowCoord, shadowParams);
#elif defined(CLUSTER_SHADOW_TYPE_PCSS)
let shadow: f32 = getShadowSpotClusteredPCSS(shadowAtlasTexture, shadowAtlasTextureSampler, shadowCoord, shadowParams);
#endif
falloffAttenuation = falloffAttenuation * mix(1.0, shadow, light.shadowIntensity);
} else {
let dir: vec3f = normalOffsetPointShadow(shadowParams, light.position, lightDirW, lightDirNormW, geometricNormal);
#if defined(CLUSTER_SHADOW_TYPE_PCF1)
let shadow: f32 = getShadowOmniClusteredPCF1(shadowAtlasTexture, shadowAtlasTextureSampler, shadowParams, omniAtlasViewport, shadowEdgePixels, dir);
#elif defined(CLUSTER_SHADOW_TYPE_PCF3)
let shadow: f32 = getShadowOmniClusteredPCF3(shadowAtlasTexture, shadowAtlasTextureSampler, shadowParams, omniAtlasViewport, shadowEdgePixels, dir);
#elif defined(CLUSTER_SHADOW_TYPE_PCF5)
let shadow: f32 = getShadowOmniClusteredPCF5(shadowAtlasTexture, shadowAtlasTextureSampler, shadowParams, omniAtlasViewport, shadowEdgePixels, dir);
#endif
falloffAttenuation = falloffAttenuation * mix(1.0, shadow, light.shadowIntensity);
}
}
#endif
}
}
#endif
#ifdef CLUSTER_AREALIGHTS
if (light.shape != {LIGHTSHAPE_PUNCTUAL}) {
{
var areaDiffuse: vec3f = (diffuseAttenuation * falloffAttenuation) * light.color * cookieAttenuation;
#if defined(LIT_SPECULAR)
areaDiffuse = mix(areaDiffuse, vec3f(0.0), dLTCSpecFres);
#endif
dDiffuseLight = dDiffuseLight + areaDiffuse;
}
#ifdef LIT_SPECULAR
var areaLightSpecular: f32;
if (light.shape == {LIGHTSHAPE_RECT}) {
areaLightSpecular = getRectLightSpecular(worldNormal, viewDir);
} else if (light.shape == {LIGHTSHAPE_DISK}) {
areaLightSpecular = getDiskLightSpecular(worldNormal, viewDir);
} else {
areaLightSpecular = getSphereLightSpecular(worldNormal, viewDir);
}
dSpecularLight = dSpecularLight + dLTCSpecFres * areaLightSpecular * falloffAttenuation * light.color * cookieAttenuation;
#ifdef LIT_CLEARCOAT
var areaLightSpecularCC: f32;
if (light.shape == {LIGHTSHAPE_RECT}) {
areaLightSpecularCC = getRectLightSpecular(clearcoat_worldNormal, viewDir);
} else if (light.shape == {LIGHTSHAPE_DISK}) {
areaLightSpecularCC = getDiskLightSpecular(clearcoat_worldNormal, viewDir);
} else {
areaLightSpecularCC = getSphereLightSpecular(clearcoat_worldNormal, viewDir);
}
ccSpecularLight = ccSpecularLight + ccLTCSpecFres * areaLightSpecularCC * falloffAttenuation * light.color * cookieAttenuation;
#endif
#endif
} else
#endif
{
{
var punctualDiffuse: vec3f = falloffAttenuation * light.color * cookieAttenuation;
#if defined(CLUSTER_AREALIGHTS)
#if defined(LIT_SPECULAR)
punctualDiffuse = mix(punctualDiffuse, vec3f(0.0), specularity);
#endif
#endif
dDiffuseLight = dDiffuseLight + punctualDiffuse;
}
#ifdef LIT_SPECULAR
let halfDir: vec3f = normalize(-lightDirNormW + viewDir);
#ifdef LIT_SPECULAR_FRESNEL
dSpecularLight = dSpecularLight +
getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, lightDirNormW, gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation *
getFresnel(
dot(viewDir, halfDir),
gloss,
specularity
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
iridescence_intensity
#endif
);
#else
dSpecularLight = dSpecularLight + getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, lightDirNormW, gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * specularity;
#endif
#ifdef LIT_CLEARCOAT
#ifdef LIT_SPECULAR_FRESNEL
ccSpecularLight = ccSpecularLight + getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat_worldNormal, viewDir, lightDirNormW, clearcoat_gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * getFresnelCC(dot(viewDir, halfDir));
#else
ccSpecularLight = ccSpecularLight + getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat_worldNormal, viewDir, lightDirNormW, clearcoat_gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation;
#endif
#endif
#ifdef LIT_SHEEN
sSpecularLight = sSpecularLight + getLightSpecularSheen(halfDir, worldNormal, viewDir, lightDirNormW, sheen_gloss) * falloffAttenuation * light.color * cookieAttenuation;
#endif
#endif
}
}
dAtten = falloffAttenuation;
dLightDirNormW = lightDirNormW;
}
fn evaluateClusterLight(
lightIndex: i32,
worldNormal: vec3f,
viewDir: vec3f,
reflectionDir: vec3f,
#if defined(LIT_CLEARCOAT)
clearcoatReflectionDir: vec3f,
#endif
gloss: f32,
specularity: vec3f,
geometricNormal: vec3f,
tbn: mat3x3f,
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel: vec3f,
#endif
clearcoat_worldNormal: vec3f,
clearcoat_gloss: f32,
sheen_gloss: f32,
iridescence_intensity: f32
) {
let clusterLightData: ClusterLightData = decodeClusterLightCore(lightIndex);
#ifdef CLUSTER_MESH_DYNAMIC_LIGHTS
let acceptLightMask: bool = clusterLightData.isDynamic;
#else
let acceptLightMask: bool = clusterLightData.isLightmapped;
#endif
if (acceptLightMask) {
evaluateLight(
clusterLightData,
worldNormal,
viewDir,
reflectionDir,
#if defined(LIT_CLEARCOAT)
clearcoatReflectionDir,
#endif
gloss,
specularity,
geometricNormal,
tbn,
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel,
#endif
clearcoat_worldNormal,
clearcoat_gloss,
sheen_gloss,
iridescence_intensity
);
}
}
fn addClusteredLights(
worldNormal: vec3f,
viewDir: vec3f,
reflectionDir: vec3f,
#if defined(LIT_CLEARCOAT)
clearcoatReflectionDir: vec3f,
#endif
gloss: f32,
specularity: vec3f,
geometricNormal: vec3f,
tbn: mat3x3f,
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel: vec3f,
#endif
clearcoat_worldNormal: vec3f,
clearcoat_gloss: f32,
sheen_gloss: f32,
iridescence_intensity: f32
) {
if (uniform.numClusteredLights <= 1) {
return;
}
let cellCoords: vec3i = vec3i(floor((vPositionW - uniform.clusterBoundsMin) * uniform.clusterCellsCountByBoundsSize));
if (!(any(cellCoords < vec3i(0)) || any(cellCoords >= uniform.clusterCellsMax))) {
let cellIndex: i32 = cellCoords.x * uniform.clusterCellsDot.x + cellCoords.y * uniform.clusterCellsDot.y + cellCoords.z * uniform.clusterCellsDot.z;
let clusterV: i32 = cellIndex / uniform.clusterTextureWidth;
let clusterU: i32 = cellIndex - clusterV * uniform.clusterTextureWidth;
for (var lightCellIndex: i32 = 0; lightCellIndex < uniform.clusterMaxCells; lightCellIndex = lightCellIndex + 1) {
let lightIndex: u32 = textureLoad(clusterWorldTexture, vec2<i32>(clusterU + lightCellIndex, clusterV), 0).r;
if (lightIndex == 0u) {
break;
}
evaluateClusterLight(
i32(lightIndex),
worldNormal,
viewDir,
reflectionDir,
#if defined(LIT_CLEARCOAT)
clearcoatReflectionDir,
#endif
gloss,
specularity,
geometricNormal,
tbn,
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel,
#endif
clearcoat_worldNormal,
clearcoat_gloss,
sheen_gloss,
iridescence_intensity
);
}
}
}`;var UO=`
fn combineColor(albedo: vec3f, sheenSpecularity: vec3f, clearcoatSpecularity: f32) -> vec3f {
var ret: vec3f = vec3f(0.0);
#ifdef LIT_OLD_AMBIENT
ret = ret + ((dDiffuseLight - uniform.light_globalAmbient) * albedo + uniform.material_ambient * uniform.light_globalAmbient);
#else
ret = ret + (albedo * dDiffuseLight);
#endif
#ifdef LIT_SPECULAR
ret = ret + dSpecularLight;
#endif
#ifdef LIT_REFLECTIONS
ret = ret + (dReflection.rgb * dReflection.a);
#endif
#ifdef LIT_SHEEN
let sheenScaling: f32 = 1.0 - max(max(sheenSpecularity.r, sheenSpecularity.g), sheenSpecularity.b) * 0.157;
ret = ret * sheenScaling + (sSpecularLight + sReflection.rgb) * sheenSpecularity;
#endif
#ifdef LIT_CLEARCOAT
let clearCoatScaling: f32 = 1.0 - ccFresnel * clearcoatSpecularity;
ret = ret * clearCoatScaling + (ccSpecularLight + ccReflection) * clearcoatSpecularity;
#endif
return ret;
}
`;var kO=`
varying uv0: vec2f;
var blitTexture: texture_2d<f32>;
var blitTextureSampler : sampler;
@fragment
fn fragmentMain(input : FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
output.color = textureSample(blitTexture, blitTextureSampler, input.uv0);
return output;
}
`;var zO=`
varying uv0: vec2f;
uniform invViewProj: mat4x4<f32>;
var blitTexture: texture_cube<f32>;
var blitTextureSampler : sampler;
@fragment
fn fragmentMain(input : FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
var projPos = vec4f(input.uv0 * 2.0 - 1.0, 0.5, 1.0);
var worldPos = uniform.invViewProj * projPos;
output.color = textureSample(blitTexture, blitTextureSampler, worldPos.xyz);
return output;
}
`;var GO=`
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);
output.uv0.y = 1.0 - output.uv0.y;
return output;
}
`;var VO=`
#if LIT_CUBEMAP_PROJECTION == BOX
uniform envBoxMin: vec3f;
uniform envBoxMax: vec3f;
#endif
fn cubeMapProject(nrdir: vec3f) -> vec3f {
#if LIT_CUBEMAP_PROJECTION == NONE
return cubeMapRotate(nrdir);
#endif
#if LIT_CUBEMAP_PROJECTION == BOX
let nrdir_rotated: vec3f = cubeMapRotate(nrdir);
let rbmax: vec3f = (uniform.envBoxMax - vPositionW) / nrdir_rotated;
let rbmin: vec3f = (uniform.envBoxMin - vPositionW) / nrdir_rotated;
let rbminmax: vec3f = select(rbmin, rbmax, nrdir_rotated > vec3f(0.0));
let fa: f32 = min(min(rbminmax.x, rbminmax.y), rbminmax.z);
let posonbox: vec3f = vPositionW + nrdir_rotated * fa;
let envBoxPos: vec3f = (uniform.envBoxMin + uniform.envBoxMax) * 0.5;
return normalize(posonbox - envBoxPos);
#endif
}
`;var HO=`
#ifdef CUBEMAP_ROTATION
uniform cubeMapRotationMatrix: mat3x3f;
#endif
fn cubeMapRotate(refDir: vec3f) -> vec3f {
#ifdef CUBEMAP_ROTATION
return refDir * uniform.cubeMapRotationMatrix;
#else
return refDir;
#endif
}
`;var WO=`
#ifdef DEBUG_ALBEDO_PASS
output.color = vec4(gammaCorrectOutput(dAlbedo), 1.0);
#endif
#ifdef DEBUG_UV0_PASS
output.color = vec4f(litArgs_albedo , 1.0);
#endif
#ifdef DEBUG_WORLD_NORMAL_PASS
output.color = vec4f(litArgs_worldNormal * 0.5 + 0.5, 1.0);
#endif
#ifdef DEBUG_OPACITY_PASS
output.color = vec4f(vec3f(litArgs_opacity) , 1.0);
#endif
#ifdef DEBUG_SPECULARITY_PASS
output.color = vec4f(litArgs_specularity, 1.0);
#endif
#ifdef DEBUG_GLOSS_PASS
output.color = vec4f(vec3f(litArgs_gloss) , 1.0);
#endif
#ifdef DEBUG_METALNESS_PASS
output.color = vec4f(vec3f(litArgs_metalness) , 1.0);
#endif
#ifdef DEBUG_AO_PASS
output.color = vec4f(vec3f(litArgs_ao) , 1.0);
#endif
#ifdef DEBUG_EMISSION_PASS
output.color = vec4f(gammaCorrectOutput(litArgs_emission), 1.0);
#endif
`;var XO=`
#ifdef DEBUG_LIGHTING_PASS
litArgs_albedo = vec3f(0.5);
#endif
#ifdef DEBUG_UV0_PASS
#ifdef VARYING_VUV0
litArgs_albedo = vec3f(vUv0, 0.0);
#else
litArgs_albedo = vec3f(0.0);
#endif
#endif
`;var YO=`
#ifndef _DECODE_INCLUDED_
#define _DECODE_INCLUDED_
fn decodeLinear(raw: vec4f) -> vec3f {
return raw.rgb;
}
fn decodeGammaFloat(raw: f32) -> f32 {
return pow(raw, 2.2);
}
fn decodeGamma3(raw: vec3f) -> vec3f {
return pow(raw, vec3f(2.2));
}
fn decodeGamma(raw: vec4f) -> vec3f {
return pow(raw.xyz, vec3f(2.2));
}
fn decodeRGBM(raw: vec4f) -> vec3f {
let color = (8.0 * raw.a) * raw.rgb;
return color * color;
}
fn decodeRGBP(raw: vec4f) -> vec3f {
let color = raw.rgb * (-raw.a * 7.0 + 8.0);
return color * color;
}
fn decodeRGBE(raw: vec4f) -> vec3f {
return select(vec3f(0.0), raw.xyz * pow(2.0, raw.w * 255.0 - 128.0), raw.a != 0.0);
}
fn passThrough(raw: vec4f) -> vec4f {
return raw;
}
fn unpackNormalXYZ(nmap: vec4f) -> vec3f {
return nmap.xyz * 2.0 - 1.0;
}
fn unpackNormalXY(nmap: vec4f) -> vec3f {
var xy = nmap.wy * 2.0 - 1.0;
return vec3f(xy, sqrt(1.0 - clamp(dot(xy, xy), 0.0, 1.0)));
}
#endif
`;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() {
dEmission = uniform.material_emissive * uniform.material_emissiveIntensity;
#ifdef STD_EMISSIVE_TEXTURE
dEmission *= {STD_EMISSIVE_TEXTURE_DECODE}(textureSampleBias({STD_EMISSIVE_TEXTURE_NAME}, {STD_EMISSIVE_TEXTURE_NAME}Sampler, {STD_EMISSIVE_TEXTURE_UV}, uniform.textureBias)).{STD_EMISSIVE_TEXTURE_CHANNEL};
#endif
#ifdef STD_EMISSIVE_VERTEX
dEmission = dEmission * saturate3(vVertexColor.{STD_EMISSIVE_VERTEX_CHANNEL});
#endif
}
`;var $O=`
fn encodeLinear(source: vec3f) -> vec4f {
return vec4f(source, 1.0);
}
fn encodeGamma(source: vec3f) -> vec4f {
return vec4f(pow(source + vec3f(0.0000001), vec3f(1.0 / 2.2)), 1.0);
}
fn encodeRGBM(source: vec3f) -> vec4f {
var color: vec3f = pow(source, vec3f(0.5));
color *= 1.0 / 8.0;
var a: f32 = saturate(max(max(color.r, color.g), max(color.b, 1.0 / 255.0)));
a = ceil(a * 255.0) / 255.0;
color /= a;
return vec4f(color, a);
}
fn encodeRGBP(source: vec3f) -> vec4f {
var gamma: vec3f = pow(source, vec3f(0.5));
var maxVal: f32 = min(8.0, max(1.0, max(gamma.x, max(gamma.y, gamma.z))));
var v: f32 = 1.0 - ((maxVal - 1.0) / 7.0);
v = ceil(v * 255.0) / 255.0;
return vec4f(gamma / (-v * 7.0 + 8.0), v);
}
fn encodeRGBE(source: vec3f) -> vec4f {
var maxVal: f32 = max(source.x, max(source.y, source.z));
if (maxVal < 1e-32) {
return vec4f(0.0, 0.0, 0.0, 0.0);
} else {
var e: f32 = ceil(log2(maxVal));
return vec4f(source / pow(2.0, e), (e + 128.0) / 255.0);
}
}
`;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);
`;var QO=`
#ifndef _ENVATLAS_INCLUDED_
#define _ENVATLAS_INCLUDED_
const atlasSize : f32 = 512.0;
const seamSize : f32 = 1.0 / atlasSize;
fn mapUv(uv : vec2f, rect : vec4f) -> vec2f {
return vec2f(mix(rect.x + seamSize, rect.x + rect.z - seamSize, uv.x),
mix(rect.y + seamSize, rect.y + rect.w - seamSize, uv.y));
}
fn mapRoughnessUv(uv : vec2f, level : f32) -> vec2f {
let t : f32 = 1.0 / exp2(level);
return mapUv(uv, vec4f(0.0, 1.0 - t, t, t * 0.5));
}
fn mapShinyUv(uv : vec2f, level : f32) -> vec2f {
let t : f32 = 1.0 / exp2(level);
return mapUv(uv, vec4f(1.0 - t, 1.0 - t, t, t * 0.5));
}
#endif
`;var JO=`
#ifdef LIT_SKYBOX_INTENSITY
uniform skyboxIntensity : f32;
#endif
fn processEnvironment(color : vec3f) -> vec3f {
#ifdef LIT_SKYBOX_INTENSITY
return color * uniform.skyboxIntensity;
#else
return color;
#endif
}
`;var eF=`
fn getFalloffWindow(lightRadius: f32, lightDir: vec3f) -> f32 {
let sqrDist: f32 = dot(lightDir, lightDir);
let invRadius: f32 = 1.0 / lightRadius;
return square(saturate(1.0 - square(sqrDist * square(invRadius))));
}
fn getFalloffInvSquared(lightRadius: f32, lightDir: vec3f) -> f32 {
let sqrDist: f32 = dot(lightDir, lightDir);
var falloff: f32 = 1.0 / (sqrDist + 1.0);
let invRadius: f32 = 1.0 / lightRadius;
falloff = falloff * 16.0;
falloff = falloff * square(saturate(1.0 - square(sqrDist * square(invRadius))));
return falloff;
}
`;var tF=`
fn getFalloffLinear(lightRadius: f32, lightDir: vec3f) -> f32 {
let d: f32 = length(lightDir);
return max(((lightRadius - d) / lightRadius), 0.0);
}
`;var sF=`
#ifndef FLOAT_AS_UINT
#define FLOAT_AS_UINT
fn float2uint(value: f32) -> vec4f {
let intBits = bitcast<u32>(value);
return vec4f(
f32((intBits >> 24u) & 0xffu),
f32((intBits >> 16u) & 0xffu),
f32((intBits >> 8u) & 0xffu),
f32(intBits & 0xffu)
) / 255.0;
}
fn uint2float(value: vec4f) -> f32 {
let rgba_u32 = vec4<u32>(value * 255.0);
let intBits: u32 =
(rgba_u32.r << 24u) |
(rgba_u32.g << 16u) |
(rgba_u32.b << 8u) |
rgba_u32.a;
return bitcast<f32>(intBits);
}
fn float2vec4(value: f32) -> vec4f {
#if defined(CAPS_TEXTURE_FLOAT_RENDERABLE)
return vec4f(value, 1.0, 1.0, 1.0);
#else
return float2uint(value);
#endif
}
#endif
`;var iF=`
#include "fogMathPS"
var<private> dBlendModeFogFactor : f32 = 1.0;
#if (FOG != NONE)
uniform fog_color : vec3f;
#if (FOG == LINEAR)
uniform fog_start : f32;
uniform fog_end : f32;
#else
uniform fog_density : f32;
#endif
#endif
#ifdef VERTEXSHADER
fn getFogFactor(depth: f32) -> f32 {
#else
fn getFogFactor() -> f32 {
let depth = pcPosition.z / pcPosition.w;
#endif
#if (FOG == LINEAR)
return evaluateFogFactorLinear(depth, uniform.fog_start, uniform.fog_end);
#elif (FOG == EXP)
return evaluateFogFactorExp(depth, uniform.fog_density);
#elif (FOG == EXP2)
return evaluateFogFactorExp2(depth, uniform.fog_density);
#else
return 1.0;
#endif
}
#ifdef VERTEXSHADER
fn addFog(color: vec3f, depth: f32) -> vec3f {
#if (FOG != NONE)
return mix(uniform.fog_color * dBlendModeFogFactor, color, getFogFactor(depth));
#else
return color;
#endif
}
#else
fn addFog(color: vec3f) -> vec3f {
#if (FOG != NONE)
return mix(uniform.fog_color * dBlendModeFogFactor, color, getFogFactor());
#else
return color;
#endif
}
#endif
`;var rF=`
fn evaluateFogFactorLinear(depth: f32, fogStart: f32, fogEnd: f32) -> f32 {
return clamp((fogEnd - depth) / (fogEnd - fogStart), 0.0, 1.0);
}
fn evaluateFogFactorExp(depth: f32, fogDensity: f32) -> f32 {
return clamp(exp(-depth * fogDensity), 0.0, 1.0);
}
fn evaluateFogFactorExp2(depth: f32, fogDensity: f32) -> f32 {
return clamp(exp(-depth * depth * fogDensity * fogDensity), 0.0, 1.0);
}
`;var aF=`
fn pow5(x: f32) -> f32 {
let x2: f32 = x * x;
return x2 * x2 * x;
}
fn getFresnel(
cosTheta: f32,
gloss: f32,
specularity: vec3f
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel: vec3f,
iridescenceIntensity: f32
#endif
) -> vec3f {
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;
#if defined(LIT_IRIDESCENCE)
return mix(ret, iridescenceFresnel, iridescenceIntensity);
#else
return ret;
#endif
}
fn getFresnelCC(cosTheta: f32) -> f32 {
let fresnel: f32 = pow5(1.0 - saturate(cosTheta));
return 0.04 + (1.0 - 0.04) * fresnel;
}`;var oF=`
attribute vertex_position: vec2f;
varying vUv0: vec2f;
@vertex
fn vertexMain(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
output.position = vec4f(input.vertex_position, 0.5, 1.0);
output.vUv0 = input.vertex_position.xy * 0.5 + vec2f(0.5);
return output;
}
`;var nF=`
#include "decodePS"
#if (GAMMA == SRGB)
fn gammaCorrectInput(color: f32) -> f32 {
return decodeGammaFloat(color);
}
fn gammaCorrectInputVec3(color: vec3f) -> vec3f {
return decodeGamma3(color);
}
fn gammaCorrectInputVec4(color: vec4f) -> vec4f {
return vec4f(decodeGamma3(color.xyz), color.w);
}
fn gammaCorrectOutput(color: vec3f) -> vec3f {
return pow(color + 0.0000001, vec3f(1.0 / 2.2));
}
#else
fn gammaCorrectInput(color: f32) -> f32 {
return color;
}
fn gammaCorrectInputVec3(color: vec3f) -> vec3f {
return color;
}
fn gammaCorrectInputVec4(color: vec4f) -> vec4f {
return color;
}
fn gammaCorrectOutput(color: vec3f) -> vec3f {
return color;
}
#endif
`;var lF=`
#ifdef STD_GLOSS_CONSTANT
uniform material_gloss: f32;
#endif
fn getGlossiness() {
dGlossiness = 1.0;
#ifdef STD_GLOSS_CONSTANT
dGlossiness = dGlossiness * uniform.material_gloss;
#endif
#ifdef STD_GLOSS_TEXTURE
dGlossiness = dGlossiness * textureSampleBias({STD_GLOSS_TEXTURE_NAME}, {STD_GLOSS_TEXTURE_NAME}Sampler, {STD_GLOSS_TEXTURE_UV}, uniform.textureBias).{STD_GLOSS_TEXTURE_CHANNEL};
#endif
#ifdef STD_GLOSS_VERTEX
dGlossiness = dGlossiness * saturate(vVertexColor.{STD_GLOSS_VERTEX_CHANNEL});
#endif
#ifdef STD_GLOSS_INVERT
dGlossiness = 1.0 - dGlossiness;
#endif
dGlossiness = dGlossiness + 0.0000001;
}
`;var cF=`
attribute aPosition: vec2f;
varying uv0: vec2f;
@vertex fn vertexMain(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
output.position = vec4f(input.aPosition, 0.0, 1.0);
output.uv0 = getImageEffectUV((input.aPosition + 1.0) * 0.5);
return output;
}
`;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
fn fragmentMain(input : FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
output.color = vec4f(gammaCorrectOutput(decodeGamma3(input.color.rgb)), input.color.a);
return output;
}
`;var fF=`
attribute vertex_position: vec4f;
attribute vertex_color: vec4f;
uniform matrix_model: mat4x4f;
uniform matrix_viewProjection: mat4x4f;
varying color: vec4f;
@vertex
fn vertexMain(input : VertexInput) -> VertexOutput {
var output : VertexOutput;
output.color = input.vertex_color;
output.position = uniform.matrix_viewProjection * uniform.matrix_model * input.vertex_position;
return output;
}
`;var uF=`
uniform material_iridescenceRefractionIndex: f32;
fn iridescence_iorToFresnelScalar(transmittedIor: f32, incidentIor: f32) -> f32 {
return pow((transmittedIor - incidentIor) / (transmittedIor + incidentIor), 2.0);
}
fn iridescence_iorToFresnelVec3(transmittedIor: vec3f, incidentIor: f32) -> vec3f {
return pow((transmittedIor - vec3f(incidentIor)) / (transmittedIor + vec3f(incidentIor)), vec3f(2.0));
}
fn iridescence_fresnelToIor(f0: vec3f) -> vec3f {
let sqrtF0: vec3f = sqrt(f0);
return (vec3f(1.0) + sqrtF0) / (vec3f(1.0) - sqrtF0);
}
const XYZ_TO_REC709: mat3x3f = mat3x3f(
vec3f(3.2404542, -1.5371385, -0.4985314),
vec3f(-0.9692660, 1.8760108, 0.0415560),
vec3f(0.0556434, -0.2040259, 1.0572252)
);
fn iridescence_sensitivity(opd: f32, shift: vec3f) -> vec3f {
let PI: f32 = 3.141592653589793;
let phase: f32 = 2.0 * PI * opd * 1.0e-9;
const val: vec3f = vec3f(5.4856e-13, 4.4201e-13, 5.2481e-13);
const pos: vec3f = vec3f(1.6810e+06, 1.7953e+06, 2.2084e+06);
const var_: vec3f = vec3f(4.3278e+09, 9.3046e+09, 6.6121e+09);
var xyz: vec3f = val * sqrt(2.0 * PI * var_) * cos(pos * phase + shift) * exp(-pow(phase, 2.0) * var_);
xyz.x = xyz.x + 9.7470e-14 * sqrt(2.0 * PI * 4.5282e+09) * cos(2.2399e+06 * phase + shift[0]) * exp(-4.5282e+09 * pow(phase, 2.0));
xyz = xyz / vec3f(1.0685e-07);
return XYZ_TO_REC709 * xyz;
}
fn iridescence_fresnelScalar(cosTheta: f32, f0: f32) -> f32 {
let x: f32 = clamp(1.0 - cosTheta, 0.0, 1.0);
let x2: f32 = x * x;
let x5: f32 = x * x2 * x2;
return f0 + (1.0 - f0) * x5;
}
fn iridescence_fresnelVec3(cosTheta: f32, f0: vec3f) -> vec3f {
let x: f32 = clamp(1.0 - cosTheta, 0.0, 1.0);
let x2: f32 = x * x;
let x5: f32 = x * x2 * x2;
return f0 + (vec3f(1.0) - f0) * x5;
}
fn calcIridescence(outsideIor: f32, cosTheta: f32, base_f0: vec3f, iridescenceThickness: f32) -> vec3f {
let PI: f32 = 3.141592653589793;
let iridescenceIor: f32 = mix(outsideIor, uniform.material_iridescenceRefractionIndex, smoothstep(0.0, 0.03, iridescenceThickness));
let sinTheta2Sq: f32 = pow(outsideIor / iridescenceIor, 2.0) * (1.0 - pow(cosTheta, 2.0));
let cosTheta2Sq: f32 = 1.0 - sinTheta2Sq;
if (cosTheta2Sq < 0.0) {
return vec3f(1.0);
}
let cosTheta2: f32 = sqrt(cosTheta2Sq);
let r0: f32 = iridescence_iorToFresnelScalar(iridescenceIor, outsideIor);
let r12: f32 = iridescence_fresnelScalar(cosTheta, r0);
let r21: f32 = r12;
let t121: f32 = 1.0 - r12;
let phi12: f32 = select(0.0, PI, iridescenceIor < outsideIor);
let phi21: f32 = PI - phi12;
let baseIor: vec3f = iridescence_fresnelToIor(base_f0 + vec3f(0.0001));
let r1: vec3f = iridescence_iorToFresnelVec3(baseIor, iridescenceIor);
let r23: vec3f = iridescence_fresnelVec3(cosTheta2, r1);
let phi23: vec3f = select(vec3f(0.0), vec3f(PI), baseIor < vec3f(iridescenceIor));
let opd: f32 = 2.0 * iridescenceIor * iridescenceThickness * cosTheta2;
let phi: vec3f = vec3f(phi21) + phi23;
let r123Sq: vec3f = clamp(vec3f(r12) * r23, vec3f(1e-5), vec3f(0.9999));
let r123: vec3f = sqrt(r123Sq);
let rs: vec3f = pow(vec3f(t121), vec3f(2.0)) * r23 / (vec3f(1.0) - r123Sq);
let c0: vec3f = vec3f(r12) + rs;
var i_irid: vec3f = c0;
var cm: vec3f = rs - vec3f(t121);
cm = cm * r123;
let sm1: vec3f = 2.0 * iridescence_sensitivity(1.0 * opd, 1.0 * phi);
i_irid = i_irid + cm * sm1;
cm = cm * r123;
let sm2: vec3f = 2.0 * iridescence_sensitivity(2.0 * opd, 2.0 * phi);
i_irid = i_irid + cm * sm2;
return max(i_irid, vec3f(0.0));
}
fn getIridescenceDiffraction(cosTheta: f32, specularity: vec3f, iridescenceThickness: f32) -> vec3f {
return calcIridescence(1.0, cosTheta, specularity, iridescenceThickness);
}
`;var dF=`
#ifdef STD_IRIDESCENCE_CONSTANT
uniform material_iridescence: f32;
#endif
fn getIridescence() {
var iridescence = 1.0;
#ifdef STD_IRIDESCENCE_CONSTANT
iridescence = iridescence * uniform.material_iridescence;
#endif
#ifdef STD_IRIDESCENCE_TEXTURE
iridescence = iridescence * textureSampleBias({STD_IRIDESCENCE_TEXTURE_NAME}, {STD_IRIDESCENCE_TEXTURE_NAME}Sampler, {STD_IRIDESCENCE_TEXTURE_UV}, uniform.textureBias).{STD_IRIDESCENCE_TEXTURE_CHANNEL};
#endif
dIridescence = iridescence;
}
`;var pF=`
uniform material_iridescenceThicknessMax: f32;
#ifdef STD_IRIDESCENCETHICKNESS_TEXTURE
uniform material_iridescenceThicknessMin: f32;
#endif
fn getIridescenceThickness() {
#ifdef STD_IRIDESCENCETHICKNESS_TEXTURE
var blend: f32 = textureSampleBias({STD_IRIDESCENCETHICKNESS_TEXTURE_NAME}, {STD_IRIDESCENCETHICKNESS_TEXTURE_NAME}Sampler, {STD_IRIDESCENCETHICKNESS_TEXTURE_UV}, uniform.textureBias).{STD_IRIDESCENCETHICKNESS_TEXTURE_CHANNEL};
var iridescenceThickness: f32 = mix(uniform.material_iridescenceThicknessMin, uniform.material_iridescenceThicknessMax, blend);
#else
var iridescenceThickness: f32 = uniform.material_iridescenceThicknessMax;
#endif
dIridescenceThickness = iridescenceThickness;
}
`;var mF=`
#ifdef STD_IOR_CONSTANT
uniform material_refractionIndex: f32;
#endif
fn getIor() {
#ifdef STD_IOR_CONSTANT
dIor = uniform.material_refractionIndex;
#else
dIor = 1.0 / 1.5;
#endif
}
`;var _F=`
#if defined(LIGHT{i})
uniform light{i}_color: vec3f;
#if LIGHT{i}TYPE == DIRECTIONAL
uniform light{i}_direction: vec3f;
#else
#define LIT_CODE_LIGHTS_POINT
uniform light{i}_position: vec3f;
uniform light{i}_radius: f32;
#if LIGHT{i}TYPE == SPOT
#define LIT_CODE_LIGHTS_SPOT
uniform light{i}_direction: vec3f;
uniform light{i}_innerConeAngle: f32;
uniform light{i}_outerConeAngle: f32;
#endif
#endif
#if LIGHT{i}SHAPE != PUNCTUAL
#define LIT_CODE_FALLOFF_SQUARED
#if LIGHT{i}TYPE == DIRECTIONAL
uniform light{i}_position: vec3f;
#endif
uniform light{i}_halfWidth: vec3f;
uniform light{i}_halfHeight: vec3f;
#else
#if LIGHT{i}FALLOFF == LINEAR
#define LIT_CODE_FALLOFF_LINEAR
#endif
#if LIGHT{i}FALLOFF == INVERSESQUARED
#define LIT_CODE_FALLOFF_SQUARED
#endif
#endif
#if defined(LIGHT{i}CASTSHADOW)
#if LIGHT{i}TYPE != OMNI
uniform light{i}_shadowMatrix: mat4x4f;
#endif
uniform light{i}_shadowIntensity: f32;
uniform light{i}_shadowParams: vec4f;
#if LIGHT{i}SHADOWTYPE == PCSS_32F
uniform light{i}_shadowSearchArea: f32;
uniform light{i}_cameraParams: vec4f;
#if LIGHT{i}TYPE == DIRECTIONAL
uniform light{i}_softShadowParams: vec4f;
#endif
#endif
#if LIGHT{i}TYPE == DIRECTIONAL
uniform light{i}_shadowMatrixPalette: array<mat4x4f, 4>;
uniform light{i}_shadowCascadeDistances: vec4f;
uniform light{i}_shadowCascadeCount: i32;
uniform light{i}_shadowCascadeBlend: f32;
#endif
#if LIGHT{i}TYPE == OMNI
NOT SUPPORTED
#else
#if defined(LIGHT{i}SHADOW_PCF)
var light{i}_shadowMap: texture_depth_2d;
var light{i}_shadowMapSampler: sampler_comparison;
#else
var light{i}_shadowMap: texture_2d<f32>;
var light{i}_shadowMapSampler: sampler;
#endif
#endif
#endif
#if defined(LIGHT{i}COOKIE)
#define LIT_CODE_COOKIE
#if LIGHT{i}TYPE == OMNI
NOT SUPPORTED
#endif
#if LIGHT{i}TYPE == SPOT
NOT SUPPORTED
#endif
#endif
#endif
`;var gF=`
fn getLightDiffuse(worldNormal: vec3f, viewDir: vec3f, lightDirNorm: vec3f) -> f32 {
return max(dot(worldNormal, -lightDirNorm), 0.0);
}
`;var SF=`
fn evalOmniLight(lightPosW: vec3f) -> vec3f {
return vPositionW - lightPosW;
}
`;var xF=`
#if defined(LIGHT{i})
evaluateLight{i}(
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel
#endif
);
#endif
`;var vF=`
#if defined(LIGHT{i})
fn evaluateLight{i}(
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel: vec3f
#endif
) {
var lightColor: vec3f = uniform.light{i}_color;
#if LIGHT{i}TYPE == DIRECTIONAL && !defined(LIT_SHADOW_CATCHER)
if (all(lightColor == vec3f(0.0, 0.0, 0.0))) {
return;
}
#endif
#if LIGHT{i}TYPE == DIRECTIONAL
dLightDirNormW = uniform.light{i}_direction;
dAtten = 1.0;
#else
var lightDirW: vec3f = evalOmniLight(uniform.light{i}_position);
dLightDirNormW = normalize(lightDirW);
#if defined(LIGHT{i}COOKIE)
#if LIGHT{i}TYPE == SPOT
#ifdef LIGHT{i}COOKIE_FALLOFF
#ifdef LIGHT{i}COOKIE_TRANSFORM
var cookieAttenuation: vec3f = getCookie2DXform(uniform.light{i}_cookie, uniform.light{i}_shadowMatrix, uniform.light{i}_cookieIntensity, uniform.light{i}_cookieMatrix, uniform.light{i}_cookieOffset).{LIGHT{i}COOKIE_CHANNEL};
#else
var cookieAttenuation: vec3f = getCookie2D(uniform.light{i}_cookie, uniform.light{i}_shadowMatrix, uniform.light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL};
#endif
#else
#ifdef LIGHT{i}COOKIE_TRANSFORM
var cookieAttenuation: vec3f = getCookie2DClipXform(uniform.light{i}_cookie, uniform.light{i}_shadowMatrix, uniform.light{i}_cookieIntensity, uniform.light{i}_cookieMatrix, uniform.light{i}_cookieOffset).{LIGHT{i}COOKIE_CHANNEL};
#else
var cookieAttenuation: vec3f = getCookie2DClip(uniform.light{i}_cookie, uniform.light{i}_shadowMatrix, uniform.light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL};
#endif
#endif
#endif
#if LIGHT{i}TYPE == OMNI
var cookieAttenuation: vec3f = getCookieCube(uniform.light{i}_cookie, uniform.light{i}_shadowMatrix, uniform.light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL};
#endif
lightColor = lightColor * cookieAttenuation;
#endif
#if LIGHT{i}SHAPE == PUNCTUAL
#if LIGHT{i}FALLOFF == LINEAR
dAtten = getFalloffLinear(uniform.light{i}_radius, lightDirW);
#else
dAtten = getFalloffInvSquared(uniform.light{i}_radius, lightDirW);
#endif
#else
dAtten = getFalloffWindow(uniform.light{i}_radius, lightDirW);
#endif
#if LIGHT{i}TYPE == SPOT
#if !defined(LIGHT{i}COOKIE) || defined(LIGHT{i}COOKIE_FALLOFF)
dAtten = dAtten * getSpotEffect(uniform.light{i}_direction, uniform.light{i}_innerConeAngle, uniform.light{i}_outerConeAngle, dLightDirNormW);
#endif
#endif
#endif
if (dAtten < 0.00001) {
return;
}
#if LIGHT{i}SHAPE != PUNCTUAL
#if LIGHT{i}SHAPE == RECT
calcRectLightValues(uniform.light{i}_position, uniform.light{i}_halfWidth, uniform.light{i}_halfHeight);
#elif LIGHT{i}SHAPE == DISK
calcDiskLightValues(uniform.light{i}_position, uniform.light{i}_halfWidth, uniform.light{i}_halfHeight);
#elif LIGHT{i}SHAPE == SPHERE
calcSphereLightValues(uniform.light{i}_position, uniform.light{i}_halfWidth, uniform.light{i}_halfHeight);
#endif
#endif
#if LIGHT{i}SHAPE != PUNCTUAL
#if LIGHT{i}TYPE == DIRECTIONAL
var attenDiffuse: f32 = getLightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirNormW);
#else
#if LIGHT{i}SHAPE == RECT
var attenDiffuse: f32 = getRectLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0;
#elif LIGHT{i}SHAPE == DISK
var attenDiffuse: f32 = getDiskLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0;
#elif LIGHT{i}SHAPE == SPHERE
var attenDiffuse: f32 = getSphereLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0;
#endif
#endif
#else
dAtten = dAtten * getLightDiffuse(litArgs_worldNormal, vec3(0.0), dLightDirNormW);
#endif
#ifdef LIGHT{i}CASTSHADOW
#if LIGHT{i}TYPE == DIRECTIONAL
var shadow: f32 = getShadow{i}(vec3(0.0));
#else
var shadow: f32 = getShadow{i}(lightDirW);
#endif
shadow = mix(1.0, shadow, uniform.light{i}_shadowIntensity);
dAtten = dAtten * shadow;
#if defined(LIT_SHADOW_CATCHER) && LIGHT{i}TYPE == DIRECTIONAL
dShadowCatcher = dShadowCatcher * shadow;
#endif
#endif
#if LIGHT{i}SHAPE != PUNCTUAL
#ifdef LIT_SPECULAR
dDiffuseLight = dDiffuseLight + (((attenDiffuse * dAtten) * lightColor) * (1.0 - dLTCSpecFres));
#else
dDiffuseLight = dDiffuseLight + ((attenDiffuse * dAtten) * lightColor);
#endif
#else
#if defined(AREA_LIGHTS) && defined(LIT_SPECULAR)
dDiffuseLight = dDiffuseLight + ((dAtten * lightColor) * (1.0 - litArgs_specularity));
#else
dDiffuseLight = dDiffuseLight + (dAtten * lightColor);
#endif
#endif
#ifdef LIGHT{i}AFFECT_SPECULARITY
#if LIGHT{i}SHAPE != PUNCTUAL
#ifdef LIT_CLEARCOAT
#if LIGHT{i}SHAPE == RECT
ccSpecularLight = ccSpecularLight + (ccLTCSpecFres * getRectLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor);
#elif LIGHT{i}SHAPE == DISK
ccSpecularLight = ccSpecularLight + (ccLTCSpecFres * getDiskLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor);
#elif LIGHT{i}SHAPE == SPHERE
ccSpecularLight = ccSpecularLight + (ccLTCSpecFres * getSphereLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor);
#endif
#endif
#ifdef LIT_SPECULAR
#if LIGHT{i}SHAPE == RECT
dSpecularLight = dSpecularLight + (dLTCSpecFres * getRectLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor);
#elif LIGHT{i}SHAPE == DISK
dSpecularLight = dSpecularLight + (dLTCSpecFres * getDiskLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor);
#elif LIGHT{i}SHAPE == SPHERE
dSpecularLight = dSpecularLight + (dLTCSpecFres * getSphereLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor);
#endif
#endif
#else
#if LIGHT{i}TYPE == DIRECTIONAL && LIT_FRESNEL_MODEL != NONE
#define LIGHT{i}FRESNEL
#endif
#ifdef LIT_SPECULAR
var halfDirW: vec3f = normalize(-dLightDirNormW + dViewDirW);
#endif
#ifdef LIT_CLEARCOAT
var lightspecularCC: vec3f = getLightSpecular(halfDirW, ccReflDirW, litArgs_clearcoat_worldNormal, dViewDirW, dLightDirNormW, litArgs_clearcoat_gloss, dTBN) * dAtten * lightColor;
#ifdef LIGHT{i}FRESNEL
lightspecularCC = lightspecularCC * getFresnelCC(dot(dViewDirW, halfDirW));
#endif
ccSpecularLight = ccSpecularLight + lightspecularCC;
#endif
#ifdef LIT_SHEEN
sSpecularLight = sSpecularLight + (getLightSpecularSheen(halfDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_sheen_gloss) * dAtten * lightColor);
#endif
#ifdef LIT_SPECULAR
var lightSpecular: vec3f = getLightSpecular(halfDirW, dReflDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_gloss, dTBN) * dAtten * lightColor;
#ifdef LIGHT{i}FRESNEL
#if defined(LIT_IRIDESCENCE)
lightSpecular = lightSpecular * getFresnel(dot(dViewDirW, halfDirW), litArgs_gloss, litArgs_specularity, iridescenceFresnel, litArgs_iridescence_intensity);
#else
lightSpecular = lightSpecular * getFresnel(dot(dViewDirW, halfDirW), litArgs_gloss, litArgs_specularity);
#endif
#else
lightSpecular = lightSpecular * litArgs_specularity;
#endif
dSpecularLight = dSpecularLight + lightSpecular;
#endif
#endif
#endif
}
#endif
`;var TF=`
#ifdef LIGHT{i}CASTSHADOW
#ifdef LIGHT{i}_SHADOW_SAMPLE_POINT
fn getShadowSampleCoordOmni{i}(shadowParams: vec4f, worldPosition: vec3f, lightPos: vec3f, lightDir: ptr<function, vec3f>, lightDirNorm: vec3f, normal: vec3f) -> vec3f {
#ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET
let distScale: f32 = length(*lightDir);
var surfacePosition = worldPosition + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;
*lightDir = surfacePosition - lightPos;
#endif
return *lightDir;
}
#endif
#ifndef LIGHT{i}_SHADOW_SAMPLE_POINT
fn getShadowSampleCoord{i}(shadowTransform: mat4x4f, shadowParams: vec4f, worldPosition: vec3f, lightPos: vec3f, lightDir: ptr<function, vec3f>, lightDirNorm: vec3f, normal: vec3f) -> vec3f {
var surfacePosition = worldPosition;
#ifdef LIGHT{i}_SHADOW_SAMPLE_SOURCE_ZBUFFER
#ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET
surfacePosition = surfacePosition + normal * shadowParams.y;
#endif
#else
#ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET
#ifdef LIGHT{i}_SHADOW_SAMPLE_ORTHO
var distScale: f32 = 1.0;
#else
var distScale: f32 = abs(dot(vPositionW - lightPos, lightDirNorm));
#endif
surfacePosition = surfacePosition + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale;
#endif
#endif
var positionInShadowSpace: vec4f = shadowTransform * vec4f(surfacePosition, 1.0);
#ifdef LIGHT{i}_SHADOW_SAMPLE_ORTHO
positionInShadowSpace.z = saturate(positionInShadowSpace.z) - 0.0001;
#else
#ifdef LIGHT{i}_SHADOW_SAMPLE_SOURCE_ZBUFFER
positionInShadowSpace.xyz = positionInShadowSpace.xyz / positionInShadowSpace.w;
#else
positionInShadowSpace.xy = positionInShadowSpace.xy / positionInShadowSpace.w;
positionInShadowSpace.z = length(*lightDir) * shadowParams.w;
#endif
#endif
return positionInShadowSpace.xyz;
}
#endif
fn getShadow{i}(lightDirW_in: vec3f) -> f32 {
var lightDirArg = lightDirW_in;
#if LIGHT{i}TYPE == OMNI
var shadowCoord: vec3f = getShadowSampleCoordOmni{i}(uniform.light{i}_shadowParams, vPositionW, uniform.light{i}_position, &lightDirArg, dLightDirNormW, dVertexNormalW);
#else
#ifdef LIGHT{i}_SHADOW_CASCADES
var cascadeIndex: i32 = getShadowCascadeIndex(uniform.light{i}_shadowCascadeDistances, uniform.light{i}_shadowCascadeCount);
#ifdef LIGHT{i}_SHADOW_CASCADE_BLEND
cascadeIndex = ditherShadowCascadeIndex(cascadeIndex, uniform.light{i}_shadowCascadeDistances, uniform.light{i}_shadowCascadeCount, uniform.light{i}_shadowCascadeBlend);
#endif
var shadowMatrix: mat4x4f = uniform.light{i}_shadowMatrixPalette[cascadeIndex];
#else
var shadowMatrix: mat4x4f = uniform.light{i}_shadowMatrix;
#endif
#if LIGHT{i}TYPE == DIRECTIONAL
var shadowCoord: vec3f = getShadowSampleCoord{i}(shadowMatrix, uniform.light{i}_shadowParams, vPositionW, vec3f(0.0), &lightDirArg, dLightDirNormW, dVertexNormalW);
#else
var shadowCoord: vec3f = getShadowSampleCoord{i}(shadowMatrix, uniform.light{i}_shadowParams, vPositionW, uniform.light{i}_position, &lightDirArg, dLightDirNormW, dVertexNormalW);
#endif
#endif
#if LIGHT{i}TYPE == DIRECTIONAL
shadowCoord = fadeShadow(shadowCoord, uniform.light{i}_shadowCascadeDistances);
#endif
#if LIGHT{i}TYPE == DIRECTIONAL
#if LIGHT{i}SHADOWTYPE == VSM_16F
return getShadowVSM16(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, 5.54);
#endif
#if LIGHT{i}SHADOWTYPE == VSM_32F
return getShadowVSM32(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, 15.0);
#endif
#if LIGHT{i}SHADOWTYPE == PCSS_32F
#if LIGHT{i}SHAPE != PUNCTUAL
let shadowSearchArea = vec2f(length(uniform.light{i}_halfWidth), length(uniform.light{i}_halfHeight)) * uniform.light{i}_shadowSearchArea;
return getShadowPCSS(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, uniform.light{i}_cameraParams, shadowSearchArea, lightDirW_in);
#else
return getShadowPCSS(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, uniform.light{i}_cameraParams, uniform.light{i}_softShadowParams, lightDirW_in);
#endif
#endif
#if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F
return getShadowPCF1x1(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams);
#endif
#if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F
return getShadowPCF3x3(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams);
#endif
#if LIGHT{i}SHADOWTYPE == PCF5_16F || LIGHT{i}SHADOWTYPE == PCF5_32F
return getShadowPCF5x5(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams);
#endif
#endif
#if LIGHT{i}TYPE == SPOT
#if LIGHT{i}SHADOWTYPE == VSM_16F
return getShadowSpotVSM16(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, 5.54, lightDirW_in);
#endif
#if LIGHT{i}SHADOWTYPE == VSM_32F
return getShadowSpotVSM32(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, 15.0, lightDirW_in);
#endif
#if LIGHT{i}SHADOWTYPE == PCSS_32F
#if LIGHT{i}SHAPE != PUNCTUAL
var shadowSearchArea: vec2f = vec2f(length(uniform.light{i}_halfWidth), length(uniform.light{i}_halfHeight)) * uniform.light{i}_shadowSearchArea;
#else
var shadowSearchArea: vec2f = vec2f(uniform.light{i}_shadowSearchArea);
#endif
return getShadowSpotPCSS(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, uniform.light{i}_cameraParams, shadowSearchArea, lightDirW_in);
#endif
#if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F
return getShadowSpotPCF1x1(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams);
#endif
#if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F
return getShadowSpotPCF3x3(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams);
#endif
#if LIGHT{i}SHADOWTYPE == PCF5_16F || LIGHT{i}SHADOWTYPE == PCF5_32F
return getShadowSpotPCF5x5(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams);
#endif
#endif
#if LIGHT{i}TYPE == OMNI
#if LIGHT{i}SHADOWTYPE == PCSS_32F
var shadowSearchArea: vec2f;
#if LIGHT{i}SHAPE != PUNCTUAL
var shadowSearchArea: vec2f = vec2f(length(uniform.light{i}_halfWidth), length(uniform.light{i}_halfHeight)) * uniform.light{i}_shadowSearchArea;
#else
var shadowSearchArea: vec2f = vec2f(uniform.light{i}_shadowSearchArea);
#endif
return getShadowOmniPCSS(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, uniform.light{i}_cameraParams, shadowSearchArea, lightDirW_in);
#endif
#if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F
return getShadowOmniPCF1x1(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, lightDirW_in);
#endif
#if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F
return getShadowOmniPCF3x3(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, lightDirW_in);
#endif
#endif
}
#endif
`;var yF=`
#ifdef LIT_CLUSTERED_LIGHTS
#define LIT_CODE_FALLOFF_LINEAR
#define LIT_CODE_FALLOFF_SQUARED
#define LIT_CODE_LIGHTS_POINT
#define LIT_CODE_LIGHTS_SPOT
#endif
#ifdef AREA_LIGHTS
var areaLightsLutTex1: texture_2d<f32>;
var areaLightsLutTex1Sampler: sampler;
var areaLightsLutTex2: texture_2d<f32>;
var areaLightsLutTex2Sampler: sampler;
#endif
#ifdef LIT_LIGHTING
#include "lightDiffuseLambertPS"
#if defined(AREA_LIGHTS) || defined(LIT_CLUSTERED_AREA_LIGHTS)
#include "ltcPS"
#endif
#endif
#ifdef SHADOW_DIRECTIONAL
#include "shadowCascadesPS"
#endif
#if defined(SHADOW_KIND_PCF1)
#include "shadowPCF1PS"
#endif
#if defined(SHADOW_KIND_PCF3)
#include "shadowPCF3PS"
#endif
#if defined(SHADOW_KIND_PCF5)
#include "shadowPCF5PS"
#endif
#if defined(SHADOW_KIND_PCSS)
#include "linearizeDepthPS"
#include "shadowSoftPS"
#endif
#if defined(SHADOW_KIND_VSM)
#include "shadowEVSMPS"
#endif
#ifdef LIT_CODE_FALLOFF_LINEAR
#include "falloffLinearPS"
#endif
#ifdef LIT_CODE_FALLOFF_SQUARED
#include "falloffInvSquaredPS"
#endif
#ifdef LIT_CODE_LIGHTS_POINT
#include "lightDirPointPS"
#endif
#ifdef LIT_CODE_LIGHTS_SPOT
#include "spotPS"
#endif
#ifdef LIT_CODE_COOKIE
#include "cookiePS"
#endif
#ifdef LIT_CLUSTERED_LIGHTS
#include "clusteredLightPS"
#endif
#ifdef LIGHT_COUNT > 0
#include "lightFunctionShadowPS, LIGHT_COUNT"
#include "lightFunctionLightPS, LIGHT_COUNT"
#endif
`;var EF=`
fn addLightMap(
lightmap: vec3f,
dir: vec3f,
worldNormal: vec3f,
viewDir: vec3f,
reflectionDir: vec3f,
gloss: f32,
specularity: vec3f,
vertexNormal: vec3f,
tbn: mat3x3f
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel: vec3f,
iridescenceIntensity: f32
#endif
) {
#if defined(LIT_SPECULAR) && defined(LIT_DIR_LIGHTMAP)
if (dot(dir, dir) < 0.0001) {
dDiffuseLight = dDiffuseLight + lightmap;
} else {
let vlight: f32 = saturate(dot(dir, -vertexNormal));
let flight: f32 = saturate(dot(dir, -worldNormal));
let nlight: f32 = (flight / max(vlight, 0.01)) * 0.5;
dDiffuseLight = dDiffuseLight + lightmap * nlight * 2.0;
let halfDir: vec3f = normalize(-dir + viewDir);
var specularLight: vec3f = lightmap * getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, dir, gloss, tbn);
#ifdef LIT_SPECULAR_FRESNEL
specularLight = specularLight *
getFresnel(dot(viewDir, halfDir),
gloss,
specularity
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
iridescenceIntensity
#endif
);
#endif
dSpecularLight = dSpecularLight + specularLight;
}
#else
dDiffuseLight = dDiffuseLight + lightmap;
#endif
}
`;var AF=`
#ifdef STD_LIGHTMAP_DIR
var<private> dLightmapDir: vec3f;
var texture_dirLightMap: texture_2d<f32>;
var texture_dirLightMapSampler: sampler;
#endif
fn getLightMap() {
dLightmap = vec3f(1.0);
#ifdef STD_LIGHT_TEXTURE
dLightmap = dLightmap * {STD_LIGHT_TEXTURE_DECODE}(textureSampleBias({STD_LIGHT_TEXTURE_NAME}, {STD_LIGHT_TEXTURE_NAME}Sampler, {STD_LIGHT_TEXTURE_UV}, uniform.textureBias)).{STD_LIGHT_TEXTURE_CHANNEL};
#ifdef STD_LIGHTMAP_DIR
var dir: vec3f = textureSampleBias(texture_dirLightMap, texture_dirLightMapSampler, {STD_LIGHT_TEXTURE_UV}, uniform.textureBias).xyz * 2.0 - 1.0;
var dirDot = dot(dir, dir);
dLightmapDir = select(vec3(0.0), dir / sqrt(dirDot), dirDot > 0.001);
#endif
#endif
#ifdef STD_LIGHT_VERTEX
dLightmap = dLightmap * saturate(vVertexColor.{STD_LIGHT_VERTEX_CHANNEL});
#endif
}
`;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);
let alphaRoughness: f32 = roughness * roughness;
let anisotropy: f32 = dAnisotropy;
let direction: vec2f = dAnisotropyRotation;
let at: f32 = mix(alphaRoughness, 1.0, anisotropy * anisotropy);
let ab: f32 = clamp(alphaRoughness, 0.001, 1.0);
let anisotropicT: vec3f = normalize(tbn * vec3f(direction, 0.0));
let anisotropicB: vec3f = normalize(cross(tbn[2], anisotropicT));
let NoH: f32 = dot(worldNormal, h);
let ToH: f32 = dot(anisotropicT, h);
let BoH: f32 = dot(anisotropicB, h);
let a2: f32 = at * ab;
let v: vec3f = vec3f(ab * ToH, at * BoH, a2 * NoH);
let v2: f32 = dot(v, v);
let w2: f32 = a2 / v2;
let D: f32 = a2 * w2 * w2 * (1.0 / PI);
let ToV: f32 = dot(anisotropicT, viewDir);
let BoV: f32 = dot(anisotropicB, viewDir);
let ToL: f32 = dot(anisotropicT, -lightDirNorm);
let BoL: f32 = dot(anisotropicB, -lightDirNorm);
let NoV: f32 = dot(worldNormal, viewDir);
let NoL: f32 = dot(worldNormal, -lightDirNorm);
let lambdaV: f32 = NoL * length(vec3f(at * ToV, ab * BoV, NoV));
let lambdaL: f32 = NoV * length(vec3f(at * ToL, ab * BoL, NoL));
let G: f32 = 0.5 / (lambdaV + lambdaL);
return D * G;
}
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);
}
`;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);
let alpha: f32 = roughness * roughness;
let NoH: f32 = max(dot(worldNormal, h), 0.0);
let NoV: f32 = max(dot(worldNormal, viewDir), 0.0);
let NoL: f32 = max(dot(worldNormal, -lightDirNorm), 0.0);
let NoH2: f32 = NoH * NoH;
let denom: f32 = NoH2 * (alpha - 1.0) + 1.0;
let D: f32 = alpha / (PI * denom * denom);
let alpha2: f32 = alpha * alpha;
let lambdaV: f32 = NoL * sqrt(NoV * NoV * (1.0 - alpha2) + alpha2);
let lambdaL: f32 = NoV * sqrt(NoL * NoL * (1.0 - alpha2) + alpha2);
let G: f32 = 0.5 / max(lambdaV + lambdaL, 0.00001);
return D * G;
}
fn getLightSpecular(h: vec3f, reflDir: vec3f, worldNormal: vec3f, viewDir: vec3f, lightDirNorm: vec3f, gloss: f32, tbn: mat3x3f) -> f32 {
return calcLightSpecular(gloss, worldNormal, viewDir, h, lightDirNorm);
}
`;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);
specPow = max(specPow, 0.0001);
return pow(nh, specPow) * (specPow + 2.0) / 8.0;
}
fn getLightSpecular(h: vec3f, reflDir: vec3f, worldNormal: vec3f, viewDir: vec3f, lightDirNorm: vec3f, gloss: f32, tbn: mat3x3f) -> f32 {
return calcLightSpecular(gloss, worldNormal, h);
}
`;var IF=`
fn sheenD(normal: vec3f, h: vec3f, roughness: f32) -> f32 {
let PI: f32 = 3.141592653589793;
let invR: f32 = 1.0 / (roughness * roughness);
var cos2h: f32 = max(dot(normal, h), 0.0);
cos2h = cos2h * cos2h;
let sin2h: f32 = max(1.0 - cos2h, 0.0078125);
return (2.0 + invR) * pow(sin2h, invR * 0.5) / (2.0 * PI);
}
fn sheenV(normal: vec3f, viewDir: vec3f, light: vec3f) -> f32 {
let NoV: f32 = max(dot(normal, viewDir), 0.000001);
let NoL: f32 = max(dot(normal, light), 0.000001);
return 1.0 / (4.0 * (NoL + NoV - NoL * NoV));
}
fn getLightSpecularSheen(h: vec3f, worldNormal: vec3f, viewDir: vec3f, lightDirNorm: vec3f, sheenGloss: f32) -> f32 {
let D: f32 = sheenD(worldNormal, h, sheenGloss);
let V: f32 = sheenV(worldNormal, viewDir, -lightDirNorm);
return D * V;
}`;var RF=`
#ifndef LINEARIZE_DEPTH
#define LINEARIZE_DEPTH
fn linearizeDepthWithParams(z: f32, cameraParams: vec4f) -> f32 {
if (cameraParams.w == 0.0) {
return (cameraParams.z * cameraParams.y) / (cameraParams.y + z * (cameraParams.z - cameraParams.y));
} else {
return cameraParams.z + z * (cameraParams.y - cameraParams.z);
}
}
#ifndef CAMERAPLANES
#define CAMERAPLANES
uniform camera_params: vec4f;
#endif
fn linearizeDepth(z: f32) -> f32 {
return linearizeDepthWithParams(z, uniform.camera_params);
}
#endif
`;var bF=`
fn evaluateBackend() -> FragmentOutput {
var output: FragmentOutput;
#ifdef LIT_SSAO
litArgs_ao = litArgs_ao * textureSampleLevel(ssaoTexture, ssaoTextureSampler, pcPosition.xy * uniform.ssaoTextureSizeInv, 0.0).r;
#endif
#ifdef LIT_NEEDS_NORMAL
#ifdef LIT_SPECULAR
getReflDir(litArgs_worldNormal, dViewDirW, litArgs_gloss, dTBN);
#endif
#ifdef LIT_CLEARCOAT
ccReflDirW = normalize(-reflect(dViewDirW, litArgs_clearcoat_worldNormal));
#endif
#endif
#ifdef LIT_SPECULAR_OR_REFLECTION
#ifdef LIT_METALNESS
var f0: f32 = 1.0 / litArgs_ior;
f0 = (f0 - 1.0) / (f0 + 1.0);
f0 = f0 * f0;
#ifdef LIT_SPECULARITY_FACTOR
litArgs_specularity = getSpecularModulate(litArgs_specularity, litArgs_albedo, litArgs_metalness, f0, litArgs_specularityFactor);
#else
litArgs_specularity = getSpecularModulate(litArgs_specularity, litArgs_albedo, litArgs_metalness, f0, 1.0);
#endif
litArgs_albedo = getAlbedoModulate(litArgs_albedo, litArgs_metalness);
#endif
#ifdef LIT_IRIDESCENCE
var iridescenceFresnel: vec3f = getIridescenceDiffraction(saturate(dot(dViewDirW, litArgs_worldNormal)), litArgs_specularity, litArgs_iridescence_thickness);
#endif
#endif
#ifdef LIT_ADD_AMBIENT
addAmbient(litArgs_worldNormal);
#ifdef LIT_SPECULAR
dDiffuseLight = dDiffuseLight * (1.0 - litArgs_specularity);
#endif
#ifdef LIT_SEPARATE_AMBIENT
var dAmbientLight: vec3f = dDiffuseLight;
dDiffuseLight = vec3(0.0);
#endif
#endif
#ifndef LIT_OLD_AMBIENT
dDiffuseLight = dDiffuseLight * uniform.material_ambient;
#endif
#ifdef LIT_AO
#ifndef LIT_OCCLUDE_DIRECT
occludeDiffuse(litArgs_ao);
#endif
#endif
#ifdef LIT_LIGHTMAP
addLightMap(
litArgs_lightmap,
litArgs_lightmapDir,
litArgs_worldNormal,
dViewDirW,
dReflDirW,
litArgs_gloss,
litArgs_specularity,
dVertexNormalW,
dTBN
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
litArgs_iridescence_intensity
#endif
);
#endif
#ifdef LIT_LIGHTING || LIT_REFLECTIONS
#ifdef LIT_REFLECTIONS
#ifdef LIT_CLEARCOAT
addReflectionCC(ccReflDirW, litArgs_clearcoat_gloss);
#ifdef LIT_SPECULAR_FRESNEL
ccFresnel = getFresnelCC(dot(dViewDirW, litArgs_clearcoat_worldNormal));
ccReflection = ccReflection * ccFresnel;
#else
ccFresnel = 0.0;
#endif
#endif
#ifdef LIT_SPECULARITY_FACTOR
ccReflection = ccReflection * litArgs_specularityFactor;
#endif
#ifdef LIT_SHEEN
addReflectionSheen(litArgs_worldNormal, dViewDirW, litArgs_sheen_gloss);
#endif
addReflection(dReflDirW, litArgs_gloss);
#ifdef LIT_FRESNEL_MODEL
dReflection = vec4f(
dReflection.rgb * getFresnel(
dot(dViewDirW, litArgs_worldNormal),
litArgs_gloss,
litArgs_specularity
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
litArgs_iridescence_intensity
#endif
),
dReflection.a
);
#else
dReflection = vec4f(dReflection.rgb * litArgs_specularity, dReflection.a);
#endif
#endif
#ifdef AREA_LIGHTS
dSpecularLight = dSpecularLight * litArgs_specularity;
#ifdef LIT_SPECULAR
calcLTCLightValues(litArgs_gloss, litArgs_worldNormal, dViewDirW, litArgs_specularity, litArgs_clearcoat_gloss, litArgs_clearcoat_worldNormal, litArgs_clearcoat_specularity);
#endif
#endif
#ifdef LIGHT_COUNT > 0
#include "lightEvaluationPS, LIGHT_COUNT"
#endif
#ifdef LIT_CLUSTERED_LIGHTS
addClusteredLights(litArgs_worldNormal, dViewDirW, dReflDirW,
#if defined(LIT_CLEARCOAT)
ccReflDirW,
#endif
litArgs_gloss, litArgs_specularity, dVertexNormalW, dTBN,
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel,
#endif
litArgs_clearcoat_worldNormal, litArgs_clearcoat_gloss, litArgs_sheen_gloss, litArgs_iridescence_intensity
);
#endif
#ifdef AREA_LIGHTS
#ifdef LIT_CLEARCOAT
litArgs_clearcoat_specularity = 1.0;
#endif
#ifdef LIT_SPECULAR
litArgs_specularity = vec3(1.0);
#endif
#endif
#ifdef LIT_REFRACTION
addRefraction(
litArgs_worldNormal,
dViewDirW,
litArgs_thickness,
litArgs_gloss,
litArgs_specularity,
litArgs_albedo,
litArgs_transmission,
litArgs_ior,
litArgs_dispersion
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
litArgs_iridescence_intensity
#endif
);
#endif
#endif
#ifdef LIT_AO
#ifdef LIT_OCCLUDE_DIRECT
occludeDiffuse(litArgs_ao);
#endif
#if LIT_OCCLUDE_SPECULAR != NONE
occludeSpecular(litArgs_gloss, litArgs_ao, litArgs_worldNormal, dViewDirW);
#endif
#endif
#if !defined(LIT_OPACITY_FADES_SPECULAR)
#if LIT_BLEND_TYPE == NORMAL || LIT_BLEND_TYPE == PREMULTIPLIED
var specLum: f32 = dot((dSpecularLight + dReflection.rgb * dReflection.a), vec3f( 0.2126, 0.7152, 0.0722 ));
#ifdef LIT_CLEARCOAT
specLum = specLum + dot(ccSpecularLight * litArgs_clearcoat_specularity + ccReflection * litArgs_clearcoat_specularity, vec3f( 0.2126, 0.7152, 0.0722 ));
#endif
litArgs_opacity = clamp(litArgs_opacity + gammaCorrectInput(specLum), 0.0, 1.0);
#endif
litArgs_opacity = litArgs_opacity * uniform.material_alphaFade;
#endif
#ifdef LIT_LIGHTMAP_BAKING
#ifdef LIT_LIGHTMAP_BAKING_COLOR
#include "bakeLmEndPS"
#endif
#ifdef LIT_LIGHTMAP_BAKING_DIR
#include "bakeDirLmEndPS"
#endif
#else
#include "endPS"
#include "outputAlphaPS"
#endif
#ifdef LIT_MSDF
output.color = applyMsdf(output.color);
#endif
#include "outputPS"
#include "debugOutputPS"
#ifdef LIT_SHADOW_CATCHER
output.color = vec4f(vec3f(dShadowCatcher), output.color.a);
#endif
return output;
}
`;var DF=`
var<private> sReflection: vec3f;
var<private> dVertexNormalW: vec3f;
var<private> dTangentW: vec3f;
var<private> dBinormalW: vec3f;
var<private> dViewDirW: vec3f;
var<private> dReflDirW: vec3f;
var<private> ccReflDirW: vec3f;
var<private> dLightDirNormW: vec3f;
var<private> dAtten: f32;
var<private> dTBN: mat3x3f;
var<private> dReflection: vec4f;
var<private> dDiffuseLight: vec3f;
var<private> dSpecularLight: vec3f;
var<private> ccFresnel: f32;
var<private> ccReflection: vec3f;
var<private> ccSpecularLight: vec3f;
var<private> ccSpecularityNoFres: f32;
var<private> sSpecularLight: vec3f;
#ifdef LIT_DISPERSION
uniform material_dispersion: f32;
#endif
#ifndef LIT_OPACITY_FADES_SPECULAR
uniform material_alphaFade: f32;
#endif
#ifdef LIT_SSAO
var ssaoTexture : texture_2d<f32>;
var ssaoTextureSampler : sampler;
uniform ssaoTextureSizeInv: vec2f;
#endif
#ifdef LIT_SHADOW_CATCHER
var<private> dShadowCatcher: f32 = 1.0;
#endif
#if LIGHT_COUNT > 0
#include "lightDeclarationPS, LIGHT_COUNT"
#endif
#ifdef LIT_SPECULAR
#if LIT_FRESNEL_MODEL == NONE && !defined(LIT_REFLECTIONS) && !defined(LIT_DIFFUSE_MAP)
#define LIT_OLD_AMBIENT
#endif
#endif
#ifdef STD_LIGHTMAP_DIR
uniform bakeDir: f32;
#endif
#ifdef LIT_LIGHTMAP_BAKING_ADD_AMBIENT
uniform ambientBakeOcclusionContrast: f32;
uniform ambientBakeOcclusionBrightness: f32;
#endif
`;var LF=`
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
#include "litUserMainStartPS"
dReflection = vec4f(0.0);
#ifdef LIT_CLEARCOAT
ccSpecularLight = vec3f(0.0);
ccReflection = vec3f(0.0);
#endif
#if LIT_NONE_SLICE_MODE == SLICED
#include "startNineSlicedPS"
#elif LIT_NONE_SLICE_MODE == TILED
#include "startNineSlicedTiledPS"
#endif
#ifdef LIT_NEEDS_NORMAL
dVertexNormalW = normalize(vNormalW);
#ifdef LIT_TANGENTS
#if defined(LIT_HEIGHTS) || defined(LIT_USE_NORMALS) || defined(LIT_USE_CLEARCOAT_NORMALS) || defined(LIT_GGX_SPECULAR)
dTangentW = vTangentW;
dBinormalW = vBinormalW;
#endif
#endif
getViewDir();
#ifdef LIT_TBN
getTBN(dTangentW, dBinormalW, dVertexNormalW);
#ifdef LIT_TWO_SIDED_LIGHTING
handleTwoSidedLighting();
#endif
#endif
#endif
evaluateFrontend();
#include "debugProcessFrontendPS"
var output: FragmentOutput = evaluateBackend();
#include "litUserMainEndPS"
return output;
}
`;var MF=`
#ifdef LIT_NEEDS_NORMAL
#include "cubeMapRotatePS"
#include "cubeMapProjectPS"
#include "envProcPS"
#endif
#ifdef LIT_SPECULAR_OR_REFLECTION
#ifdef LIT_METALNESS
#include "metalnessModulatePS"
#endif
#ifdef LIT_IRIDESCENCE
#include "iridescenceDiffractionPS"
#endif
#endif
#if defined(LIT_SPECULAR_OR_REFLECTION) || defined(LIT_REFRACTION)
#if LIT_FRESNEL_MODEL == SCHLICK
#include "fresnelSchlickPS"
#endif
#endif
#ifdef LIT_AO
#include "aoDiffuseOccPS"
#include "aoSpecOccPS"
#endif
#if LIT_REFLECTION_SOURCE == ENVATLASHQ
#include "envAtlasPS"
#include "reflectionEnvHQPS"
#elif LIT_REFLECTION_SOURCE == ENVATLAS
#include "envAtlasPS"
#include "reflectionEnvPS"
#elif LIT_REFLECTION_SOURCE == CUBEMAP
#include "reflectionCubePS"
#elif LIT_REFLECTION_SOURCE == SPHEREMAP
#include "reflectionSpherePS"
#endif
#ifdef LIT_REFLECTIONS
#ifdef LIT_CLEARCOAT
#include "reflectionCCPS"
#endif
#ifdef LIT_SHEEN
#include "reflectionSheenPS"
#endif
#endif
#ifdef LIT_REFRACTION
#if defined(LIT_DYNAMIC_REFRACTION)
#include "refractionDynamicPS"
#elif defined(LIT_REFLECTIONS)
#include "refractionCubePS"
#endif
#endif
#ifdef LIT_SHEEN
#include "lightSheenPS"
#endif
uniform material_ambient: vec3f;
#ifdef LIT_SPECULAR
#ifdef LIT_LIGHTING
#ifdef LIT_GGX_SPECULAR
#ifdef LIT_ANISOTROPY
#include "lightSpecularAnisoGGXPS"
#else
#include "lightSpecularGGXPS"
#endif
#else
#include "lightSpecularBlinnPS"
#endif
#endif
#endif
#include "combinePS"
#ifdef LIT_LIGHTMAP
#include "lightmapAddPS"
#endif
#ifdef LIT_ADD_AMBIENT
#include "ambientPS"
#endif
#ifdef LIT_MSDF
#include "msdfPS"
#endif
#ifdef LIT_NEEDS_NORMAL
#include "viewDirPS"
#ifdef LIT_SPECULAR
#ifdef LIT_ANISOTROPY
#include "reflDirAnisoPS"
#else
#include "reflDirPS"
#endif
#endif
#endif
#include "lightingPS"
`;var OF=`
#include "basePS"
#include "sphericalPS"
#include "decodePS"
#include "gammaPS"
#include "tonemappingPS"
#include "fogPS"
#if LIT_NONE_SLICE_MODE == SLICED
#include "baseNineSlicedPS"
#elif LIT_NONE_SLICE_MODE == TILED
#include "baseNineSlicedTiledPS"
#endif
#ifdef LIT_TBN
#include "TBNPS"
#ifdef LIT_TWO_SIDED_LIGHTING
#include "twoSidedLightingPS"
#endif
#endif
`;var FF=`
#include "varyingsPS"
#include "litUserDeclarationPS"
#include "frontendDeclPS"
#if defined(PICK_PASS) || defined(PREPASS_PASS)
#include "frontendCodePS"
#include "litUserCodePS"
#include "litOtherMainPS"
#elif defined(SHADOW_PASS)
#include "frontendCodePS"
#include "litUserCodePS"
#include "litShadowMainPS"
#else
#include "litForwardDeclarationPS"
#include "litForwardPreCodePS"
#include "frontendCodePS"
#include "litForwardPostCodePS"
#include "litForwardBackendPS"
#include "litUserCodePS"
#include "litForwardMainPS"
#endif
`;var NF=`
#include "varyingsVS"
#include "litUserDeclarationVS"
#ifdef VERTEX_COLOR
attribute vertex_color: vec4f;
#endif
#ifdef NINESLICED
varying vMask: vec2f;
varying vTiledUv: vec2f;
var<private> dMaskGlobal: vec2f;
var<private> dTiledUvGlobal: vec2f;
uniform innerOffset: vec4f;
uniform outerScale: vec2f;
uniform atlasRect: vec4f;
#endif
var<private> dPositionW: vec3f;
var<private> dModelMatrix: mat4x4f;
#include "transformCoreVS"
#ifdef UV0
attribute vertex_texCoord0: vec2f;
#include "uv0VS"
#endif
#ifdef UV1
attribute vertex_texCoord1: vec2f;
#include "uv1VS"
#endif
#ifdef LINEAR_DEPTH
#ifndef VIEWMATRIX
#define VIEWMATRIX
uniform matrix_view: mat4x4f;
#endif
#endif
#include "transformVS"
#ifdef NORMALS
#include "normalCoreVS"
#include "normalVS"
#endif
#ifdef TANGENTS
attribute vertex_tangent: vec4f;
#endif
#include "uvTransformUniformsPS, UV_TRANSFORMS_COUNT"
#ifdef MSDF
#include "msdfVS"
#endif
#include "litUserCodeVS"
#ifdef VERTEX_COLOR
fn decodeGamma3(raw: vec3f) -> vec3f {
return pow(raw, vec3f(2.2));
}
fn gammaCorrectInputVec4(color: vec4f) -> vec4f {
return vec4f(decodeGamma3(color.xyz), color.w);
}
#endif
@vertex
fn vertexMain(input : VertexInput) -> VertexOutput {
#include "litUserMainStartVS"
var output : VertexOutput;
output.position = getPosition();
output.vPositionW = getWorldPosition();
#ifdef NORMALS
output.vNormalW = getNormal();
#endif
#ifdef TANGENTS
output.vTangentW = normalize(dNormalMatrix * vertex_tangent.xyz);
output.vBinormalW = cross(output.vNormalW, output.vTangentW) * vertex_tangent.w;
#elif defined(GGX_SPECULAR)
output.vObjectSpaceUpW = normalize(dNormalMatrix * vec3f(0.0, 1.0, 0.0));
#endif
#ifdef UV0
var uv0: vec2f = getUv0();
#ifdef UV0_UNMODIFIED
output.vUv0 = uv0;
#endif
#endif
#ifdef UV1
var uv1: vec2f = getUv1();
#ifdef UV1_UNMODIFIED
output.vUv1 = uv1;
#endif
#endif
#include "uvTransformVS, UV_TRANSFORMS_COUNT"
#ifdef VERTEX_COLOR
#ifdef STD_VERTEX_COLOR_GAMMA
output.vVertexColor = gammaCorrectInputVec4(vertex_color);
#else
output.vVertexColor = vertex_color;
#endif
#endif
#ifdef LINEAR_DEPTH
output.vLinearDepth = -(uniform.matrix_view * vec4f(output.vPositionW, 1.0)).z;
#endif
#ifdef MSDF
unpackMsdfParams();
output.outline_color = dOutlineColor;
output.outline_thickness = dOutlineThickness;
output.shadow_color = dShadowColor;
output.shadow_offset = dShadowOffset;
#endif
#ifdef NINESLICED
output.vMask = dMaskGlobal;
output.vTiledUv = dTiledUvGlobal;
#endif
#include "litUserMainEndVS"
return output;
}
`;var BF=`
#ifdef PICK_PASS
#include "pickPS"
#endif
#ifdef PREPASS_PASS
#include "floatAsUintPS"
#endif
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
#include "litUserMainStartPS"
var output: FragmentOutput;
evaluateFrontend();
#ifdef PICK_PASS
output.color = getPickOutput();
#ifdef DEPTH_PICK_PASS
output.color1 = getPickDepth();
#endif
#endif
#ifdef PREPASS_PASS
output.color = float2vec4(vLinearDepth);
#endif
#include "litUserMainEndPS"
return output;
}
`;var UF=`
var<private> litArgs_albedo: vec3f;
var<private> litArgs_opacity: f32;
var<private> litArgs_emission: vec3f;
var<private> litArgs_worldNormal: vec3f;
var<private> litArgs_ao: f32;
var<private> litArgs_lightmap: vec3f;
var<private> litArgs_lightmapDir: vec3f;
var<private> litArgs_metalness: f32;
var<private> litArgs_specularity: vec3f;
var<private> litArgs_specularityFactor: f32;
var<private> litArgs_gloss: f32;
var<private> litArgs_sheen_gloss: f32;
var<private> litArgs_sheen_specularity: vec3f;
var<private> litArgs_transmission: f32;
var<private> litArgs_thickness: f32;
var<private> litArgs_ior: f32;
var<private> litArgs_dispersion: f32;
var<private> litArgs_iridescence_intensity: f32;
var<private> litArgs_iridescence_thickness: f32;
var<private> litArgs_clearcoat_worldNormal: vec3f;
var<private> litArgs_clearcoat_specularity: f32;
var<private> litArgs_clearcoat_gloss: f32;
`;var kF=`
#if LIT_NONE_SLICE_MODE == TILED
var<private> textureBias: f32 = -1000.0;
#else
uniform textureBias: f32;
#endif
#include "litShaderArgsPS"
`;var zF=`
#if LIGHT_TYPE != DIRECTIONAL
uniform view_position: vec3f;
uniform light_radius: f32;
#endif
#if SHADOW_TYPE == PCSS_32F
#include "linearizeDepthPS"
#endif
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
#include "litUserMainStartPS"
var output: FragmentOutput;
evaluateFrontend();
#ifdef PERSPECTIVE_DEPTH
var depth: f32 = input.position.z;
#if SHADOW_TYPE == PCSS_32F
#if LIGHT_TYPE != DIRECTIONAL
depth = linearizeDepthWithParams(depth, camera_params);
#endif
#endif
#else
var depth: f32 = min(distance(uniform.view_position, input.vPositionW) / uniform.light_radius, 0.99999);
#define MODIFIED_DEPTH
#endif
#if SHADOW_TYPE == VSM_16F || SHADOW_TYPE == VSM_32F
#if SHADOW_TYPE == VSM_32F
var exponent: f32 = 15.0;
#else
var exponent: f32 = 5.54;
#endif
var depth_vsm = 2.0 * depth - 1.0;
depth_vsm = exp(exponent * depth_vsm);
output.color = vec4f(depth_vsm, depth_vsm * depth_vsm, 1.0, 1.0);
#else
#if SHADOW_TYPE == PCSS_32F
output.color = vec4f(depth, 0.0, 0.0, 1.0);
#else
#ifdef MODIFIED_DEPTH
output.fragDepth = depth;
#endif
output.color = vec4f(1.0);
#endif
#endif
#include "litUserMainEndPS"
return output;
}
`;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;
const LUT_BIAS: f32 = 0.5 / LUT_SIZE;
let dotNV: f32 = saturate(dot( N, V ));
let uv: vec2f = vec2f( roughness, sqrt( 1.0 - dotNV ) );
return uv * LUT_SCALE + LUT_BIAS;
}
fn LTC_ClippedSphereFormFactor( f: vec3f ) -> f32 {
let l: f32 = length( f );
return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
}
fn LTC_EdgeVectorFormFactor( v1: vec3f, v2: vec3f ) -> vec3f {
let x: f32 = dot( v1, v2 );
let y: f32 = abs( x );
let a: f32 = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
let b: f32 = 3.4175940 + ( 4.1616724 + y ) * y;
let v: f32 = a / b;
let inv_sqrt_term = inverseSqrt( max( 1.0 - x * x, 1e-7f ) );
let theta_sintheta: f32 = select( (0.5 * inv_sqrt_term - v), v, x > 0.0 );
return cross( v1, v2 ) * theta_sintheta;
}
struct Coords {
coord0: vec3f,
coord1: vec3f,
coord2: vec3f,
coord3: vec3f,
}
fn LTC_EvaluateRect( N: vec3f, V: vec3f, P: vec3f, mInv: mat3x3f, rectCoords: Coords) -> f32 {
let v1: vec3f = rectCoords.coord1 - rectCoords.coord0;
let v2: vec3f = rectCoords.coord3 - rectCoords.coord0;
let lightNormal: vec3f = cross( v1, v2 );
let factor: f32 = sign(-dot( lightNormal, P - rectCoords.coord0 ));
let T1: vec3f = normalize( V - N * dot( V, N ) );
let T2: vec3f = factor * cross( N, T1 );
let mat: mat3x3f = mInv * transpose( mat3x3f( T1, T2, N ) );
var coords: array<vec3f, 4>;
coords[0] = mat * ( rectCoords.coord0 - P );
coords[1] = mat * ( rectCoords.coord1 - P );
coords[2] = mat * ( rectCoords.coord2 - P );
coords[3] = mat * ( rectCoords.coord3 - P );
coords[0] = normalize( coords[0] );
coords[1] = normalize( coords[1] );
coords[2] = normalize( coords[2] );
coords[3] = normalize( coords[3] );
var vectorFormFactor: vec3f = vec3f( 0.0 );
vectorFormFactor = vectorFormFactor + LTC_EdgeVectorFormFactor( coords[0], coords[1] );
vectorFormFactor = vectorFormFactor + LTC_EdgeVectorFormFactor( coords[1], coords[2] );
vectorFormFactor = vectorFormFactor + LTC_EdgeVectorFormFactor( coords[2], coords[3] );
vectorFormFactor = vectorFormFactor + LTC_EdgeVectorFormFactor( coords[3], coords[0] );
let result: f32 = LTC_ClippedSphereFormFactor( vectorFormFactor );
return result;
}
var<private> dLTCCoords: Coords;
fn getLTCLightCoords(lightPos: vec3f, halfWidth: vec3f, halfHeight: vec3f) -> Coords {
var coords: Coords;
coords.coord0 = lightPos + halfWidth - halfHeight;
coords.coord1 = lightPos - halfWidth - halfHeight;
coords.coord2 = lightPos - halfWidth + halfHeight;
coords.coord3 = lightPos + halfWidth + halfHeight;
return coords;
}
var<private> dSphereRadius: f32;
fn getSphereLightCoords(lightPos: vec3f, halfWidth: vec3f, halfHeight: vec3f) -> Coords {
dSphereRadius = max(length(halfWidth), length(halfHeight));
let f: vec3f = reflect(normalize(lightPos - uniform.view_position), vNormalW);
let w: vec3f = normalize(cross(f, halfHeight));
let h: vec3f = normalize(cross(f, w));
return getLTCLightCoords(lightPos, w * dSphereRadius, h * dSphereRadius);
}
var<private> dLTCUV: vec2f;
#ifdef LIT_CLEARCOAT
var<private> ccLTCUV: vec2f;
#endif
fn getLTCLightUV(gloss: f32, worldNormal: vec3f, viewDir: vec3f) -> vec2f {
let roughness: f32 = max((1.0 - gloss) * (1.0 - gloss), 0.001);
return LTC_Uv( worldNormal, viewDir, roughness );
}
var<private> dLTCSpecFres: vec3f;
#ifdef LIT_CLEARCOAT
var<private> ccLTCSpecFres: vec3f;
#endif
fn getLTCLightSpecFres(uv: vec2f, specularity: vec3f) -> vec3f {
let t2: vec4f = textureSampleLevel(areaLightsLutTex2, areaLightsLutTex2Sampler, uv, 0.0);
return specularity * t2.x + ( vec3f( 1.0 ) - specularity) * t2.y;
}
fn calcLTCLightValues(gloss: f32, worldNormal: vec3f, viewDir: vec3f, specularity: vec3f, clearcoatGloss: f32, clearcoatWorldNormal: vec3f, clearcoatSpecularity: f32) {
dLTCUV = getLTCLightUV(gloss, worldNormal, viewDir);
dLTCSpecFres = getLTCLightSpecFres(dLTCUV, specularity);
#ifdef LIT_CLEARCOAT
ccLTCUV = getLTCLightUV(clearcoatGloss, clearcoatWorldNormal, viewDir);
ccLTCSpecFres = getLTCLightSpecFres(ccLTCUV, vec3f(clearcoatSpecularity));
#endif
}
fn calcRectLightValues(lightPos: vec3f, halfWidth: vec3f, halfHeight: vec3f) {
dLTCCoords = getLTCLightCoords(lightPos, halfWidth, halfHeight);
}
fn calcDiskLightValues(lightPos: vec3f, halfWidth: vec3f, halfHeight: vec3f) {
calcRectLightValues(lightPos, halfWidth, halfHeight);
}
fn calcSphereLightValues(lightPos: vec3f, halfWidth: vec3f, halfHeight: vec3f) {
dLTCCoords = getSphereLightCoords(lightPos, halfWidth, halfHeight);
}
fn SolveCubic(Coefficient_in: vec4f) -> vec3f {
let pi: f32 = 3.14159;
var Coefficient = Coefficient_in;
Coefficient = vec4f(Coefficient.xyz / Coefficient.w, Coefficient.w);
let new_yz: vec2f = Coefficient.yz / 3.0;
Coefficient = vec4f(Coefficient.x, new_yz.x, new_yz.y, Coefficient.w);
let A: f32 = Coefficient.w;
let B: f32 = Coefficient.z;
let C: f32 = Coefficient.y;
let D: f32 = Coefficient.x;
let Delta: vec3f = vec3f(
-Coefficient.z * Coefficient.z + Coefficient.y,
-Coefficient.y * Coefficient.z + Coefficient.x,
dot(vec2f(Coefficient.z, -Coefficient.y), Coefficient.xy)
);
let Discriminant: f32 = dot(vec2f(4.0 * Delta.x, -Delta.y), Delta.zy);
var xlc: vec2f;
var xsc: vec2f;
{
let A_a: f32 = 1.0;
let C_a: f32 = Delta.x;
let D_a: f32 = -2.0 * B * Delta.x + Delta.y;
let Theta: f32 = atan2(sqrt(Discriminant), -D_a) / 3.0;
let sqrt_neg_Ca = sqrt(-C_a);
let x_1a: f32 = 2.0 * sqrt_neg_Ca * cos(Theta);
let x_3a: f32 = 2.0 * sqrt_neg_Ca * cos(Theta + (2.0 / 3.0) * pi);
let xl: f32 = select(x_3a, x_1a, (x_1a + x_3a) > 2.0 * B);
xlc = vec2f(xl - B, A);
}
{
let A_d: f32 = D;
let C_d: f32 = Delta.z;
let D_d: f32 = -D * Delta.y + 2.0 * C * Delta.z;
let Theta: f32 = atan2(D * sqrt(Discriminant), -D_d) / 3.0;
let sqrt_neg_Cd = sqrt(-C_d);
let x_1d: f32 = 2.0 * sqrt_neg_Cd * cos(Theta);
let x_3d: f32 = 2.0 * sqrt_neg_Cd * cos(Theta + (2.0 / 3.0) * pi);
let xs: f32 = select(x_3d, x_1d, x_1d + x_3d < 2.0 * C);
xsc = vec2f(-D, xs + C);
}
let E: f32 = xlc.y * xsc.y;
let F: f32 = -xlc.x * xsc.y - xlc.y * xsc.x;
let G: f32 = xlc.x * xsc.x;
let xmc: vec2f = vec2f(C * F - B * G, -B * F + C * E);
var Root: vec3f = vec3f(xsc.x / xsc.y, xmc.x / xmc.y, xlc.x / xlc.y);
if (Root.x < Root.y && Root.x < Root.z) {
Root = Root.yxz;
} else if (Root.z < Root.x && Root.z < Root.y) {
Root = Root.xzy;
}
return Root;
}
fn LTC_EvaluateDisk(N: vec3f, V: vec3f, P: vec3f, Minv: mat3x3f, points: Coords) -> f32 {
let T1: vec3f = normalize(V - N * dot(V, N));
let T2: vec3f = cross(N, T1);
let R: mat3x3f = transpose( mat3x3f( T1, T2, N ) );
var L_: array<vec3f, 3>;
L_[0] = R * ( points.coord0 - P );
L_[1] = R * ( points.coord1 - P );
L_[2] = R * ( points.coord2 - P );
let C: vec3f = 0.5 * (L_[0] + L_[2]);
var V1: vec3f = 0.5 * (L_[1] - L_[2]);
var V2: vec3f = 0.5 * (L_[1] - L_[0]);
let C_Minv: vec3f = Minv * C;
let V1_Minv: vec3f = Minv * V1;
let V2_Minv: vec3f = Minv * V2;
var a: f32;
var b: f32;
let d11: f32 = dot(V1_Minv, V1_Minv);
let d22: f32 = dot(V2_Minv, V2_Minv);
let d12: f32 = dot(V1_Minv, V2_Minv);
if (abs(d12) / sqrt(d11 * d22) > 0.0001) {
let tr: f32 = d11 + d22;
let det_inner: f32 = -d12 * d12 + d11 * d22;
let det: f32 = sqrt(det_inner);
let u: f32 = 0.5 * sqrt(tr - 2.0 * det);
let v: f32 = 0.5 * sqrt(tr + 2.0 * det);
let e_max: f32 = (u + v) * (u + v);
let e_min: f32 = (u - v) * (u - v);
var V1_: vec3f;
var V2_: vec3f;
if (d11 > d22) {
V1_ = d12 * V1_Minv + (e_max - d11) * V2_Minv;
V2_ = d12 * V1_Minv + (e_min - d11) * V2_Minv;
} else {
V1_ = d12*V2_Minv + (e_max - d22)*V1_Minv;
V2_ = d12*V2_Minv + (e_min - d22)*V1_Minv;
}
a = 1.0 / e_max;
b = 1.0 / e_min;
V1 = normalize(V1_);
V2 = normalize(V2_);
} else {
a = 1.0 / dot(V1_Minv, V1_Minv);
b = 1.0 / dot(V2_Minv, V2_Minv);
V1 = V1_Minv * sqrt(a);
V2 = V2_Minv * sqrt(b);
}
var V3: vec3f = normalize(cross(V1, V2));
if (dot(C_Minv, V3) < 0.0) {
V3 = V3 * -1.0;
}
let L: f32 = dot(V3, C_Minv);
let x0: f32 = dot(V1, C_Minv) / L;
let y0: f32 = dot(V2, C_Minv) / L;
let E1: f32 = inverseSqrt(a);
let E2: f32 = inverseSqrt(b);
let a_scaled = a * L * L;
let b_scaled = b * L * L;
let c0: f32 = a_scaled * b_scaled;
let c1: f32 = a_scaled * b_scaled * (1.0 + x0 * x0 + y0 * y0) - a_scaled - b_scaled;
let c2: f32 = 1.0 - a_scaled * (1.0 + x0 * x0) - b_scaled * (1.0 + y0 * y0);
let c3: f32 = 1.0;
let roots: vec3f = SolveCubic(vec4f(c0, c1, c2, c3));
let e1: f32 = roots.x;
let e2: f32 = roots.y;
let e3: f32 = roots.z;
var avgDir: vec3f = vec3f(a_scaled * x0 / (a_scaled - e2), b_scaled * y0 / (b_scaled - e2), 1.0);
let rotate: mat3x3f = mat3x3f(V1, V2, V3);
avgDir = rotate * avgDir;
avgDir = normalize(avgDir);
let L1: f32 = sqrt(-e2 / e3);
let L2: f32 = sqrt(-e2 / e1);
let formFactor: f32 = max(0.0, L1 * L2 * inverseSqrt((1.0 + L1 * L1) * (1.0 + L2 * L2)));
const LUT_SIZE_disk: f32 = 64.0;
const LUT_SCALE_disk: f32 = ( LUT_SIZE_disk - 1.0 ) / LUT_SIZE_disk;
const LUT_BIAS_disk: f32 = 0.5 / LUT_SIZE_disk;
var uv: vec2f = vec2f(avgDir.z * 0.5 + 0.5, formFactor);
uv = uv * LUT_SCALE_disk + LUT_BIAS_disk;
let scale: f32 = textureSampleLevel(areaLightsLutTex2, areaLightsLutTex2Sampler, uv, 0.0).w;
return formFactor * scale;
}
fn FixNan(value: f32) -> f32 {
return select(value, 0.0, value != value);
}
fn getRectLightDiffuse(worldNormal: vec3f, viewDir: vec3f, lightDir: vec3f, lightDirNorm: vec3f) -> f32 {
let identityMat = mat3x3f(vec3f(1.0, 0.0, 0.0), vec3f(0.0, 1.0, 0.0), vec3f(0.0, 0.0, 1.0));
return LTC_EvaluateRect( worldNormal, viewDir, vPositionW, identityMat, dLTCCoords );
}
fn getDiskLightDiffuse(worldNormal: vec3f, viewDir: vec3f, lightDir: vec3f, lightDirNorm: vec3f) -> f32 {
let identityMat = mat3x3f(vec3f(1.0, 0.0, 0.0), vec3f(0.0, 1.0, 0.0), vec3f(0.0, 0.0, 1.0));
return FixNan(LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, identityMat, dLTCCoords ));
}
fn getSphereLightDiffuse(worldNormal: vec3f, viewDir: vec3f, lightDir: vec3f, lightDirNorm: vec3f) -> f32 {
let falloff: f32 = dSphereRadius / (dot(lightDir, lightDir) + dSphereRadius);
return FixNan(getLightDiffuse(worldNormal, viewDir, lightDirNorm) * falloff);
}
fn getLTCLightInvMat(uv: vec2f) -> mat3x3f {
let t1: vec4f = textureSampleLevel(areaLightsLutTex1, areaLightsLutTex1Sampler, uv, 0.0);
return mat3x3f(
vec3f( t1.x, 0.0, t1.y ),
vec3f( 0.0, 1.0, 0.0 ),
vec3f( t1.z, 0.0, t1.w )
);
}
fn calcRectLightSpecular(worldNormal: vec3f, viewDir: vec3f, uv: vec2f) -> f32 {
let mInv: mat3x3f = getLTCLightInvMat(uv);
return LTC_EvaluateRect( worldNormal, viewDir, vPositionW, mInv, dLTCCoords );
}
fn getRectLightSpecular(worldNormal: vec3f, viewDir: vec3f) -> f32 {
return calcRectLightSpecular(worldNormal, viewDir, dLTCUV);
}
fn calcDiskLightSpecular(worldNormal: vec3f, viewDir: vec3f, uv: vec2f) -> f32 {
let mInv: mat3x3f = getLTCLightInvMat(uv);
return LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, mInv, dLTCCoords );
}
fn getDiskLightSpecular(worldNormal: vec3f, viewDir: vec3f) -> f32 {
return calcDiskLightSpecular(worldNormal, viewDir, dLTCUV);
}
fn getSphereLightSpecular(worldNormal: vec3f, viewDir: vec3f) -> f32 {
return calcDiskLightSpecular(worldNormal, viewDir, dLTCUV);
}
`;var VF=`
#ifdef STD_METALNESS_CONSTANT
uniform material_metalness: f32;
#endif
fn getMetalness() {
var metalness: f32 = 1.0;
#ifdef STD_METALNESS_CONSTANT
metalness = metalness * uniform.material_metalness;
#endif
#ifdef STD_METALNESS_TEXTURE
metalness = metalness * textureSampleBias({STD_METALNESS_TEXTURE_NAME}, {STD_METALNESS_TEXTURE_NAME}Sampler, {STD_METALNESS_TEXTURE_UV}, uniform.textureBias).{STD_METALNESS_TEXTURE_CHANNEL};
#endif
#ifdef STD_METALNESS_VERTEX
metalness = metalness * saturate(vVertexColor.{STD_METALNESS_VERTEX_CHANNEL});
#endif
dMetalness = metalness;
}
`;var HF=`
var texture_msdfMap: texture_2d<f32>;
var texture_msdfMapSampler: sampler;
fn median(r: f32, g: f32, b: f32) -> f32 {
return max(min(r, g), min(max(r, g), b));
}
fn map(min: f32, max: f32, v: f32) -> f32 {
return (v - min) / (max - min);
}
uniform font_sdfIntensity: f32;
uniform font_pxrange: f32;
uniform font_textureWidth: f32;
#ifndef LIT_MSDF_TEXT_ATTRIBUTE
uniform outline_color: vec4f;
uniform outline_thickness: f32;
uniform shadow_color: vec4f;
uniform shadow_offset: vec2f;
#else
varying outline_color: vec4f;
varying outline_thickness: f32;
varying shadow_color: vec4f;
varying shadow_offset: vec2f;
#endif
fn applyMsdf(color_in: vec4f) -> vec4f {
#ifndef LIT_MSDF_TEXT_ATTRIBUTE
var outline_colorValue = uniform.outline_color;
var outline_thicknessValue = uniform.outline_thickness;
var shadow_colorValue = uniform.shadow_color;
var shadow_offsetValue = uniform.shadow_offset;
#else
var outline_colorValue = outline_color;
var outline_thicknessValue = outline_thickness;
var shadow_colorValue = shadow_color;
var shadow_offsetValue = shadow_offset;
#endif
var color = vec4f(gammaCorrectInputVec3(color_in.rgb), color_in.a);
let tsample: vec3f = textureSample(texture_msdfMap, texture_msdfMapSampler, vUv0).rgb;
let uvShdw: vec2f = vUv0 - shadow_offsetValue;
let ssample: vec3f = textureSample(texture_msdfMap, texture_msdfMapSampler, uvShdw).rgb;
let sigDist: f32 = median(tsample.r, tsample.g, tsample.b);
var sigDistShdw: f32 = median(ssample.r, ssample.g, ssample.b);
let smoothingMax: f32 = 0.2;
let w: vec2f = abs(dpdx(vUv0)) + abs(dpdy(vUv0));
let smoothing: f32 = clamp(w.x * uniform.font_textureWidth / uniform.font_pxrange, 0.0, smoothingMax);
let mapMin: f32 = 0.05;
let mapMax: f32 = clamp(1.0 - uniform.font_sdfIntensity, mapMin, 1.0);
let sigDistInner: f32 = map(mapMin, mapMax, sigDist);
let sigDistOutline: f32 = map(mapMin, mapMax, sigDist + outline_thicknessValue);
sigDistShdw = map(mapMin, mapMax, sigDistShdw + outline_thicknessValue);
let center: f32 = 0.5;
let inside: f32 = smoothstep(center - smoothing, center + smoothing, sigDistInner);
let outline: f32 = smoothstep(center - smoothing, center + smoothing, sigDistOutline);
let shadow: f32 = smoothstep(center - smoothing, center + smoothing, sigDistShdw);
let tcolor_outline: vec4f = outline * vec4f(outline_colorValue.a * outline_colorValue.rgb, outline_colorValue.a);
var tcolor: vec4f = select(vec4f(0.0), tcolor_outline, outline > inside);
tcolor = mix(tcolor, color, inside);
let scolor_shadow: vec4f = shadow * vec4f(shadow_colorValue.a * shadow_colorValue.rgb, shadow_colorValue.a);
let scolor: vec4f = select(tcolor, scolor_shadow, shadow > outline);
tcolor = mix(scolor, tcolor, outline);
tcolor = vec4f(gammaCorrectOutput(tcolor.rgb), tcolor.a);
return tcolor;
}
`;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<f32>;
uniform morphFactor: array<f32, {MORPH_TEXTURE_MAX_COUNT}>;
uniform morphIndex: array<u32, {MORPH_TEXTURE_MAX_COUNT}>;
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;
varying outline_thickness: f32;
varying shadow_color: vec4f;
varying shadow_offset: vec2f;
var<private> dOutlineColor: vec4f;
var<private> dOutlineThickness: f32;
var<private> dShadowColor: vec4f;
var<private> dShadowOffset: vec2f;
fn unpackMsdfParams() {
let little: vec3f = vertex_outlineParameters % vec3f(256.0);
let big: vec3f = (vertex_outlineParameters - little) / 256.0;
dOutlineColor = vec4f(little.x, big.x, little.y, big.y) / 255.0;
dOutlineThickness = little.z / 255.0 * 0.2;
let little_shadow = vertex_shadowParameters % vec3f(256.0);
let big_shadow = (vertex_shadowParameters - little_shadow) / 256.0;
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;
}
`;var jF=`
var<private> dNormalMatrix: mat3x3f;
fn getNormal() -> vec3f {
dNormalMatrix = getNormalMatrix(dModelMatrix);
let localNormal: vec3f = getLocalNormal(vertex_normal);
return normalize(dNormalMatrix * localNormal);
}`;var qF=`
attribute vertex_normal: vec3f;
uniform matrix_normal: mat3x3f;
#ifdef MORPHING_NORMAL
#ifdef MORPHING_INT
var morphNormalTex: texture_2d<u32>;
var morphNormalTexSampler: sampler;
#else
var morphNormalTex: texture_2d<f32>;
var morphNormalTexSampler: sampler;
#endif
#endif
fn getLocalNormal(vertexNormal: vec3f) -> vec3f {
var localNormal: vec3f = vertexNormal;
#ifdef MORPHING_NORMAL
let morphUV: vec2i = getTextureMorphCoords();
#ifdef MORPHING_INT
let morphNormalInt: vec4u = textureLoad(morphNormalTex, morphUV, 0);
let morphNormalF: vec3f = vec3f(morphNormalInt.xyz) / 65535.0 * 2.0 - 1.0;
localNormal = localNormal + morphNormalF;
#else
let morphNormal: vec3f = textureLoad(morphNormalTex, morphUV, 0).xyz;
localNormal = localNormal + morphNormal;
#endif
#endif
return localNormal;
}
#if defined(SKIN) || defined(BATCH)
fn getNormalMatrix(modelMatrix: mat4x4f) -> mat3x3f {
return mat3x3f(modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz);
}
#elif defined(INSTANCING)
fn getNormalMatrix(modelMatrix: mat4x4f) -> mat3x3f {
return mat3x3f(modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz);
}
#else
fn getNormalMatrix(modelMatrix: mat4x4f) -> mat3x3f {
return uniform.matrix_normal;
}
#endif
`;var $F=`
#ifdef STD_NORMAL_TEXTURE
uniform material_bumpiness: f32;
#endif
#ifdef STD_NORMALDETAIL_TEXTURE
uniform material_normalDetailMapBumpiness: f32;
fn blendNormals(inN1: vec3f, inN2: vec3f) -> vec3f {
let n1: vec3f = inN1 + vec3f(0.0, 0.0, 1.0);
let n2: vec3f = inN2 * vec3f(-1.0, -1.0, 1.0);
return n1 * dot(n1, n2) / n1.z - n2;
}
#endif
fn getNormal() {
#ifdef STD_NORMAL_TEXTURE
var normalMap: vec3f = {STD_NORMAL_TEXTURE_DECODE}(textureSampleBias({STD_NORMAL_TEXTURE_NAME}, {STD_NORMAL_TEXTURE_NAME}Sampler, {STD_NORMAL_TEXTURE_UV}, uniform.textureBias));
normalMap = mix(vec3f(0.0, 0.0, 1.0), normalMap, uniform.material_bumpiness);
#ifdef STD_NORMALDETAIL_TEXTURE
var normalDetailMap: vec3f = {STD_NORMALDETAIL_TEXTURE_DECODE}(textureSampleBias({STD_NORMALDETAIL_TEXTURE_NAME}, {STD_NORMALDETAIL_TEXTURE_NAME}Sampler, {STD_NORMALDETAIL_TEXTURE_UV}, uniform.textureBias));
normalDetailMap = mix(vec3f(0.0, 0.0, 1.0), normalDetailMap, uniform.material_normalDetailMapBumpiness);
normalMap = blendNormals(normalMap, normalDetailMap);
#endif
dNormalW = normalize(dTBN * normalMap);
#else
dNormalW = dVertexNormalW;
#endif
}
`;var ZF=`
uniform material_opacity: f32;
uniform material_alphaDitherScale: f32;
fn getOpacity() {
dAlpha = uniform.material_opacity;
#ifdef STD_OPACITY_TEXTURE
dAlpha = dAlpha * textureSampleBias({STD_OPACITY_TEXTURE_NAME}, {STD_OPACITY_TEXTURE_NAME}Sampler, {STD_OPACITY_TEXTURE_UV}, uniform.textureBias).{STD_OPACITY_TEXTURE_CHANNEL};
#endif
#ifdef STD_OPACITY_VERTEX
dAlpha = dAlpha * clamp(vVertexColor.{STD_OPACITY_VERTEX_CHANNEL}, 0.0, 1.0);
#endif
}
`;var QF=`
#if STD_OPACITY_DITHER == BAYER8
#include "bayerPS"
#endif
uniform blueNoiseJitter: vec4f;
#if STD_OPACITY_DITHER == BLUENOISE
var blueNoiseTex32 : texture_2d<f32>;
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
#if STD_OPACITY_DITHER == BLUENOISE
var uv = fract(pcPosition.xy / 32.0 + uniform.blueNoiseJitter.xy + id);
var noise: f32 = textureSampleLevel(blueNoiseTex32, blueNoiseTex32Sampler, uv, 0.0).y;
#endif
#if STD_OPACITY_DITHER == IGNNOISE
var magic = vec3f(0.06711056, 0.00583715, 52.9829189);
var noise: f32 = fract(magic.z * fract(dot(pcPosition.xy + uniform.blueNoiseJitter.xy + id, magic.xy)));
#endif
#endif
noise = pow(noise, 2.2);
if (alpha < noise) {
discard;
}
}
`;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
output.color = vec4f(output.color.rgb * litArgs_opacity, litArgs_opacity);
#else
output.color = vec4f(output.color.rgb, 1.0);
#endif
`;var tN=`
varying vUv0: vec2f;
var source: texture_2d<f32>;
var sourceSampler: sampler;
@fragment fn fragmentMain(input : FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
output.color = textureSample(source, sourceSampler, input.vUv0);
return output;
}
`;var sN=`
uniform material_sheen: vec3f;
fn getSheen() {
var sheenColor = uniform.material_sheen;
#ifdef STD_SHEEN_TEXTURE
sheenColor = sheenColor * {STD_SHEEN_TEXTURE_DECODE}(textureSampleBias({STD_SHEEN_TEXTURE_NAME}, {STD_SHEEN_TEXTURE_NAME}Sampler, {STD_SHEEN_TEXTURE_UV}, uniform.textureBias)).{STD_SHEEN_TEXTURE_CHANNEL};
#endif
#ifdef STD_SHEEN_VERTEX
sheenColor = sheenColor * saturate3(vVertexColor.{STD_SHEEN_VERTEX_CHANNEL});
#endif
sSpecularity = sheenColor;
}
`;var iN=`
uniform material_sheenGloss: f32;
fn getSheenGlossiness() {
var sheenGlossiness = uniform.material_sheenGloss;
#ifdef STD_SHEENGLOSS_TEXTURE
sheenGlossiness = sheenGlossiness * textureSampleBias({STD_SHEENGLOSS_TEXTURE_NAME}, {STD_SHEENGLOSS_TEXTURE_NAME}Sampler, {STD_SHEENGLOSS_TEXTURE_UV}, uniform.textureBias).{STD_SHEENGLOSS_TEXTURE_CHANNEL};
#endif
#ifdef STD_SHEENGLOSS_VERTEX
sheenGlossiness = sheenGlossiness * saturate(vVertexColor.{STD_SHEENGLOSS_VERTEX_CHANNEL});
#endif
#ifdef STD_SHEENGLOSS_INVERT
sheenGlossiness = 1.0 - sheenGlossiness;
#endif
sGlossiness = sheenGlossiness + 0.0000001;
}
`;var rN=`
uniform material_heightMapFactor: f32;
fn getParallax() {
var parallaxScale = uniform.material_heightMapFactor;
var height: f32 = textureSampleBias({STD_HEIGHT_TEXTURE_NAME}, {STD_HEIGHT_TEXTURE_NAME}Sampler, {STD_HEIGHT_TEXTURE_UV}, uniform.textureBias).{STD_HEIGHT_TEXTURE_CHANNEL};
height = height * parallaxScale - parallaxScale * 0.5;
var viewDirT: vec3f = dViewDirW * dTBN;
viewDirT.z = viewDirT.z + 0.42;
dUvOffset = height * (viewDirT.xy / viewDirT.z);
}
`;var aN=`
fn encodePickOutput(id: u32) -> vec4f {
let inv: vec4f = vec4f(1.0 / 255.0);
let shifts: vec4u = vec4u(16u, 8u, 0u, 24u);
let col: vec4u = (vec4u(id) >> shifts) & vec4u(0xffu);
return vec4f(col) * inv;
}
#ifndef PICK_CUSTOM_ID
uniform meshInstanceId: u32;
fn getPickOutput() -> vec4f {
return encodePickOutput(uniform.meshInstanceId);
}
#endif
#ifdef DEPTH_PICK_PASS
#include "floatAsUintPS"
#ifndef CAMERAPLANES
#define CAMERAPLANES
uniform camera_params: vec4f;
#endif
fn getPickDepth() -> vec4f {
var linearDepth: f32;
if (uniform.camera_params.w > 0.5) {
linearDepth = pcPosition.z;
} else {
let viewDist = 1.0 / pcPosition.w;
linearDepth = (viewDist - uniform.camera_params.z) / (uniform.camera_params.y - uniform.camera_params.z);
}
return float2uint(linearDepth);
}
#endif
`;var oN=`
fn getReflDir(worldNormal: vec3f, viewDir: vec3f, gloss: f32, tbn: mat3x3f) {
dReflDirW = normalize(-reflect(viewDir, worldNormal));
}
`;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;
let anisotropicT: vec3f = normalize(tbn * vec3f(direction, 0.0));
let anisotropicB: vec3f = normalize(cross(tbn[2], anisotropicT));
let anisotropy: f32 = dAnisotropy;
let anisotropicDirection: vec3f = anisotropicB;
let anisotropicTangent: vec3f = cross(anisotropicDirection, viewDir);
let anisotropicNormal: vec3f = cross(anisotropicTangent, anisotropicDirection);
let bendFactor: f32 = 1.0 - anisotropy * (1.0 - roughness);
let bendFactor4: f32 = bendFactor * bendFactor * bendFactor * bendFactor;
let bentNormal: vec3f = normalize(mix(normalize(anisotropicNormal), normalize(worldNormal), bendFactor4));
dReflDirW = reflect(-viewDir, bentNormal);
}`;var lN=`
#ifdef LIT_CLEARCOAT
fn addReflectionCC(reflDir: vec3f, gloss: f32) {
ccReflection = ccReflection + calcReflection(reflDir, gloss);
}
#endif
`;var cN=`
var texture_cubeMap: texture_cube<f32>;
var texture_cubeMapSampler: sampler;
uniform material_reflectivity: f32;
fn calcReflection(reflDir: vec3f, gloss: f32) -> vec3f {
var lookupVec: vec3f = cubeMapProject(reflDir);
lookupVec.x = lookupVec.x * -1.0;
return {reflectionDecode}(textureSample(texture_cubeMap, texture_cubeMapSampler, lookupVec));
}
fn addReflection(reflDir: vec3f, gloss: f32) {
dReflection = dReflection + vec4f(calcReflection(reflDir, gloss), uniform.material_reflectivity);
}
`;var hN=`
#ifndef ENV_ATLAS
#define ENV_ATLAS
var texture_envAtlas: texture_2d<f32>;
var texture_envAtlasSampler: sampler;
#endif
var texture_cubeMap: texture_cube<f32>;
var texture_cubeMapSampler: sampler;
uniform material_reflectivity: f32;
fn calcReflection(reflDir: vec3f, gloss: f32) -> vec3f {
let dir: vec3f = cubeMapProject(reflDir) * vec3f(-1.0, 1.0, 1.0);
let uv: vec2f = toSphericalUv(dir);
let level: f32 = saturate(1.0 - gloss) * 5.0;
let ilevel: f32 = floor(level);
let flevel: f32 = level - ilevel;
let sharp: vec3f = {reflectionCubemapDecode}(textureSample(texture_cubeMap, texture_cubeMapSampler, dir));
let roughA: vec3f = {reflectionDecode}(textureSample(texture_envAtlas, texture_envAtlasSampler, mapRoughnessUv(uv, ilevel)));
let roughB: vec3f = {reflectionDecode}(textureSample(texture_envAtlas, texture_envAtlasSampler, mapRoughnessUv(uv, ilevel + 1.0)));
return processEnvironment(mix(sharp, mix(roughA, roughB, flevel), min(level, 1.0)));
}
fn addReflection(reflDir: vec3f, gloss: f32) {
dReflection = dReflection + vec4f(calcReflection(reflDir, gloss), uniform.material_reflectivity);
}
`;var fN=`
#ifndef ENV_ATLAS
#define ENV_ATLAS
var texture_envAtlas: texture_2d<f32>;
var texture_envAtlasSampler: sampler;
#endif
uniform material_reflectivity: f32;
fn shinyMipLevel(uv: vec2f) -> f32 {
let dx: vec2f = dpdx(uv);
let dy: vec2f = dpdy(uv);
let uv2: vec2f = vec2f(fract(uv.x + 0.5), uv.y);
let dx2: vec2f = dpdx(uv2);
let dy2: vec2f = dpdy(uv2);
let maxd: f32 = min(max(dot(dx, dx), dot(dy, dy)), max(dot(dx2, dx2), dot(dy2, dy2)));
return clamp(0.5 * log2(maxd) - 1.0 + uniform.textureBias, 0.0, 5.0);
}
fn calcReflection(reflDir: vec3f, gloss: f32) -> vec3f {
let dir: vec3f = cubeMapProject(reflDir) * vec3f(-1.0, 1.0, 1.0);
let uv: vec2f = toSphericalUv(dir);
let level: f32 = saturate(1.0 - gloss) * 5.0;
let ilevel: f32 = floor(level);
let level2: f32 = shinyMipLevel(uv * atlasSize);
let ilevel2: f32 = floor(level2);
var uv0: vec2f;
var uv1: vec2f;
var weight: f32;
if (ilevel == 0.0) {
uv0 = mapShinyUv(uv, ilevel2);
uv1 = mapShinyUv(uv, ilevel2 + 1.0);
weight = level2 - ilevel2;
} else {
uv0 = mapRoughnessUv(uv, ilevel);
uv1 = uv0;
weight = 0.0;
}
let linearA: vec3f = {reflectionDecode}(textureSample(texture_envAtlas, texture_envAtlasSampler, uv0));
let linearB: vec3f = {reflectionDecode}(textureSample(texture_envAtlas, texture_envAtlasSampler, uv1));
let linear0: vec3f = mix(linearA, linearB, weight);
let linear1: vec3f = {reflectionDecode}(textureSample(texture_envAtlas, texture_envAtlasSampler, mapRoughnessUv(uv, ilevel + 1.0)));
return processEnvironment(mix(linear0, linear1, level - ilevel));
}
fn addReflection(reflDir: vec3f, gloss: f32) {
dReflection = dReflection + vec4f(calcReflection(reflDir, gloss), uniform.material_reflectivity);
}
`;var uN=`
#ifndef VIEWMATRIX
#define VIEWMATRIX
uniform matrix_view: mat4x4f;
#endif
var texture_sphereMap: texture_2d<f32>;
var texture_sphereMapSampler: sampler;
uniform material_reflectivity: f32;
fn calcReflection(reflDir: vec3f, gloss: f32) -> vec3f {
let viewRotationMatrix = mat3x3f(uniform.matrix_view[0].xyz, uniform.matrix_view[1].xyz, uniform.matrix_view[2].xyz);
let reflDirV: vec3f = viewRotationMatrix * reflDir;
let m: f32 = 2.0 * sqrt(dot(reflDirV.xy, reflDirV.xy) + (reflDirV.z + 1.0) * (reflDirV.z + 1.0));
let sphereMapUv: vec2f = reflDirV.xy / m + 0.5;
return {reflectionDecode}(textureSample(texture_sphereMap, texture_sphereMapSampler, sphereMapUv));
}
fn addReflection(reflDir: vec3f, gloss: f32) {
dReflection = dReflection + vec4f(calcReflection(reflDir, gloss), uniform.material_reflectivity);
}
`;var dN=`
fn addReflectionSheen(worldNormal: vec3f, viewDir: vec3f, gloss: f32) {
let NoV: f32 = dot(worldNormal, viewDir);
let alphaG: f32 = gloss * gloss;
let a: f32 = select(
-8.48 * alphaG + 14.3 * gloss - 9.95,
-339.2 * alphaG + 161.4 * gloss - 25.9,
gloss < 0.25
);
let b: f32 = select(
1.97 * alphaG - 3.27 * gloss + 0.72,
44.0 * alphaG - 23.7 * gloss + 3.26,
gloss < 0.25
);
let dg_add: f32 = select(
0.1 * ( gloss - 0.25 ),
0.0,
gloss < 0.25
);
let dg: f32 = exp( a * NoV + b ) + dg_add;
sReflection = sReflection + (calcReflection(worldNormal, 0.0) * saturate(dg));
}`;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);
let refrVec: vec3f = IOR * viewVec - (IOR * vn + sqrt(k)) * normal;
return refrVec;
}
fn addRefraction(
worldNormal: vec3f,
viewDir: vec3f,
thickness: f32,
gloss: f32,
specularity: vec3f,
albedo: vec3f,
transmission: f32,
refractionIndex: f32,
dispersion: f32
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel: vec3f,
iridescenceIntensity: f32
#endif
) {
let tmpRefl: vec4f = dReflection;
let reflectionDir: vec3f = refract2(-viewDir, worldNormal, refractionIndex);
dReflection = vec4f(0.0);
addReflection(reflectionDir, gloss);
dDiffuseLight = mix(dDiffuseLight, dReflection.rgb * albedo, transmission);
dReflection = tmpRefl;
}
`;var mN=`
uniform material_invAttenuationDistance: f32;
uniform material_attenuation: vec3f;
fn evalRefractionColor(refractionVector: vec3f, gloss: f32, refractionIndex: f32) -> vec3f {
let pointOfRefraction: vec4f = vec4f(vPositionW + refractionVector, 1.0);
let projectionPoint: vec4f = uniform.matrix_viewProjection * pointOfRefraction;
let uv: vec2f = getGrabScreenPos(projectionPoint);
let iorToRoughness: f32 = (1.0 - gloss) * clamp((1.0 / refractionIndex) * 2.0 - 2.0, 0.0, 1.0);
let refractionLod: f32 = log2(uniform.uScreenSize.x) * iorToRoughness;
var refraction: vec3f = textureSampleLevel(uSceneColorMap, uSceneColorMapSampler, uv, refractionLod).rgb;
#ifdef SCENE_COLORMAP_GAMMA
refraction = decodeGamma3(refraction);
#endif
return refraction;
}
fn addRefraction(
worldNormal: vec3f,
viewDir: vec3f,
thickness: f32,
gloss: f32,
specularity: vec3f,
albedo: vec3f,
transmission: f32,
refractionIndex: f32,
dispersion: f32,
#if defined(LIT_IRIDESCENCE)
iridescenceFresnel: vec3f,
iridescenceIntensity: f32
#endif
) {
var modelScale: vec3f;
modelScale.x = length(uniform.matrix_model[0].xyz);
modelScale.y = length(uniform.matrix_model[1].xyz);
modelScale.z = length(uniform.matrix_model[2].xyz);
let scale: vec3f = thickness * modelScale;
var refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndex)) * scale;
var refraction = evalRefractionColor(refractionVector, gloss, refractionIndex);
#ifdef LIT_DISPERSION
let halfSpread: f32 = (1.0 / refractionIndex - 1.0) * 0.025 * dispersion;
let refractionIndexR: f32 = refractionIndex - halfSpread;
refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndexR)) * scale;
refraction.r = evalRefractionColor(refractionVector, gloss, refractionIndexR).r;
let refractionIndexB: f32 = refractionIndex + halfSpread;
refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndexB)) * scale;
refraction.b = evalRefractionColor(refractionVector, gloss, refractionIndexB).b;
#endif
var transmittance: vec3f;
if (uniform.material_invAttenuationDistance != 0.0)
{
let attenuation: vec3f = -log(uniform.material_attenuation) * uniform.material_invAttenuationDistance;
transmittance = exp(-attenuation * length(refractionVector));
}
else
{
transmittance = vec3f(1.0);
}
let fresnel: vec3f = vec3f(1.0) -
getFresnel(
dot(viewDir, worldNormal),
gloss,
specularity
#if defined(LIT_IRIDESCENCE)
, iridescenceFresnel,
iridescenceIntensity
#endif
);
dDiffuseLight = mix(dDiffuseLight, refraction * transmittance * fresnel, transmission);
}
`;var _N=`
varying vUv0: vec2f;
#ifdef CUBEMAP_SOURCE
var sourceCube: texture_cube<f32>;
var sourceCubeSampler : sampler;
#else
var sourceTex: texture_2d<f32>;
var sourceTexSampler : sampler;
#endif
#ifdef USE_SAMPLES_TEX
var samplesTex: texture_2d<f32>;
var samplesTexSampler : sampler;
uniform samplesTexInverseSize: vec2f;
#endif
uniform params: vec3f;
fn targetFace() -> f32 { return uniform.params.x; }
fn targetTotalPixels() -> f32 { return uniform.params.y; }
fn sourceTotalPixels() -> f32 { return uniform.params.z; }
const PI: f32 = 3.141592653589793;
fn saturate(x: f32) -> f32 {
return clamp(x, 0.0, 1.0);
}
#include "decodePS"
#include "encodePS"
fn modifySeams(dir: vec3f, scale: f32) -> vec3f {
let adir = abs(dir);
let M = max(max(adir.x, adir.y), adir.z);
return dir / M * vec3f(
select(scale, 1.0, adir.x == M),
select(scale, 1.0, adir.y == M),
select(scale, 1.0, adir.z == M)
);
}
fn toSpherical(dir: vec3f) -> vec2f {
let nonZeroXZ = any(dir.xz != vec2f(0.0, 0.0));
return vec2f(select(0.0, atan2(dir.x, dir.z), nonZeroXZ), asin(dir.y));
}
fn fromSpherical(uv: vec2f) -> vec3f {
return vec3f(cos(uv.y) * sin(uv.x),
sin(uv.y),
cos(uv.y) * cos(uv.x));
}
fn getDirectionEquirect(uv: vec2f) -> vec3f {
return fromSpherical((vec2f(uv.x, 1.0 - uv.y) * 2.0 - 1.0) * vec2f(PI, PI * 0.5));
}
fn signNotZero(k: f32) -> f32 {
return select(-1.0, 1.0, k >= 0.0);
}
fn signNotZeroVec2(v: vec2f) -> vec2f {
return vec2f(signNotZero(v.x), signNotZero(v.y));
}
fn octDecode(o: vec2f) -> vec3f {
var v = vec3f(o.x, 1.0 - abs(o.x) - abs(o.y), o.y);
if (v.y < 0.0) {
var temp: vec2f = (1.0 - abs(v.zx)) * signNotZeroVec2(v.xz);
v = vec3f(temp.x, v.y, temp.y);
}
return normalize(v);
}
fn getDirectionOctahedral(uv: vec2f) -> vec3f {
return octDecode(vec2f(uv.x, 1.0 - uv.y) * 2.0 - 1.0);
}
fn octEncode(v: vec3f) -> vec2f {
let l1norm = abs(v.x) + abs(v.y) + abs(v.z);
var result = v.xz * (1.0 / l1norm);
if (v.y < 0.0) {
result = (1.0 - abs(result.yx)) * signNotZeroVec2(result.xy);
}
return result;
}
#ifdef CUBEMAP_SOURCE
fn sampleCubemapDir(dir: vec3f) -> vec4f {
return textureSample(sourceCube, sourceCubeSampler, modifySeams(dir, 1.0));
}
fn sampleCubemapSph(sph: vec2f) -> vec4f {
return sampleCubemapDir(fromSpherical(sph));
}
fn sampleCubemapDirLod(dir: vec3f, mipLevel: f32) -> vec4f {
return textureSampleLevel(sourceCube, sourceCubeSampler, modifySeams(dir, 1.0), mipLevel);
}
fn sampleCubemapSphLod(sph: vec2f, mipLevel: f32) -> vec4f {
return sampleCubemapDirLod(fromSpherical(sph), mipLevel);
}
#else
fn sampleEquirectSph(sph: vec2f) -> vec4f {
let uv = sph / vec2f(PI * 2.0, PI) + 0.5;
return textureSample(sourceTex, sourceTexSampler, vec2f(uv.x, 1.0 - uv.y));
}
fn sampleEquirectDir(dir: vec3f) -> vec4f {
return sampleEquirectSph(toSpherical(dir));
}
fn sampleEquirectSphLod(sph: vec2f, mipLevel: f32) -> vec4f {
let uv = sph / vec2f(PI * 2.0, PI) + 0.5;
return textureSampleLevel(sourceTex, sourceTexSampler, vec2f(uv.x, 1.0 - uv.y), mipLevel);
}
fn sampleEquirectDirLod(dir: vec3f, mipLevel: f32) -> vec4f {
return sampleEquirectSphLod(toSpherical(dir), mipLevel);
}
fn sampleOctahedralDir(dir: vec3f) -> vec4f {
let uv = octEncode(dir) * 0.5 + 0.5;
return textureSample(sourceTex, sourceTexSampler, vec2f(uv.x, 1.0 - uv.y));
}
fn sampleOctahedralSph(sph: vec2f) -> vec4f {
return sampleOctahedralDir(fromSpherical(sph));
}
fn sampleOctahedralDirLod(dir: vec3f, mipLevel: f32) -> vec4f {
let uv = octEncode(dir) * 0.5 + 0.5;
return textureSampleLevel(sourceTex, sourceTexSampler, vec2f(uv.x, 1.0 - uv.y), mipLevel);
}
fn sampleOctahedralSphLod(sph: vec2f, mipLevel: f32) -> vec4f {
return sampleOctahedralDirLod(fromSpherical(sph), mipLevel);
}
#endif
fn getDirectionCubemap(uv: vec2f) -> vec3f {
let st = uv * 2.0 - 1.0;
let face = targetFace();
var vec: vec3f;
if (face == 0.0) {
vec = vec3f(1, -st.y, -st.x);
} else if (face == 1.0) {
vec = vec3f(-1, -st.y, st.x);
} else if (face == 2.0) {
vec = vec3f(st.x, 1, st.y);
} else if (face == 3.0) {
vec = vec3f(st.x, -1, -st.y);
} else if (face == 4.0) {
vec = vec3f(st.x, -st.y, 1);
} else {
vec = vec3f(-st.x, -st.y, -1);
}
return normalize(modifySeams(vec, 1.0));
}
fn matrixFromVector(n: vec3f) -> mat3x3f {
let a = 1.0 / (1.0 + n.z);
let b = -n.x * n.y * a;
let b1 = vec3f(1.0 - n.x * n.x * a, b, -n.x);
let b2 = vec3f(b, 1.0 - n.y * n.y * a, -n.y);
return mat3x3f(b1, b2, n);
}
fn matrixFromVectorSlow(n: vec3f) -> mat3x3f {
let up = select(vec3f(0.0, 0.0, select(-1.0, 1.0, n.y > 0.0)), vec3f(0.0, 1.0, 0.0), abs(n.y) > 0.0000001);
let x = normalize(cross(up, n));
let y = cross(n, x);
return mat3x3f(x, y, n);
}
fn reproject(uv: vec2f) -> vec4f {
if ({NUM_SAMPLES} <= 1) {
return {ENCODE_FUNC}({DECODE_FUNC}({SOURCE_FUNC}Dir({TARGET_FUNC}(uv))));
} else {
let t = {TARGET_FUNC}(uv);
let tu = dpdx(t);
let tv = dpdy(t);
var result = vec3f(0.0);
for (var u = 0.0; u < {NUM_SAMPLES_SQRT}; u += 1.0) {
for (var v = 0.0; v < {NUM_SAMPLES_SQRT}; v += 1.0) {
result += {DECODE_FUNC}({SOURCE_FUNC}Dir(normalize(t +
tu * (u / {NUM_SAMPLES_SQRT} - 0.5) +
tv * (v / {NUM_SAMPLES_SQRT} - 0.5))));
}
}
return {ENCODE_FUNC}(result / ({NUM_SAMPLES_SQRT} * {NUM_SAMPLES_SQRT}));
}
}
const unpackFloat: vec4f = vec4f(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0);
#ifdef USE_SAMPLES_TEX
fn unpackSample(i: i32, L: ptr<function, vec3f>, mipLevel: ptr<function, f32>) {
var u = (f32(i * 4) + 0.5) * uniform.samplesTexInverseSize.x;
var v = (floor(u) + 0.5) * uniform.samplesTexInverseSize.y;
var raw: vec4f;
raw.x = dot(textureSample(samplesTex, samplesTexSampler, vec2f(u, v)), unpackFloat); u += uniform.samplesTexInverseSize.x;
raw.y = dot(textureSample(samplesTex, samplesTexSampler, vec2f(u, v)), unpackFloat); u += uniform.samplesTexInverseSize.x;
raw.z = dot(textureSample(samplesTex, samplesTexSampler, vec2f(u, v)), unpackFloat); u += uniform.samplesTexInverseSize.x;
raw.w = dot(textureSample(samplesTex, samplesTexSampler, vec2f(u, v)), unpackFloat);
*L = raw.xyz * 2.0 - 1.0;
*mipLevel = raw.w * 8.0;
}
fn prefilterSamples(uv: vec2f) -> vec4f {
let vecSpace = matrixFromVectorSlow({TARGET_FUNC}(uv));
var L: vec3f;
var mipLevel: f32;
var result = vec3f(0.0);
var totalWeight = 0.0;
for (var i = 0; i < {NUM_SAMPLES}; i += 1) {
unpackSample(i, &L, &mipLevel);
result += {DECODE_FUNC}({SOURCE_FUNC}DirLod(vecSpace * L, mipLevel)) * L.z;
totalWeight += L.z;
}
return {ENCODE_FUNC}(result / totalWeight);
}
fn prefilterSamplesUnweighted(uv: vec2f) -> vec4f {
let vecSpace = matrixFromVectorSlow({TARGET_FUNC}(uv));
var L: vec3f;
var mipLevel: f32;
var result = vec3f(0.0);
for (var i = 0; i < {NUM_SAMPLES}; i += 1) {
unpackSample(i, &L, &mipLevel);
result += {DECODE_FUNC}({SOURCE_FUNC}DirLod(vecSpace * L, mipLevel));
}
return {ENCODE_FUNC}(result / f32({NUM_SAMPLES}));
}
#endif
@fragment
fn fragmentMain(input : FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
output.color = {PROCESS_FUNC}(input.vUv0);
return output;
}
`;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 SN=`
var uSceneDepthMap: texture_2d<uff>;
#ifndef SCREENSIZE
#define SCREENSIZE
uniform uScreenSize: vec4f;
#endif
#ifndef VIEWMATRIX
#define VIEWMATRIX
uniform matrix_view: mat4x4f;
#endif
#ifndef LINEARIZE_DEPTH
#define LINEARIZE_DEPTH
#ifndef CAMERAPLANES
#define CAMERAPLANES
uniform camera_params: vec4f;
#endif
fn linearizeDepth(z: f32) -> f32 {
if (uniform.camera_params.w == 0.0) {
return (uniform.camera_params.z * uniform.camera_params.y) / (uniform.camera_params.y + z * (uniform.camera_params.z - uniform.camera_params.y));
} else {
return uniform.camera_params.z + z * (uniform.camera_params.y - uniform.camera_params.z);
}
}
#endif
fn delinearizeDepth(linearDepth: f32) -> f32 {
if (uniform.camera_params.w == 0.0) {
return (uniform.camera_params.y * (uniform.camera_params.z - linearDepth)) / (linearDepth * (uniform.camera_params.z - uniform.camera_params.y));
} else {
return (linearDepth - uniform.camera_params.z) / (uniform.camera_params.y - uniform.camera_params.z);
}
}
fn getLinearScreenDepth(uv: vec2f) -> f32 {
let textureSize = textureDimensions(uSceneDepthMap, 0);
let texel: vec2i = vec2i(uv * vec2f(textureSize));
#ifdef SCENE_DEPTHMAP_LINEAR
return textureLoad(uSceneDepthMap, texel, 0).r;
#else
return linearizeDepth(textureLoad(uSceneDepthMap, texel, 0).r);
#endif
}
#ifndef VERTEXSHADER
fn getLinearScreenDepthFrag() -> f32 {
let uv: vec2f = pcPosition.xy * uniform.uScreenSize.zw;
return getLinearScreenDepth(uv);
}
#endif
fn getLinearDepth(pos: vec3f) -> f32 {
return -(uniform.matrix_view * vec4f(pos, 1.0)).z;
}
`;var xN=`
fn getShadowCascadeIndex(shadowCascadeDistances: vec4f, shadowCascadeCount: i32) -> i32 {
let depth: f32 = 1.0 / pcPosition.w;
let comparisons: vec4f = step(shadowCascadeDistances, vec4f(depth));
let cascadeIndex: i32 = i32(dot(comparisons, vec4f(1.0)));
return min(cascadeIndex, shadowCascadeCount - 1);
}
fn ditherShadowCascadeIndex(cascadeIndex_in: i32, shadowCascadeDistances: vec4f, shadowCascadeCount: i32, blendFactor: f32) -> i32 {
var cascadeIndex: i32 = cascadeIndex_in;
if (cascadeIndex < shadowCascadeCount - 1) {
let currentRangeEnd: f32 = shadowCascadeDistances[cascadeIndex];
let transitionStart: f32 = blendFactor * currentRangeEnd;
let depth: f32 = 1.0 / pcPosition.w;
if (depth > transitionStart) {
let transitionFactor: f32 = smoothstep(transitionStart, currentRangeEnd, depth);
let dither: f32 = fract(sin(dot(pcPosition.xy, vec2f(12.9898, 78.233))) * 43758.5453);
if (dither < transitionFactor) {
cascadeIndex = cascadeIndex + 1;
}
}
}
return cascadeIndex;
}
fn fadeShadow(shadowCoord_in: vec3f, shadowCascadeDistances: vec4f) -> vec3f {
var shadowCoord: vec3f = shadowCoord_in;
let depth: f32 = 1.0 / pcPosition.w;
if (depth > shadowCascadeDistances.w) {
shadowCoord.z = -9999999.0;
}
return shadowCoord;
}
`;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);
}
fn chebyshevUpperBound(moments: vec2f, mean: f32, minVariance: f32, lightBleedingReduction: f32) -> f32 {
var variance: f32 = moments.y - (moments.x * moments.x);
variance = max(variance, minVariance);
let d: f32 = mean - moments.x;
var pMax: f32 = variance / (variance + (d * d));
pMax = reduceLightBleeding(pMax, lightBleedingReduction);
return select(pMax, 1.0, mean <= moments.x);
}
fn calculateEVSM(moments_in: vec3f, Z_in: f32, vsmBias: f32, exponent: f32) -> f32 {
let Z: f32 = 2.0 * Z_in - 1.0;
let warpedDepth: f32 = exp(exponent * Z);
let moments: vec2f = moments_in.xy + vec2f(warpedDepth, warpedDepth*warpedDepth) * (1.0 - moments_in.z);
let VSMBias: f32 = vsmBias;
let depthScale: f32 = VSMBias * exponent * warpedDepth;
let minVariance1: f32 = depthScale * depthScale;
return chebyshevUpperBound(moments, warpedDepth, minVariance1, 0.1);
}
fn VSM16(tex: texture_2d<f32>, texSampler: sampler, texCoords: vec2f, resolution: f32, Z: f32, vsmBias: f32, exponent: f32) -> f32 {
let moments: vec3f = textureSampleLevel(tex, texSampler, texCoords, 0.0).xyz;
return calculateEVSM(moments, Z, vsmBias, exponent);
}
fn getShadowVSM16(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, shadowCoord: vec3f, shadowParams: vec4f, exponent: f32) -> f32 {
return VSM16(shadowMap, shadowMapSampler, shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent);
}
fn getShadowSpotVSM16(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, shadowCoord: vec3f, shadowParams: vec4f, exponent: f32, lightDir: vec3f) -> f32 {
let Z: f32 = length(lightDir) * shadowParams.w + shadowParams.z;
return VSM16(shadowMap, shadowMapSampler, shadowCoord.xy, shadowParams.x, Z, shadowParams.y, exponent);
}
fn VSM32(tex: texture_2d<f32>, texSampler: sampler, texCoords_in: vec2f, resolution: f32, Z: f32, vsmBias: f32, exponent: f32) -> f32 {
#ifdef CAPS_TEXTURE_FLOAT_FILTERABLE
var moments: vec3f = textureSampleLevel(tex, texSampler, texCoords_in, 0.0).xyz;
#else
var pixelSize : f32 = 1.0 / resolution;
let texCoords: vec2f = texCoords_in - vec2f(pixelSize);
let s00: vec3f = textureSampleLevel(tex, texSampler, texCoords, 0.0).xyz;
let s10: vec3f = textureSampleLevel(tex, texSampler, texCoords + vec2f(pixelSize, 0.0), 0.0).xyz;
let s01: vec3f = textureSampleLevel(tex, texSampler, texCoords + vec2f(0.0, pixelSize), 0.0).xyz;
let s11: vec3f = textureSampleLevel(tex, texSampler, texCoords + vec2f(pixelSize), 0.0).xyz;
let fr: vec2f = fract(texCoords * resolution);
let h0: vec3f = mix(s00, s10, fr.x);
let h1: vec3f = mix(s01, s11, fr.x);
var moments: vec3f = mix(h0, h1, fr.y);
#endif
return calculateEVSM(moments, Z, vsmBias, exponent);
}
fn getShadowVSM32(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, shadowCoord: vec3f, shadowParams: vec4f, exponent: f32) -> f32 {
return VSM32(shadowMap, shadowMapSampler, shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent);
}
fn getShadowSpotVSM32(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, shadowCoord: vec3f, shadowParams: vec4f, exponent: f32, lightDir: vec3f) -> f32 {
let Z: f32 = length(lightDir) * shadowParams.w + shadowParams.z;
return VSM32(shadowMap, shadowMapSampler, shadowCoord.xy, shadowParams.x, Z, shadowParams.y, exponent);
}
`;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);
}
`;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;
let shadowMapSizeInv: f32 = 1.0 / shadowParams.x;
let base_uv_temp: vec2f = floor(uv + 0.5);
let s: f32 = (uv.x + 0.5 - base_uv_temp.x);
let t: f32 = (uv.y + 0.5 - base_uv_temp.y);
let base_uv: vec2f = (base_uv_temp - vec2f(0.5)) * shadowMapSizeInv;
var sum: f32 = 0.0;
let uw0: f32 = (3.0 - 2.0 * s);
let uw1: f32 = (1.0 + 2.0 * s);
let u0_offset: f32 = (2.0 - s) / uw0 - 1.0;
let u1_offset: f32 = s / uw1 + 1.0;
let vw0: f32 = (3.0 - 2.0 * t);
let vw1: f32 = (1.0 + 2.0 * t);
let v0_offset: f32 = (2.0 - t) / vw0 - 1.0;
let v1_offset: f32 = t / vw1 + 1.0;
let u0: f32 = u0_offset * shadowMapSizeInv + base_uv.x;
let v0: f32 = v0_offset * shadowMapSizeInv + base_uv.y;
let u1: f32 = u1_offset * shadowMapSizeInv + base_uv.x;
let v1: f32 = v1_offset * shadowMapSizeInv + base_uv.y;
sum = sum + uw0 * vw0 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u0, v0), z);
sum = sum + uw1 * vw0 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u1, v0), z);
sum = sum + uw0 * vw1 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u0, v1), z);
sum = sum + uw1 * vw1 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u1, v1), z);
sum = sum * (1.0 / 16.0);
return sum;
}
fn getShadowPCF3x3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {
return _getShadowPCF3x3(shadowMap, shadowMapSampler, shadowCoord, shadowParams.xyz);
}
fn getShadowSpotPCF3x3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {
return _getShadowPCF3x3(shadowMap, shadowMapSampler, shadowCoord, shadowParams.xyz);
}
`;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;
let shadowMapSizeInv: f32 = 1.0 / shadowParams.x;
let base_uv_temp: vec2f = floor(uv + 0.5);
let s: f32 = (uv.x + 0.5 - base_uv_temp.x);
let t: f32 = (uv.y + 0.5 - base_uv_temp.y);
let base_uv: vec2f = (base_uv_temp - vec2f(0.5)) * shadowMapSizeInv;
let uw0: f32 = (4.0 - 3.0 * s);
let uw1: f32 = 7.0;
let uw2: f32 = (1.0 + 3.0 * s);
let u0_offset: f32 = (3.0 - 2.0 * s) / uw0 - 2.0;
let u1_offset: f32 = (3.0 + s) / uw1;
let u2_offset: f32 = s / uw2 + 2.0;
let vw0: f32 = (4.0 - 3.0 * t);
let vw1: f32 = 7.0;
let vw2: f32 = (1.0 + 3.0 * t);
let v0_offset: f32 = (3.0 - 2.0 * t) / vw0 - 2.0;
let v1_offset: f32 = (3.0 + t) / vw1;
let v2_offset: f32 = t / vw2 + 2.0;
var sum: f32 = 0.0;
let u0: f32 = u0_offset * shadowMapSizeInv + base_uv.x;
let v0: f32 = v0_offset * shadowMapSizeInv + base_uv.y;
let u1: f32 = u1_offset * shadowMapSizeInv + base_uv.x;
let v1: f32 = v1_offset * shadowMapSizeInv + base_uv.y;
let u2: f32 = u2_offset * shadowMapSizeInv + base_uv.x;
let v2: f32 = v2_offset * shadowMapSizeInv + base_uv.y;
sum = sum + uw0 * vw0 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u0, v0), z);
sum = sum + uw1 * vw0 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u1, v0), z);
sum = sum + uw2 * vw0 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u2, v0), z);
sum = sum + uw0 * vw1 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u0, v1), z);
sum = sum + uw1 * vw1 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u1, v1), z);
sum = sum + uw2 * vw1 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u2, v1), z);
sum = sum + uw0 * vw2 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u0, v2), z);
sum = sum + uw1 * vw2 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u1, v2), z);
sum = sum + uw2 * vw2 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u2, v2), z);
sum = sum * (1.0 / 144.0);
sum = saturate(sum);
return sum;
}
fn getShadowPCF5x5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {
return _getShadowPCF5x5(shadowMap, shadowMapSampler, shadowCoord, shadowParams.xyz);
}
fn getShadowSpotPCF5x5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 {
return _getShadowPCF5x5(shadowMap, shadowMapSampler, shadowCoord, shadowParams.xyz);
}
`;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;
let dt: f32 = dot(uv.xy, vec2f(a, b));
let sn: f32 = dt % PI;
return fract(sin(sn) * c);
}
struct VogelDiskData {
invNumSamples: f32,
initialAngle: f32,
currentPointId: f32,
}
fn prepareDiskConstants(data: ptr<function, VogelDiskData>, sampleCount: i32, randomSeed: f32) {
let pi2: f32 = 6.28318530718;
data.invNumSamples = 1.0 / f32(sampleCount);
data.initialAngle = randomSeed * pi2;
data.currentPointId = 0.0;
}
fn generateDiskSample(data: ptr<function, VogelDiskData>) -> vec2f {
let GOLDEN_ANGLE: f32 = 2.399963;
let r: f32 = sqrt((data.currentPointId + 0.5) * data.invNumSamples);
let theta: f32 = data.currentPointId * GOLDEN_ANGLE + data.initialAngle;
let offset: vec2f = vec2f(cos(theta), sin(theta)) * pow(r, 1.33);
data.currentPointId = data.currentPointId + 1.0;
return offset;
}
fn PCSSFindBlocker(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, avgBlockerDepth: ptr<function, f32>, numBlockers: ptr<function, i32>,
shadowCoords: vec2f, z: f32, shadowBlockerSamples: i32, penumbraSize: f32, invShadowMapSize: f32, randomSeed: f32) {
var diskData: VogelDiskData;
prepareDiskConstants(&diskData, shadowBlockerSamples, randomSeed);
let searchWidth: f32 = penumbraSize * invShadowMapSize;
var blockerSum: f32 = 0.0;
var numBlockers_local: i32 = 0;
for( var i: i32 = 0; i < shadowBlockerSamples; i = i + 1 ) {
let diskUV: vec2f = generateDiskSample(&diskData);
let sampleUV: vec2f = shadowCoords + diskUV * searchWidth;
let shadowMapDepth: f32 = textureSampleLevel(shadowMap, shadowMapSampler, sampleUV, 0.0).r;
if ( shadowMapDepth < z ) {
blockerSum = blockerSum + shadowMapDepth;
numBlockers_local = numBlockers_local + 1;
}
}
*avgBlockerDepth = blockerSum / f32(numBlockers_local);
*numBlockers = numBlockers_local;
}
fn PCSSFilter(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, uv: vec2f, receiverDepth: f32, shadowSamples: i32, filterRadius: f32, randomSeed: f32) -> f32 {
var diskData: VogelDiskData;
prepareDiskConstants(&diskData, shadowSamples, randomSeed);
var sum: f32 = 0.0;
for (var i: i32 = 0; i < shadowSamples; i = i + 1) {
let offsetUV: vec2f = generateDiskSample(&diskData) * filterRadius;
let depth: f32 = textureSampleLevel(shadowMap, shadowMapSampler, uv + offsetUV, 0.0).r;
sum = sum + step(receiverDepth, depth);
}
return sum / f32(shadowSamples);
}
fn getPenumbra(dblocker: f32, dreceiver: f32, penumbraSize: f32, penumbraFalloff: f32) -> f32 {
let dist: f32 = dreceiver - dblocker;
let penumbra: f32 = 1.0 - pow(1.0 - dist, penumbraFalloff);
return penumbra * penumbraSize;
}
fn PCSSDirectional(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, shadowCoords: vec3f, cameraParams: vec4f, softShadowParams: vec4f) -> f32 {
let receiverDepth: f32 = shadowCoords.z;
let randomSeed: f32 = fractSinRand(pcPosition.xy);
let shadowSamples: i32 = i32(softShadowParams.x);
let shadowBlockerSamples: i32 = i32(softShadowParams.y);
let penumbraSize: f32 = softShadowParams.z;
let penumbraFalloff: f32 = softShadowParams.w;
let shadowMapSize: i32 = i32(textureDimensions(shadowMap, 0).x);
var invShadowMapSize: f32 = 1.0 / f32(shadowMapSize);
invShadowMapSize = invShadowMapSize * (f32(shadowMapSize) / 2048.0);
var penumbra: f32;
if (shadowBlockerSamples > 0) {
var avgBlockerDepth: f32 = 0.0;
var numBlockers: i32 = 0;
PCSSFindBlocker(shadowMap, shadowMapSampler, &avgBlockerDepth, &numBlockers, shadowCoords.xy, receiverDepth, shadowBlockerSamples, penumbraSize, invShadowMapSize, randomSeed);
if (numBlockers < 1) {
return 1.0;
}
penumbra = getPenumbra(avgBlockerDepth, shadowCoords.z, penumbraSize, penumbraFalloff);
} else {
penumbra = penumbraSize;
}
let filterRadius: f32 = penumbra * invShadowMapSize;
return PCSSFilter(shadowMap, shadowMapSampler, shadowCoords.xy, receiverDepth, shadowSamples, filterRadius, randomSeed);
}
fn getShadowPCSS(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, shadowCoord: vec3f, shadowParams: vec4f, cameraParams: vec4f, softShadowParams: vec4f, lightDir: vec3f) -> f32 {
return PCSSDirectional(shadowMap, shadowMapSampler, shadowCoord, cameraParams, softShadowParams);
}
`;var CN=`
attribute vertex_boneIndices: f32;
var texture_poseMap: texture_2d<uff>;
fn getBoneMatrix(indexFloat: f32) -> mat4x4f {
let width = i32(textureDimensions(texture_poseMap).x);
let index: i32 = i32(indexFloat + 0.5) * 3;
let iy: i32 = index / width;
let ix: i32 = index % width;
let v1: vec4f = textureLoad(texture_poseMap, vec2i(ix + 0, iy), 0);
let v2: vec4f = textureLoad(texture_poseMap, vec2i(ix + 1, iy), 0);
let v3: vec4f = textureLoad(texture_poseMap, vec2i(ix + 2, iy), 0);
return mat4x4f(
v1.x, v2.x, v3.x, 0,
v1.y, v2.y, v3.y, 0,
v1.z, v2.z, v3.z, 0,
v1.w, v2.w, v3.w, 1.0
);
}
`;var PN=`
attribute vertex_boneWeights: vec4f;
attribute vertex_boneIndices: vec4f;
var texture_poseMap: texture_2d<uff>;
struct BoneMatrix {
v1: vec4f,
v2: vec4f,
v3: vec4f,
}
fn getBoneMatrix(width: i32, index: i32) -> BoneMatrix {
let v = index / width;
let u = index % width;
var result: BoneMatrix;
result.v1 = textureLoad(texture_poseMap, vec2i(u + 0, v), 0);
result.v2 = textureLoad(texture_poseMap, vec2i(u + 1, v), 0);
result.v3 = textureLoad(texture_poseMap, vec2i(u + 2, v), 0);
return result;
}
fn getSkinMatrix(indicesFloat: vec4f, weights: vec4f) -> mat4x4f {
let width = i32(textureDimensions(texture_poseMap).x);
var indices = vec4i(indicesFloat + 0.5) * 3;
let boneA = getBoneMatrix(width, indices.x);
let boneB = getBoneMatrix(width, indices.y);
let boneC = getBoneMatrix(width, indices.z);
let boneD = getBoneMatrix(width, indices.w);
let v1 = boneA.v1 * weights.x + boneB.v1 * weights.y + boneC.v1 * weights.z + boneD.v1 * weights.w;
let v2 = boneA.v2 * weights.x + boneB.v2 * weights.y + boneC.v2 * weights.z + boneD.v2 * weights.w;
let v3 = boneA.v3 * weights.x + boneB.v3 * weights.y + boneC.v3 * weights.z + boneD.v3 * weights.w;
let one = dot(weights, vec4f(1.0, 1.0, 1.0, 1.0));
return mat4x4f(
v1.x, v2.x, v3.x, 0,
v1.y, v2.y, v3.y, 0,
v1.z, v2.z, v3.z, 0,
v1.w, v2.w, v3.w, one
);
}
`;var wN=`
#define LIT_SKYBOX_INTENSITY
#include "envProcPS"
#include "gammaPS"
#include "tonemappingPS"
#ifdef PREPASS_PASS
varying vLinearDepth: f32;
#include "floatAsUintPS"
#endif
varying vViewDir : vec3f;
uniform skyboxHighlightMultiplier : f32;
#if defined(SKY_FISHEYE) && !defined(SKYMESH)
uniform fisheye_k : f32;
uniform fisheye_invK : f32;
uniform fisheye_projMat00 : f32;
uniform fisheye_projMat11 : f32;
uniform matrix_view : mat4x4f;
uniform cubeMapRotationMatrix : mat3x3f;
varying vClipXYW : vec3f;
#endif
#ifdef SKY_CUBEMAP
var texture_cubeMap : texture_cube<f32>;
var texture_cubeMap_sampler : sampler;
#ifdef SKYMESH
varying vWorldPos : vec3f;
uniform cubeMapRotationMatrix : mat3x3f;
uniform projectedSkydomeCenter : vec3f;
#endif
#else
#include "sphericalPS"
#include "envAtlasPS"
var texture_envAtlas : texture_2d<f32>;
var texture_envAtlas_sampler : sampler;
uniform mipLevel : f32;
#endif
@fragment
fn fragmentMain(input : FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
#ifdef PREPASS_PASS
output.color = float2vec4(vLinearDepth);
#else
var linear : vec3f;
var dir : vec3f;
#if defined(SKY_FISHEYE) && !defined(SKYMESH)
let ndc : vec2f = input.vClipXYW.xy / input.vClipXYW.z;
let px : f32 = ndc.x / uniform.fisheye_projMat00;
let py : f32 = ndc.y / uniform.fisheye_projMat11;
let r : f32 = sqrt(px * px + py * py);
let theta : f32 = uniform.fisheye_k * atan(r * uniform.fisheye_invK);
let sinT : f32 = sin(theta);
let cosT : f32 = cos(theta);
var camDir : vec3f;
if (r > 1e-6) {
camDir = vec3f(px / r * sinT, py / r * sinT, -cosT);
} else {
camDir = vec3f(0.0, 0.0, -1.0);
}
let viewMat3 : mat3x3f = mat3x3f(
uniform.matrix_view[0].xyz,
uniform.matrix_view[1].xyz,
uniform.matrix_view[2].xyz
);
dir = transpose(viewMat3) * camDir;
dir = dir * uniform.cubeMapRotationMatrix;
#elif defined(SKY_CUBEMAP) && defined(SKYMESH)
var envDir : vec3f = normalize(input.vWorldPos - uniform.projectedSkydomeCenter);
dir = envDir * uniform.cubeMapRotationMatrix;
#else
dir = input.vViewDir;
#endif
#ifdef SKY_CUBEMAP
dir.x *= -1.0;
linear = {SKYBOX_DECODE_FNC}(textureSample(texture_cubeMap, texture_cubeMap_sampler, dir));
#else
dir *= vec3f(-1.0, 1.0, 1.0);
let uv : vec2f = toSphericalUv(normalize(dir));
linear = {SKYBOX_DECODE_FNC}(textureSample(texture_envAtlas, texture_envAtlas_sampler, mapRoughnessUv(uv, uniform.mipLevel)));
#endif
if (any(linear >= vec3f(64.0))) {
linear *= uniform.skyboxHighlightMultiplier;
}
output.color = vec4f(gammaCorrectOutput(toneMap(processEnvironment(linear))), 1.0);
#endif
return output;
}
`;var IN=`
attribute aPosition : vec4f;
uniform matrix_view : mat4x4f;
uniform matrix_projectionSkybox : mat4x4f;
uniform cubeMapRotationMatrix : mat3x3f;
varying vViewDir : vec3f;
#ifdef SKY_FISHEYE
varying vClipXYW : vec3f;
#endif
#ifdef PREPASS_PASS
varying vLinearDepth: f32;
#endif
#ifdef SKYMESH
uniform matrix_model : mat4x4f;
varying vWorldPos : vec3f;
#endif
@vertex
fn vertexMain(input : VertexInput) -> VertexOutput {
var output : VertexOutput;
var view : mat4x4f = uniform.matrix_view;
#ifdef SKYMESH
var worldPos : vec4f = uniform.matrix_model * input.aPosition;
output.vWorldPos = worldPos.xyz;
output.position = uniform.matrix_projectionSkybox * (view * worldPos);
#ifdef PREPASS_PASS
output.vLinearDepth = -(uniform.matrix_view * vec4f(worldPos.xyz, 1.0)).z;
#endif
#else
view[3][0] = 0.0;
view[3][1] = 0.0;
view[3][2] = 0.0;
output.vViewDir = input.aPosition.xyz * uniform.cubeMapRotationMatrix;
#ifdef SKY_FISHEYE
var viewPos : vec4f = view * input.aPosition;
output.position = vec4f(viewPos.xy, 0.0, -viewPos.z);
output.vClipXYW = vec3f(output.position.xy, output.position.w);
#else
output.position = uniform.matrix_projectionSkybox * (view * input.aPosition);
#endif
#ifdef PREPASS_PASS
output.vLinearDepth = -pcPosition.w;
#endif
#endif
output.position.z = output.position.w - 1.0e-7;
return output;
}
`;var vm=`
fn writeSortIndirectArgs(
baseSlot: u32,
count: u32,
slotInfo: vec4<u32>
) {
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
fn getSpecularity() {
var specularColor = vec3f(1.0, 1.0, 1.0);
#ifdef STD_SPECULAR_CONSTANT
specularColor = specularColor * uniform.material_specular;
#endif
#ifdef STD_SPECULAR_TEXTURE
specularColor = specularColor * {STD_SPECULAR_TEXTURE_DECODE}(textureSampleBias({STD_SPECULAR_TEXTURE_NAME}, {STD_SPECULAR_TEXTURE_NAME}Sampler, {STD_SPECULAR_TEXTURE_UV}, uniform.textureBias)).{STD_SPECULAR_TEXTURE_CHANNEL};
#endif
#ifdef STD_SPECULAR_VERTEX
specularColor = specularColor * saturate3(vVertexColor.{STD_SPECULAR_VERTEX_CHANNEL});
#endif
dSpecularity = specularColor;
}
`;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));
}
fn toSphericalUv(dir : vec3f) -> vec2f {
const PI : f32 = 3.141592653589793;
let uv : vec2f = toSpherical(dir) / vec2f(PI * 2.0, PI) + vec2f(0.5, 0.5);
return vec2f(uv.x, 1.0 - uv.y);
}
`;var DN=`
#ifdef STD_SPECULARITYFACTOR_CONSTANT
uniform material_specularityFactor: f32;
#endif
fn getSpecularityFactor() {
var specularityFactor = 1.0;
#ifdef STD_SPECULARITYFACTOR_CONSTANT
specularityFactor = specularityFactor * uniform.material_specularityFactor;
#endif
#ifdef STD_SPECULARITYFACTOR_TEXTURE
specularityFactor = specularityFactor * textureSampleBias({STD_SPECULARITYFACTOR_TEXTURE_NAME}, {STD_SPECULARITYFACTOR_TEXTURE_NAME}Sampler, {STD_SPECULARITYFACTOR_TEXTURE_UV}, uniform.textureBias).{STD_SPECULARITYFACTOR_TEXTURE_CHANNEL};
#endif
#ifdef STD_SPECULARITYFACTOR_VERTEX
specularityFactor = specularityFactor * saturate(vVertexColor.{STD_SPECULARITYFACTOR_VERTEX_CHANNEL});
#endif
dSpecularityFactor = specularityFactor;
}
`;var LN=`
fn getSpotEffect(lightSpotDir: vec3f, lightInnerConeAngle: f32, lightOuterConeAngle: f32, lightDirNorm: vec3f) -> f32 {
let cosAngle: f32 = dot(lightDirNorm, lightSpotDir);
return smoothstep(lightOuterConeAngle, lightInnerConeAngle, cosAngle);
}`;var MN=`
nineSlicedUv = vec2f(vUv0.x, 1.0 - vUv0.y);
`;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);
var clampedUv: vec2f = mix(innerOffset.xy * 0.5, vec2f(1.0) - innerOffset.zw * 0.5, fract((vTiledUv - tileSize) * tileScale));
clampedUv = clampedUv * atlasRect.zw + atlasRect.xy;
var nineSlicedUv: vec2f = vUv0 * tileMask + clampedUv * (vec2f(1.0) - tileMask);
nineSlicedUv.y = 1.0 - nineSlicedUv.y;
`;var FN=`
var<private> 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
var texture_opacityMap : texture_2d<f32>;
var texture_opacityMapSampler : sampler;
#endif
#endif
#ifdef FORWARD_PASS
var<private> dAlbedo: vec3f;
var<private> dNormalW: vec3f;
var<private> dSpecularity: vec3f = vec3f(0.0, 0.0, 0.0);
var<private> dGlossiness: f32 = 0.0;
#ifdef LIT_REFRACTION
var<private> dTransmission: f32;
var<private> dThickness: f32;
#endif
#ifdef LIT_SCENE_COLOR
var uSceneColorMap : texture_2d<f32>;
var uSceneColorMapSampler : sampler;
#endif
#ifdef LIT_SCREEN_SIZE
uniform uScreenSize: vec4f;
#endif
#ifdef LIT_TRANSFORMS
var<private> matrix_viewProjection: mat4x4f;
var<private> matrix_model: mat4x4f;
#endif
#ifdef STD_HEIGHT_MAP
var<private> dUvOffset: vec2f;
#ifdef STD_HEIGHT_TEXTURE_ALLOCATE
var texture_heightMap : texture_2d<f32>;
var texture_heightMapSampler : sampler;
#endif
#endif
#ifdef STD_DIFFUSE_TEXTURE_ALLOCATE
var texture_diffuseMap : texture_2d<f32>;
var texture_diffuseMapSampler : sampler;
#endif
#ifdef STD_DIFFUSEDETAIL_TEXTURE_ALLOCATE
var texture_diffuseDetailMap : texture_2d<f32>;
var texture_diffuseDetailMapSampler : sampler;
#endif
#ifdef STD_NORMAL_TEXTURE_ALLOCATE
var texture_normalMap : texture_2d<f32>;
var texture_normalMapSampler : sampler;
#endif
#ifdef STD_NORMALDETAIL_TEXTURE_ALLOCATE
var texture_normalDetailMap : texture_2d<f32>;
var texture_normalDetailMapSampler : sampler;
#endif
#ifdef STD_THICKNESS_TEXTURE_ALLOCATE
var texture_thicknessMap : texture_2d<f32>;
var texture_thicknessMapSampler : sampler;
#endif
#ifdef STD_REFRACTION_TEXTURE_ALLOCATE
var texture_refractionMap : texture_2d<f32>;
var texture_refractionMapSampler : sampler;
#endif
#ifdef LIT_IRIDESCENCE
var<private> dIridescence: f32;
var<private> dIridescenceThickness: f32;
#ifdef STD_IRIDESCENCE_THICKNESS_TEXTURE_ALLOCATE
var texture_iridescenceThicknessMap : texture_2d<f32>;
var texture_iridescenceThicknessMapSampler : sampler;
#endif
#ifdef STD_IRIDESCENCE_TEXTURE_ALLOCATE
var texture_iridescenceMap : texture_2d<f32>;
var texture_iridescenceMapSampler : sampler;
#endif
#endif
#ifdef LIT_CLEARCOAT
var<private> ccSpecularity: f32;
var<private> ccGlossiness: f32;
var<private> ccNormalW: vec3f;
#endif
#ifdef LIT_GGX_SPECULAR
var<private> dAnisotropy: f32;
var<private> dAnisotropyRotation: vec2f;
#endif
#ifdef LIT_SPECULAR_OR_REFLECTION
#ifdef LIT_SHEEN
var<private> sSpecularity: vec3f;
var<private> sGlossiness: f32;
#ifdef STD_SHEEN_TEXTURE_ALLOCATE
var texture_sheenMap : texture_2d<f32>;
var texture_sheenMapSampler : sampler;
#endif
#ifdef STD_SHEENGLOSS_TEXTURE_ALLOCATE
var texture_sheenGlossMap : texture_2d<f32>;
var texture_sheenGlossMapSampler : sampler;
#endif
#endif
#ifdef LIT_METALNESS
var<private> dMetalness: f32;
var<private> dIor: f32;
#ifdef STD_METALNESS_TEXTURE_ALLOCATE
var texture_metalnessMap : texture_2d<f32>;
var texture_metalnessMapSampler : sampler;
#endif
#endif
#ifdef LIT_SPECULARITY_FACTOR
var<private> dSpecularityFactor: f32;
#ifdef STD_SPECULARITYFACTOR_TEXTURE_ALLOCATE
var texture_specularityFactorMap : texture_2d<f32>;
var texture_specularityFactorMapSampler : sampler;
#endif
#endif
#ifdef STD_SPECULAR_COLOR
#ifdef STD_SPECULAR_TEXTURE_ALLOCATE
var texture_specularMap : texture_2d<f32>;
var texture_specularMapSampler : sampler;
#endif
#endif
#ifdef STD_GLOSS_TEXTURE_ALLOCATE
var texture_glossMap : texture_2d<f32>;
var texture_glossMapSampler : sampler;
#endif
#endif
#ifdef STD_AO
var <private> dAo: f32;
#ifdef STD_AO_TEXTURE_ALLOCATE
var texture_aoMap : texture_2d<f32>;
var texture_aoMapSampler : sampler;
#endif
#ifdef STD_AODETAIL_TEXTURE_ALLOCATE
var texture_aoDetailMap : texture_2d<f32>;
var texture_aoDetailMapSampler : sampler;
#endif
#endif
var <private> dEmission: vec3f;
#ifdef STD_EMISSIVE_TEXTURE_ALLOCATE
var texture_emissiveMap : texture_2d<f32>;
var texture_emissiveMapSampler : sampler;
#endif
#ifdef LIT_CLEARCOAT
#ifdef STD_CLEARCOAT_TEXTURE_ALLOCATE
var texture_clearCoatMap : texture_2d<f32>;
var texture_clearCoatMapSampler : sampler;
#endif
#ifdef STD_CLEARCOATGLOSS_TEXTURE_ALLOCATE
var texture_clearCoatGlossMap : texture_2d<f32>;
var texture_clearCoatGlossMapSampler : sampler;
#endif
#ifdef STD_CLEARCOATNORMAL_TEXTURE_ALLOCATE
var texture_clearCoatNormalMap : texture_2d<f32>;
var texture_clearCoatNormalMapSampler : sampler;
#endif
#endif
#ifdef LIT_GGX_SPECULAR
#ifdef STD_ANISOTROPY_TEXTURE_ALLOCATE
var texture_anisotropyMap : texture_2d<f32>;
var texture_anisotropyMapSampler : sampler;
#endif
#endif
#if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR)
var<private> dLightmap: vec3f;
#ifdef STD_LIGHT_TEXTURE_ALLOCATE
var texture_lightMap : texture_2d<f32>;
var texture_lightMapSampler : sampler;
#endif
#endif
#endif
#include "litShaderCorePS"
`;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)
#include "alphaTestPS"
#endif
#if STD_OPACITY_DITHER != NONE
#include "opacityDitherPS"
#endif
#endif
#ifdef FORWARD_PASS
#ifdef STD_HEIGHT_MAP
#include "parallaxPS"
#endif
#include "diffusePS"
#ifdef LIT_NEEDS_NORMAL
#include "normalMapPS"
#endif
#ifdef LIT_REFRACTION
#include "transmissionPS"
#include "thicknessPS"
#endif
#ifdef LIT_IRIDESCENCE
#include "iridescencePS"
#include "iridescenceThicknessPS"
#endif
#ifdef LIT_SPECULAR_OR_REFLECTION
#ifdef LIT_SHEEN
#include "sheenPS"
#include "sheenGlossPS"
#endif
#ifdef LIT_METALNESS
#include "metalnessPS"
#include "iorPS"
#endif
#ifdef LIT_SPECULARITY_FACTOR
#include "specularityFactorPS"
#endif
#ifdef STD_SPECULAR_COLOR
#include "specularPS"
#else
fn getSpecularity() {
dSpecularity = vec3f(1.0, 1.0, 1.0);
}
#endif
#include "glossPS"
#endif
#ifdef STD_AO
#include "aoPS"
#endif
#include "emissivePS"
#ifdef LIT_CLEARCOAT
#include "clearCoatPS"
#include "clearCoatGlossPS"
#include "clearCoatNormalPS"
#endif
#if defined(LIT_SPECULAR) && defined(LIT_LIGHTING) && defined(LIT_GGX_SPECULAR)
#include "anisotropyPS"
#endif
#if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR)
#include "lightmapPS"
#endif
#endif
fn evaluateFrontend() {
#if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE
getOpacity();
#if defined(LIT_ALPHA_TEST)
alphaTest(dAlpha);
#endif
#if STD_OPACITY_DITHER != NONE
opacityDither(dAlpha * uniform.material_alphaDitherScale, 0.0);
#endif
litArgs_opacity = dAlpha;
#endif
#ifdef FORWARD_PASS
#ifdef STD_HEIGHT_MAP
getParallax();
#endif
getAlbedo();
litArgs_albedo = dAlbedo;
#ifdef LIT_NEEDS_NORMAL
getNormal();
litArgs_worldNormal = dNormalW;
#endif
#ifdef LIT_REFRACTION
getRefraction();
litArgs_transmission = dTransmission;
getThickness();
litArgs_thickness = dThickness;
#ifdef LIT_DISPERSION
litArgs_dispersion = uniform.material_dispersion;
#endif
#endif
#ifdef LIT_IRIDESCENCE
getIridescence();
getIridescenceThickness();
litArgs_iridescence_intensity = dIridescence;
litArgs_iridescence_thickness = dIridescenceThickness;
#endif
#ifdef LIT_SPECULAR_OR_REFLECTION
#ifdef LIT_SHEEN
getSheen();
litArgs_sheen_specularity = sSpecularity;
getSheenGlossiness();
litArgs_sheen_gloss = sGlossiness;
#endif
#ifdef LIT_METALNESS
getMetalness();
litArgs_metalness = dMetalness;
getIor();
litArgs_ior = dIor;
#endif
#ifdef LIT_SPECULARITY_FACTOR
getSpecularityFactor();
litArgs_specularityFactor = dSpecularityFactor;
#endif
getGlossiness();
getSpecularity();
litArgs_specularity = dSpecularity;
litArgs_gloss = dGlossiness;
#endif
#ifdef STD_AO
getAO();
litArgs_ao = dAo;
#endif
getEmission();
litArgs_emission = dEmission;
#ifdef LIT_CLEARCOAT
getClearCoat();
getClearCoatGlossiness();
getClearCoatNormal();
litArgs_clearcoat_specularity = ccSpecularity;
litArgs_clearcoat_gloss = ccGlossiness;
litArgs_clearcoat_worldNormal = ccNormalW;
#endif
#if defined(LIT_SPECULAR) && defined(LIT_LIGHTING) && defined(LIT_GGX_SPECULAR)
getAnisotropy();
#endif
#if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR)
getLightMap();
litArgs_lightmap = dLightmap;
#ifdef STD_LIGHTMAP_DIR
litArgs_lightmapDir = dLightmapDir;
#endif
#endif
#endif
}
`;var BN=`
#ifdef LIT_TANGENTS
#define TBN_TANGENTS
#else
#if defined(LIT_USE_NORMALS) || defined(LIT_USE_CLEARCOAT_NORMALS)
#define TBN_DERIVATIVES
#endif
#endif
#if defined(TBN_DERIVATIVES)
uniform tbnBasis: f32;
#endif
fn getTBN(tangent: vec3f, binormal: vec3f, normal: vec3f) {
#ifdef TBN_TANGENTS
dTBN = mat3x3f(normalize(tangent), normalize(binormal), normalize(normal));
#elif defined(TBN_DERIVATIVES)
let uv: vec2f = {lightingUv};
let dp1: vec3f = dpdx( vPositionW );
let dp2: vec3f = dpdy( vPositionW );
let duv1: vec2f = dpdx( uv );
let duv2: vec2f = dpdy( uv );
let dp2perp: vec3f = cross( dp2, normal );
let dp1perp: vec3f = cross( normal, dp1 );
let T: vec3f = dp2perp * duv1.x + dp1perp * duv2.x;
let B: vec3f = dp2perp * duv1.y + dp1perp * duv2.y;
let denom: f32 = max( dot(T, T), dot(B, B) );
let invmax: f32 = select(uniform.tbnBasis / sqrt( denom ), 0.0, denom == 0.0);
dTBN = mat3x3f(T * invmax, -B * invmax, normal );
#else
var B: vec3f = cross(normal, vObjectSpaceUpW);
var T: vec3f = cross(normal, B);
if (dot(B,B) == 0.0)
{
let major: f32 = max(max(normal.x, normal.y), normal.z);
if (normal.x == major)
{
B = cross(normal, vec3f(0.0, 1.0, 0.0));
T = cross(normal, B);
}
else if (normal.y == major)
{
B = cross(normal, vec3f(0.0, 0.0, 1.0));
T = cross(normal, B);
}
else
{
B = cross(normal, vec3f(1.0, 0.0, 0.0));
T = cross(normal, B);
}
}
dTBN = mat3x3f(normalize(T), normalize(B), normalize(normal));
#endif
}`;var UN=`
#ifdef STD_THICKNESS_CONSTANT
uniform material_thickness: f32;
#endif
fn getThickness() {
dThickness = 1.0;
#ifdef STD_THICKNESS_CONSTANT
dThickness = dThickness * uniform.material_thickness;
#endif
#ifdef STD_THICKNESS_TEXTURE
dThickness = dThickness * textureSampleBias({STD_THICKNESS_TEXTURE_NAME}, {STD_THICKNESS_TEXTURE_NAME}Sampler, {STD_THICKNESS_TEXTURE_UV}, uniform.textureBias).{STD_THICKNESS_TEXTURE_CHANNEL};
#endif
#ifdef STD_THICKNESS_VERTEX
dThickness = dThickness * saturate(vVertexColor.{STD_THICKNESS_VERTEX_CHANNEL});
#endif
}
`;var kN=`
#ifndef TONEMAP_NO_EXPOSURE_UNIFORM
#if TONEMAP != NONE
uniform exposure: f32;
fn getExposure() -> f32 { return uniform.exposure; }
#else
fn getExposure() -> f32 { return 1.0; }
#endif
#else
#if TONEMAP != NONE
fn getExposure() -> f32 { return uniforms.exposure; }
#else
fn getExposure() -> f32 { return 1.0; }
#endif
#endif
#if (TONEMAP == NONE)
#include "tonemappingNonePS"
#elif TONEMAP == FILMIC
#include "tonemappingFilmicPS"
#elif TONEMAP == LINEAR
#include "tonemappingLinearPS"
#elif TONEMAP == HEJL
#include "tonemappingHejlPS"
#elif TONEMAP == ACES
#include "tonemappingAcesPS"
#elif TONEMAP == ACES2
#include "tonemappingAces2PS"
#elif TONEMAP == NEUTRAL
#include "tonemappingNeutralPS"
#endif
`;var zN=`
fn toneMap(color: vec3f) -> vec3f {
let tA: f32 = 2.51;
let tB: f32 = 0.03;
let tC: f32 = 2.43;
let tD: f32 = 0.59;
let tE: f32 = 0.14;
let x: vec3f = color * getExposure();
return (x * (tA * x + tB)) / (x * (tC * x + tD) + tE);
}
`;var GN=`
const ACESInputMat: mat3x3f = mat3x3f(
vec3f(0.59719, 0.35458, 0.04823),
vec3f(0.07600, 0.90834, 0.01566),
vec3f(0.02840, 0.13383, 0.83777)
);
const ACESOutputMat: mat3x3f = mat3x3f(
vec3f( 1.60475, -0.53108, -0.07367),
vec3f(-0.10208, 1.10813, -0.00605),
vec3f(-0.00327, -0.07276, 1.07602)
);
fn RRTAndODTFit(v: vec3f) -> vec3f {
let a: vec3f = v * (v + vec3f(0.0245786)) - vec3f(0.000090537);
let b: vec3f = v * (vec3f(0.983729) * v + vec3f(0.4329510)) + vec3f(0.238081);
return a / b;
}
fn toneMap(color: vec3f) -> vec3f {
var c: vec3f = color * (getExposure() / 0.6);
c = c * ACESInputMat;
c = RRTAndODTFit(c);
c = c * ACESOutputMat;
return clamp(c, vec3f(0.0), vec3f(1.0));
}
`;var VN=`
const A: f32 = 0.15;
const B: f32 = 0.50;
const C: f32 = 0.10;
const D: f32 = 0.20;
const E: f32 = 0.02;
const F: f32 = 0.30;
const W: f32 = 11.2;
fn uncharted2Tonemap(x: vec3f) -> vec3f {
return ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - vec3f(E / F);
}
fn toneMap(color: vec3f) -> vec3f {
var c: vec3f = uncharted2Tonemap(color * getExposure());
let whiteScale: vec3f = vec3f(1.0) / uncharted2Tonemap(vec3f(W, W, W));
c *= whiteScale;
return c;
}
`;var HN=`
fn toneMap(color: vec3f) -> vec3f {
let A: f32 = 0.22;
let B: f32 = 0.3;
let C: f32 = 0.1;
let D: f32 = 0.2;
let E: f32 = 0.01;
let F: f32 = 0.3;
let Scl: f32 = 1.25;
let adjusted_color = color * getExposure();
let h = max(vec3f(0.0), adjusted_color - vec3f(0.004));
return (h * ((Scl * A) * h + Scl * vec3f(C * B)) + Scl * vec3f(D * E)) /
(h * (A * h + vec3f(B)) + vec3f(D * F)) -
Scl * vec3f(E / F);
}
`;var WN=`
fn toneMap(color: vec3f) -> vec3f {
return color * getExposure();
}
`;var XN=`
fn toneMap(col: vec3f) -> vec3f {
var color = col * getExposure();
let startCompression = 0.8 - 0.04;
let desaturation = 0.15;
let x = min(color.r, min(color.g, color.b));
let offset = select(0.04, x - 6.25 * x * x, x < 0.08);
color -= vec3f(offset);
let peak = max(color.r, max(color.g, color.b));
if (peak < startCompression) {
return color;
}
let d = 1.0 - startCompression;
let newPeak = 1.0 - d * d / (peak + d - startCompression);
color *= newPeak / peak;
let g = 1.0 - 1.0 / (desaturation * (peak - newPeak) + 1.0);
return mix(color, vec3f(newPeak), vec3f(g));
}
`;var YN=`
fn toneMap(color: vec3f) -> vec3f {
return color;
}
`;var KN=`
#ifdef PIXELSNAP
uniform uScreenSize: vec4f;
#endif
#ifdef SCREENSPACE
uniform projectionFlipY: f32;
#endif
fn evalWorldPosition(vertexPosition: vec3f, modelMatrix: mat4x4f) -> vec4f {
var localPos: vec3f = getLocalPosition(vertexPosition);
#ifdef NINESLICED
var localPosXZ: vec2f = localPos.xz;
localPosXZ = localPosXZ * uniform.outerScale;
let positiveUnitOffset: vec2f = clamp(vertexPosition.xz, vec2f(0.0), vec2f(1.0));
let negativeUnitOffset: vec2f = clamp(-vertexPosition.xz, vec2f(0.0), vec2f(1.0));
localPosXZ = localPosXZ + (-positiveUnitOffset * uniform.innerOffset.xy + negativeUnitOffset * uniform.innerOffset.zw) * vertex_texCoord0.xy;
dTiledUvGlobal = (localPosXZ - uniform.outerScale + uniform.innerOffset.xy) * -0.5 + 1.0;
localPosXZ = localPosXZ * -0.5;
localPos = vec3f(localPosXZ.x, localPosXZ.y, localPos.y);
#endif
var posW: vec4f = modelMatrix * vec4f(localPos, 1.0);
#ifdef SCREENSPACE
posW = vec4f(posW.xy, 0.0, 1.0);
#endif
return posW;
}
fn getPosition() -> vec4f {
dModelMatrix = getModelMatrix();
let posW: vec4f = evalWorldPosition(vertex_position.xyz, dModelMatrix);
dPositionW = posW.xyz;
var screenPos: vec4f;
#ifdef UV1LAYOUT
screenPos = vec4f(vertex_texCoord1.xy * 2.0 - 1.0, 0.5, 1.0);
screenPos.y *= -1.0;
#else
#ifdef SCREENSPACE
screenPos = posW;
screenPos.y *= uniform.projectionFlipY;
#else
screenPos = uniform.matrix_viewProjection * posW;
#endif
#ifdef PIXELSNAP
screenPos.xy = (screenPos.xy * 0.5) + 0.5;
screenPos.xy *= uniforms.uScreenSize.xy;
screenPos.xy = floor(screenPos.xy);
screenPos.xy *= uniforms.uScreenSize.zw;
screenPos.xy = (screenPos.xy * 2.0) - 1.0;
#endif
#endif
return screenPos;
}
fn getWorldPosition() -> vec3f {
return dPositionW;
}
`;var jN=`
attribute vertex_position: vec4f;
uniform matrix_viewProjection: mat4x4f;
uniform matrix_model: mat4x4f;
#ifdef MORPHING
uniform morph_tex_params: vec2f;
attribute morph_vertex_id: u32;
fn getTextureMorphCoords() -> vec2i {
var textureSize: vec2i = vec2i(uniform.morph_tex_params);
var morphGridV: i32 = i32(morph_vertex_id) / textureSize.x;
var morphGridU: i32 = i32(morph_vertex_id) - (morphGridV * textureSize.x);
morphGridV = textureSize.y - morphGridV - 1;
return vec2i(morphGridU, morphGridV);
}
#ifdef MORPHING_POSITION
#ifdef MORPHING_INT
uniform aabbSize: vec3f;
uniform aabbMin: vec3f;
var morphPositionTex: texture_2d<u32>;
#else
var morphPositionTex: texture_2d<f32>;
#endif
#endif
#endif
#ifdef defined(BATCH)
#include "skinBatchVS"
fn getModelMatrix() -> mat4x4f {
return getBoneMatrix(vertex_boneIndices);
}
#elif defined(SKIN)
#include "skinVS"
fn getModelMatrix() -> mat4x4f {
return uniform.matrix_model * getSkinMatrix(vertex_boneIndices, vertex_boneWeights);
}
#elif defined(INSTANCING)
#include "transformInstancingVS"
#else
fn getModelMatrix() -> mat4x4f {
return uniform.matrix_model;
}
#endif
fn getLocalPosition(vertexPosition: vec3f) -> vec3f {
var localPos: vec3f = vertexPosition;
#ifdef MORPHING_POSITION
var morphUV: vec2i = getTextureMorphCoords();
#ifdef MORPHING_INT
var morphPos: vec3f = vec3f(textureLoad(morphPositionTex, morphUV, 0).xyz) / 65535.0 * uniform.aabbSize + uniform.aabbMin;
#else
var morphPos: vec3f = textureLoad(morphPositionTex, morphUV, 0).xyz;
#endif
localPos += morphPos;
#endif
return localPos;
}
`;var qN=`
attribute instance_line1: vec4f;
attribute instance_line2: vec4f;
attribute instance_line3: vec4f;
attribute instance_line4: vec4f;
fn getModelMatrix() -> mat4x4f {
return uniform.matrix_model * mat4x4f(instance_line1, instance_line2, instance_line3, instance_line4);
}
`;var $N=`
#ifdef STD_REFRACTION_CONSTANT
uniform material_refraction: f32;
#endif
fn getRefraction() {
var refraction: f32 = 1.0;
#ifdef STD_REFRACTION_CONSTANT
refraction = uniform.material_refraction;
#endif
#ifdef STD_REFRACTION_TEXTURE
refraction = refraction * textureSampleBias({STD_REFRACTION_TEXTURE_NAME}, {STD_REFRACTION_TEXTURE_NAME}Sampler, {STD_REFRACTION_TEXTURE_UV}, uniform.textureBias).{STD_REFRACTION_TEXTURE_CHANNEL};
#endif
#ifdef STD_REFRACTION_VERTEX
refraction = refraction * saturate(vVertexColor.{STD_REFRACTION_VERTEX_CHANNEL});
#endif
dTransmission = refraction;
}
`;var ZN=`
fn handleTwoSidedLighting() {
if (!pcFrontFacing) { dTBN[2] = -dTBN[2]; }
}
`;var QN=`
#ifdef NINESLICED
fn getUv0() -> vec2f {
var uv = vertex_position.xz;
let positiveUnitOffset = clamp(vertex_position.xz, vec2f(0.0, 0.0), vec2f(1.0, 1.0));
let negativeUnitOffset = clamp(-vertex_position.xz, vec2f(0.0, 0.0), vec2f(1.0, 1.0));
uv = uv + ((-positiveUnitOffset * uniform.innerOffset.xy) + (negativeUnitOffset * uniform.innerOffset.zw)) * vertex_texCoord0.xy;
uv = uv * -0.5 + vec2f(0.5, 0.5);
uv = uv * uniform.atlasRect.zw + uniform.atlasRect.xy;
dMaskGlobal = vertex_texCoord0.xy;
return uv;
}
#else
fn getUv0() -> vec2f {
return vertex_texCoord0;
}
#endif
`;var JN=`
fn getUv1() -> vec2f {
return vertex_texCoord1;
}
`;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)
);
`;var tB=`
uniform {TRANSFORM_NAME_{i}}0: vec3f;
uniform {TRANSFORM_NAME_{i}}1: vec3f;
`;var sB=`
fn getViewDir() {
dViewDirW = normalize(uniform.view_position - vPositionW);
}
`;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<o;a++){let l=e.layerOrder[a],h=r[l.layer];h&&(l.transparent?i.pushTransparent(h):i.pushOpaque(h),i.subLayerEnabled[a]=l.enabled)}this.scene.layers=i}if(e.batchGroups){let i=this.batcher;if(i)for(let r=0,a=e.batchGroups.length;r<a;r++){let o=e.batchGroups[r];i.addGroup(o.name,o.dynamic,o.maxAabbSize,o.id,o.layers)}}e.i18nAssets&&(this.i18n.assets=e.i18nAssets),this._loadLibraries(e.libraries,s)}_loadLibraries(e,s){let i=e.length,r=i,a=/^https?:\/\//;if(i){let o=(l,h)=>{r--,l?s(l):r===0&&(this.onLibrariesLoaded(),s(null))};for(let l=0;l<i;++l){let h=e[l];!a.test(h.toLowerCase())&&this._scriptPrefix&&(h=xe.join(this._scriptPrefix,h)),this.loader.load(h,"script",o)}}else this.onLibrariesLoaded(),s(null)}_parseScenes(e){if(e)for(let s=0;s<e.length;s++)this.scenes.add(e[s].name,e[s].url)}_parseAssets(e){let s=[],i={},r={};for(let a=0;a<this.scriptsOrder.length;a++){let o=this.scriptsOrder[a];e[o]&&(i[o]=!0,s.push(e[o]))}if(this.enableBundles)for(let a in e)e[a].type==="bundle"&&(r[a]=!0,s.push(e[a]));for(let a in e)i[a]||r[a]||s.push(e[a]);for(let a=0;a<s.length;a++){let o=s[a],l=new ae(o.name,o.type,o.file,o.data);if(l.id=parseInt(o.id,10),l.preload=o.preload?o.preload:!1,l.loaded=o.type==="script"&&o.data&&o.data.loadingType>0,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<i.length;r++)i[r].unload(),i[r].off();this.assets.off(),this.scene.destroy(),this.scene=null,this.graphicsDevice.destroy(),this.graphicsDevice=null,this.off(),this._soundManager?.destroy(),this._soundManager=null,fm.app=null,ou._applications[e]=null,ys()===this&&qy(null),ou.cancelTick(this)}static cancelTick(e){e.frameRequestId&&(cancelAnimationFrame(e.frameRequestId),e.frameRequestId=void 0)}getEntityFromIndex(e){return this._entityIndex[e]}_registerSceneImmediate(e){this.on("postrender",e.immediate.onPostRender,e.immediate),this._gsplatSortedEvt=e.on("gsplat:sorted",s=>{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;
}
vec3 decodeRGBM(vec4 rgbm) {
vec3 color = (8.0 * rgbm.a) * rgbm.rgb;
return color * color;
}
float saturate(float x) {
return clamp(x, 0.0, 1.0);
}
vec4 encodeRGBM(vec3 color) {
vec4 encoded;
encoded.rgb = pow(color.rgb, vec3(0.5));
encoded.rgb *= 1.0 / 8.0;
encoded.a = saturate( max( max( encoded.r, encoded.g ), max( encoded.b, 1.0 / 255.0 ) ) );
encoded.a = ceil(encoded.a * 255.0) / 255.0;
encoded.rgb /= encoded.a;
return encoded;
}
vec3 decode(vec4 pixel) {
#if HDR
return pixel.rgb;
#else
return decodeRGBM(pixel);
#endif
}
bool isUsed(vec4 pixel) {
#if HDR
return any(greaterThan(pixel.rgb, vec3(0.0)));
#else
return pixel.a > 0.0;
#endif
}
varying vec2 vUv0;
uniform sampler2D source;
uniform vec2 pixelOffset;
uniform vec2 sigmas;
uniform float bZnorm;
uniform float kernel[{MSIZE}];
void main(void) {
vec4 pixel = texture2DLod(source, vUv0, 0.0);
if (!isUsed(pixel)) {
gl_FragColor = pixel;
return ;
}
float sigma = sigmas.x;
float bSigma = sigmas.y;
vec3 pixelHdr = decode(pixel);
vec3 accumulatedHdr = vec3(0.0);
float accumulatedFactor = 0.000001;
const int kSize = ({MSIZE} - 1) / 2;
for (int i = -kSize; i <= kSize; ++i) {
for (int j = -kSize; j <= kSize; ++j) {
vec2 coord = vUv0 + vec2(float(i), float(j)) * pixelOffset;
vec4 pix = texture2DLod(source, coord, 0.0);
if (isUsed(pix)) {
vec3 hdr = decode(pix);
float factor = kernel[kSize + j] * kernel[kSize + i];
factor *= normpdf3(hdr - pixelHdr, bSigma) * bZnorm;
accumulatedHdr += factor * hdr;
accumulatedFactor += factor;
}
}
}
vec3 finalHDR = accumulatedHdr / accumulatedFactor;
#if HDR
gl_FragColor = vec4(finalHDR, 1.0);
#else
gl_FragColor = encodeRGBM(finalHDR);
#endif
}
`;var aB=`
varying vec2 vUv0;
uniform sampler2D source;
uniform vec2 pixelOffset;
bool isUsed(vec4 pixel) {
#if HDR
return any(greaterThan(pixel.rgb, vec3(0.0)));
#else
return pixel.a > 0.0;
#endif
}
void main(void) {
vec4 c = texture2DLod(source, vUv0, 0.0);
c = isUsed(c) ? c : texture2DLod(source, vUv0 - pixelOffset, 0.0);
c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(0, -pixelOffset.y), 0.0);
c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(pixelOffset.x, -pixelOffset.y), 0.0);
c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(-pixelOffset.x, 0), 0.0);
c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(pixelOffset.x, 0), 0.0);
c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(-pixelOffset.x, pixelOffset.y), 0.0);
c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(0, pixelOffset.y), 0.0);
c = isUsed(c) ? c : texture2DLod(source, vUv0 + pixelOffset, 0.0);
gl_FragColor = c;
}
`;var oB=`
fn normpdf3(v: vec3f, sigma: f32) -> f32 {
return 0.39894 * exp(-0.5 * dot(v, v) / (sigma * sigma)) / sigma;
}
fn decodeRGBM(rgbm: vec4f) -> vec3f {
let color = (8.0 * rgbm.a) * rgbm.rgb;
return color * color;
}
fn saturate(x: f32) -> f32 {
return clamp(x, 0.0, 1.0);
}
fn encodeRGBM(color: vec3f) -> vec4f {
var encoded: vec4f;
let rgb_processed = pow(color.rgb, vec3f(0.5)) * (1.0 / 8.0);
encoded = vec4f(rgb_processed, 0.0);
let max_g_b = max( encoded.g, max( encoded.b, 1.0 / 255.0 ) );
let max_rgb = max( encoded.r, max_g_b );
encoded.a = clamp(max_rgb, 0.0, 1.0);
encoded.a = ceil(encoded.a * 255.0) / 255.0;
encoded = vec4f(encoded.rgb / encoded.a, encoded.a);
return encoded;
}
fn decode(pixel: vec4f) -> vec3f {
#if HDR
return pixel.rgb;
#else
return decodeRGBM(pixel);
#endif
}
fn isUsed(pixel: vec4f) -> bool {
#if HDR
return any(pixel.rgb > vec3f(0.0));
#else
return pixel.a > 0.0;
#endif
}
varying vUv0: vec2f;
var source: texture_2d<f32>;
var sourceSampler: sampler;
uniform kernel: array<f32, {MSIZE}>;
uniform pixelOffset: vec2f;
uniform sigmas: vec2f;
uniform bZnorm: f32;
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let pixel = textureSampleLevel(source, sourceSampler, input.vUv0, 0.0);
if (!isUsed(pixel)) {
output.color = pixel;
return output;
}
let sigma = uniform.sigmas.x;
let bSigma = uniform.sigmas.y;
let pixelHdr = decode(pixel);
var accumulatedHdr = vec3f(0.0);
var accumulatedFactor = 0.000001;
const kSize = ({MSIZE} - 1) / 2;
for (var i: i32 = -kSize; i <= kSize; i = i + 1) {
for (var j: i32 = -kSize; j <= kSize; j = j + 1) {
let coord = input.vUv0 + vec2f(f32(i), f32(j)) * uniform.pixelOffset;
let pix = textureSampleLevel(source, sourceSampler, coord, 0.0);
if (isUsed(pix)) {
let hdr = decode(pix);
var factor = uniform.kernel[u32(kSize + j)].element * uniform.kernel[u32(kSize + i)].element;
factor = factor * normpdf3(hdr - pixelHdr, bSigma) * uniform.bZnorm;
accumulatedHdr = accumulatedHdr + factor * hdr;
accumulatedFactor = accumulatedFactor + factor;
}
}
}
let finalHDR = accumulatedHdr / accumulatedFactor;
#if HDR
output.color = vec4f(finalHDR, 1.0);
#else
output.color = encodeRGBM(finalHDR);
#endif
return output;
}
`;var nB=`
varying vUv0: vec2f;
var source: texture_2d<f32>;
var sourceSampler: sampler;
uniform pixelOffset: vec2f;
fn isUsed(pixel: vec4f) -> bool {
#ifdef HDR
return any(pixel.rgb > vec3f(0.0));
#else
return pixel.a > 0.0;
#endif
}
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var c: vec4f = textureSampleLevel(source, sourceSampler, input.vUv0, 0.0);
c = select(textureSampleLevel(source, sourceSampler, input.vUv0 - uniform.pixelOffset, 0.0), c, isUsed(c));
c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(0.0, -uniform.pixelOffset.y), 0.0), c, isUsed(c));
c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(uniform.pixelOffset.x, -uniform.pixelOffset.y), 0.0), c, isUsed(c));
c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(-uniform.pixelOffset.x, 0.0), 0.0), c, isUsed(c));
c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(uniform.pixelOffset.x, 0.0), 0.0), c, isUsed(c));
c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(-uniform.pixelOffset.x, uniform.pixelOffset.y), 0.0), c, isUsed(c));
c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(0.0, uniform.pixelOffset.y), 0.0), c, isUsed(c));
c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + uniform.pixelOffset, 0.0), c, isUsed(c));
var output: FragmentOutput;
output.color = c;
return output;
}
`;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;i<s;i++)this.passMaterials[i]||(this.passMaterials[i]=this.createMaterialForPass(e,i,!1));this.ambientAOMaterial||(this.ambientAOMaterial=this.createMaterialForPass(e,0,!0),this.ambientAOMaterial.onUpdateShader=function(i){return i.litOptions.lightMapWithoutAmbient=!0,i.litOptions.separateAmbient=!0,i})}createTexture(t,e){return new Z(this.device,{width:t,height:t,format:this.scene.lightmapPixelFormat,mipmaps:!1,type:this.bakeHDR?Gt:_i,minFilter:0,magFilter:0,addressU:1,addressV:1,name:e})}collectModels(t,e,s){if(!t.enabled)return;let i;if(t.model?.model&&t.model?.enabled&&(s&&s.push(new nu(t)),t.model.lightmapped&&e&&(i=t.model.model.meshInstances)),t.render?.enabled&&(s&&s.push(new nu(t)),t.render.lightmapped&&e&&(i=t.render.meshInstances)),i){let r=!0;for(let a=0;a<i.length;a++)if(!i[a].mesh.vertexBuffer.format.hasUv1){r=!1;break}if(r){let a=[];for(let o=0;o<i.length;o++){let l=i[o].mesh;this._tempSet.has(l)?e.push(new nu(t,[i[o]])):a.push(i[o]),this._tempSet.add(l)}this._tempSet.clear(),a.length>0&&e.push(new nu(t,a))}}for(let r=0;r<t._children.length;r++)this.collectModels(t._children[r],e,s)}prepareShadowCasters(t){let e=[];for(let s=0;s<t.length;s++){let i=t[s].component;if(i.castShadows=i.castShadowsLightmap,i.castShadowsLightmap){let r=t[s].meshInstances;for(let a=0;a<r.length;a++)r[a].visibleThisFrame=!0,e.push(r[a])}}return e}updateTransforms(t){for(let e=0;e<t.length;e++){let s=t[e].meshInstances;for(let i=0;i<s.length;i++)s[i].node.getWorldTransform()}}calculateLightmapSize(t){let e,s=this.scene.lightmapSizeMultiplier||16,i=u0,r,a;t.model?(a=t.model.lightmapSizeMultiplier,t.model.asset?(e=this.assets.get(t.model.asset).data,e.area&&(r=e.area)):t.model._area&&(e=t.model,e._area&&(r=e._area))):t.render&&(a=t.render.lightmapSizeMultiplier,t.render.type!=="asset"&&t.render._area&&(e=t.render,e._area&&(r=e._area)));let o={x:1,y:1,z:1,uv:1};r&&(o.x=r.x,o.y=r.y,o.z=r.z,o.uv=r.uv);let l=a||1;o.x*=l,o.y*=l,o.z*=l;let h=t.render||t.model,f=this.computeNodeBounds(h.meshInstances);i.copy(f.halfExtents);let u=o.x*i.y*i.z+o.y*i.x*i.z+o.z*i.x*i.y;return u/=o.uv,u=Math.sqrt(u),Math.min(R.nextPowerOfTwo(u*s),this.scene.lightmapMaxResolution||I8)}setLightmapping(t,e,s,i){for(let r=0;r<t.length;r++){let a=t[r],o=a.meshInstances;for(let l=0;l<o.length;l++){let h=o[l];if(h.setLightmapped(e),e){i&&(h._shaderDefs|=i),h.mask=xi;for(let f=0;f<s;f++){let u=a.renderTargets[f].colorBuffer;u.minFilter=1,u.magFilter=1,h.setRealtimeLightmap(we.lightmapParamNames[f],u)}}}}}bake(t,e=zf){let s=this.device,i=Tt();this.scene._updateSkyMesh(),this.stats.renderPasses=0,this.stats.shadowMapTime=0,this.stats.forwardTime=0;let r=s._shaderStats.linked,a=s._renderTargetCreationTime,o=s._shaderStats.compileTime,l=[],h=[];if(t){for(let u=0;u<t.length;u++)this.collectModels(t[u],l,null);this.collectModels(this.root,null,h)}else this.collectModels(this.root,l,h);if(l.length>0){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;s<t.length;s++){let i=t[s],r=this.calculateLightmapSize(i.node);for(let a=0;a<e;a++){let o=this.createTexture(r,`lightmapper_lightmap_${s}`);yr.incRef(o),i.renderTargets[a]=new me({colorBuffer:o,depth:!1})}if(!this.renderTargets.has(r)){let a=this.createTexture(r,`lightmapper_temp_lightmap_${r}`);yr.incRef(a),this.renderTargets.set(r,new me({colorBuffer:a,depth:!1}))}}}prepareLightsToBake(t,e){if(this.scene.ambientBake){let i=new LS(this);e.push(i)}let s=this.renderer.lights;for(let i=0;i<s.length;i++){let r=s[i],a=new c0(this,r);t.push(a),r.enabled&&(r.mask&vi)!==0&&(r.mask=vi|xi|cs,r.shadowUpdateMode=r.type===Ce?Qg:Qi,e.push(a))}e.sort()}restoreLights(t){for(let e=0;e<t.length;e++)t[e].restore()}setupScene(){this.ambientLight.copy(this.scene.ambientLight),this.scene.ambientBake||this.scene.ambientLight.set(0,0,0),this.renderer.setSceneConstants(),this.device.scope.resolve("ambientBakeOcclusionContrast").setValue(this.scene.ambientBakeOcclusionContrast),this.device.scope.resolve("ambientBakeOcclusionBrightness").setValue(this.scene.ambientBakeOcclusionBrightness)}restoreScene(){this.scene.ambientLight.copy(this.ambientLight)}computeNodeBounds(t){let e=new ge;if(t.length>0){e.copy(t[0].aabb);for(let s=1;s<t.length;s++)e.add(t[s].aabb)}return e}computeNodesBounds(t){for(let e=0;e<t.length;e++){let s=t[e].meshInstances;t[e].bounds=this.computeNodeBounds(s)}}computeBounds(t){let e=new ge;for(let s=0;s<t.length;s++){e.copy(t[0].aabb);for(let i=1;i<t.length;i++)e.add(t[i].aabb)}return e}backupMaterials(t){for(let e=0;e<t.length;e++)this.materials[e]=t[e].material}restoreMaterials(t){for(let e=0;e<t.length;e++)t[e].material=this.materials[e]}lightCameraPrepare(t,e){let s=e.light,i;return s.type===je&&(i=s.getRenderData(null,0).shadowCamera,i._node.setPosition(s._node.getPosition()),i._node.setRotation(s._node.getRotation()),i._node.rotateLocal(-90,0,0),i.projection=ts,i.nearClip=s.attenuationEnd/1e3,i.farClip=s.attenuationEnd,i.aspectRatio=1,i.fov=s._outerConeAngle*2,this.renderer.updateCameraFrustum(i)),i}lightCameraPrepareAndCull(t,e,s,i){let r=t.light,a=!0;if(r.type===Ce){u0.copy(i.center),u0.y+=i.halfExtents.y,this.camera.node.setPosition(u0),this.camera.node.setEulerAngles(-90,0,0),this.camera.nearClip=0,this.camera.farClip=i.halfExtents.y*2;let o=Math.max(i.halfExtents.x,i.halfExtents.z);this.camera.orthoHeight=o}else t.lightBounds.intersects(e.bounds)||(a=!1);if(r.type===je){let o=!1,l=e.meshInstances;for(let h=0;h<l.length;h++)if(l[h]._isVisible(s)){o=!0;break}o||(a=!1)}return a}setupLightArray(t,e){t[Ce].length=0,t[We].length=0,t[je].length=0,t[e.type][0]=e,e.visibleThisFrame=!0}renderShadowMap(t,e,s,i){let r=i.light,a=this.scene.clusteredLightingEnabled,o=r.castShadows&&(!a||this.scene.lighting.shadowsEnabled);if(!e&&o)if(!r.shadowMap&&!a&&(r.shadowMap=this.shadowMapCache.get(this.device,r)),r.type===Ce)this.renderer._shadowRendererDirectional.cull(r,t,this.camera,s),this.renderer._shadowRendererDirectional.getLightRenderPass(r,this.camera)?.render();else if(this.renderer._shadowRendererLocal.cull(r,t,s),a)this.shadowLocalClusteredPass.update([r]),this.shadowLocalClusteredPass.enabled&&this.shadowLocalClusteredPass.render();else{let l=r.numShadowFaces,h=r._type===je;for(let f=0;f<l;f++)new Fp(this.device,this.renderer.shadowRenderer,r,f,h).render()}return!0}postprocessTextures(t,e,s){let r=this.lightmapFilters.getDilate(t,this.bakeHDR),a,o=this.scene.lightmapFilterEnabled;o&&(this.lightmapFilters.prepareDenoise(this.scene.lightmapFilterRange,this.scene.lightmapFilterSmoothness,this.bakeHDR),a=this.lightmapFilters.getDenoise(this.bakeHDR)),t.setBlendState(Oe.NOBLEND),t.setDepthState(Pt.NODEPTH),t.setStencilState(null,null);for(let l=0;l<e.length;l++){let h=e[l];for(let f=0;f<s;f++){let u=h.renderTargets[f],d=u.colorBuffer,p=this.renderTargets.get(d.width),m=p.colorBuffer;this.lightmapFilters.prepare(d.width,d.height);for(let _=0;_<1;_++)this.lightmapFilters.setSourceTexture(d),Qt(t,p,o&&f===0&&_===0?a:r),this.lightmapFilters.setSourceTexture(m),Qt(t,u,r)}}}bakeInternal(t,e,s){let i=this.scene,r=i.layers,a=this.device,o=i.clusteredLightingEnabled;this.createMaterials(a,i,t),this.setupScene(),r._update(),this.computeNodesBounds(e),this.allocateTextures(e,t),this.renderer.collectLights(r);let l=[],h=[];this.prepareLightsToBake(l,h),this.updateTransforms(s);let f=this.prepareShadowCasters(s);this.renderer.updateCpuSkinMatrices(f),this.renderer.gpuUpdate(f);let u=this.computeBounds(f),d,p,m,_;for(d=0;d<e.length;d++)for(m=e[d].meshInstances,p=0;p<m.length;p++)_=m[p],_.setLightmapped(!1),_.mask=vi,_.setRealtimeLightmap(we.lightmapParamNames[0],this.blackTex),_.setRealtimeLightmap(we.lightmapParamNames[1],this.blackTex);for(p=0;p<h.length;p++)h[p].light.enabled=!1;let S=[[],[],[]],g,T,C=!1;for(d=0;d<h.length;d++){let v=h[d],E=v instanceof LS,y=v.light.type===Ce,P=v.numVirtualLights;t>1&&P>1&&v.light.bakeDir&&(P=1);for(let A=0;A<P;A++){P>1&&v.prepareVirtualLight(A,P),v.startBake();let w=!1,I=this.lightCameraPrepare(a,v);for(T=0;T<e.length;T++){let D=e[T];if(m=D.meshInstances,!this.lightCameraPrepareAndCull(v,D,I,u))continue;this.setupLightArray(S,v.light);let G=y?[]:[v.light];for(o&&this.renderer.lightTextureAtlas.update(G,this.lightingParams),w=this.renderShadowMap(r,w,f,v),o&&this.worldClusters.update(G,this.lightingParams),this.backupMaterials(m),g=0;g<t&&!(g>0&&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<m.length;p++)m[p].material=b;this.renderer.updateShaders(m),g===b8&&this.constantBakeDir.setValue(v.light.bakeDir?1:0);let N=new f0(a,this.renderer,this.camera,o?this.worldClusters:null,m,S);for(N.init(U),N.colorOps.clear=!0,N.colorOps.clearValue.copy(this.camera.clearColor),N.render(),N.destroy(),D.renderTargets[g]=U,this.renderTargets.set(H,M),p=0;p<m.length;p++)_=m[p],_.setRealtimeLightmap(we.lightmapParamNames[g],L),_._shaderDefs|=yc}this.restoreMaterials(m)}v.endBake(this.shadowMapCache)}}for(this.postprocessTextures(a,e,t),T=0;T<s.length;T++)s[T].restore();this.restoreLights(l),this.restoreScene(),o||this.shadowMapCache.clear()}};var d0=class d0 extends J{constructor(e,s){super();n(this,"system");n(this,"entity");this.system=e,this.entity=s,this.system.schema&&!this._accessorsBuilt&&this.buildAccessors(this.system.schema),this.on("set",function(i,r,a){this.fire(`set_${i}`,i,r,a)}),this.on("set_enabled",this.onSetEnabled,this)}static _buildAccessors(e,s){s.forEach(i=>{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<a;r++){let o=i[r],l,h;typeof o=="object"?(l=o.name,h=o.type):(l=o,h=void 0);let f=s[l];f!==void 0?(h!==void 0&&(f=D8(f,h)),e[l]=f):e[l]=e.data[l]}e.enabled&&e.entity.enabled&&e.onEnable()}getPropertiesOfType(e){let s=[];return(this.schema||[]).forEach(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._left||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[0])this._left=-1/0,this._right=e[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<r;++o)t[o]=i[a+o];else{let o=this._t,l=this._p1*r;switch(e){case 1:for(let h=0;h<r;++h)t[h]=R.lerp(i[a+h],i[l+h],o);break;case 2:{let h=this._hermite;if(!h.valid){let m=o*o,_=o+o,S=1-o,g=S*S;h.valid=!0,h.p0=(1+_)*g,h.m0=o*g,h.p1=m*(3-_),h.m1=m*(o-1)}let f=(this._p0*3+1)*r,u=(this._p0*3+2)*r,d=(this._p1*3+1)*r,p=(this._p1*3+0)*r;for(let m=0;m<r;++m)t[m]=h.p0*i[f+m]+h.m0*i[u+m]*this._len+h.p1*i[d+m]+h.m1*i[p+m]*this._len;break}}}}};var lu=class{constructor(t){this._name=`${t.name}Snapshot`,this._time=-1,this._cache=[],this._results=[];for(let i=0;i<t._inputs.length;++i)this._cache[i]=new p0;let e=t._curves,s=t._outputs;for(let i=0;i<e.length;++i){let r=e[i],a=s[r._output],o=[];for(let l=0;l<a._components;++l)o[l]=0;this._results[i]=o}}};var MS=class MS{constructor(t,e,s,i,r,a){this._name=t.name,this._track=t,this._snapshot=new lu(t),this._playing=i,this._time=e,this._speed=s,this._loop=r,this._blendWeight=1,this._blendOrder=0,this._eventHandler=a,this.alignCursorToCurrentTime()}set name(t){this._name=t}get name(){return this._name}set track(t){this._track=t,this._snapshot=new lu(t)}get track(){return this._track}get snapshot(){return this._snapshot}set time(t){this._time=t,this.alignCursorToCurrentTime()}get time(){return this._time}set speed(t){let e=Math.sign(t)!==Math.sign(this._speed);this._speed=t,e&&this.alignCursorToCurrentTime()}get speed(){return this._speed}set loop(t){this._loop=t}get loop(){return this._loop}set blendWeight(t){this._blendWeight=t}get blendWeight(){return this._blendWeight}set blendOrder(t){this._blendOrder=t}get blendOrder(){return this._blendOrder}set eventCursor(t){this._eventCursor=t}get eventCursor(){return this._eventCursor}get eventCursorEnd(){return this.isReverse?0:this._track.events.length-1}get nextEvent(){return this._track.events[this._eventCursor]}get isReverse(){return this._speed<0}nextEventAheadOfTime(t){return this.nextEvent?this.isReverse?this.nextEvent.time<=t:this.nextEvent.time>=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<t:!1}resetEventCursor(){this._eventCursor=this.isReverse?this._track.events.length-1:0}moveEventCursor(){this._eventCursor+=this.isReverse?-1:1,this._eventCursor>=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;r<s;++r)i+=t[r]*e[r];return i}static normalize(t){let e=c.dot(t,t);if(e>0){e=1/Math.sqrt(e);let s=t.length;for(let i=0;i<s;++i)t[i]*=e}}static set(t,e,s){let i=t.length;if(s==="quaternion"){let r=c.dot(e,e);r>0&&(r=1/Math.sqrt(r));for(let a=0;a<i;++a)t[a]=e[a]*r}else for(let r=0;r<i;++r)t[r]=e[r]}static blendVec(t,e,s,i){let r=i?1:1-s,a=t.length;for(let o=0;o<a;++o)t[o]=t[o]*r+e[o]*s}static blendQuat(t,e,s,i){let r=t.length,a=i?1:1-s;c.dot(t,e)<0&&(s=-s);for(let o=0;o<r;++o)t[o]=t[o]*a+e[o]*s;i||c.normalize(t)}static blend(t,e,s,i,r){i==="quaternion"?c.blendQuat(t,e,s,r):c.blendVec(t,e,s,r)}static stableSort(t,e){let s=t.length;for(let i=0;i<s-1;++i)for(let r=i+1;r<s;++r)if(e(t[r],t[i])){let a=t[i];t[i]=t[r],t[r]=a}}};var Xt=class Xt{constructor(t,e){this._component=t,this.mask=new Int8Array(t.layers.length),this.weights=new Float32Array(t.layers.length),this.totalWeight=0,this.counter=0,this.layerCounter=0,this.valueType=e,this.dirty=!0,this.value=e===Xt.TYPE_QUAT?[0,0,0,1]:[0,0,0],this.baseValue=null,this.setter=null}get _normalizeWeights(){return this._component.normalizeWeights}getWeight(t){return this.dirty&&this.updateWeights(),this._normalizeWeights&&this.totalWeight===0||!this.mask[t]?0:this._normalizeWeights?this.weights[t]/this.totalWeight:R.clamp(this.weights[t],0,1)}_layerBlendType(t){return this._component.layers[t].blendType}setMask(t,e){this.mask[t]=e,this._normalizeWeights&&(this._component.layers[t].blendType===OS&&(this.mask=this.mask.fill(0,0,t)),this.dirty=!0)}updateWeights(){this.totalWeight=0;for(let t=0;t<this.weights.length;t++)this.weights[t]=this._component.layers[t].weight,this.totalWeight+=this.mask[t]*this.weights[t];this.dirty=!1}updateValue(t,e){if(this.counter===0&&(Ir.set(this.value,Xt.IDENTITY_QUAT_ARR,this.valueType),this._normalizeWeights||Ir.blend(this.value,this.baseValue,1,this.valueType)),!(!this.mask[t]||this.getWeight(t)===0)){if(this._layerBlendType(t)===$I&&!this._normalizeWeights)if(this.valueType===Xt.TYPE_QUAT){let s=Xt.q1.set(this.value[0],this.value[1],this.value[2],this.value[3]),i=Xt.q2.set(this.baseValue[0],this.baseValue[1],this.baseValue[2],this.baseValue[3]),r=Xt.q3.set(e[0],e[1],e[2],e[3]),a=i.invert().mul(r);a.slerp($.IDENTITY,a,this.getWeight(t)),s.mul(a),Xt.quatArr[0]=s.x,Xt.quatArr[1]=s.y,Xt.quatArr[2]=s.z,Xt.quatArr[3]=s.w,Ir.set(this.value,Xt.quatArr,this.valueType)}else Xt.vecArr[0]=e[0]-this.baseValue[0],Xt.vecArr[1]=e[1]-this.baseValue[1],Xt.vecArr[2]=e[2]-this.baseValue[2],Ir.blend(this.value,Xt.vecArr,this.getWeight(t),this.valueType,!0);else Ir.blend(this.value,e,this.getWeight(t),this.valueType);this.setter&&this.setter(this.value)}}unbind(){this.setter&&this.setter(this.baseValue)}};n(Xt,"TYPE_QUAT","quaternion"),n(Xt,"TYPE_VEC3","vector3"),n(Xt,"q1",new $),n(Xt,"q2",new $),n(Xt,"q3",new $),n(Xt,"quatArr",[0,0,0,1]),n(Xt,"vecArr",[0,0,0]),n(Xt,"IDENTITY_QUAT_ARR",[0,0,0,1]);var Cm=Xt;var ih=class{constructor(t){this._binder=t,this._clips=[],this._inputs=[],this._outputs=[],this._targets={}}get clips(){return this._clips}addClip(t){let e=this._targets,s=this._binder,i=t.track.curves,r=t.snapshot,a=[],o=[];for(let l=0;l<i.length;++l){let f=i[l].paths;for(let u=0;u<f.length;++u){let d=f[u],p=s.resolve(d),m=e[p&&p.targetPath||null];if(!m&&p){m={target:p,value:[],curves:0,blendCounter:0};for(let _=0;_<m.target.components;++_)m.value.push(0);if(e[p.targetPath]=m,s.animComponent){if(!s.animComponent.targets[p.targetPath]){let _;p.targetPath.substring(p.targetPath.length-13)==="localRotation"?_=Cm.TYPE_QUAT:_=Cm.TYPE_VEC3,s.animComponent.targets[p.targetPath]=new Cm(s.animComponent,_)}s.animComponent.targets[p.targetPath].layerCounter++,s.animComponent.targets[p.targetPath].setMask(s.layerIndex,1)}}m&&(m.curves++,a.push(r._results[l]),o.push(m))}}this._clips.push(t),this._inputs.push(a),this._outputs.push(o)}removeClip(t){let e=this._targets,s=this._binder,i=this._clips,a=i[t].track.curves;for(let o=0;o<a.length;++o){let h=a[o].paths;for(let f=0;f<h.length;++f){let u=h[f],d=this._binder.resolve(u);d&&(d.curves--,d.curves===0&&(s.unresolve(u),delete e[d.targetPath],s.animComponent&&s.animComponent.targets[d.targetPath].layerCounter--))}}i.splice(t,1),this._inputs.splice(t,1),this._outputs.splice(t,1)}removeClips(){for(;this._clips.length>0;)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<e.length;++s){let i=e[s];if(i.name===t)return i}return null}rebind(){this._binder.rebind(),this._targets={};let t=[...this.clips];this.removeClips(),t.forEach(e=>{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].blendOrder<s[l].blendOrder);for(let o=0;o<i.length;++o){let l=i[o],h=s[l],f=this._inputs[l],u=this._outputs[l],d=h.blendWeight;if(d>0&&h._update(t),!e)break;let p,m,_;if(d>=1)for(let S=0;S<f.length;++S)p=f[S],m=u[S],_=m.value,Ir.set(_,p,m.target.type),m.blendCounter++;else if(d>0)for(let S=0;S<f.length;++S)p=f[S],m=u[S],_=m.value,m.blendCounter===0?Ir.set(_,p,m.target.type):Ir.blend(_,p,d,m.target.type),m.blendCounter++}let r=this._targets,a=this._binder;for(let o in r)if(r.hasOwnProperty(o)){let l=r[o];if(a.animComponent&&l.target.usesLayerBlending){let h=a.animComponent.targets[o];h.counter===h.layerCounter&&(h.counter=0),h.path||(h.path=o,h.baseValue=l.target.get(),h.setter=l.target.set),h.updateValue(a.layerIndex,l.value),h.counter++}else l.target.set(l.value);l.blendCounter=0}this._binder.update(t)}};var rh=class{constructor(t){this._events=[...t],this._events.sort((e,s)=>e.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;l<s.length;++l)a[l].update(t,s[l]._data);for(let l=0;l<r.length;++l){let h=r[l],f=i[h._output],u=o[l];a[h._input].eval(u,h._interpolation,f)}}};n(S0,"EMPTY",Object.freeze(new S0("empty",Number.MAX_VALUE,[],[],[])));var Qs=S0;var ua=class{static joinPath(t,e){e=e||".";let s=function(i){return i.replace(/\\/g,"\\\\").replace(new RegExp(`\\${e}`,"g"),`\\${e}`)};return t.map(s).join(e)}static splitPath(t,e){e=e||".";let s=[],i="",r=0;for(;r<t.length;){let a=t[r++];a==="\\"&&r<t.length?(a=t[r++],a==="\\"||a===e?i+=a:i+=`\\${a}`):a===e?(s.push(i),i=""):i+=a}return i.length>0&&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;a<r.children.length;++a)s(r.children[a])};s(t),this.nodes=e,this.targetCache={};let i=function(r){let a=r;for(;a&&!(a instanceof Ne);)a=a.parent;let o;return a&&(a.render?o=a.render.meshInstances:a.model&&(o=a.model.meshInstances)),o};this.nodeCounts={},this.activeNodes=[],this.handlers={localPosition:function(r){let a=r.localPosition,o=function(l){a.set(...l)};return c.createAnimTarget(o,"vector",3,r,"localPosition")},localRotation:function(r){let a=r.localRotation,o=function(l){a.set(...l)};return c.createAnimTarget(o,"quaternion",4,r,"localRotation")},localScale:function(r){let a=r.localScale,o=function(l){a.set(...l)};return c.createAnimTarget(o,"vector",3,r,"localScale")},weight:function(r,a){a.indexOf("name.")===0?a=a.replace("name.",""):a=Number(a);let o=i(r),l=[];if(o)for(let h=0;h<o.length;++h)o[h].node.name===r.name&&o[h].morphInstance&&l.push(o[h].morphInstance);if(l.length>0){let h={set:f=>{for(let u=0;u<l.length;++u)l[u].setWeight(a,f[0])},get:()=>[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<o.length;++h)if(o[h].node.name===r.name){l=o[h];break}if(l){let h=f=>{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;s<e.length;++s){let i=e[s];if(this._isPathInMask(i,t.entityPath.length===1))return!0;for(let r=1;r<t.entityPath.length;r++)if(i+=`/${t.entityPath[r]}`,this._isPathInMask(i,r===t.entityPath.length-1))return!0}return!1}findNode(t){if(!this._isPathActive(t))return null;let e;return this.graph&&(e=this.graph.findByPath(t.entityPath),e||(e=this.graph.findByPath(t.entityPath.slice(1)))),e||(e=this.nodes[t.entityPath[t.entityPath.length-1]||""]),e}static createAnimTarget(t,e,s,i,r,a){let o=ua.encode(i.path,a||"entity",r);return new ml(t,e,s,o)}resolve(t){let e=ua.encode(t.entityPath,t.component,t.propertyPath),s=this.targetCache[e];if(s)return s;let i=this.findNode(t);if(!i)return null;let r=this.handlers[t.propertyPath];return!r||(s=r(i),!s)?null:(this.targetCache[e]=s,this.nodeCounts[i.path]?this.nodeCounts[i.path]++:(this.activeNodes.push(i),this.nodeCounts[i.path]=1),s)}unresolve(t){if(t.component!=="graph")return;let e=this.nodes[t.entityPath[t.entityPath.length-1]||""];if(this.nodeCounts[e.path]--,this.nodeCounts[e.path]===0){let s=this.activeNodes,i=s.indexOf(e.node),r=s.length;i<r-1&&(s[i]=s[r-1]),s.pop()}}update(t){let e=this.activeNodes;for(let s=0;s<e.length;++s)e[s]._dirtifyLocal()}assignMask(t){return t!==this._mask?(this._mask=t,!0):!1}};var uu=class extends le{constructor(){super(...arguments);n(this,"_animations",{});n(this,"_assets",[]);n(this,"_loop",!0);n(this,"animEvaluator",null);n(this,"model",null);n(this,"skeleton",null);n(this,"fromSkel",null);n(this,"toSkel",null);n(this,"animationsIndex",{});n(this,"prevAnim",null);n(this,"currAnim",null);n(this,"blend",0);n(this,"blending",!1);n(this,"blendSpeed",0);n(this,"activate",!0);n(this,"speed",1)}set animations(e){this._animations=e,this.onSetAnimations()}get animations(){return this._animations}set assets(e){let s=this._assets;if(s&&s.length){for(let r=0;r<s.length;r++)if(s[r]){let a=this.system.app.assets.get(s[r]);if(a){a.off("change",this.onAssetChanged,this),a.off("remove",this.onAssetRemoved,this);let o=this.animationsIndex[a.id];this.currAnim===o&&this._stopCurrentAnimation(),delete this.animations[o],delete this.animationsIndex[a.id]}}}this._assets=e;let i=e.map(r=>r 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;i<s.length;++i)s[i].time=e}}get currentTime(){if(this.skeleton)return this.skeleton._time;if(this.animEvaluator){let e=this.animEvaluator.clips;if(e.length>0)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;s<this.animEvaluator.clips.length;++s)this.animEvaluator.clips[s].loop=e}get loop(){return this._loop}play(e,s=0){if(!(!this.enabled||!this.entity.enabled)&&this.animations[e]){if(this.prevAnim=this.currAnim,this.currAnim=e,this.model){!this.skeleton&&!this.animEvaluator&&this._createAnimationController();let i=this.animations[this.prevAnim],r=this.animations[this.currAnim];if(this.blending=s>0&&!!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.resources.length;o++)this.animations[a.resources[o].name]=a.resources[o],this.animationsIndex[a.id]=a.resources[o].name;else this.animations[a.name]=a.resource,this.animationsIndex[a.id]=a.name;this.animations=this.animations},r=a=>{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;a<o;a++){let l=s.get(e[a]);l?r(l):s.on(`add:${e[a]}`,r)}}onAssetChanged(e,s,i,r){if(s==="resource"||s==="resources")if(s==="resources"&&i&&i.length===0&&(i=null),i){let a=!1;if(i.length>1){if(r&&r.length>1)for(let o=0;o<r.length;o++)delete this.animations[r[o].name];else delete this.animations[e.name];a=!1;for(let o=0;o<i.length;o++)this.animations[i[o].name]=i[o],!a&&this.currAnim===i[o].name&&this.playing&&this.enabled&&this.entity.enabled&&(a=!0,this.play(i[o].name));a||(this._stopCurrentAnimation(),this.onSetAnimations())}else{if(r&&r.length>1)for(let o=0;o<r.length;o++)delete this.animations[r[o].name];this.animations[e.name]=i[0]||i,a=!1,this.currAnim===e.name&&this.playing&&this.enabled&&this.entity.enabled&&(a=!0,this.play(e.name)),a||(this._stopCurrentAnimation(),this.onSetAnimations())}this.animationsIndex[e.id]=e.name}else{if(r.length>1)for(let a=0;a<r.length;a++)delete this.animations[r[a].name],this.currAnim===r[a].name&&this._stopCurrentAnimation();else delete this.animations[e.name],this.currAnim===e.name&&this._stopCurrentAnimation();delete this.animationsIndex[e.id]}}onAssetRemoved(e){if(e.off("remove",this.onAssetRemoved,this),this.animations){if(e.resources.length>1)for(let s=0;s<e.resources.length;s++)delete this.animations[e.resources[s].name],this.currAnim===e.resources[s].name&&this._stopCurrentAnimation();else delete this.animations[e.name],this.currAnim===e.name&&this._stopCurrentAnimation();delete this.animationsIndex[e.id]}}_stopCurrentAnimation(){if(this.currAnim=null,this.playing=!1,this.skeleton&&(this.skeleton.currentTime=0,this.skeleton.animation=null),this.animEvaluator){for(let e=0;e<this.animEvaluator.clips.length;++e)this.animEvaluator.clips[e].stop();this.animEvaluator.update(0),this.animEvaluator.removeClips()}}onEnable(){super.onEnable();let e=this.assets,s=this.system.app.assets;if(e)for(let i=0,r=e.length;i<r;i++){let a=e[i];a instanceof ae||(a=s.get(a)),a&&!a.resource&&s.load(a)}if(this.activate&&!this.currAnim){let i=Object.keys(this.animations);i.length>0&&this.play(i[0])}}onBeforeRemove(){for(let e=0;e<this.assets.length;e++){let s=this.assets[e];typeof s=="number"&&(s=this.system.app.assets.get(s)),s&&(s.off("change",this.onAssetChanged,this),s.off("remove",this.onAssetRemoved,this))}this.skeleton=null,this.fromSkel=null,this.toSkel=null,this.animEvaluator=null}update(e){if(this.blending&&(this.blend+=e*this.blendSpeed,this.blend>=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;i<s.clips.length;++i){let r=s.clips[i];r.speed=this.speed,this.playing?r.resume():r.pause()}this.blending&&s.clips.length>1&&(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;f<a.length;f++){let u=a[f];u.children?this._children.push(l(u.type,t,this,u.name,1,u.parameter?[u.parameter]:u.parameters,u.children,u.syncAnimations,l,h)):this._children.push(new Qo(t,this,u.name,u.point,u.speed))}}get weight(){return this.calculateWeights(),this._parent?this._parent.weight*this._weight:this._weight}get syncAnimations(){return this._syncAnimations}getChild(t){for(let e=0;e<this._children.length;e++)if(this._children[e].name===t)return this._children[e];return null}updateParameterValues(){let t=!0;for(let e=0;e<this._parameterValues.length;e++){let s=this._findParameter(this._parameters[e]).value;this._parameterValues[e]!==s&&(this._parameterValues[e]=s,t=!1)}return t}getNodeWeightedDuration(t){return this._children[t].animTrack.duration/this._children[t].speedMultiplier*this._children[t].weight}getNodeCount(){let t=0;for(let e=0;e<this._children.length;e++)this._children[e].constructor===c?t+=this._children[e].getNodeCount():t++;return t}};var v0=class extends Jo{constructor(t,e,s,i,r,a,o,l,h){a.sort((f,u)=>f.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;e<this._children.length;e++){let s=this._children[e];if(e!==this._children.length-1){let i=this._children[e+1];if(s.point===i.point)s.weight=.5,i.weight=.5;else if(R.between(this._parameterValues[0],s.point,i.point,!0)){let r=Math.abs(s.point-i.point),a=Math.abs(s.point-this._parameterValues[0]),o=(r-a)/r;s.weight=o,i.weight=1-o}else i.weight=0}this._syncAnimations&&(t+=s.animTrack.duration/s.absoluteSpeed*s.weight)}if(this._syncAnimations)for(let e=0;e<this._children.length;e++){let s=this._children[e];s.weightedSpeed=s.animTrack.duration/s.absoluteSpeed/t}}};var _l=class _l extends Jo{pointDistanceCache(t,e){let s=`${t}${e}`;return this._pointCache[s]||(this._pointCache[s]=this._children[e].point.clone().sub(this._children[t].point)),this._pointCache[s]}calculateWeights(){if(this.updateParameterValues())return;let t,e;_l._p.set(...this._parameterValues),t=0,e=0;for(let s=0;s<this._children.length;s++){let i=this._children[s],r=i.point;_l._pip.set(_l._p.x,_l._p.y).sub(r);let a=Number.MAX_VALUE;for(let o=0;o<this._children.length;o++){if(s===o)continue;let l=this.pointDistanceCache(s,o),h=R.clamp(1-_l._pip.dot(l)/l.lengthSq(),0,1);h<a&&(a=h)}i.weight=a,t+=a,this._syncAnimations&&(e+=i.animTrack.duration/i.absoluteSpeed*i.weight)}for(let s=0;s<this._children.length;s++){let i=this._children[s];i.weight=i._weight/t,this._syncAnimations&&(i.weightedSpeed=i.animTrack.duration/i.absoluteSpeed/e)}}};n(_l,"_p",new B),n(_l,"_pip",new B);var T0=_l;var gl=class gl extends Jo{pointCache(t,e){let s=`${t}${e}`;return this._pointCache[s]||(this._pointCache[s]=new B((this._children[e].pointLength-this._children[t].pointLength)/((this._children[e].pointLength+this._children[t].pointLength)/2),B.angleRad(this._children[t].point,this._children[e].point)*2)),this._pointCache[s]}calculateWeights(){if(this.updateParameterValues())return;let t,e;gl._p.set(...this._parameterValues);let s=gl._p.length();t=0,e=0;for(let i=0;i<this._children.length;i++){let r=this._children[i],a=r.point,o=r.pointLength,l=Number.MAX_VALUE;for(let h=0;h<this._children.length;h++){if(i===h)continue;let f=this.pointCache(i,h),u=this._children[h].pointLength;gl._pip.set((s-o)/((u+o)/2),B.angleRad(a,gl._p)*2);let d=R.clamp(1-Math.abs(gl._pip.dot(f)/f.lengthSq()),0,1);d<l&&(l=d)}r.weight=l,t+=l,this._syncAnimations&&(e+=r.animTrack.duration/r.absoluteSpeed*r.weight)}for(let i=0;i<this._children.length;i++){let r=this._children[i];if(r.weight=r._weight/t,this._syncAnimations){let a=r.animTrack.duration/e*t;r.weightedSpeed=r.absoluteSpeed*a}}}};n(gl,"_p",new B),n(gl,"_pip",new B);var y0=gl;var E0=class extends Jo{calculateWeights(){if(this.updateParameterValues())return;let t=0,e=0;for(let s=0;s<this._children.length;s++)if(t+=Math.max(this._parameterValues[s],0),this._syncAnimations){let i=this._children[s];e+=i.animTrack.duration/i.absoluteSpeed*i.weight}for(let s=0;s<this._children.length;s++){let i=this._children[s],r=Math.max(this._parameterValues[s],0);t?(i.weight=r/t,this._syncAnimations&&(i.weightedSpeed=i.animTrack.duration/i.absoluteSpeed/e)):(i.weight=0,this._syncAnimations&&(i.weightedSpeed=0))}}};var FS=class{constructor(t,e,s=1,i=!0,r){n(this,"_animations",{});n(this,"_animationList",[]);this._controller=t,this._name=e,this._speed=s,this._loop=i,this._hasAnimations=!1,r?this._blendTree=this._createTree(r.type,this,null,e,1,r.parameter?[r.parameter]:r.parameters,r.children,r.syncAnimations,this._createTree,this._controller.findParameter):this._blendTree=new Qo(this,null,e,1,s)}_createTree(t,e,s,i,r,a,o,l,h,f){switch(t){case"1D":return new v0(e,s,i,r,a,o,l,h,f);case KI:return new T0(e,s,i,r,a,o,l,h,f);case YI:return new y0(e,s,i,r,a,o,l,h,f);case jI:return new E0(e,s,i,r,a,o,l,h,f)}}_getNodeFromPath(t){let e=this._blendTree;for(let s=1;s<t.length;s++)e=e.getChild(t[s]);return e}addAnimation(t,e){let s=t.join("."),i=this._animationList.findIndex(r=>r.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;e<this.animations.length;e++)t+=this.animations[e].weight;return t}get timelineDuration(){let t=0;for(let e=0;e<this.animations.length;e++){let s=this.animations[e];s.animTrack.duration>t&&(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;l<e.length;l++)this._states[e[l].name]=new FS(this,e[l].name,e[l].speed,e[l].loop,e[l].blendTree),this._stateNames.push(e[l].name);this._transitions=s.map(l=>new 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;e<this._stateNames.length;e++)this._states[this._stateNames[e]].playable||(t=!1);return t}set playing(t){this._playing=t}get playing(){return this._playing}get activeStateProgress(){return this._getActiveStateProgressForTime(this._timeInState)}get activeStateDuration(){if(this._activeStateDurationDirty){let t=0;for(let e=0;e<this.activeStateAnimations.length;e++){let s=this._animEvaluator.findClip(this.activeStateAnimations[e].name);s&&(t=Math.max(t,s.track.duration))}this._activeStateDuration=t,this._activeStateDurationDirty=!1}return this._activeStateDuration}set activeStateCurrentTime(t){this._timeInStateBefore=t,this._timeInState=t;for(let e=0;e<this.activeStateAnimations.length;e++){let s=this.animEvaluator.findClip(this.activeStateAnimations[e].name);s&&(s.time=t)}}get activeStateCurrentTime(){return this._timeInState}get transitioning(){return this._isTransitioning}get transitionProgress(){return this._currTransitionTime/this._totalTransitionTime}get states(){return this._stateNames}assignMask(t){return this._animEvaluator.assignMask(t)}_findState(t){return this._states[t]}_getActiveStateProgressForTime(t){if(this.activeStateName===hu||this.activeStateName==="END"||this.activeStateName==="ANY")return 1;let e=this._animEvaluator.findClip(this.activeStateAnimations[0].name);return e?e.progressForTime(t):null}_findTransitionsFromState(t){let e=this._findTransitionsFromStateCache[t];return e||(e=this._transitions.filter(s=>s.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;s<e.length;s++){let i=e[s],r=this._findParameter(i.parameterName);switch(i.predicate){case zI:if(!(r.value>i.value))return!1;break;case GI:if(!(r.value<i.value))return!1;break;case VI: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;h<t.conditions.length;h++){let f=t.conditions[h];this._findParameter(f.parameterName).type===cu&&this._consumeTrigger(f.parameterName)}if(this.previousState){this._isTransitioning||(this._transitionPreviousStates=[]),this._transitionPreviousStates.push({name:this._previousStateName,weight:1});let h=Math.min(this._totalTransitionTime!==0?this._currTransitionTime/this._totalTransitionTime:1,1);for(let f=0;f<this._transitionPreviousStates.length;f++){this._isTransitioning?f!==this._transitionPreviousStates.length-1?this._transitionPreviousStates[f].weight*=1-h:this._transitionPreviousStates[f].weight=h:this._transitionPreviousStates[f].weight=1,e=this._findState(this._transitionPreviousStates[f].name);for(let u=0;u<e.animations.length;u++)s=e.animations[u],i=this._animEvaluator.findClip(`${s.name}.previous.${f}`),i||(i=this._animEvaluator.findClip(s.name),i.name=`${s.name}.previous.${f}`),f!==this._transitionPreviousStates.length-1&&i.pause()}}this._isTransitioning=!0,this._totalTransitionTime=t.time,this._currTransitionTime=0,this._transitionInterruptionSource=t.interruptionSource;let r=this.activeState,a=t.transitionOffset&&t.transitionOffset>0&&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;h<r.animations.length;h++){if(i=this._animEvaluator.findClip(r.animations[h].name),i)i.reset();else{let f=Number.isFinite(r.animations[h].speed)?r.animations[h].speed:r.speed;i=new th(r.animations[h].animTrack,this._timeInState,f,!0,r.loop,this._eventHandler),i.name=r.animations[h].name,this._animEvaluator.addClip(i)}if(t.time>0?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._timeInState<this.activeStateDuration)&&(this._timeInStateBefore=this._timeInState,this._timeInState+=t*this.activeState.speed,!this.activeState.loop&&this._timeInState>this.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<this._transitionPreviousStates.length;o++){e=this._findState(this._transitionPreviousStates[o].name);let l=this._transitionPreviousStates[o].weight;for(let h=0;h<e.animations.length;h++)s=e.animations[h],i=this._animEvaluator.findClip(`${s.name}.previous.${o}`),i&&(i.blendWeight=(1-a)*s.normalizedWeight*l)}e=this.activeState;for(let o=0;o<e.animations.length;o++)s=e.animations[o],this._animEvaluator.findClip(s.name).blendWeight=a*s.normalizedWeight}else{this._isTransitioning=!1;let a=this.activeStateAnimations.length,o=this._animEvaluator.clips.length;for(let l=0;l<o-a;l++)this._animEvaluator.removeClip(0);this._transitionPreviousStates=[],e=this.activeState;for(let l=0;l<e.animations.length;l++)s=e.animations[l],i=this._animEvaluator.findClip(s.name),i&&(i.blendWeight=s.normalizedWeight)}else if(this.activeState._blendTree.constructor!==Qo){e=this.activeState;for(let a=0;a<e.animations.length;a++)s=e.animations[a],i=this._animEvaluator.findClip(s.name),i&&(i.blendWeight=s.normalizedWeight,s.parent.syncAnimations&&(i.speed=s.speed))}this._animEvaluator.update(t,this.activeState.hasAnimations)}};var QI=new B,A0=new x,NS=new Q,BS=new F,US=new $,C0=class c extends ah{constructor(t,e,s,i,r){super(e),this.animComponent=t,this._mask=i,this.layerName=s,this.layerIndex=r}static _packFloat(t){return t[0]}static _packBoolean(t){return!!t[0]}static _packVec2(t){return QI.x=t[0],QI.y=t[1],QI}static _packVec3(t){return A0.x=t[0],A0.y=t[1],A0.z=t[2],A0}static _packVec4(t){return NS.x=t[0],NS.y=t[1],NS.z=t[2],NS.w=t[3],NS}static _packColor(t){return BS.r=t[0],BS.g=t[1],BS.b=t[2],BS.a=t[3],BS}static _packQuat(t){return US.x=t[0],US.y=t[1],US.z=t[2],US.w=t[3],US}resolve(t){let e=ua.encode(t.entityPath,t.component,t.propertyPath),s=this.targetCache[e];if(s)return s;let i,r,a;switch(t.component){case"entity":i=this._getEntityFromHierarchy(t.entityPath),a=ua.encode(i.path,"entity",t.propertyPath),r=i;break;case"graph":if(r=this.findNode(t),!r)return null;a=ua.encode(r.path,"graph",t.propertyPath);break;default:if(i=this._getEntityFromHierarchy(t.entityPath),r=i.findComponent(t.component),!r)return null;a=ua.encode(i.path,t.component,t.propertyPath);break}return s=this._createAnimTargetForProperty(r,t.propertyPath,a),this.targetCache[e]=s,s}update(t){let e=this.activeNodes;if(e)for(let s=0;s<e.length;s++)e[s]._dirtifyLocal()}_getEntityFromHierarchy(t){if(!this.animComponent.entity.name===t[0])return null;let e=this.animComponent.entity;return t.length===1?e:e._parent.findByPath(t)}_resolvePath(t,e,s){let i=e.length-(s?0:1);for(let r=0;r<i;r++)t=t[e[r]];return t}_setter(t,e,s){let i=this._resolvePath(t,e),r=e[e.length-1],a=`set${r.substring(0,1).toUpperCase()}${r.substring(1)}`;if(i[a]){let h=i[`get${r.substring(0,1).toUpperCase()}${r.substring(1)}`].bind(i)();h=[h.x,h.y,h.z,h.w];let f=i[a].bind(i);return{set:u=>{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;i<s.children.length;++i)e(s.children[i])};e(this.graph),this.nodes=t}};var Im=class{constructor(t,e,s,i=1,r=OS){n(this,"_name");n(this,"_controller");n(this,"_component");n(this,"_weight");n(this,"_blendType");n(this,"_mask",null);n(this,"_blendTime",0);n(this,"_blendTimeElapsed",0);n(this,"_startingWeight",0);n(this,"_targetWeight",0);this._name=t,this._controller=e,this._component=s,this._weight=i,this._blendType=r}get name(){return this._name}set playing(t){this._controller.playing=t}get playing(){return this._controller.playing}get playable(){return this._controller.playable}get activeState(){return this._controller.activeStateName}get previousState(){return this._controller.previousStateName}get activeStateProgress(){return this._controller.activeStateProgress}get activeStateDuration(){return this._controller.activeStateDuration}set activeStateCurrentTime(t){let e=this._controller,s=e.playing;e.playing=!0,e.activeStateCurrentTime=t,s||e.update(0),e.playing=s}get activeStateCurrentTime(){return this._controller.activeStateCurrentTime}get transitioning(){return this._controller.transitioning}get transitionProgress(){return this.transitioning?this._controller.transitionProgress:null}get states(){return this._controller.states}set weight(t){this._weight=t,this._component.dirtifyTargets()}get weight(){return this._weight}set blendType(t){t!==this._blendType&&(this._blendType=t,this._controller.normalizeWeights&&this._component.rebind())}get blendType(){return this._blendType}set mask(t){this._controller.assignMask(t)&&this._component.rebind(),this._mask=t}get mask(){return this._mask}play(t){this._controller.play(t)}pause(){this._controller.pause()}reset(){this._controller.reset()}rebind(){this._controller.rebind()}update(t){this._blendTime&&(this._blendTimeElapsed<this._blendTime?(this.weight=R.lerp(this._startingWeight,this._targetWeight,this._blendTimeElapsed/this._blendTime),this._blendTimeElapsed+=t):(this.weight=this._targetWeight,this._blendTime=0,this._blendTimeElapsed=0,this._startingWeight=0,this._targetWeight=0)),this._controller.update(t)}blendToWeight(t,e){this._startingWeight=this.weight,this._targetWeight=t,this._blendTime=Math.max(0,e),this._blendTimeElapsed=0}assignAnimation(t,e,s,i){e instanceof Qs&&(this._controller.assignAnimation(t,e,s,i),this._controller._transitions.length===0&&this._controller._transitions.push(new oh({from:"START",to:t})),this._component.activate&&this._component.playable&&(this._component.playing=!0))}removeNodeAnimations(t){this._controller.removeNodeAnimations(t)&&(this._component.playing=!1)}getAnimationAsset(t){return this._component.animationAssets[`${this.name}:${t}`]}transition(t,e=0,s=null){this._controller.updateStateFromTransition(new oh({from:this._controller.activeStateName,to:t,time:e,transitionOffset:s}))}};var en=class{constructor(t){if(this._layers=[],this._parameters={},Array.isArray(t.layers))this._layers=t.layers;else for(let e in t.layers){let s=t.layers[e],i={name:s.name,blendType:s.blendType,weight:s.weight,states:[],transitions:[]};for(let r=0;r<s.states.length;r++)i.states.push(t.states[s.states[r]]);for(let r=0;r<s.transitions.length;r++){let a=t.transitions[s.transitions[r]];if(a.conditions&&!Array.isArray(a.conditions)){let o=Object.keys(a.conditions),l=[];for(let h=0;h<o.length;h++){let f=a.conditions[o[h]];f.parameterName&&l.push(f)}a.conditions=l}Number.isInteger(a.from)&&(a.from=t.states[a.from].name),Number.isInteger(a.to)&&(a.to=t.states[a.to].name),i.transitions.push(a)}this._layers.push(i)}for(let e in t.parameters){let s=t.parameters[e];this._parameters[s.name]={type:s.type,value:s.value}}}get parameters(){return Object.assign({},this._parameters)}get layers(){return this._layers}};var du=class extends le{constructor(){super(...arguments);n(this,"_stateGraphAsset",null);n(this,"_animationAssets",{});n(this,"_speed",1);n(this,"_activate",!0);n(this,"_playing",!1);n(this,"_rootBone",null);n(this,"_stateGraph",null);n(this,"_layers",[]);n(this,"_layerIndices",{});n(this,"_parameters",{});n(this,"_targets",{});n(this,"_consumedTriggers",new Set);n(this,"_normalizeWeights",!1);n(this,"findParameter",e=>this._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;e<this._layers.length;e++)if(!this._layers[e].playable)return!1;return!0}get baseLayer(){return this._layers.length>0?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;s<e.length;s++)e[s].dirty=!0}_addLayer({name:e,states:s,transitions:i,weight:r,mask:a,blendType:o}){let l;this.rootBone?l=this.rootBone:l=this.entity;let h=this._layers.length,f=new C0(this,l,e,a,h),u=new ih(f),d=new wm(u,s,i,this._activate,this,this.findParameter,this.consumeTrigger);return this._layers.push(new Im(e,d,this,r,o)),this._layerIndices[e]=h,this._layers[h]}addLayer(e,s,i,r){let a=this.findAnimationLayer(e);if(a)return a;let o=[{name:"START",speed:1}],l=[];return this._addLayer({name:e,states:o,transitions:l,weight:s,mask:i,blendType:r})}_assignParameters(e){this._parameters={};let s=Object.keys(e.parameters);for(let i=0;i<s.length;i++){let r=s[i];this._parameters[r]={type:e.parameters[r].type,value:e.parameters[r].value}}}loadStateGraph(e){this._stateGraph=e,this._assignParameters(e),this._layers=[];let s=!1;for(let i=0;i<e.layers.length;i++){let r=e.layers[i];this._addLayer({...r}),r.states.some(a=>a.blendTree)&&(s=!0)}s||this.setupAnimationAssets()}setupAnimationAssets(){for(let e=0;e<this._layers.length;e++){let s=this._layers[e],i=s.name;for(let r=0;r<s.states.length;r++){let a=s.states[r];if(sh.indexOf(a)===-1){let o=`${i}:${a}`;this._animationAssets[o]||(this._animationAssets[o]={asset:null})}}}this.loadAnimationAssets()}loadAnimationAssets(){for(let e=0;e<this._layers.length;e++){let s=this._layers[e];for(let i=0;i<s.states.length;i++){let r=s.states[i];if(sh.indexOf(r)!==-1)continue;let a=this._animationAssets[`${s.name}:${r}`];if(!a||!a.asset){this.findAnimationLayer(s.name).assignAnimation(r,Qs.EMPTY);continue}let o=a.asset,l=this.system.app.assets.get(o);l&&(l.resource?this.onAnimationAssetLoaded(s.name,r,l):(l.once("load",function(h,f){return function(u){this.onAnimationAssetLoaded(h,f,u)}.bind(this)}.bind(this)(s.name,r)),this.system.app.assets.load(l)))}}}onAnimationAssetLoaded(e,s,i){this.findAnimationLayer(e).assignAnimation(s,i.resource)}removeStateGraph(){this._stateGraph=null,this._stateGraphAsset=null,this._animationAssets={},this._layers=[],this._layerIndices={},this._parameters={},this._playing=!1,this.unbind(),this._targets={}}reset(){this._assignParameters(this._stateGraph);for(let e=0;e<this._layers.length;e++){let s=this._layers[e].playing;this._layers[e].reset(),this._layers[e].playing=s}}unbind(){this._normalizeWeights||Object.keys(this._targets).forEach(e=>{this._targets[e].unbind()})}rebind(){this._targets={};for(let e=0;e<this._layers.length;e++)this._layers[e].rebind()}findAnimationLayer(e){let s=this._layerIndices[e];return this._layers[s]||null}addAnimationState(e,s,i=1,r=!0,a="Base"){this._stateGraph||this.loadStateGraph(new en({layers:[{name:a,states:[{name:"START",speed:1},{name:e,speed:i,loop:r,defaultState:!0}],transitions:[{from:"START",to:e}]}],parameters:{}}));let o=this.findAnimationLayer(a);o?o.assignAnimation(e,s,i,r):this.addLayer(a)?.assignAnimation(e,s,i,r)}assignAnimation(e,s,i,r=1,a=!0){if(!this._stateGraph&&e.indexOf(".")===-1){this.loadStateGraph(new en({layers:[{name:"Base",states:[{name:"START",speed:1},{name:e,speed:r,loop:a,defaultState:!0}],transitions:[{from:"START",to:e}]}],parameters:{}})),this.baseLayer.assignAnimation(e,s);return}let o=i?this.findAnimationLayer(i):this.baseLayer;o&&o.assignAnimation(e,s,r,a)}removeNodeAnimations(e,s){let i=s?this.findAnimationLayer(s):this.baseLayer;i&&i.removeNodeAnimations(e)}getParameterValue(e,s){let i=this._parameters[e];if(i&&i.type===s)return i.value}setParameterValue(e,s,i){let r=this._parameters[e];if(r&&r.type===s){r.value=i;return}}getFloat(e){return this.getParameterValue(e,_0)}setFloat(e,s){this.setParameterValue(e,_0,s)}getInteger(e){return this.getParameterValue(e,m0)}setInteger(e,s){typeof s=="number"&&s%1===0&&this.setParameterValue(e,m0,s)}getBoolean(e){return this.getParameterValue(e,g0)}setBoolean(e,s){this.setParameterValue(e,g0,!!s)}getTrigger(e){return this.getParameterValue(e,cu)}setTrigger(e,s=!1){this.setParameterValue(e,cu,!0),s&&this._consumedTriggers.add(e)}resetTrigger(e){this.setParameterValue(e,cu,!1)}onBeforeRemove(){Number.isFinite(this._stateGraphAsset)&&this.system.app.assets.get(this._stateGraphAsset).off("change",this._onStateGraphAssetChangeEvent,this)}update(e){for(let s=0;s<this.layers.length;s++)this.layers[s].update(e*this.speed);this._consumedTriggers.forEach(s=>{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<i;r++){let a=s.getChildShape(r);if(Ammo.getPointer(a)===Ammo.getPointer(e))return r}return null}_onInsert(e){if(!(typeof Ammo>"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<o.length;h+=3)a.setValue(o[h]*i.x,o[h+1]*i.y,o[h+2]*i.z),r.addPoint(a,!1);Ammo.destroy(a),r.recalcLocalAabb(),r.setMargin(.01);let l=this.system._getNodeTransform(e);s.addChildShape(l,r),Ammo.destroy(l)}createAmmoMesh(t,e,s,i,r=!0){let a=this.system,o;if(a._triMeshCache[t.id])o=a._triMeshCache[t.id];else{let f=t.vertexBuffer,u=f.getFormat(),d,p;for(let D=0;D<u.elements.length;D++){let O=u.elements[D];if(O.name===ee){p=new Float32Array(f.lock(),O.offset),d=O.stride/4;break}}let m=[];t.getIndices(m);let _=t.primitive[0].count/3,S=new Ammo.btVector3,g,T,C,v=t.primitive[0].base;o=new Ammo.btTriangleMesh,a._triMeshCache[t.id]=o;let E=new Map,y=o.getIndexedMeshArray();y.at(0).m_numTriangles=_;let P=i?i.x:1,A=i?i.y:1,w=i?i.z:1,I=D=>{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<a.length;o++)e.convexHull?this.createAmmoHull(a[o],EB,s,r):this.createAmmoMesh(a[o],EB,s,r,e.checkVertexDuplicates)}else if(e.model){let a=e.model.meshInstances;for(let l=0;l<a.length;l++)this.createAmmoMesh(a[l].mesh,a[l].node,s,null,e.checkVertexDuplicates);let o=new Ammo.btVector3(r.x,r.y,r.z);s.setLocalScaling(o),Ammo.destroy(o)}return s}}recreatePhysicalShapes(t){let e=t.data;if((e.renderAsset||e.asset)&&t.enabled&&t.entity.enabled){this.loadAsset(t,e.renderAsset||e.asset,e.renderAsset?"render":"model");return}this.doRecreatePhysicalShape(t)}loadAsset(t,e,s){let i=t.data,r=this.system.app.assets,a=i[s],o=f=>{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<e;s++){let i=t.shape.getChildShape(s);Ammo.destroy(i)}Ammo.destroy(t.shape),t.shape=null}},fR=class extends xl{createPhysicalShape(t,e){if(typeof Ammo<"u")return new Ammo.btCompoundShape}_addEachDescendant(t){!t.collision||t.rigidbody||(t.collision._compoundParent=this,t!==this.entity&&t.collision.system.recreatePhysicalShapes(t.collision))}_updateEachDescendant(t){t.collision&&t.collision._compoundParent===this&&(t.collision._compoundParent=null,t!==this.entity&&!t.rigidbody&&t.collision.system.recreatePhysicalShapes(t.collision))}_updateEachDescendantTransform(t){!t.collision||t.collision._compoundParent!==this.collision._compoundParent||this.collision.system.updateCompoundChildTransform(t,!1)}},Fm=class extends Fe{constructor(t){super(t),this.id="collision",this.ComponentType=eo,this.DataType=R0,this.schema=O8,this.implementations={},this._triMeshCache={},this.on("beforeremove",this.onBeforeRemove,this),this.on("remove",this.onRemove,this)}initializeComponentData(t,e,s){s=["type","halfExtents","radius","axis","height","convexHull","shape","model","asset","render","renderAsset","enabled","linearOffset","angularOffset","checkVertexDuplicates"];let i={};for(let o=0,l=s.length;o<l;o++){let h=s[o];i[h]=e[h]}let r;if(e.hasOwnProperty("asset")?(r=s.indexOf("model"),r!==-1&&s.splice(r,1),r=s.indexOf("render"),r!==-1&&s.splice(r,1)):e.hasOwnProperty("model")&&(r=s.indexOf("asset"),r!==-1&&s.splice(r,1)),i.type||(i.type=t.data.type),t.data.type=i.type,Array.isArray(i.halfExtents)&&(i.halfExtents=new x(i.halfExtents)),Array.isArray(i.linearOffset)&&(i.linearOffset=new x(i.linearOffset)),Array.isArray(i.angularOffset)){let o=i.angularOffset;o.length===3?i.angularOffset=new $().setFromEulerAngles(o[0],o[1],o[2]):i.angularOffset=new $(i.angularOffset)}let a=this._createImplementation(i.type);a.beforeInitialize(t,i),super.initializeComponentData(t,i,s),a.afterInitialize(t,i)}_createImplementation(t){if(this.implementations[t]===void 0){let e;switch(t){case"box":e=new aR(this);break;case"sphere":e=new oR(this);break;case"capsule":e=new nR(this);break;case"cylinder":e=new lR(this);break;case"cone":e=new cR(this);break;case"mesh":e=new hR(this);break;case"compound":e=new fR(this);break;default:}this.implementations[t]=e}return this.implementations[t]}_getImplementation(t){return this.implementations[t.collision.data.type]}cloneComponent(t,e){return this._getImplementation(t).clone(t,e)}onBeforeRemove(t,e){this.implementations[e.data.type].beforeRemove(t,e),e.onBeforeRemove()}onRemove(t,e){this.implementations[e.type].remove(t,e)}updateCompoundChildTransform(t,e){let s=t.collision._compoundParent;if(s!==t.collision&&t.enabled&&t.collision.enabled&&(t._dirtyLocal||e)){let i=this._getNodeTransform(t,s.entity),r=s.getCompoundChildShapeIndex(t.collision.shape);r===null?s.shape.addChildShape(i,t.collision.data.shape):s.shape.updateChildTransform(r,i,!0),Ammo.destroy(i)}}_removeCompoundChild(t,e){if(t.shape.getNumChildShapes()!==0)if(t.shape.removeChildShape)t.shape.removeChildShape(e);else{let s=t.getCompoundChildShapeIndex(e);s!==null&&t.shape.removeChildShapeByIndex(s)}}onTransformChanged(t,e,s,i){this.implementations[t.data.type].updateTransform(t,e,s,i)}changeType(t,e,s){this.implementations[e].beforeRemove(t.entity,t),this.implementations[e].remove(t.entity,t.data),this._createImplementation(s).reset(t,t.data)}recreatePhysicalShapes(t){this.implementations[t.data.type].recreatePhysicalShapes(t)}_calculateNodeRelativeTransform(t,e){if(t===e){let s=t.getWorldTransform().getScale();L0.setScale(s.x,s.y,s.z)}else this._calculateNodeRelativeTransform(t.parent,e),L0.mul(t.getLocalTransform())}_getNodeScaling(t){let s=t.getWorldTransform().getScale();return new Ammo.btVector3(s.x,s.y,s.z)}_getNodeTransform(t,e){let s,i;e?(this._calculateNodeRelativeTransform(t,e),s=L8,i=xu,L0.getTranslation(s),i.setFromMat4(L0)):(s=t.getPosition(),i=t.getRotation());let r=new Ammo.btQuaternion,a=new Ammo.btTransform;a.setIdentity();let o=a.getOrigin(),l=t.collision;if(l&&l._hasOffset){let h=l.data.linearOffset,f=l.data.angularOffset,u=M8;xu.copy(i).transformVector(h,u),u.add(s),xu.copy(i).mul(f),o.setValue(u.x,u.y,u.z),r.setValue(xu.x,xu.y,xu.z,xu.w)}else o.setValue(s.x,s.y,s.z),r.setValue(i.x,i.y,i.z,i.w);return a.setRotation(r),Ammo.destroy(r),a}destroy(){for(let t in this._triMeshCache)Ammo.destroy(this._triMeshCache[t]);this._triMeshCache=null,super.destroy()}};var M0=new F,F8=new et,uR=class{constructor(t,e,s){this._entity=t,this._element=t.element,this.model=new Ei,this.node=new Pe,this.model.graph=this.node,this.mesh=e,this.meshInstance=new we(this.mesh,s,this.node),this.meshInstance.name=`ImageElement: ${t.name}`,this.meshInstance.castShadow=!1,this.meshInstance.receiveShadow=!1,this._meshDirty=!1,this.model.meshInstances.push(this.meshInstance),this._entity.addChild(this.model.graph),this.model._entity=this._entity,this.unmaskMeshInstance=null}destroy(){this.setMaterial(null),this._element.removeModelFromLayers(this.model),this.model.destroy(),this.model=null,this.node=null,this.mesh=null,this.meshInstance?.destroy(),this.meshInstance=null,this.unmaskMeshInstance?.destroy(),this.unmaskMeshInstance=null,this._entity=null,this._element=null}setMesh(t){this.meshInstance&&(this.mesh=t,this.meshInstance.mesh=t,this.meshInstance.visible=!!t,this.unmaskMeshInstance&&(this.unmaskMeshInstance.mesh=t),this.forceUpdateAabb())}setMask(t){if(this.meshInstance){if(this._entity.enabled&&this._element.enabled&&this._element.removeModelFromLayers(this.model),t){this.unmaskMeshInstance=new we(this.mesh,this.meshInstance.material,this.node),this.unmaskMeshInstance.name=`Unmask: ${this._entity.name}`,this.unmaskMeshInstance.castShadow=!1,this.unmaskMeshInstance.receiveShadow=!1,this.unmaskMeshInstance.pick=!1,this.model.meshInstances.push(this.unmaskMeshInstance);for(let e in this.meshInstance.parameters)this.unmaskMeshInstance.setParameter(e,this.meshInstance.parameters[e].data)}else{let e=this.model.meshInstances.indexOf(this.unmaskMeshInstance);e>=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;o<r;o++)i[o].element&&(s=i[o]);if(!s)return null;let a=t(s);return a||s}return null};if(this.unmaskMeshInstance){let e=t(this._entity);e&&e.element?this.unmaskMeshInstance.drawOrder=e.element.drawOrder+e.element.getMaskOffset():this.unmaskMeshInstance.drawOrder=this.meshInstance.drawOrder+this._element.getMaskOffset()}}setDrawOrder(t){this.meshInstance&&(this.meshInstance.drawOrder=t)}setCull(t){if(!this.meshInstance)return;let e=this._element,s=null;t&&e._isScreenSpace()&&(s=function(i){return e.isVisibleForCamera(i)}),this.meshInstance.cull=t,this.meshInstance.isVisibleFunc=s,this.unmaskMeshInstance&&(this.unmaskMeshInstance.cull=t,this.unmaskMeshInstance.isVisibleFunc=s)}setScreenSpace(t){this.meshInstance&&(this.meshInstance.screenSpace=t,this.unmaskMeshInstance&&(this.unmaskMeshInstance.screenSpace=t))}setLayer(t){this.meshInstance&&(this.meshInstance.layer=t,this.unmaskMeshInstance&&(this.unmaskMeshInstance.layer=t))}forceUpdateAabb(t){this.meshInstance&&(this.meshInstance._aabbVer=-1,this.unmaskMeshInstance&&(this.unmaskMeshInstance._aabbVer=-1))}setAabbFunc(t){this.meshInstance&&(this.meshInstance._updateAabbFunc=t,this.unmaskMeshInstance&&(this.unmaskMeshInstance._updateAabbFunc=t))}},Nm=class{constructor(t){n(this,"_evtSetMeshes",null);this._element=t,this._entity=t.entity,this._system=t.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 Q(0,0,1,1),this._mask=!1,this._maskRef=0,this._outerScale=new B,this._outerScaleUniform=new Float32Array(2),this._innerOffset=new Q,this._innerOffsetUniform=new Float32Array(4),this._atlasRect=new Q,this._atlasRectUniform=new Float32Array(4),this._defaultMesh=this._createMesh(),this._renderable=new uR(this._entity,this._defaultMesh,this._material),this._color=new F(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),!t._beingInitialized&&t.enabled&&t.entity.enabled&&this.onEnable()}destroy(){this.textureAsset=null,this.spriteAsset=null,this.materialAsset=null,this._renderable.setMesh(this._defaultMesh),this._renderable.destroy(),this._defaultMesh=null,this._element.off("resize",this._onParentResizeOrPivotChange,this),this._element.off("set:pivot",this._onParentResizeOrPivotChange,this),this._element.off("screen:set:screenspace",this._onScreenSpaceChange,this),this._element.off("set:screen",this._onScreenChange,this),this._element.off("set:draworder",this._onDrawOrderChange,this),this._element.off("screen:set:resolution",this._onResolutionChange,this)}_onResolutionChange(t){}_onParentResizeOrPivotChange(){this._renderable.mesh&&this._updateMesh(this._renderable.mesh)}_onScreenSpaceChange(t){this._updateMaterial(t)}_onScreenChange(t,e){t?this._updateMaterial(t.screen.screenSpace):this._updateMaterial(!1)}_onDrawOrderChange(t){this._renderable.setDrawOrder(t),this.mask&&this._element.screen&&this._element.screen.screen.once("syncdraworder",function(){this._renderable.setUnmaskDrawOrder()},this)}_hasUserMaterial(){return!!this._materialAsset||!!this._material&&this._system.defaultImageMaterials.indexOf(this._material)===-1}_use9Slicing(){return this.sprite&&(this.sprite.renderMode===It||this.sprite.renderMode===Rt)}_updateMaterial(t){let e=!!this._mask,s=!!(this.sprite&&this.sprite.renderMode===It),i=!!(this.sprite&&this.sprite.renderMode===Rt);this._hasUserMaterial()||(this._material=this._system.getImageElementMaterial(t,e,s,i)),this._renderable&&(this._renderable.setCull(!this._element._isScreenSpace()||this._element._isScreenCulled()),this._renderable.setMaterial(this._material),this._renderable.setScreenSpace(t),this._renderable.setLayer(t?ow:Xg))}_createMesh(){let t=this._element,e=t.calculatedWidth,s=t.calculatedHeight,i=this._rect,r=this._system.app.graphicsDevice,a=new Float32Array([e,0,0,0,0,1,i.x+i.z,1-i.y,e,s,0,0,0,1,i.x+i.z,1-(i.y+i.w),0,0,0,0,0,1,i.x,1-i.y,0,s,0,0,0,1,i.x,1-(i.y+i.w)]),o=F8.get(r,()=>new 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&&a<this._targetAspectRatio?s=e.calculatedHeight*this._targetAspectRatio:i=e.calculatedWidth/this._targetAspectRatio}let r=e._isScreenSpace();if(this._updateMaterial(r),this._renderable&&this._renderable.forceUpdateAabb(),this.sprite&&(this.sprite.renderMode===It||this.sprite.renderMode===Rt)){let a=this._sprite.atlas.frames[this._sprite.frameKeys[this._spriteFrame]],o=2/a.rect.z,l=2/a.rect.w;this._innerOffset.set(a.border.x*o,a.border.y*l,a.border.z*o,a.border.w*l);let h=this.sprite.atlas.texture;this._atlasRect.set(a.rect.x/h.width,a.rect.y/h.height,a.rect.z/h.width,a.rect.w/h.height);let f=this._pixelsPerUnit!==null?this._pixelsPerUnit:this.sprite.pixelsPerUnit,u=a.rect.z/f,d=a.rect.w/f;this._outerScale.set(Math.max(s,this._innerOffset.x*u),Math.max(i,this._innerOffset.y*d));let p=u,m=d;this._outerScale.x/=u,this._outerScale.y/=d,p*=R.clamp(s/(this._innerOffset.x*u),1e-4,1),m*=R.clamp(i/(this._innerOffset.y*d),1e-4,1),this._renderable&&(this._innerOffsetUniform[0]=this._innerOffset.x,this._innerOffsetUniform[1]=this._innerOffset.y,this._innerOffsetUniform[2]=this._innerOffset.z,this._innerOffsetUniform[3]=this._innerOffset.w,this._renderable.setParameter("innerOffset",this._innerOffsetUniform),this._atlasRectUniform[0]=this._atlasRect.x,this._atlasRectUniform[1]=this._atlasRect.y,this._atlasRectUniform[2]=this._atlasRect.z,this._atlasRectUniform[3]=this._atlasRect.w,this._renderable.setParameter("atlasRect",this._atlasRectUniform),this._outerScaleUniform[0]=this._outerScale.x,this._outerScaleUniform[1]=this._outerScale.y,this._renderable.setParameter("outerScale",this._outerScaleUniform),this._renderable.setAabbFunc(this._updateAabbFunc),this._renderable.node.setLocalScale(p,m,1),this._renderable.node.setLocalPosition((.5-e.pivot.x)*s,(.5-e.pivot.y)*i,0))}else{let a=t.vertexBuffer,o=new Float32Array(a.lock()),l=e.pivot.x,h=e.pivot.y;o[0]=s-l*s,o[1]=0-h*i,o[8]=s-l*s,o[9]=i-h*i,o[16]=0-l*s,o[17]=0-h*i,o[24]=0-l*s,o[25]=i-h*i;let f=1,u=1,d=this._rect;if(this._sprite&&this._sprite.frameKeys[this._spriteFrame]&&this._sprite.atlas){let _=this._sprite.atlas.frames[this._sprite.frameKeys[this._spriteFrame]];_&&(d=_.rect,f=this._sprite.atlas.texture.width,u=this._sprite.atlas.texture.height)}o[6]=(d.x+d.z)/f,o[7]=1-d.y/u,o[14]=(d.x+d.z)/f,o[15]=1-(d.y+d.w)/u,o[22]=d.x/f,o[23]=1-d.y/u,o[30]=d.x/f,o[31]=1-(d.y+d.w)/u,a.unlock();let p=new x(0-l*s,0-h*i,0),m=new x(s-l*s,i-h*i,0);t.aabb.setMinMax(p,m),this._renderable&&(this._renderable.node.setLocalScale(1,1,1),this._renderable.node.setLocalPosition(0,0,0),this._renderable.setAabbFunc(null))}this._meshDirty=!1}_updateSprite(){let t=!1,e=null;if(this._targetAspectRatio=-1,this._sprite&&this._sprite.atlas){e=this._sprite.meshes[this.spriteFrame],t=this._sprite.renderMode===It||this._sprite.renderMode===Rt;let s=this._sprite.atlas.frames[this._sprite.frameKeys[this._spriteFrame]];s?.rect.w>0&&(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<this._symbols.length?this._symbols[this._index]:null),this._cur}_store(){return this._buf.push(this._cur),this._next()}_output(t){this._buf.push(t)}},mR=class{constructor(t){this._scanner=new pR(t),this._error=null}parse(t,e){for(;;)switch(this._scanner.read()){case 0:return!0;case 1:return!1;case 2:Array.prototype.push.apply(t,this._scanner.buf());break;case 3:if(!this._parseTag(t,e))return!1;break;default:return!1}}error(){return`Error evaluating markup at #${this._scanner.last().toString()} (${this._scanner.error()||this._error})`}_parseTag(t,e){let s=this._scanner.read();if(s!==7)return this._error="expected identifier",!1;let i=this._scanner.buf().join("");if(i[0]==="/"){for(let a=e.length-1;a>=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;e<c.length;++e){let s=c[e],i={};i[s.name]={value:s.value,attributes:s.attributes},AB(t,i)}return t}function k8(c,t){if(c.length===0)return null;let e={};for(let f=0;f<c.length;++f){let u=c[f];e.hasOwnProperty(u.start)?e[u.start].open===null?e[u.start].open=[u]:e[u.start].open.push(u):e[u.start]={open:[u],close:null},e.hasOwnProperty(u.end)?e[u.end].close===null?e[u.end].close=[u]:e[u.end].close.push(u):e[u.end]={open:null,close:[u]}}let s=[];function i(f){s=s.filter(u=>f.find(d=>d===u)===void 0)}function r(f){for(let u=0;u<f.length;++u)s.push(f[u])}let a=Object.keys(e).sort((f,u)=>f-u),o=[];for(let f=0;f<a.length;++f){let u=e[a[f]];u.close!==null&&i(u.close),u.open!==null&&r(u.open),o.push({start:a[f],tags:U8(s)})}let l=[],h=null;for(let f=0;f<o.length;++f){let u=o[f];for(;l.length<u.start;)l.push(h?h.tags:null);h=u}for(;l.length<t;)l.push(null);return l}function z8(c){let t=new mR(c),e=[],s=[];if(!t.parse(e,s))return{symbols:c,tags:null};if(s.find(a=>a.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;e<s;e++)this._model.meshInstances[e].drawOrder=t}_onPivotChange(t){this._font&&this._updateText()}_onLocaleSet(t){if(this._i18nKey){if(this.fontAsset){let e=this._system.app.assets.get(this.fontAsset);(!e||!e.resource||e.resource!==this._font)&&(this.font=null)}this._resetLocalizedText()}}_onLocalizationData(t,e){this._i18nKey&&e[this._i18nKey]&&this._resetLocalizedText()}_resetLocalizedText(){this._setText(this._system.app.i18n.getText(this._i18nKey))}_setText(t){if(this.unicodeConverter){let e=this._system.getUnicodeConverter();e&&(t=e(t))}this._text!==t&&(this._font&&this._updateText(t),this._text=t)}_updateText(t){let e;if(t===void 0&&(t=this._text),this._symbols=Nr.getSymbols(t.normalize?t.normalize("NFC"):t),this._symbols.length===0&&(this._symbols=[" "]),this._enableMarkup){let u=O0.evaluate(this._symbols);this._symbols=u.symbols,e=u.tags||[]}if(this._rtlReorder){let u=this._system.app.systems.element.getRtlReorder();if(u){let d=u(this._symbols);this._rtl=d.rtl,this._symbols=d.mapping.map(function(p){return this._symbols[p]},this),e&&(e=d.mapping.map(p=>e[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<d;u++){let p=r[u]||0,m=this._meshInfo[u];if(m.count!==p){if(a||(o.removeModelFromLayers(this._model),a=!0),m.count=p,m.positions.length=m.normals.length=p*3*4,m.indices.length=p*3*2,m.uvs.length=p*2*4,m.colors.length=p*4*4,m.outlines.length=p*4*3,m.shadows.length=p*4*3,m.meshInstance&&this._removeMeshInstance(m.meshInstance),p===0){m.meshInstance=null;continue}for(let g=0;g<p;g++)m.indices[g*3*2+0]=g*4,m.indices[g*3*2+1]=g*4+1,m.indices[g*3*2+2]=g*4+3,m.indices[g*3*2+3]=g*4+2,m.indices[g*3*2+4]=g*4+3,m.indices[g*3*2+5]=g*4+1,m.normals[g*4*3+0]=0,m.normals[g*4*3+1]=0,m.normals[g*4*3+2]=-1,m.normals[g*4*3+3]=0,m.normals[g*4*3+4]=0,m.normals[g*4*3+5]=-1,m.normals[g*4*3+6]=0,m.normals[g*4*3+7]=0,m.normals[g*4*3+8]=-1,m.normals[g*4*3+9]=0,m.normals[g*4*3+10]=0,m.normals[g*4*3+11]=-1;let _=G8(this._system.app.graphicsDevice,m),S=new we(_,this._material,this._node);if(S.name=`Text Element: ${this._entity.name}`,S.castShadow=!1,S.receiveShadow=!1,S.cull=!l,S.screenSpace=l,S.drawOrder=this._drawOrder,h&&(S.cull=!0,S.isVisibleFunc=f),this._setTextureParams(S,this._font.textures[u]),S.setParameter("material_emissive",this._colorUniform),S.setParameter("material_opacity",this._color.a),S.setParameter("font_sdfIntensity",this._font.intensity),S.setParameter("font_pxrange",this._getPxRange(this._font)),S.setParameter("font_textureWidth",this._font.data.info.maps[u].width),S.setParameter("outline_color",this._outlineColorUniform),S.setParameter("outline_thickness",this._outlineThicknessScale*this._outlineThickness),S.setParameter("shadow_color",this._shadowColorUniform),this._symbolShadowParams)this._shadowOffsetUniform[0]=0,this._shadowOffsetUniform[1]=0;else{let g=-this._font.data.info.maps[u].width/this._font.data.info.maps[u].height;this._shadowOffsetUniform[0]=this._shadowOffsetScale*this._shadowOffset.x,this._shadowOffsetUniform[1]=g*this._shadowOffsetScale*this._shadowOffset.y}S.setParameter("shadow_offset",this._shadowOffsetUniform),m.meshInstance=S,this._model.meshInstances.push(S)}}this._element.maskedBy&&this._element._setMaskedBy(this._element.maskedBy),a&&this._element.enabled&&this._entity.enabled&&this._element.addModelToLayers(this._model),this._updateMeshes(),this._rangeStart=0,this._rangeEnd=this._symbols.length,this._updateRenderRange()}_removeMeshInstance(t){t.destroy();let e=this._model.meshInstances.indexOf(t);e!==-1&&this._model.meshInstances.splice(e,1)}_setMaterial(t){if(this._material=t,this._model)for(let e=0,s=this._model.meshInstances.length;e<s;e++){let i=this._model.meshInstances[e];i.material=t}}_updateMaterial(t){let e=this._element,s=e._isScreenCulled(),i=function(a){return e.isVisibleForCamera(a)},r=this._font&&this._font.type===vu;if(this._material=this._system.getTextElementMaterial(t,r,this._enableMarkup),this._model)for(let a=0,o=this._model.meshInstances.length;a<o;a++){let l=this._model.meshInstances[a];l.cull=!t,l.material=this._material,l.screenSpace=t,s?(l.cull=!0,l.isVisibleFunc=i):l.isVisibleFunc=null}}_updateMaterialEmissive(){this._symbolColors?(this._colorUniform[0]=1,this._colorUniform[1]=1,this._colorUniform[2]=1):(Et.linear(this._color),this._colorUniform[0]=Et.r,this._colorUniform[1]=Et.g,this._colorUniform[2]=Et.b)}_updateMaterialOutline(){this._symbolOutlineParams?(this._outlineColorUniform[0]=0,this._outlineColorUniform[1]=0,this._outlineColorUniform[2]=0,this._outlineColorUniform[3]=1):(Et.linear(this._outlineColor),this._outlineColorUniform[0]=Et.r,this._outlineColorUniform[1]=Et.g,this._outlineColorUniform[2]=Et.b,this._outlineColorUniform[3]=Et.a)}_updateMaterialShadow(){this._symbolOutlineParams?(this._shadowColorUniform[0]=0,this._shadowColorUniform[1]=0,this._shadowColorUniform[2]=0,this._shadowColorUniform[3]=0):(Et.linear(this._shadowColor),this._shadowColorUniform[0]=Et.r,this._shadowColorUniform[1]=Et.g,this._shadowColorUniform[2]=Et.b,this._shadowColorUniform[3]=Et.a)}_isWordBoundary(t){return PB.test(t)}_isValidNextChar(t){return t!==null&&!W8.test(t)}_isNextCJKBoundary(t,e){return wB.test(t)&&(PB.test(e)||H8.test(e))}_isNextCJKWholeWord(t){return wB.test(t)}_updateMeshes(){let t=this._font.data,e=this,s=Math.min(this._minFontSize,this._maxFontSize),i=this._maxFontSize,r=this._shouldAutoFit();r&&(this._fontSize=this._maxFontSize);let a=32,o=this._symbols.length,l=0,h=0,f=0,u=0,d=1,p=0,m=0,_=0,S=0,g=0,T=0,C=Math.abs(this._element.anchor.x-this._element.anchor.z)>=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<this._meshInfo.length;oe++)this._meshInfo[oe].quad=0,this._meshInfo[oe].lines={};let b=255,N=255,k=255,z=255+255*256,V=255+255*256,q=0,re=255+255*256,te=255+255*256,j=127+127*256;for(let oe=0;oe<o;oe++){if(P=this._symbols[oe],I=oe+1>=o?null:this._symbols[oe+1],CB.test(P)){T++,(!this._wrapLines||this._maxLines<0||d<this._maxLines)&&(D(this._symbols,oe,u),m=oe+1,_=oe+1);continue}let qe=0,ot=0,Ve=0,Lt=1,Vs,ds;if(A=t.chars[P],!A)if(X8.indexOf(P)!==-1)A=Y8;else if(t.chars[" "])A=t.chars[" "];else for(let mt in t.chars){A=t.chars[mt];break}if(A){let mt=0;if(g>0){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||d<this._maxLines))if(S===0)m=oe,D(this._symbols,oe,u);else{let mt=Math.max(oe-m,0);if(this._meshInfo.length<=1)de.lines[d-1]-=mt,de.quad-=mt;else{let Px=m,wx=oe;for(let yC=Px;yC<wx;yC++){let BH=this._symbols[yC],eD=t.chars[BH],tD=this._meshInfo[eD&&eD.map||0];tD.lines[d-1]-=1,tD.quad-=1}}oe-=mt+1,D(this._symbols,m,p);continue}w=de.quad,de.lines[d-1]=w;let Cx=l-qe,vC=Cx+Lt,TC=h-ot,Jb=TC+Lt;if(this._rtl){let mt=Lt-qe-this._spacing*Ve-qe;Cx-=mt,vC-=mt}de.positions[w*4*3+0]=Cx,de.positions[w*4*3+1]=TC,de.positions[w*4*3+2]=f,de.positions[w*4*3+3]=vC,de.positions[w*4*3+4]=TC,de.positions[w*4*3+5]=f,de.positions[w*4*3+6]=vC,de.positions[w*4*3+7]=Jb,de.positions[w*4*3+8]=f,de.positions[w*4*3+9]=Cx,de.positions[w*4*3+10]=Jb,de.positions[w*4*3+11]=f,this.width=Math.max(this.width,Qb);let Vl;if(this._shouldAutoFitWidth()&&this.width>this._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||_<o&&D(this._symbols,o,l)}this._noResize=!0,this.autoWidth=this._autoWidth,this.autoHeight=this._autoHeight,this._noResize=!1;let G=this._element.pivot.x,M=this._element.pivot.y,H=this._alignment.x,U=this._alignment.y;for(let L=0;L<this._meshInfo.length;L++){if(this._meshInfo[L].count===0)continue;let b=0;for(let V in this._meshInfo[L].lines){let q=this._meshInfo[L].lines[V],re=this._lineWidths[parseInt(V,10)],te=-G*this._element.calculatedWidth+H*(this._element.calculatedWidth-re)*(this._rtl?-1:1),j=(1-M)*this._element.calculatedHeight-y-(1-U)*(this._element.calculatedHeight-this.height);for(let oe=b;oe<=q;oe++)this._meshInfo[L].positions[oe*4*3]+=te,this._meshInfo[L].positions[oe*4*3+3]+=te,this._meshInfo[L].positions[oe*4*3+6]+=te,this._meshInfo[L].positions[oe*4*3+9]+=te,this._meshInfo[L].positions[oe*4*3+1]+=j,this._meshInfo[L].positions[oe*4*3+4]+=j,this._meshInfo[L].positions[oe*4*3+7]+=j,this._meshInfo[L].positions[oe*4*3+10]+=j;if(this._rtl)for(let oe=b;oe<=q;oe++){let be=oe*4*3;for(let Ve=0;Ve<4;++Ve)this._meshInfo[L].positions[be+Ve*3]=this._element.calculatedWidth-this._meshInfo[L].positions[be+Ve*3]+te*2;let qe=this._meshInfo[L].positions[be+3],ot=this._meshInfo[L].positions[be+6];this._meshInfo[L].positions[be+3]=this._meshInfo[L].positions[be+0],this._meshInfo[L].positions[be+6]=this._meshInfo[L].positions[be+9],this._meshInfo[L].positions[be+0]=qe,this._meshInfo[L].positions[be+9]=ot}b=q+1}let N=this._meshInfo[L].count*4,k=this._meshInfo[L].quad*4,z=new Jr(this._meshInfo[L].meshInstance.mesh.vertexBuffer);for(let V=0;V<N;V++)V>=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;a<r;a++){if(!this._meshInfo[a])continue;let o=this._meshInfo[a].meshInstance;o&&(o.setParameter("font_sdfIntensity",this._font.intensity),o.setParameter("font_pxrange",this._getPxRange(this._font)),o.setParameter("font_textureWidth",this._font.data.info.maps[a].width))}}}_onFontRemove(t){}_setTextureParams(t,e){this._font&&(this._font.type===vu?(t.deleteParameter("texture_emissiveMap"),t.deleteParameter("texture_opacityMap"),t.setParameter("texture_msdfMap",e)):this._font.type===dR&&(t.deleteParameter("texture_msdfMap"),t.setParameter("texture_emissiveMap",e),t.setParameter("texture_opacityMap",e)))}_getPxRange(t){let e=Object.keys(this._font.data.chars);for(let s=0;s<e.length;s++){let i=this._font.data.chars[e[s]];if(i.range)return(i.scale||1)*i.range}return 2}_getUv(t){let e=this._font.data;if(!e.chars[t])return e.chars[" "]?this._getUv(" "):[0,0,0,0];let s=e.chars[t].map,i=e.info.maps[s].width,r=e.info.maps[s].height,a=e.chars[t].x,o=e.chars[t].y,l=a,h=o,f=a+e.chars[t].width,u=o-e.chars[t].height,d=1-e.chars[t].height/r;return[l/i,d-h/r,f/i,d-u/r]}onEnable(){this._fontAsset.autoLoad=!0,this._model&&this._element.addModelToLayers(this._model)}onDisable(){this._fontAsset.autoLoad=!1,this._model&&this._element.removeModelFromLayers(this._model)}_setStencil(t){if(this._model){let e=this._model.meshInstances;for(let s=0;s<e.length;s++)e[s].stencilFront=t,e[s].stencilBack=t}}_shouldAutoFitWidth(){return this._autoFitWidth&&!this._autoWidth}_shouldAutoFitHeight(){return this._autoFitHeight&&!this._autoHeight}_shouldAutoFit(){return this._autoFitWidth&&!this._autoWidth||this._autoFitHeight&&!this._autoHeight}_calculateCharsPerTexture(t){let e={};t===void 0&&(t=this._symbols.length);for(let s=0,i=t;s<i;s++){let r=this._symbols[s],a=this._font.data.chars[r];a||(a=this._font.data.chars[" "],a||(a=this._font.data.chars[Object.keys(this._font.data.chars)[0]]));let o=a.map;e[o]?e[o]++:e[o]=1}return e}_updateRenderRange(){let t=this._rangeStart===0?0:this._calculateCharsPerTexture(this._rangeStart),e=this._rangeEnd===0?0:this._calculateCharsPerTexture(this._rangeEnd);for(let s=0,i=this._meshInfo.length;s<i;s++){let r=t[s]||0,a=e[s]||0,o=this._meshInfo[s].meshInstance;if(o){let l=o.mesh;l&&(l.primitive[0].base=r*3*2,l.primitive[0].count=(a-r)*3*2)}}}set text(t){this._i18nKey=null;let e=t!=null&&t.toString()||"";this._setText(e)}get text(){return this._text}set key(t){let e=t!==null?t.toString():null;this._i18nKey!==e&&(this._i18nKey=e,e?(this._fontAsset.disableLocalization=!1,this._resetLocalizedText()):this._fontAsset.disableLocalization=!0)}get key(){return this._i18nKey}set color(t){let e=t.r,s=t.g,i=t.b;if(!(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._model)){if(this._symbolColors)this._font&&this._updateText();else{Et.linear(this._color),this._colorUniform[0]=Et.r,this._colorUniform[1]=Et.g,this._colorUniform[2]=Et.b;for(let r=0,a=this._model.meshInstances.length;r<a;r++)this._model.meshInstances[r].setParameter("material_emissive",this._colorUniform)}this._element&&this._element.fire("set:color",this._color)}}get color(){return this._color}set opacity(t){if(this._color.a!==t&&(this._color.a=t,this._model))for(let e=0,s=this._model.meshInstances.length;e<s;e++)this._model.meshInstances[e].setParameter("material_opacity",t);this._element&&this._element.fire("set:opacity",t)}get opacity(){return this._color.a}set lineHeight(t){let e=this._lineHeight;this._lineHeight=t,this._scaledLineHeight=t,e!==t&&this._font&&this._updateText()}get lineHeight(){return this._lineHeight}set wrapLines(t){let e=this._wrapLines;this._wrapLines=t,e!==t&&this._font&&this._updateText()}get wrapLines(){return this._wrapLines}get lines(){return this._lineContents}set spacing(t){let e=this._spacing;this._spacing=t,e!==t&&this._font&&this._updateText()}get spacing(){return this._spacing}set fontSize(t){let e=this._fontSize;this._fontSize=t,this._originalFontSize=t,e!==t&&this._font&&this._updateText()}get fontSize(){return this._fontSize}set fontAsset(t){this._fontAsset.defaultAsset=t}get fontAsset(){return this._fontAsset.localizedAsset}set font(t){let e;if(this._font&&(e=this._font.type,this._font.off&&this._font.off("render",this._onFontRender,this)),this._font=t,this._fontMinY=0,this._fontMaxY=0,!t)return;let s=this._font.data;for(let r in s.chars){let a=s.chars[r];a.bounds&&(this._fontMinY=Math.min(this._fontMinY,a.bounds[1]),this._fontMaxY=Math.max(this._fontMaxY,a.bounds[3]))}if(this._font.on&&this._font.on("render",this._onFontRender,this),this._fontAsset.localizedAsset&&this._system.app.assets.get(this._fontAsset.localizedAsset).resource!==this._font&&(this._fontAsset.defaultAsset=null),t.type!==e){let r=this._element._isScreenSpace();this._updateMaterial(r)}for(let r=0,a=this._font.textures.length;r<a;r++)if(!this._meshInfo[r])this._meshInfo[r]=new _R;else{let o=this._meshInfo[r].meshInstance;o&&(o.setParameter("font_sdfIntensity",this._font.intensity),o.setParameter("font_pxrange",this._getPxRange(this._font)),o.setParameter("font_textureWidth",this._font.data.info.maps[r].width),this._setTextureParams(o,this._font.textures[r]))}let i=!1;for(let r=this._font.textures.length;r<this._meshInfo.length;r++)this._meshInfo[r].meshInstance&&(i||(this._element.removeModelFromLayers(this._model),i=!0),this._removeMeshInstance(this._meshInfo[r].meshInstance));this._meshInfo.length>this._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<this._meshInfo.length;e++)this._meshInfo[e].meshInstance&&(t?this._aabb.add(this._meshInfo[e].meshInstance.aabb):(this._aabb.copy(this._meshInfo[e].meshInstance.aabb),t=!0));this._aabbDirty=!1}return this._aabb}set outlineColor(t){let e=t instanceof F?t.r:t[0],s=t instanceof F?t.g:t[1],i=t instanceof F?t.b:t[2],r=t instanceof F?t.a:t[3];if(!(this._outlineColor.r===e&&this._outlineColor.g===s&&this._outlineColor.b===i&&this._outlineColor.a===r)&&(this._outlineColor.r=e,this._outlineColor.g=s,this._outlineColor.b=i,this._outlineColor.a=r,!!this._model)){if(this._symbolOutlineParams)this._font&&this._updateText();else{Et.linear(this._outlineColor),this._outlineColorUniform[0]=Et.r,this._outlineColorUniform[1]=Et.g,this._outlineColorUniform[2]=Et.b,this._outlineColorUniform[3]=Et.a;for(let a=0,o=this._model.meshInstances.length;a<o;a++)this._model.meshInstances[a].setParameter("outline_color",this._outlineColorUniform)}this._element&&this._element.fire("set:outline",this._color)}}get outlineColor(){return this._outlineColor}set outlineThickness(t){let e=this._outlineThickness;if(this._outlineThickness=t,e!==t&&this._font){if(!this._model)return;if(this._symbolOutlineParams)this._font&&this._updateText();else for(let s=0,i=this._model.meshInstances.length;s<i;s++)this._model.meshInstances[s].setParameter("outline_thickness",this._outlineThicknessScale*this._outlineThickness)}}get outlineThickness(){return this._outlineThickness}set shadowColor(t){let e=t instanceof F?t.r:t[0],s=t instanceof F?t.g:t[1],i=t instanceof F?t.b:t[2],r=t instanceof F?t.a:t[3];if(!(this._shadowColor.r===e&&this._shadowColor.g===s&&this._shadowColor.b===i&&this._shadowColor.a===r)&&(this._shadowColor.r=e,this._shadowColor.g=s,this._shadowColor.b=i,this._shadowColor.a=r,!!this._model))if(this._symbolShadowParams)this._font&&this._updateText();else{Et.linear(this._shadowColor),this._shadowColorUniform[0]=Et.r,this._shadowColorUniform[1]=Et.g,this._shadowColorUniform[2]=Et.b,this._shadowColorUniform[3]=Et.a;for(let a=0,o=this._model.meshInstances.length;a<o;a++)this._model.meshInstances[a].setParameter("shadow_color",this._shadowColorUniform)}}get shadowColor(){return this._shadowColor}set shadowOffset(t){let e=t instanceof B?t.x:t[0],s=t instanceof B?t.y:t[1];if(!(this._shadowOffset.x===e&&this._shadowOffset.y===s)&&(this._shadowOffset.set(e,s),this._font&&this._model))if(this._symbolShadowParams)this._updateText();else for(let i=0,r=this._model.meshInstances.length;i<r;i++){let a=-this._font.data.info.maps[i].width/this._font.data.info.maps[i].height;this._shadowOffsetUniform[0]=this._shadowOffsetScale*this._shadowOffset.x,this._shadowOffsetUniform[1]=a*this._shadowOffsetScale*this._shadowOffset.y,this._model.meshInstances[i].setParameter("shadow_offset",this._shadowOffsetUniform)}}get shadowOffset(){return this._shadowOffset}set minFontSize(t){this._minFontSize!==t&&(this._minFontSize=t,this.font&&this._shouldAutoFit()&&this._updateText())}get minFontSize(){return this._minFontSize}set maxFontSize(t){this._maxFontSize!==t&&(this._maxFontSize=t,this.font&&this._shouldAutoFit()&&this._updateText())}get maxFontSize(){return this._maxFontSize}set autoFitWidth(t){this._autoFitWidth!==t&&(this._autoFitWidth=t,this._fontSize=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize,this.font&&this._updateText())}get autoFitWidth(){return this._autoFitWidth}set autoFitHeight(t){this._autoFitHeight!==t&&(this._autoFitHeight=t,this._fontSize=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize,this.font&&this._updateText())}get autoFitHeight(){return this._autoFitHeight}set maxLines(t){this._maxLines!==t&&(t===null&&this._maxLines===-1||(this._maxLines=t===null?-1:t,this.font&&this._wrapLines&&this._updateText()))}get maxLines(){return this._maxLines}set enableMarkup(t){if(t=!!t,this._enableMarkup===t)return;this._enableMarkup=t,this.font&&this._updateText();let e=this._element._isScreenSpace();this._updateMaterial(e)}get enableMarkup(){return this._enableMarkup}get symbols(){return this._symbols}get symbolColors(){return this._symbolColors===null?null:this._symbolColors.map(function(t){return this._colorPalette.slice(t*3,t*3+3)},this)}get symbolOutlineParams(){return this._symbolOutlineParams===null?null:this._symbolOutlineParams.map(function(t){return this._outlinePalette.slice(t*5,t*5+5)},this)}get symbolShadowParams(){return this._symbolShadowParams===null?null:this._symbolShadowParams.map(function(t){return this._shadowPalette.slice(t*6,t*6+6)},this)}get rtl(){return this._rtl}set rangeStart(t){t=Math.max(0,Math.min(t,this._symbols.length)),t!==this._rangeStart&&(this._rangeStart=t,this._updateRenderRange())}get rangeStart(){return this._rangeStart}set rangeEnd(t){t=Math.max(this._rangeStart,Math.min(t,this._symbols.length)),t!==this._rangeEnd&&(this._rangeEnd=t,this._updateRenderRange())}get rangeEnd(){return this._rangeEnd}};var gR=new x,RB=new W,vl=new x,j8=new x,da=new W,F0=new W,N0=new W,km=new W,zs=class extends le{constructor(e,s){super(e,s);n(this,"_evtLayersChanged",null);n(this,"_evtLayerAdded",null);n(this,"_evtLayerRemoved",null);this._beingInitialized=!1,this._anchor=new Q,this._localAnchor=new Q,this._pivot=new B,this._width=this._calculatedWidth=32,this._height=this._calculatedHeight=32,this._margin=new Q(0,0,-32,-32),this._modelTransform=new W,this._screenToWorld=new W,this._anchorTransform=new W,this._anchorDirty=!0,this._parentWorldTransform=new W,this._screenTransform=new W,this._screenCorners=[new x,new x,new x,new x],this._canvasCorners=[new B,new B,new B,new B],this._worldCorners=[new x,new x,new x,new x],this._cornersDirty=!0,this._canvasCornersDirty=!0,this._worldCornersDirty=!0,this.entity.on("insert",this._onInsert,this),this._patch(),this.screen=null,this._type=mu,this._image=null,this._text=null,this._group=null,this._drawOrder=0,this._fitMode=_u,this._useInput=!1,this._layers=[Va],this._addedModels=[],this._batchGroupId=-1,this._offsetReadAt=0,this._maskOffset=.5,this._maskedBy=null}set enabled(e){let s=this.data,i=s.enabled;s.enabled=e,this.fire("set","enabled",i,e)}get enabled(){return this.data.enabled}get _absLeft(){return this._localAnchor.x+this._margin.x}get _absRight(){return this._localAnchor.z-this._margin.z}get _absTop(){return this._localAnchor.w-this._margin.w}get _absBottom(){return this._localAnchor.y+this._margin.y}get _hasSplitAnchorsX(){return Math.abs(this._anchor.x-this._anchor.z)>.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<this._layers.length;s++){let i=this.system.app.scene.layers.getLayerById(this._layers[s]);if(i)for(let r=0;r<this._addedModels.length;r++)i.removeMeshInstances(this._addedModels[r].meshInstances)}if(this._layers=e,!(!this.enabled||!this.entity.enabled||!this._addedModels.length))for(let s=0;s<this._layers.length;s++){let i=this.system.app.scene.layers.getLayerById(this._layers[s]);if(i)for(let r=0;r<this._addedModels.length;r++)i.addMeshInstances(this._addedModels[r].meshInstances)}}get layers(){return this._layers}set left(e){this._margin.x=e;let s=this.entity.getLocalPosition(),i=this._absRight,r=this._localAnchor.x+e;this._setWidth(i-r),s.x=e+this._calculatedWidth*this._pivot.x,this.entity.setLocalPosition(s)}get left(){return this._margin.x}set margin(e){this._margin.copy(e),this._calculateSize(!0,!0),this.fire("set:margin",this._margin)}get margin(){return this._margin}get maskedBy(){return this._maskedBy}set pivot(e){let{pivot:s,margin:i}=this,r=s.x,a=s.y;e instanceof B?s.copy(e):s.set(...e);let o=i.x+i.z,l=s.x-r;i.x+=o*l,i.z-=o*l;let h=i.y+i.w,f=s.y-a;i.y+=h*f,i.w-=h*f,this._anchorDirty=!0,this._cornersDirty=!0,this._worldCornersDirty=!0,this._calculateSize(!1,!1),this._flagChildrenAsDirty(),this.fire("set:pivot",s)}get pivot(){return this._pivot}set right(e){this._margin.z=e;let s=this.entity.getLocalPosition(),i=this._absLeft,r=this._localAnchor.z-e;this._setWidth(r-i),s.x=this._localAnchor.z-this._localAnchor.x-e-this._calculatedWidth*(1-this._pivot.x),this.entity.setLocalPosition(s)}get right(){return this._margin.z}get screenCorners(){if(!this._cornersDirty||!this.screen)return this._screenCorners;let e=this.entity.parent&&this.entity.parent.element&&this.entity.parent.element.screenCorners[0];this._screenCorners[0].set(this._absLeft,this._absBottom,0),this._screenCorners[1].set(this._absRight,this._absBottom,0),this._screenCorners[2].set(this._absRight,this._absTop,0),this._screenCorners[3].set(this._absLeft,this._absTop,0);let s=this.screen.screen.screenSpace;for(let i=0;i<4;i++)this._screenTransform.transformPoint(this._screenCorners[i],this._screenCorners[i]),s&&this._screenCorners[i].mulScalar(this.screen.screen.scale),e&&this._screenCorners[i].add(e);return this._cornersDirty=!1,this._canvasCornersDirty=!0,this._worldCornersDirty=!0,this._screenCorners}get textWidth(){return this._text?this._text.width:0}get textHeight(){return this._text?this._text.height:0}set top(e){this._margin.w=e;let s=this.entity.getLocalPosition(),i=this._absBottom,r=this._localAnchor.w-e;this._setHeight(r-i),s.y=this._localAnchor.w-this._localAnchor.y-e-this._calculatedHeight*(1-this._pivot.y),this.entity.setLocalPosition(s)}get top(){return this._margin.w}set type(e){e!==this._type&&(this._type=e,this._image&&(this._image.destroy(),this._image=null),this._text&&(this._text.destroy(),this._text=null),e===Dm?this._image=new Nm(this):e===kS&&(this._text=new Um(this)))}get type(){return this._type}set useInput(e){this._useInput!==e&&(this._useInput=e,this.system.app.elementInput?e?this.enabled&&this.entity.enabled&&this.system.app.elementInput.addElement(this):this.system.app.elementInput.removeElement(this):this._useInput,this.fire("set:useInput",e))}get useInput(){return this._useInput}set fitMode(e){this._fitMode=e,this._calculateSize(!0,!0),this._image&&this._image.refreshMesh()}get fitMode(){return this._fitMode}set width(e){this._width=e,this._hasSplitAnchorsX||this._setCalculatedWidth(e,!0),this.fire("set:width",this._width)}get width(){return this._width}get worldCorners(){if(!this._worldCornersDirty)return this._worldCorners;if(this.screen){let e=this.screenCorners;if(!this.screen.screen.screenSpace){da.copy(this.screen.screen._screenMatrix),da.data[13]=-da.data[13],da.mul2(this.screen.getWorldTransform(),da);for(let s=0;s<4;s++)da.transformPoint(e[s],this._worldCorners[s])}}else{let e=this.entity.getLocalPosition();da.setTranslate(-e.x,-e.y,-e.z),F0.setTRS(x.ZERO,this.entity.getLocalRotation(),this.entity.getLocalScale()),N0.setTranslate(e.x,e.y,e.z);let s=this.entity.parent?this.entity.parent:this.entity;km.copy(s.getWorldTransform()),km.mul(N0).mul(F0).mul(da),vl.set(e.x-this.pivot.x*this.calculatedWidth,e.y-this.pivot.y*this.calculatedHeight,e.z),km.transformPoint(vl,this._worldCorners[0]),vl.set(e.x+(1-this.pivot.x)*this.calculatedWidth,e.y-this.pivot.y*this.calculatedHeight,e.z),km.transformPoint(vl,this._worldCorners[1]),vl.set(e.x+(1-this.pivot.x)*this.calculatedWidth,e.y+(1-this.pivot.y)*this.calculatedHeight,e.z),km.transformPoint(vl,this._worldCorners[2]),vl.set(e.x-this.pivot.x*this.calculatedWidth,e.y+(1-this.pivot.y)*this.calculatedHeight,e.z),km.transformPoint(vl,this._worldCorners[3])}return this._worldCornersDirty=!1,this._worldCorners}set fontSize(e){this._setValue("fontSize",e)}get fontSize(){return this._text?this._text.fontSize:null}set minFontSize(e){this._setValue("minFontSize",e)}get minFontSize(){return this._text?this._text.minFontSize:null}set maxFontSize(e){this._setValue("maxFontSize",e)}get maxFontSize(){return this._text?this._text.maxFontSize:null}set maxLines(e){this._setValue("maxLines",e)}get maxLines(){return this._text?this._text.maxLines:null}set autoFitWidth(e){this._setValue("autoFitWidth",e)}get autoFitWidth(){return this._text?this._text.autoFitWidth:null}set autoFitHeight(e){this._setValue("autoFitHeight",e)}get autoFitHeight(){return this._text?this._text.autoFitHeight:null}set color(e){this._setValue("color",e)}get color(){return this._text?this._text.color:this._image?this._image.color:null}set font(e){this._setValue("font",e)}get font(){return this._text?this._text.font:null}set fontAsset(e){this._setValue("fontAsset",e)}get fontAsset(){return this._text&&typeof this._text.fontAsset=="number"?this._text.fontAsset:null}set spacing(e){this._setValue("spacing",e)}get spacing(){return this._text?this._text.spacing:null}set lineHeight(e){this._setValue("lineHeight",e)}get lineHeight(){return this._text?this._text.lineHeight:null}set wrapLines(e){this._setValue("wrapLines",e)}get wrapLines(){return this._text?this._text.wrapLines:null}set lines(e){this._setValue("lines",e)}get lines(){return this._text?this._text.lines:null}set alignment(e){this._setValue("alignment",e)}get alignment(){return this._text?this._text.alignment:null}set autoWidth(e){this._setValue("autoWidth",e)}get autoWidth(){return this._text?this._text.autoWidth:null}set autoHeight(e){this._setValue("autoHeight",e)}get autoHeight(){return this._text?this._text.autoHeight:null}set rtlReorder(e){this._setValue("rtlReorder",e)}get rtlReorder(){return this._text?this._text.rtlReorder:null}set unicodeConverter(e){this._setValue("unicodeConverter",e)}get unicodeConverter(){return this._text?this._text.unicodeConverter:null}set text(e){this._setValue("text",e)}get text(){return this._text?this._text.text:null}set key(e){this._setValue("key",e)}get key(){return this._text?this._text.key:null}set texture(e){this._setValue("texture",e)}get texture(){return this._image?this._image.texture:null}set textureAsset(e){this._setValue("textureAsset",e)}get textureAsset(){return this._image?this._image.textureAsset:null}set material(e){this._setValue("material",e)}get material(){return this._image?this._image.material:null}set materialAsset(e){this._setValue("materialAsset",e)}get materialAsset(){return this._image?this._image.materialAsset:null}set sprite(e){this._setValue("sprite",e)}get sprite(){return this._image?this._image.sprite:null}set spriteAsset(e){this._setValue("spriteAsset",e)}get spriteAsset(){return this._image?this._image.spriteAsset:null}set spriteFrame(e){this._setValue("spriteFrame",e)}get spriteFrame(){return this._image?this._image.spriteFrame:null}set pixelsPerUnit(e){this._setValue("pixelsPerUnit",e)}get pixelsPerUnit(){return this._image?this._image.pixelsPerUnit:null}set opacity(e){this._setValue("opacity",e)}get opacity(){return this._text?this._text.opacity:this._image?this._image.opacity:null}set rect(e){this._setValue("rect",e)}get rect(){return this._image?this._image.rect:null}set mask(e){this._setValue("mask",e)}get mask(){return this._image?this._image.mask:null}set outlineColor(e){this._setValue("outlineColor",e)}get outlineColor(){return this._text?this._text.outlineColor:null}set outlineThickness(e){this._setValue("outlineThickness",e)}get outlineThickness(){return this._text?this._text.outlineThickness:null}set shadowColor(e){this._setValue("shadowColor",e)}get shadowColor(){return this._text?this._text.shadowColor:null}set shadowOffset(e){this._setValue("shadowOffset",e)}get shadowOffset(){return this._text?this._text.shadowOffset:null}set enableMarkup(e){this._setValue("enableMarkup",e)}get enableMarkup(){return this._text?this._text.enableMarkup:null}set rangeStart(e){this._setValue("rangeStart",e)}get rangeStart(){return this._text?this._text.rangeStart:null}set rangeEnd(e){this._setValue("rangeEnd",e)}get rangeEnd(){return this._text?this._text.rangeEnd:null}_setValue(e,s){this._text?(this._text[e]!==s&&this._dirtyBatch(),this._text[e]=s):this._image&&(this._image[e]!==s&&this._dirtyBatch(),this._image[e]=s)}_patch(){this.entity._sync=this._sync,this.entity.setPosition=this._setPosition,this.entity.setLocalPosition=this._setLocalPosition}_unpatch(){this.entity._sync=Ne.prototype._sync,this.entity.setPosition=Ne.prototype.setPosition,this.entity.setLocalPosition=Ne.prototype.setLocalPosition}_setPosition(e,s,i){if(!this.element.screen){Ne.prototype.setPosition.call(this,e,s,i);return}e instanceof x?gR.copy(e):gR.set(e,s,i),this.getWorldTransform(),RB.copy(this.element._screenToWorld).invert(),RB.transformPoint(gR,this.localPosition),this._dirtyLocal||this._dirtifyLocal()}_setLocalPosition(e,s,i){e instanceof x?this.localPosition.copy(e):this.localPosition.set(e,s,i);let r=this.element,a=this.localPosition,o=r._pivot;r._margin.x=a.x-r._calculatedWidth*o.x,r._margin.z=r._localAnchor.z-r._localAnchor.x-r._calculatedWidth-r._margin.x,r._margin.y=a.y-r._calculatedHeight*o.y,r._margin.w=r._localAnchor.w-r._localAnchor.y-r._calculatedHeight-r._margin.y,this._dirtyLocal||this._dirtifyLocal()}_sync(){let e=this.element,s=e.screen;if(s){if(e._anchorDirty){let i=0,r=0,a=0,o=1;if(this._parent&&this._parent.element)i=this._parent.element.calculatedWidth,r=this._parent.element.calculatedHeight,a=this._parent.element.pivot.x,o=this._parent.element.pivot.y;else{let l=s.screen.resolution;i=l.x/s.screen.scale,r=l.y/s.screen.scale}e._anchorTransform.setTranslate(i*(e.anchor.x-a),-(r*(o-e.anchor.y)),0),e._anchorDirty=!1,e._calculateLocalAnchors()}e._sizeDirty&&e._calculateSize(!1,!1)}if(this._dirtyLocal){this.localTransform.setTRS(this.localPosition,this.localRotation,this.localScale);let i=this.localPosition,r=e._pivot;e._margin.x=i.x-e._calculatedWidth*r.x,e._margin.z=e._localAnchor.z-e._localAnchor.x-e._calculatedWidth-e._margin.x,e._margin.y=i.y-e._calculatedHeight*r.y,e._margin.w=e._localAnchor.w-e._localAnchor.y-e._calculatedHeight-e._margin.y,this._dirtyLocal=!1}if(!s){this._dirtyWorld&&(e._cornersDirty=!0,e._canvasCornersDirty=!0,e._worldCornersDirty=!0),Ne.prototype._sync.call(this);return}if(this._dirtyWorld){if(this._parent===null)this.worldTransform.copy(this.localTransform);else if(this._parent.element?e._screenToWorld.mul2(this._parent.element._modelTransform,e._anchorTransform):e._screenToWorld.copy(e._anchorTransform),e._modelTransform.mul2(e._screenToWorld,this.localTransform),s){e._screenToWorld.mul2(s.screen._screenMatrix,e._screenToWorld),s.screen.screenSpace||e._screenToWorld.mul2(s.worldTransform,e._screenToWorld),this.worldTransform.mul2(e._screenToWorld,this.localTransform);let i=e._parentWorldTransform;i.setIdentity();let r=this._parent;r&&r.element&&r!==s&&(da.setTRS(x.ZERO,r.getLocalRotation(),r.getLocalScale()),i.mul2(r.element._parentWorldTransform,da));let a=vl;a.set(0,0,this.localPosition.z);let o=j8;o.set(e._absLeft+e._pivot.x*e.calculatedWidth,e._absBottom+e._pivot.y*e.calculatedHeight,0),da.setTranslate(-o.x,-o.y,-o.z),F0.setTRS(a,this.getLocalRotation(),this.getLocalScale()),N0.setTranslate(o.x,o.y,o.z),e._screenTransform.mul2(e._parentWorldTransform,N0).mul(F0).mul(da),e._cornersDirty=!0,e._canvasCornersDirty=!0,e._worldCornersDirty=!0}else this.worldTransform.copy(e._modelTransform);this._dirtyWorld=!1}}_onInsert(e){let s=this._parseUpToScreen();this.entity._dirtifyWorld(),this._updateScreen(s.screen),this._dirtifyMask()}_dirtifyMask(){let e=this.entity;for(;e;){let s=e.parent;if((s===null||s.screen)&&e.element){(!this.system._prerender||!this.system._prerender.length)&&(this.system._prerender=[],this.system.app.once("prerender",this._onPrerender,this));let i=this.system._prerender.indexOf(this.entity);i>=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<this.system._prerender.length;e++){let s=this.system._prerender[e];s.element&&s.element.syncMask(1)}this.system._prerender.length=0}_bindScreen(e){e._bindElement(this)}_unbindScreen(e){e._unbindElement(this)}_updateScreen(e){this.screen&&this.screen!==e&&this._unbindScreen(this.screen.screen);let s=this.screen;this.screen=e,this.screen&&this._bindScreen(this.screen.screen),this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY),this.fire("set:screen",this.screen,s),this._anchorDirty=!0;let i=this.entity.children;for(let r=0,a=i.length;r<a;r++)i[r].element&&i[r].element._updateScreen(e);this.screen&&this.screen.screen.syncDrawOrder()}syncMask(e){let s=this._parseUpToScreen();this._updateMask(s.mask,e)}_setMaskedBy(e){let s=this._image||this._text;if(e){let i=e.element._image._maskRef;s?._setStencil(new Ls({ref:i,func:2})),this._maskedBy=e}else s?._setStencil(null),this._maskedBy=null}_updateMask(e,s){if(e){if(this._setMaskedBy(e),this.mask){let r=e.element._image._maskRef,a=new Ls({ref:r,func:2,zpass:qC});this._image._setStencil(a),this._image._maskRef=s,s++,e=this.entity}let i=this.entity.children;for(let r=0,a=i.length;r<a;r++)i[r].element?._updateMask(e,s);this.mask&&s--}else{if(this._setMaskedBy(null),this.mask){let r=new Ls({ref:s,func:7,zpass:jC});this._image._setStencil(r),this._image._maskRef=s,s++,e=this.entity}let i=this.entity.children;for(let r=0,a=i.length;r<a;r++)i[r].element?._updateMask(e,s);this.mask&&s--}}_parseUpToScreen(){let e={screen:null,mask:null},s=this.entity._parent;for(;s&&!s.screen;)s.element&&s.element.mask&&(e.mask||(e.mask=s)),s=s.parent;return s&&s.screen&&(e.screen=s),e}_onScreenResize(e){this._anchorDirty=!0,this._cornersDirty=!0,this._worldCornersDirty=!0,this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY),this.fire("screen:set:resolution",e)}_onScreenSpaceChange(){this.fire("screen:set:screenspace",this.screen.screen.screenSpace)}_onScreenRemove(){this.screen&&(this.screen._destroying?this.screen=null:this._updateScreen(null))}_calculateLocalAnchors(){let e=1e3,s=1e3,i=this.entity._parent;if(i&&i.element)e=i.element.calculatedWidth,s=i.element.calculatedHeight;else if(this.screen){let r=this.screen.screen.resolution,a=this.screen.screen.scale;e=r.x/a,s=r.y/a}this._localAnchor.set(this._anchor.x*e,this._anchor.y*s,this._anchor.z*e,this._anchor.w*s)}getOffsetPosition(e,s){let i=this.entity.getLocalPosition().clone();return i.x+=e,i.y+=s,this._screenToWorld.transformPoint(i,i),i}onLayersChanged(e,s){this.addModelToLayers(this._image?this._image._renderable.model:this._text._model),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),s.on("add",this.onLayerAdded,this),s.on("remove",this.onLayerRemoved,this)}onLayerAdded(e){this.layers.indexOf(e.id)<0||(this._image?e.addMeshInstances(this._image._renderable.model.meshInstances):this._text&&e.addMeshInstances(this._text._model.meshInstances))}onLayerRemoved(e){this.layers.indexOf(e.id)<0||(this._image?e.removeMeshInstances(this._image._renderable.model.meshInstances):this._text&&e.removeMeshInstances(this._text._model.meshInstances))}onEnable(){let e=this.system.app.scene,s=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),s&&(this._evtLayerAdded=s.on("add",this.onLayerAdded,this),this._evtLayerRemoved=s.on("remove",this.onLayerRemoved,this)),this._batchGroupId>=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<i;s++)e[s].element&&(e[s].element._anchorDirty=!0,e[s].element._sizeDirty=!0)}addModelToLayers(e){this._addedModels.push(e);for(let s=0;s<this.layers.length;s++){let i=this.system.app.scene.layers.getLayerById(this.layers[s]);i&&i.addMeshInstances(e.meshInstances)}}removeModelFromLayers(e){let s=this._addedModels.indexOf(e);s>=0&&this._addedModels.splice(s,1);for(let i=0;i<this.layers.length;i++){let r=this.system.app.scene.layers.getLayerById(this.layers[i]);r&&r.removeMeshInstances(e.meshInstances)}}getMaskOffset(){let e=this.system.app.frame;this._offsetReadAt!==e&&(this._maskOffset=.5,this._offsetReadAt=e);let s=this._maskOffset;return this._maskOffset-=.001,s}isVisibleForCamera(e){let s,i,r,a;if(this.maskedBy){let d=this.maskedBy.element.screenCorners;s=Math.min(Math.min(d[0].x,d[1].x),Math.min(d[2].x,d[3].x)),i=Math.max(Math.max(d[0].x,d[1].x),Math.max(d[2].x,d[3].x)),a=Math.min(Math.min(d[0].y,d[1].y),Math.min(d[2].y,d[3].y)),r=Math.max(Math.max(d[0].y,d[1].y),Math.max(d[2].y,d[3].y))}else{let d=this.system.app.graphicsDevice.width,p=this.system.app.graphicsDevice.height,m=e._rect.z*d,_=e._rect.w*p;s=e._rect.x*d,i=s+m,r=(1-e._rect.y)*p,a=r-_}let o=this.screenCorners,l=Math.min(Math.min(o[0].x,o[1].x),Math.min(o[2].x,o[3].x)),h=Math.max(Math.max(o[0].x,o[1].x),Math.max(o[2].x,o[3].x)),f=Math.min(Math.min(o[0].y,o[1].y),Math.min(o[2].y,o[3].y)),u=Math.max(Math.max(o[0].y,o[1].y),Math.max(o[2].y,o[3].y));return!(h<s||l>i||f>r||u<a)}_isScreenSpace(){return this.screen&&this.screen.screen?this.screen.screen.screenSpace:!1}_isScreenCulled(){return this.screen&&this.screen.screen?this.screen.screen.cull:!1}_dirtyBatch(){this.batchGroupId!==-1&&this.system.app.batcher?.markGroupDirty(this.batchGroupId)}};n(zs,"EVENT_MOUSEDOWN","mousedown"),n(zs,"EVENT_MOUSEUP","mouseup"),n(zs,"EVENT_MOUSEENTER","mouseenter"),n(zs,"EVENT_MOUSELEAVE","mouseleave"),n(zs,"EVENT_MOUSEMOVE","mousemove"),n(zs,"EVENT_MOUSEWHEEL","mousewheel"),n(zs,"EVENT_CLICK","click"),n(zs,"EVENT_TOUCHSTART","touchstart"),n(zs,"EVENT_TOUCHEND","touchend"),n(zs,"EVENT_TOUCHMOVE","touchmove"),n(zs,"EVENT_TOUCHCANCEL","touchcancel");var B0=class{constructor(){n(this,"enabled",!0)}};var q8=["enabled"],zm=class extends Fe{constructor(t){super(t),this.id="element",this.ComponentType=zs,this.DataType=B0,this.schema=q8,this._unicodeConverter=null,this._rtlReorder=null,this._defaultTexture=new Z(t.graphicsDevice,{width:1,height:1,format:st,name:"element-system"});let e=this._defaultTexture.lock(),s=new Uint8Array(4);s[0]=255,s[1]=255,s[2]=255,s[3]=255,e.set(s),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)}destroy(){super.destroy(),this._defaultTexture.destroy()}initializeComponentData(t,e,s){t._beingInitialized=!0,e.anchor!==void 0&&(e.anchor instanceof Q?t.anchor.copy(e.anchor):t.anchor.set(e.anchor[0],e.anchor[1],e.anchor[2],e.anchor[3])),e.pivot!==void 0&&(e.pivot instanceof B?t.pivot.copy(e.pivot):t.pivot.set(e.pivot[0],e.pivot[1]));let i=Math.abs(t.anchor.x-t.anchor.z)>.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;N<b.length;++N){let k=b[N],z=k.anchor;(z.x!==0||z.y!==0||z.z!==0||z.w!==0)&&(k.anchor=Q.ZERO)}}function u(b){if(!t.wrap)return[b];let N=[[]],k=A(b),z=0,V=t[e.fitting]===2;for(let q=0;q<b.length;++q){N[N.length-1].length>0&&(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;z<b.length;++z)N&&b[z].reverse();return k&&b.reverse(),b}function p(b){let N=[];for(let k=0;k<b.length;++k){let z=b[k],V=A(z),q=S(V,e),re=_(t[e.fitting],q,br[e.axis]);re===Rr.APPLY_STRETCHING?g(V,q,e):re===Rr.APPLY_SHRINKING&&T(V,q,e),N.push(V)}return N}function m(b,N){let k=[],z=[];for(let re=0;re<b.length;++re){let te=b[re];te.largestElement=null,te.largestSize={width:Number.NEGATIVE_INFINITY,height:Number.NEGATIVE_INFINITY};for(let j=0;j<te.length;++j){let oe=N[re][j];oe[s.size]>te.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<b.length;++re){let te=b[re];for(let j=0;j<te.length;++j){let oe=N[re][j],be=oe[s.size],qe=b.length===1?br[s.axis]:te.largestSize[s.size],ot=_(t[s.fitting],be,qe);ot===Rr.APPLY_STRETCHING?oe[s.size]=Math.min(qe,oe[s.maxSize]):ot===Rr.APPLY_SHRINKING&&(oe[s.size]=Math.max(qe,oe[s.minSize]))}}return N}function _(b,N,k){switch(b){case 0:return Rr.NONE;case 1:return N<k?Rr.APPLY_STRETCHING:Rr.NONE;case 2:return N>=k?Rr.APPLY_SHRINKING:Rr.NONE;case 3:return N<k?Rr.APPLY_STRETCHING:Rr.APPLY_SHRINKING;default:throw new Error(`Unrecognized fitting mode: ${b}`)}}function S(b,N){let k=D(b,N.size),z=(b.length-1)*t.spacing[N.axis];return k+z}function g(b,N,k){let z=M(b,k.maxSize),V=O(b,k.fittingProportion),q=L(V,z),re=br[k.axis]-N;for(let te=0;te<b.length;++te){let j=z[te],oe=C(j,re,V,q),be=b[j][k.size]+oe,qe=b[j][k.maxSize],ot=Math.min(be,qe);b[j][k.size]=ot;let Ve=Math.max(be-ot,0),Lt=oe-Ve;re-=Lt}}function T(b,N,k){let z=M(b,k.minSize,!0),V=O(b,k.fittingProportion),q=G(V),re=L(q,z),te=N-br[k.axis];for(let j=0;j<b.length;++j){let oe=z[j],be=C(oe,te,q,re),qe=b[oe][k.size]-be,ot=b[oe][k.minSize],Ve=Math.max(qe,ot);b[oe][k.size]=Ve;let Lt=Math.max(Ve-qe,0),Vs=be-Lt;te-=Vs}}function C(b,N,k,z){let V=k[b],q=z[b];return Math.abs(V)<1e-5&&Math.abs(q)<1e-5?N:N*V/q}function v(b,N){let k={};k[e.axis]=0,k[s.axis]=0,b[e.size]=Number.NEGATIVE_INFINITY;let z=[];for(let V=0;V<b.length;++V){let q=b[V];if(q.length===0){z.push([]);continue}let re=[],te=N[V];for(let j=0;j<q.length;++j){let oe=q[j],be=te[j];k[s.axis]-=r(oe,be),k[e.axis]-=i(oe,be),re[j]={},re[j][e.axis]=k[e.axis],re[j][s.axis]=k[s.axis],k[s.axis]+=r(oe,be),k[e.axis]+=a(oe,be)+t.spacing[e.axis]}q[e.size]=k[e.axis]-t.spacing[e.axis],q[s.size]=q.largestSize[s.size],b[e.size]=Math.max(b[e.size],q[e.size]),k[e.axis]=0,k[s.axis]+=q[s.size]+t.spacing[s.axis],z.push(re)}return b[s.size]=k[s.axis]-t.spacing[s.axis],z}function E(b,N,k){let z=t.alignment[e.axis],V=t.alignment[s.axis],q=t.padding[e.axis],re=t.padding[s.axis];for(let te=0;te<b.length;++te){let j=b[te],oe=N[te],be=k[te],qe=(br[e.axis]-j[e.size])*z+q,ot=(br[s.axis]-b[s.size])*V+re;for(let Ve=0;Ve<j.length;++Ve){let Lt=(j[s.size]-oe[Ve][s.size])*t.alignment[s.axis];be[Ve][e.axis]+=qe,be[Ve][s.axis]+=ot+Lt}}}function y(b,N,k){for(let z=0;z<b.length;++z){let V=b[z],q=N[z],re=k[z];for(let te=0;te<V.length;++te){let j=V[te];j[e.calculatedSize]=q[te][e.size],j[s.calculatedSize]=q[te][s.size],t.orientation===Ge?j.entity.setLocalPosition(re[te][e.axis],re[te][s.axis],j.entity.getLocalPosition().z):j.entity.setLocalPosition(re[te][s.axis],re[te][e.axis],j.entity.getLocalPosition().z)}}}function P(b){let N=b.width,k=b.height,z=(br.x-N)*t.alignment.x+t.padding.x,V=(br.y-k)*t.alignment.y+t.padding.y;return{bounds:new Q(z,V,N,k)}}function A(b){let N=[];for(let k=0;k<b.length;++k){let z=b[k],V=Math.max(w(z,"minWidth"),0),q=Math.max(w(z,"minHeight"),0),re=Math.max(w(z,"maxWidth"),V),te=Math.max(w(z,"maxHeight"),q),j=I(w(z,"width"),V,re),oe=I(w(z,"height"),q,te),be=w(z,"fitWidthProportion"),qe=w(z,"fitHeightProportion");N.push({minWidth:V,minHeight:q,maxWidth:re,maxHeight:te,width:j,height:oe,fitWidthProportion:be,fitHeightProportion:qe})}return N}function w(b,N){let k=b.entity.layoutchild;return k&&k.enabled&&k[N]!==void 0&&k[N]!==null?k[N]:b[N]!==void 0?b[N]:eK[N]}function I(b,N,k){return Math.min(Math.max(b,N),k)}function D(b,N){return b.reduce((k,z)=>k+z[N],0)}function O(b,N){let k=D(b,N),z=[],V=b.length;if(k===0)for(let q=0;q<V;++q)z.push(1/V);else for(let q=0;q<V;++q)z.push(b[q][N]/k);return z}function G(b){if(b.length===1)return[1];let N=[],k=b.length;for(let z=0;z<k;++z)N.push((1-b[z])/(k-1));return N}function M(b,N,k){return b.forEach(H),b.slice().sort((z,V)=>k?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<e.length;++s)e[s].reflow();if(++t>=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<s.length;i++)s[i].setCustomAabb(this._customAabb)}}get customAabb(){return this._customAabb}set type(e){if(this._type!==e)if(this._area=null,this._type=e,e==="asset")this._asset!==null?this._bindModelAsset(this._asset):this.model=null;else{let s=V0(this.system.app.graphicsDevice,e);this._area=s.area;let i=s.mesh,r=new Pe,a=new Ei;a.graph=r,a.meshInstances=[new we(i,this._material,r)],this.model=a,this._asset=null}}get type(){return this._type}set asset(e){let s=this.system.app.assets,i=e;if(e instanceof ae&&(i=e.id),this._asset!==i){if(this._asset){s.off(`add:${this._asset}`,this._onModelAssetAdded,this);let r=s.get(this._asset);r&&this._unbindModelAsset(r)}if(this._asset=i,this._asset){let r=s.get(this._asset);r?this._bindModelAsset(r):(this.model=null,s.on(`add:${this._asset}`,this._onModelAssetAdded,this))}else this.model=null}}get asset(){return this._asset}set model(e){if(this._model!==e&&!(e&&e._immutable)&&(this._model&&(this._model._immutable=!1,this.removeModelFromLayers(),this._model.getGraph().destroy(),delete this._model._entity,this._clonedModel&&(this._model.destroy(),this._clonedModel=!1)),this._model=e,this._model)){this._model._immutable=!0;let s=this._model.meshInstances;for(let i=0;i<s.length;i++)s[i].castShadow=this._castShadows,s[i].receiveShadow=this._receiveShadows,s[i].setCustomAabb(this._customAabb);this.lightmapped=this._lightmapped,this.entity.addChild(this._model.graph),this.enabled&&this.entity.enabled&&this.addModelToLayers(),this._model._entity=this.entity,this.entity.animation&&this.entity.animation.setModel(this._model),this.entity.anim&&this.entity.anim.rebind(),this.type==="asset"?this.mapping=this._mapping:this._unsetMaterialEvents()}}get model(){return this._model}set lightmapped(e){if(e!==this._lightmapped&&(this._lightmapped=e,this._model)){let s=this._model.meshInstances;for(let i=0;i<s.length;i++)s[i].setLightmapped(e)}}get lightmapped(){return this._lightmapped}set castShadows(e){if(this._castShadows===e)return;let s=this._model;if(s){let i=this.layers,r=this.system.app.scene;if(this._castShadows&&!e)for(let o=0;o<i.length;o++){let l=this.system.app.scene.layers.getLayerById(this.layers[o]);l&&l.removeShadowCasters(s.meshInstances)}let a=s.meshInstances;for(let o=0;o<a.length;o++)a[o].castShadow=e;if(!this._castShadows&&e)for(let o=0;o<i.length;o++){let l=r.layers.getLayerById(i[o]);l&&l.addShadowCasters(s.meshInstances)}}this._castShadows=e}get castShadows(){return this._castShadows}set receiveShadows(e){if(this._receiveShadows!==e&&(this._receiveShadows=e,this._model)){let s=this._model.meshInstances;for(let i=0,r=s.length;i<r;i++)s[i].receiveShadow=e}}get receiveShadows(){return this._receiveShadows}set castShadowsLightmap(e){this._castShadowsLightmap=e}get castShadowsLightmap(){return this._castShadowsLightmap}set lightmapSizeMultiplier(e){this._lightmapSizeMultiplier=e}get lightmapSizeMultiplier(){return this._lightmapSizeMultiplier}set layers(e){let s=this.system.app.scene.layers;if(this.meshInstances)for(let i=0;i<this._layers.length;i++){let r=s.getLayerById(this._layers[i]);r&&r.removeMeshInstances(this.meshInstances)}this._layers.length=0;for(let i=0;i<e.length;i++)this._layers[i]=e[i];if(!(!this.enabled||!this.entity.enabled||!this.meshInstances))for(let i=0;i<this._layers.length;i++){let r=s.getLayerById(this._layers[i]);r&&r.addMeshInstances(this.meshInstances)}}get layers(){return this._layers}set batchGroupId(e){this._batchGroupId!==e&&(this.entity.enabled&&this._batchGroupId>=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<l;o++)if(e[o]!==void 0)e[o]?(a=this.system.app.assets.get(e[o]),this._loadAndSetMeshInstanceMaterial(a,s[o],o)):s[o].material=this.system.defaultMaterial;else if(r)if(r[o]&&(r[o].material||r[o].path)){if(r[o].material!==void 0)a=this.system.app.assets.get(r[o].material);else if(r[o].path!==void 0){let h=this._getMaterialAssetUrl(r[o].path);h&&(a=this.system.app.assets.getByUrl(h))}this._loadAndSetMeshInstanceMaterial(a,s[o],o)}else s[o].material=this.system.defaultMaterial}get mapping(){return this._mapping}addModelToLayers(){let e=this.system.app.scene.layers;for(let s=0;s<this._layers.length;s++){let i=e.getLayerById(this._layers[s]);i&&i.addMeshInstances(this.meshInstances)}}removeModelFromLayers(){let e=this.system.app.scene.layers;for(let s=0;s<this._layers.length;s++){let i=e.getLayerById(this._layers[s]);i&&i.removeMeshInstances(this.meshInstances)}}onRemoveChild(){this._model&&this.removeModelFromLayers()}onInsertChild(){this._model&&this.enabled&&this.entity.enabled&&this.addModelToLayers()}onRemove(){this.asset=null,this.model=null,this.materialAsset=null,this._unsetMaterialEvents(),this.entity.off("remove",this.onRemoveChild,this),this.entity.off("insert",this.onInsertChild,this)}onLayersChanged(e,s){this.addModelToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),s.on("add",this.onLayerAdded,this),s.on("remove",this.onLayerRemoved,this)}onLayerAdded(e){this.layers.indexOf(e.id)<0||e.addMeshInstances(this.meshInstances)}onLayerRemoved(e){this.layers.indexOf(e.id)<0||e.removeMeshInstances(this.meshInstances)}_setMaterialEvent(e,s,i,r){let a=`${s}:${i}`;this.system.app.assets.on(a,r,this),this._materialEvents||(this._materialEvents=[]),this._materialEvents[e]||(this._materialEvents[e]={}),this._materialEvents[e][a]={id:i,handler:r}}_unsetMaterialEvents(){let e=this.system.app.assets,s=this._materialEvents;if(s){for(let i=0,r=s.length;i<r;i++){if(!s[i])continue;let a=s[i];for(let o in a)e.off(o,a[o].handler,this)}this._materialEvents=null}}_getAssetByIdOrPath(e){let s=null;if(!isNaN(parseInt(e,10)))s=this.system.app.assets.get(e);else if(this.asset){let r=this._getMaterialAssetUrl(e);r&&(s=this.system.app.assets.getByUrl(r))}return s}_getMaterialAssetUrl(e){if(!this.asset)return null;let s=this.system.app.assets.get(this.asset);return s?s.getAbsoluteUrl(e):null}_loadAndSetMeshInstanceMaterial(e,s,i){let r=this.system.app.assets;e&&(e.resource?(s.material=e.resource,this._setMaterialEvent(i,"remove",e.id,function(){s.material=this.system.defaultMaterial})):(this._setMaterialEvent(i,"load",e.id,function(a){s.material=a.resource,this._setMaterialEvent(i,"remove",e.id,function(){s.material=this.system.defaultMaterial})}),this.enabled&&this.entity.enabled&&r.load(e)))}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));let r=this._type==="asset",a;if(this._model?this.addModelToLayers():r&&this._asset&&(a=e.assets.get(this._asset),a&&a.resource!==this._model&&this._bindModelAsset(a)),this._materialAsset&&(a=e.assets.get(this._materialAsset),a&&a.resource!==this._material&&this._bindMaterialAsset(a)),r&&this._mapping)for(let o in this._mapping)this._mapping[o]&&(a=this._getAssetByIdOrPath(this._mapping[o]),a&&!a.resource&&e.assets.load(a));this._batchGroupId>=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<i;s++)e[s].visible=!1}}show(){if(this._model){let e=this._model.meshInstances;for(let s=0,i=e.length;s<i;s++)e[s].visible=!0}}_bindMaterialAsset(e){if(e.on("load",this._onMaterialAssetLoad,this),e.on("unload",this._onMaterialAssetUnload,this),e.on("remove",this._onMaterialAssetRemove,this),e.on("change",this._onMaterialAssetChange,this),e.resource)this._onMaterialAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}}_unbindMaterialAsset(e){e.off("load",this._onMaterialAssetLoad,this),e.off("unload",this._onMaterialAssetUnload,this),e.off("remove",this._onMaterialAssetRemove,this),e.off("change",this._onMaterialAssetChange,this)}_onMaterialAssetAdd(e){this.system.app.assets.off(`add:${e.id}`,this._onMaterialAssetAdd,this),this._materialAsset===e.id&&this._bindMaterialAsset(e)}_onMaterialAssetLoad(e){this._setMaterial(e.resource)}_onMaterialAssetUnload(e){this._setMaterial(this.system.defaultMaterial)}_onMaterialAssetRemove(e){this._onMaterialAssetUnload(e)}_onMaterialAssetChange(e){}_bindModelAsset(e){if(this._unbindModelAsset(e),e.on("load",this._onModelAssetLoad,this),e.on("unload",this._onModelAssetUnload,this),e.on("change",this._onModelAssetChange,this),e.on("remove",this._onModelAssetRemove,this),e.resource)this._onModelAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}}_unbindModelAsset(e){e.off("load",this._onModelAssetLoad,this),e.off("unload",this._onModelAssetUnload,this),e.off("change",this._onModelAssetChange,this),e.off("remove",this._onModelAssetRemove,this)}_onModelAssetAdded(e){this.system.app.assets.off(`add:${e.id}`,this._onModelAssetAdded,this),e.id===this._asset&&this._bindModelAsset(e)}_onModelAssetLoad(e){this.model=e.resource.clone(),this._clonedModel=!0}_onModelAssetUnload(e){this.model=null}_onModelAssetChange(e,s,i,r){s==="data"&&(this.mapping=this._mapping)}_onModelAssetRemove(e){this.model=null}_setMaterial(e){if(this._material===e)return;this._material=e;let s=this._model;if(s&&this._type!=="asset"){let i=s.meshInstances;for(let r=0,a=i.length;r<a;r++)i[r].material=e}}};var H0=class{constructor(){n(this,"enabled",!0)}};var FB=["enabled"],Xm=class extends Fe{constructor(t){super(t),this.id="model",this.ComponentType=Tl,this.DataType=H0,this.schema=FB,this.defaultMaterial=ra(t.graphicsDevice),this.on("beforeremove",this.onRemove,this)}initializeComponentData(t,e,s){s=["material","materialAsset","asset","castShadows","receiveShadows","castShadowsLightmap","lightmapped","lightmapSizeMultiplier","type","mapping","layers","isStatic","batchGroupId"],(e.batchGroupId===null||e.batchGroupId===void 0)&&(e.batchGroupId=-1),e.layers&&e.layers.length&&(e.layers=e.layers.slice(0));for(let i=0;i<s.length;i++)e.hasOwnProperty(s[i])&&(t[s[i]]=e[s[i]]);e.aabbCenter&&e.aabbHalfExtents&&(t.customAabb=new ge(new x(e.aabbCenter),new x(e.aabbHalfExtents))),super.initializeComponentData(t,e,["enabled"])}cloneComponent(t,e){let s={type:t.model.type,asset:t.model.asset,castShadows:t.model.castShadows,receiveShadows:t.model.receiveShadows,castShadowsLightmap:t.model.castShadowsLightmap,lightmapped:t.model.lightmapped,lightmapSizeMultiplier:t.model.lightmapSizeMultiplier,isStatic:t.model.isStatic,enabled:t.model.enabled,layers:t.model.layers,batchGroupId:t.model.batchGroupId,mapping:Wl({},t.model.mapping)},i=t.model.materialAsset;!(i instanceof ae)&&i!=null&&(i=this.app.assets.get(i));let r=t.model.material;(!r||r===this.defaultMaterial||!i||r===i.resource)&&(s.materialAsset=i);let a=this.addComponent(e,s);if(t.model.model&&t.model.type==="asset"&&!t.model.asset&&(a.model=t.model.model.clone(),a._clonedModel=!0),s.materialAsset||(a.material=r),t.model.model){let o=t.model.model.meshInstances,l=a.model.meshInstances;for(let h=0;h<o.length;h++)l[h].mask=o[h].mask,l[h].material=o[h].material,l[h].layer=o[h].layer,l[h].receiveShadow=o[h].receiveShadow}return t.model.customAabb&&(a.customAabb=t.model.customAabb.clone()),a}onRemove(t,e){e.onRemove()}};le._buildAccessors(Tl.prototype,FB);var rK=["emitterExtents","emitterRadius","emitterExtentsInner","emitterRadiusInner","loop","initialVelocity","animSpeed","normalMap","particleNormal"],aK=["numParticles","lifetime","rate","rate2","startAngle","startAngle2","lighting","halfLambert","intensity","wrap","wrapBounds","depthWrite","noFog","sort","stretch","alignToMotion","preWarm","emitterShape","animTilesX","animTilesY","animStartFrame","animNumFrames","animNumAnimations","animIndex","randomizeAnimIndex","animLoop","colorMap","localSpace","screenSpace","orientation"],oK=["scaleGraph","scaleGraph2","colorGraph","colorGraph2","alphaGraph","alphaGraph2","velocityGraph","velocityGraph2","localVelocityGraph","localVelocityGraph2","rotationSpeedGraph","rotationSpeedGraph2","radialSpeedGraph","radialSpeedGraph2"],W0=["colorMapAsset","normalMapAsset","meshAsset","renderAsset"],Ym,Km=class extends le{constructor(e,s){super(e,s);n(this,"_requestedDepth",!1);n(this,"_drawOrder",0);n(this,"_evtLayersChanged",null);n(this,"_evtLayerAdded",null);n(this,"_evtLayerRemoved",null);n(this,"_evtSetMeshes",null);this.on("set_colorMapAsset",this.onSetColorMapAsset,this),this.on("set_normalMapAsset",this.onSetNormalMapAsset,this),this.on("set_meshAsset",this.onSetMeshAsset,this),this.on("set_mesh",this.onSetMesh,this),this.on("set_renderAsset",this.onSetRenderAsset,this),this.on("set_loop",this.onSetLoop,this),this.on("set_blendType",this.onSetBlendType,this),this.on("set_depthSoftening",this.onSetDepthSoftening,this),this.on("set_layers",this.onSetLayers,this),rK.forEach(i=>{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.layers.length;e++){let s=this.system.app.scene.layers.getLayerById(this.layers[e]);s&&(s.addMeshInstances([this.emitter.meshInstance]),this.emitter._layer=s)}}removeMeshInstanceFromLayers(){if(this.emitter)for(let e=0;e<this.layers.length;e++){let s=this.system.app.scene.layers.getLayerById(this.layers[e]);s&&s.removeMeshInstances([this.emitter.meshInstance])}}onSetLayers(e,s,i){if(this.emitter){for(let r=0;r<s.length;r++){let a=this.system.app.scene.layers.getLayerById(s[r]);a&&a.removeMeshInstances([this.emitter.meshInstance])}if(!(!this.enabled||!this.entity.enabled))for(let r=0;r<i.length;r++){let a=this.system.app.scene.layers.getLayerById(i[r]);a&&a.addMeshInstances([this.emitter.meshInstance])}}}onLayersChanged(e,s){this.addMeshInstanceToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),s.on("add",this.onLayerAdded,this),s.on("remove",this.onLayerRemoved,this)}onLayerAdded(e){!this.emitter||this.layers.indexOf(e.id)<0||e.addMeshInstances([this.emitter.meshInstance])}onLayerRemoved(e){!this.emitter||this.layers.indexOf(e.id)<0||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,s,i){let r=this.system.app.assets;if(s){let a=r.get(s);a&&this._unbindColorMapAsset(a)}if(i){i instanceof ae&&(this.data.colorMapAsset=i.id,i=i.id);let a=r.get(i);a?this._bindColorMapAsset(a):r.once(`add:${i}`,o=>{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<a;r++){let o=i[W0[r]];if(o){if(!(o instanceof ae))if(parseInt(o,10)>=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<W0.length;e++){let s=W0[e];this.data[s]&&(this[s]=null)}this.off()}reset(){this.emitter&&this.emitter.reset()}stop(){this.emitter&&(this.emitter.loop=!1,this.emitter.resetTime(),this.emitter.addTime(0,!0))}pause(){this.data.paused=!0}unpause(){this.data.paused=!1}play(){this.data.paused=!1,this.emitter&&(this.emitter.meshInstance.visible=!0,this.emitter.loop=this.data.loop,this.emitter.resetTime())}isPlaying(){return this.data.paused?!1:this.emitter&&this.emitter.loop?!0:Date.now()<=this.emitter.endTime}setInTools(){let{emitter:e}=this;e&&!e.inTools&&(e.inTools=!0,this.rebuild())}rebuild(){let e=this.enabled;this.enabled=!1,this.emitter&&this.emitter.rebuild(),this.enabled=e}};var X0=class{constructor(){n(this,"numParticles",1);n(this,"rate",1);n(this,"rate2",null);n(this,"startAngle",0);n(this,"startAngle2",null);n(this,"lifetime",50);n(this,"emitterExtents",new x);n(this,"emitterExtentsInner",new x);n(this,"emitterRadius",0);n(this,"emitterRadiusInner",0);n(this,"emitterShape",Ni);n(this,"initialVelocity",0);n(this,"wrap",!1);n(this,"wrapBounds",new x);n(this,"localSpace",!1);n(this,"screenSpace",!1);n(this,"colorMap",null);n(this,"colorMapAsset",null);n(this,"normalMap",null);n(this,"normalMapAsset",null);n(this,"loop",!0);n(this,"preWarm",!1);n(this,"sort",0);n(this,"mode",jg);n(this,"scene",null);n(this,"lighting",!1);n(this,"halfLambert",!1);n(this,"intensity",1);n(this,"stretch",0);n(this,"alignToMotion",!1);n(this,"depthSoftening",0);n(this,"renderAsset",null);n(this,"meshAsset",null);n(this,"mesh",null);n(this,"depthWrite",!1);n(this,"noFog",!1);n(this,"orientation",vc);n(this,"particleNormal",new x(0,1,0));n(this,"animTilesX",1);n(this,"animTilesY",1);n(this,"animStartFrame",0);n(this,"animNumFrames",1);n(this,"animNumAnimations",1);n(this,"animIndex",0);n(this,"randomizeAnimIndex",!1);n(this,"animSpeed",1);n(this,"animLoop",!0);n(this,"scaleGraph",null);n(this,"scaleGraph2",null);n(this,"colorGraph",null);n(this,"colorGraph2",null);n(this,"alphaGraph",null);n(this,"alphaGraph2",null);n(this,"localVelocityGraph",null);n(this,"localVelocityGraph2",null);n(this,"velocityGraph",null);n(this,"velocityGraph2",null);n(this,"rotationSpeedGraph",null);n(this,"rotationSpeedGraph2",null);n(this,"radialSpeedGraph",null);n(this,"radialSpeedGraph2",null);n(this,"blendType",ls);n(this,"enabled",!0);n(this,"paused",!1);n(this,"autoPlay",!0);n(this,"layers",[Os])}};var NB=`
varying vec4 texCoordsAlphaLife;
uniform sampler2D colorMap;
uniform sampler2D colorParam;
uniform float graphSampleSize;
uniform float graphNumSamples;
#ifndef CAMERAPLANES
#define CAMERAPLANES
uniform vec4 camera_params;
#endif
#ifdef SOFT
uniform float softening;
#endif
uniform float colorMult;
float saturate(float x) {
return clamp(x, 0.0, 1.0);
}
void main(void) {
vec4 tex = texture2D(colorMap, vec2(texCoordsAlphaLife.x, 1.0 - texCoordsAlphaLife.y));
vec4 ramp = texture2D(colorParam, vec2(texCoordsAlphaLife.w, 0.0));
ramp.rgb *= colorMult;
ramp.a += texCoordsAlphaLife.z;
vec3 rgb = tex.rgb * ramp.rgb;
float a = tex.a * ramp.a;
`;var BB=`
vec3 unpack3NFloats(float src) {
float r = fract(src);
float g = fract(src * 256.0);
float b = fract(src * 65536.0);
return vec3(r, g, b);
}
float saturate(float x) {
return clamp(x, 0.0, 1.0);
}
vec4 tex1Dlod_lerp(TEXTURE_ACCEPT_HIGHP(tex), vec2 tc) {
return mix( texture2D(tex,tc), texture2D(tex,tc + graphSampleSize), fract(tc.x*graphNumSamples) );
}
vec4 tex1Dlod_lerp(TEXTURE_ACCEPT_HIGHP(tex), vec2 tc, out vec3 w) {
vec4 a = texture2D(tex,tc);
vec4 b = texture2D(tex,tc + graphSampleSize);
float c = fract(tc.x*graphNumSamples);
vec3 unpackedA = unpack3NFloats(a.w);
vec3 unpackedB = unpack3NFloats(b.w);
w = mix(unpackedA, unpackedB, c);
return mix(a, b, c);
}
vec2 rotate(vec2 quadXY, float pRotation, out mat2 rotMatrix) {
float c = cos(pRotation);
float s = sin(pRotation);
mat2 m = mat2(c, -s, s, c);
rotMatrix = m;
return m * quadXY;
}
vec3 billboard(vec3 InstanceCoords, vec2 quadXY) {
#ifdef SCREEN_SPACE
vec3 pos = vec3(-1, 0, 0) * quadXY.x + vec3(0, -1, 0) * quadXY.y;
#else
vec3 pos = -matrix_viewInverse[0].xyz * quadXY.x + -matrix_viewInverse[1].xyz * quadXY.y;
#endif
return pos;
}
vec3 customFace(vec3 InstanceCoords, vec2 quadXY) {
vec3 pos = faceTangent * quadXY.x + faceBinorm * quadXY.y;
return pos;
}
vec2 safeNormalize(vec2 v) {
float l = length(v);
return (l > 1e-06) ? v / l : v;
}
void main(void) {
vec3 meshLocalPos = particle_vertexData.xyz;
float id = floor(particle_vertexData.w);
float rndFactor = fract(sin(id + 1.0 + seed));
vec3 rndFactor3 = vec3(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));
float uv = id / numParticlesPot;
readInput(uv);
#ifdef LOCAL_SPACE
inVel = mat3(matrix_model) * inVel;
#endif
vec2 velocityV = safeNormalize((mat3(matrix_view) * inVel).xy);
float particleLifetime = lifetime;
if (inLife <= 0.0 || inLife > particleLifetime || !inShow)
meshLocalPos = vec3(0.0);
vec2 quadXY = meshLocalPos.xy;
float nlife = clamp(inLife / particleLifetime, 0.0, 1.0);
vec3 paramDiv;
vec4 params = tex1Dlod_lerp(TEXTURE_PASS(internalTex2), vec2(nlife, 0), paramDiv);
float scale = params.y;
float scaleDiv = paramDiv.x;
float alphaDiv = paramDiv.z;
scale += (scaleDiv * 2.0 - 1.0) * scaleDivMult * fract(rndFactor*10000.0);
#ifndef USE_MESH
texCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife);
#else
texCoordsAlphaLife = vec4(particle_uv, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife);
#endif
vec3 particlePos = inPos;
vec3 particlePosMoved = vec3(0.0);
mat2 rotMatrix;
`;var UB=`
float animFrame = min(floor(texCoordsAlphaLife.w * animTexParams.y) + animTexParams.x, animTexParams.z);
`;var kB=`
float animFrame = floor(mod(texCoordsAlphaLife.w * animTexParams.y + animTexParams.x, animTexParams.z + 1.0));
`;var zB=`
float animationIndex;
if (animTexIndexParams.y == 1.0) {
animationIndex = floor((animTexParams.w + 1.0) * rndFactor3.z) * (animTexParams.z + 1.0);
} else {
animationIndex = animTexIndexParams.x * (animTexParams.z + 1.0);
}
float atlasX = (animationIndex + animFrame) * animTexTilesParams.x;
float atlasY = 1.0 - floor(atlasX + 1.0) * animTexTilesParams.y;
atlasX = fract(atlasX);
texCoordsAlphaLife.xy *= animTexTilesParams.xy;
texCoordsAlphaLife.xy += vec2(atlasX, atlasY);
`;var GB=`
void readInput(float uv) {
vec4 tex = texture2D(particleTexIN, vec2(uv, 0.25));
vec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.75));
inPos = tex.xyz;
inVel = tex2.xyz;
inAngle = (tex.w < 0.0? -tex.w : tex.w) - 1000.0;
inShow = tex.w >= 0.0;
inLife = tex2.w;
}
`;var VB=`
#define PI2 6.283185307179586
uniform vec3 inBoundsSize;
uniform vec3 inBoundsCenter;
uniform float maxVel;
float decodeFloatRG(vec2 rg) {
return rg.y * (1.0 / 255.0) + rg.x;
}
float decodeFloatRGBA( vec4 rgba ) {
return dot(rgba, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));
}
void readInput(float uv) {
vec4 tex0 = texture2D(particleTexIN, vec2(uv, 0.125));
vec4 tex1 = texture2D(particleTexIN, vec2(uv, 0.375));
vec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.625));
vec4 tex3 = texture2D(particleTexIN, vec2(uv, 0.875));
inPos = vec3(decodeFloatRG(tex0.rg), decodeFloatRG(tex0.ba), decodeFloatRG(tex1.rg));
inPos = (inPos - vec3(0.5)) * inBoundsSize + inBoundsCenter;
inVel = tex2.xyz;
inVel = (inVel - vec3(0.5)) * maxVel;
inAngle = decodeFloatRG(tex1.ba) * PI2;
inShow = tex2.a > 0.5;
inLife = decodeFloatRGBA(tex3);
float maxNegLife = max(lifetime, numParticles * (rate+rateDiv));
float maxPosLife = lifetime+1.0;
inLife = inLife * (maxNegLife + maxPosLife) - maxNegLife;
}
`;var HB=`
void writeOutput() {
if (gl_FragCoord.y<1.0) {
gl_FragColor = vec4(outPos, (outAngle + 1000.0) * visMode);
} else {
gl_FragColor = vec4(outVel, outLife);
}
}
`;var WB=`
uniform vec3 outBoundsMul;
uniform vec3 outBoundsAdd;
vec2 encodeFloatRG( float v ) {
vec2 enc = vec2(1.0, 255.0) * v;
enc = fract(enc);
enc -= enc.yy * vec2(1.0/255.0, 1.0/255.0);
return enc;
}
vec4 encodeFloatRGBA( float v ) {
vec4 enc = vec4(1.0, 255.0, 65025.0, 160581375.0) * v;
enc = fract(enc);
enc -= enc.yzww * vec4(1.0/255.0,1.0/255.0,1.0/255.0,0.0);
return enc;
}
void writeOutput() {
outPos = outPos * outBoundsMul + outBoundsAdd;
outAngle = fract(outAngle / PI2);
outVel = (outVel / maxVel) + vec3(0.5);
float maxNegLife = max(lifetime, numParticles * (rate+rateDiv));
float maxPosLife = lifetime+1.0;
outLife = (outLife + maxNegLife) / (maxNegLife + maxPosLife);
if (gl_FragCoord.y < 1.0) {
gl_FragColor = vec4(encodeFloatRG(outPos.x), encodeFloatRG(outPos.y));
} else if (gl_FragCoord.y < 2.0) {
gl_FragColor = vec4(encodeFloatRG(outPos.z), encodeFloatRG(outAngle));
} else if (gl_FragCoord.y < 3.0) {
gl_FragColor = vec4(outVel, visMode*0.5+0.5);
} else {
gl_FragColor = encodeFloatRGBA(outLife);
}
}
`;var XB=`
uniform mat3 spawnBounds;
uniform vec3 spawnPosInnerRatio;
vec3 calcSpawnPosition(vec3 inBounds, float rndFactor) {
vec3 pos = inBounds - vec3(0.5);
vec3 posAbs = abs(pos);
vec3 maxPos = vec3(max(posAbs.x, max(posAbs.y, posAbs.z)));
vec3 edge = maxPos + (vec3(0.5) - maxPos) * spawnPosInnerRatio;
pos.x = edge.x * (maxPos.x == posAbs.x ? sign(pos.x) : 2.0 * pos.x);
pos.y = edge.y * (maxPos.y == posAbs.y ? sign(pos.y) : 2.0 * pos.y);
pos.z = edge.z * (maxPos.z == posAbs.z ? sign(pos.z) : 2.0 * pos.z);
#ifndef LOCAL_SPACE
return emitterPos + spawnBounds * pos;
#else
return spawnBounds * pos;
#endif
}
void addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) {
localVelocity -= vec3(0, 0, initialVelocity);
}
`;var YB=`
writeOutput();
}
`;var KB=`
varying vec2 vUv0;
uniform highp sampler2D particleTexIN;
uniform highp sampler2D internalTex0;
uniform highp sampler2D internalTex1;
uniform highp sampler2D internalTex2;
uniform highp sampler2D internalTex3;
uniform mat3 emitterMatrix;
uniform mat3 emitterMatrixInv;
uniform vec3 emitterScale;
uniform vec3 emitterPos;
uniform vec3 frameRandom;
uniform vec3 localVelocityDivMult;
uniform vec3 velocityDivMult;
uniform float delta;
uniform float rate;
uniform float rateDiv;
uniform float lifetime;
uniform float numParticles;
uniform float rotSpeedDivMult;
uniform float radialSpeedDivMult;
uniform float seed;
uniform float startAngle;
uniform float startAngle2;
uniform float initialVelocity;
uniform float graphSampleSize;
uniform float graphNumSamples;
vec3 inPos;
vec3 inVel;
float inAngle;
bool inShow;
float inLife;
float visMode;
vec3 outPos;
vec3 outVel;
float outAngle;
bool outShow;
float outLife;
`;var jB=`
if (outLife >= lifetime) {
outLife -= max(lifetime, numParticles * particleRate);
visMode = -1.0;
}
`;var qB=`
visMode = outLife < 0.0? -1.0: visMode;
`;var $B=`
if (outLife >= lifetime) {
outLife -= max(lifetime, numParticles * particleRate);
visMode = 1.0;
}
visMode = outLife < 0.0? 1.0: visMode;
`;var ZB=`
uniform float spawnBoundsSphere;
uniform float spawnBoundsSphereInnerRatio;
vec3 calcSpawnPosition(vec3 inBounds, float rndFactor) {
float rnd4 = fract(rndFactor * 1000.0);
vec3 norm = normalize(inBounds.xyz - vec3(0.5));
float r = rnd4 * (1.0 - spawnBoundsSphereInnerRatio) + spawnBoundsSphereInnerRatio;
#ifndef LOCAL_SPACE
return emitterPos + norm * r * spawnBoundsSphere;
#else
return norm * r * spawnBoundsSphere;
#endif
}
void addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) {
localVelocity += normalize(inBounds - vec3(0.5)) * initialVelocity;
}
`;var QB=`
float saturate(float x) {
return clamp(x, 0.0, 1.0);
}
vec3 unpack3NFloats(float src) {
float r = fract(src);
float g = fract(src * 256.0);
float b = fract(src * 65536.0);
return vec3(r, g, b);
}
vec3 tex1Dlod_lerp(TEXTURE_ACCEPT_HIGHP(tex), vec2 tc, out vec3 w) {
vec4 a = texture2D(tex, tc);
vec4 b = texture2D(tex, tc + graphSampleSize);
float c = fract(tc.x * graphNumSamples);
vec3 unpackedA = unpack3NFloats(a.w);
vec3 unpackedB = unpack3NFloats(b.w);
w = mix(unpackedA, unpackedB, c);
return mix(a.xyz, b.xyz, c);
}
#define HASHSCALE4 vec4(1031, .1030, .0973, .1099)
vec4 hash41(float p) {
vec4 p4 = fract(vec4(p) * HASHSCALE4);
p4 += dot(p4, p4.wzxy+19.19);
return fract(vec4((p4.x + p4.y)*p4.z, (p4.x + p4.z)*p4.y, (p4.y + p4.z)*p4.w, (p4.z + p4.w)*p4.x));
}
void main(void) {
if (gl_FragCoord.x > numParticles) discard;
readInput(vUv0.x);
visMode = inShow? 1.0 : -1.0;
vec4 rndFactor = hash41(gl_FragCoord.x + seed);
float particleRate = rate + rateDiv * rndFactor.x;
outLife = inLife + delta;
float nlife = clamp(outLife / lifetime, 0.0, 1.0);
vec3 localVelocityDiv;
vec3 velocityDiv;
vec3 paramDiv;
vec3 localVelocity = tex1Dlod_lerp(TEXTURE_PASS(internalTex0), vec2(nlife, 0), localVelocityDiv);
vec3 velocity = tex1Dlod_lerp(TEXTURE_PASS(internalTex1), vec2(nlife, 0), velocityDiv);
vec3 params = tex1Dlod_lerp(TEXTURE_PASS(internalTex2), vec2(nlife, 0), paramDiv);
float rotSpeed = params.x;
float rotSpeedDiv = paramDiv.y;
vec3 radialParams = tex1Dlod_lerp(TEXTURE_PASS(internalTex3), vec2(nlife, 0), paramDiv);
float radialSpeed = radialParams.x;
float radialSpeedDiv = radialParams.y;
bool respawn = inLife <= 0.0 || outLife >= lifetime;
inPos = respawn ? calcSpawnPosition(rndFactor.xyz, rndFactor.x) : inPos;
inAngle = respawn ? mix(startAngle, startAngle2, rndFactor.x) : inAngle;
#ifndef LOCAL_SPACE
vec3 radialVel = inPos - emitterPos;
#else
vec3 radialVel = inPos;
#endif
radialVel = (dot(radialVel, radialVel) > 1.0E-8) ? radialSpeed * normalize(radialVel) : vec3(0.0);
radialVel += (radialSpeedDiv * vec3(2.0) - vec3(1.0)) * radialSpeedDivMult * rndFactor.xyz;
localVelocity += (localVelocityDiv * vec3(2.0) - vec3(1.0)) * localVelocityDivMult * rndFactor.xyz;
velocity += (velocityDiv * vec3(2.0) - vec3(1.0)) * velocityDivMult * rndFactor.xyz;
rotSpeed += (rotSpeedDiv * 2.0 - 1.0) * rotSpeedDivMult * rndFactor.y;
addInitialVelocity(localVelocity, rndFactor.xyz);
#ifndef LOCAL_SPACE
outVel = emitterMatrix * localVelocity + (radialVel + velocity) * emitterScale;
#else
outVel = (localVelocity + radialVel) / emitterScale + emitterMatrixInv * velocity;
#endif
outPos = inPos + outVel * delta;
outAngle = inAngle + rotSpeed * delta;
`;var JB=`
quadXY = rotate(quadXY, inAngle, rotMatrix);
vec3 localPos = billboard(particlePos, quadXY);
`;var eU=`
dBlendModeFogFactor = 0.0;
rgb *= saturate(gammaCorrectInput(max(a, 0.0)));
if ((rgb.r + rgb.g + rgb.b) < 0.000001) discard;
`;var tU=`
rgb = mix(vec3(1.0), rgb, vec3(a));
if (rgb.r + rgb.g + rgb.b > 2.99) discard;
`;var sU=`
if (a < 0.01) discard;
`;var iU=`
attribute vec4 particle_vertexData;
attribute vec4 particle_vertexData2;
attribute vec4 particle_vertexData3;
attribute float particle_vertexData4;
#ifndef USE_MESH
attribute vec2 particle_vertexData5;
#else
attribute vec4 particle_vertexData5;
#endif
uniform mat4 matrix_viewProjection;
uniform mat4 matrix_model;
#ifndef VIEWMATRIX
#define VIEWMATRIX
uniform mat4 matrix_view;
#endif
uniform mat3 matrix_normal;
uniform mat4 matrix_viewInverse;
uniform float numParticles;
uniform float lifetime;
uniform float stretch;
uniform float seed;
uniform vec3 emitterScale;
uniform vec3 faceTangent;
uniform vec3 faceBinorm;
#ifdef PARTICLE_GPU
#ifdef WRAP
uniform vec3 wrapBounds;
#endif
#endif
#ifdef PARTICLE_GPU
uniform highp sampler2D internalTex0;
uniform highp sampler2D internalTex1;
uniform highp sampler2D internalTex2;
#endif
uniform vec3 emitterPos;
varying vec4 texCoordsAlphaLife;
vec2 rotate(vec2 quadXY, float pRotation, out mat2 rotMatrix)
{
float c = cos(pRotation);
float s = sin(pRotation);
mat2 m = mat2(c, -s, s, c);
rotMatrix = m;
return m * quadXY;
}
vec3 billboard(vec3 InstanceCoords, vec2 quadXY)
{
#ifdef SCREEN_SPACE
vec3 pos = vec3(-1, 0, 0) * quadXY.x + vec3(0, -1, 0) * quadXY.y;
#else
vec3 pos = -matrix_viewInverse[0].xyz * quadXY.x + -matrix_viewInverse[1].xyz * quadXY.y;
#endif
return pos;
}
vec3 customFace(vec3 InstanceCoords, vec2 quadXY)
{
vec3 pos = faceTangent * quadXY.x + faceBinorm * quadXY.y;
return pos;
}
void main(void)
{
vec3 particlePos = particle_vertexData.xyz;
vec3 inPos = particlePos;
vec3 vertPos = particle_vertexData3.xyz;
vec3 inVel = vec3(particle_vertexData2.w, particle_vertexData3.w, particle_vertexData5.x);
float id = floor(particle_vertexData4);
float rndFactor = fract(sin(id + 1.0 + seed));
vec3 rndFactor3 = vec3(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));
#ifdef LOCAL_SPACE
inVel = mat3(matrix_model) * inVel;
#endif
vec2 velocityV = normalize((mat3(matrix_view) * inVel).xy);
vec2 quadXY = vertPos.xy;
#ifdef USE_MESH
texCoordsAlphaLife = vec4(particle_vertexData5.zw, particle_vertexData2.z, particle_vertexData.w);
#else
texCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, particle_vertexData2.z, particle_vertexData.w);
#endif
mat2 rotMatrix;
float inAngle = particle_vertexData2.x;
vec3 particlePosMoved = vec3(0.0);
vec3 meshLocalPos = particle_vertexData3.xyz;
`;var rU=`
localPos *= particle_vertexData2.y * emitterScale;
localPos += particlePos;
#ifdef SCREEN_SPACE
gl_Position = vec4(localPos.x, localPos.y, 0.0, 1.0);
#else
gl_Position = matrix_viewProjection * vec4(localPos, 1.0);
#endif
`;var aU=`
quadXY = rotate(quadXY, inAngle, rotMatrix);
vec3 localPos = customFace(particlePos, quadXY);
`;var oU=`
rgb = addFog(rgb);
rgb = toneMap(rgb);
rgb = gammaCorrectOutput(rgb);
gl_FragColor = vec4(rgb, a);
}
`;var nU=`
localPos *= scale * emitterScale;
localPos += particlePos;
#ifdef SCREEN_SPACE
gl_Position = vec4(localPos.x, localPos.y, 0.0, 1.0);
#else
gl_Position = matrix_viewProjection * vec4(localPos.xyz, 1.0);
#endif
`;var lU=`
vec3 negNormal = normal * 0.5 + 0.5;
vec3 posNormal = -normal * 0.5 + 0.5;
negNormal *= negNormal;
posNormal *= posNormal;
`;var cU=`
attribute vec4 particle_vertexData;
#if defined(USE_MESH)
#if defined(USE_MESH_UV)
attribute vec2 particle_uv;
#else
vec2 particle_uv = vec2(0.0, 0.0);
#endif
#endif
uniform mat4 matrix_viewProjection;
uniform mat4 matrix_model;
uniform mat3 matrix_normal;
uniform mat4 matrix_viewInverse;
#ifndef VIEWMATRIX
#define VIEWMATRIX
uniform mat4 matrix_view;
#endif
uniform float numParticles;
uniform float numParticlesPot;
uniform float graphSampleSize;
uniform float graphNumSamples;
uniform float stretch;
uniform vec3 emitterScale;
uniform vec3 emitterPos;
uniform vec3 faceTangent;
uniform vec3 faceBinorm;
uniform float rate;
uniform float rateDiv;
uniform float lifetime;
uniform float scaleDivMult;
uniform float alphaDivMult;
uniform float seed;
uniform float delta;
uniform sampler2D particleTexOUT;
uniform sampler2D particleTexIN;
#ifdef PARTICLE_GPU
#ifdef WRAP
uniform vec3 wrapBounds;
#endif
#endif
#ifdef PARTICLE_GPU
uniform highp sampler2D internalTex0;
uniform highp sampler2D internalTex1;
uniform highp sampler2D internalTex2;
#endif
#ifndef CAMERAPLANES
#define CAMERAPLANES
uniform vec4 camera_params;
#endif
varying vec4 texCoordsAlphaLife;
vec3 inPos;
vec3 inVel;
float inAngle;
bool inShow;
float inLife;
`;var hU=`
vec3 negNormal = max(normal, vec3(0.0));
vec3 posNormal = max(-normal, vec3(0.0));
`;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;
`;var uU=`
particlePos = (matrix_model * vec4(particlePos, 1.0)).xyz;
`;var dU=`
vec3 localPos = meshLocalPos;
localPos.xy = rotate(localPos.xy, inAngle, rotMatrix);
localPos.yz = rotate(localPos.yz, inAngle, rotMatrix);
billboard(particlePos, quadXY);
`;var pU=`
Normal = normalize(localPos + matrix_viewInverse[2].xyz);
`;var mU=`
vec3 normalMap = normalize(texture2D(normalMap, vec2(texCoordsAlphaLife.x, 1.0 - texCoordsAlphaLife.y)).xyz * 2.0 - 1.0);
vec3 normal = ParticleMat * normalMap;
`;var _U=`
inAngle = atan(velocityV.x, velocityV.y);
`;var gU=`
#include "particleUpdaterInitPS"
#ifdef PACK8
#include "particleInputRgba8PS"
#include "particleOutputRgba8PS"
#else
#include "particleInputFloatPS"
#include "particleOutputFloatPS"
#endif
#ifdef EMITTERSHAPE_BOX
#include "particleUpdaterAABBPS"
#else
#include "particleUpdaterSpherePS"
#endif
#include "particleUpdaterStartPS"
#ifdef RESPAWN
#include "particleUpdaterRespawnPS"
#endif
#ifdef NO_RESPAWN
#include "particleUpdaterNoRespawnPS"
#endif
#ifdef ON_STOP
#include "particleUpdaterOnStopPS"
#endif
#include "particleUpdaterEndPS"
`;var SU=`
#if NORMAL != NONE
#if NORMAL == VERTEX
varying vec3 Normal;
#endif
#if NORMAL == MAP
varying mat3 ParticleMat;
#endif
uniform vec3 lightCube[6];
#endif
#ifdef SOFT
varying float vDepth;
#include "screenDepthPS"
#endif
#include "gammaPS"
#include "tonemappingPS"
#include "fogPS"
#if NORMAL == MAP
uniform sampler2D normalMap;
#endif
#include "particlePS"
#ifdef SOFT
#include "particle_softPS"
#endif
#if NORMAL == VERTEX
vec3 normal = Normal;
#endif
#if NORMAL == MAP
#include "particle_normalMapPS"
#endif
#if NORMAL != NONE
#ifdef HALF_LAMBERT
#include "particle_halflambertPS"
#else
#include "particle_lambertPS"
#endif
#include "particle_lightingPS"
#endif
#if BLEND == NORMAL
#include "particle_blendNormalPS"
#elif BLEND == ADDITIVE
#include "particle_blendAddPS"
#elif BLEND == MULTIPLICATIVE
#include "particle_blendMultiplyPS"
#endif
#include "particle_endPS"
`;var xU=`
#ifdef ANIMTEX
uniform vec2 animTexTilesParams;
uniform vec4 animTexParams;
uniform vec2 animTexIndexParams;
#endif
#if NORMAL == MAP
varying mat3 ParticleMat;
#endif
#if NORMAL == VERTEX
varying vec3 Normal;
#endif
#ifdef SOFT
varying float vDepth;
#endif
#ifdef PARTICLE_GPU
#include "particle_initVS"
#ifdef PACK8
#include "particleInputRgba8PS"
#else
#include "particleInputFloatPS"
#endif
#ifdef SOFT
#include "screenDepthPS"
#endif
#include "particleVS"
#else
#ifdef SOFT
#include "screenDepthPS"
#endif
#include "particle_cpuVS"
#endif
#ifdef LOCAL_SPACE
#include "particle_localShiftVS"
#endif
#ifdef ANIMTEX
#ifdef ANIMTEX_LOOP
#include "particleAnimFrameLoopVS"
#else
#include "particleAnimFrameClampVS"
#endif
#include "particleAnimTexVS"
#endif
#ifdef PARTICLE_GPU
#ifdef WRAP
#include "particle_wrapVS"
#endif
#endif
#ifdef ALIGN_TO_MOTION
#include "particle_pointAlongVS"
#endif
#ifdef USE_MESH
#include "particle_meshVS"
#else
#ifdef CUSTOM_FACE
#include "particle_customFaceVS"
#else
#include "particle_billboardVS"
#endif
#endif
#if NORMAL == VERTEX
#include "particle_normalVS"
#endif
#if NORMAL == MAP
#include "particle_TBNVS"
#endif
#ifdef STRETCH
#include "particle_stretchVS"
#endif
#ifdef PARTICLE_GPU
#include "particle_endVS"
#else
#include "particle_cpu_endVS"
#endif
#ifdef SOFT
#include "particle_softVS"
#endif
}
`;var vU=`
float depth = getLinearScreenDepth();
float particleDepth = vDepth;
float depthDiff = saturate(abs(particleDepth - depth) * softening);
a *= depthDiff;
`;var TU=`
vDepth = getLinearDepth(localPos);
`;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);
`;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;
`;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;
`;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<f32>;
var colorMapSampler: sampler;
var colorParam: texture_2d<f32>;
var colorParamSampler: sampler;
uniform graphSampleSize: f32;
uniform graphNumSamples: f32;
#ifndef CAMERAPLANES
#define CAMERAPLANES
uniform camera_params: vec4f;
#endif
#ifdef SOFT
uniform softening: f32;
#endif
uniform colorMult: f32;
fn saturate(x: f32) -> f32 {
return clamp(x, 0.0, 1.0);
}
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let tex: vec4f = textureSample(colorMap, colorMapSampler, vec2f(input.texCoordsAlphaLife.x, 1.0 - input.texCoordsAlphaLife.y));
var ramp: vec4f = textureSample(colorParam, colorParamSampler, vec2f(input.texCoordsAlphaLife.w, 0.0));
ramp = vec4f(ramp.rgb * uniform.colorMult, ramp.a);
ramp.a = ramp.a + input.texCoordsAlphaLife.z;
var rgb: vec3f = tex.rgb * ramp.rgb;
var a: f32 = tex.a * ramp.a;
`;var wU=`
fn unpack3NFloats(src: f32) -> vec3f {
let r = fract(src);
let g = fract(src * 256.0);
let b = fract(src * 65536.0);
return vec3f(r, g, b);
}
fn saturate(x: f32) -> f32 {
return clamp(x, 0.0, 1.0);
}
struct TexLerpUnpackResult {
result: vec4f,
unpacked: vec3f
}
fn tex1Dlod_lerp_simple(tex: texture_2d<f32>, textureSize: vec2u, tc: vec2f) -> vec4f {
let tc_next = tc + vec2f(uniform.graphSampleSize);
let texelA: vec2i = vec2i(tc * vec2f(textureSize));
let texelB: vec2i = vec2i(tc_next * vec2f(textureSize));
return mix( textureLoad(tex, texelA, 0), textureLoad(tex, texelB, 0), fract(tc.x * uniform.graphNumSamples) );
}
fn tex1Dlod_lerp_unpack(tex: texture_2d<f32>, textureSize: vec2u, tc: vec2f) -> TexLerpUnpackResult {
let tc_next = tc + vec2f(uniform.graphSampleSize);
let texelA: vec2i = vec2i(tc * vec2f(textureSize));
let texelB: vec2i = vec2i(tc_next * vec2f(textureSize));
let a = textureLoad(tex, texelA, 0);
let b = textureLoad(tex, texelB, 0);
let c = fract(tc.x * uniform.graphNumSamples);
let unpackedA = unpack3NFloats(a.w);
let unpackedB = unpack3NFloats(b.w);
let w_out = mix(unpackedA, unpackedB, c);
return TexLerpUnpackResult(mix(a, b, c), w_out);
}
struct RotateResult {
rotatedVec: vec2f,
matrix: mat2x2f
}
fn rotateWithMatrix(quadXY: vec2f, pRotation: f32) -> RotateResult {
let c = cos(pRotation);
let s = sin(pRotation);
let m = mat2x2f(vec2f(c, -s), vec2f(s, c));
return RotateResult(m * quadXY, m);
}
fn billboard(InstanceCoords: vec3f, quadXY: vec2f) -> vec3f {
var pos: vec3f;
#ifdef SCREEN_SPACE
pos = vec3f(-1.0, 0.0, 0.0) * quadXY.x + vec3f(0.0, -1.0, 0.0) * quadXY.y;
#else
pos = -uniform.matrix_viewInverse[0].xyz * quadXY.x + -uniform.matrix_viewInverse[1].xyz * quadXY.y;
#endif
return pos;
}
fn customFace(InstanceCoords: vec3f, quadXY: vec2f) -> vec3f {
let pos = uniform.faceTangent * quadXY.x + uniform.faceBinorm * quadXY.y;
return pos;
}
fn safeNormalize(v: vec2f) -> vec2f {
let l = length(v);
return select(v, v / l, l > 1e-06);
}
@vertex
fn vertexMain(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
let meshLocalPos_in = input.particle_vertexData.xyz;
let id = floor(input.particle_vertexData.w);
let rndFactor = fract(sin(id + 1.0 + uniform.seed));
let rndFactor3 = vec3f(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));
let uv = id / uniform.numParticlesPot;
readInput(uv);
#ifdef LOCAL_SPACE
let modelRotation = mat3x3f(uniform.matrix_model[0].xyz, uniform.matrix_model[1].xyz, uniform.matrix_model[2].xyz);
inVel = modelRotation * inVel;
#endif
let viewRotation = mat3x3f(uniform.matrix_view[0].xyz, uniform.matrix_view[1].xyz, uniform.matrix_view[2].xyz);
let velocityV = safeNormalize((viewRotation * inVel).xy);
let particleLifetime = uniform.lifetime;
var meshLocalPos = meshLocalPos_in;
if (inLife <= 0.0 || inLife > particleLifetime || !inShow) {
meshLocalPos = vec3f(0.0);
}
let quadXY = meshLocalPos.xy;
let nlife = clamp(inLife / particleLifetime, 0.0, 1.0);
let internalTexSize = textureDimensions(internalTex2, 0);
let lerp_result = tex1Dlod_lerp_unpack(internalTex2, internalTexSize, vec2f(nlife, 0.0));
let params = lerp_result.result;
let paramDiv = lerp_result.unpacked;
var scale = params.y;
let scaleDiv = paramDiv.x;
let alphaDiv = paramDiv.z;
scale = scale + (scaleDiv * 2.0 - 1.0) * uniform.scaleDivMult * fract(rndFactor*10000.0);
#ifndef USE_MESH
output.texCoordsAlphaLife = vec4f(quadXY * -0.5 + 0.5, (alphaDiv * 2.0 - 1.0) * uniform.alphaDivMult * fract(rndFactor*1000.0), nlife);
#else
output.texCoordsAlphaLife = vec4f(particle_uv, (alphaDiv * 2.0 - 1.0) * uniform.alphaDivMult * fract(rndFactor*1000.0), nlife);
#endif
var particlePos = inPos;
var particlePosMoved = vec3f(0.0);
var rotMatrix: mat2x2f;
`;var IU=`
let animFrame: f32 = min(floor(input.texCoordsAlphaLife.w * uniform.animTexParams.y) + uniform.animTexParams.x, uniform.animTexParams.z);
`;var RU=`
let animFrame: f32 = floor((output.texCoordsAlphaLife.w * uniform.animTexParams.y + uniform.animTexParams.x) % (uniform.animTexParams.z + 1.0));
`;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);
} else {
animationIndex = uniform.animTexIndexParams.x * (uniform.animTexParams.z + 1.0);
}
var atlasX: f32 = (animationIndex + animFrame) * uniform.animTexTilesParams.x;
let atlasY: f32 = 1.0 - floor(atlasX + 1.0) * uniform.animTexTilesParams.y;
atlasX = fract(atlasX);
let current_tcal_xy = output.texCoordsAlphaLife.xy;
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);
`;var DU=`
fn readInput(uv: f32) {
let textureSize = textureDimensions(particleTexIN, 0);
let texel0: vec2i = vec2i(vec2f(uv, 0.25) * vec2f(textureSize));
let texel1: vec2i = vec2i(vec2f(uv, 0.75) * vec2f(textureSize));
let tex: vec4f = textureLoad(particleTexIN, texel0, 0);
let tex2: vec4f = textureLoad(particleTexIN, texel1, 0);
inPos = tex.xyz;
inVel = tex2.xyz;
inAngle = abs(tex.w) - 1000.0;
inShow = tex.w >= 0.0;
inLife = tex2.w;
}
`;var LU=`
const PI2: f32 = 6.283185307179586;
uniform inBoundsSize: vec3f;
uniform inBoundsCenter: vec3f;
uniform maxVel: f32;
fn decodeFloatRG(rg: vec2f) -> f32 {
return rg.y * (1.0 / 255.0) + rg.x;
}
fn decodeFloatRGBA( rgba: vec4f ) -> f32 {
return dot(rgba, vec4f(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0));
}
fn readInput(uv: f32) {
let textureSize = textureDimensions(particleTexIN, 0);
let texel0: vec2i = vec2i(vec2f(uv, 0.125) * vec2f(textureSize));
let texel1: vec2i = vec2i(vec2f(uv, 0.375) * vec2f(textureSize));
let texel2: vec2i = vec2i(vec2f(uv, 0.625) * vec2f(textureSize));
let texel3: vec2i = vec2i(vec2f(uv, 0.875) * vec2f(textureSize));
let tex0 = textureLoad(particleTexIN, texel0, 0);
let tex1 = textureLoad(particleTexIN, texel1, 0);
let tex2 = textureLoad(particleTexIN, texel2, 0);
let tex3 = textureLoad(particleTexIN, texel3, 0);
inPos = vec3f(decodeFloatRG(tex0.rg), decodeFloatRG(tex0.ba), decodeFloatRG(tex1.rg));
inPos = (inPos - vec3f(0.5)) * uniform.inBoundsSize + uniform.inBoundsCenter;
inVel = tex2.xyz;
inVel = (inVel - vec3f(0.5)) * uniform.maxVel;
inAngle = decodeFloatRG(tex1.ba) * PI2;
inShow = tex2.a > 0.5;
let life_decoded = decodeFloatRGBA(tex3);
let maxNegLife = max(uniform.lifetime, uniform.numParticles * (uniform.rate + uniform.rateDiv));
let maxPosLife = uniform.lifetime + 1.0;
inLife = life_decoded * (maxNegLife + maxPosLife) - maxNegLife;
}`;var MU=`
fn getOutput() -> vec4f {
if (pcPosition.y < 1.0) {
return vec4f(outPos, (outAngle + 1000.0) * visMode);
} else {
return vec4f(outVel, outLife);
}
}
`;var OU=`
uniform outBoundsMul: vec3f;
uniform outBoundsAdd: vec3f;
fn encodeFloatRG( v: f32 ) -> vec2f {
var enc: vec2f = vec2f(1.0, 255.0) * v;
enc = fract(enc);
enc = enc - enc.yy * (1.0 / 255.0);
return enc;
}
fn encodeFloatRGBA( v: f32 ) -> vec4f {
let factors = vec4f(1.0, 255.0, 65025.0, 160581375.0);
var enc: vec4f = factors * v;
enc = fract(enc);
enc = enc - enc.yzww * vec4f(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);
return enc;
}
fn getOutput() -> vec4f {
outPos = outPos * uniform.outBoundsMul + uniform.outBoundsAdd;
outAngle = fract(outAngle / PI2);
outVel = (outVel / uniform.maxVel) + vec3f(0.5);
let maxNegLife = max(uniform.lifetime, uniform.numParticles * (uniform.rate + uniform.rateDiv));
let maxPosLife = uniform.lifetime + 1.0;
outLife = (outLife + maxNegLife) / (maxNegLife + maxPosLife);
if (pcPosition.y < 1.0) {
return vec4f(encodeFloatRG(outPos.x), encodeFloatRG(outPos.y));
} else if (pcPosition.y < 2.0) {
return vec4f(encodeFloatRG(outPos.z), encodeFloatRG(outAngle));
} else if (pcPosition.y < 3.0) {
return vec4f(outVel, visMode * 0.5 + 0.5);
} else {
return encodeFloatRGBA(outLife);
}
}
`;var FU=`
uniform spawnBounds: mat3x3f;
uniform spawnPosInnerRatio: vec3f;
fn calcSpawnPosition(inBounds: vec3f, rndFactor: f32) -> vec3f {
var pos = inBounds - vec3f(0.5);
let posAbs = abs(pos);
let maxComp = max(posAbs.x, max(posAbs.y, posAbs.z));
let maxPos = vec3f(maxComp);
let edge = maxPos + (vec3f(0.5) - maxPos) * uniform.spawnPosInnerRatio;
pos.x = edge.x * select(2.0 * pos.x, sign(pos.x), maxPos.x == posAbs.x);
pos.y = edge.y * select(2.0 * pos.y, sign(pos.y), maxPos.y == posAbs.y);
pos.z = edge.z * select(2.0 * pos.z, sign(pos.z), maxPos.z == posAbs.z);
#ifndef LOCAL_SPACE
return uniform.emitterPos + uniform.spawnBounds * pos;
#else
return uniform.spawnBounds * pos;
#endif
}
fn addInitialVelocity(localVelocity: ptr<function, vec3f>, inBounds: vec3f) {
*localVelocity = *localVelocity - vec3f(0.0, 0.0, uniform.initialVelocity);
}
`;var NU=`
output.color = getOutput();
return output;
}
`;var BU=`
varying vUv0: vec2f;
var particleTexIN: texture_2d<uff>;
var internalTex0: texture_2d<uff>;
var internalTex1: texture_2d<uff>;
var internalTex2: texture_2d<uff>;
var internalTex3: texture_2d<uff>;
uniform emitterMatrix: mat3x3f;
uniform emitterMatrixInv: mat3x3f;
uniform emitterScale: vec3f;
uniform emitterPos: vec3f;
uniform frameRandom: vec3f;
uniform localVelocityDivMult: vec3f;
uniform velocityDivMult: vec3f;
uniform delta: f32;
uniform rate: f32;
uniform rateDiv: f32;
uniform lifetime: f32;
uniform numParticles: f32;
uniform rotSpeedDivMult: f32;
uniform radialSpeedDivMult: f32;
uniform seed: f32;
uniform startAngle: f32;
uniform startAngle2: f32;
uniform initialVelocity: f32;
uniform graphSampleSize: f32;
uniform graphNumSamples: f32;
var<private> inPos: vec3f;
var<private> inVel: vec3f;
var<private> inAngle: f32;
var<private> inShow: bool;
var<private> inLife: f32;
var<private> visMode: f32;
var<private> outPos: vec3f;
var<private> outVel: vec3f;
var<private> outAngle: f32;
var<private> outShow: bool;
var<private> outLife: f32;
`;var UU=`
if (outLife >= uniform.lifetime) {
outLife = outLife - max(uniform.lifetime, uniform.numParticles * particleRate);
visMode = -1.0;
}
`;var kU=`
visMode = select(visMode, -1.0, outLife < 0.0);
`;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);
`;var GU=`
uniform spawnBoundsSphere: f32;
uniform spawnBoundsSphereInnerRatio: f32;
fn calcSpawnPosition(inBounds: vec3f, rndFactor: f32) -> vec3f {
let rnd4: f32 = fract(rndFactor * 1000.0);
let norm: vec3f = normalize(inBounds.xyz - vec3f(0.5));
let r: f32 = rnd4 * (1.0 - uniform.spawnBoundsSphereInnerRatio) + uniform.spawnBoundsSphereInnerRatio;
#ifndef LOCAL_SPACE
return uniform.emitterPos + norm * r * uniform.spawnBoundsSphere;
#else
return norm * r * uniform.spawnBoundsSphere;
#endif
}
fn addInitialVelocity(localVelocity: ptr<function, vec3f>, inBounds: vec3f) {
let initialVelOffset: vec3f = normalize(inBounds - vec3f(0.5)) * uniform.initialVelocity;
*localVelocity = *localVelocity + initialVelOffset;
}
`;var VU=`
fn saturate(x: f32) -> f32 {
return clamp(x, 0.0, 1.0);
}
fn unpack3NFloats(src: f32) -> vec3f {
let r = fract(src);
let g = fract(src * 256.0);
let b = fract(src * 65536.0);
return vec3f(r, g, b);
}
struct TexLerpUnpackResult {
result: vec3f,
unpacked: vec3f
}
fn tex1Dlod_lerp(tex: texture_2d<f32>, textureSize: vec2u, tc: vec2f) -> TexLerpUnpackResult {
let tc_next = tc + vec2f(uniform.graphSampleSize);
let texelA: vec2i = vec2i(tc * vec2f(textureSize));
let texelB: vec2i = vec2i(tc_next * vec2f(textureSize));
let a = textureLoad(tex, texelA, 0);
let b = textureLoad(tex, texelB, 0);
let c = fract(tc.x * uniform.graphNumSamples);
let unpackedA = unpack3NFloats(a.w);
let unpackedB = unpack3NFloats(b.w);
let w_out = mix(unpackedA, unpackedB, c);
return TexLerpUnpackResult(mix(a.xyz, b.xyz, c), w_out);
}
const HASHSCALE4: vec4f = vec4f(1031.0, 0.1030, 0.0973, 0.1099);
fn hash41(p: f32) -> vec4f {
var p4 = fract(vec4f(p) * HASHSCALE4);
p4 = p4 + dot(p4, p4.wzxy + 19.19);
return fract(vec4f((p4.x + p4.y)*p4.z, (p4.x + p4.z)*p4.y, (p4.y + p4.z)*p4.w, (p4.z + p4.w)*p4.x));
}
@fragment
fn fragmentMain(input : FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
if (pcPosition.x > uniform.numParticles) {
discard;
return output;
}
readInput(input.vUv0.x);
visMode = select(-1.0, 1.0, inShow);
let rndFactor = hash41(pcPosition.x + uniform.seed);
let particleRate = uniform.rate + uniform.rateDiv * rndFactor.x;
outLife = inLife + uniform.delta;
let nlife = clamp(outLife / uniform.lifetime, 0.0, 1.0);
let internalTexSize = textureDimensions(internalTex0, 0);
let lerpResult0 = tex1Dlod_lerp(internalTex0, internalTexSize, vec2f(nlife, 0.0));
var localVelocity = lerpResult0.result;
let localVelocityDiv = lerpResult0.unpacked;
let lerpResult1 = tex1Dlod_lerp(internalTex1, internalTexSize, vec2f(nlife, 0.0));
var velocity = lerpResult1.result;
let velocityDiv = lerpResult1.unpacked;
let lerpResult2 = tex1Dlod_lerp(internalTex2, internalTexSize, vec2f(nlife, 0.0));
let params = lerpResult2.result;
let paramDiv = lerpResult2.unpacked;
var rotSpeed = params.x;
let rotSpeedDiv = paramDiv.y;
let lerpResult3 = tex1Dlod_lerp(internalTex3, internalTexSize, vec2f(nlife, 0.0));
let radialParams = lerpResult3.result;
let radialParamDiv = lerpResult3.unpacked;
let radialSpeed = radialParams.x;
let radialSpeedDiv = radialParamDiv.y;
let respawn = inLife <= 0.0 || outLife >= uniform.lifetime;
inPos = select(inPos, calcSpawnPosition(rndFactor.xyz, rndFactor.x), respawn);
inAngle = select(inAngle, mix(uniform.startAngle, uniform.startAngle2, rndFactor.x), respawn);
#ifndef LOCAL_SPACE
var radialVel: vec3f = inPos - uniform.emitterPos;
#else
var radialVel: vec3f = inPos;
#endif
radialVel = select(vec3f(0.0), radialSpeed * normalize(radialVel), dot(radialVel, radialVel) > 1.0E-8);
radialVel = radialVel + (radialSpeedDiv * vec3f(2.0) - vec3f(1.0)) * uniform.radialSpeedDivMult * rndFactor.xyz;
localVelocity = localVelocity + (localVelocityDiv * vec3f(2.0) - vec3f(1.0)) * uniform.localVelocityDivMult * rndFactor.xyz;
velocity = velocity + (velocityDiv * vec3f(2.0) - vec3f(1.0)) * uniform.velocityDivMult * rndFactor.xyz;
rotSpeed = rotSpeed + (rotSpeedDiv * 2.0 - 1.0) * uniform.rotSpeedDivMult * rndFactor.y;
addInitialVelocity(&localVelocity, rndFactor.xyz);
#ifndef LOCAL_SPACE
outVel = uniform.emitterMatrix * localVelocity + (radialVel + velocity) * uniform.emitterScale;
#else
outVel = (localVelocity + radialVel) / uniform.emitterScale + uniform.emitterMatrixInv * velocity;
#endif
outPos = inPos + outVel * uniform.delta;
outAngle = inAngle + rotSpeed * uniform.delta;
`;var HU=`
let rotationResult = rotateWithMatrix(quadXY, inAngle);
let rotatedQuadXY = rotationResult.rotatedVec;
rotMatrix = rotationResult.matrix;
var localPos = billboard(particlePos, rotatedQuadXY);
`;var WU=`
dBlendModeFogFactor = 0.0;
rgb = rgb * saturate(gammaCorrectInput(max(a, 0.0)));
if ((rgb.r + rgb.g + rgb.b) < 0.000001) {
discard;
}
`;var XU=`
rgb = mix(vec3f(1.0), rgb, a);
if ((rgb.r + rgb.g + rgb.b) > 2.99) {
discard;
}
`;var YU=`
if (a < 0.01) {
discard;
}
`;var KU=`
attribute particle_vertexData: vec4f;
attribute particle_vertexData2: vec4f;
attribute particle_vertexData3: vec4f;
attribute particle_vertexData4: f32;
#ifndef USE_MESH
attribute particle_vertexData5: vec2f;
#else
attribute particle_vertexData5: vec4f;
#endif
uniform matrix_viewProjection: mat4x4f;
uniform matrix_model: mat4x4f;
#ifndef VIEWMATRIX
#define VIEWMATRIX
uniform matrix_view: mat4x4f;
#endif
uniform matrix_normal: mat3x3f;
uniform matrix_viewInverse: mat4x4f;
uniform numParticles: f32;
uniform lifetime: f32;
uniform stretch: f32;
uniform seed: f32;
uniform emitterScale: vec3f;
uniform faceTangent: vec3f;
uniform faceBinorm: vec3f;
#ifdef PARTICLE_GPU
#ifdef WRAP
uniform wrapBounds: vec3f;
#endif
#endif
#ifdef PARTICLE_GPU
var internalTex0: texture_2d<uff>;
var internalTex1: texture_2d<uff>;
var internalTex2: texture_2d<uff>;
#endif
uniform emitterPos: vec3f;
varying texCoordsAlphaLife: vec4f;
struct RotateResult {
rotatedVec: vec2f,
matrix: mat2x2f
}
fn rotateWithMatrix(quadXY: vec2f, pRotation: f32) -> RotateResult {
let c = cos(pRotation);
let s = sin(pRotation);
let m = mat2x2f(vec2f(c, -s), vec2f(s, c));
return RotateResult(m * quadXY, m);
}
fn billboard(InstanceCoords: vec3f, quadXY: vec2f) -> vec3f {
var pos: vec3f;
#ifdef SCREEN_SPACE
pos = vec3f(-1.0, 0.0, 0.0) * quadXY.x + vec3f(0.0, -1.0, 0.0) * quadXY.y;
#else
pos = -uniform.matrix_viewInverse[0].xyz * quadXY.x + -uniform.matrix_viewInverse[1].xyz * quadXY.y;
#endif
return pos;
}
fn customFace(InstanceCoords: vec3f, quadXY: vec2f) -> vec3f {
let pos = uniform.faceTangent * quadXY.x + uniform.faceBinorm * quadXY.y;
return pos;
}
fn safeNormalize(v: vec2f) -> vec2f {
let l = length(v);
return select(v, v / l, l > 1e-06);
}
@vertex
fn vertexMain(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
var particlePos = input.particle_vertexData.xyz;
let inPos = particlePos;
let vertPos = input.particle_vertexData3.xyz;
var inVel = vec3f(input.particle_vertexData2.w, input.particle_vertexData3.w, input.particle_vertexData5.x);
let id = floor(input.particle_vertexData4);
let rndFactor = fract(sin(id + 1.0 + uniform.seed));
let rndFactor3 = vec3f(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0));
#ifdef LOCAL_SPACE
let modelRotation = mat3x3f(uniform.matrix_model[0].xyz, uniform.matrix_model[1].xyz, uniform.matrix_model[2].xyz);
inVel = modelRotation * inVel;
#endif
let velocityV = safeNormalize((mat3x3f(uniform.matrix_view[0].xyz, uniform.matrix_view[1].xyz, uniform.matrix_view[2].xyz) * inVel).xy);
let quadXY = vertPos.xy;
#ifdef USE_MESH
output.texCoordsAlphaLife = vec4f(input.particle_vertexData5.zw, input.particle_vertexData2.z, input.particle_vertexData.w);
#else
output.texCoordsAlphaLife = vec4f(quadXY * -0.5 + 0.5, input.particle_vertexData2.z, input.particle_vertexData.w);
#endif
var rotMatrix: mat2x2f;
var inAngle = input.particle_vertexData2.x;
var particlePosMoved = vec3f(0.0);
let meshLocalPos = input.particle_vertexData3.xyz;
`;var jU=`
localPos = localPos * input.particle_vertexData2.y * uniform.emitterScale;
localPos = localPos + particlePos;
#ifdef SCREEN_SPACE
output.position = vec4f(localPos.x, localPos.y, 0.0, 1.0);
#else
output.position = uniform.matrix_viewProjection * vec4f(localPos, 1.0);
#endif
`;var qU=`
let rotationResult = rotateWithMatrix(quadXY, inAngle);
let rotatedQuadXY = rotationResult.rotatedVec;
rotMatrix = rotationResult.matrix;
var localPos = customFace(particlePos, rotatedQuadXY);
`;var $U=`
rgb = addFog(rgb);
rgb = toneMap(rgb);
rgb = gammaCorrectOutput(rgb);
output.color = vec4f(rgb, a);
return output;
}
`;var ZU=`
localPos = localPos * scale * uniform.emitterScale;
localPos = localPos + particlePos;
#ifdef SCREEN_SPACE
output.position = vec4f(localPos.x, localPos.y, 0.0, 1.0);
#else
output.position = uniform.matrix_viewProjection * vec4f(localPos.xyz, 1.0);
#endif
`;var QU=`
var negNormal: vec3f = normal * 0.5 + 0.5;
var posNormal: vec3f = -normal * 0.5 + 0.5;
negNormal = negNormal * negNormal;
posNormal = posNormal * posNormal;
`;var JU=`
attribute particle_vertexData: vec4f;
#if defined(USE_MESH)
#if defined(USE_MESH_UV)
attribute particle_uv: vec2f;
#else
var<private> particle_uv: vec2f = vec2f(0.0, 0.0);
#endif
#endif
uniform matrix_viewProjection: mat4x4f;
uniform matrix_model: mat4x4f;
uniform matrix_normal: mat3x3f;
uniform matrix_viewInverse: mat4x4f;
#ifndef VIEWMATRIX
#define VIEWMATRIX
uniform matrix_view: mat4x4f;
#endif
uniform numParticles: f32;
uniform numParticlesPot: f32;
uniform graphSampleSize: f32;
uniform graphNumSamples: f32;
uniform stretch: f32;
uniform emitterScale: vec3f;
uniform emitterPos: vec3f;
uniform faceTangent: vec3f;
uniform faceBinorm: vec3f;
uniform rate: f32;
uniform rateDiv: f32;
uniform lifetime: f32;
uniform scaleDivMult: f32;
uniform alphaDivMult: f32;
uniform seed: f32;
uniform delta: f32;
#ifdef PARTICLE_GPU
#ifdef WRAP
uniform wrapBounds: vec3f;
#endif
#endif
var particleTexOUT: texture_2d<uff>;
var particleTexIN: texture_2d<uff>;
#ifdef PARTICLE_GPU
var internalTex0: texture_2d<uff>;
var internalTex1: texture_2d<uff>;
var internalTex2: texture_2d<uff>;
#endif
#ifndef CAMERAPLANES
#define CAMERAPLANES
uniform camera_params: vec4f;
#endif
varying texCoordsAlphaLife: vec4f;
var<private> inPos: vec3f;
var<private> inVel: vec3f;
var<private> inAngle: f32;
var<private> inShow: bool;
var<private> inLife: f32;
`;var ek=`
var negNormal: vec3f = max(normal, vec3(0.0));
var posNormal: vec3f = max(-normal, vec3(0.0));
`;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;
`;var sk=`
particlePos = (uniform.matrix_model * vec4f(particlePos, 1.0)).xyz;
`;var ik=`
var localPos = meshLocalPos;
let rotResultXY = rotateWithMatrix(localPos.xy, inAngle);
localPos = vec3f(rotResultXY.rotatedVec, localPos.z);
rotMatrix = rotResultXY.matrix;
let rotResultYZ = rotateWithMatrix(localPos.yz, inAngle);
localPos = vec3f(localPos.x, rotResultYZ.rotatedVec);
rotMatrix = rotResultYZ.matrix;
billboard(particlePos, quadXY);
`;var rk=`
output.Normal = normalize(localPos + uniform.matrix_viewInverse[2].xyz);
`;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<f32>(ParticleMat0, ParticleMat1, ParticleMat2);
let normal: vec3f = ParticleMat * normalMap;
`;var ok=`
inAngle = atan2(velocityV.x, velocityV.y);
`;var nk=`
#include "particleUpdaterInitPS"
#ifdef PACK8
#include "particleInputRgba8PS"
#include "particleOutputRgba8PS"
#else
#include "particleInputFloatPS"
#include "particleOutputFloatPS"
#endif
#ifdef EMITTERSHAPE_BOX
#include "particleUpdaterAABBPS"
#else
#include "particleUpdaterSpherePS"
#endif
#include "particleUpdaterStartPS"
#ifdef RESPAWN
#include "particleUpdaterRespawnPS"
#endif
#ifdef NO_RESPAWN
#include "particleUpdaterNoRespawnPS"
#endif
#ifdef ON_STOP
#include "particleUpdaterOnStopPS"
#endif
#include "particleUpdaterEndPS"
`;var lk=`
#if NORMAL != NONE
#if NORMAL == VERTEX
varying Normal: vec3f;
#endif
#if NORMAL == MAP
varying ParticleMat0: vec3f;
varying ParticleMat1: vec3f;
varying ParticleMat2: vec3f;
#endif
uniform lightCube: array<vec3f, 6>;
#endif
#ifdef SOFT
varying vDepth: f32;
#include "screenDepthPS"
#endif
#include "gammaPS"
#include "tonemappingPS"
#include "fogPS"
#if NORMAL == MAP
var normalMap: texture_2d<f32>;
var normalMapSampler: sampler;
#endif
#include "particlePS"
#ifdef SOFT
#include "particle_softPS"
#endif
#if NORMAL == VERTEX
var normal: vec3f = Normal;
#endif
#if NORMAL == MAP
#include "particle_normalMapPS"
#endif
#if NORMAL != NONE
#ifdef HALF_LAMBERT
#include "particle_halflambertPS"
#else
#include "particle_lambertPS"
#endif
#include "particle_lightingPS"
#endif
#if BLEND == NORMAL
#include "particle_blendNormalPS"
#elif BLEND == ADDITIVE
#include "particle_blendAddPS"
#elif BLEND == MULTIPLICATIVE
#include "particle_blendMultiplyPS"
#endif
#include "particle_endPS"
`;var ck=`
#ifdef ANIMTEX
uniform animTexTilesParams: vec2f;
uniform animTexParams: vec4f;
uniform animTexIndexParams: vec2f;
#endif
#if NORMAL == MAP
varying ParticleMat0: vec3f;
varying ParticleMat1: vec3f;
varying ParticleMat2: vec3f;
#endif
#if NORMAL == VERTEX
varying Normal: vec3f;
#endif
#ifdef SOFT
varying vDepth: f32;
#endif
#ifdef PARTICLE_GPU
#include "particle_initVS"
#ifdef PACK8
#include "particleInputRgba8PS"
#else
#include "particleInputFloatPS"
#endif
#ifdef SOFT
#include "screenDepthPS"
#endif
#include "particleVS"
#else
#ifdef SOFT
#include "screenDepthPS"
#endif
#include "particle_cpuVS"
#endif
#ifdef LOCAL_SPACE
#include "particle_localShiftVS"
#endif
#ifdef ANIMTEX
#ifdef ANIMTEX_LOOP
#include "particleAnimFrameLoopVS"
#else
#include "particleAnimFrameClampVS"
#endif
#include "particleAnimTexVS"
#endif
#ifdef PARTICLE_GPU
#ifdef WRAP
#include "particle_wrapVS"
#endif
#endif
#ifdef ALIGN_TO_MOTION
#include "particle_pointAlongVS"
#endif
#ifdef USE_MESH
#include "particle_meshVS"
#else
#ifdef CUSTOM_FACE
#include "particle_customFaceVS"
#else
#include "particle_billboardVS"
#endif
#endif
#if NORMAL == VERTEX
#include "particle_normalVS"
#endif
#if NORMAL == MAP
#include "particle_TBNVS"
#endif
#ifdef STRETCH
#include "particle_stretchVS"
#endif
#ifdef PARTICLE_GPU
#include "particle_endVS"
#else
#include "particle_cpu_endVS"
#endif
#ifdef SOFT
#include "particle_softVS"
#endif
return output;
}
`;var hk=`
var depth: f32 = getLinearScreenDepthFrag();
var particleDepth: f32 = vDepth;
var depthDiff: f32 = saturate(abs(particleDepth - depth) * uniform.softening);
a = a * depthDiff;
`;var fk=`
output.vDepth = getLinearDepth(localPos);
`;var uk=`
let moveDir: vec3f = inVel * uniform.stretch;
var posPrev: vec3f = particlePos - moveDir;
posPrev = posPrev + particlePosMoved;
let viewRotationTemp: mat3x3f = mat3x3f(uniform.matrix_view[0].xyz, uniform.matrix_view[1].xyz, uniform.matrix_view[2].xyz);
let centerToVertexV: vec2f = normalize((viewRotationTemp * localPos).xy);
let interpolation: f32 = dot(-velocityV, centerToVertexV) * 0.5 + 0.5;
particlePos = mix(particlePos, posPrev, interpolation);
`;var dk=`
let rot3 = mat3x3f(
vec3f(rotMatrix[0][0], rotMatrix[1][0], 0.0),
vec3f(rotMatrix[0][1], rotMatrix[1][1], 0.0),
vec3f(0.0, 0.0, 1.0)
);
let viewBasis = mat3x3f(
-uniform.matrix_viewInverse[0].xyz,
-uniform.matrix_viewInverse[1].xyz,
uniform.matrix_viewInverse[2].xyz
);
let tempMat = viewBasis * rot3;
output.ParticleMat0 = tempMat[0];
output.ParticleMat1 = tempMat[1];
output.ParticleMat2 = tempMat[2];
`;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;
`;var mk={particlePS:PU,particleVS:wU,particleAnimFrameClampVS:IU,particleAnimFrameLoopVS:RU,particleAnimTexVS:bU,particleInputFloatPS:DU,particleInputRgba8PS:LU,particleOutputFloatPS:MU,particleOutputRgba8PS:OU,particleUpdaterAABBPS:FU,particleUpdaterEndPS:NU,particleUpdaterInitPS:BU,particleUpdaterNoRespawnPS:UU,particleUpdaterOnStopPS:kU,particleUpdaterRespawnPS:zU,particleUpdaterSpherePS:GU,particleUpdaterStartPS:VU,particle_billboardVS:HU,particle_blendAddPS:WU,particle_blendMultiplyPS:XU,particle_blendNormalPS:YU,particle_cpuVS:KU,particle_cpu_endVS:jU,particle_customFaceVS:qU,particle_endPS:$U,particle_endVS:ZU,particle_halflambertPS:QU,particle_initVS:JU,particle_lambertPS:ek,particle_lightingPS:tk,particle_localShiftVS:sk,particle_meshVS:ik,particle_normalVS:rk,particle_normalMapPS:ak,particle_pointAlongVS:ok,particle_simulationPS:nk,particle_shaderPS:lk,particle_shaderVS:ck,particle_softPS:hk,particle_softVS:fk,particle_stretchVS:uk,particle_TBNVS:dk,particle_wrapVS:pk};var nK=["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"],jm=class extends Fe{constructor(t){super(t),this.id="particlesystem",this.ComponentType=Km,this.DataType=X0,this.schema=nK,this.propertyTypes={emitterExtents:"vec3",emitterExtentsInner:"vec3",particleNormal:"vec3",wrapBounds:"vec3",localVelocityGraph:"curveset",localVelocityGraph2:"curveset",velocityGraph:"curveset",velocityGraph2:"curveset",colorGraph:"curveset",colorGraph2:"curveset",alphaGraph:"curve",alphaGraph2:"curve",rotationSpeedGraph:"curve",rotationSpeedGraph2:"curve",radialSpeedGraph:"curve",radialSpeedGraph2:"curve",scaleGraph:"curve",scaleGraph2:"curve"},this.on("beforeremove",this.onBeforeRemove,this),this.app.systems.on("update",this.onUpdate,this),ne.get(t.graphicsDevice,fe).add(CU),ne.get(t.graphicsDevice,se).add(mk)}initializeComponentData(t,e,s){let i={};s=[];let r=this.propertyTypes;(e.mesh instanceof ae||typeof e.mesh=="number")&&(e.meshAsset=e.mesh,delete e.mesh);for(let a in e){if(e.hasOwnProperty(a)&&(s.push(a),i[a]=e[a]),r[a]==="vec3")Array.isArray(i[a])&&(i[a]=new x(i[a][0],i[a][1],i[a][2]));else if(r[a]==="curve"){if(!(i[a]instanceof Ps)){let o=i[a].type;i[a]=new Ps(i[a].keys),i[a].type=o}}else if(r[a]==="curveset"&&!(i[a]instanceof ki)){let o=i[a].type;i[a]=new ki(i[a].keys),i[a].type=o}i.layers&&Array.isArray(i.layers)&&(i.layers=i.layers.slice(0))}super.initializeComponentData(t,i,s)}cloneComponent(t,e){let s=t.particlesystem.data,i=this.schema,r={};for(let a=0,o=i.length;a<o;a++){let l=i[a],h=s[l];h instanceof x||h instanceof Ps||h instanceof ki?(h=h.clone(),r[l]=h):l==="layers"?r.layers=s.layers.slice(0):h!=null&&(r[l]=h)}return this.addComponent(e,r)}onUpdate(t){let e=this.store,s=this.app.stats.particles,i=this.app.scene.layers;for(let r=0;r<i.layerList.length;r++)i.layerList[r].requiresLightCube=!1;for(let r in e)if(e.hasOwnProperty(r)){let a=e[r],o=a.entity,l=a.data;if(l.enabled&&o.enabled){let h=o.particlesystem.emitter;if(!h?.meshInstance.visible)continue;if(h.lighting){let f=l.layers;for(let u=0;u<f.length;u++){let d=i.getLayerById(f[u]);d&&(d.requiresLightCube=!0)}}if(!l.paused){let f=0;if(h.simTime+=t,h.simTime>=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;u<f;u++)h.addTime(h.fixedTimeStep,!1);s._updatesPerFrame+=f,s._frameTime+=h._addTimeTime,h._addTimeTime=0}h.finishFrame()}}}}onBeforeRemove(t,e){e.onBeforeRemove()}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this)}};var ER=class extends Mo{constructor(t,e){super(),this.skin=t,this.skinInstance=e}},sn=class sn{static createCachedSkinInstance(t,e,s){let i=sn.getCachedSkinInstance(t,e);return i||(i=new er(t),i.resolve(e,s),sn.addCachedSkinInstance(t,e,i)),i}static getCachedSkinInstance(t,e){let s=null,i=sn._skinInstanceCache.get(e);if(i){let r=i.find(a=>a.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<s.length;i++)s[i].setCustomAabb(this._customAabb)}get customAabb(){return this._customAabb}set type(e){if(this._type!==e&&(this._area=null,this._type=e,this.destroyMeshInstances(),e!=="asset")){let s=this._material;(!s||s===this.system.defaultMaterial)&&(s=this._materialReferences[0]&&this._materialReferences[0].asset&&this._materialReferences[0].asset.resource);let i=V0(this.system.app.graphicsDevice,e);this._area=i.area,this.meshInstances=[new we(i.mesh,s||this.system.defaultMaterial,this.entity)]}}get type(){return this._type}set meshInstances(e){if(this.destroyMeshInstances(),this._meshInstances=e,this._meshInstances){let s=this._meshInstances;for(let i=0;i<s.length;i++)s[i].node||(s[i].node=this.entity),s[i].castShadow=this._castShadows,s[i].receiveShadow=this._receiveShadows,s[i].renderStyle=this._renderStyle,s[i].setLightmapped(this._lightmapped),s[i].setCustomAabb(this._customAabb);this.enabled&&this.entity.enabled&&this.addToLayers()}}get meshInstances(){return this._meshInstances}set lightmapped(e){if(e!==this._lightmapped){this._lightmapped=e;let s=this._meshInstances;if(s)for(let i=0;i<s.length;i++)s[i].setLightmapped(e)}}get lightmapped(){return this._lightmapped}set castShadows(e){if(this._castShadows!==e){let s=this._meshInstances;if(s){let i=this.layers,r=this.system.app.scene;if(this._castShadows&&!e)for(let a=0;a<i.length;a++){let o=r.layers.getLayerById(this.layers[a]);o&&o.removeShadowCasters(s)}for(let a=0;a<s.length;a++)s[a].castShadow=e;if(!this._castShadows&&e)for(let a=0;a<i.length;a++){let o=r.layers.getLayerById(i[a]);o&&o.addShadowCasters(s)}}this._castShadows=e}}get castShadows(){return this._castShadows}set receiveShadows(e){if(this._receiveShadows!==e){this._receiveShadows=e;let s=this._meshInstances;if(s)for(let i=0;i<s.length;i++)s[i].receiveShadow=e}}get receiveShadows(){return this._receiveShadows}set castShadowsLightmap(e){this._castShadowsLightmap=e}get castShadowsLightmap(){return this._castShadowsLightmap}set lightmapSizeMultiplier(e){this._lightmapSizeMultiplier=e}get lightmapSizeMultiplier(){return this._lightmapSizeMultiplier}set layers(e){let s=this.system.app.scene.layers,i;if(this._meshInstances)for(let r=0;r<this._layers.length;r++)i=s.getLayerById(this._layers[r]),i&&i.removeMeshInstances(this._meshInstances);this._layers.length=0;for(let r=0;r<e.length;r++)this._layers[r]=e[r];if(!(!this.enabled||!this.entity.enabled||!this._meshInstances))for(let r=0;r<this._layers.length;r++)i=s.getLayerById(this._layers[r]),i&&i.addMeshInstances(this._meshInstances)}get layers(){return this._layers}set batchGroupId(e){this._batchGroupId!==e&&(this.entity.enabled&&this._batchGroupId>=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;s<this._meshInstances.length;s++)this._meshInstances[s].material=e}get material(){return this._material}set materialAssets(e=[]){if(this._materialReferences.length>e.length){for(let s=e.length;s<this._materialReferences.length;s++)this._materialReferences[s].id=null;this._materialReferences.length=e.length}for(let s=0;s<e.length;s++)if(this._materialReferences[s]||this._materialReferences.push(new pa(s,this,this.system.app.assets,{add:this._onMaterialAdded,load:this._onMaterialLoad,remove:this._onMaterialRemove,unload:this._onMaterialUnload},this)),e[s]){let i=e[s]instanceof ae?e[s].id:e[s];this._materialReferences[s].id!==i&&(this._materialReferences[s].id=i),this._materialReferences[s].asset&&this._onMaterialAdded(s,this,this._materialReferences[s].asset)}else this._materialReferences[s].id=null,this._meshInstances[s]&&(this._meshInstances[s].material=this.system.defaultMaterial)}get materialAssets(){return this._materialReferences.map(e=>e.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<e.length;s++)e[s].destroy();this._meshInstances.length=0}}addToLayers(){let e=this.system.app.scene.layers;for(let s=0;s<this._layers.length;s++){let i=e.getLayerById(this._layers[s]);i&&i.addMeshInstances(this._meshInstances)}}removeFromLayers(){if(this._meshInstances&&this._meshInstances.length){let e=this.system.app.scene.layers;for(let s=0;s<this._layers.length;s++){let i=e.getLayerById(this._layers[s]);i&&i.removeMeshInstances(this._meshInstances)}}}onRemoveChild(){this.removeFromLayers()}onInsertChild(){this._meshInstances&&this.enabled&&this.entity.enabled&&this.addToLayers()}onRemove(){this.destroyMeshInstances(),this.asset=null,this.materialAsset=null,this._assetReference.id=null;for(let e=0;e<this._materialReferences.length;e++)this._materialReferences[e].id=null;this.entity.off("remove",this.onRemoveChild,this),this.entity.off("insert",this.onInsertChild,this)}onLayersChanged(e,s){this.addToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),s.on("add",this.onLayerAdded,this),s.on("remove",this.onLayerRemoved,this)}onLayerAdded(e){this.layers.indexOf(e.id)<0||e.addMeshInstances(this._meshInstances)}onLayerRemoved(e){this.layers.indexOf(e.id)<0||e.removeMeshInstances(this._meshInstances)}onEnable(){let e=this.system.app,s=e.scene,i=s.layers;this._rootBone&&this._cloneSkinInstances(),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));let r=this._type==="asset";this._meshInstances&&this._meshInstances.length?this.addToLayers():r&&this.asset&&this._onRenderAssetAdded();for(let a=0;a<this._materialReferences.length;a++)this._materialReferences[a].asset&&this.system.app.assets.load(this._materialReferences[a].asset);this._batchGroupId>=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;e<this._meshInstances.length;e++)this._meshInstances[e].visible=!1}show(){if(this._meshInstances)for(let e=0;e<this._meshInstances.length;e++)this._meshInstances[e].visible=!0}_onRenderAssetAdded(){this._assetReference.asset&&(this._assetReference.asset.resource?this._onRenderAssetLoad():this.enabled&&this.entity.enabled&&this.system.app.assets.load(this._assetReference.asset))}_onRenderAssetLoad(){if(this.destroyMeshInstances(),this._assetReference.asset){let e=this._assetReference.asset.resource;this._evtSetMeshes?.off(),this._evtSetMeshes=e.on("set:meshes",this._onSetMeshes,this),e.meshes&&this._onSetMeshes(e.meshes)}}_onSetMeshes(e){this._cloneMeshes(e)}_clearSkinInstances(){for(let e=0;e<this._meshInstances.length;e++){let s=this._meshInstances[e];Eu.removeCachedSkinInstance(s.skinInstance),s.skinInstance=null}}_cloneSkinInstances(){if(this._meshInstances.length&&this._rootBone instanceof Pe)for(let e=0;e<this._meshInstances.length;e++){let s=this._meshInstances[e],i=s.mesh;i.skin&&!s.skinInstance&&(s.skinInstance=Eu.createCachedSkinInstance(i.skin,this._rootBone,this.entity))}}_cloneMeshes(e){if(e&&e.length){let s=[];for(let i=0;i<e.length;i++){let r=e[i],a=this._materialReferences[i]&&this._materialReferences[i].asset&&this._materialReferences[i].asset.resource,o=new we(r,a||this.system.defaultMaterial,this.entity);s.push(o),r.morph&&(o.morphInstance=new Ar(r.morph))}this.meshInstances=s,this._cloneSkinInstances()}}_onRenderAssetUnload(){this._type==="asset"&&this.destroyMeshInstances()}_onRenderAssetRemove(){this._evtSetMeshes?.off(),this._evtSetMeshes=null,this._onRenderAssetUnload()}_onMaterialAdded(e,s,i){i.resource?this._onMaterialLoad(e,s,i):this.enabled&&this.entity.enabled&&this.system.app.assets.load(i)}_updateMainMaterial(e,s){e===0&&(this.material=s)}_onMaterialLoad(e,s,i){this._meshInstances[e]&&(this._meshInstances[e].material=i.resource),this._updateMainMaterial(e,i.resource)}_onMaterialRemove(e,s,i){this._meshInstances[e]&&(this._meshInstances[e].material=this.system.defaultMaterial),this._updateMainMaterial(e,this.system.defaultMaterial)}_onMaterialUnload(e,s,i){this._meshInstances[e]&&(this._meshInstances[e].material=this.system.defaultMaterial),this._updateMainMaterial(e,this.system.defaultMaterial)}resolveDuplicatedEntityReferenceProperties(e,s){e.rootBone&&(this.rootBone=s[e.rootBone.guid])}};var Y0=class{constructor(){n(this,"enabled",!0)}};var AR=["enabled"],Cu=["material","meshInstances","asset","materialAssets","castShadows","receiveShadows","castShadowsLightmap","lightmapped","lightmapSizeMultiplier","renderStyle","type","layers","isStatic","batchGroupId","rootBone"],qm=class extends Fe{constructor(t){super(t),this.id="render",this.ComponentType=Au,this.DataType=Y0,this.schema=AR,this.defaultMaterial=ra(t.graphicsDevice),this.on("beforeremove",this.onRemove,this)}initializeComponentData(t,e,s){(e.batchGroupId===null||e.batchGroupId===void 0)&&(e.batchGroupId=-1),e.layers&&e.layers.length&&(e.layers=e.layers.slice(0));for(let i=0;i<Cu.length;i++)e.hasOwnProperty(Cu[i])&&(t[Cu[i]]=e[Cu[i]]);e.aabbCenter&&e.aabbHalfExtents&&(t.customAabb=new ge(new x(e.aabbCenter),new x(e.aabbHalfExtents))),super.initializeComponentData(t,e,AR)}cloneComponent(t,e){let s={};for(let o=0;o<Cu.length;o++)s[Cu[o]]=t.render[Cu[o]];s.enabled=t.render.enabled,delete s.meshInstances;let i=this.addComponent(e,s),r=t.render.meshInstances,a=r.map(o=>o.mesh);i._onSetMeshes(a);for(let o=0;o<r.length;o++)i.meshInstances[o].material=r[o].material;return t.render.customAabb&&(i.customAabb=t.render.customAabb.clone()),i}onRemove(t,e){e.onRemove()}};le._buildAccessors(Au.prototype,AR);var $m=class{constructor(t,e){n(this,"_constructor");n(this,"_pool",[]);n(this,"_count",0);this._constructor=t,this._resize(e)}_resize(t){if(t>this._pool.length)for(let e=this._pool.length;e<t;e++)this._pool[e]=new this._constructor}allocate(){return this._count>=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;d<u;d++){let p=Ammo.castObject(o.at(d),Ammo.btRigidBody);if(p&&p.entity){if(i.filterTags&&!p.entity.tags.has(...i.filterTags)||i.filterCallback&&!i.filterCallback(p.entity))continue;let m=l.at(d),_=h.at(d),S=new Qm(p.entity,new x(m.x(),m.y(),m.z()),new x(_.x(),_.y(),_.z()),f.at(d));r.push(S)}}i.sort&&r.sort((d,p)=>d.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;o<a;o++){let l=r.getManifoldByIndexInternal(o),h=l.getBody0(),f=l.getBody1(),u=Ammo.castObject(h,Ammo.btRigidBody),d=Ammo.castObject(f,Ammo.btRigidBody),p=u.entity,m=d.entity;if(!p||!m)continue;let _=u.getCollisionFlags(),S=d.getCollisionFlags(),g=l.getNumContacts(),T=[],C=[],v;if(g>0)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<g;A++){let w=l.getContactPoint(A),I=this._createContactPointFromAmmo(w);if(E||y){T.push(I);let D=this._createReverseContactPointFromAmmo(w);C.push(D)}if(P){let D=this._createSingleContactResult(p,m,I);this.fire("contact",D)}}if(E){let A=this._createContactResult(m,T);v=this._storeCollision(p,m),p.collision&&(p.collision.fire("contact",A),v&&p.collision.fire("collisionstart",A)),p.rigidbody&&(p.rigidbody.fire("contact",A),v&&p.rigidbody.fire("collisionstart",A))}if(y){let A=this._createContactResult(p,C);v=this._storeCollision(m,p),m.collision&&(m.collision.fire("contact",A),v&&m.collision.fire("collisionstart",A)),m.rigidbody&&(m.rigidbody.fire("contact",A),v&&m.rigidbody.fire("collisionstart",A))}}}}this._cleanOldCollisions(),this.contactPointPool.freeAll(),this.contactResultPool.freeAll(),this.singleContactResultPool.freeAll()}onUpdate(e){let s,i;this._stats.physicsStart=Tt(),this._gravityFloat32[0]=this.gravity.x,this._gravityFloat32[1]=this.gravity.y,this._gravityFloat32[2]=this.gravity.z;let r=this.dynamicsWorld.getGravity();(r.x()!==this._gravityFloat32[0]||r.y()!==this._gravityFloat32[1]||r.z()!==this._gravityFloat32[2])&&(r.setValue(this.gravity.x,this.gravity.y,this.gravity.z),this.dynamicsWorld.setGravity(r));let a=this._triggers;for(s=0,i=a.length;s<i;s++)a[s].updateTransform();let o=this._compounds;for(s=0,i=o.length;s<i;s++)o[s]._updateCompound();let l=this._kinematic;for(s=0,i=l.length;s<i;s++)l[s]._updateKinematic();this.dynamicsWorld.stepSimulation(e,this.maxSubSteps,this.fixedTimeStep);let h=this._dynamic;for(s=0,i=h.length;s<i;s++)h[s]._updateDynamic();this.dynamicsWorld.setInternalTickCallback||this._checkForCollisions(Ammo.getPointer(this.dynamicsWorld),e),this._stats.physicsTime=Tt()-this._stats.physicsStart}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this),typeof Ammo<"u"&&(Ammo.destroy(this.dynamicsWorld),Ammo.destroy(this.solver),Ammo.destroy(this.overlappingPairCache),Ammo.destroy(this.dispatcher),Ammo.destroy(this.collisionConfiguration),Ammo.destroy(yl),Ammo.destroy(El),this.dynamicsWorld=null,this.solver=null,this.overlappingPairCache=null,this.dispatcher=null,this.collisionConfiguration=null,yl=null,El=null,Js.onAppDestroy())}};n(Al,"EVENT_CONTACT","contact");le._buildAccessors(Js.prototype,_k);var fh="none",CR="blend";var gk=new W,Pu=class extends le{constructor(e,s){super(e,s);n(this,"_resolution",new B(640,320));n(this,"_referenceResolution",new B(640,320));n(this,"_scaleMode",fh);n(this,"scale",1);n(this,"_scaleBlend",.5);n(this,"_priority",0);n(this,"_screenSpace",!1);n(this,"cull",!1);n(this,"_screenMatrix",new W);n(this,"_elements",new Set);e.app.graphicsDevice.on("resizecanvas",this._onResize,this)}syncDrawOrder(){this.system.queueDrawOrderSync(this.entity.guid,this._processDrawOrderSync,this)}_recurseDrawOrderSync(e,s){if(!(e instanceof Ne))return s;if(e.element){let r=e.element.drawOrder;e.element.drawOrder=s++,e.element._batchGroupId>=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;r<i.length;r++)s=this._recurseDrawOrderSync(i[r],s);return s}_processDrawOrderSync(){this._recurseDrawOrderSync(this.entity,1),this.fire("syncdraworder")}_calcProjectionMatrix(){let e=this._resolution.x/this.scale,s=this._resolution.y/this.scale,i=0,r=e,a=-s;this._screenMatrix.setOrtho(i,r,a,0,1,-1),this._screenSpace||(gk.setScale(.5*e,.5*s,1),this._screenMatrix.mul2(gk,this._screenMatrix))}_updateScale(){this.scale=this._calcScale(this._resolution,this.referenceResolution)}_calcScale(e,s){let i=Math.log2((e.x||1)/s.x),r=Math.log2((e.y||1)/s.y);return Math.pow(2,i*(1-this._scaleBlend)+r*this._scaleBlend)}_onResize(e,s){this._screenSpace&&(this._resolution.set(e,s),this.resolution=this._resolution)}_bindElement(e){this._elements.add(e)}_unbindElement(e){this._elements.delete(e)}onRemove(){this.system.app.graphicsDevice.off("resizecanvas",this._onResize,this),this.fire("remove"),this._elements.forEach(e=>e._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;i<s.length;i++){let r=s[i];r.element&&!r.element.screen&&r.element._updateScreen(e),r.screen||this._updateDescendantElements(r,e)}}destroy(){super.destroy(),this.app.graphicsDevice.off("resizecanvas",this._onResize,this),this.app.systems.off("update",this._onUpdate,this)}_onUpdate(t){let e=this.store;for(let s in e)e[s].entity.screen.update&&e[s].entity.screen.update(t)}_onResize(t,e){this.windowResolution.x=t,this.windowResolution.y=e}cloneComponent(t,e){let s=t.screen;return this.addComponent(e,{enabled:s.enabled,screenSpace:s.screenSpace,scaleMode:s.scaleMode,scaleBlend:s.scaleBlend,priority:s.priority,resolution:s.resolution.clone(),referenceResolution:s.referenceResolution.clone()})}onRemoveComponent(t,e){e.onRemove()}processDrawOrderSyncQueue(){let t=this._drawOrderSyncQueue.list();for(let e=0;e<t.length;e++){let s=t[e];s.callback.call(s.scope)}this._drawOrderSyncQueue.clear()}queueDrawOrderSync(t,e,s){this._drawOrderSyncQueue.list().length||this.app.once("prerender",this.processDrawOrderSyncQueue,this),this._drawOrderSyncQueue.has(t)||this._drawOrderSyncQueue.push(t,{callback:e,scope:s})}};le._buildAccessors(Pu.prototype,PR);var uh=new B,Sk=new x,wu=new ws,xk=new go,vk=new x,qS=new x,hK=new $,fK={x:"y",y:"x"},io=class extends J{constructor(t,e){if(super(),!t||!(t instanceof zs))throw new Error("Element was null or not an ElementComponent");if(e&&e!=="x"&&e!=="y")throw new Error(`Unrecognized axis: ${e}`);this._element=t,this._app=t.system.app,this._axis=e||null,this._enabled=!0,this._dragScale=new x,this._dragStartMousePosition=new x,this._dragStartHandlePosition=new x,this._deltaMousePosition=new x,this._deltaHandlePosition=new x,this._isDragging=!1,this._toggleLifecycleListeners("on")}_toggleLifecycleListeners(t){this._element[t]("mousedown",this._onMouseDownOrTouchStart,this),this._element[t]("touchstart",this._onMouseDownOrTouchStart,this),this._element[t]("selectstart",this._onMouseDownOrTouchStart,this)}_toggleDragListeners(t){let e=t==="on";this._hasDragListeners&&e||(this._app.mouse&&(this._element[t]("mousemove",this._onMove,this),this._element[t]("mouseup",this._onMouseUpOrTouchEnd,this)),ue.touch&&(this._element[t]("touchmove",this._onMove,this),this._element[t]("touchend",this._onMouseUpOrTouchEnd,this),this._element[t]("touchcancel",this._onMouseUpOrTouchEnd,this)),this._element[t]("selectmove",this._onMove,this),this._element[t]("selectend",this._onMouseUpOrTouchEnd,this),this._hasDragListeners=e)}_onMouseDownOrTouchStart(t){if(this._element&&!this._isDragging&&this.enabled){this._dragCamera=t.camera,this._calculateDragScale();let e=this._screenToLocal(t);e&&(this._toggleDragListeners("on"),this._isDragging=!0,this._dragStartMousePosition.copy(e),this._dragStartHandlePosition.copy(this._element.entity.getLocalPosition()),this.fire("drag:start"))}}_onMouseUpOrTouchEnd(){this._isDragging&&(this._isDragging=!1,this._toggleDragListeners("off"),this.fire("drag:end"))}_screenToLocal(t){return t.inputSource?wu.set(t.inputSource.getOrigin(),t.inputSource.getDirection()):(this._determineInputPosition(t),this._chooseRayOriginAndDirection()),vk.copy(this._element.entity.forward).mulScalar(-1),xk.setFromPointNormal(this._element.entity.getPosition(),vk),xk.intersectsRay(wu,qS)?(hK.copy(this._element.entity.getRotation()).invert().transformVector(qS,qS),qS.mul(this._dragScale),qS):null}_determineInputPosition(t){let e=this._app.graphicsDevice.maxPixelRatio;typeof t.x<"u"&&typeof t.y<"u"?(uh.x=t.x*e,uh.y=t.y*e):t.changedTouches&&(uh.x=t.changedTouches[0].x*e,uh.y=t.changedTouches[0].y*e)}_chooseRayOriginAndDirection(){this._element.screen&&this._element.screen.screen.screenSpace?(wu.origin.set(uh.x,-uh.y,0),wu.direction.copy(x.FORWARD)):(Sk.copy(this._dragCamera.screenToWorld(uh.x,uh.y,1)),wu.origin.copy(this._dragCamera.entity.getPosition()),wu.direction.copy(Sk).sub(wu.origin).normalize())}_calculateDragScale(){let t=this._element.entity.parent,e=this._element.screen&&this._element.screen.screen,s=e&&e.screenSpace,i=s?e.scale:1,r=this._dragScale;for(r.set(i,i,i);t&&(r.mul(t.getLocalScale()),t=t.parent,!(s&&t.screen)););r.x=1/r.x,r.y=1/r.y,r.z=0}_onMove(t){let{_element:e,_deltaMousePosition:s,_deltaHandlePosition:i,_axis:r}=this;if(e&&this._isDragging&&this.enabled&&e.enabled&&e.entity.enabled){let a=this._screenToLocal(t);if(a){if(s.sub2(a,this._dragStartMousePosition),i.add2(this._dragStartHandlePosition,s),r){let o=e.entity.getLocalPosition(),l=fK[r];i[l]=o[l]}e.entity.setLocalPosition(i),this.fire("drag:move",i)}}}destroy(){this._toggleLifecycleListeners("off"),this._toggleDragListeners("off")}set enabled(t){this._enabled=t}get enabled(){return this._enabled}get isDragging(){return this._isDragging}};n(io,"EVENT_DRAGSTART","drag:start"),n(io,"EVENT_DRAGEND","drag:end"),n(io,"EVENT_DRAGMOVE","drag:move");var uK=0,Tk=1,dK=2,pK=0,mK=1;var $S=new B,dh=class extends le{constructor(e,s){super(e,s);n(this,"_horizontal");n(this,"_vertical");n(this,"_scrollMode");n(this,"_bounceAmount");n(this,"_friction");n(this,"_dragThreshold",10);n(this,"_useMouseWheel",!0);n(this,"_mouseWheelSensitivity",new B(1,1));n(this,"_horizontalScrollbarVisibility",0);n(this,"_verticalScrollbarVisibility",0);n(this,"_viewportEntity",null);n(this,"_contentEntity",null);n(this,"_horizontalScrollbarEntity",null);n(this,"_verticalScrollbarEntity",null);n(this,"_evtElementAdd",null);n(this,"_evtElementRemove",null);n(this,"_evtViewportEntityElementAdd",null);n(this,"_evtViewportElementRemove",null);n(this,"_evtViewportResize",null);n(this,"_evtContentEntityElementAdd",null);n(this,"_evtContentElementRemove",null);n(this,"_evtContentResize",null);n(this,"_evtHorizontalScrollbarAdd",null);n(this,"_evtHorizontalScrollbarRemove",null);n(this,"_evtHorizontalScrollbarValue",null);n(this,"_evtVerticalScrollbarAdd",null);n(this,"_evtVerticalScrollbarRemove",null);n(this,"_evtVerticalScrollbarValue",null);this._scrollbarUpdateFlags={},this._scrollbarEntities={},this._prevContentSizes={},this._prevContentSizes[Ge]=null,this._prevContentSizes[dt]=null,this._scroll=new B,this._velocity=new x,this._dragStartPosition=new x,this._disabledContentInput=!1,this._disabledContentInputEntities=[],this._evtElementAdd=this.entity.on("element:add",this._onElementComponentAdd,this),this._toggleElementListeners("on")}set horizontal(e){this._horizontal!==e&&(this._horizontal=e,this._syncScrollbarEnabledState(Ge))}get horizontal(){return this._horizontal}set vertical(e){this._vertical!==e&&(this._vertical=e,this._syncScrollbarEnabledState(dt))}get vertical(){return this._vertical}set scrollMode(e){this._scrollMode=e}get scrollMode(){return this._scrollMode}set bounceAmount(e){this._bounceAmount=e}get bounceAmount(){return this._bounceAmount}set friction(e){this._friction=e}get friction(){return this._friction}set dragThreshold(e){this._dragThreshold=e}get dragThreshold(){return this._dragThreshold}set useMouseWheel(e){this._useMouseWheel=e}get useMouseWheel(){return this._useMouseWheel}set mouseWheelSensitivity(e){e?e instanceof B?this._mouseWheelSensitivity=e.clone():this._mouseWheelSensitivity=new B(e[0],e[1]):this._mouseWheelSensitivity=e}get mouseWheelSensitivity(){return this._mouseWheelSensitivity}set horizontalScrollbarVisibility(e){this._horizontalScrollbarVisibility=e}get horizontalScrollbarVisibility(){return this._horizontalScrollbarVisibility}set verticalScrollbarVisibility(e){this._verticalScrollbarVisibility=e}get verticalScrollbarVisibility(){return this._verticalScrollbarVisibility}set viewportEntity(e){if(this._viewportEntity===e)return;let s=typeof e=="string";this._viewportEntity&&s&&this._viewportEntity.guid===e||(this._viewportEntity&&this._viewportEntityUnsubscribe(),e instanceof Pe?this._viewportEntity=e:s?this._viewportEntity=this.system.app.getEntityFromIndex(e)||null:this._viewportEntity=null,this._viewportEntity&&this._viewportEntitySubscribe())}get viewportEntity(){return this._viewportEntity}set contentEntity(e){if(this._contentEntity===e)return;let s=typeof e=="string";this._contentEntity&&s&&this._contentEntity.guid===e||(this._contentEntity&&this._contentEntityUnsubscribe(),e instanceof Pe?this._contentEntity=e:s?this._contentEntity=this.system.app.getEntityFromIndex(e)||null:this._contentEntity=null,this._contentEntity&&this._contentEntitySubscribe())}get contentEntity(){return this._contentEntity}set horizontalScrollbarEntity(e){if(this._horizontalScrollbarEntity===e)return;let s=typeof e=="string";this._horizontalScrollbarEntity&&s&&this._horizontalScrollbarEntity.guid===e||(this._horizontalScrollbarEntity&&this._horizontalScrollbarEntityUnsubscribe(),e instanceof Pe?this._horizontalScrollbarEntity=e:s?this._horizontalScrollbarEntity=this.system.app.getEntityFromIndex(e)||null:this._horizontalScrollbarEntity=null,this._scrollbarEntities[Ge]=this._horizontalScrollbarEntity,this._horizontalScrollbarEntity&&this._horizontalScrollbarEntitySubscribe())}get horizontalScrollbarEntity(){return this._horizontalScrollbarEntity}set verticalScrollbarEntity(e){if(this._verticalScrollbarEntity===e)return;let s=typeof e=="string";this._verticalScrollbarEntity&&s&&this._verticalScrollbarEntity.guid===e||(this._verticalScrollbarEntity&&this._verticalScrollbarEntityUnsubscribe(),e instanceof Pe?this._verticalScrollbarEntity=e:s?this._verticalScrollbarEntity=this.system.app.getEntityFromIndex(e)||null:this._verticalScrollbarEntity=null,this._scrollbarEntities[dt]=this._verticalScrollbarEntity,this._verticalScrollbarEntity&&this._verticalScrollbarEntitySubscribe())}get verticalScrollbarEntity(){return this._verticalScrollbarEntity}set scroll(e){this._onSetScroll(e.x,e.y)}get scroll(){return this._scroll}_toggleElementListeners(e){if(this.entity.element){if(e==="on"&&this._hasElementListeners)return;this.entity.element[e]("resize",this._syncAll,this),this.entity.element[e]("mousewheel",this._onMouseWheel,this),this._hasElementListeners=e==="on"}}_onElementComponentAdd(e){this._evtElementRemove=this.entity.element.once("beforeremove",this._onElementComponentRemove,this),this._toggleElementListeners("on")}_onElementComponentRemove(e){this._evtElementRemove?.off(),this._evtElementRemove=null,this._toggleElementListeners("off")}_viewportEntitySubscribe(){this._evtViewportEntityElementAdd=this._viewportEntity.on("element:add",this._onViewportElementGain,this),this._viewportEntity.element&&this._onViewportElementGain()}_viewportEntityUnsubscribe(){this._evtViewportEntityElementAdd?.off(),this._evtViewportEntityElementAdd=null,this._viewportEntity?.element&&this._onViewportElementLose()}_viewportEntityElementSubscribe(){let e=this._viewportEntity.element;this._evtViewportElementRemove=e.once("beforeremove",this._onViewportElementLose,this),this._evtViewportResize=e.on("resize",this._syncAll,this)}_viewportEntityElementUnsubscribe(){this._evtViewportElementRemove?.off(),this._evtViewportElementRemove=null,this._evtViewportResize?.off(),this._evtViewportResize=null}_onViewportElementGain(){this._viewportEntityElementSubscribe(),this._syncAll()}_onViewportElementLose(){this._viewportEntityElementUnsubscribe()}_contentEntitySubscribe(){this._evtContentEntityElementAdd=this._contentEntity.on("element:add",this._onContentElementGain,this),this._contentEntity.element&&this._onContentElementGain()}_contentEntityUnsubscribe(){this._evtContentEntityElementAdd?.off(),this._evtContentEntityElementAdd=null,this._contentEntity?.element&&this._onContentElementLose()}_contentEntityElementSubscribe(){let e=this._contentEntity.element;this._evtContentElementRemove=e.once("beforeremove",this._onContentElementLose,this),this._evtContentResize=e.on("resize",this._syncAll,this)}_contentEntityElementUnsubscribe(){this._evtContentElementRemove?.off(),this._evtContentElementRemove=null,this._evtContentResize?.off(),this._evtContentResize=null}_onContentElementGain(){this._contentEntityElementSubscribe(),this._destroyDragHelper(),this._contentDragHelper=new io(this._contentEntity.element),this._contentDragHelper.on("drag:start",this._onContentDragStart,this),this._contentDragHelper.on("drag:end",this._onContentDragEnd,this),this._contentDragHelper.on("drag:move",this._onContentDragMove,this),this._prevContentSizes[Ge]=null,this._prevContentSizes[dt]=null,this._syncAll()}_onContentElementLose(){this._contentEntityElementUnsubscribe(),this._destroyDragHelper()}_onContentDragStart(){this._contentEntity&&this.enabled&&this.entity.enabled&&this._dragStartPosition.copy(this._contentEntity.getLocalPosition())}_onContentDragEnd(){this._prevContentDragPosition=null,this._enableContentInput()}_onContentDragMove(e){if(this._contentEntity&&this.enabled&&this.entity.enabled&&(this._wasDragged=!0,this._setScrollFromContentPosition(e),this._setVelocityFromContentPositionDelta(e),!this._disabledContentInput)){let s=e.x-this._dragStartPosition.x,i=e.y-this._dragStartPosition.y;(Math.abs(s)>this.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 s<i?-this._getViewportSize(e):i-s}_getMaxScrollValue(e){return this._contentIsLargerThanViewport(e)?1:0}_getScrollbarHandleSize(e,s){let i=this._getViewportSize(s),r=this._getContentSize(s);if(Math.abs(r)<.001)return 1;let a=Math.min(i/r,1),o=this._toOvershoot(this._scroll[e],s);return o===0?a:a/(1+Math.abs(o))}_getViewportSize(e){return this._getSize(e,this._viewportEntity)}_getContentSize(e){return this._getSize(e,this._contentEntity)}_getSize(e,s){return s?.element?s.element[this._getCalculatedDimension(e)]:0}_getScrollingEnabled(e){if(e===Ge)return this.horizontal;if(e===dt)return this.vertical}_getScrollbarVisibility(e){if(e===Ge)return this.horizontalScrollbarVisibility;if(e===dt)return this.verticalScrollbarVisibility}_getSign(e){return e===Ge?1:-1}_getAxis(e){return e===Ge?"x":"y"}_getCalculatedDimension(e){return e===Ge?"calculatedWidth":"calculatedHeight"}_destroyDragHelper(){this._contentDragHelper&&this._contentDragHelper.destroy()}onUpdate(){this._contentEntity&&(this._updateVelocity(),this._syncScrollbarEnabledState(Ge),this._syncScrollbarEnabledState(dt))}_updateVelocity(){if(!this._isDragging()){if(this.scrollMode===1&&(this._hasOvershoot("x",Ge)&&this._setVelocityFromOvershoot(this.scroll.x,"x",Ge),this._hasOvershoot("y",dt)&&this._setVelocityFromOvershoot(this.scroll.y,"y",dt)),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,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;r<a;r++)e(i[r])};if(this._contentEntity){let s=this._contentEntity.children;for(let i=0,r=s.length;i<r;i++)e(s[i])}this._disabledContentInput=!0}onEnable(){this._setScrollbarComponentsEnabled(!0),this._setContentDraggingEnabled(!0),this._syncAll()}onDisable(){this._setScrollbarComponentsEnabled(!1),this._setContentDraggingEnabled(!1)}onRemove(){this._evtElementAdd?.off(),this._evtElementAdd=null,this._evtElementRemove?.off(),this._evtElementRemove=null,this.viewportEntity=null,this.contentEntity=null,this.horizontalScrollbarEntity=null,this.verticalScrollbarEntity=null,this._toggleElementListeners("off"),this._destroyDragHelper()}resolveDuplicatedEntityReferenceProperties(e,s){e.viewportEntity&&(this.viewportEntity=s[e.viewportEntity.guid]),e.contentEntity&&(this.contentEntity=s[e.contentEntity.guid]),e.horizontalScrollbarEntity&&(this.horizontalScrollbarEntity=s[e.horizontalScrollbarEntity.guid]),e.verticalScrollbarEntity&&(this.verticalScrollbarEntity=s[e.verticalScrollbarEntity.guid])}};n(dh,"EVENT_SETSCROLL","set:scroll");var $0=class{constructor(){n(this,"enabled",!0)}};var wR=["enabled"],yk=["horizontal","vertical","scrollMode","bounceAmount","friction","dragThreshold","useMouseWheel","mouseWheelSensitivity","horizontalScrollbarVisibility","verticalScrollbarVisibility","viewportEntity","contentEntity","horizontalScrollbarEntity","verticalScrollbarEntity"],e_=class extends Fe{constructor(t){super(t),this.id="scrollview",this.ComponentType=dh,this.DataType=$0,this.schema=wR,this.on("beforeremove",this._onRemoveComponent,this),this.app.systems.on("update",this.onUpdate,this)}initializeComponentData(t,e,s){for(let i=0;i<yk.length;i++){let r=yk[i];e[r]!==void 0&&(t[r]=e[r])}super.initializeComponentData(t,e,wR)}cloneComponent(t,e){let s=t.scrollview;return this.addComponent(e,{enabled:s.enabled,horizontal:s.horizontal,vertical:s.vertical,scrollMode:s.scrollMode,bounceAmount:s.bounceAmount,friction:s.friction,dragThreshold:s.dragThreshold,useMouseWheel:s.useMouseWheel,mouseWheelSensitivity:s.mouseWheelSensitivity,horizontalScrollbarVisibility:s.horizontalScrollbarVisibility,verticalScrollbarVisibility:s.verticalScrollbarVisibility,viewportEntity:s.viewportEntity,contentEntity:s.contentEntity,horizontalScrollbarEntity:s.horizontalScrollbarEntity,verticalScrollbarEntity:s.verticalScrollbarEntity})}onUpdate(t){let e=this.store;for(let s in e){let i=e[s].entity,r=i.scrollview;r.enabled&&i.enabled&&r.onUpdate()}}_onRemoveComponent(t,e){e.onRemove()}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this)}};le._buildAccessors(dh.prototype,wR);var ph=class extends le{constructor(){super(...arguments);n(this,"_orientation",Ge);n(this,"_value",0);n(this,"_handleSize",0);n(this,"_handleEntity",null);n(this,"_evtHandleEntityElementAdd",null);n(this,"_evtHandleEntityChanges",[]);n(this,"_handleDragHelper",null)}set orientation(e){this._orientation!==e&&(this._orientation=e,this._handleEntity?.element&&(this._handleEntity.element[this._getOppositeDimension()]=0,this._rebuildDragHelper(),this._updateHandlePositionAndSize()))}get orientation(){return this._orientation}set value(e){Math.abs(e-this._value)>1e-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;e<this._evtHandleEntityChanges.length;e++)this._evtHandleEntityChanges[e].off();this._evtHandleEntityChanges.length=0}_onHandleElementGain(){this._handleEntityElementSubscribe(),this._rebuildDragHelper(),this._updateHandlePositionAndSize()}_rebuildDragHelper(){this._destroyDragHelper(),this._handleDragHelper=new io(this._handleEntity.element,this._getAxis()),this._handleDragHelper.enabled=this.enabled&&this.entity.enabled,this._handleDragHelper.on("drag:move",this._onHandleDrag,this)}_onHandleElementLose(){this._handleEntityElementUnsubscribe(),this._destroyDragHelper()}_onHandleDrag(e){this._handleEntity&&this.enabled&&this.entity.enabled&&(this.value=this._handlePositionToScrollValue(e[this._getAxis()]))}_updateHandlePositionAndSize(){let e=this._handleEntity;if(!e)return;let s=e.getLocalPosition();s[this._getAxis()]=this._getHandlePosition(),e.setLocalPosition(s),e.element&&(e.element[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?this._orientation===Ge?this.entity.element.calculatedWidth:this.entity.element.calculatedHeight:0}_getHandleLength(){return this._getTrackLength()*this._handleSize}_getHandlePosition(){return this._scrollValueToHandlePosition(this._value)}_getSign(){return this._orientation===Ge?1:-1}_getAxis(){return this._orientation===Ge?"x":"y"}_getDimension(){return this._orientation===Ge?"width":"height"}_getOppositeDimension(){return this._orientation===Ge?"height":"width"}_destroyDragHelper(){this._handleDragHelper?.destroy(),this._handleDragHelper=null}onEnable(){this._handleDragHelper&&(this._handleDragHelper.enabled=!0)}onDisable(){this._handleDragHelper&&(this._handleDragHelper.enabled=!1)}onRemove(){this._destroyDragHelper()}resolveDuplicatedEntityReferenceProperties(e,s){e.handleEntity&&(this.handleEntity=s[e.handleEntity.guid])}};n(ph,"EVENT_SETVALUE","set:value");var Z0=class{constructor(){n(this,"enabled",!0)}};var IR=["enabled"],Ek=["orientation","value","handleSize","handleEntity"],t_=class extends Fe{constructor(t){super(t),this.id="scrollbar",this.ComponentType=ph,this.DataType=Z0,this.schema=IR,this.on("add",this._onAddComponent,this),this.on("beforeremove",this._onRemoveComponent,this)}initializeComponentData(t,e,s){for(let i=0;i<Ek.length;i++){let r=Ek[i];e.hasOwnProperty(r)&&(t[r]=e[r])}super.initializeComponentData(t,e,IR)}cloneComponent(t,e){let s=t.scrollbar;return this.addComponent(e,{enabled:s.enabled,orientation:s.orientation,value:s.value,handleSize:s.handleSize,handleEntity:s.handleEntity})}_onAddComponent(t){t.fire("scrollbar:add")}_onRemoveComponent(t,e){e.onRemove()}};le._buildAccessors(ph.prototype,IR);var _K={volume:0,pitch:0,loop:!1,startTime:0,duration:0,position:new x,maxDistance:0,refDistance:0,rollOffFactor:0,distanceModel:0,onPlay:null,onPause:null,onResume:null,onStop:null,onEnd:null},ir=class extends J{constructor(e,s="Untitled",i={}){super();n(this,"name");n(this,"instances",[]);this._component=e,this._assets=e.system.app.assets,this._manager=e.system.manager,this.name=s,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._duration=i.duration>0?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<r;i++)s[i].pause()&&(e=!0);return e}resume(){let e=!1,s=this.instances;for(let i=0,r=s.length;i<r;i++)s[i].resume()&&(e=!0);return e}stop(){let e=!1,s=this.instances,i=s.length;for(;i--;)s[i].stop(),e=!0;return s.length=0,e}load(){if(!this._hasAsset())return;let e=this._assets.get(this._asset);if(!e){this._assets.off(`add:${this._asset}`,this._onAssetAdd,this),this._assets.once(`add:${this._asset}`,this._onAssetAdd,this);return}if(e.off("remove",this._onAssetRemoved,this),e.on("remove",this._onAssetRemoved,this),!e.resource){e.off("load",this._onAssetLoad,this),e.once("load",this._onAssetLoad,this),this._assets.load(e);return}this.fire("load",e.resource)}setExternalNodes(e,s){if(e&&(s||(s=e),this._firstNode=e,this._lastNode=s,!this._overlap)){let i=this.instances;for(let r=0,a=i.length;r<a;r++)i[r].setExternalNodes(e,s)}}clearExternalNodes(){if(this._firstNode=null,this._lastNode=null,!this._overlap){let e=this.instances;for(let s=0,i=e.length;s<i;s++)e[s].clearExternalNodes()}}getExternalNodes(){return[this._firstNode,this._lastNode]}_hasAsset(){return this._asset!=null}_createInstance(){let e=null,s=this._component,i=null;if(this._hasAsset()){let a=this._assets.get(this._asset);a&&(i=a.resource)}let r=_K;return r.volume=this._volume*s.volume,r.pitch=this._pitch*s.pitch,r.loop=this._loop,r.startTime=this._startTime,r.duration=this._duration,r.onPlay=this._onInstancePlayHandler,r.onPause=this._onInstancePauseHandler,r.onResume=this._onInstanceResumeHandler,r.onStop=this._onInstanceStopHandler,r.onEnd=this._onInstanceEndHandler,s.positional?(r.position.copy(s.entity.getPosition()),r.maxDistance=s.maxDistance,r.refDistance=s.refDistance,r.rollOffFactor=s.rollOffFactor,r.distanceModel=s.distanceModel,e=new ip(this._manager,i,r)):e=new _r(this._manager,i,r),this._firstNode&&e.setExternalNodes(this._firstNode,this._lastNode),e}_onInstancePlay(e){this.fire("play",e),this._component.fire("play",this,e)}_onInstancePause(e){this.fire("pause",e),this._component.fire("pause",this,e)}_onInstanceResume(e){this.fire("resume",e),this._component.fire("resume",this,e)}_onInstanceStop(e){let s=this.instances.indexOf(e);s!==-1&&this.instances.splice(s,1),this.fire("stop",e),this._component.fire("stop",this,e)}_onInstanceEnd(e){let s=this.instances.indexOf(e);s!==-1&&this.instances.splice(s,1),this.fire("end",e),this._component.fire("end",this,e)}_onAssetAdd(e){this.load()}_onAssetLoad(e){this.load()}_onAssetRemoved(e){e.off("remove",this._onAssetRemoved,this),this._assets.off(`add:${e.id}`,this._onAssetAdd,this),this.stop()}updatePosition(e){let s=this.instances;for(let i=0,r=s.length;i<r;i++)s[i].position=e}set asset(e){let s=this._asset;if(s){this._assets.off(`add:${s}`,this._onAssetAdd,this);let i=this._assets.get(s);i&&i.off("remove",this._onAssetRemoved,this)}this._asset=e,this._asset instanceof ae&&(this._asset=this._asset.id),this._hasAsset()&&this._component.enabled&&this._component.entity.enabled&&this.load()}get asset(){return this._asset}set autoPlay(e){this._autoPlay=!!e}get autoPlay(){return this._autoPlay}set duration(e){if(this._duration=Math.max(0,Number(e)||0)||null,!this._overlap){let s=this.instances;for(let i=0,r=s.length;i<r;i++)s[i].duration=this._duration}}get duration(){let e=0;if(this._hasAsset()){let s=this._assets.get(this._asset);e=s?.resource?s.resource.duration:0}return this._duration!=null?this._duration%(e||1):e}get isLoaded(){if(this._hasAsset()){let e=this._assets.get(this._asset);if(e)return!!e.resource}return!1}get isPaused(){let e=this.instances,s=e.length;if(s===0)return!1;for(let i=0;i<s;i++)if(!e[i].isPaused)return!1;return!0}get isPlaying(){let e=this.instances;for(let s=0,i=e.length;s<i;s++)if(e[s].isPlaying)return!0;return!1}get isStopped(){let e=this.instances;for(let s=0,i=e.length;s<i;s++)if(!e[s].isStopped)return!1;return!0}set loop(e){this._loop=!!e;let s=this.instances;for(let i=0,r=s.length;i<r;i++)s[i].loop=this._loop}get loop(){return this._loop}set overlap(e){this._overlap=!!e}get overlap(){return this._overlap}set pitch(e){if(this._pitch=Math.max(Number(e)||0,.01),!this._overlap){let s=this.instances;for(let i=0,r=s.length;i<r;i++)s[i].pitch=this.pitch*this._component.pitch}}get pitch(){return this._pitch}set startTime(e){if(this._startTime=Math.max(0,Number(e)||0),!this._overlap){let s=this.instances;for(let i=0,r=s.length;i<r;i++)s[i].startTime=this._startTime}}get startTime(){return this._startTime}set volume(e){if(this._volume=R.clamp(Number(e)||0,0,1),!this._overlap){let s=this.instances;for(let i=0,r=s.length;i<r;i++)s[i].volume=this._volume*this._component.volume}}get volume(){return this._volume}};n(ir,"EVENT_PLAY","play"),n(ir,"EVENT_PAUSE","pause"),n(ir,"EVENT_RESUME","resume"),n(ir,"EVENT_STOP","stop"),n(ir,"EVENT_END","end"),n(ir,"EVENT_LOAD","load");var ma=class extends le{constructor(){super(...arguments);n(this,"_volume",1);n(this,"_pitch",1);n(this,"_positional",!0);n(this,"_refDistance",1);n(this,"_maxDistance",1e4);n(this,"_rollOffFactor",1);n(this,"_distanceModel",ep);n(this,"_slots",{});n(this,"_playingBeforeDisable",{})}_updateSoundInstances(e,s,i){let r=this._slots;for(let a in r){let o=r[a];if(!o.overlap){let l=o.instances;for(let h=0,f=l.length;h<f;h++)l[h][e]=i?o[e]*s:s}}}set distanceModel(e){this._distanceModel=e,this._updateSoundInstances("distanceModel",e,!1)}get distanceModel(){return this._distanceModel}set maxDistance(e){this._maxDistance=e,this._updateSoundInstances("maxDistance",e,!1)}get maxDistance(){return this._maxDistance}set refDistance(e){this._refDistance=e,this._updateSoundInstances("refDistance",e,!1)}get refDistance(){return this._refDistance}set rollOffFactor(e){this._rollOffFactor=e,this._updateSoundInstances("rollOffFactor",e,!1)}get rollOffFactor(){return this._rollOffFactor}set pitch(e){this._pitch=e,this._updateSoundInstances("pitch",e,!0)}get pitch(){return this._pitch}set volume(e){this._volume=e,this._updateSoundInstances("volume",e,!0)}get volume(){return this._volume}set positional(e){this._positional=e;let s=this._slots;for(let i in s){let r=s[i];if(!r.overlap){let a=r.instances,o=a.length;for(let l=o-1;l>=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;i<s.length;i++)e.hasOwnProperty(s[i])&&(t[s[i]]=e[s[i]]);super.initializeComponentData(t,e,["enabled"])}cloneComponent(t,e){let s=t.sound,i=s.slots,r={};for(let o in i){let l=i[o];r[o]={name:l.name,volume:l.volume,pitch:l.pitch,loop:l.loop,duration:l.duration,startTime:l.startTime,overlap:l.overlap,autoPlay:l.autoPlay,asset:l.asset}}let a={distanceModel:s.distanceModel,enabled:s.enabled,maxDistance:s.maxDistance,pitch:s.pitch,positional:s.positional,refDistance:s.refDistance,rollOffFactor:s.rollOffFactor,slots:r,volume:s.volume};return this.addComponent(e,a)}onUpdate(t){let e=this.store;for(let s in e)if(e.hasOwnProperty(s)){let r=e[s].entity;if(r.enabled){let a=r.sound;if(a.enabled&&a.positional){let o=r.getPosition(),l=a.slots;for(let h in l)l[h].updatePosition(o)}}}}onBeforeRemove(t,e){let s=e.slots;for(let i in s)s[i].overlap||s[i].stop();e.onRemove()}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this)}};le._buildAccessors(ma.prototype,Ak);var J0="simple",eE="animated";var rr=class extends J{constructor(e,s){super();n(this,"_evtSetMeshes",null);n(this,"_component");n(this,"_frame",0);n(this,"_sprite",null);n(this,"_spriteAsset",null);n(this,"_playing",!1);n(this,"_paused",!1);n(this,"_time",0);n(this,"name");n(this,"fps",0);n(this,"loop",!1);this._component=e,this.fps=s.fps||0,this.loop=s.loop||!1,this.name=s.name,this.spriteAsset=s.spriteAsset}get duration(){if(this._sprite){let e=this.fps||Number.MIN_VALUE;return this._sprite.frameKeys.length/Math.abs(e)}return 0}set frame(e){this._setFrame(e);let s=this.fps||Number.MIN_VALUE;this._setTime(this._frame/s)}get frame(){return this._frame}get isPaused(){return this._paused}get isPlaying(){return this._playing}set sprite(e){if(this._sprite&&(this._evtSetMeshes?.off(),this._evtSetMeshes=null,this._sprite.off("set:pixelsPerUnit",this._onSpritePpuChanged,this),this._sprite.off("set:atlas",this._onSpriteMeshesChange,this),this._sprite.atlas&&this._sprite.atlas.off("set:texture",this._onSpriteMeshesChange,this)),this._sprite=e,this._sprite&&(this._evtSetMeshes=this._sprite.on("set:meshes",this._onSpriteMeshesChange,this),this._sprite.on("set:pixelsPerUnit",this._onSpritePpuChanged,this),this._sprite.on("set:atlas",this._onSpriteMeshesChange,this),this._sprite.atlas&&this._sprite.atlas.on("set:texture",this._onSpriteMeshesChange,this)),this._component.currentClip===this){let s;!e||!e.atlas?(s=this._component._meshInstance,s&&(s.deleteParameter("texture_emissiveMap"),s.deleteParameter("texture_opacityMap")),this._component.removeFromLayers()):(e.atlas.texture&&(s=this._component._meshInstance,s&&(s.setParameter("texture_emissiveMap",e.atlas.texture),s.setParameter("texture_opacityMap",e.atlas.texture)),this._component.enabled&&this._component.entity.enabled&&this._component.addToLayers()),this.time&&this.fps?this.time=this.time:this.frame=this.frame)}}get sprite(){return this._sprite}set spriteAsset(e){let s=this._component.system.app.assets,i=e;if(e instanceof ae&&(i=e.id),this._spriteAsset!==i){if(this._spriteAsset){let r=s.get(this._spriteAsset);r&&this._unbindSpriteAsset(r)}if(this._spriteAsset=i,this._spriteAsset){let r=s.get(this._spriteAsset);r?this._bindSpriteAsset(r):(this.sprite=null,s.on(`add:${this._spriteAsset}`,this._onSpriteAssetAdded,this))}else this.sprite=null}}get spriteAsset(){return this._spriteAsset}set time(e){this._setTime(e),this._sprite?this.frame=Math.min(this._sprite.frameKeys.length-1,Math.floor(this._time*Math.abs(this.fps))):this.frame=0}get time(){return this._time}_onSpriteAssetAdded(e){this._component.system.app.assets.off(`add:${e.id}`,this._onSpriteAssetAdded,this),this._spriteAsset===e.id&&this._bindSpriteAsset(e)}_bindSpriteAsset(e){e.on("load",this._onSpriteAssetLoad,this),e.on("remove",this._onSpriteAssetRemove,this),e.resource?this._onSpriteAssetLoad(e):this._component.system.app.assets.load(e)}_unbindSpriteAsset(e){e&&(e.off("load",this._onSpriteAssetLoad,this),e.off("remove",this._onSpriteAssetRemove,this),e.resource&&!e.resource.atlas&&this._component.system.app.assets.off(`load:${e.data.textureAtlasAsset}`,this._onTextureAtlasLoad,this))}_onSpriteAssetLoad(e){if(!e.resource)this.sprite=null;else if(e.resource.atlas)this.sprite=e.resource;else{let s=e.data.textureAtlasAsset,i=this._component.system.app.assets;i.off(`load:${s}`,this._onTextureAtlasLoad,this),i.once(`load:${s}`,this._onTextureAtlasLoad,this)}}_onTextureAtlasLoad(e){let s=this._spriteAsset;s instanceof ae?this._onSpriteAssetLoad(s):this._onSpriteAssetLoad(this._component.system.app.assets.get(s))}_onSpriteAssetRemove(e){this.sprite=null}_onSpriteMeshesChange(){this._component.currentClip===this&&this._component._showFrame(this.frame)}_onSpritePpuChanged(){this._component.currentClip===this&&this.sprite.renderMode!==Ti&&this._component._showFrame(this.frame)}_update(e){if(this.fps===0||!this._playing||this._paused||!this._sprite)return;let s=this.fps<0?-1:1,i=this._time+e*this._component.speed*s,r=this.duration,a=i>r||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<i;s++){let r=this.system.app.scene.layers.getLayerById(this._layers[s]);r&&r.addMeshInstances(e)}this._inLayers=!0}removeFromLayers(){if(!this._inLayers||!this._meshInstance)return;let e=[this._meshInstance];for(let s=0,i=this._layers.length;s<i;s++){let r=this.system.app.scene.layers.getLayerById(this._layers[s]);r&&r.removeMeshInstances(e)}this._inLayers=!1}_showFrame(e){if(!this.sprite)return;let s=this.sprite.meshes[e];if(!s){this._meshInstance&&(this._meshInstance.mesh=null,this._meshInstance.visible=!1);return}let i;if(this.sprite.renderMode===It?i=this.system.default9SlicedMaterialSlicedMode:this.sprite.renderMode===Rt?i=this.system.default9SlicedMaterialTiledMode:i=this.system.defaultMaterial,this._meshInstance||(this._meshInstance=new we(s,this._material,this._node),this._meshInstance.castShadow=!1,this._meshInstance.receiveShadow=!1,this._meshInstance.drawOrder=this._drawOrder,this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._meshInstance.setParameter(wk,this._colorUniform),this._meshInstance.setParameter(Ik,this._color.a),this.enabled&&this.entity.enabled&&this.addToLayers()),this._meshInstance.material!==i&&(this._meshInstance.material=i),this._meshInstance.mesh!==s&&(this._meshInstance.mesh=s,this._meshInstance.visible=!0,this._meshInstance._aabbVer=-1),this.sprite.atlas&&this.sprite.atlas.texture?(this._meshInstance.setParameter(Ck,this.sprite.atlas.texture),this._meshInstance.setParameter(Pk,this.sprite.atlas.texture)):(this._meshInstance.deleteParameter(Ck),this._meshInstance.deleteParameter(Pk)),this.sprite.atlas&&(this.sprite.renderMode===It||this.sprite.renderMode===Rt)){this._meshInstance._updateAabbFunc=this._updateAabbFunc;let r=this.sprite.atlas.frames[this.sprite.frameKeys[e]];if(r){let a=2/r.rect.z,o=2/r.rect.w;this._innerOffset.set(r.border.x*a,r.border.y*o,r.border.z*a,r.border.w*o);let l=this.sprite.atlas.texture;this._atlasRect.set(r.rect.x/l.width,r.rect.y/l.height,r.rect.z/l.width,r.rect.w/l.height)}else this._innerOffset.set(0,0,0,0);this._innerOffsetUniform[0]=this._innerOffset.x,this._innerOffsetUniform[1]=this._innerOffset.y,this._innerOffsetUniform[2]=this._innerOffset.z,this._innerOffsetUniform[3]=this._innerOffset.w,this._meshInstance.setParameter(gK,this._innerOffsetUniform),this._atlasRectUniform[0]=this._atlasRect.x,this._atlasRectUniform[1]=this._atlasRect.y,this._atlasRectUniform[2]=this._atlasRect.z,this._atlasRectUniform[3]=this._atlasRect.w,this._meshInstance.setParameter(xK,this._atlasRectUniform)}else this._meshInstance._updateAabbFunc=null;this._updateTransform()}_updateTransform(){let e=this.flipX?-1:1,s=this.flipY?-1:1,i=0,r=0;if(this.sprite&&(this.sprite.renderMode===It||this.sprite.renderMode===Rt)){let a=1,o=1;if(this.sprite.atlas){let f=this.sprite.atlas.frames[this.sprite.frameKeys[this.frame]];f&&(a=f.rect.z,o=f.rect.w,i=(.5-f.pivot.x)*this._width,r=(.5-f.pivot.y)*this._height)}let l=a/this.sprite.pixelsPerUnit,h=o/this.sprite.pixelsPerUnit;this._outerScale.set(Math.max(this._width,this._innerOffset.x*l),Math.max(this._height,this._innerOffset.y*h)),e*=l,s*=h,this._outerScale.x/=l,this._outerScale.y/=h,e*=R.clamp(this._width/(this._innerOffset.x*l),1e-4,1),s*=R.clamp(this._height/(this._innerOffset.y*h),1e-4,1),this._meshInstance&&(this._outerScaleUniform[0]=this._outerScale.x,this._outerScaleUniform[1]=this._outerScale.y,this._meshInstance.setParameter(SK,this._outerScaleUniform))}this._node.setLocalScale(e,s,1),this._node.setLocalPosition(i,r,0)}_updateAabb(e){return e.center.set(0,0,0),e.halfExtents.set(this._outerScale.x*.5,this._outerScale.y*.5,.001),e.setFromTransformedAabb(e,this._node.getWorldTransform()),e}_tryAutoPlay(){if(!this._autoPlayClip||this.type!==eE)return;let e=this._clips[this._autoPlayClip];e&&!e.isPlaying&&(!this._currentClip||!this._currentClip.isPlaying)&&this.enabled&&this.entity.enabled&&this.play(e.name)}_onLayersChanged(e,s){e.off("add",this._onLayerAdded,this),e.off("remove",this._onLayerRemoved,this),s.on("add",this._onLayerAdded,this),s.on("remove",this._onLayerRemoved,this),this.enabled&&this.entity.enabled&&this.addToLayers()}_onLayerAdded(e){this.layers.indexOf(e.id)<0||this._inLayers&&this.enabled&&this.entity.enabled&&this._meshInstance&&e.addMeshInstances([this._meshInstance])}_onLayerRemoved(e){!this._meshInstance||this.layers.indexOf(e.id)<0||e.removeMeshInstances([this._meshInstance])}addClip(e){let s=new rr(this,{name:e.name,fps:e.fps,loop:e.loop,spriteAsset:e.spriteAsset});return this._clips[e.name]=s,s.name&&s.name===this._autoPlayClip&&this._tryAutoPlay(),s}removeClip(e){delete this._clips[e]}clip(e){return this._clips[e]}play(e){let s=this._clips[e],i=this._currentClip;return i&&i!==s&&(i._playing=!1),this._currentClip=s,this._currentClip&&(this._currentClip=s,this._currentClip.play()),s}pause(){this._currentClip!==this._defaultClip&&this._currentClip.isPlaying&&this._currentClip.pause()}resume(){this._currentClip!==this._defaultClip&&this._currentClip.isPaused&&this._currentClip.resume()}stop(){this._currentClip!==this._defaultClip&&this._currentClip.stop()}};n(Lr,"EVENT_PLAY","play"),n(Lr,"EVENT_PAUSE","pause"),n(Lr,"EVENT_RESUME","resume"),n(Lr,"EVENT_STOP","stop"),n(Lr,"EVENT_END","end"),n(Lr,"EVENT_LOOP","loop");var tE=class{constructor(){n(this,"enabled",!0)}};var Rk=["enabled"],i_=class extends Fe{constructor(t){super(t),this.id="sprite",this.ComponentType=Lr,this.DataType=tE,this.schema=Rk,this._defaultTexture=null,this._defaultMaterial=null,this._default9SlicedMaterialSlicedMode=null,this._default9SlicedMaterialTiledMode=null,this.app.systems.on("update",this.onUpdate,this),this.on("beforeremove",this.onBeforeRemove,this)}set defaultMaterial(t){this._defaultMaterial=t}get defaultMaterial(){if(!this._defaultMaterial){let t=new Z(this.app.graphicsDevice,{width:1,height:1,format:st,name:"sprite"}),e=new Uint8Array(t.lock());e[0]=e[1]=e[2]=e[3]=255,t.unlock();let s=new it;s.diffuse.set(0,0,0),s.emissive.set(1,1,1),s.emissiveMap=t,s.opacityMap=t,s.opacityMapChannel="a",s.useLighting=!1,s.useTonemap=!1,s.useFog=!1,s.useSkybox=!1,s.blendType=Ms,s.depthWrite=!1,s.pixelSnap=!1,s.cull=0,s.update(),this._defaultTexture=t,this._defaultMaterial=s}return this._defaultMaterial}set default9SlicedMaterialSlicedMode(t){this._default9SlicedMaterialSlicedMode=t}get default9SlicedMaterialSlicedMode(){if(!this._default9SlicedMaterialSlicedMode){let t=this.defaultMaterial.clone();t.nineSlicedMode=It,t.update(),this._default9SlicedMaterialSlicedMode=t}return this._default9SlicedMaterialSlicedMode}set default9SlicedMaterialTiledMode(t){this._default9SlicedMaterialTiledMode=t}get default9SlicedMaterialTiledMode(){if(!this._default9SlicedMaterialTiledMode){let t=this.defaultMaterial.clone();t.nineSlicedMode=Rt,t.update(),this._default9SlicedMaterialTiledMode=t}return this._default9SlicedMaterialTiledMode}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this),this._defaultTexture&&(this._defaultTexture.destroy(),this._defaultTexture=null)}initializeComponentData(t,e,s){if(e.enabled!==void 0&&(t.enabled=e.enabled),t.type=e.type,e.layers&&Array.isArray(e.layers)&&(t.layers=e.layers.slice(0)),e.drawOrder!==void 0&&(t.drawOrder=e.drawOrder),e.color!==void 0&&(e.color instanceof F?t.color.set(e.color.r,e.color.g,e.color.b,e.opacity??1):t.color.set(e.color[0],e.color[1],e.color[2],e.opacity??1),t.color=t.color),e.opacity!==void 0&&(t.opacity=e.opacity),e.flipX!==void 0&&(t.flipX=e.flipX),e.flipY!==void 0&&(t.flipY=e.flipY),e.width!==void 0&&(t.width=e.width),e.height!==void 0&&(t.height=e.height),e.spriteAsset!==void 0&&(t.spriteAsset=e.spriteAsset),e.sprite&&(t.sprite=e.sprite),e.frame!==void 0&&(t.frame=e.frame),e.clips)for(let i in e.clips)t.addClip(e.clips[i]);e.speed!==void 0&&(t.speed=e.speed),e.autoPlayClip&&(t.autoPlayClip=e.autoPlayClip),t.batchGroupId=e.batchGroupId===void 0||e.batchGroupId===null?-1:e.batchGroupId,super.initializeComponentData(t,e,s)}cloneComponent(t,e){let s=t.sprite;return this.addComponent(e,{enabled:s.enabled,type:s.type,spriteAsset:s.spriteAsset,sprite:s.sprite,width:s.width,height:s.height,frame:s.frame,color:s.color.clone(),opacity:s.opacity,flipX:s.flipX,flipY:s.flipY,speed:s.speed,clips:s.clips,autoPlayClip:s.autoPlayClip,batchGroupId:s.batchGroupId,drawOrder:s.drawOrder,layers:s.layers.slice(0)})}onUpdate(t){let e=this.store;for(let s in e)if(e.hasOwnProperty(s)){let i=e[s];if(i.data.enabled&&i.entity.enabled){let r=i.entity.sprite;r._currentClip&&r._currentClip._update(t)}}}onBeforeRemove(t,e){e.onDestroy()}};le._buildAccessors(Lr.prototype,Rk);var ro=class extends le{constructor(e,s){super(e,s);n(this,"_oldState",!0);n(this,"_size",new x);this.on("set_enabled",this._onSetEnabled,this)}set size(e){e instanceof x?this._size.copy(e):e instanceof Array&&e.length>=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<i;s++)if(this.effects[s].effect===t){e=s;break}e>=0&&(e>0?this.effects[e-1].outputTarget=e+1<this.effects.length?this.effects[e+1].inputTarget:null:this.effects.length>1&&(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<e;t++){let s=this.effects[t].effect;this._newPostEffect!==s&&s.needsDepthBuffer&&this._requestDepthMap()}}_releaseDepthMaps(){for(let t=0,e=this.effects.length;t<e;t++)this.effects[t].effect.needsDepthBuffer&&this._releaseDepthMap()}_requestDepthMap(){let t=this.app.scene.layers.getLayerById(Zt);t&&(t.incrementCounter(),this.camera.requestSceneDepthMap(!0))}_releaseDepthMap(){let t=this.app.scene.layers.getLayerById(Zt);t&&(t.decrementCounter(),this.camera.requestSceneDepthMap(!1))}destroy(){for(let t=0,e=this.effects.length;t<e;t++)this.effects[t].inputTarget.destroy();this.effects.length=0,this.disable()}enable(){!this.enabled&&this.effects.length&&(this.enabled=!0,this._requestDepthMaps(),this.app.graphicsDevice.on("resizecanvas",this._onCanvasResized,this),this.destinationRenderTarget=this.camera.renderTarget,this.camera.renderTarget=this.effects[0].inputTarget,this.camera.onPostprocessing=()=>{if(this.enabled){let t=null,e=this.effects.length;if(e)for(let s=0;s<e;s++){let i=this.effects[s],r=i.outputTarget;s===e-1&&(t=this.camera.rect,this.destinationRenderTarget&&(r=this.destinationRenderTarget)),i.effect.render(i.inputTarget,r,t)}}})}disable(){this.enabled&&(this.enabled=!1,this.app.graphicsDevice.off("resizecanvas",this._onCanvasResized,this),this._releaseDepthMaps(),this._destroyOffscreenTarget(this._sourceTarget),this.camera.renderTarget=this.destinationRenderTarget,this.camera.onPostprocessing=null)}_onCanvasResized(t,e){let s=this.camera.rect,i=this.destinationRenderTarget;t=i?.width??t,e=i?.height??e,this.camera.camera.aspectRatio=t*s.z/(e*s.w),this.resizeRenderTargets()}resizeRenderTargets(){let t=this.app.graphicsDevice,e=this.destinationRenderTarget,s=e?.width??t.width,i=e?.height??t.height,r=this.camera.rect,a=Math.floor(r.z*s),o=Math.floor(r.w*i),l=this.effects;for(let h=0,f=l.length;h<f;h++){let u=l[h];(u.inputTarget.width!==a||u.inputTarget.height!==o)&&this._resizeOffscreenTarget(u.inputTarget)}}onCameraRectChanged(t,e,s){this.enabled&&this.resizeRenderTargets()}};var ar=class extends le{constructor(e,s){super(e,s);n(this,"onPostprocessing",null);n(this,"_renderSceneDepthMap",0);n(this,"_renderSceneColorMap",0);n(this,"_sceneDepthMapRequested",!1);n(this,"_sceneColorMapRequested",!1);n(this,"_priority",0);n(this,"_disablePostEffectsLayer",Va);n(this,"_camera");n(this,"_evtLayersChanged",null);n(this,"_evtLayerAdded",null);n(this,"_evtLayerRemoved",null);this._camera=new Bs(e.app.graphicsDevice),this._camera.node=s,this._postEffects=new a_(e.app,this)}setShaderPass(e){let s=Ns.get(this.system.app.graphicsDevice),i=e?s.allocate(e,{isForward:!0}):null;return this._camera.shaderPassInfo=i,i.index}getShaderPass(){return this._camera.shaderPassInfo?.name}set framePasses(e){this._camera.framePasses=e||[],this.dirtyLayerCompositionCameras(),this.system.app.scene.updateShaders=!0}get framePasses(){return this._camera.framePasses}set renderPasses(e){this.framePasses=e}get renderPasses(){return this.framePasses}get shaderParams(){return this._camera.shaderParams}set gammaCorrection(e){this.camera.shaderParams.gammaCorrection=e}get gammaCorrection(){return this.camera.shaderParams.gammaCorrection}set toneMapping(e){this.camera.shaderParams.toneMapping=e}get toneMapping(){return this.camera.shaderParams.toneMapping}set fog(e){this._camera.fogParams=e}get fog(){return this._camera.fogParams}set aperture(e){this._camera.aperture=e}get aperture(){return this._camera.aperture}set aspectRatio(e){this._camera.aspectRatio=e}get aspectRatio(){return this._camera.aspectRatio}set aspectRatioMode(e){this._camera.aspectRatioMode=e}get aspectRatioMode(){return this._camera.aspectRatioMode}set calculateProjection(e){this._camera.calculateProjection=e}get calculateProjection(){return this._camera.calculateProjection}set calculateTransform(e){this._camera.calculateTransform=e}get calculateTransform(){return this._camera.calculateTransform}get camera(){return this._camera}set clearColor(e){this._camera.clearColor=e}get clearColor(){return this._camera.clearColor}set clearColorBuffer(e){this._camera.clearColorBuffer=e,this.dirtyLayerCompositionCameras()}get clearColorBuffer(){return this._camera.clearColorBuffer}set clearDepth(e){this._camera.clearDepth=e}get clearDepth(){return this._camera.clearDepth}set clearDepthBuffer(e){this._camera.clearDepthBuffer=e,this.dirtyLayerCompositionCameras()}get clearDepthBuffer(){return this._camera.clearDepthBuffer}set clearStencilBuffer(e){this._camera.clearStencilBuffer=e,this.dirtyLayerCompositionCameras()}get clearStencilBuffer(){return this._camera.clearStencilBuffer}set cullFaces(e){this._camera.cullFaces=e}get cullFaces(){return this._camera.cullFaces}set disablePostEffectsLayer(e){this._disablePostEffectsLayer=e,this.dirtyLayerCompositionCameras()}get disablePostEffectsLayer(){return this._disablePostEffectsLayer}set farClip(e){this._camera.farClip=e}get farClip(){return this._camera.farClip}set flipFaces(e){this._camera.flipFaces=e}get flipFaces(){return this._camera.flipFaces}set fov(e){this._camera.fov=e}get fov(){return this._camera.fov}get frustum(){return this._camera.frustum}set frustumCulling(e){this._camera.frustumCulling=e}get frustumCulling(){return this._camera.frustumCulling}set horizontalFov(e){this._camera.horizontalFov=e}get horizontalFov(){return this._camera.horizontalFov}set layers(e){let s=this._camera.layers,i=this.system.app.scene;s.forEach(r=>{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<e.length;s++){let i=this.system.app.scene.layers.getLayerById(e[s]);i&&i.addCamera(this)}}removeCameraFromLayers(){let e=this.layers;for(let s=0;s<e.length;s++){let i=this.system.app.scene.layers.getLayerById(e[s]);i&&i.removeCamera(this)}}onLayersChanged(e,s){this.addCameraToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),s.on("add",this.onLayerAdded,this),s.on("remove",this.onLayerRemoved,this)}onLayerAdded(e){this.layers.indexOf(e.id)<0||e.addCamera(this)}onLayerRemoved(e){this.layers.indexOf(e.id)<0||e.removeCamera(this)}onEnable(){let e=this.system.app.scene,s=e.layers;this.system.addCamera(this),this._evtLayersChanged?.off(),this._evtLayersChanged=e.on("set:layers",this.onLayersChanged,this),s&&(this._evtLayerAdded?.off(),this._evtLayerAdded=s.on("add",this.onLayerAdded,this),this._evtLayerRemoved?.off(),this._evtLayerRemoved=s.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&this.addCameraToLayers(),this.postEffects.enable()}onDisable(){let s=this.system.app.scene.layers;this.postEffects.disable(),this.removeCameraFromLayers(),this._evtLayersChanged?.off(),this._evtLayersChanged=null,s&&(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){return this._camera.calculateAspectRatio(e)}frameUpdate(e){this.aspectRatioMode===Ac&&(this.aspectRatio=this.calculateAspectRatio(e))}startXr(e,s,i){this.system.app.xr.start(this,e,s,i)}endXr(e){if(!this._camera.xr){e&&e(new 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}};var iE=class{constructor(){n(this,"enabled",!0)}};var Dk=["enabled"],o_=class extends Fe{constructor(e){super(e);n(this,"cameras",[]);this.id="camera",this.ComponentType=ar,this.DataType=iE,this.schema=Dk,this.on("beforeremove",this.onBeforeRemove,this),this.app.on("prerender",this.onAppPrerender,this)}initializeComponentData(e,s,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 r=0;r<i.length;r++){let a=i[r];if(s.hasOwnProperty(a)){let o=s[a];switch(a){case"rect":case"scissorRect":Array.isArray(o)?e[a]=new Q(o[0],o[1],o[2],o[3]):e[a]=o;break;case"clearColor":Array.isArray(o)?e[a]=new F(o[0],o[1],o[2],o[3]):e[a]=o;break;default:e[a]=o;break}}}super.initializeComponentData(e,s,["enabled"])}cloneComponent(e,s){let i=e.camera;return this.addComponent(s,{aspectRatio:i.aspectRatio,aspectRatioMode:i.aspectRatioMode,calculateProjection:i.calculateProjection,calculateTransform:i.calculateTransform,clearColor:i.clearColor,clearColorBuffer:i.clearColorBuffer,clearDepthBuffer:i.clearDepthBuffer,clearStencilBuffer:i.clearStencilBuffer,renderSceneDepthMap:i.renderSceneDepthMap,renderSceneColorMap:i.renderSceneColorMap,cullFaces:i.cullFaces,enabled:i.enabled,farClip:i.farClip,flipFaces:i.flipFaces,fov:i.fov,frustumCulling:i.frustumCulling,horizontalFov:i.horizontalFov,layers:i.layers,renderTarget:i.renderTarget,nearClip:i.nearClip,orthoHeight:i.orthoHeight,projection:i.projection,priority:i.priority,rect:i.rect,scissorRect:i.scissorRect,aperture:i.aperture,sensitivity:i.sensitivity,shutter:i.shutter,gammaCorrection:i.gammaCorrection,toneMapping:i.toneMapping})}onBeforeRemove(e,s){this.removeCamera(s),s.onRemove()}onAppPrerender(){for(let e=0,s=this.cameras.length;e<s;e++)this.cameras[e].onAppPrerender()}addCamera(e){this.cameras.push(e),Uc(this.cameras)}removeCamera(e){let s=this.cameras.indexOf(e);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<s.length;i++){let r=this.system.app.scene.layers.getLayerById(s[i]);r&&(r.removeLight(this),this._light.removeLayer(r))}this._layers=e;for(let i=0;i<e.length;i++){let r=this.system.app.scene.layers.getLayerById(e[i]);r&&this.enabled&&this.entity.enabled&&(r.addLight(this),this._light.addLayer(r))}}get layers(){return this._layers}set shadowUpdateOverrides(e){this._light.shadowUpdateOverrides=e}get shadowUpdateOverrides(){return this._light.shadowUpdateOverrides}set shadowSamples(e){this._light.shadowSamples=e}get shadowSamples(){return this._light.shadowSamples}set shadowBlockerSamples(e){this._light.shadowBlockerSamples=e}get shadowBlockerSamples(){return this._light.shadowBlockerSamples}set penumbraSize(e){this._light.penumbraSize=e}get penumbraSize(){return this._light.penumbraSize}set penumbraFalloff(e){this._light.penumbraFalloff=e}get penumbraFalloff(){return this._light.penumbraFalloff}addLightToLayers(){for(let e=0;e<this._layers.length;e++){let s=this.system.app.scene.layers.getLayerById(this._layers[e]);s&&(s.addLight(this),this._light.addLayer(s))}}removeLightFromLayers(){for(let e=0;e<this._layers.length;e++){let s=this.system.app.scene.layers.getLayerById(this._layers[e]);s&&(s.removeLight(this),this._light.removeLayer(s))}}onLayersChanged(e,s){this.enabled&&this.entity.enabled&&this.addLightToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),s.on("add",this.onLayerAdded,this),s.on("remove",this.onLayerRemoved,this)}onLayerAdded(e){this._layers.indexOf(e.id)>=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<Iu.length;e++){let s=Iu[e];this[s]=this[s]}this.enabled&&this.entity.enabled&&this.onEnable()}onCookieAssetSet(){let e=!1;this._cookieAsset.type==="cubemap"&&!this._cookieAsset.loadFaces&&(this._cookieAsset.loadFaces=!0,e=!0),(!this._cookieAsset.resource||e)&&this.system.app.assets.load(this._cookieAsset),this._cookieAsset.resource&&this.onCookieAssetLoad()}onCookieAssetAdd(e){this._cookieAssetId===e.id&&(this._cookieAsset=e,this._light.enabled&&this.onCookieAssetSet(),this._cookieAsset.on("load",this.onCookieAssetLoad,this),this._cookieAsset.on("remove",this.onCookieAssetRemove,this))}onCookieAssetLoad(){!this._cookieAsset||!this._cookieAsset.resource||(this.cookie=this._cookieAsset.resource)}onCookieAssetRemove(){this._cookieAssetId&&(this._cookieAssetAdd&&(this.system.app.assets.off(`add:${this._cookieAssetId}`,this.onCookieAssetAdd,this),this._cookieAssetAdd=!1),this._cookieAsset&&(this._cookieAsset.off("load",this.onCookieAssetLoad,this),this._cookieAsset.off("remove",this.onCookieAssetRemove,this),this._cookieAsset=null),this.cookie=null)}onEnable(){let e=this.system.app.scene,s=e.layers;this._light.enabled=!0,this._evtLayersChanged?.off(),this._evtLayersChanged=e.on("set:layers",this.onLayersChanged,this),s&&(this._evtLayerAdded?.off(),this._evtLayerAdded=s.on("add",this.onLayerAdded,this),this._evtLayerRemoved?.off(),this._evtLayerRemoved=s.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&this.addLightToLayers(),this._cookieAsset&&!this.cookie&&this.onCookieAssetSet()}onDisable(){let s=this.system.app.scene.layers;this._light.enabled=!1,this._evtLayersChanged?.off(),this._evtLayersChanged=null,s&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this.removeLightFromLayers()}onRemove(){this.onDisable(),this._light.destroy(),this.cookieAsset=null}};var rE=class{constructor(){n(this,"enabled",!0)}};var Lk=["enabled"],n_=class extends Fe{constructor(t){super(t),this.id="light",this.ComponentType=Ru,this.DataType=rE,this.schema=Lk,this.on("beforeremove",this._onRemoveComponent,this)}initializeComponentData(t,e){let s={...e};s.layers&&Array.isArray(s.layers)&&(s.layers=s.layers.slice(0)),s.color&&Array.isArray(s.color)&&(s.color=new F(s.color[0],s.color[1],s.color[2])),s.cookieOffset&&s.cookieOffset instanceof Array&&(s.cookieOffset=new B(s.cookieOffset[0],s.cookieOffset[1])),s.cookieScale&&s.cookieScale instanceof Array&&(s.cookieScale=new B(s.cookieScale[0],s.cookieScale[1])),s.hasOwnProperty("enable")&&(s.enabled=s.enable);for(let i=0;i<Iu.length;i++){let r=Iu[i];s.hasOwnProperty(r)&&(t[r]=s[r])}super.initializeComponentData(t,s,["enabled"])}_onRemoveComponent(t,e){e.onRemove()}cloneComponent(t,e){let s=t.light,i={enabled:s.enabled};for(let r=0;r<Iu.length;r++){let a=Iu[r],o=s[a];o&&o.clone?i[a]=o.clone():i[a]=o}return this.addComponent(e,i)}};le._buildAccessors(Ru.prototype,Lk);var vK=["x","y","z","w"],TK=[void 0,void 0,B,x,Q];function c_(c,t,e,s){switch(t.type){case"boolean":return!!e;case"number":if(typeof e=="number")return e;if(typeof e=="string"){let i=parseInt(e,10);return isNaN(i)?null:i}else if(typeof e=="boolean")return 0+e;return null;case"json":{let i={};if(Array.isArray(t.schema)){(!e||typeof e!="object")&&(e={});for(let r=0;r<t.schema.length;r++){let a=t.schema[r];if(a.name)if(a.array){i[a.name]=[];let o=Array.isArray(e[a.name])?e[a.name]:[];for(let l=0;l<o.length;l++)i[a.name].push(c_(c,a,o[l]))}else{let o=e.hasOwnProperty(a.name)?e[a.name]:a.default;i[a.name]=c_(c,a,o)}}}return i}case"asset":return e instanceof ae?e:typeof e=="number"?c.assets.get(e)||null:typeof e=="string"&&c.assets.get(parseInt(e,10))||null;case"entity":return e instanceof Pe?e:typeof e=="string"?c.getEntityFromIndex(e):null;case"rgb":case"rgba":if(e instanceof F)return s instanceof F?(s.copy(e),s):e.clone();if(e instanceof Array&&e.length>=3&&e.length<=4){for(let i=0;i<e.length;i++)if(typeof e[i]!="number")return null;return s||(s=new F),s.r=e[0],s.g=e[1],s.b=e[2],s.a=e.length===3?1:e[3],s}else if(typeof e=="string"&&/#(?:[0-9a-f]{2}){3,4}/i.test(e))return s||(s=new F),s.fromString(e),s;return null;case"vec2":case"vec3":case"vec4":{let i=parseInt(t.type.slice(3),10),r=TK[i];if(e instanceof r)return s instanceof r?(s.copy(e),s):e.clone();if(e instanceof Array&&e.length===i){for(let a=0;a<e.length;a++)if(typeof e[a]!="number")return null;s||(s=new r);for(let a=0;a<i;a++)s[vK[a]]=e[a];return s}return null}case"curve":if(e){let i;if(e instanceof Ps||e instanceof ki)i=e.clone();else{let r=e.keys[0]instanceof Array?ki:Ps;i=new r(e.keys),i.type=e.type}return i}break}return e}function Mk(c,t,e,s){return t.array?e.map((i,r)=>c_(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<h;l++)this.__attributes[t].push(c_(this.app,e,s[l],a?a[l]:null))}else this.__attributes[t]=c_(this.app,e,s,a);this.fire(i,t,this.__attributes[t],o),this.fire(r,this.__attributes[t],o)}})))}remove(t){return this.index[t]?(delete this.index[t],delete this.scriptType.prototype[t],!0):!1}has(t){return!!this.index[t]}get(t){return this.index[t]||null}};n(l_,"assignAttributesToScript",bR),n(l_,"attributeToValue",Mk),n(l_,"reservedNames",new Set(["app","entity","enabled","_enabled","_enabledOld","_destroyed","__attributes","__attributesRaw","__scriptType","__executionOrder","_callbacks","_callbackActive","has","get","on","off","fire","once","hasEvent"]));var ao=l_;var Mr=class extends ks{constructor(e){super(e);n(this,"__attributes");n(this,"__attributesRaw");this.initScriptType(e)}static get attributes(){return this.hasOwnProperty("__attributes")||(this.__attributes=new ao(this)),this.__attributes}initScript(e){ks.prototype.initScript.call(this,e),this.__attributes={},this.__attributesRaw=e.attributes||{}}initScriptType(e){this.initScript(e)}__initializeAttributes(e){if(!(!e&&!this.__attributesRaw)){for(let s in this.__scriptType.attributes.index)this.__attributesRaw&&this.__attributesRaw.hasOwnProperty(s)?this[s]=this.__attributesRaw[s]:this.__attributes.hasOwnProperty(s)||(this.__scriptType.attributes.index[s].hasOwnProperty("default")?this[s]=this.__scriptType.attributes.index[s].default:this[s]=null);this.__attributesRaw=null}}static extend(e){for(let s in e)e.hasOwnProperty(s)&&(this.prototype[s]=e[s])}};var or=class extends le{constructor(e,s){super(e,s);n(this,"_attributeDataMap",new Map);this._scripts=[],this._updateList=new po({sortBy:"__executionOrder"}),this._postUpdateList=new po({sortBy:"__executionOrder"}),this._scriptsIndex={},this._destroyedScripts=[],this._destroyed=!1,this._scriptsData=null,this._oldState=!0,this._enabled=!0,this._beingEnabled=!1,this._isLoopingThroughScripts=!1,this._executionOrder=-1,this.on("set_enabled",this._onSetEnabled,this)}set scripts(e){this._scriptsData=e;for(let s in e){if(!e.hasOwnProperty(s))continue;let i=this._scriptsIndex[s];if(i&&(typeof e[s].enabled=="boolean"&&(i.once("preInitialize",()=>{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<i;s++){let r=this.scripts[s];r._initialized&&!r._postInitialized&&r.enabled&&(r._postInitialized=!0,r.postInitialize&&this._scriptMethod(r,RS))}this._endLooping(e)}_beginLooping(){let e=this._isLoopingThroughScripts;return this._isLoopingThroughScripts=!0,e}_endLooping(e){this._isLoopingThroughScripts=e,this._isLoopingThroughScripts||this._removeDestroyedScripts()}_onSetEnabled(e,s,i){this._beingEnabled=!0,this._checkState(),this._beingEnabled=!1}_checkState(){let e=this.enabled&&this.entity.enabled;if(e===this._oldState)return;this._oldState=e,this.fire(e?"enable":"disable"),this.fire("state",e),e?this.system._addComponentToEnabled(this):this.system._removeComponentFromEnabled(this);let s=this._beginLooping();for(let i=0,r=this.scripts.length;i<r;i++){let a=this.scripts[i];a.once("preInitialize",()=>{this.initializeAttributes(a)}),a.enabled=a._enabled}this._endLooping(s)}_onBeforeRemove(){this.fire("remove");let e=this._beginLooping();for(let s=0;s<this.scripts.length;s++){let i=this.scripts[s];i&&this.destroy(i.__scriptType.__name)}this._endLooping(e)}_removeDestroyedScripts(){let e=this._destroyedScripts.length;if(e){for(let s=0;s<e;s++){let i=this._destroyedScripts[s];this._removeScriptInstance(i)}this._destroyedScripts.length=0,this._resetExecutionOrder(0,this._scripts.length)}}_onInitializeAttributes(){for(let e=0,s=this.scripts.length;e<s;e++){let i=this.scripts[e];this.initializeAttributes(i)}}initializeAttributes(e){if(e instanceof Mr)e.__initializeAttributes();else{let s=e.__scriptType.__name,i=this._attributeDataMap.get(s);if(!i)return;let r=this.system.app.scripts?.getSchema(s);bR(this.system.app,r.attributes,i,e)}}_scriptMethod(e,s,i){e[s](i)}_onInitialize(){let e=this._scripts,s=this._beginLooping();for(let i=0,r=e.length;i<r;i++){let a=e[i];!a._initialized&&a.enabled&&(a._initialized=!0,a.initialize&&this._scriptMethod(a,IS))}this._endLooping(s)}_onPostInitialize(){this.onPostStateChange()}_onUpdate(e){let s=this._updateList;if(!s.length)return;let i=this._beginLooping();for(s.loopIndex=0;s.loopIndex<s.length;s.loopIndex++){let r=s.items[s.loopIndex];r.enabled&&this._scriptMethod(r,C2,e)}this._endLooping(i)}_onPostUpdate(e){let s=this._postUpdateList;if(!s.length)return;let i=this._beginLooping();for(s.loopIndex=0;s.loopIndex<s.length;s.loopIndex++){let r=s.items[s.loopIndex];r.enabled&&this._scriptMethod(r,P2,e)}this._endLooping(i)}_insertScriptInstance(e,s,i){s===-1?(this._scripts.push(e),e.__executionOrder=i,e.update&&this._updateList.append(e),e.postUpdate&&this._postUpdateList.append(e)):(this._scripts.splice(s,0,e),e.__executionOrder=s,this._resetExecutionOrder(s+1,i+1),e.update&&this._updateList.insert(e),e.postUpdate&&this._postUpdateList.insert(e))}_removeScriptInstance(e){let s=this._scripts.indexOf(e);return s===-1||(this._scripts.splice(s,1),e.update&&this._updateList.remove(e),e.postUpdate&&this._postUpdateList.remove(e)),s}_resetExecutionOrder(e,s){for(let i=e;i<s;i++)this._scripts[i].__executionOrder=i}_resolveEntityScriptAttribute(e,s,i,r,a,o){if(e.array){let l=i.length;if(!l)return;let h=i.slice();for(let f=0;f<l;f++){let u=h[f]instanceof Ne?h[f].guid:h[f];o[u]&&(h[f]=r?o[u].guid:o[u])}a[s]=h}else{if(i instanceof Ne)i=i.guid;else if(typeof i!="string")return;o[i]&&(a[s]=o[i])}}has(e){if(typeof e=="string")return!!this._scriptsIndex[e];if(!e)return!1;let s=e,i=s.__name,r=this._scriptsIndex[i];return(r&&r.instance)instanceof s}get(e){if(typeof e=="string"){let o=this._scriptsIndex[e];return o?o.instance:null}if(!e)return null;let s=e,i=s.__name,r=this._scriptsIndex[i],a=r&&r.instance;return a instanceof s?a:null}create(e,s={}){let i=this,r=e,a=e;if(typeof r=="string")r=this.system.app.scripts.get(r);else if(r){let o=r0(r),l=Object.prototype.hasOwnProperty.call(r,"scriptName")&&r.scriptName;if(r.prototype instanceof Mr,Object.prototype.hasOwnProperty.call(r,"__name")||(r.__name=Qc(r)),a=r.__name,!a)return null}if(r){if(!this._scriptsIndex[a]||!this._scriptsIndex[a].instance){let o=new r({app:this.system.app,entity:this.entity,enabled:s.hasOwnProperty("enabled")?s.enabled:!0,attributes:s.attributes||{}});s.properties&&typeof s.properties=="object"&&Object.assign(o,s.properties),!(o instanceof Mr)&&s.attributes&&this._attributeDataMap.set(a,{...s.attributes});let l=this._scripts.length,h=-1;return typeof s.ind=="number"&&s.ind!==-1&&l>s.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<p.schema.length;S++){let g=p.schema[S];if(g.type==="entity")if(p.array)for(let T=0;T<m.length;T++)this._resolveEntityScriptAttribute(g,g.name,m[T][g.name],f,_[T],s);else this._resolveEntityScriptAttribute(g,g.name,m[g.name],f,_,s)}}}}}}move(e,s){let i=this._scripts.length;if(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<e.order.length;s++)t.create(e.order[s],{enabled:e.scripts[e.order[s]].enabled,attributes:e.scripts[e.order[s]].attributes,preloading:this.preloading})}}cloneComponent(t,e){let s=[],i={};for(let a=0;a<t.script._scripts.length;a++){let o=t.script._scripts[a],l=o.__scriptType.__name;s.push(l);let h=t.script._attributeDataMap?.get(l)||{};for(let f in o.__attributes)h[f]=o.__attributes[f];i[l]={enabled:o._enabled,attributes:h}}for(let a in t.script._scriptsIndex)a.awaiting&&s.splice(a.ind,0,a);let r={enabled:t.script.enabled,order:s,scripts:i};return this.addComponent(e,r)}_resetExecutionOrder(){oE=0;for(let t=0,e=this._components.length;t<e;t++)this._components.items[t]._executionOrder=oE++}_callComponentMethod(t,e,s){for(t.loopIndex=0;t.loopIndex<t.length;t.loopIndex++)t.items[t.loopIndex][e](s)}_onInitialize(){this.preloading=!1,this._callComponentMethod(this._components,yK),this._callComponentMethod(this._enabledComponents,EK)}_onPostInitialize(){this._callComponentMethod(this._enabledComponents,AK)}_onUpdate(t){this._callComponentMethod(this._enabledComponents,CK,t)}_onPostUpdate(t){this._callComponentMethod(this._enabledComponents,PK,t)}_addComponentToEnabled(t){this._enabledComponents.insert(t)}_removeComponentFromEnabled(t){this._enabledComponents.remove(t)}_onBeforeRemove(t,e){this._components.items.indexOf(e)>=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.activeSplats<s&&(this.intervals[0]=0,this.intervals[1]=this.activeSplats)}}appendSubDraws(t,e,s,i,r,a){let o=i,l=r/a|0,h=r%a;if(h>0){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.length<r&&(DR=new Uint32Array(r));let a=DR,o=0;for(let u=0;u<s;u++)o=this.appendSubDraws(a,o,e[u*2],e[u*2+1]-e[u*2],this.intervalOffsets[u],t);this.subDrawCount=o;let{x:l,y:h}=gt.calcTextureSize(o,wK);this.subDrawTexture=Z.createDataTexture2D(this.device,"subDrawData",l,h,At),this.subDrawTexture.lock().set(a.subarray(0,o*4)),this.subDrawTexture.unlock()}update(){let t=this.node.getWorldTransform(),e=!this.previousWorldTransform.equals(t);e&&this.previousWorldTransform.copy(t);let s=this._consumeRenderDirty?this._consumeRenderDirty():!1;return e||s}writeBoundsSpheres(t,e){if(this.octreeNodes)for(let s=0;s<this.octreeNodes.length;s++){let i=this.octreeNodes[s].boundingSphere;t[e++]=i.x,t[e++]=i.y,t[e++]=i.z,t[e++]=i.w}else{let s=this.resource.aabb,i=s.halfExtents,r=Math.sqrt(i.x*i.x+i.y*i.y+i.z*i.z);t[e++]=s.center.x,t[e++]=s.center.y,t[e++]=s.center.z,t[e++]=r}}get hasSphericalHarmonics(){return this.resource.gsplatData?.shBands>0}};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<l;y++)h[y]=E[y*2],f[y]=E[y*2+1];h[l]=h[l-1]+f[l-1],f[l]=0},p=(E,y,P,A,w,I,D)=>{let{ids:O,intervals:G}=I,M=l/P,H=0;for(let U=0;U<E.length;U++){let L=E[U],b=O[U],N=t.get(b),k=G[U].length>0?G[U]:[0,N.length/3];for(let z=0;z<k.length;z+=2){let V=k[z]*3,q=k[z+1]*3;H=D(N,L,V,q,H,M,y,P,A,w)}}},m=(E,y,P,A,w,I)=>{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<M;Ve+=3){let Lt=D[Ve],Vs=D[Ve+1],ds=D[Ve+2],di=(Lt*oe+Vs*be+ds*qe+ot)*U,Qu=di>>>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<M;j+=3){let oe=D[j]-q,be=D[j+1]-re,qe=D[j+2]-te,ot=oe*oe+be*be+qe*qe,Ve=Math.sqrt(ot)*V,Vs=(b-Ve)*U,ds=Vs>>>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<E;D++)y[D]+=y[D-1];y[E-1]!==P&&!o&&(o=!0);for(let D=0;D<P;D++){let O=A[D],G=--y[O];w[G]=r[D]}},g=E=>{let y=1/0,P=-1/0;for(let A=0;A<E.length;A++){let w=E[A],{transformedDirection:I,offset:D,scale:O,aabbMin:G,aabbMax:M}=w,H=I.x,U=I.y,L=I.z,b=H>=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);be<y&&(y=be),qe>P&&(P=qe)}return y===1/0&&(y=0,P=0),{minDist:y,maxDist:P}},T=E=>{let y=-1/0;for(let A=0;A<E.length;A++){let w=E[A],{transformedPosition:I,scale:D,aabbMin:O,aabbMax:G}=w,M=I.x,H=I.y,U=I.z;for(let L=0;L<8;L++){let b=L&1?G[0]:O[0],N=L&2?G[1]:O[1],k=L&4?G[2]:O[2],z=b-M,V=N-H,q=k-U,re=z*z+V*V+q*q,te=Math.sqrt(re)*D;te>y&&(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.length<w)&&(r=new Uint32Array(w));let I=0;for(let D=0;D<y.length;D++){let O=t.get(y[D]),G=P[D],M=A[D].length>0?A[D]:[0,O.length/3];for(let H=0;H<M.length;H+=2){let U=G[H/2],L=M[H+1]-M[H];for(let b=0;b<L;b++)r[I++]=U++}}};c.addEventListener("message",E=>{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;s<t;s++){let i=1;for(let r=0;r<e.length;r++)if(s<=e[r].maxDistance){i=e[r].weight;break}this.weightByDistance[s]=i}this.lastCameraBin=-1,this.lastBucketCount=-1}static computeCameraBin(t,e,s){let i=c.NUM_BINS;if(t)return i-1;let a=-e/s*i;return Math.max(0,Math.min(i-1,Math.floor(a)))}compute(t,e){if(t===this.lastCameraBin&&e===this.lastBucketCount)return this.binWeights;this.lastCameraBin=t,this.lastBucketCount=e;let s=c.NUM_BINS,i=this.bitsPerBin;for(let o=0;o<s;o++){let l=Math.abs(o-t);i[o]=this.weightByDistance[l]}let r=0;for(let o=0;o<s;o++)r+=i[o];let a=0;for(let o=0;o<s;o++){let l=Math.max(1,Math.floor(i[o]/r*e));this.binWeights[o*2]=a,this.binWeights[o*2+1]=l,a+=l}if(a>e){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"
#include "fogPS"
#if FOG != NONE && !defined(GSPLAT_NO_FOG)
#define GSPLAT_FOG
#endif
fn prepareOutputFromGamma(gammaColor: vec3f, depth: f32) -> vec3f {
var color = gammaColor;
#if TONEMAP != NONE || GAMMA == NONE || defined(GSPLAT_FOG)
color = decodeGamma3(color);
#endif
#ifdef GSPLAT_FOG
color = addFog(color, depth);
#endif
#if TONEMAP != NONE
color = toneMap(color);
#endif
#if TONEMAP != NONE || (GAMMA != NONE && defined(GSPLAT_FOG))
color = gammaCorrectOutput(color);
#endif
return color;
}
`;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<storage, read> sortElementCount: array<u32>;
@group(0) @binding(1) var<storage, read_write> dispatchArgs: array<u32>;
@compute @workgroup_size(1)
fn main() {
let count = sortElementCount[0];
let maxDim = {MAX_DIM}u;
let countWg = (count + {SPLATS_PER_WG_MINUS_1}u) / {SPLATS_PER_WG}u;
if (countWg <= maxDim) {
dispatchArgs[0] = countWg;
dispatchArgs[1] = 1u;
} else {
let y = (countWg + maxDim - 1u) / maxDim;
let x = (countWg + y - 1u) / y;
dispatchArgs[0] = x;
dispatchArgs[1] = y;
}
dispatchArgs[2] = 1u;
let placeWg = (count + 255u) / 256u;
if (placeWg <= maxDim) {
dispatchArgs[3] = placeWg;
dispatchArgs[4] = 1u;
} else {
let y = (placeWg + maxDim - 1u) / maxDim;
let x = (placeWg + y - 1u) / y;
dispatchArgs[3] = x;
dispatchArgs[4] = y;
}
dispatchArgs[5] = 1u;
}
`;var Bk=`
@group(0) @binding(0) var<storage, read> countersBuffer: array<u32>;
@group(0) @binding(1) var<storage, read_write> dispatchArgs: array<u32>;
@group(0) @binding(2) var<storage, read> largeSplatIds: array<u32>;
@compute @workgroup_size(1)
fn main() {
let count = min(countersBuffer[1], arrayLength(&largeSplatIds));
let maxDim = {MAX_DIM}u;
if (count <= maxDim) {
dispatchArgs[0] = count;
dispatchArgs[1] = 1u;
} else {
let y = (count + maxDim - 1u) / maxDim;
let x = (count + y - 1u) / y;
dispatchArgs[0] = x;
dispatchArgs[1] = y;
}
dispatchArgs[2] = 1u;
}
`;var Uk=`
#include "gsplatCommonCS"
#include "gsplatTileIntersectCS"
const MAX_TILE_ENTRIES: u32 = 0xFFFFu;
const BITMASK_W: u32 = 8u;
const BITMASK_H: u32 = 4u;
const LARGE_AABB_THRESHOLD: u32 = 64u;
@group(0) @binding(0) var<storage, read> compactedSplatIds: array<u32>;
@group(0) @binding(1) var<storage, read> sortElementCount: array<u32>;
@group(0) @binding(2) var<storage, read_write> projCache: array<u32>;
@group(0) @binding(3) var<storage, read_write> tileSplatCounts: array<atomic<u32>>;
struct Uniforms {
splatTextureSize: u32,
numTilesX: u32,
numTilesY: u32,
viewProj: mat4x4f,
viewMatrix: mat4x4f,
focal: f32,
viewportWidth: f32,
viewportHeight: f32,
nearClip: f32,
farClip: f32,
minPixelSize: f32,
isOrtho: u32,
exposure: f32,
alphaClip: f32,
minContribution: f32,
#ifdef GSPLAT_FISHEYE
fisheye_k: f32,
fisheye_inv_k: f32,
fisheye_projMat00: f32,
fisheye_projMat11: f32,
#endif
}
@group(0) @binding(4) var<uniform> uniforms: Uniforms;
@group(0) @binding(5) var<storage, read_write> pairBuffer: array<u32>;
@group(0) @binding(6) var<storage, read_write> countersBuffer: array<atomic<u32>>;
@group(0) @binding(7) var<storage, read_write> splatPairStart: array<u32>;
@group(0) @binding(8) var<storage, read_write> splatPairCount: array<u32>;
@group(0) @binding(9) var<storage, read_write> largeSplatIds: array<u32>;
@group(0) @binding(10) var<storage, read_write> depthBuffer: array<u32>;
#include "gsplatComputeSplatCS"
#include "gsplatFormatDeclCS"
#include "gsplatFormatReadCS"
#include "gsplatProjectCommonCS"
@compute @workgroup_size(256)
fn main(
@builtin(global_invocation_id) gid: vec3u,
@builtin(num_workgroups) numWorkgroups: vec3u
) {
let threadIdx = gid.y * (numWorkgroups.x * 256u) + gid.x;
let numVisible = sortElementCount[0];
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) {
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}u;
projCache[base + 0u] = bitcast<u32>(proj.screen.x);
projCache[base + 1u] = bitcast<u32>(proj.screen.y);
projCache[base + 2u] = bitcast<u32>(cx);
projCache[base + 3u] = bitcast<u32>(cy);
projCache[base + 4u] = bitcast<u32>(cz);
#ifdef PICK_MODE
let pcIdVal = loadPcId().r;
projCache[base + 5u] = pcIdVal;
projCache[base + 6u] = pack2x16float(vec2f(0.0, opacity));
#else
let color = getColor();
var rgb = max(color, vec3f(0.0));
projCache[base + 5u] = pack2x16float(vec2f(rgb.x, rgb.y));
projCache[base + 6u] = pack2x16float(vec2f(rgb.z, opacity));
#endif
depthBuffer[threadIdx] = bitcast<u32>(proj.viewDepth);
let screen = proj.screen;
let eval = computeSplatTileEval(screen, cx, cy, cz, half(opacity),
uniforms.viewportWidth, uniforms.viewportHeight,
uniforms.alphaClip);
let radiusFactor = eval.radiusFactor;
projCache[base + 7u] = bitcast<u32>(-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))));
let maxTileY = min(i32(uniforms.numTilesY) - 1i, i32(floor(eval.splatMax.y / f32(TILE_SIZE))));
let aabbW = u32(maxTileX - minTileX + 1i);
var deferredToLarge = false;
if (maxTileX >= minTileX && maxTileY >= minTileY &&
aabbW * u32(maxTileY - minTileY + 1i) > LARGE_AABB_THRESHOLD) {
let idx = atomicAdd(&countersBuffer[1], 1u);
if (idx < arrayLength(&largeSplatIds)) {
largeSplatIds[idx] = threadIdx;
deferredToLarge = true;
}
}
if (deferredToLarge) {
splatPairStart[threadIdx] = 0u;
splatPairCount[threadIdx] = 0u;
return;
}
var myPairCount: u32 = 0u;
var bitmask: u32 = 0u;
if (minTileX == maxTileX && minTileY == maxTileY) {
myPairCount = 1u;
bitmask = 1u;
} else {
for (var ty = minTileY; ty <= maxTileY; ty++) {
for (var tx = minTileX; tx <= maxTileX; tx++) {
let tMin = vec2f(f32(tx) * f32(TILE_SIZE), f32(ty) * f32(TILE_SIZE));
let tMax = tMin + vec2f(f32(TILE_SIZE));
if (tileIntersectsEllipse(tMin, tMax, screen, cx, cy, cz, radiusFactor)) {
myPairCount++;
let localX = u32(tx - minTileX);
let localY = u32(ty - minTileY);
if (localX < BITMASK_W && localY < BITMASK_H) {
let bitIdx = localY * BITMASK_W + localX;
bitmask |= (1u << bitIdx);
}
}
}
}
}
if (myPairCount == 0u) {
splatPairStart[threadIdx] = 0u;
splatPairCount[threadIdx] = 0u;
return;
}
let pairBase = atomicAdd(&countersBuffer[0], myPairCount);
splatPairStart[threadIdx] = pairBase;
splatPairCount[threadIdx] = myPairCount;
var j: u32 = 0u;
for (var ty = minTileY; ty <= maxTileY; ty++) {
for (var tx = minTileX; tx <= maxTileX; tx++) {
let localX = u32(tx - minTileX);
let localY = u32(ty - minTileY);
var hits: bool;
if (localX < BITMASK_W && localY < BITMASK_H) {
let bitIdx = localY * BITMASK_W + localX;
hits = (bitmask & (1u << bitIdx)) != 0u;
} else {
let tMin = vec2f(f32(tx) * f32(TILE_SIZE), f32(ty) * f32(TILE_SIZE));
let tMax = tMin + vec2f(f32(TILE_SIZE));
hits = tileIntersectsEllipse(tMin, tMax, screen, cx, cy, cz, radiusFactor);
}
if (hits) {
let tileIdx = u32(ty) * uniforms.numTilesX + u32(tx);
let localOff = atomicAdd(&tileSplatCounts[tileIdx], 1u);
if (localOff < MAX_TILE_ENTRIES) {
pairBuffer[pairBase + j] = (tileIdx << 16u) | (localOff & 0xFFFFu);
j++;
}
}
}
}
if (j != myPairCount) {
splatPairCount[threadIdx] = j;
}
}
`;var kk=`
#include "gsplatCommonCS"
#include "gsplatTileIntersectCS"
const WG_SIZE: u32 = 256u;
const MAX_TILE_ENTRIES: u32 = 0xFFFFu;
@group(0) @binding(0) var<storage, read> projCache: array<u32>;
@group(0) @binding(1) var<storage, read_write> tileSplatCounts: array<atomic<u32>>;
@group(0) @binding(2) var<storage, read_write> pairBuffer: array<u32>;
@group(0) @binding(3) var<storage, read_write> countersBuffer: array<atomic<u32>>;
@group(0) @binding(4) var<storage, read_write> splatPairStart: array<u32>;
@group(0) @binding(5) var<storage, read_write> splatPairCount: array<u32>;
@group(0) @binding(6) var<storage, read> largeSplatIds: array<u32>;
struct Uniforms {
numTilesX: u32,
numTilesY: u32,
viewportWidth: f32,
viewportHeight: f32,
alphaClip: f32,
}
@group(0) @binding(7) var<uniform> uniforms: Uniforms;
var<workgroup> wgPairCounts: array<u32, WG_SIZE>;
var<workgroup> wgPairOffsets: array<u32, WG_SIZE>;
var<workgroup> wgBase: u32;
@compute @workgroup_size(256)
fn main(
@builtin(workgroup_id) wgId: vec3u,
@builtin(num_workgroups) numWorkgroups: vec3u,
@builtin(local_invocation_index) lid: u32
) {
let largeSplatIdx = wgId.y * numWorkgroups.x + wgId.x;
let count = min(atomicLoad(&countersBuffer[1]), arrayLength(&largeSplatIds));
let isActive = largeSplatIdx < count;
var threadIdx = u32(0);
var minTileX = 0i;
var maxTileX = 0i;
var minTileY = 0i;
var maxTileY = 0i;
var aabbW = u32(0);
var totalTiles = u32(0);
var screen = vec2f(0.0);
var cx = 0.0f;
var cy = 0.0f;
var cz = 0.0f;
var radiusFactor = 0.0f;
if (isActive) {
threadIdx = largeSplatIds[largeSplatIdx];
let cacheBase = threadIdx * {CACHE_STRIDE}u;
screen = vec2f(bitcast<f32>(projCache[cacheBase + 0u]), bitcast<f32>(projCache[cacheBase + 1u]));
cx = bitcast<f32>(projCache[cacheBase + 2u]);
cy = bitcast<f32>(projCache[cacheBase + 3u]);
cz = bitcast<f32>(projCache[cacheBase + 4u]);
let opacity = unpack2x16float(projCache[cacheBase + 6u]).y;
let eval = computeSplatTileEval(screen, cx, cy, cz, half(opacity),
uniforms.viewportWidth, uniforms.viewportHeight,
uniforms.alphaClip);
radiusFactor = eval.radiusFactor;
minTileX = max(0i, i32(floor(eval.splatMin.x / f32(TILE_SIZE))));
maxTileX = min(i32(uniforms.numTilesX) - 1i, i32(floor(eval.splatMax.x / f32(TILE_SIZE))));
minTileY = max(0i, i32(floor(eval.splatMin.y / f32(TILE_SIZE))));
maxTileY = min(i32(uniforms.numTilesY) - 1i, i32(floor(eval.splatMax.y / f32(TILE_SIZE))));
if (maxTileX >= minTileX && maxTileY >= minTileY) {
aabbW = u32(maxTileX - minTileX + 1i);
totalTiles = aabbW * u32(maxTileY - minTileY + 1i);
}
}
var myHitCount: u32 = 0u;
for (var i = lid; i < totalTiles; i += WG_SIZE) {
let localX = i % aabbW;
let localY = i / aabbW;
let tx = minTileX + i32(localX);
let ty = minTileY + i32(localY);
let tMin = vec2f(f32(tx) * f32(TILE_SIZE), f32(ty) * f32(TILE_SIZE));
let tMax = tMin + vec2f(f32(TILE_SIZE));
if (tileIntersectsEllipse(tMin, tMax, screen, cx, cy, cz, radiusFactor)) {
myHitCount++;
}
}
wgPairCounts[lid] = myHitCount;
workgroupBarrier();
if (lid == 0u && isActive) {
var sum: u32 = 0u;
for (var i: u32 = 0u; i < WG_SIZE; i++) {
wgPairOffsets[i] = sum;
sum += wgPairCounts[i];
}
if (sum > 0u) {
wgBase = atomicAdd(&countersBuffer[0], sum);
} else {
wgBase = 0u;
}
splatPairStart[threadIdx] = wgBase;
splatPairCount[threadIdx] = sum | 0x80000000u;
}
workgroupBarrier();
let myBase = wgBase + wgPairOffsets[lid];
var j: u32 = 0u;
for (var i = lid; i < totalTiles; i += WG_SIZE) {
let localX = i % aabbW;
let localY = i / aabbW;
let tx = minTileX + i32(localX);
let ty = minTileY + i32(localY);
let tMin = vec2f(f32(tx) * f32(TILE_SIZE), f32(ty) * f32(TILE_SIZE));
let tMax = tMin + vec2f(f32(TILE_SIZE));
if (tileIntersectsEllipse(tMin, tMax, screen, cx, cy, cz, radiusFactor)) {
let tileIdx = u32(ty) * uniforms.numTilesX + u32(tx);
let localOff = atomicAdd(&tileSplatCounts[tileIdx], 1u);
if (localOff < MAX_TILE_ENTRIES) {
pairBuffer[myBase + j] = (tileIdx << 16u) | (localOff & 0xFFFFu);
j++;
}
}
}
wgPairCounts[lid] = j;
workgroupBarrier();
if (lid == 0u && isActive) {
var actualTotal: u32 = 0u;
for (var i: u32 = 0u; i < WG_SIZE; i++) {
actualTotal += wgPairCounts[i];
}
let storedCount = splatPairCount[threadIdx] & 0x7FFFFFFFu;
if (actualTotal != storedCount) {
splatPairCount[threadIdx] = actualTotal | 0x80000000u;
}
}
}
`;var zk=`
@group(0) @binding(0) var<storage, read> pairBuffer: array<u32>;
@group(0) @binding(1) var<storage, read> splatPairStart: array<u32>;
@group(0) @binding(2) var<storage, read> splatPairCount: array<u32>;
@group(0) @binding(3) var<storage, read> tileSplatCounts: array<u32>;
@group(0) @binding(4) var<storage, read_write> tileEntries: array<u32>;
@group(0) @binding(5) var<storage, read> sortElementCount: array<u32>;
@compute @workgroup_size(256)
fn main(@builtin(global_invocation_id) gid: vec3u, @builtin(num_workgroups) numWorkgroups: vec3u) {
let threadIdx = gid.y * (numWorkgroups.x * 256u) + gid.x;
let numVisible = sortElementCount[0];
if (threadIdx >= numVisible) {
return;
}
let rawCount = splatPairCount[threadIdx];
if (rawCount == 0u || (rawCount & 0x80000000u) != 0u) {
return;
}
let count = rawCount;
let start = splatPairStart[threadIdx];
let pairLen = arrayLength(&pairBuffer);
let tileEntriesLen = arrayLength(&tileEntries);
for (var j: u32 = 0u; j < count; j++) {
let pairIdx = start + j;
if (pairIdx >= pairLen) { break; }
let packed = pairBuffer[pairIdx];
let tileIdx = packed >> 16u;
let localOff = packed & 0xFFFFu;
let entryIdx = tileSplatCounts[tileIdx] + localOff;
if (entryIdx < tileEntriesLen) {
tileEntries[entryIdx] = threadIdx;
}
}
}
`;var Gk=`
const WG_SIZE: u32 = 256u;
@group(0) @binding(0) var<storage, read> pairBuffer: array<u32>;
@group(0) @binding(1) var<storage, read> splatPairStart: array<u32>;
@group(0) @binding(2) var<storage, read> splatPairCount: array<u32>;
@group(0) @binding(3) var<storage, read> tileSplatCounts: array<u32>;
@group(0) @binding(4) var<storage, read_write> tileEntries: array<u32>;
@group(0) @binding(5) var<storage, read> largeSplatIds: array<u32>;
@group(0) @binding(6) var<storage, read> countersBuffer: array<u32>;
@compute @workgroup_size(256)
fn main(
@builtin(workgroup_id) wgId: vec3u,
@builtin(num_workgroups) numWorkgroups: vec3u,
@builtin(local_invocation_index) lid: u32
) {
let largeSplatIdx = wgId.y * numWorkgroups.x + wgId.x;
let numLarge = min(countersBuffer[1], arrayLength(&largeSplatIds));
if (largeSplatIdx >= numLarge) {
return;
}
let threadIdx = largeSplatIds[largeSplatIdx];
let pairCount = splatPairCount[threadIdx] & 0x7FFFFFFFu;
if (pairCount == 0u) {
return;
}
let start = splatPairStart[threadIdx];
let pairLen = arrayLength(&pairBuffer);
let tileEntriesLen = arrayLength(&tileEntries);
for (var j = lid; j < pairCount; j += WG_SIZE) {
let pairIdx = start + j;
if (pairIdx >= pairLen) { break; }
let packed = pairBuffer[pairIdx];
let tileIdx = packed >> 16u;
let localOff = packed & 0xFFFFu;
let entryIdx = tileSplatCounts[tileIdx] + localOff;
if (entryIdx < tileEntriesLen) {
tileEntries[entryIdx] = threadIdx;
}
}
}
`;var Vk=`
#include "gsplatLocalBitonicCS"
@group(0) @binding(0) var<storage, read_write> tileEntries: array<u32>;
@group(0) @binding(1) var<storage, read> tileSplatCounts: array<u32>;
@group(0) @binding(2) var<storage, read> depthBuffer: array<u32>;
@group(0) @binding(3) var<storage, read> smallTileList: array<u32>;
@group(0) @binding(4) var<storage, read> tileListCounts: array<u32>;
@compute @workgroup_size(256)
fn main(
@builtin(local_invocation_index) localIdx: u32,
@builtin(workgroup_id) wid: vec3u,
@builtin(num_workgroups) numWorkgroups: vec3u
) {
let workgroupIdx = wid.y * numWorkgroups.x + wid.x;
if (workgroupIdx >= tileListCounts[0]) {
return;
}
let tileIdx = smallTileList[workgroupIdx];
let tStart = tileSplatCounts[tileIdx];
let tEnd = tileSplatCounts[tileIdx + 1u];
let count = tEnd - tStart;
bitonicSortRange(localIdx, tStart, count);
}
`;var _h=`
fn calcDispatch2D(count: u32, maxDim: u32) -> vec2u {
if (count <= maxDim) {
return vec2u(count, 1u);
}
let y = (count + maxDim - 1u) / maxDim;
let x = (count + y - 1u) / y;
return vec2u(x, y);
}
`;var Hk=`
${Jc}
${_h}
const MAX_TILE_ENTRIES: u32 = 4096u;
const CLASSIFY_WORKGROUP: u32 = 256u;
@group(0) @binding(0) var<storage, read> tileSplatCounts: array<u32>;
@group(0) @binding(1) var<storage, read_write> smallTileList: array<u32>;
@group(0) @binding(2) var<storage, read_write> largeTileList: array<u32>;
@group(0) @binding(3) var<storage, read_write> rasterizeTileList: array<u32>;
@group(0) @binding(4) var<storage, read_write> tileListCounts: array<atomic<u32>>;
@group(0) @binding(5) var<storage, read_write> indirectDispatchArgs: array<u32>;
@group(0) @binding(6) var<storage, read_write> largeTileOverflowBases: array<u32>;
@group(0) @binding(8) var<storage, read_write> indirectDrawArgs: array<DrawIndirectArgs>;
struct Uniforms {
numTiles: u32,
dispatchSlotOffset: u32,
bufferCapacity: u32,
maxWorkgroupsPerDim: u32,
drawSlot: u32,
}
@group(0) @binding(7) var<uniform> uniforms: Uniforms;
@compute @workgroup_size(256)
fn main(@builtin(local_invocation_index) localIdx: u32) {
let numTiles = uniforms.numTiles;
let totalEntries = tileSplatCounts[numTiles];
for (var i: u32 = localIdx; i < numTiles; i += CLASSIFY_WORKGROUP) {
let tStart = tileSplatCounts[i];
let tEnd = tileSplatCounts[i + 1u];
let count = tEnd - tStart;
if (count == 0u || tEnd > uniforms.bufferCapacity) {
continue;
}
let rIdx = atomicAdd(&tileListCounts[2], 1u);
rasterizeTileList[rIdx] = i;
if (count <= MAX_TILE_ENTRIES) {
let sIdx = atomicAdd(&tileListCounts[0], 1u);
smallTileList[sIdx] = i;
} else {
let overflowOffset = atomicAdd(&tileListCounts[3], count);
let lIdx = atomicAdd(&tileListCounts[1], 1u);
largeTileList[lIdx] = i;
largeTileOverflowBases[lIdx] = totalEntries + overflowOffset;
}
}
workgroupBarrier();
if (localIdx == 0u) {
let smallCount = atomicLoad(&tileListCounts[0]);
let largeCount = atomicLoad(&tileListCounts[1]);
let rasterizeCount = atomicLoad(&tileListCounts[2]);
let off = uniforms.dispatchSlotOffset;
let maxDim = uniforms.maxWorkgroupsPerDim;
let smallDim = calcDispatch2D(smallCount, maxDim);
indirectDispatchArgs[off + 0u] = smallDim.x;
indirectDispatchArgs[off + 1u] = smallDim.y;
indirectDispatchArgs[off + 2u] = 1u;
let largeDim = calcDispatch2D(largeCount, maxDim);
indirectDispatchArgs[off + 3u] = largeDim.x;
indirectDispatchArgs[off + 4u] = largeDim.y;
indirectDispatchArgs[off + 5u] = 1u;
let rasterDim = calcDispatch2D(rasterizeCount, maxDim);
indirectDispatchArgs[off + 6u] = rasterDim.x;
indirectDispatchArgs[off + 7u] = rasterDim.y;
indirectDispatchArgs[off + 8u] = 1u;
indirectDrawArgs[uniforms.drawSlot] = DrawIndirectArgs(rasterizeCount * 6u, 1u, 0u, 0u, 0u);
}
}
`;var Wk=`
const NUM_BUCKETS: u32 = 128u;
const MAX_CHUNK_SIZE: u32 = 4096u;
const WG_SIZE: u32 = 256u;
@group(0) @binding(0) var<storage, read_write> tileEntries: array<u32>;
@group(0) @binding(1) var<storage, read> largeTileOverflowBases: array<u32>;
@group(0) @binding(2) var<storage, read> tileSplatCounts: array<u32>;
@group(0) @binding(3) var<storage, read> depthBuffer: array<u32>;
@group(0) @binding(4) var<storage, read> largeTileList: array<u32>;
@group(0) @binding(5) var<storage, read_write> chunkRanges: array<u32>;
@group(0) @binding(6) var<storage, read_write> totalChunks: array<atomic<u32>>;
@group(0) @binding(7) var<storage, read> tileListCounts: array<u32>;
struct Uniforms {
bufferCapacity: u32,
maxChunks: u32,
}
@group(0) @binding(8) var<uniform> uniforms: Uniforms;
var<workgroup> sDepthMin: atomic<u32>;
var<workgroup> sDepthMax: atomic<u32>;
var<workgroup> sBucketCounts: array<atomic<u32>, NUM_BUCKETS>;
var<workgroup> sBucketOffsets: array<u32, NUM_BUCKETS + 1>;
var<workgroup> sBucketCursors: array<atomic<u32>, NUM_BUCKETS>;
@compute @workgroup_size(256)
fn main(
@builtin(local_invocation_index) localIdx: u32,
@builtin(workgroup_id) wid: vec3u,
@builtin(num_workgroups) numWorkgroups: vec3u
) {
let largeTileIdx = wid.y * numWorkgroups.x + wid.x;
if (largeTileIdx >= tileListCounts[1]) {
return;
}
let tileIdx = largeTileList[largeTileIdx];
let tStart = tileSplatCounts[tileIdx];
let tEnd = tileSplatCounts[tileIdx + 1u];
let count = tEnd - tStart;
let overflowBase = largeTileOverflowBases[largeTileIdx];
if (overflowBase + count > uniforms.bufferCapacity) {
return;
}
if (localIdx == 0u) {
atomicStore(&sDepthMin, 0xFFFFFFFFu);
atomicStore(&sDepthMax, 0u);
}
if (localIdx < NUM_BUCKETS) {
atomicStore(&sBucketCounts[localIdx], 0u);
atomicStore(&sBucketCursors[localIdx], 0u);
}
workgroupBarrier();
for (var i: u32 = localIdx; i < count; i += WG_SIZE) {
let entryIdx = tileEntries[tStart + i];
let depthU = depthBuffer[entryIdx];
atomicMin(&sDepthMin, depthU);
atomicMax(&sDepthMax, depthU);
}
workgroupBarrier();
let depthMinU = atomicLoad(&sDepthMin);
let depthMaxU = atomicLoad(&sDepthMax);
let depthMin = bitcast<f32>(depthMinU);
let depthMax = bitcast<f32>(depthMaxU);
let logMin = log(max(depthMin, 1e-6));
let logRange = log(max(depthMax, 1e-6)) - logMin;
let bucketScale = select(f32(NUM_BUCKETS) / logRange, 0.0, logRange < 1e-10);
for (var i: u32 = localIdx; i < count; i += WG_SIZE) {
let entryIdx = tileEntries[tStart + i];
let depth = bitcast<f32>(depthBuffer[entryIdx]);
let bucket = min(u32((log(max(depth, 1e-6)) - logMin) * bucketScale), NUM_BUCKETS - 1u);
atomicAdd(&sBucketCounts[bucket], 1u);
tileEntries[overflowBase + i] = entryIdx;
}
workgroupBarrier();
if (localIdx == 0u) {
sBucketOffsets[0] = 0u;
for (var b: u32 = 0u; b < NUM_BUCKETS; b++) {
sBucketOffsets[b + 1u] = sBucketOffsets[b] + atomicLoad(&sBucketCounts[b]);
}
}
workgroupBarrier();
for (var i: u32 = localIdx; i < count; i += WG_SIZE) {
let entryIdx = tileEntries[overflowBase + i];
let depth = bitcast<f32>(depthBuffer[entryIdx]);
let bucket = min(u32((log(max(depth, 1e-6)) - logMin) * bucketScale), NUM_BUCKETS - 1u);
let writePos = sBucketOffsets[bucket] + atomicAdd(&sBucketCursors[bucket], 1u);
tileEntries[tStart + writePos] = entryIdx;
}
workgroupBarrier();
if (localIdx == 0u) {
var chunkStart: u32 = 0u;
var currentSize: u32 = 0u;
let maxChunks = uniforms.maxChunks;
for (var b: u32 = 0u; b < NUM_BUCKETS; b++) {
var bRemaining = sBucketOffsets[b + 1u] - sBucketOffsets[b];
if (bRemaining == 0u) {
continue;
}
while (bRemaining > 0u) {
let space = MAX_CHUNK_SIZE - currentSize;
let take = min(bRemaining, space);
currentSize += take;
bRemaining -= take;
if (currentSize == MAX_CHUNK_SIZE) {
let cIdx = atomicAdd(&totalChunks[0], 1u);
if (cIdx < maxChunks) {
chunkRanges[cIdx * 2u] = tStart + chunkStart;
chunkRanges[cIdx * 2u + 1u] = currentSize;
}
chunkStart += currentSize;
currentSize = 0u;
}
}
}
if (currentSize > 0u) {
let cIdx = atomicAdd(&totalChunks[0], 1u);
if (cIdx < maxChunks) {
chunkRanges[cIdx * 2u] = tStart + chunkStart;
chunkRanges[cIdx * 2u + 1u] = currentSize;
}
}
}
}
`;var Xk=`
#include "gsplatLocalBitonicCS"
@group(0) @binding(0) var<storage, read_write> tileEntries: array<u32>;
@group(0) @binding(1) var<storage, read> depthBuffer: array<u32>;
@group(0) @binding(2) var<storage, read> chunkRanges: array<u32>;
@group(0) @binding(3) var<storage, read> totalChunks: array<u32>;
struct Uniforms {
maxChunks: u32,
}
@group(0) @binding(4) var<uniform> uniforms: Uniforms;
@compute @workgroup_size(256)
fn main(
@builtin(local_invocation_index) localIdx: u32,
@builtin(workgroup_id) wid: vec3u,
@builtin(num_workgroups) numWorkgroups: vec3u
) {
let chunkIdx = wid.y * numWorkgroups.x + wid.x;
if (chunkIdx >= min(totalChunks[0], uniforms.maxChunks)) {
return;
}
let tStart = chunkRanges[chunkIdx * 2u];
let count = chunkRanges[chunkIdx * 2u + 1u];
bitonicSortRange(localIdx, tStart, count);
}
`;var Yk=`
${_h}
@group(0) @binding(0) var<storage, read> totalChunks: array<u32>;
@group(0) @binding(1) var<storage, read_write> chunkSortIndirect: array<u32>;
struct Uniforms {
maxChunks: u32,
maxWorkgroupsPerDim: u32,
}
@group(0) @binding(2) var<uniform> uniforms: Uniforms;
@compute @workgroup_size(1)
fn main() {
let count = min(totalChunks[0], uniforms.maxChunks);
let dim = calcDispatch2D(count, uniforms.maxWorkgroupsPerDim);
chunkSortIndirect[0] = dim.x;
chunkSortIndirect[1] = dim.y;
chunkSortIndirect[2] = 1u;
}
`;var Kk=`
const MAX_TILE_ENTRIES: u32 = 4096u;
const INDEX_BITS: u32 = 12u;
const INDEX_MASK: u32 = 0xFFFu;
const DEPTH_LEVELS: f32 = 1048575.0;
const BITONIC_WG_SIZE: u32 = 256u;
var<workgroup> sData: array<u32, 4096>;
var<workgroup> sDepthMin: atomic<u32>;
var<workgroup> sDepthMax: atomic<u32>;
fn insertZeroBit(v: u32, bitPos: u32) -> u32 {
let mask = (1u << bitPos) - 1u;
return ((v >> bitPos) << (bitPos + 1u)) | (v & mask);
}
fn bitonicSortRange(localIdx: u32, tStart: u32, count: u32) {
let clampedCount = min(count, MAX_TILE_ENTRIES);
if (clampedCount <= 1u) {
return;
}
if (localIdx == 0u) {
atomicStore(&sDepthMin, 0xFFFFFFFFu);
atomicStore(&sDepthMax, 0u);
}
var sortN: u32 = 1u;
while (sortN < clampedCount) {
sortN = sortN << 1u;
}
for (var i: u32 = localIdx; i < sortN; i += BITONIC_WG_SIZE) {
if (i < clampedCount) {
let entryIdx = tileEntries[tStart + i];
sData[i] = depthBuffer[entryIdx];
} else {
sData[i] = 0xFFFFFFFFu;
}
}
workgroupBarrier();
for (var i: u32 = localIdx; i < clampedCount; i += BITONIC_WG_SIZE) {
atomicMin(&sDepthMin, sData[i]);
atomicMax(&sDepthMax, sData[i]);
}
workgroupBarrier();
let depthMinU = atomicLoad(&sDepthMin);
let depthMaxU = atomicLoad(&sDepthMax);
let depthMin = bitcast<f32>(depthMinU);
let depthMax = bitcast<f32>(depthMaxU);
let logMin = log(max(depthMin, 1e-6));
let logRange = log(max(depthMax, 1e-6)) - logMin;
let invLogRange = select(DEPTH_LEVELS / logRange, 0.0, logRange < 1e-10);
for (var i: u32 = localIdx; i < sortN; i += BITONIC_WG_SIZE) {
if (i < clampedCount) {
let depth = bitcast<f32>(sData[i]);
let logDepth = log(max(depth, 1e-6));
let depth20 = min(u32((logDepth - logMin) * invLogRange + 0.5), u32(DEPTH_LEVELS));
sData[i] = (depth20 << INDEX_BITS) | i;
} else {
sData[i] = 0xFFFFFFFFu;
}
}
workgroupBarrier();
for (var k: u32 = 2u; k <= sortN; k = k << 1u) {
for (var j: u32 = k >> 1u; j > 0u; j = j >> 1u) {
let bitPos = countTrailingZeros(j);
let halfN = sortN >> 1u;
for (var c: u32 = localIdx; c < halfN; c += BITONIC_WG_SIZE) {
let l = insertZeroBit(c, bitPos);
let r = l | j;
let ascending = (l & k) == 0u;
let shouldSwap = select(sData[l] < sData[r], sData[l] > sData[r], ascending);
if (shouldSwap) {
let tmp = sData[l]; sData[l] = sData[r]; sData[r] = tmp;
}
}
workgroupBarrier();
}
}
for (var i: u32 = localIdx; i < clampedCount; i += BITONIC_WG_SIZE) {
let localIndex = sData[i] & INDEX_MASK;
sData[i] = tileEntries[tStart + localIndex];
}
workgroupBarrier();
for (var i: u32 = localIdx; i < clampedCount; i += BITONIC_WG_SIZE) {
tileEntries[tStart + i] = sData[i];
}
}
`;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 {
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
);
}
struct SplatCov2D {
screen: vec2f,
a: f32,
b: f32,
c: f32,
viewDepth: f32,
valid: bool,
#if GSPLAT_AA
aaFactor: f32,
#endif
}
fn computeSplatCov(
worldCenter: vec3f,
rotation: half4,
scale: half3,
viewMatrix: mat4x4f,
viewProj: mat4x4f,
focal: f32,
viewportWidth: f32,
viewportHeight: f32,
nearClip: f32,
farClip: f32,
opacity: f32,
minPixelSize: f32,
isOrtho: u32,
alphaClip: f32,
minContribution: f32,
#ifdef GSPLAT_FISHEYE
fisheye_k: f32,
fisheye_inv_k: f32,
fisheye_projMat00: f32,
fisheye_projMat11: f32,
#endif
) -> SplatCov2D {
var result: SplatCov2D;
result.valid = false;
let viewCenter = (viewMatrix * vec4f(worldCenter, 1.0)).xyz;
#ifdef GSPLAT_FISHEYE
let fv = viewCenter;
let r_xy = length(fv.xy);
let neg_z = -fv.z;
let theta = atan2(r_xy, neg_z);
let maxTheta = min(fisheye_k * 1.5707963, 3.13);
if (theta > maxTheta - 0.01 || dot(fv, fv) < 0.0001) {
return result;
}
let tk = theta * fisheye_inv_k;
let sin_tk = sin(tk);
let cos_tk = cos(tk);
let g_theta = fisheye_k * sin_tk / cos_tk;
let fisheye_s = select(select(0.0, 1.0 / neg_z, neg_z > 0.0), g_theta / r_xy, r_xy > 1e-4);
let fndc = vec2f(fisheye_projMat00 * fisheye_s * fv.x, fisheye_projMat11 * fisheye_s * fv.y);
let screen = vec2f(
(fndc.x * 0.5 + 0.5) * viewportWidth,
(fndc.y * 0.5 + 0.5) * viewportHeight
);
#else
if (viewCenter.z > 0.0) {
return result;
}
let clip = viewProj * vec4f(worldCenter, 1.0);
let ndc = clip.xy / clip.w;
let screen = vec2f(
(ndc.x * 0.5 + 0.5) * viewportWidth,
(ndc.y * 0.5 + 0.5) * viewportHeight
);
#endif
let rot: half3x3 = quatToMat3(rotation);
let s: vec3f = vec3f(scale);
let M: mat3x3f = transpose(mat3x3f(
s.x * vec3f(rot[0]),
s.y * vec3f(rot[1]),
s.z * vec3f(rot[2])
));
let w0 = vec3f(viewMatrix[0].x, viewMatrix[1].x, viewMatrix[2].x);
let w1 = vec3f(viewMatrix[0].y, viewMatrix[1].y, viewMatrix[2].y);
let w2 = vec3f(viewMatrix[0].z, viewMatrix[1].z, viewMatrix[2].z);
#ifdef GSPLAT_FISHEYE
let fisheyeFocal = viewportWidth * fisheye_projMat00;
let g_prime = 1.0 / (cos_tk * cos_tk);
let d2 = dot(fv, fv);
let r_sq = max(r_xy * r_xy, 1e-8);
let K_coeff = select(0.0, (g_prime * neg_z / d2 - fisheye_s) / r_sq, r_xy > 1e-4);
let Jxx = fisheyeFocal * (fisheye_s + K_coeff * fv.x * fv.x);
let Jxy = fisheyeFocal * K_coeff * fv.x * fv.y;
let Jyy = fisheyeFocal * (fisheye_s + K_coeff * fv.y * fv.y);
let Jzx = fisheyeFocal * g_prime * fv.x / d2;
let Jzy = fisheyeFocal * g_prime * fv.y / d2;
let tt0 = Jxx * w0 + Jxy * w1 + Jzx * w2;
let tt1 = Jxy * w0 + Jyy * w1 + Jzy * w2;
#else
let ortho = isOrtho == 1u;
let v = select(viewCenter.xyz, vec3f(0.0, 0.0, 1.0), ortho);
let vz = select(min(v.z, -0.001), v.z, ortho);
let J1 = focal / vz;
let J2 = -J1 / vz * v.xy;
let tt0 = J1 * w0 + J2.x * w2;
let tt1 = J1 * w1 + J2.y * w2;
#endif
let b0 = M * tt0;
let b1 = M * tt1;
let aRaw = dot(b0, b0);
let b = dot(b0, b1);
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;
}
let radiusFactor = computeRadiusFactor(half(opacity), alphaClip);
let vmin = min(1024.0, min(viewportWidth, viewportHeight));
let maxRadius = vmin;
let radiusXUncapped = sqrt(2.0 * a);
let radiusYUncapped = sqrt(2.0 * c);
let radiusX = min(radiusXUncapped, maxRadius);
let radiusY = min(radiusYUncapped, maxRadius);
if (max(radiusX, radiusY) < minPixelSize) {
return result;
}
if (screen.x + radiusX < 0.0 || screen.x - radiusX > viewportWidth ||
screen.y + radiusY < 0.0 || screen.y - radiusY > viewportHeight) {
return result;
}
let capScale = max(1.0, max(radiusXUncapped, radiusYUncapped) / maxRadius);
let invCapScale2 = 1.0 / (capScale * capScale);
result.screen = screen;
let scaledCov = vec3f(a, b, c) * invCapScale2;
result.a = scaledCov.x;
result.b = scaledCov.y;
result.c = scaledCov.z;
#ifdef GSPLAT_FISHEYE
result.viewDepth = sqrt(d2);
#else
result.viewDepth = -viewCenter.z;
#endif
result.valid = true;
return result;
}
`;var pE=`
struct SplatTileEval {
radiusFactor: f32,
splatMin: vec2f,
splatMax: vec2f,
}
fn computeRadiusFactor(opacity: half, alphaClip: f32) -> f32 {
return min(8.0, 2.0 * log(f32(opacity) / alphaClip));
}
fn computeSplatTileEval(
screen: vec2f,
cx: f32, cy: f32, cz: f32,
opacity: half,
viewportWidth: f32, viewportHeight: f32,
alphaClip: f32
) -> SplatTileEval {
let K = cx * cz - cy * cy;
let a = 4.0 * cz / K;
let c = 4.0 * cx / K;
let radiusFactor = computeRadiusFactor(opacity, alphaClip);
let vmin = min(1024.0, min(viewportWidth, viewportHeight));
let radius = vec2f(min(sqrt(2.0 * a), vmin), min(sqrt(2.0 * c), vmin));
var result: SplatTileEval;
result.radiusFactor = radiusFactor;
result.splatMin = screen - radius;
result.splatMax = screen + radius;
return result;
}
fn segmentIntersectsEllipse(a: f32, b: f32, c: f32, d: f32, l: f32, r: f32) -> bool {
let delta = b * b - 4.0 * a * c;
let t1 = (l - d) * (2.0 * a) + b;
let t2 = (r - d) * (2.0 * a) + b;
return delta >= 0.0 && (t1 <= 0.0 || t1 * t1 <= delta) && (t2 >= 0.0 || t2 * t2 <= delta);
}
fn tileIntersectsEllipse(
tileMin: vec2f, tileMax: vec2f, center: vec2f,
cx: f32, cy: f32, cz: f32,
radiusFactor: f32
) -> bool {
if (center.x >= tileMin.x && center.x <= tileMax.x &&
center.y >= tileMin.y && center.y <= tileMax.y) {
return true;
}
let w = radiusFactor;
var dx: f32;
if (center.x * 2.0 < tileMin.x + tileMax.x) {
dx = center.x - tileMin.x;
} else {
dx = center.x - tileMax.x;
}
if (segmentIntersectsEllipse(cz, -2.0 * cy * dx, cx * dx * dx - w, center.y, tileMin.y, tileMax.y)) {
return true;
}
var dy: f32;
if (center.y * 2.0 < tileMin.y + tileMax.y) {
dy = center.y - tileMin.y;
} else {
dy = center.y - tileMax.y;
}
if (segmentIntersectsEllipse(cx, -2.0 * cy * dy, cz * dy * dy - w, center.x, tileMin.x, tileMax.x)) {
return true;
}
return false;
}
`;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"
#if FOG != NONE
#include "fogMathPS"
#include "gammaPS"
#endif
#endif
const BATCH_SIZE: u32 = 64u;
const ALPHA_THRESHOLD: half = half(1.0) / half(255.0);
const EXP4: half = exp(half(-4.0));
const INV_EXP4: half = half(1.0) / (half(1.0) - EXP4);
struct Uniforms {
screenWidth: u32,
screenHeight: u32,
numTilesX: u32,
nearClip: f32,
farClip: f32,
alphaClip: f32,
#if FOG != NONE
fog_color: vec3f,
fog_start: f32,
fog_end: f32,
fog_density: f32,
#endif
}
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var<storage, read> tileEntries: array<u32>;
@group(0) @binding(2) var<storage, read> tileSplatCounts: array<u32>;
@group(0) @binding(3) var<storage, read> projCache: array<u32>;
@group(0) @binding(4) var<storage, read> rasterizeTileList: array<u32>;
@group(0) @binding(5) var<storage, read> tileListCounts: array<u32>;
@group(0) @binding(6) var<storage, read> depthBuffer: array<u32>;
#ifdef PICK_MODE
@group(0) @binding(7) var pickIdTexture: texture_storage_2d<r32uint, write>;
@group(0) @binding(8) var pickDepthTexture: texture_storage_2d<rgba16float, write>;
#else
@group(0) @binding(7) var outputTexture: texture_storage_2d<rgba16float, write>;
#ifdef DEPTH_TEST
@group(0) @binding(8) var sceneDepthMap: texture_2d<f32>;
#endif
#endif
var<workgroup> sharedCenterScreen: array<vec2f, 64>;
var<workgroup> sharedCoeffs: array<vec3f, 64>;
var<workgroup> sharedPowerCutoff: array<f32, 64>;
#ifdef HEATMAP_MODE
var<workgroup> sharedHeatCount: atomic<u32>;
#endif
#ifdef PICK_MODE
var<workgroup> sharedOpacity: array<half, 64>;
var<workgroup> sharedPickId: array<u32, 64>;
var<workgroup> sharedViewDepth: array<f32, 64>;
#else
var<workgroup> sharedColor: array<half4, 64>;
#ifdef DEPTH_TEST
var<workgroup> sharedViewDepth: array<f32, 64>;
#endif
#endif
#ifdef PICK_MODE
fn evalSplatPick(pixelCoord: vec2f, center: vec2f, coeffX: f32, coeffY: f32, coeffXY: f32,
opacity: half, pickId: u32, viewDepth: f32, alphaClip: half,
bestPickId: ptr<function, u32>, depthAccum: ptr<function, f32>,
weightAccum: ptr<function, f32>, T: ptr<function, half>) {
let dx = pixelCoord - center;
let power = coeffX * dx.x * dx.x + coeffXY * dx.x * dx.y + coeffY * dx.y * dx.y;
let gauss = (half(exp(power)) - EXP4) * INV_EXP4;
let alpha = half(min(half(0.99), opacity * gauss));
let newT = *T * (half(1.0) - alpha);
let visible = power > -4.0 && alpha > ALPHA_THRESHOLD && *T >= ALPHA_THRESHOLD;
if (!visible) { return; }
if (alpha >= alphaClip) {
if (*bestPickId == 0xFFFFFFFFu) {
*bestPickId = pickId;
}
let normalizedDepth = saturate((viewDepth - uniforms.nearClip) / (uniforms.farClip - uniforms.nearClip));
let w = f32(alpha) * f32(*T);
*depthAccum += w * normalizedDepth;
*weightAccum += w;
}
*T = newT;
}
#endif
#ifdef HEATMAP_MODE
fn heatmapColor(v: f32) -> vec3f {
let t = saturate(v / 2000.0);
if (t < 0.2) {
return mix(vec3f(0.0, 0.0, 1.0), vec3f(0.0, 1.0, 1.0), t * 5.0);
} else if (t < 0.4) {
return mix(vec3f(0.0, 1.0, 1.0), vec3f(1.0, 1.0, 0.0), (t - 0.2) * 5.0);
} else if (t < 0.6) {
return mix(vec3f(1.0, 1.0, 0.0), vec3f(1.0, 0.0, 0.0), (t - 0.4) * 5.0);
}
return mix(vec3f(1.0, 0.0, 0.0), vec3f(0.15, 0.0, 0.0), (t - 0.6) * 2.5);
}
#endif
@compute @workgroup_size(8, 8)
fn main(
@builtin(local_invocation_id) lid: vec3u,
@builtin(local_invocation_index) localIdx: u32,
@builtin(workgroup_id) wid: vec3u,
@builtin(num_workgroups) numWorkgroups: vec3u
) {
let workgroupIdx = wid.y * numWorkgroups.x + wid.x;
if (workgroupIdx >= tileListCounts[2]) {
return;
}
let tileIdx = rasterizeTileList[workgroupIdx];
let tileX = tileIdx % uniforms.numTilesX;
let tileY = tileIdx / uniforms.numTilesX;
let tStart = tileSplatCounts[tileIdx];
let tEnd = tileSplatCounts[tileIdx + 1u];
let basePixel = vec2u(tileX * 16u + lid.x * 2u, tileY * 16u + lid.y * 2u);
let p00 = vec2f(f32(basePixel.x) + 0.5, f32(basePixel.y) + 0.5);
let p10 = p00 + vec2f(1.0, 0.0);
let p01 = p00 + vec2f(0.0, 1.0);
let p11 = p00 + vec2f(1.0, 1.0);
#ifdef PICK_MODE
var T00: half = half(1.0); var T10: half = half(1.0);
var T01: half = half(1.0); var T11: half = half(1.0);
var pickId00: u32 = 0xFFFFFFFFu; var pickId10: u32 = 0xFFFFFFFFu;
var pickId01: u32 = 0xFFFFFFFFu; var pickId11: u32 = 0xFFFFFFFFu;
var dAcc00: f32 = 0.0; var dAcc10: f32 = 0.0;
var dAcc01: f32 = 0.0; var dAcc11: f32 = 0.0;
var wAcc00: f32 = 0.0; var wAcc10: f32 = 0.0;
var wAcc01: f32 = 0.0; var wAcc11: f32 = 0.0;
let clipH = half(uniforms.alphaClip);
#else
var T = half4(1.0);
var c00 = half3(0.0); var c10 = half3(0.0);
var c01 = half3(0.0); var c11 = half3(0.0);
#ifdef DEPTH_TEST
var sceneDepth = vec4f(1e20);
let depthY0 = uniforms.screenHeight - 1u - basePixel.y;
let depthY1 = depthY0 - 1u;
if (basePixel.x < uniforms.screenWidth && basePixel.y < uniforms.screenHeight) {
sceneDepth.x = textureLoad(sceneDepthMap, vec2i(vec2u(basePixel.x, depthY0)), 0).r;
}
if (basePixel.x + 1u < uniforms.screenWidth && basePixel.y < uniforms.screenHeight) {
sceneDepth.y = textureLoad(sceneDepthMap, vec2i(vec2u(basePixel.x + 1u, depthY0)), 0).r;
}
if (basePixel.x < uniforms.screenWidth && basePixel.y + 1u < uniforms.screenHeight) {
sceneDepth.z = textureLoad(sceneDepthMap, vec2i(vec2u(basePixel.x, depthY1)), 0).r;
}
if (basePixel.x + 1u < uniforms.screenWidth && basePixel.y + 1u < uniforms.screenHeight) {
sceneDepth.w = textureLoad(sceneDepthMap, vec2i(vec2u(basePixel.x + 1u, depthY1)), 0).r;
}
#endif
#endif
let tileCount = tEnd - tStart;
#ifdef HEATMAP_MODE
if (localIdx == 0u) { atomicStore(&sharedHeatCount, 0u); }
workgroupBarrier();
var processedCount: u32 = 0u;
#endif
let numBatches = (tileCount + BATCH_SIZE - 1u) / BATCH_SIZE;
var threadDone = false;
for (var batch: u32 = 0u; batch < numBatches; batch++) {
let batchOffset = batch * BATCH_SIZE + localIdx;
if (batchOffset < tileCount) {
let cacheIdx = tileEntries[tStart + batchOffset];
let base = cacheIdx * {CACHE_STRIDE}u;
sharedCenterScreen[localIdx] = vec2f(
bitcast<f32>(projCache[base + 0u]),
bitcast<f32>(projCache[base + 1u])
);
let cx = bitcast<f32>(projCache[base + 2u]);
let cy = bitcast<f32>(projCache[base + 3u]);
let cz = bitcast<f32>(projCache[base + 4u]);
sharedCoeffs[localIdx] = vec3f(cx * -0.5, cz * -0.5, -cy);
sharedPowerCutoff[localIdx] = bitcast<f32>(projCache[base + 7u]);
#ifdef PICK_MODE
sharedPickId[localIdx] = projCache[base + 5u];
sharedOpacity[localIdx] = half(unpack2x16float(projCache[base + 6u]).y);
sharedViewDepth[localIdx] = bitcast<f32>(depthBuffer[cacheIdx]);
#else
let rg = unpack2x16float(projCache[base + 5u]);
let ba = unpack2x16float(projCache[base + 6u]);
#if FOG != NONE
let viewDepth = bitcast<f32>(depthBuffer[cacheIdx]);
#if (FOG == LINEAR)
let fogFactor = evaluateFogFactorLinear(viewDepth, uniforms.fog_start, uniforms.fog_end);
#elif (FOG == EXP)
let fogFactor = evaluateFogFactorExp(viewDepth, uniforms.fog_density);
#elif (FOG == EXP2)
let fogFactor = evaluateFogFactorExp2(viewDepth, uniforms.fog_density);
#endif
var foggedColor = decodeGamma3(vec3f(rg.x, rg.y, ba.x));
foggedColor = mix(uniforms.fog_color, foggedColor, fogFactor);
sharedColor[localIdx] = half4(half3(gammaCorrectOutput(foggedColor)), half(ba.y));
#else
sharedColor[localIdx] = half4(half(rg.x), half(rg.y), half(ba.x), half(ba.y));
#endif
#ifdef DEPTH_TEST
sharedViewDepth[localIdx] = bitcast<f32>(depthBuffer[cacheIdx]);
#endif
#endif
}
workgroupBarrier();
if (!threadDone) {
let batchCount = min(BATCH_SIZE, tileCount - batch * BATCH_SIZE);
for (var i: u32 = 0u; i < batchCount; i++) {
let center = sharedCenterScreen[i];
let coeffs = sharedCoeffs[i];
#ifdef PICK_MODE
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);
evalSplatPick(p11, center, coeffs.x, coeffs.y, coeffs.z, splatOpacity, splatPickId, splatDepth, clipH, &pickId11, &dAcc11, &wAcc11, &T11);
if (all(vec4<half>(T00, T10, T01, T11) < half4(ALPHA_THRESHOLD))) {
threadDone = true;
break;
}
#else
let splatColor = sharedColor[i];
#ifdef DEPTH_TEST
let splatDepth = sharedViewDepth[i];
if (all(vec4f(splatDepth) > sceneDepth)) {
threadDone = true;
break;
}
#endif
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;
}
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);
var valid = (power4 > vec4f(-4.0)) & (alpha4 > half4(ALPHA_THRESHOLD)) & (T >= half4(ALPHA_THRESHOLD));
#ifdef DEPTH_TEST
valid = valid & (vec4f(splatDepth) <= sceneDepth);
#endif
let weight = alpha4 * T * select(half4(0.0), half4(1.0), valid);
c00 += splatColor.rgb * weight.x;
c10 += splatColor.rgb * weight.y;
c01 += splatColor.rgb * weight.z;
c11 += splatColor.rgb * weight.w;
T = select(T, newT, valid);
#ifdef HEATMAP_MODE
processedCount += 1u;
#endif
if (all(T < half4(ALPHA_THRESHOLD))) {
threadDone = true;
break;
}
#endif
}
}
workgroupBarrier();
}
#ifdef HEATMAP_MODE
atomicAdd(&sharedHeatCount, processedCount);
workgroupBarrier();
let avgCount = f32(atomicLoad(&sharedHeatCount)) / 64.0;
let heatColor = vec4f(heatmapColor(avgCount), 1.0);
if (basePixel.x < uniforms.screenWidth && basePixel.y < uniforms.screenHeight) {
textureStore(outputTexture, basePixel, heatColor);
}
if (basePixel.x + 1u < uniforms.screenWidth && basePixel.y < uniforms.screenHeight) {
textureStore(outputTexture, vec2u(basePixel.x + 1u, basePixel.y), heatColor);
}
if (basePixel.x < uniforms.screenWidth && basePixel.y + 1u < uniforms.screenHeight) {
textureStore(outputTexture, vec2u(basePixel.x, basePixel.y + 1u), heatColor);
}
if (basePixel.x + 1u < uniforms.screenWidth && basePixel.y + 1u < uniforms.screenHeight) {
textureStore(outputTexture, vec2u(basePixel.x + 1u, basePixel.y + 1u), heatColor);
}
#else
if (basePixel.x < uniforms.screenWidth && basePixel.y < uniforms.screenHeight) {
#ifdef PICK_MODE
textureStore(pickIdTexture, basePixel, vec4u(pickId00, 0u, 0u, 0u));
textureStore(pickDepthTexture, basePixel, vec4f(dAcc00, wAcc00, 0.0, 0.0));
#else
textureStore(outputTexture, basePixel, vec4f(decodeGamma3(vec3f(c00)), f32(half(1.0) - T.x)));
#endif
}
if (basePixel.x + 1u < uniforms.screenWidth && basePixel.y < uniforms.screenHeight) {
let px10 = vec2u(basePixel.x + 1u, basePixel.y);
#ifdef PICK_MODE
textureStore(pickIdTexture, px10, vec4u(pickId10, 0u, 0u, 0u));
textureStore(pickDepthTexture, px10, vec4f(dAcc10, wAcc10, 0.0, 0.0));
#else
textureStore(outputTexture, px10, vec4f(decodeGamma3(vec3f(c10)), f32(half(1.0) - T.y)));
#endif
}
if (basePixel.x < uniforms.screenWidth && basePixel.y + 1u < uniforms.screenHeight) {
let px01 = vec2u(basePixel.x, basePixel.y + 1u);
#ifdef PICK_MODE
textureStore(pickIdTexture, px01, vec4u(pickId01, 0u, 0u, 0u));
textureStore(pickDepthTexture, px01, vec4f(dAcc01, wAcc01, 0.0, 0.0));
#else
textureStore(outputTexture, px01, vec4f(decodeGamma3(vec3f(c01)), f32(half(1.0) - T.z)));
#endif
}
if (basePixel.x + 1u < uniforms.screenWidth && basePixel.y + 1u < uniforms.screenHeight) {
let px11 = vec2u(basePixel.x + 1u, basePixel.y + 1u);
#ifdef PICK_MODE
textureStore(pickIdTexture, px11, vec4u(pickId11, 0u, 0u, 0u));
textureStore(pickDepthTexture, px11, vec4f(dAcc11, wAcc11, 0.0, 0.0));
#else
textureStore(outputTexture, px11, vec4f(decodeGamma3(vec3f(c11)), f32(half(1.0) - T.w)));
#endif
}
#endif
}
`;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
}
var<private> splat: Splat;
fn setSplat(idx: u32) {
splat.index = idx;
splat.uv = vec2i(i32(idx % uniforms.splatTextureSize), i32(idx / uniforms.splatTextureSize));
}
`;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<h/2?this._shrinkFrameCount++:this._shrinkFrameCount=0,this._shrinkFrameCount>=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*2<this._allocatedEntryCapacity;(o||l)&&(this._tileEntriesBuffer?.destroy(),this._pairBuffer?.destroy(),this._allocatedEntryCapacity=a,this._tileEntriesBuffer=new Ee(s,a*4,8),this._pairBuffer=new Ee(s,a*4)),this._lastBufferSubmitVersion=s.submitVersion}dispatch(){let e=this._mainSet,s=e.outputTexture;if(!s)return;let i=s.width,r=s.height;this._dispatchPipeline(e,i,r,!1),this.tileComposite.update(this._lastDrawSlot,s,e._rasterizeTileListBuffer,this._lastNumTilesX,i,r)}dispatchPick(e,s,i){this._pickSet||(this._pickSet=this._createDispatchSet(!0));let r=this._pickSet;return r.resizeOutputTextures(s,i),this._dispatchPipeline(r,s,i,!0),this.tileComposite.prepareForPicking(this._lastDrawSlot,r.pickIdTexture,r.pickDepthTexture,r._rasterizeTileListBuffer,this._lastNumTilesX,s,i)}_dispatchPipeline(e,s,i,r){let a=this._numSplats;if(!this._compactedSplatIds||!this._sortElementCountBuffer||a===0)return;let o=this.device,l=Math.ceil(s/$k),h=Math.ceil(i/$k);if(l*h>Zk){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<storage, read> compactedSplatIds: array<u32>;
@group(0) @binding(1) var<storage, read> sortElementCount: array<u32>;
@group(0) @binding(2) var<storage, read_write> projCache: array<u32>;
@group(0) @binding(3) var<storage, read_write> sortKeys: array<u32>;
@group(0) @binding(4) var<storage, read_write> renderCounter: array<atomic<u32>>;
struct BinWeight {
base: f32,
divider: f32
}
@group(0) @binding(5) var<storage, read> binWeights: array<BinWeight>;
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<uniform> uniforms: ProjectorUniforms;
#include "gsplatComputeSplatCS"
#include "gsplatFormatDeclCS"
#include "gsplatFormatReadCS"
#include "gsplatProjectCommonCS"
var<workgroup> wgCount: atomic<u32>;
var<workgroup> 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<u32>(clipPos.x);
projCache[base + 1u] = bitcast<u32>(clipPos.y);
projCache[base + 2u] = bitcast<u32>(clipPos.z);
projCache[base + 3u] = bitcast<u32>(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<storage, read> renderCounter: array<u32>;
@group(0) @binding(1) var<storage, read_write> indirectDrawArgs: array<DrawIndexedIndirectArgs>;
@group(0) @binding(2) var<storage, read_write> numSplatsBuf: array<u32>;
@group(0) @binding(3) var<storage, read_write> indirectDispatchArgs: array<u32>;
@group(0) @binding(4) var<storage, read_write> sortElementCountBuf: array<u32>;
struct WriteArgsUniforms {
drawSlot: u32,
indexCount: u32,
sortSlotBase: u32,
pad0: u32,
sortIndirectInfo: vec4<u32>
};
@group(0) @binding(5) var<uniform> 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<<l,G=Cl.computeCameraBin(o,h,I),M=this.binWeightsUtil.compute(G,O);this.binWeightsBuffer.write(0,M),y.setParameter("compactedSplatIds",i),y.setParameter("sortElementCount",r),y.setParameter("projCache",this.projCache),y.setParameter("sortKeys",this.sortKeys),y.setParameter("renderCounter",this.renderCounter),y.setParameter("binWeights",this.binWeightsBuffer);for(let z of e.format.resourceStreams){let V=e.getTexture(z.name);V&&y.setParameter(z.name,V)}let U=s.camera.camera,L=U.viewMatrix,b=this.device.isWebGPU;rz.mul2(Bs.applyShaderProjectionTransform(U.projectionMatrix,nz,S,b),L),az.set(rz.data),oz.set(L.data);let N=m*nz.data[0];this.cameraPositionData[0]=P.x,this.cameraPositionData[1]=P.y,this.cameraPositionData[2]=P.z,y.setParameter("cameraPosition",this.cameraPositionData),this.cameraDirectionData[0]=w.x,this.cameraDirectionData[1]=w.y,this.cameraDirectionData[2]=w.z,y.setParameter("cameraDirection",this.cameraDirectionData),y.setParameter("viewMatrix",oz),y.setParameter("viewProj",az),y.setParameter("focal",N),y.setParameter("viewportWidth",m),y.setParameter("viewportHeight",_),y.setParameter("nearClip",U.nearClip),y.setParameter("farClip",U.farClip),y.setParameter("alphaClip",u),y.setParameter("minPixelSize",d),y.setParameter("minContribution",p),y.setParameter("isOrtho",U.projection===ni?1:0),y.setParameter("splatTextureSize",e.textureSize),y.setParameter("numBins",Cl.NUM_BINS),y.setParameter("minDist",h),y.setParameter("invRange",D),y.setParameter("pad0",0),v&&(y.setParameter("fisheye_k",T.k),y.setParameter("fisheye_inv_k",T.invK),y.setParameter("fisheye_projMat00",T.projMat00),y.setParameter("fisheye_projMat11",T.projMat11));let k=Math.ceil(a/MK);Ye.calcDispatchSize(k,BR,this.device.limits.maxComputeWorkgroupsPerDimension||65535),y.setupDispatch(BR.x,BR.y,1),this.device.computeDispatch([y],"GSplatProjector")}writeIndirectArgs(t,e,s,i,r){let a=this._writeIndirectArgsCompute;a.setParameter("renderCounter",this.renderCounter),a.setParameter("indirectDrawArgs",this.device.indirectDrawBuffer),a.setParameter("numSplatsBuf",s),a.setParameter("indirectDispatchArgs",this.device.indirectDispatchBuffer),a.setParameter("sortElementCountBuf",i),a.setParameter("drawSlot",t),a.setParameter("indexCount",LK),a.setParameter("sortSlotBase",e),a.setParameter("pad0",0),a.setParameter("sortIndirectInfo",r),a.setupDispatch(1),this.device.computeDispatch([a],"GSplatProjectorWriteIndirectArgs")}};var yE=new wp;var bu=class{constructor(t,e,s=0,i=null,r=null,a=null){n(this,"resource");n(this,"node");n(this,"intervals",new Map);n(this,"id",0);n(this,"allocId",yE.get());n(this,"lodIndex",0);n(this,"_lodBaseDistance",5);n(this,"_lodMultiplier",3);n(this,"_aabb",null);n(this,"parameters",null);n(this,"_streams",null);n(this,"lodDirty",!1);n(this,"renderDirty",!1);n(this,"workBufferUpdate",Tp);n(this,"_lastFormatVersion",-1);n(this,"_workBufferModifier",null);n(this,"parentPlacement",null);this.id=a??r?.id??0,this.resource=t,this.node=e,this.lodIndex=s,this.parameters=i??r?.parameters??null,this.parentPlacement=r}set lodBaseDistance(t){this._lodBaseDistance!==t&&(this._lodBaseDistance=t,this.lodDirty=!0)}get lodBaseDistance(){return this._lodBaseDistance}set lodMultiplier(t){this._lodMultiplier!==t&&(this._lodMultiplier=t,this.lodDirty=!0)}get lodMultiplier(){return this._lodMultiplier}destroy(){this._streams?.destroy(),this._streams=null,this.intervals.clear(),this.resource=null}set workBufferModifier(t){this._workBufferModifier=t,this.renderDirty=!0}get workBufferModifier(){return this.parentPlacement?.workBufferModifier??this._workBufferModifier}consumeRenderDirty(){let t=this.resource?.format;t&&this._lastFormatVersion!==t.extraStreamsVersion&&(this._lastFormatVersion=t.extraStreamsVersion,this.renderDirty=!0),this.workBufferUpdate===Iw?this.renderDirty=!0:this.workBufferUpdate===ww&&(this.renderDirty=!0,this.workBufferUpdate=Tp);let e=this.renderDirty;return this.renderDirty=!1,e}set aabb(t){this._aabb=t?.clone()??null}get aabb(){return this._aabb??this.resource?.aabb}getLodDistance(t){return this.lodBaseDistance*Math.pow(this.lodMultiplier,t)}getInstanceTexture(t,e){let s=this.resource;if(s?.format)return!this._streams&&s.format.instanceStreams.length>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;r<e.nodes.length;r++){let a=new kR;a.inst=this,this.nodeInfos[r]=a}let i=e.files.length;this.filePlacements=new Array(i).fill(null),e.environmentUrl&&(e.incEnvironmentRefCount(),e.ensureEnvironmentResource()),this._deviceLostEvent=t.on("devicelost",this._onDeviceLost,this)}get pendingLoadCount(){let t=this.pending.size+this.prefetchPending.size;return this.octree.environmentUrl&&!this.environmentPlacement&&t++,t}destroy(t=!1){if(!t&&this.octree&&!this.octree.destroyed){let e=this.getFileDecrements();for(let s of e)this.octree.decRefCount(s,0);for(let s of this.pending)this.filePlacements[s]||this.octree.unloadResource(s);for(let s of this.prefetchPending)this.filePlacements[s]||this.octree.unloadResource(s);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 t=0;t<this.filePlacements.length;t++)this.filePlacements[t]&&this.octree.decRefCount(t,0);this.filePlacements.fill(null),this.activePlacements.clear(),this.pending.clear(),this.pendingDecrements.clear(),this.removedCandidates.clear(),this.prefetchPending.clear(),this.pendingVisibleAdds.clear();for(let t of this.nodeInfos)t.resetLod();this.environmentPlacement&&(this.activePlacements.delete(this.environmentPlacement),this.environmentPlacement=null,this.octree.unloadEnvironmentResource()),this.dirtyModifiedPlacements=!0,this.dirtyPlacementSetChanged=!0,this.needsLodUpdate=!0}getFileDecrements(){let t=[];for(let e=0;e<this.filePlacements.length;e++)this.filePlacements[e]&&t.push(e);return t}selectDesiredLodIndex(t,e,s,i){if(i>0){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<i)&&(r=new Float32Array(i),this._lodMinDistThresholds=r);let a=e;r[1]=a;for(let o=2;o<=t;o++)a*=s,r[o]=a;return r}evaluateNodeLods(t,e,s,i,r,a,o,l,h=!0,f=0){let{lodBehindPenalty:u}=o,d=t.camera,p=Math.tan(d.fov*.5*R.DEG_TO_RAD);d.horizontalFov&&(p/=d.aspectRatio);let m=p*d.aspectRatio,_=Math.min(p,m)/BK,S=t.getPosition(),g=this.placement.node.getWorldTransform();UR.copy(g).invert();let T=UR.transformPoint(S,FK),C=t.forward,v=UR.transformVector(C,NK).normalize(),E=this.octree.nodes,y=this.nodeInfos,P=this.octree.nodeBoundsMinMax,A=T.x,w=T.y,I=T.z,D=v.x,O=v.y,G=v.z,M=0,H=null;e>=1&&(H=this._ensureLodMinDistThresholds(e,s,i));let U=f>0?rn/Math.sqrt(f):0;for(let L=0;L<E.length;L++){let b=y[L],N=L*6,k=A,z=P[N],V=P[N+3];k<z?k=z:k>V&&(k=V);let q=w,re=P[N+1],te=P[N+4];q<re?q=re:q>te&&(q=te);let j=I,oe=P[N+2],be=P[N+5];j<oe?j=oe:j>be&&(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||ds<s)Cs=0;else for(Cs=e;Cs>1&&ds<H[Cs];)Cs--;if(Cs<r&&(Cs=r),Cs>a&&(Cs=a),b.optimalLod=Cs,b.worldDistance=ds*l,U>0&&Cs>=0){let di=Math.sqrt(b.worldDistance)*U>>>0;b.budgetBucket=di<rn?di:rn-1}if(h){let di=E[L].lods[Cs];di&&di.count&&(M+=di.count)}}return M}evaluateOptimalLods(t,e,s=1,i=0){let r=this.octree.lodLevels-1,{lodBaseDistance:a,lodMultiplier:o}=this.placement,{lodRangeMin:l,lodRangeMax:h}=e,f=Math.max(0,Math.min(l??0,r)),u=Math.max(f,Math.min(h??r,r));this.rangeMin=f,this.rangeMax=u;let d=this.placement.node.getWorldTransform().getScale().x,p=a*s,m=Math.max(1.2,o*Math.pow(s,-.2));return this.evaluateNodeLods(t,r,p,m,f,u,e,d,!0,i)}applyLodChanges(t,e){let s=this.octree.nodes,{lodUnderfillLimit:i=0}=e;for(let r=0;r<s.length;r++){let a=s[r],o=this.nodeInfos[r],l=o.optimalLod,h=o.currentLod,f=this.selectDesiredLodIndex(a,l,t,i);if(f!==h){let u=h>=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;l<o.length;l++)if(o[l].fileIndex===r){a=l;break}this.nodeInfos[s].currentLod=a}}gh.length>0&&(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;h<this.lodLevels;h++){let f=o.lods[h.toString()];f?(l.push({file:this.files[f.file].url||"",fileIndex:f.file,offset:f.offset||0,count:f.count||0}),this.files[f.file].lodLevel=h):l.push({file:"",fileIndex:-1,offset:0,count:0})}return new AE(l,o.bound)});let r=this.nodes.length,a=new Float32Array(r*6);for(let o=0;o<r;o++){let l=this.nodes[o].bounds,h=l.getMin(),f=l.getMax(),u=o*6;a[u+0]=h.x,a[u+1]=h.y,a[u+2]=h.z,a[u+3]=f.x,a[u+4]=f.y,a[u+5]=f.z}this.nodeBoundsMinMax=a}destroy(){this.destroyed=!0,this.fileResources.clear(),this.cooldowns.clear(),this.assetLoader?.destroy(),this.assetLoader=null,this.environmentResource=null}_traceLodCounts(){}_extractLeafNodes(t,e){if(t.lods)e.push({lods:t.lods,bound:t.bound});else if(t.children)for(let s of t.children)this._extractLeafNodes(s,e)}getFileResource(t){return this.fileResources.get(t)}incRefCount(t){let e=this.fileRefCounts[t]+1;this.fileRefCounts[t]=e,this.cooldowns.delete(t)}decRefCount(t,e){let s=this.fileRefCounts[t]-1;this.fileRefCounts[t]=s,s===0&&(e===0?this.unloadResource(t):this.cooldowns.set(t,e))}unloadResource(t){if(!this.assetLoader)return;let e=this.files[t].url;this.assetLoader.unload(e),this.fileResources.has(t)&&(this.fileResources.delete(t),this._traceLodCounts())}updateCooldownTick(t){this.cooldownTicks=t,this.cooldowns.size>0&&(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;s<t.length;s++){let i=t[s],r=i.intervalAllocIds,a=i.intervals,o=a.length/2;if(o>0&&r.length===o)for(let l=0;l<o;l++)this._diffAlloc(r[l],a[l*2+1]-a[l*2],e);else this._diffAlloc(i.allocId,i.activeSplats,e)}for(let[s,i]of e)GR.has(s)||(m_.push(i),e.delete(s))}_diffAlloc(t,e,s){GR.add(t);let i=s.get(t);i?i.size!==e&&(m_.push(i),s.delete(t),e>0&&(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<Pl.length;h++)s.set(Pl[h],p_[h])}this.fullRebuild=i;let r=m_.length+Pl.length,a=Math.max(50,r);if(!i&&e.fragmentation>.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;o<t.length;o++){let l=t[o],h=l.intervalAllocIds,f=l.intervals,u=f.length/2;a+=u>0?u:1;let d=s,p=[];if(u>0&&h.length===u)for(let m=0;m<u;m++){this.allocIdToSplat.set(h[m],l);let _=e.get(h[m]);_&&(p.push(_.offset),r+=f[m*2+1]-f[m*2],i&&i.has(h[m])&&(d=!0,this.needsUploadIds.add(h[m])))}else{this.allocIdToSplat.set(l.allocId,l);let m=e.get(l.allocId);m&&(p.push(m.offset),r+=l.activeSplats,i&&i.has(l.allocId)&&(d=!0,this.needsUploadIds.add(l.allocId)))}if(p.length>0&&(l.setLayout(p),d&&(this.needsUpload.push(l),s)))for(let m=0;m<h.length;m++)this.needsUploadIds.add(h[m])}this.totalActiveSplats=r,this.totalIntervals=a}buildBoundsGroups(t){let e=new Map;for(let i=0;i<t.length;i++){let r=t[i],a=r.parentPlacementId;e.has(a)||e.set(a,{splat:r,boundsBaseIndex:0,numBoundsEntries:r.numBoundsEntries})}let s=0;for(let i of e.values())i.boundsBaseIndex=s,s+=i.numBoundsEntries,this.boundsGroups.push(i);for(let i=0;i<t.length;i++){let r=e.get(t[i].parentPlacementId);t[i].boundsBaseIndex=r.boundsBaseIndex}}};var wE=class{constructor(){n(this,"_states",new WeakMap)}hasChanges(t){let e=!1;for(let s of t){if(!s.resource)continue;let i=s.resource.format?.extraStreamsVersion??0,r=s.workBufferModifier?.hash??0,a=s.resource.numSplats??0,o=s.resource.centersVersion,l=this._states.get(s);l?(l.formatVersion!==i||l.modifierHash!==r||l.numSplats!==a||l.centersVersion!==o)&&(l.formatVersion=i,l.modifierHash=r,l.numSplats=a,l.centersVersion=o,e=!0):(this._states.set(s,{formatVersion:i,modifierHash:r,numSplats:a,centersVersion:o}),e=!0)}return e}};var hz=`
struct Interval {
workBufferBase: u32,
splatCount: u32,
boundsIndex: u32,
pad: u32
};
struct BoundsEntry {
centerX: f32,
centerY: f32,
centerZ: f32,
radius: f32,
transformIndex: u32,
pad0: u32,
pad1: u32,
pad2: u32
};
struct CullUniforms {
#ifdef GSPLAT_FISHEYE
cameraWorldPos: vec3f,
maxTheta: f32,
cameraForward: vec3f,
numIntervals: u32,
#else
frustumPlanes: array<vec4f, 6>,
numIntervals: u32
#endif
};
@group(0) @binding(0) var<uniform> uniforms: CullUniforms;
@group(0) @binding(1) var<storage, read> intervals: array<Interval>;
@group(0) @binding(2) var<storage, read_write> countBuffer: array<u32>;
@group(0) @binding(3) var<storage, read> boundsBuffer: array<BoundsEntry>;
@group(0) @binding(4) var<storage, read> transformsBuffer: array<vec4f>;
@compute @workgroup_size({WORKGROUP_SIZE})
fn main(@builtin(global_invocation_id) gid: vec3u) {
let idx = gid.x;
if (idx < uniforms.numIntervals) {
let interval = intervals[idx];
let entry = boundsBuffer[interval.boundsIndex];
let localCenter = vec3f(entry.centerX, entry.centerY, entry.centerZ);
let radius = entry.radius;
let base = entry.transformIndex * 3u;
let row0 = transformsBuffer[base];
let row1 = transformsBuffer[base + 1u];
let row2 = transformsBuffer[base + 2u];
let worldCenter = vec3f(
dot(vec4f(localCenter, 1.0), row0),
dot(vec4f(localCenter, 1.0), row1),
dot(vec4f(localCenter, 1.0), row2)
);
let worldRadius = radius * length(vec3f(row0.x, row1.x, row2.x));
#ifdef GSPLAT_FISHEYE
let v = worldCenter - uniforms.cameraWorldPos;
let d = length(v);
var visible = true;
if (d > worldRadius) {
let cosAngle = dot(v / d, uniforms.cameraForward);
let theta = acos(clamp(cosAngle, -1.0, 1.0));
let angularRadius = asin(min(worldRadius / d, 1.0));
visible = (theta - angularRadius) < uniforms.maxTheta;
}
#else
var visible = true;
for (var p = 0; p < 6; p++) {
let plane = uniforms.frustumPlanes[p];
let dist = dot(plane.xyz, worldCenter) + plane.w;
if (dist <= -worldRadius) {
visible = false;
break;
}
}
#endif
countBuffer[idx] = select(0u, interval.splatCount, visible);
}
if (idx == 0u) {
countBuffer[uniforms.numIntervals] = 0u;
}
}
`;var fz=`
struct Interval {
workBufferBase: u32,
splatCount: u32,
boundsIndex: u32,
pad: u32
};
struct ScatterUniforms {
numIntervals: u32,
pad0: u32,
pad1: u32,
pad2: u32
};
@group(0) @binding(0) var<uniform> uniforms: ScatterUniforms;
@group(0) @binding(1) var<storage, read> intervals: array<Interval>;
@group(0) @binding(2) var<storage, read> prefixSumBuffer: array<u32>;
@group(0) @binding(3) var<storage, read_write> compactedOutput: array<u32>;
@compute @workgroup_size({WORKGROUP_SIZE})
fn main(@builtin(workgroup_id) wgId: vec3u, @builtin(local_invocation_id) lid: vec3u) {
let intervalIdx = wgId.x;
if (intervalIdx >= uniforms.numIntervals) { return; }
let outputOffset = prefixSumBuffer[intervalIdx];
let nextOffset = prefixSumBuffer[intervalIdx + 1u];
let count = nextOffset - outputOffset;
if (count == 0u) { return; }
let workBufferBase = intervals[intervalIdx].workBufferBase;
let tid = lid.x;
for (var j = tid; j < count; j += {WORKGROUP_SIZE}u) {
compactedOutput[outputOffset + j] = workBufferBase + j;
}
}
`;var uz=`
${Jc}
${_h}
${vm}
@group(0) @binding(0) var<storage, read> prefixSumBuffer: array<u32>;
@group(0) @binding(1) var<storage, read_write> indirectDrawArgs: array<DrawIndexedIndirectArgs>;
@group(0) @binding(2) var<storage, read_write> numSplatsBuf: array<u32>;
@group(0) @binding(3) var<storage, read_write> indirectDispatchArgs: array<u32>;
@group(0) @binding(4) var<storage, read_write> sortElementCountBuf: array<u32>;
struct WriteArgsUniforms {
drawSlot: u32,
indexCount: u32,
dispatchSlotBase: u32,
totalSplats: u32,
sortIndirectInfo: vec4<u32>
};
@group(0) @binding(5) var<uniform> uniforms: WriteArgsUniforms;
@compute @workgroup_size(1)
fn main(@builtin(global_invocation_id) gid: vec3u) {
let count = prefixSumBuffer[uniforms.totalSplats];
let instanceCount = (count + {INSTANCE_SIZE}u - 1u) / {INSTANCE_SIZE}u;
indirectDrawArgs[uniforms.drawSlot] = DrawIndexedIndirectArgs(
uniforms.indexCount,
instanceCount,
0u,
0,
0u
);
numSplatsBuf[0] = count;
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[keygenOffset + 0u] = keygenDim.x;
indirectDispatchArgs[keygenOffset + 1u] = keygenDim.y;
indirectDispatchArgs[keygenOffset + 2u] = 1u;
writeSortIndirectArgs(keygenSlot + 1u, count, uniforms.sortIndirectInfo);
sortElementCountBuf[0] = count;
}
`;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;a<e.length;a++){let o=e[a];if(o.intervals.length>0){let l=o.intervalNodeIndices;for(let h=0;h<o.intervals.length;h+=2){let f=o.intervals[h+1]-o.intervals[h];i[r++]=o.intervalOffsets[h/2],i[r++]=f,i[r++]=o.boundsBaseIndex+(l.length>0?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;t<rn;t++)this._buckets[t]=[]}}balance(t,e){this._initBuckets();for(let o=0;o<rn;o++)this._buckets[o].length=0;let s=0;for(let[,o]of t){let l=o.octree.nodes,h=o.nodeInfos;for(let f=0,u=l.length;f<u;f++){let d=h[f],p=d.optimalLod;if(p<0)continue;let m=l[f].lods;d.lods=m,this._buckets[d.budgetBucket].push(d),s+=m[p].count}}let i=s;if(i===e)return;let r=i>e,a=!1;for(;!a&&(r?i>e:i<e);){let o=!1;if(r)for(let l=rn-1;l>=0&&!a;l--){let h=this._buckets[l];for(let f=0,u=h.length;f<u;f++){let d=h[f];if(d.optimalLod<d.inst.rangeMax){let p=d.lods,m=d.optimalLod;if(i-=p[m].count-p[m+1].count,d.optimalLod=m+1,o=!0,i<=e){a=!0;break}}}}else for(let l=0;l<rn&&!a;l++){let h=this._buckets[l];for(let f=0,u=h.length;f<u;f++){let d=h[f];if(d.optimalLod>d.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<s){let i=null,r=this._freeBucketHeads[e];for(;r&&!(r._size>=t&&(!i||r._size<i._size)&&(i=r,r._size===t));)r=r._nextFree;if(i)return i}for(let i=e+1;i<s;i++)if(this._freeBucketHeads[i])return this._freeBucketHeads[i];return null}allocate(t){let e=this._findFreeBlock(t);if(!e)return null;if(this._usedSize+=t,this._freeSize-=t,e._size===t)return e._free=!1,this._removeFromBucket(e),e;let s=this._obtain(e._offset,t,!1);return e._offset+=t,e._size-=t,this._rebucket(e),this._insertAfterInMainList(s,e._prev),s}free(t){t._free=!0,this._usedSize-=t._size,this._freeSize+=t._size;let e=t._prev,s=t._next,i=e&&e._free,r=s&&s._free;i&&r?(e._size+=t._size+s._size,this._removeFromMainList(t),this._removeFromMainList(s),this._removeFromBucket(s),this._release(t),this._release(s),this._rebucket(e)):i?(e._size+=t._size,this._removeFromMainList(t),this._release(t),this._rebucket(e)):r?(t._size+=s._size,this._removeFromMainList(s),this._removeFromBucket(s),this._release(s),this._addToBucket(t)):this._addToBucket(t)}grow(t){if(t<=this._capacity)return;let e=t-this._capacity;if(this._capacity=t,this._freeSize+=e,this._tailAll&&this._tailAll._free)this._tailAll._size+=e,this._rebucket(this._tailAll);else{let s=this._obtain(this._capacity-e,e,!0);this._insertAfterInMainList(s,this._tailAll),this._addToBucket(s)}}defrag(t=0,e=new Set){return e.clear(),this._freeRegionCount===0||(t===0?this._defragFull(e):this._defragIncremental(t,e)),e}_defragFull(t){for(let r=0;r<this._freeBucketHeads.length;r++){let a=this._freeBucketHeads[r];for(;a;){let o=a._nextFree;this._removeFromMainList(a),a._prevFree=null,a._nextFree=null,a._bucket=-1,this._pool.push(a),a=o}this._freeBucketHeads[r]=null}this._freeRegionCount=0;let e=0,s=this._headAll;for(;s;)s._offset!==e&&(s._offset=e,t.add(s)),e+=s._size,s=s._next;let i=this._capacity-e;if(i>0){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<s;a++){let o=this._tailAll;for(;o&&o._free;)o=o._prev;if(!o)break;let l=this._findFreeBlock(o._size);if(!l||l._offset>=o._offset)break;this._moveBlock(o,l),e.add(o)}let r=this._headAll;for(let a=0;a<i&&r;){let o=r._next;if(r._free&&o&&!o._free){let l=o,h=r;l._offset=h._offset,h._offset=l._offset+l._size;let f=h._prev,u=l._next;if(l._prev=f,l._next=h,h._prev=l,h._next=u,f?f._next=l:this._headAll=l,u?u._prev=h:this._tailAll=h,h._next&&h._next._free){let d=h._next;h._size+=d._size,this._removeFromMainList(d),this._removeFromBucket(d),this._release(d),this._rebucket(h)}e.add(l),a++,r=h._next}else r=o}}_moveBlock(t,e){let s=t._size,i=e._offset,r=t._prev;this._removeFromMainList(t);let a=this._obtain(t._offset,s,!0);if(this._insertAfterInMainList(a,r),this._addToBucket(a),a._next&&a._next._free){let o=a._next;a._size+=o._size,this._removeFromMainList(o),this._removeFromBucket(o),this._release(o),this._rebucket(a)}if(a._prev&&a._prev._free){let o=a._prev;o._size+=a._size,this._removeFromMainList(a),this._removeFromBucket(a),this._release(a),this._rebucket(o)}if(t._offset=i,e._size===s){let o=e._prev;this._removeFromMainList(e),this._removeFromBucket(e),this._release(e),this._insertAfterInMainList(t,o)}else e._offset+=s,e._size-=s,this._rebucket(e),this._insertAfterInMainList(t,e._prev)}updateAllocation(t,e){for(let s=0;s<t.length;s++)this.free(t[s]);for(let s=0;s<e.length;s++){let i=e[s],r=this.allocate(i);if(r)e[s]=r;else{let a=i;for(let h=s+1;h<e.length;h++)a+=e[h];let o=this._usedSize+a,l=Math.ceil(o*this._growMultiplier);l>this._capacity&&this.grow(l),this.defrag(0);for(let h=s;h<e.length;h++){let f=e[h],u=this.allocate(f);e[h]=u}return!0}}return!1}};var Sh=new x,JS=new x,dz=new x,wl=new x,ex=new W,kK=new Uint32Array([0,0,0,0]),__=new Set,XR=new Set,bE=[],YR=[],tx=new Set,KR={translationDelta:0},jR=new x,pz=new x,qR=new Set,$R=new Set,mz=[[1,0,0],[0,1,0],[0,0,1],[1,1,0],[1,0,1],[0,1,1],[1,.5,0],[.5,0,1]],K$e=[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),new F(0,1,1),new F(1,.5,0),new F(.5,0,1)],xh=null,DE=class{constructor(t,e,s,i){n(this,"device");n(this,"node",new Pe("GSplatManager"));n(this,"workBuffer");n(this,"renderer");n(this,"worldStates",new Map);n(this,"lastWorldStateVersion",0);n(this,"activeRenderer");n(this,"_worldStateDirty",!1);n(this,"cpuSorter",null);n(this,"gpuSorter",null);n(this,"intervalCompaction",null);n(this,"projector",null);n(this,"indirectDrawSlot",-1);n(this,"indirectDispatchSlot",-1);n(this,"lastCompactedNumIntervals",0);n(this,"sortedVersion",0);n(this,"_awaitingLodUpdate",!1);n(this,"_workBufferFormatVersion",-1);n(this,"_workBufferRebuildRequired",!1);n(this,"bufferCopyUploaded",0);n(this,"bufferCopyTotal",0);n(this,"_stateTracker",new wE);n(this,"_centersVersions",new Map);n(this,"framesTillFullUpdate",0);n(this,"lastLodCameraPos",new x(1/0,1/0,1/0));n(this,"lastLodCameraFwd",new x(1/0,1/0,1/0));n(this,"lastLodCameraFov",-1);n(this,"lastSortCameraPos",new x(1/0,1/0,1/0));n(this,"lastSortCameraFwd",new x(1/0,1/0,1/0));n(this,"lastCullingCameraFwd",new x(1/0,1/0,1/0));n(this,"lastCullingProjMat",new W);n(this,"sortNeeded",!0);n(this,"_budgetBalancer",new IE);n(this,"_budgetScale",1);n(this,"_allocator");n(this,"_allocationMap",new Map);n(this,"lastColorUpdateCameraPos",new x(1/0,1/0,1/0));n(this,"cameraNode");n(this,"scene");n(this,"layerPlacements",[]);n(this,"layerPlacementsDirty",!1);n(this,"_placementSetChanged",!1);n(this,"octreeInstances",new Map);n(this,"octreeInstancesToDestroy",[]);n(this,"hasNewOctreeInstances",!1);n(this,"renderMode");this.device=t,this.scene=e.scene,this.director=e,this.cameraNode=i;let r=1.15,a=this.scene.gsplat.splatBudget;this._allocator=new RE(a>0?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<this.layerPlacements.length;e++){let s=this.layerPlacements[e];if(!__.has(s)){this.layerPlacementsDirty=!0;break}}this._placementSetChanged||(this._placementSetChanged=this.layerPlacementsDirty),this.layerPlacements.length=0;for(let e of __)this.layerPlacements.push(e);__.clear(),XR.clear()}updateWorldState(){let t=this._stateTracker.hasChanges(this.layerPlacements);for(let[,i]of this.octreeInstances)this._stateTracker.hasChanges(i.activePlacements)&&(t=!0);if(this.layerPlacementsDirty||t||this.worldStates.size===0||this._worldStateDirty){this.lastWorldStateVersion++;let i=[];for(let a of this.layerPlacements){if(this.cpuSorter&&!a.resource.hasCenters)continue;a.ensureInstanceStreams(this.device);let o=new ZS(this.device,a.resource,a,a.consumeRenderDirty.bind(a));i.push(o)}for(let[,a]of this.octreeInstances)a.activePlacements.forEach(o=>{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;l<t.splats.length;l++)t.splats[l].update();if(this.updateColorCameraTracking(),t.pendingReleases&&t.pendingReleases.length){let l=this.scene.gsplat.cooldownTicks;for(let[h,f]of t.pendingReleases)h.decRefCount(f,l);t.pendingReleases.length=0}this.renderer.update(e,i)}cleanupOldWorldStates(t){let e=this.worldStates.get(t);if(!e.fullRebuild){for(let s=this.sortedVersion+1;s<t;s++)if(this.worldStates.get(s)?.fullRebuild){e.fullRebuild=!0;break}}if(!e.fullRebuild){let s=e.needsUploadIds,i=e.allocIdToSplat;for(let r=this.sortedVersion+1;r<t;r++){let a=this.worldStates.get(r);if(a){for(let o of a.needsUploadIds)if(!s.has(o)){s.add(o);let l=i.get(o);l&&!$R.has(l)&&(e.needsUpload.push(l),$R.add(l))}}}$R.clear()}for(let s=this.sortedVersion;s<t;s++){let i=this.worldStates.get(s);if(i){for(let r of i.splats)r.resource.decRefCount();this.worldStates.delete(s),i.destroy()}}}applyWorkBufferUpdates(t){let{colorUpdateAngle:e}=this.scene.gsplat,s=Math.tan(e*R.DEG_TO_RAD),i=this.cameraNode.getPosition(),{translationDelta:r}=this.calculateColorCameraDeltas(),a=r>0,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<h.length;f++){let u=l.nodeInfos[h[f]];u.colorAccumulatedTranslation+=r;let d=s*Math.max(1,u.worldDistance);u.colorAccumulatedTranslation>=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;r<mz.length;r++)xh[r]??(xh[r]=[0,0,0]),xh[r][0]=e,xh[r][1]=s,xh[r][2]=i;return xh}else if(t===Pc)return mz}calculateColorCameraDeltas(){if(KR.translationDelta=0,isFinite(this.lastColorUpdateCameraPos.x)){let t=this.cameraNode.getPosition();KR.translationDelta=this.lastColorUpdateCameraPos.distance(t)}return KR}fireFrameReadyEvent(){let t=this.sortedVersion===this.lastWorldStateVersion&&!this._awaitingLodUpdate,e=0;for(let[,s]of this.octreeInstances)e+=s.pendingLoadCount;this.director.eventHandler.fire("frame:ready",this.cameraNode.camera,this.renderer.layer,t,e)}computeGlobalMaxDistance(){let t=0;Sh.copy(this.cameraNode.getPosition());for(let[,e]of this.octreeInstances){let s=e.placement.node.getWorldTransform(),i=e.placement.aabb;s.transformPoint(i.center,wl);let r=s.getScale().x,a=wl.distance(Sh)+i.halfExtents.length()*r;a>t&&(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);d<r&&(r=d),d>a&&(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;l<ME.length;l++){let h=ME[l],f=a.layersMap.get(h);f&&(f.destroy(),a.layersMap.delete(h))}ME.length=0}});let e=0,s=0,i=0,r=t.cameras;for(let a=0;a<r.length;a++){let o=r[a].camera,l=this.camerasMap.get(o),h=o.layers;for(let f=0;f<h.length;f++){let u=t.getLayerById(h[f]);if(u?.enabled&&(u.gsplatPlacementsDirty||!l)){let d=u.gsplatPlacements.length>0,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;a<t.layerList.length;a++)t.layerList[a].gsplatPlacementsDirty=!1}};var Du=class extends le{constructor(e,s){super(e,s);n(this,"_layers",[Os]);n(this,"_instance",null);n(this,"_placement",null);n(this,"_id",bT.get());n(this,"_materialTmp",null);n(this,"_highQualitySH",!0);n(this,"_lodBaseDistance",5);n(this,"_lodMultiplier",3);n(this,"_customAabb",null);n(this,"_assetReference");n(this,"_resource",null);n(this,"_evtLayersChanged",null);n(this,"_evtLayerAdded",null);n(this,"_evtLayerRemoved",null);n(this,"_castShadows",!1);n(this,"_unified",!0);n(this,"_parameters",new Map);n(this,"_workBufferUpdate",Tp);n(this,"_workBufferModifier",null);this._assetReference=new pa("asset",this,e.app.assets,{add:this._onGSplatAssetAdded,load:this._onGSplatAssetLoad,remove:this._onGSplatAssetRemove,unload:this._onGSplatAssetUnload},this),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 customAabb(e){this._customAabb=e,this._instance?.meshInstance?.setCustomAabb(this._customAabb),this._placement&&(this._placement.aabb=this._customAabb)}get customAabb(){return this._customAabb??this._placement?.aabb??this.resource?.aabb??null}set instance(e){if(!this.unified&&(this.destroyInstance(),this._instance=e,this._instance)){let s=this._instance.meshInstance;s.node||(s.node=this.entity),s.castShadow=this._castShadows,s.setCustomAabb(this._customAabb),this.enabled&&this.entity.enabled&&this.addToLayers()}}get instance(){return this.unified,this._instance}set material(e){this.unified||(this._instance?this._instance.material=e:this._materialTmp=e)}get material(){return this.unified?null:this._instance?.material??this._materialTmp??null}set highQualitySH(e){e!==this._highQualitySH&&(this._highQualitySH=e,this._instance?.setHighQualitySH(e))}get highQualitySH(){return this._highQualitySH}set castShadows(e){if(this._castShadows!==e){let s=this.layers,i=this.system.app.scene;if(this._placement)if(e)for(let a=0;a<s.length;a++)i.layers.getLayerById(s[a])?.addGSplatShadowCaster(this._placement);else for(let a=0;a<s.length;a++)i.layers.getLayerById(s[a])?.removeGSplatShadowCaster(this._placement);let r=this._instance?.meshInstance;if(r){if(this._castShadows&&!e)for(let a=0;a<s.length;a++)i.layers.getLayerById(this.layers[a])?.removeShadowCasters([r]);if(r.castShadow=e,!this._castShadows&&e)for(let a=0;a<s.length;a++)i.layers.getLayerById(s[a])?.addShadowCasters([r])}this._castShadows=e}}get castShadows(){return this._castShadows}set lodBaseDistance(e){this._lodBaseDistance=Math.max(.1,e),this._placement&&(this._placement.lodBaseDistance=this._lodBaseDistance)}get lodBaseDistance(){return this._lodBaseDistance}set lodMultiplier(e){this._lodMultiplier=Math.max(1.2,e),this._placement&&(this._placement.lodMultiplier=this._lodMultiplier)}get lodMultiplier(){return this._lodMultiplier}set lodDistances(e){Array.isArray(e)&&e.length>0&&(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<e.length;s++)this._layers[s]=e[s];!this.enabled||!this.entity.enabled||this.addToLayers()}get layers(){return this._layers}set asset(e){let s=e instanceof ae?e.id:e;this._assetReference.id!==s&&(this._assetReference.asset&&this._assetReference.asset.resource&&this._onGSplatAssetRemove(),this._assetReference.id=s,this._assetReference.asset&&this._onGSplatAssetAdded())}get asset(){return this._assetReference.id}set resource(e){this._resource!==e&&((this._resource||this._assetReference.asset?.resource)&&this._onGSplatAssetRemove(),e&&this._assetReference.id&&(this._assetReference.id=null),this._resource=e,this._resource&&this.enabled&&this.entity.enabled&&this._onGSplatAssetLoad())}get resource(){return this._resource??this._assetReference.asset?.resource??null}destroyInstance(){this._placement&&(this.removeFromLayers(),this._placement.destroy(),this._placement=null),this._instance&&(this.removeFromLayers(),this._instance?.destroy(),this._instance=null)}addToLayers(){if(this._placement){let s=this.system.app.scene.layers;for(let i=0;i<this._layers.length;i++){let r=s.getLayerById(this._layers[i]);r&&(r.addGSplatPlacement(this._placement),this._castShadows&&r.addGSplatShadowCaster(this._placement))}return}let e=this._instance?.meshInstance;if(e){let s=this.system.app.scene.layers;for(let i=0;i<this._layers.length;i++)s.getLayerById(this._layers[i])?.addMeshInstances([e])}}removeFromLayers(){if(this._placement){let s=this.system.app.scene.layers;for(let i=0;i<this._layers.length;i++){let r=s.getLayerById(this._layers[i]);r&&(r.removeGSplatPlacement(this._placement),r.removeGSplatShadowCaster(this._placement))}return}let e=this._instance?.meshInstance;if(e){let s=this.system.app.scene.layers;for(let i=0;i<this._layers.length;i++)s.getLayerById(this._layers[i])?.removeMeshInstances([e])}}onRemoveChild(){this.removeFromLayers()}onInsertChild(){this.enabled&&this.entity.enabled&&(this._instance||this._placement)&&this.addToLayers()}onRemove(){this.destroyInstance(),this.asset=null,this._assetReference.id=null,this.entity.off("remove",this.onRemoveChild,this),this.entity.off("insert",this.onInsertChild,this)}onLayersChanged(e,s){this.addToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),s.on("add",this.onLayerAdded,this),s.on("remove",this.onLayerRemoved,this)}onLayerAdded(e){this.layers.indexOf(e.id)<0||this.unified||this._instance&&e.addMeshInstances(this._instance.meshInstance)}onLayerRemoved(e){this.layers.indexOf(e.id)<0||this.unified||this._instance&&e.removeMeshInstances(this._instance.meshInstance)}onEnable(){let e=this.system.app.scene,s=e.layers;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._instance||this._placement?this.addToLayers():this.asset?this._onGSplatAssetAdded():this._resource&&this._onGSplatAssetLoad()}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.removeFromLayers()}hide(){this._instance&&(this._instance.meshInstance.visible=!1)}show(){this._instance&&(this._instance.meshInstance.visible=!0)}setParameter(e,s){let i=this.system.app.graphicsDevice.scope.resolve(e);this._parameters.set(e,{scopeId:i,data:s}),this._placement&&(this._placement.renderDirty=!0)}getParameter(e){return this._parameters.get(e)?.data}deleteParameter(e){this._parameters.delete(e),this._placement&&(this._placement.renderDirty=!0)}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 bu(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 hm(e,{material:this._materialTmp,highQualitySH:this._highQualitySH,scene:this.system.app.scene}),this._materialTmp=null))}_onGSplatAssetUnload(){this.destroyInstance()}_onGSplatAssetRemove(){this._onGSplatAssetUnload()}};var FE=class{constructor(){n(this,"enabled",!0)}};var _z=`
uniform mat4 matrix_model;
uniform mat4 matrix_view;
#ifndef GSPLAT_CENTER_NOPROJ
uniform vec4 camera_params;
uniform mat4 matrix_projection;
#ifdef GSPLAT_FISHEYE
uniform float fisheye_k;
uniform float fisheye_inv_k;
uniform float fisheye_projMat00;
uniform float fisheye_projMat11;
#endif
#endif
bool initCenter(vec3 modelCenter, inout SplatCenter center) {
mat4 modelView = matrix_view * matrix_model;
vec4 centerView = modelView * vec4(modelCenter, 1.0);
#ifndef GSPLAT_CENTER_NOPROJ
#ifdef GSPLAT_FISHEYE
vec3 v = centerView.xyz;
float r_xy = length(v.xy);
float neg_z = -v.z;
float theta = atan(r_xy, neg_z);
float maxTheta = min(fisheye_k * 1.5707963, 3.13);
if (theta > maxTheta - 0.01 || dot(v, v) < 0.0001) {
return false;
}
float tk = theta * fisheye_inv_k;
float sin_tk = sin(tk);
float cos_tk = cos(tk);
float g_theta = fisheye_k * sin_tk / cos_tk;
float fisheye_s = (r_xy > 1e-4) ? g_theta / r_xy : (neg_z > 0.0 ? 1.0 / neg_z : 0.0);
vec2 ndc = vec2(fisheye_projMat00 * fisheye_s * v.x, fisheye_projMat11 * fisheye_s * v.y);
float near = camera_params.z;
float far = camera_params.y;
float linearDepth = neg_z;
#if WEBGPU
float depthNdc = clamp((linearDepth - near) / (far - near), 0.0, 1.0);
#else
float depthNdc = clamp(2.0 * (linearDepth - near) / (far - near) - 1.0, -1.0, 1.0);
#endif
center.proj = vec4(ndc, depthNdc, 1.0);
center.projMat00 = fisheye_projMat00;
center.fisheyeSinTK = sin_tk;
center.fisheyeCosTK = cos_tk;
center.fisheyeRxy = r_xy;
#else
if (camera_params.w != 1.0 && centerView.z > 0.0) {
return false;
}
vec4 centerProj = matrix_projection * centerView;
#if WEBGPU
centerProj.z = clamp(centerProj.z, 0, abs(centerProj.w));
#else
centerProj.z = clamp(centerProj.z, -abs(centerProj.w), abs(centerProj.w));
#endif
center.proj = centerProj;
center.projMat00 = matrix_projection[0][0];
#endif
#endif
center.view = centerView.xyz / centerView.w;
center.modelView = modelView;
return true;
}
`;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 float alphaClip;
#else
uniform float alphaClipForward;
#endif
void clipCorner(inout SplatCorner corner, float alpha) {
#if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS)
float alphaClipValue = alphaClip;
#else
float alphaClipValue = alphaClipForward;
#endif
float clip = min(1.0, sqrt(max(0.0, log(alpha / alphaClipValue))) * 0.5);
corner.offset *= clip;
corner.uv *= clip;
}
`;var Sz=`
struct Splat {
uint index;
ivec2 uv;
};
Splat splat;
void setSplat(uint idx) {
splat.index = idx;
splat.uv = ivec2(idx % splatTextureSize, idx / splatTextureSize);
}
`;var xz=`
#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
`;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) {
mat3 rot = quatToMat3(rotation);
mat3 M = transpose(mat3(
scale.x * rot[0],
scale.y * rot[1],
scale.z * rot[2]
));
covA = vec3(dot(M[0], M[0]), dot(M[0], M[1]), dot(M[0], M[2]));
covB = vec3(dot(M[1], M[1]), dot(M[1], M[2]), dot(M[2], M[2]));
}
bool initCornerCov(SplatSource source, SplatCenter center, out SplatCorner corner, vec3 covA, vec3 covB) {
mat3 Vrk = mat3(
covA.x, covA.y, covA.z,
covA.y, covB.x, covB.y,
covA.z, covB.y, covB.z
);
float focal = viewport_size.x * center.projMat00;
vec3 v = center.view.xyz;
#ifdef GSPLAT_FISHEYE
float r_sq = max(center.fisheyeRxy * center.fisheyeRxy, 1e-8);
float d2 = dot(v, v);
float neg_z = -v.z;
float g_prime = 1.0 / (center.fisheyeCosTK * center.fisheyeCosTK);
float g_theta = fisheye_k * center.fisheyeSinTK / center.fisheyeCosTK;
float sv = (center.fisheyeRxy > 1e-4) ? g_theta / center.fisheyeRxy : (neg_z > 0.0 ? 1.0 / neg_z : 0.0);
float K = (center.fisheyeRxy > 1e-4) ? (g_prime * neg_z / d2 - sv) / r_sq : 0.0;
mat3 J = mat3(
focal * (sv + K * v.x * v.x), focal * K * v.x * v.y, focal * g_prime * v.x / d2,
focal * K * v.x * v.y, focal * (sv + K * v.y * v.y), focal * g_prime * v.y / d2,
0.0, 0.0, 0.0
);
#else
vec3 vp = camera_params.w == 1.0 ? vec3(0.0, 0.0, 1.0) : v;
float J1 = focal / vp.z;
vec2 J2 = -J1 / vp.z * vp.xy;
mat3 J = mat3(
J1, 0.0, J2.x,
0.0, J1, J2.y,
0.0, 0.0, 0.0
);
#endif
mat3 W = transpose(mat3(center.modelView));
mat3 T = W * J;
mat3 cov = transpose(T) * Vrk * T;
#if GSPLAT_AA
float detOrig = cov[0][0] * cov[1][1] - cov[0][1] * cov[0][1];
float detBlur = (cov[0][0] + 0.3) * (cov[1][1] + 0.3) - cov[0][1] * cov[0][1];
corner.aaFactor = sqrt(max(detOrig / detBlur, 0.0));
#endif
float diagonal1 = cov[0][0] + 0.3;
float offDiagonal = cov[0][1];
float diagonal2 = cov[1][1] + 0.3;
float mid = 0.5 * (diagonal1 + diagonal2);
float radius = length(vec2((diagonal1 - diagonal2) / 2.0, offDiagonal));
float lambda1 = mid + radius;
float lambda2 = max(mid - radius, 0.1);
float vmin = min(1024.0, min(viewport_size.x, viewport_size.y));
float l1 = 2.0 * min(sqrt(2.0 * lambda1), vmin);
float l2 = 2.0 * min(sqrt(2.0 * lambda2), vmin);
if (max(l1, l2) < minPixelSize) {
return false;
}
vec2 c = center.proj.ww * viewport_size.zw;
if (any(greaterThan(abs(center.proj.xy) - vec2(max(l1, l2)) * c, center.proj.ww))) {
return false;
}
vec2 diagonalVector = normalize(vec2(offDiagonal, lambda1 - diagonal1));
vec2 v1 = l1 * diagonalVector;
vec2 v2 = l2 * vec2(diagonalVector.y, -diagonalVector.x);
corner.offset = vec3((source.cornerUV.x * v1 + source.cornerUV.y * v2) * c, 0.0);
corner.uv = source.cornerUV;
return true;
}
#if GSPLAT_2DGS
void initCorner2DGS(SplatSource source, vec4 rotation, vec3 scale, out SplatCorner corner) {
vec2 localPos = source.cornerUV * vec2(scale.x, scale.y) * 3.0;
vec3 v = vec3(localPos, 0.0);
vec3 t = 2.0 * cross(rotation.xyz, v);
corner.offset = v + rotation.w * t + cross(rotation.xyz, t);
corner.uv = source.cornerUV;
}
#endif
bool initCorner(SplatSource source, SplatCenter center, out SplatCorner corner) {
vec4 rotation = getRotation().yzwx;
vec3 scale = getScale();
modifySplatRotationScale(center.modelCenterOriginal, center.modelCenterModified, rotation, scale);
#if GSPLAT_2DGS
initCorner2DGS(source, rotation, scale, corner);
return true;
#else
vec3 covA, covB;
computeCovariance(rotation.wxyz, scale, covA, covB);
return initCornerCov(source, center, corner, covA, covB);
#endif
}
`;var Cz=`
#include "tonemappingPS"
#include "decodePS"
#include "gammaPS"
#include "fogPS"
#if FOG != NONE && !defined(GSPLAT_NO_FOG)
#define GSPLAT_FOG
#endif
vec3 prepareOutputFromGamma(vec3 gammaColor, float depth) {
vec3 color = gammaColor;
#if TONEMAP != NONE || GAMMA == NONE || defined(GSPLAT_FOG)
color = decodeGamma(color);
#endif
#ifdef GSPLAT_FOG
color = addFog(color, depth);
#endif
#if TONEMAP != NONE
color = toneMap(color);
#endif
#if TONEMAP != NONE || (GAMMA != NONE && defined(GSPLAT_FOG))
color = gammaCorrectOutput(color);
#endif
return color;
}
`;var Pz=`
#ifndef DITHER_NONE
#include "bayerPS"
#include "opacityDitherPS"
varying float id;
#endif
#if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS)
uniform float alphaClip;
#endif
#ifdef PREPASS_PASS
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)
flat varying uint vPickId;
#endif
#ifdef PICK_PASS
#include "pickPS"
#endif
const float EXP4 = exp(-4.0);
const float INV_EXP4 = 1.0 / (1.0 - EXP4);
float normExp(float x) {
return (exp(x * -4.0) - EXP4) * INV_EXP4;
}
void main(void) {
mediump float A = dot(gaussianUV, gaussianUV);
if (A > 1.0) {
discard;
}
mediump float alpha = normExp(A) * gaussianColor.a;
#if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS)
if (alpha < alphaClip) {
discard;
}
#endif
#ifdef PICK_PASS
#ifdef GSPLAT_UNIFIED_ID
pcFragColor0 = encodePickOutput(vPickId);
#else
pcFragColor0 = getPickOutput();
#endif
#ifdef DEPTH_PICK_PASS
pcFragColor1 = getPickDepth();
#endif
#elif SHADOW_PASS
gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
#elif PREPASS_PASS
gl_FragColor = float2vec4(vLinearDepth);
#else
if (alpha < alphaClipForward) {
discard;
}
#ifndef DITHER_NONE
opacityDither(alpha, id * 0.013);
#endif
gl_FragColor = vec4(gaussianColor.xyz * alpha, alpha);
#endif
}
`;var wz=`
attribute vec3 vertex_position;
uniform uint numSplats;
uniform highp usampler2D splatOrder;
bool initSource(out SplatSource source) {
source.order = uint(gl_InstanceID) * {GSPLAT_INSTANCE_SIZE}u + uint(vertex_position.z);
if (source.order >= numSplats) {
return false;
}
ivec2 orderUV = ivec2(source.order % splatTextureSize, source.order / splatTextureSize);
uint splatId = texelFetch(splatOrder, orderUV, 0).r;
setSplat(splatId);
source.cornerUV = vertex_position.xy;
return true;
}
`;var Iz=`
#include "gsplatCommonVS"
varying mediump vec2 gaussianUV;
varying mediump vec4 gaussianColor;
#ifndef DITHER_NONE
varying float id;
#endif
mediump vec4 discardVec = vec4(0.0, 0.0, 2.0, 1.0);
#ifdef PREPASS_PASS
varying float vLinearDepth;
#endif
#if defined(GSPLAT_UNIFIED_ID) && defined(PICK_PASS)
flat varying uint vPickId;
#endif
#ifdef GSPLAT_OVERDRAW
uniform sampler2D colorRamp;
uniform float colorRampIntensity;
#endif
void main(void) {
SplatSource source;
if (!initSource(source)) {
gl_Position = discardVec;
return;
}
vec3 modelCenter = getCenter();
SplatCenter center;
center.modelCenterOriginal = modelCenter;
modifySplatCenter(modelCenter);
center.modelCenterModified = modelCenter;
if (!initCenter(modelCenter, center)) {
gl_Position = discardVec;
return;
}
SplatCorner corner;
if (!initCorner(source, center, corner)) {
gl_Position = discardVec;
return;
}
#ifdef GSPLAT_SEPARATE_OPACITY
float opacity = getOpacity();
vec4 clr = vec4(getColor(), opacity);
#else
vec4 clr = getColor();
#endif
#if GSPLAT_AA
clr.a *= corner.aaFactor;
#endif
#if SH_BANDS > 0
vec3 dir = normalize(center.view * mat3(center.modelView));
vec3 sh[SH_COEFFS];
float scale;
readSHData(sh, scale);
clr.xyz += evalSH(sh, dir) * scale;
#endif
modifySplatColor(modelCenter, clr);
#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;
}
clipCorner(corner, clr.w);
#if GSPLAT_2DGS
vec3 modelCorner = center.modelCenterModified + corner.offset;
gl_Position = matrix_projection * center.modelView * vec4(modelCorner, 1.0);
#else
gl_Position = center.proj + vec4(corner.offset.xyz, 0);
#endif
gaussianUV = corner.uv;
#ifdef GSPLAT_OVERDRAW
float t = clamp(modelCenter.y / 20.0, 0.0, 1.0);
vec3 rampColor = textureLod(colorRamp, vec2(t, 0.5), 0.0).rgb;
clr.a *= (1.0 / 32.0) * colorRampIntensity;
gaussianColor = vec4(rampColor, clr.a);
#else
gaussianColor = vec4(prepareOutputFromGamma(max(clr.xyz, 0.0), -center.view.z), clr.w);
#endif
#ifndef DITHER_NONE
id = float(splat.index);
#endif
#ifdef PREPASS_PASS
vLinearDepth = -center.view.z;
#endif
#if defined(GSPLAT_UNIFIED_ID) && defined(PICK_PASS)
vPickId = loadPcId().r;
#endif
}
`;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;
}
uint pack101010(vec3 v) {
uvec3 t = uvec3(v * 1023.0) << uvec3(20u, 10u, 0u);
return t.x | t.y | t.z;
}
uint pack111110(vec3 v) {
uvec3 t = uvec3(v * vec3(2047.0, 2047.0, 1023.0)) << uvec3(21u, 10u, 0u);
return t.x | t.y | t.z;
}
vec4 unpack8888(uint v) {
return vec4((uvec4(v) >> uvec4(24u, 16u, 8u, 0u)) & 0xffu) / 255.0;
}
vec3 unpack101010(uint v) {
return vec3((uvec3(v) >> uvec3(20u, 10u, 0u)) & 0x3ffu) / 1023.0;
}
vec3 unpack111110(uint v) {
return vec3((uvec3(v) >> uvec3(21u, 10u, 0u)) & uvec3(0x7ffu, 0x7ffu, 0x3ffu)) / vec3(2047.0, 2047.0, 1023.0);
}
vec3 resolveCodebook(vec3 s, vec4 codebook[64]) {
uvec3 idx = uvec3(s * 255.0);
vec3 v = vec3(
codebook[idx.x >> 2u][idx.x & 3u],
codebook[idx.y >> 2u][idx.y & 3u],
codebook[idx.z >> 2u][idx.z & 3u]
);
return (v - codebook[0].x) / (codebook[63].w - codebook[0].x);
}
`;var bz=`
uniform uint splatTextureSize;
`;var Dz=`
uint tAw;
vec4 tBcached;
vec4 unpackRotation(vec3 data) {
return vec4(data.xyz, sqrt(max(0.0, 1.0 - dot(data, data))));
}
vec3 getCenter() {
uvec4 tA = loadTransformA();
tAw = tA.w;
tBcached = loadTransformB();
return uintBitsToFloat(tA.xyz);
}
vec4 getColor() {
return loadSplatColor();
}
vec4 getRotation() {
return unpackRotation(vec3(unpackHalf2x16(tAw), tBcached.w)).wxyz;
}
vec3 getScale() {
return tBcached.xyz;
}
#include "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;
}
void fetchScale(in uvec4 t, out float scale, out vec3 a, out vec3 b, out vec3 c) {
scale = uintBitsToFloat(t.x);
a = unpack111011s(t.y);
b = unpack111011s(t.z);
c = unpack111011s(t.w);
}
void fetch(in uvec4 t, out vec3 a, out vec3 b, out vec3 c, out vec3 d) {
a = unpack111011s(t.x);
b = unpack111011s(t.y);
c = unpack111011s(t.z);
d = unpack111011s(t.w);
}
void fetch(in uint t, out vec3 a) {
a = unpack111011s(t);
}
#if SH_BANDS == 1
void readSHData(out vec3 sh[3], out float scale) {
fetchScale(loadSplatSH_1to3(), scale, sh[0], sh[1], sh[2]);
}
#elif SH_BANDS == 2
void readSHData(out vec3 sh[8], out float scale) {
fetchScale(loadSplatSH_1to3(), scale, sh[0], sh[1], sh[2]);
fetch(loadSplatSH_4to7(), sh[3], sh[4], sh[5], sh[6]);
fetch(loadSplatSH_8to11().x, sh[7]);
}
#else
void readSHData(out vec3 sh[15], out float scale) {
fetchScale(loadSplatSH_1to3(), scale, sh[0], sh[1], sh[2]);
fetch(loadSplatSH_4to7(), sh[3], sh[4], sh[5], sh[6]);
fetch(loadSplatSH_8to11(), sh[7], sh[8], sh[9], sh[10]);
fetch(loadSplatSH_12to15(), sh[11], sh[12], sh[13], sh[14]);
}
#endif
#endif
`;var Mz=`
#include "gsplatPackingPS"
uniform highp sampler2D chunkTexture;
vec4 chunkDataA;
vec4 chunkDataB;
vec4 chunkDataC;
vec4 chunkDataD;
vec4 chunkDataE;
uvec4 packedData;
vec3 unpack111011(uint bits) {
return vec3(
float(bits >> 21u) / 2047.0,
float((bits >> 11u) & 0x3ffu) / 1023.0,
float(bits & 0x7ffu) / 2047.0
);
}
const float norm = sqrt(2.0);
vec4 unpackRotation(uint bits) {
float a = (float((bits >> 20u) & 0x3ffu) / 1023.0 - 0.5) * norm;
float b = (float((bits >> 10u) & 0x3ffu) / 1023.0 - 0.5) * norm;
float c = (float(bits & 0x3ffu) / 1023.0 - 0.5) * norm;
float m = sqrt(1.0 - (a * a + b * b + c * c));
uint mode = bits >> 30u;
if (mode == 0u) return vec4(m, a, b, c);
if (mode == 1u) return vec4(a, m, b, c);
if (mode == 2u) return vec4(a, b, m, c);
return vec4(a, b, c, m);
}
vec3 getCenter() {
uint w = uint(textureSize(chunkTexture, 0).x) / 5u;
uint chunkId = splat.index / 256u;
ivec2 chunkUV = ivec2((chunkId % w) * 5u, chunkId / w);
chunkDataA = texelFetch(chunkTexture, chunkUV, 0);
chunkDataB = texelFetch(chunkTexture, chunkUV + ivec2(1, 0), 0);
chunkDataC = texelFetch(chunkTexture, chunkUV + ivec2(2, 0), 0);
chunkDataD = texelFetch(chunkTexture, chunkUV + ivec2(3, 0), 0);
chunkDataE = texelFetch(chunkTexture, chunkUV + ivec2(4, 0), 0);
packedData = loadPackedTexture();
return mix(chunkDataA.xyz, vec3(chunkDataA.w, chunkDataB.xy), unpack111011(packedData.x));
}
vec4 getColor() {
vec4 r = unpack8888(packedData.w);
return vec4(mix(chunkDataD.xyz, vec3(chunkDataD.w, chunkDataE.xy), r.rgb), r.w);
}
vec4 getRotation() {
return unpackRotation(packedData.y);
}
vec3 getScale() {
return exp(mix(vec3(chunkDataB.zw, chunkDataC.x), chunkDataC.yzw, unpack111011(packedData.z)));
}
#include "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;
}
void readSHData(out vec3 sh[15], out float scale) {
uvec4 shData0 = loadShTexture0();
uvec4 shData1 = loadShTexture1();
uvec4 shData2 = loadShTexture2();
vec4 r0 = unpack8888s(shData0.x);
vec4 r1 = unpack8888s(shData0.y);
vec4 r2 = unpack8888s(shData0.z);
vec4 r3 = unpack8888s(shData0.w);
vec4 g0 = unpack8888s(shData1.x);
vec4 g1 = unpack8888s(shData1.y);
vec4 g2 = unpack8888s(shData1.z);
vec4 g3 = unpack8888s(shData1.w);
vec4 b0 = unpack8888s(shData2.x);
vec4 b1 = unpack8888s(shData2.y);
vec4 b2 = unpack8888s(shData2.z);
vec4 b3 = unpack8888s(shData2.w);
sh[0] = vec3(r0.x, g0.x, b0.x);
sh[1] = vec3(r0.y, g0.y, b0.y);
sh[2] = vec3(r0.z, g0.z, b0.z);
sh[3] = vec3(r0.w, g0.w, b0.w);
sh[4] = vec3(r1.x, g1.x, b1.x);
sh[5] = vec3(r1.y, g1.y, b1.y);
sh[6] = vec3(r1.z, g1.z, b1.z);
sh[7] = vec3(r1.w, g1.w, b1.w);
sh[8] = vec3(r2.x, g2.x, b2.x);
sh[9] = vec3(r2.y, g2.y, b2.y);
sh[10] = vec3(r2.z, g2.z, b2.z);
sh[11] = vec3(r2.w, g2.w, b2.w);
sh[12] = vec3(r3.x, g3.x, b3.x);
sh[13] = vec3(r3.y, g3.y, b3.y);
sh[14] = vec3(r3.z, g3.z, b3.z);
scale = 1.0;
}
#endif
`;var Fz=`
uniform vec3 means_mins;
uniform vec3 means_maxs;
#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;
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() {
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 getRotation() {
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 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"
`;var Nz=`
#if SH_BANDS > 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;
}
#endif
`;var Bz=`
#include "gsplatContainerDeclarationsVS"
vec3 splatCenter;
vec4 splatColor;
vec3 splatScale;
vec4 splatRotation;
`;var Uz=`
vec3 getCenter() {
#include "gsplatContainerUserReadVS"
return splatCenter;
}
vec4 getRotation() {
return splatRotation;
}
vec3 getScale() {
return splatScale;
}
vec4 getColor() {
return splatColor;
}
`;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
uniform camera_params: vec4f;
uniform matrix_projection: mat4x4f;
#ifdef GSPLAT_FISHEYE
uniform fisheye_k: f32;
uniform fisheye_inv_k: f32;
uniform fisheye_projMat00: f32;
uniform fisheye_projMat11: f32;
#endif
#endif
fn initCenter(modelCenter: vec3f, center: ptr<function, SplatCenter>) -> bool {
let modelView: mat4x4f = uniform.matrix_view * uniform.matrix_model;
let centerView: vec4f = modelView * vec4f(modelCenter, 1.0);
#ifndef GSPLAT_CENTER_NOPROJ
#ifdef GSPLAT_FISHEYE
let v: vec3f = centerView.xyz;
let r_xy: f32 = length(v.xy);
let neg_z: f32 = -v.z;
let theta: f32 = atan2(r_xy, neg_z);
let maxTheta: f32 = min(uniform.fisheye_k * 1.5707963, 3.13);
if (theta > maxTheta - 0.01 || dot(v, v) < 0.0001) {
return false;
}
let tk: f32 = theta * uniform.fisheye_inv_k;
let sin_tk: f32 = sin(tk);
let cos_tk: f32 = cos(tk);
let g_theta: f32 = uniform.fisheye_k * sin_tk / cos_tk;
let fisheye_s: f32 = select(select(0.0, 1.0 / neg_z, neg_z > 0.0), g_theta / r_xy, r_xy > 1e-4);
let ndc: vec2f = vec2f(uniform.fisheye_projMat00 * fisheye_s * v.x, uniform.fisheye_projMat11 * fisheye_s * v.y);
let near: f32 = uniform.camera_params.z;
let far: f32 = uniform.camera_params.y;
let linearDepth: f32 = neg_z;
let depthNdc: f32 = clamp((linearDepth - near) / (far - near), 0.0, 1.0);
center.proj = vec4f(ndc, depthNdc, 1.0);
center.projMat00 = uniform.fisheye_projMat00;
center.fisheyeSinTK = sin_tk;
center.fisheyeCosTK = cos_tk;
center.fisheyeRxy = r_xy;
#else
if (uniform.camera_params.w != 1.0 && centerView.z > 0.0) {
return false;
}
var centerProj: vec4f = uniform.matrix_projection * centerView;
centerProj.z = clamp(centerProj.z, 0.0, abs(centerProj.w));
center.proj = centerProj;
center.projMat00 = uniform.matrix_projection[0][0];
#endif
#endif
center.view = centerView.xyz / centerView.w;
center.modelView = modelView;
return true;
}
`;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<function, SplatCorner>, 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<private> 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<function, array<half3, SH_COEFFS>>, 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<function, vec3f>, 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<function, vec3f>) {
}
fn modifySplatRotationScale(originalCenter: vec3f, modifiedCenter: vec3f, rotation: ptr<function, vec4f>, scale: ptr<function, vec3f>) {
}
fn modifySplatColor(center: vec3f, color: ptr<function, vec4f>) {
}
`;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<function, vec3f>, covB_ptr: ptr<function, vec3f>) {
let rot: half3x3 = quatToMat3(rotation);
let s: vec3f = vec3f(scale);
let M: mat3x3f = transpose(mat3x3f(
s.x * vec3f(rot[0]),
s.y * vec3f(rot[1]),
s.z * vec3f(rot[2])
));
*covA_ptr = vec3f(dot(M[0], M[0]), dot(M[0], M[1]), dot(M[0], M[2]));
*covB_ptr = vec3f(dot(M[1], M[1]), dot(M[1], M[2]), dot(M[2], M[2]));
}
fn initCornerCov(source: ptr<function, SplatSource>, center: ptr<function, SplatCenter>, corner: ptr<function, SplatCorner>, covA: vec3f, covB: vec3f) -> bool {
let Vrk = mat3x3f(
vec3f(covA.x, covA.y, covA.z),
vec3f(covA.y, covB.x, covB.y),
vec3f(covA.z, covB.y, covB.z)
);
let focal = uniform.viewport_size.x * center.projMat00;
let v = center.view.xyz;
#ifdef GSPLAT_FISHEYE
let r_sq = max(center.fisheyeRxy * center.fisheyeRxy, 1e-8);
let d2 = dot(v, v);
let neg_z = -v.z;
let g_prime = 1.0 / (center.fisheyeCosTK * center.fisheyeCosTK);
let g_theta = uniform.fisheye_k * center.fisheyeSinTK / center.fisheyeCosTK;
let sv = select(select(0.0, 1.0 / neg_z, neg_z > 0.0), g_theta / center.fisheyeRxy, center.fisheyeRxy > 1e-4);
let K = select(0.0, (g_prime * neg_z / d2 - sv) / r_sq, center.fisheyeRxy > 1e-4);
let J = mat3x3f(
vec3f(focal * (sv + K * v.x * v.x), focal * K * v.x * v.y, focal * g_prime * v.x / d2),
vec3f(focal * K * v.x * v.y, focal * (sv + K * v.y * v.y), focal * g_prime * v.y / d2),
vec3f(0.0, 0.0, 0.0)
);
#else
let vp = select(center.view.xyz, vec3f(0.0, 0.0, 1.0), uniform.camera_params.w == 1.0);
let J1 = focal / vp.z;
let J2 = -J1 / vp.z * vp.xy;
let J = mat3x3f(
vec3f(J1, 0.0, J2.x),
vec3f(0.0, J1, J2.y),
vec3f(0.0, 0.0, 0.0)
);
#endif
let W = transpose(mat3x3f(center.modelView[0].xyz, center.modelView[1].xyz, center.modelView[2].xyz));
let T = W * J;
let cov = transpose(T) * Vrk * T;
#if GSPLAT_AA
let detOrig = cov[0][0] * cov[1][1] - cov[0][1] * cov[1][0];
let detBlur = (cov[0][0] + 0.3) * (cov[1][1] + 0.3) - cov[0][1] * cov[1][0];
corner.aaFactor = half(sqrt(max(detOrig / detBlur, 0.0)));
#endif
let diagonal1 = cov[0][0] + 0.3;
let offDiagonal = cov[0][1];
let diagonal2 = cov[1][1] + 0.3;
let mid = 0.5 * (diagonal1 + diagonal2);
let radius = length(vec2f((diagonal1 - diagonal2) / 2.0, offDiagonal));
let lambda1 = mid + radius;
let lambda2 = max(mid - radius, 0.1);
let vmin = min(1024.0, min(uniform.viewport_size.x, uniform.viewport_size.y));
let l1 = 2.0 * min(sqrt(2.0 * lambda1), vmin);
let l2 = 2.0 * min(sqrt(2.0 * lambda2), vmin);
if (max(l1, l2) < uniform.minPixelSize) {
return false;
}
let c = center.proj.ww * uniform.viewport_size.zw;
if (any((abs(center.proj.xy) - vec2f(max(l1, l2)) * c) > center.proj.ww)) {
return false;
}
let diagonalVector = normalize(vec2f(offDiagonal, lambda1 - diagonal1));
let v1 = l1 * diagonalVector;
let v2 = l2 * vec2f(diagonalVector.y, -diagonalVector.x);
corner.offset = vec3f((f32(source.cornerUV.x) * v1 + f32(source.cornerUV.y) * v2) * c, 0.0);
corner.uv = source.cornerUV;
return true;
}
#if GSPLAT_2DGS
fn initCorner2DGS(source: ptr<function, SplatSource>, rotation: vec4f, scale: vec3f, corner: ptr<function, SplatCorner>) {
let localPos: vec2f = vec2f(source.cornerUV) * vec2f(scale.x, scale.y) * 3.0;
let v: vec3f = vec3f(localPos, 0.0);
let t: vec3f = 2.0 * cross(rotation.xyz, v);
corner.offset = v + rotation.w * t + cross(rotation.xyz, t);
corner.uv = source.cornerUV;
}
#endif
fn initCorner(source: ptr<function, SplatSource>, center: ptr<function, SplatCenter>, corner: ptr<function, SplatCorner>) -> bool {
var rotation: vec4f = getRotation().yzwx;
var scale: vec3f = getScale();
modifySplatRotationScale(center.modelCenterOriginal, center.modelCenterModified, &rotation, &scale);
#if GSPLAT_2DGS
initCorner2DGS(source, rotation, scale, corner);
return true;
#else
var covA: vec3f;
var covB: vec3f;
computeCovariance(half4(rotation.wxyz), half3(scale), &covA, &covB);
return initCornerCov(source, center, corner, covA, covB);
#endif
}
`;var qz=`
varying vUv0: vec2f;
var<storage, read> rasterizeTileList: array<u32>;
uniform numTilesX: u32;
uniform screenWidth: f32;
uniform screenHeight: f32;
@vertex
fn vertexMain(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
let quadIdx = pcVertexIndex / 6u;
let cornerIdx = pcVertexIndex % 6u;
let tileIdx = rasterizeTileList[quadIdx];
let tileX = tileIdx % uniform.numTilesX;
let tileY = tileIdx / uniform.numTilesX;
let corners = array<vec2f, 6>(
vec2f(0.0, 0.0), vec2f(1.0, 0.0), vec2f(1.0, 1.0),
vec2f(0.0, 0.0), vec2f(1.0, 1.0), vec2f(0.0, 1.0)
);
let corner = corners[cornerIdx];
let x0 = f32(tileX * 16u);
let y0 = f32(tileY * 16u);
let pixelX = x0 + corner.x * 16.0;
let pixelY = y0 + corner.y * 16.0;
output.position = vec4f(
pixelX / uniform.screenWidth * 2.0 - 1.0,
pixelY / uniform.screenHeight * 2.0 - 1.0,
0.5, 1.0
);
output.vUv0 = vec2f(pixelX / uniform.screenWidth,
pixelY / uniform.screenHeight);
return output;
}
`;var $z=`
#ifndef DITHER_NONE
#include "bayerPS"
#include "opacityDitherPS"
varying id: f32;
#endif
#if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS)
uniform alphaClip: f32;
#endif
#ifdef PREPASS_PASS
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 {
return (exp(x * half(-4.0)) - EXP4) * INV_EXP4;
}
varying gaussianUV: half2;
varying gaussianColor: half4;
#if defined(GSPLAT_UNIFIED_ID) && defined(PICK_PASS)
varying @interpolate(flat) vPickId: u32;
#endif
#ifdef PICK_PASS
#include "pickPS"
#endif
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let A: half = dot(gaussianUV, gaussianUV);
if (A > half(1.0)) {
discard;
return output;
}
var alpha: half = normExp(A) * gaussianColor.a;
#if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS)
if (alpha < half(uniform.alphaClip)) {
discard;
return output;
}
#endif
#ifdef PICK_PASS
#ifdef GSPLAT_UNIFIED_ID
output.color = encodePickOutput(vPickId);
#else
output.color = getPickOutput();
#endif
#ifdef DEPTH_PICK_PASS
output.color1 = getPickDepth();
#endif
#elif SHADOW_PASS
output.color = vec4f(0.0, 0.0, 0.0, 1.0);
#elif PREPASS_PASS
output.color = float2vec4(vLinearDepth);
#else
if (alpha < half(uniform.alphaClipForward)) {
discard;
return output;
}
#ifndef DITHER_NONE
opacityDither(f32(alpha), id * 0.013);
#endif
output.color = vec4f(vec3f(gaussianColor.xyz * alpha), f32(alpha));
#endif
return output;
}`;var Zz=`
#ifdef PICK_MODE
#include "pickPS"
#include "floatAsUintPS"
var pickIdTexture: texture_2d<u32>;
var pickDepthTexture: texture_2d<f32>;
#else
#include "tonemappingPS"
#include "gammaPS"
var source: texture_2d<f32>;
#endif
varying vUv0: vec2f;
@fragment fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
#ifdef PICK_MODE
let texSize = vec2f(textureDimensions(pickIdTexture));
let coord = vec2u(input.vUv0 * texSize);
let pickId = textureLoad(pickIdTexture, coord, 0).r;
if (pickId == 0xFFFFFFFFu) {
discard;
return output;
}
output.color = encodePickOutput(pickId);
let depthData = textureLoad(pickDepthTexture, coord, 0);
let normalizedDepth = select(depthData.r / depthData.g, 1.0, depthData.g < 1e-6);
output.color1 = float2uint(normalizedDepth);
#else
let texSize = vec2f(textureDimensions(source));
let coord = vec2u(input.vUv0 * texSize);
let linear = textureLoad(source, coord, 0);
output.color = vec4f(gammaCorrectOutput(toneMap(linear.rgb)), linear.a);
#endif
return output;
}
`;var Qz=`
attribute vertex_position: vec3f;
#ifdef GSPLAT_INDIRECT_DRAW
var<storage, read> numSplatsStorage: array<u32>;
var<storage, read> compactedSplatIds: array<u32>;
#else
uniform numSplats: u32;
var<storage, read> splatOrder: array<u32>;
#endif
fn initSource(source: ptr<function, SplatSource>) -> bool {
source.order = pcInstanceIndex * {GSPLAT_INSTANCE_SIZE}u + u32(vertex_position.z);
#ifdef GSPLAT_INDIRECT_DRAW
let numSplats = numSplatsStorage[0];
#else
let numSplats = uniform.numSplats;
#endif
if (source.order >= numSplats) {
return false;
}
var splatId: u32;
#ifdef GSPLAT_INDIRECT_DRAW
splatId = compactedSplatIds[source.order];
#else
splatId = splatOrder[source.order];
#endif
setSplat(splatId);
source.cornerUV = half2(vertex_position.xy);
return true;
}
`;var Jz=`
#include "gsplatCommonVS"
varying gaussianUV: half2;
varying gaussianColor: half4;
#ifndef DITHER_NONE
varying id: f32;
#endif
const discardVec: vec4f = vec4f(0.0, 0.0, 2.0, 1.0);
#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<f32>;
var colorRampSampler: sampler;
#endif
@vertex
fn vertexMain(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
var source: SplatSource;
if (!initSource(&source)) {
output.position = discardVec;
return output;
}
var modelCenter: vec3f = getCenter();
var center: SplatCenter;
center.modelCenterOriginal = modelCenter;
modifySplatCenter(&modelCenter);
center.modelCenterModified = modelCenter;
if (!initCenter(modelCenter, &center)) {
output.position = discardVec;
return output;
}
var corner: SplatCorner;
if (!initCorner(&source, &center, &corner)) {
output.position = discardVec;
return output;
}
#ifdef GSPLAT_SEPARATE_OPACITY
let opacity = getOpacity();
var clr: half4 = half4(vec4f(getColor(), opacity));
#else
var clr: half4 = half4(getColor());
#endif
#if GSPLAT_AA
clr.a = clr.a * corner.aaFactor;
#endif
#if SH_BANDS > 0
let modelView3x3 = mat3x3f(center.modelView[0].xyz, center.modelView[1].xyz, center.modelView[2].xyz);
let dir = normalize(center.view * modelView3x3);
var sh: array<half3, SH_COEFFS>;
var scale: f32;
readSHData(&sh, &scale);
clr = half4(clr.xyz + evalSH(&sh, dir) * half(scale), clr.a);
#endif
var clrF32 = vec4f(clr);
modifySplatColor(modelCenter, &clrF32);
clr = half4(clrF32);
#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;
}
clipCorner(&corner, clr.w);
#if GSPLAT_2DGS
let modelCorner: vec3f = center.modelCenterModified + corner.offset;
output.position = uniform.matrix_projection * center.modelView * vec4f(modelCorner, 1.0);
#else
output.position = center.proj + vec4f(corner.offset.xyz, 0.0);
#endif
output.gaussianUV = corner.uv;
#ifdef GSPLAT_OVERDRAW
let t: f32 = clamp(center.modelCenterOriginal.y / 20.0, 0.0, 1.0);
let rampColor: vec3f = textureSampleLevel(colorRamp, colorRampSampler, vec2f(t, 0.5), 0.0).rgb;
clr.a = clr.a * half(1.0 / 32.0) * half(uniform.colorRampIntensity);
output.gaussianColor = half4(half3(rampColor), clr.a);
#else
output.gaussianColor = half4(half3(prepareOutputFromGamma(max(vec3f(clr.xyz), vec3f(0.0)), -center.view.z)), clr.w);
#endif
#ifndef DITHER_NONE
output.id = f32(splat.index);
#endif
#ifdef PREPASS_PASS
output.vLinearDepth = -center.view.z;
#endif
#if defined(GSPLAT_UNIFIED_ID) && defined(PICK_PASS)
output.vPickId = loadPcId().r;
#endif
return output;
}
`;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<storage, read> sortedIndices: array<u32>;
var<storage, read> projCache: array<u32>;
var<storage, read> numSplatsStorage: array<u32>;
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<f32>;
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<f32>(projCache[base + 0u]),
bitcast<f32>(projCache[base + 1u]),
bitcast<f32>(projCache[base + 2u]),
bitcast<f32>(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;
}
fn pack101010(v: vec3f) -> u32 {
let t = vec3u(v * vec3f(1023.0, 1023.0, 1023.0)) << vec3u(20u, 10u, 0u);
return t.x | t.y | t.z;
}
fn pack111110(v: vec3f) -> u32 {
let t = vec3u(v * vec3f(2047.0, 2047.0, 1023.0)) << vec3u(21u, 10u, 0u);
return t.x | t.y | t.z;
}
fn unpack8888(v: u32) -> vec4f {
return vec4f((vec4u(v) >> vec4u(24u, 16u, 8u, 0u)) & vec4u(0xffu)) / 255.0;
}
fn unpack101010(v: u32) -> vec3f {
return vec3f((vec3u(v) >> vec3u(20u, 10u, 0u)) & vec3u(0x3ffu)) / 1023.0;
}
fn unpack111110(v: u32) -> vec3f {
return vec3f((vec3u(v) >> vec3u(21u, 10u, 0u)) & vec3u(0x7ffu, 0x7ffu, 0x3ffu)) / vec3f(2047.0, 2047.0, 1023.0);
}`;var sG=`
uniform splatTextureSize: u32;
`;var iG=`
var<private> tAw: u32;
var<private> tBcached: vec4f;
fn unpackRotation(data: vec3f) -> vec4f {
return vec4f(data.xyz, sqrt(max(0.0, 1.0 - dot(data, data))));
}
fn getCenter() -> vec3f {
let tA: vec4<u32> = loadTransformA();
tAw = tA.w;
tBcached = loadTransformB();
return bitcast<vec3f>(tA.xyz);
}
fn getColor() -> vec4f {
return loadSplatColor();
}
fn getRotation() -> vec4f {
return unpackRotation(vec3f(unpack2x16float(tAw), tBcached.w)).wxyz;
}
fn getScale() -> vec3f {
return tBcached.xyz;
}
#include "gsplatUncompressedSHVS"
`;var rG=`
#if SH_BANDS > 0
fn unpack111011s(bits: u32) -> vec3f {
return (vec3f((vec3<u32>(bits) >> vec3<u32>(21u, 11u, 0u)) & vec3<u32>(0x7ffu, 0x3ffu, 0x7ffu)) / vec3f(2047.0, 1023.0, 2047.0)) * 2.0 - 1.0;
}
struct ScaleAndSH {
scale: f32,
a: vec3f,
b: vec3f,
c: vec3f
};
fn fetchScale(t_in: vec4<u32>) -> ScaleAndSH {
var result: ScaleAndSH;
result.scale = bitcast<f32>(t_in.x);
result.a = unpack111011s(t_in.y);
result.b = unpack111011s(t_in.z);
result.c = unpack111011s(t_in.w);
return result;
}
struct SH {
a: vec3f,
b: vec3f,
c: vec3f,
d: vec3f
};
fn fetch4(t_in: vec4<u32>) -> SH {
var result: SH;
result.a = unpack111011s(t_in.x);
result.b = unpack111011s(t_in.y);
result.c = unpack111011s(t_in.z);
result.d = unpack111011s(t_in.w);
return result;
}
fn fetch1(t_in: u32) -> vec3f {
return unpack111011s(t_in);
}
#if SH_BANDS == 1
fn readSHData(sh: ptr<function, array<half3, 3>>, scale: ptr<function, f32>) {
let result = fetchScale(loadSplatSH_1to3());
*scale = result.scale;
sh[0] = half3(result.a);
sh[1] = half3(result.b);
sh[2] = half3(result.c);
}
#elif SH_BANDS == 2
fn readSHData(sh: ptr<function, array<half3, 8>>, scale: ptr<function, f32>) {
let first: ScaleAndSH = fetchScale(loadSplatSH_1to3());
*scale = first.scale;
sh[0] = half3(first.a);
sh[1] = half3(first.b);
sh[2] = half3(first.c);
let second: SH = fetch4(loadSplatSH_4to7());
sh[3] = half3(second.a);
sh[4] = half3(second.b);
sh[5] = half3(second.c);
sh[6] = half3(second.d);
sh[7] = half3(fetch1(loadSplatSH_8to11().x));
}
#else
fn readSHData(sh: ptr<function, array<half3, 15>>, scale: ptr<function, f32>) {
let first: ScaleAndSH = fetchScale(loadSplatSH_1to3());
*scale = first.scale;
sh[0] = half3(first.a);
sh[1] = half3(first.b);
sh[2] = half3(first.c);
let second: SH = fetch4(loadSplatSH_4to7());
sh[3] = half3(second.a);
sh[4] = half3(second.b);
sh[5] = half3(second.c);
sh[6] = half3(second.d);
let third: SH = fetch4(loadSplatSH_8to11());
sh[7] = half3(third.a);
sh[8] = half3(third.b);
sh[9] = half3(third.c);
sh[10] = half3(third.d);
let fourth: SH = fetch4(loadSplatSH_12to15());
sh[11] = half3(fourth.a);
sh[12] = half3(fourth.b);
sh[13] = half3(fourth.c);
sh[14] = half3(fourth.d);
}
#endif
#endif
`;var aG=`
#include "gsplatPackingPS"
var chunkTexture: texture_2d<uff>;
var<private> chunkDataA: vec4f;
var<private> chunkDataB: vec4f;
var<private> chunkDataC: vec4f;
var<private> chunkDataD: vec4f;
var<private> chunkDataE: vec4f;
var<private> packedData: vec4u;
fn unpack111011(bits: u32) -> vec3f {
return (vec3f((vec3<u32>(bits) >> vec3<u32>(21u, 11u, 0u)) & vec3<u32>(0x7ffu, 0x3ffu, 0x7ffu))) / vec3f(2047.0, 1023.0, 2047.0);
}
const norm_const: f32 = sqrt(2.0);
fn unpackRotation(bits: u32) -> vec4f {
let a = (f32((bits >> 20u) & 0x3ffu) / 1023.0 - 0.5) * norm_const;
let b = (f32((bits >> 10u) & 0x3ffu) / 1023.0 - 0.5) * norm_const;
let c = (f32(bits & 0x3ffu) / 1023.0 - 0.5) * norm_const;
let m = sqrt(1.0 - (a * a + b * b + c * c));
let mode = bits >> 30u;
if (mode == 0u) { return vec4f(m, a, b, c); }
if (mode == 1u) { return vec4f(a, m, b, c); }
if (mode == 2u) { return vec4f(a, b, m, c); }
return vec4f(a, b, c, m);
}
fn getCenter() -> vec3f {
let tex_size_u = textureDimensions(chunkTexture, 0);
let w: u32 = tex_size_u.x / 5u;
let chunkId: u32 = splat.index / 256u;
let chunkUV: vec2<i32> = vec2<i32>(i32((chunkId % w) * 5u), i32(chunkId / w));
chunkDataA = textureLoad(chunkTexture, chunkUV + vec2<i32>(0, 0), 0);
chunkDataB = textureLoad(chunkTexture, chunkUV + vec2<i32>(1, 0), 0);
chunkDataC = textureLoad(chunkTexture, chunkUV + vec2<i32>(2, 0), 0);
chunkDataD = textureLoad(chunkTexture, chunkUV + vec2<i32>(3, 0), 0);
chunkDataE = textureLoad(chunkTexture, chunkUV + vec2<i32>(4, 0), 0);
packedData = loadPackedTexture();
return mix(chunkDataA.xyz, vec3f(chunkDataA.w, chunkDataB.xy), unpack111011(packedData.x));
}
fn getColor() -> vec4f {
let r = unpack8888(packedData.w);
return vec4f(mix(chunkDataD.xyz, vec3f(chunkDataD.w, chunkDataE.xy), r.rgb), r.w);
}
fn getRotation() -> vec4f {
return unpackRotation(packedData.y);
}
fn getScale() -> vec3f {
return exp(mix(vec3f(chunkDataB.zw, chunkDataC.x), chunkDataC.yzw, unpack111011(packedData.z)));
}
#include "gsplatCompressedSHVS"
`;var oG=`
#if SH_BANDS > 0
fn unpack8888s(bits: u32) -> half4 {
let unpacked_u = (vec4<u32>(bits) >> vec4<u32>(0u, 8u, 16u, 24u)) & vec4<u32>(0xffu);
return half4(vec4f(unpacked_u) * (8.0 / 255.0) - 4.0);
}
fn readSHData(sh: ptr<function, array<half3, 15>>, scale: ptr<function, f32>) {
let shData0: vec4<u32> = loadShTexture0();
let shData1: vec4<u32> = loadShTexture1();
let shData2: vec4<u32> = loadShTexture2();
let r0: half4 = unpack8888s(shData0.x);
let r1: half4 = unpack8888s(shData0.y);
let r2: half4 = unpack8888s(shData0.z);
let r3: half4 = unpack8888s(shData0.w);
let g0: half4 = unpack8888s(shData1.x);
let g1: half4 = unpack8888s(shData1.y);
let g2: half4 = unpack8888s(shData1.z);
let g3: half4 = unpack8888s(shData1.w);
let b0: half4 = unpack8888s(shData2.x);
let b1: half4 = unpack8888s(shData2.y);
let b2: half4 = unpack8888s(shData2.z);
let b3: half4 = unpack8888s(shData2.w);
sh[0] = half3(r0.x, g0.x, b0.x);
sh[1] = half3(r0.y, g0.y, b0.y);
sh[2] = half3(r0.z, g0.z, b0.z);
sh[3] = half3(r0.w, g0.w, b0.w);
sh[4] = half3(r1.x, g1.x, b1.x);
sh[5] = half3(r1.y, g1.y, b1.y);
sh[6] = half3(r1.z, g1.z, b1.z);
sh[7] = half3(r1.w, g1.w, b1.w);
sh[8] = half3(r2.x, g2.x, b2.x);
sh[9] = half3(r2.y, g2.y, b2.y);
sh[10] = half3(r2.z, g2.z, b2.z);
sh[11] = half3(r2.w, g2.w, b2.w);
sh[12] = half3(r3.x, g3.x, b3.x);
sh[13] = half3(r3.y, g3.y, b3.y);
sh[14] = half3(r3.z, g3.z, b3.z);
*scale = 1.0;
}
#endif
`;var nG=`
uniform means_mins: vec3f;
uniform means_maxs: vec3f;
#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;
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 {
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 getRotation() -> vec4f {
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) {
quat = vec4f(d, abc);
} else if (qmode == 1u) {
quat = vec4f(abc.x, d, abc.y, abc.z);
} else if (qmode == 2u) {
quat = vec4f(abc.x, abc.y, d, abc.z);
} else {
quat = vec4f(abc.x, abc.y, abc.z, d);
}
return quat;
}
fn getScale() -> vec3f {
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"
`;var lG=`
#if SH_BANDS > 0
#ifndef SOG_V2
uniform shN_mins: f32;
uniform shN_maxs: f32;
#endif
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<function, array<half3, SH_COEFFS>>, scale: ptr<function, f32>) {
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
`;var cG=`
#include "gsplatContainerDeclarationsVS"
var<private> splatCenter: vec3f;
var<private> splatColor: vec4f;
var<private> splatScale: vec3f;
var<private> splatRotation: vec4f;
`;var hG=`
fn getCenter() -> vec3f {
#include "gsplatContainerUserReadVS"
return splatCenter;
}
fn getRotation() -> vec4f {
return splatRotation;
}
fn getScale() -> vec3f {
return splatScale;
}
fn getColor() -> vec4f {
return splatColor;
}
`;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<sx.length;i++)e.hasOwnProperty(sx[i])&&(t[sx[i]]=e[sx[i]]);e.aabbCenter&&e.aabbHalfExtents&&(t.customAabb=new ge(new x(e.aabbCenter),new x(e.aabbHalfExtents))),super.initializeComponentData(t,e,JR)}cloneComponent(t,e){let s=t.gsplat,i={};sx.forEach(a=>{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<v;++G){let M=_[G*3+0]*3,H=_[G*3+1]*3,U=_[G*3+2]*3;C(P,m,M),C(A,m,H),C(w,m,U),S(I,A,P),S(D,w,P),g(O,I,D),T(O,0);for(let L=0;L<3;++L)y[M+L]+=O[L],y[H+L]+=O[L],y[U+L]+=O[L]}for(let G=0;G<E;++G)T(y,G*3);return new Uint8Array(y.buffer)},u=m=>{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<T.num_attributes();++M)A.push(g.GetAttribute(T,M));A.sort((M,H)=>(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<I.length;++M)I[M]+=12;w+=12}_.attributes=A.map((M,H)=>({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<T.num_attributes();++M){let H=A[M],U=l(H),L=T.num_points()*U,b=e._malloc(L);g.GetAttributeDataArrayForAllPoints(T,H,H.data_type(),L,b);let N=new Uint8Array(e.HEAPU8.buffer,b,L);for(let k=0;k<T.num_points();++k)for(let z=0;z<U;++z)G[k*w+I[M]+z]=N[k*U+z];if(!D&&H.attribute_type()===0){let k=f(r(N,H.data_type()),E?new Uint16Array(_.indices):new Uint32Array(_.indices));for(let z=0;z<T.num_points();++z)for(let V=0;V<12;++V)G[z*w+O+V]=k[z*12+V]}e._free(b)}return e.destroy(T),e.destroy(g),e.destroy(S),_},d=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(`
`),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<a;++l){let h=new Worker(r);h.postMessage({type:"init",module:e}),o.push(h)}BE.init(o)}),!0)},SG=c=>{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<i;++r)c[r]=s(t[r]);return c},Mu=(c,t,e=!1)=>{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<a.count;++u){let d=l[u];for(let p=0;p<s;++p)r[d*s+p]=f[u*s+p]}}else if(c.hasOwnProperty("bufferView")){let a=t[c.bufferView];if(e&&a.hasOwnProperty("byteStride")){let o=s*i.BYTES_PER_ELEMENT,l=new ArrayBuffer(c.count*o),h=new Uint8Array(l),f=0;for(let u=0;u<c.count;++u){let d=(c.byteOffset||0)+u*a.byteStride;for(let p=0;p<o;++p)h[f++]=a[d++]}r=new i(l)}else r=new i(a.buffer,a.byteOffset+(c.byteOffset||0),c.count*s)}else r=new i(c.count*s);return r},x_=(c,t)=>{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<c;e++)t[e]=e;return t},KK=(c,t)=>{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<e.count;++h)s[h*3+0]=l[h*o+0],s[h*3+1]=l[h*o+1],s[h*3+2]=l[h*o+2]}else s=new Ro[e.type](e.buffer,e.offset,e.count*3);let i=e.count;t||(t=YK(i));let r=Kp(s,t),a=new Float32Array(r.length);a.set(r),c[Ot]={buffer:a.buffer,size:12,offset:0,stride:12,count:i,components:3,type:ye}},jK=c=>{let t=s=>{let i=[];for(let r=0;r<s._levels.length;++r){let a=[];if(s.cubemap)for(let o=0;o<6;++o)a.push(s._levels[r][o]);else a=s._levels[r];i.push(a)}return i},e=new Z(c.device,c);return e._levels=t(c),e},qK=c=>{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<u.elements.length;++r)if(h=u.elements[r],l=t[h.name],f=l.offset-e.offset,l.buffer!==e.buffer||l.stride!==h.stride||l.size!==h.size||f!==h.offset){d=!1;break}let p=new ft(c,u,s),m=p.lock(),_=new Uint32Array(m),S;if(d)S=new Uint32Array(e.buffer,e.offset,s*p.format.size/4),_.set(S);else{let g,T;for(r=0;r<p.format.elements.length;++r){h=p.format.elements[r],g=h.stride/4,l=t[h.name],T=l.stride/4,S=new Uint32Array(l.buffer,l.offset,(l.count-1)*T+(l.size+3)/4);let C=0,v=h.offset/4,E=Math.floor((l.size+3)/4);for(a=0;a<s;++a){for(o=0;o<E;++o)_[v+o]=S[C+o];C+=T,v+=g}}}return p.unlock(),p},ZK=(c,t,e,s,i,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<f;a++){for(o=0;o<16;o++)g[o]=S[a*16+o];l=new W,l.set(g),u.push(l)}}else for(a=0;a<f;a++)l=new W,u.push(l);let d=[];for(a=0;a<f;a++)d[a]=i[h[a]].name;let p=d.join("#"),m=r.get(p);return m||(m=new Vc(c,u,d),r.set(p,m)),m},JK=(c,t,e,s,i,r,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<e.length;++s)t[`${e[s]}MapUv`]=i;let r=[0,0],a=[1,1],o=c.extensions?.KHR_texture_transform;if(o){let l=o.offset||r,h=o.scale||a,f=o.rotation?-o.rotation*R.RAD_TO_DEG:0,u=new B(h[0],h[1]),d=new B(l[0],1-h[1]-l[1]);for(s=0;s<e.length;++s)t[`${e[s]}MapTiling`]=u,t[`${e[s]}MapOffset`]=d,t[`${e[s]}MapRotation`]=f}},tj=(c,t,e)=>{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<c.samplers.length;++p){let A=c.samplers[p];h.hasOwnProperty(A.input)||(h[A.input]=o(e[A.input])),f.hasOwnProperty(A.output)||(f[A.output]=o(e[A.output]));let w=A.hasOwnProperty("interpolation")&&l.hasOwnProperty(A.interpolation)?l[A.interpolation]:1,I={paths:[],input:A.input,output:A.output,interpolation:w};u[p]=I}let m=[],_={translation:"localPosition",rotation:"localRotation",scale:"localScale"},S=A=>{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;b<M;b++){let N=new Float32Array(L,U*b,H);for(let q=0;q<H;q++)N[q]=G[q*M+b];let k=new an(1,N),z=O?.[b]?`name.${O[b]}`:b;f[-d]=k;let V={paths:[{entityPath:I,component:"graph",propertyPath:[`weight.${z}`]}],input:A.input,output:-d,interpolation:A.interpolation};d++,u[`morphCurve-${p}-${b}`]=V}};for(p=0;p<c.channels.length;++p){let A=c.channels[p],w=A.target,I=u[A.sampler],D=i[w.node],O=a[w.node],G=S(D);w.path.startsWith("weights")?(g(I,O,G),u[A.sampler].morphCurve=!0):I.paths.push({entityPath:G,component:"graph",propertyPath:[_[w.path]]})}let T=[],C=[],v=[];for(let A in h)T.push(h[A]),h[A]=T.length-1;for(let A in f)C.push(f[A]),f[A]=C.length-1;for(let A in u){let w=u[A];w.morphCurve||(v.push(new Th(w.paths,h[w.input],f[w.output],w.interpolation)),w.paths.length>0&&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<m.length;++p){let A=m[p];if(p===0||A!==E){if(y=C[A],y.components===4){let w=y.data,I=w.length-4;for(let D=0;D<I;D+=4)w[D+0]*w[D+4]+w[D+1]*w[D+5]+w[D+2]*w[D+6]+w[D+3]*w[D+7]<0&&(w[D+4]*=-1,w[D+5]*=-1,w[D+6]*=-1,w[D+7]*=-1)}E=A}}let P=0;for(p=0;p<T.length;p++)y=T[p]._data,P=Math.max(P,y.length===0?0:y[y.length-1]);return new Qs(c.hasOwnProperty("name")?c.name:`animation_${t}`,P,T,C,v)},ix=new W,rx=new x,vG=new $,pj=(c,t,e)=>{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<t.length;s++)e[t[s].name]=s;return e},Tj=(c,t,e,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<u;T++){let C=T*3;if(l&&p.set(l[C],l[C+1],l[C+2]),h){let v=T*4;m.set(h[v],h[v+1],h[v+2],h[v+3])}f&&_.set(f[C],f[C+1],f[C+2]),S.setTRS(p,m,_);for(let v=0;v<16;v++)d[g++]=S.data[v]}r.matrices=d}})},Ej=(c,t,e)=>{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<c.nodes.length;++o){let l=c.nodes[o];if(l.hasOwnProperty("children")){let h=a[o],f={};for(let u=0;u<l.children.length;++u){let d=a[l.children[u]];d.parent||(f.hasOwnProperty(d.name)?d.name+=f[d.name]++:f[d.name]=1,h.addChild(d))}}}return a},Aj=(c,t)=>{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<s;i++){let r=c.scenes[i];if(r.nodes){let a=new Pe(r.name);for(let o=0;o<r.nodes.length;o++){let l=t[r.nodes[o]];a.addChild(l)}e.push(a)}}return e},Cj=(c,t,e)=>{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<m.length;w++)P[w]=new Lu,P[w].meshes=m[w];wj(t,P,y);let A=new sb;return A.gltf=t,A.nodes=l,A.scenes=h,A.animations=T,A.textures=C,A.materials=E,A.variants=d,A.meshVariants=_,A.meshDefaultMaterials=S,A.renders=P,A.skins=y,A.lights=f,A.cameras=u,A.nodeInstancingMap=o,a&&a(t,A),await Promise.all(g),A},Rj=(c,t)=>{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<u.length;p++)d[p]=u.charCodeAt(p);return d}return new Promise((u,d)=>{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<i.length;a++)r+=String.fromCharCode(i[a]);return decodeURIComponent(escape(r))})(c));if(s.asset&&s.asset.version&&parseFloat(s.asset.version)<2){t(`Invalid gltf version. Expected version 2.0 or above but found version '${s.asset.version}'.`);return}t(null,s)},Fj=(c,t)=>{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(;o<r;){let l=e.getUint32(o,!0);o+l+8>e.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<c.bufferViews.length;++o){let l=c.bufferViews[o];i&&i(l);let h;r?h=new Promise((f,u)=>{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;f<h.length;f++)h[f].events=new rh(Object.values(s.data.events));l.destroy(),e(null,h)}}):e(null,this[`_parseAnimationV${a.animation.version}`](a))})}open(t,e,s){return e}_parseAnimationV3(t){let e=t.animation,s=new iu;s.name=e.name,s.duration=e.duration;for(let i=0;i<e.nodes.length;i++){let r=new ul,a=e.nodes[i];r._name=a.name;for(let o=0;o<a.keys.length;o++){let l=a.keys[o],h=l.time,f=l.pos,u=l.rot,d=l.scale,p=new x(f[0],f[1],f[2]),m=new $().setFromEulerAngles(u[0],u[1],u[2]),_=new x(d[0],d[1],d[2]),S=new fl(h,p,m,_);r._keys.push(S)}s.addNode(r)}return s}_parseAnimationV4(t){let e=t.animation,s=new iu;s.name=e.name,s.duration=e.duration;for(let i=0;i<e.nodes.length;i++){let r=new ul,a=e.nodes[i];r._name=a.name;let o=a.defaults.p,l=a.defaults.r,h=a.defaults.s;for(let f=0;f<a.keys.length;f++){let u=a.keys[f],d=u.t,p=o||u.p,m=l||u.r,_=h||u.s,S=new x(p[0],p[1],p[2]),g=new $().setFromEulerAngles(m[0],m[1],m[2]),T=new x(_[0],_[1],_[2]),C=new fl(d,S,g,T);r._keys.push(C)}s.addNode(r)}return s}};var T_=class extends Re{constructor(t){super(t,"animclip")}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 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<t.renders.length;++h)a.push(r("render",t.renders[h],h));let o=[];for(let h=0;h<t.materials.length;++h)o.push(r("material",t.materials[h],h));let l=[];for(let h=0;h<t.animations.length;++h)l.push(r("animation",t.animations[h],h));this.data=t,this._model=null,this._assetName=e.name,this._assets=s,this._defaultMaterial=i,this.renders=a,this.materials=o,this.textures=t.textures,this.animations=l}get model(){if(!this._model){let t=c.createModel(this.data,this._defaultMaterial),e=c.createAsset(this._assetName,"model",t,0);this._assets.add(e),this._model=e}return this._model}static createAsset(t,e,s,i){let r=new ae(`${t}/${e}/${i}`,e,{url:""});return r.resource=s,r.loaded=!0,r}instantiateModelEntity(t){let e=new Ne(void 0,this._assets._loader._app);return e.addComponent("model",Object.assign({type:"asset",asset:this.model},t)),e}instantiateRenderEntity(t){let e=this._defaultMaterial,s=[],i=function(o,l,h,f,u,d,p,m){let _=u[h.id],S=_===void 0?e:f[_],g=new we(h,S);h.morph&&(g.morphInstance=new Ar(h.morph)),p.hasOwnProperty("skin")&&s.push({meshInstance:g,rootBone:o,entity:l});let T=m.get(p);if(T){let C=T.matrices,v=Ft.getDefaultInstancingFormat(h.device),E=new ft(h.device,v,C.length/16,{data:C});g.setInstancing(E),g.instancingData._destroyVertexBuffer=!0}return g},r=(o,l,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<h.nodes.length;m++)if(h.nodes[m]===l){let S=h.gltf.nodes[m];if(S.hasOwnProperty("mesh")){let g=h.renders[S.mesh].meshes;d=this.renders[S.mesh];for(let T=0;T<g.length;T++){let C=g[T];if(C){let v=i(o,f,C,h.materials,h.meshDefaultMaterials,h.skins,S,h.nodeInstancingMap);u||(u=[]),u.push(v)}}}if(h.lights){let g=h.lights.get(S);g&&f.addChild(g.clone())}if(h.cameras){let g=h.cameras.get(S);g&&g.camera.system.cloneComponent(g,f)}}u&&(f.addComponent("render",Object.assign({type:"asset",meshInstances:u},t)),f.render.assignAsset(d));let p=l.children;for(let m=0;m<p.length;m++){let _=r(o,p[m],h);f.addChild(_)}return f},a=[];for(let o of this.data.scenes)a.push(r(null,o,this.data));return s.forEach(o=>{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<i.length;r++){let a=i[r];this._applyMaterialVariant(s,a.meshInstances)}}applyMaterialVariantInstances(t,e){let s=e?this.data.variants[e]:null;s!==void 0&&this._applyMaterialVariant(s,t)}_applyMaterialVariant(t,e){e.forEach(s=>{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<t.nodes.length;a++){let o=t.nodes[a];if(o.root===i.graph){let l=t.gltf.nodes[a];if(l.hasOwnProperty("mesh")){let h=t.renders[l.mesh].meshes;for(let f=0;f<h.length;f++){let u=h[f];u&&s(i,u,t.skins,r,t.materials,o,l)}}}}return i}destroy(){let t=this._assets,e=function(i){t.remove(i),i.unload()},s=function(i){i.forEach(r=>{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;l<p[0]._levels.length;++l)m.push(p.map(g=>g._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<a.length;++h)a[h]!==null&&f.indexOf(a[h])===-1&&a[h].destroy();for(h=0;h<r.length;++h)r[h]!==null&&s.indexOf(r[h])===-1&&r[h].unload()}cmpArrays(t,e){if(t.length!==e.length)return!1;for(let s=0;s<t.length;++s)if(t[s]!==e[s])return!1;return!0}resolveId(t){let e=parseInt(t,10);return e===t||e.toString()===t?e:t}loadAssets(t,e){t.hasOwnProperty("_handlerState")||(t._handlerState={assetIds:[null,null,null,null,null,null,null],assets:[null,null,null,null,null,null,null]});let s=this,i=s.getAssetIds(t),r=[null,null,null,null,null,null,null],a=t._handlerState.assetIds,o=t._handlerState.assets,l=s._registry,h=7,f=function(m,_){r[m]=_,h--,h===0&&(s.update(t,i,r),e(null,t.resources))},u=function(m,_,S){e(_)},d=function(m,_){_.loaded?f(m,_):(l.once(`load:${_.id}`,f.bind(s,m)),l.once(`error:${_.id}`,u.bind(s,m)),_.loading||l.load(_))},p;for(let m=0;m<7;++m){let _=this.resolveId(i[m]);if(!_)f(m,null);else if(s.compareAssetIds(_,a[m]))d(m,o[m]);else if(parseInt(_,10)===_)p=l.get(_),p?d(m,p):setTimeout(((S,g)=>{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<i;f++)h(f)}open(t,e,s){let i;return e.textures?i=new Ou(e.textures,e.data):i=new Ou(e,null),i}patch(t,e){let s=t.resource;!s.data&&t.data?s.data=t.data:!t.data&&s.data&&(t.data=s.data),t.data&&(t.data=nb(t.data))}};var lb=.28209479177387814,cb=class{constructor(t,e,s,i,r,a){let o=(v,E)=>{let y=(1<<E)-1;return(v&y)/y},l=(v,E)=>{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<C?y[P][v*16+A]*(8/255)-4:0}}}},VE=class{constructor(){n(this,"numSplats");n(this,"comments");n(this,"chunkData");n(this,"vertexData");n(this,"shData0");n(this,"shData1");n(this,"shData2");n(this,"shBands")}createIter(t,e,s,i,r){return new cb(this,t,e,s,i,r)}calcAabb(t){let{chunkData:e,numChunks:s,chunkSize:i}=this,r=Math.exp(Math.max(e[9],e[10],e[11])),a=e[0]-r,o=e[1]-r,l=e[2]-r,h=e[3]+r,f=e[4]+r,u=e[5]+r;for(let d=1;d<s;++d){let p=d*i;r=Math.exp(Math.max(e[p+9],e[p+10],e[p+11])),a=Math.min(a,e[p+0]-r),o=Math.min(o,e[p+1]-r),l=Math.min(l,e[p+2]-r),h=Math.max(h,e[p+3]+r),f=Math.max(f,e[p+4]+r),u=Math.max(u,e[p+5]+r)}return t.center.set((a+h)*.5,(o+f)*.5,(l+u)*.5),t.halfExtents.set((h-a)*.5,(f-o)*.5,(u-l)*.5),!0}getCenters(){let{vertexData:t,chunkData:e,numChunks:s,chunkSize:i}=this,r=new Float32Array(this.numSplats*3),a,o,l,h,f,u;for(let d=0;d<s;++d){let p=d*i;a=e[p+0],o=e[p+1],l=e[p+2],h=e[p+3],f=e[p+4],u=e[p+5];let m=Math.min(this.numSplats,(d+1)*256);for(let _=d*256;_<m;++_){let S=t[_*4],g=(S>>>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;u<s;++u){let d=u*i;r=e[d+0],a=e[d+1],o=e[d+2],l=e[d+3],h=e[d+4],f=e[d+5],t[u*6+0]=r,t[u*6+1]=a,t[u*6+2]=o,t[u*6+3]=l,t[u*6+4]=h,t[u*6+5]=f}}calcFocalPoint(t){let{chunkData:e,numChunks:s,chunkSize:i}=this;t.x=0,t.y=0,t.z=0;for(let r=0;r<s;++r){let a=r*i;t.x+=e[a+0]+e[a+3],t.y+=e[a+1]+e[a+4],t.z+=e[a+2]+e[a+5]}t.mulScalar(.5/s)}get isCompressed(){return!0}get numChunks(){return Math.ceil(this.numSplats/256)}get chunkSize(){return this.chunkData.length/this.numChunks}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"],{shBands:e}=this;if(e>0){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<this.numSplats;++f)if(h.read(f),s.x[f]=i.x,s.y[f]=i.y,s.z[f]=i.z,s.rot_1[f]=r.x,s.rot_2[f]=r.y,s.rot_3[f]=r.z,s.rot_0[f]=r.w,s.scale_0[f]=a.x,s.scale_1[f]=a.y,s.scale_2[f]=a.z,s.f_dc_0[f]=(o.x-.5)/lb,s.f_dc_1[f]=(o.y-.5)/lb,s.f_dc_2[f]=(o.z-.5)/lb,s.opacity[f]=o.w<=0?-40:o.w>=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;r<i;++r)for(let a=0;a<s;++a)c[r*t+a]=e[r*s+a]},HE=class extends rt{constructor(t,e,s={}){super(t,e,s);let{chunkData:i,chunkSize:r,numChunks:a,numSplats:o,vertexData:l,shBands:h}=e;this.chunks=new Float32Array(a*6),e.getChunks(this.chunks);let f=[{name:"packedTexture",format:At}];h>0&&(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<a;++S)_[S*20+15]=1,_[S*20+16]=1,_[S*20+17]=1;m.unlock()}destroy(){super.destroy()}configureMaterialDefines(t){t.set("SH_BANDS",this.streams.textures.has("shTexture0")?3:0)}evalChunkTextureSize(t){let e=Math.ceil(Math.sqrt(t)),s=Math.ceil(t/e);return new B(e*5,s)}};var AG=new Uint8Array([112,108,121,10]),CG=new Uint8Array([10,101,110,100,95,104,101,97,100,101,114,10]),hb=new Map([["char",Int8Array],["uchar",Uint8Array],["short",Int16Array],["ushort",Uint16Array],["int",Int32Array],["uint",Uint32Array],["float",Float32Array],["double",Float64Array]]),fb=class{constructor(t,e){n(this,"reader");n(this,"progressFunc");n(this,"data");n(this,"view");n(this,"head",0);n(this,"tail",0);this.reader=t,this.progressFunc=e}async read(){let{value:t,done:e}=await this.reader.read();if(e)throw new Error("Stream finished before end of header");this.push(t),this.progressFunc?.(t.byteLength)}push(t){if(!this.data)this.data=t,this.view=new DataView(this.data.buffer),this.tail=t.length;else{let e=this.tail-this.head,s=e+t.length;if(this.data.length>=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.tail<this.data.length?i.set(this.data.subarray(this.head,this.tail),0):i.set(this.data,0),i.set(t,e),this.data=i,this.view=new DataView(this.data.buffer),this.head=0,this.tail=s}}}compact(){this.head>0&&(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<c.length;++i){let r=c[i].split(" ");switch(r[0]){case"comment":e.push(r.slice(1).join(" "));break;case"format":s=r[1];break;case"element":t.push({name:r[1],count:parseInt(r[2],10),properties:[]});break;case"property":{if(!hb.has(r[1]))throw new Error(`Unrecognized property data type '${r[1]}' in ply header`);t[t.length-1].properties.push({type:r[1],name:r[2],storage:null,byteSize:hb.get(r[1]).BYTES_PER_ELEMENT});break}default:throw new Error(`Unrecognized header value '${r[0]}' in ply header`)}}return{elements:t,format:s,comments:e}},Gj=c=>{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<u;){for(;c.remaining===0;)await c.read();let m=Math.min(u-p,c.remaining),_=c.data;for(let S=0;S<m;++S)d[p++]=_[c.head++]}};if(await h(s.chunkData.buffer,i*r*4),await h(s.vertexData.buffer,a*4*4),t.length===3){let f=l*16,u=new Uint8Array(f),d=new Uint8Array(f),p=new Uint8Array(f),m=1024,_=t[2].properties.length/3,S=new Uint8Array(m*_*3);for(let g=0;g<s.numSplats;g+=m){let T=Math.min(m,s.numSplats-g);await h(S.buffer,T*_*3);for(let C=0;C<T;++C)for(let v=0;v<15;++v){let E=(g+C)*16+v;v<_?(u[E]=S[(C*3+0)*_+v],d[E]=S[(C*3+1)*_+v],p[E]=S[(C*3+2)*_+v]):(u[E]=127,d[E]=127,p[E]=127)}}s.shData0=u,s.shData1=d,s.shData2=p,s.shBands={3:1,8:2,15:3}[_]}else s.shBands=0;return s},Wj=async(c,t,e)=>{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<s.count;){for(;c.remaining<o;)await c.read(),f();let u=Math.min(s.count-l,Math.floor(c.remaining/o));for(let d=0;d<r;++d){let p=a[d];for(let m=0;m<u;++m)p[m+l]=h[m*r+d]}l+=u,c.head+=u*o}return new Qa(t,e)},Xj=async(c,t,e)=>{for(let s=0;s<t.length;++s){let i=t[s],r=i.properties.reduce((l,h)=>l+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<i.count;){for(;c.remaining<r;)await c.read();let l=Math.min(i.count-o,Math.floor(c.remaining/r));for(let h=0;h<l;++h){for(let f=0;f<i.properties.length;++f)a[f](c,o);o++}}}return new Qa(t,e)},Yj=async(c,t=null,e=null)=>{let s=(d,p)=>{let m=d.length-p.length,_,S;for(_=0;_<=m;++_){for(S=0;S<p.length&&d[_+S]===p[S];++S);if(S===p.length)return _}return-1},i=(d,p)=>{if(d.length<p.length)return!1;for(let m=0;m<p.length;++m)if(d[m]!==p[m])return!1;return!0},r=new fb(c,e),a;for(;;){if(await r.read(),r.tail>=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<s&&(a=Math.ceil(a*s/o)),c.fire("progress",r,a)};t.forEach(r=>{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<o.numFiles;f++){let u=r(h);if(u.magic!==33639248)throw new Error("Invalid zip file: CDR not found");let d=a(u.lfhOffsetBytes);if(d.magic!==67324752)throw new Error("Invalid zip file: LFH not found");l.push({filename:u.filename,compression:{0:"none",8:"deflate"}[u.compressionMethod]??"unknown",data:new Uint8Array(c,d.offsetBytes,u.compressedSizeBytes)}),h+=u.recordSizeBytes}return l},Zj=async c=>{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.size<this.maxConcurrentLoads?this._startLoading(e):this._loadQueue.push(e))}_startLoading(e){this._currentlyLoading.add(e);let s=this._urlToAsset.get(e);s||(s=new ae(e,"gsplat",{url:e}),this._registry.add(s),this._urlToAsset.set(e,s)),s.once("load",()=>this._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;r<this.maxRetries?(this._retryCount.set(e,r+1),s.loaded=!1,s.loading=!1,this._registry.load(s)):(this._currentlyLoading.delete(e),this._retryCount.delete(e),this._processQueue())}_processQueue(){if(!(this._destroyed||!this._canLoad()))for(;this._currentlyLoading.size<this.maxConcurrentLoads&&this._loadQueue.length>0;){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;i<t.length;i++)s=s*e.fieldCodeBase+t.charCodeAt(i)-e.fieldFirstCode;return e.fieldArray[s]}};var $E=class c{constructor(t,e){this._node=t,this._data=e}run(){let t=Object.prototype.toString.call(this._node);return t==="[object Object]"?this._handleMap():t==="[object Array]"?this._handleArray():this._result=this._node,this._result}_handleMap(){this._result={},Object.keys(this._node).forEach(this._handleKey,this)}_handleKey(t){let e=t,s=t.length;s===1?e=Fu.oneCharToKey(t,this._data):s===2&&(e=Fu.multCharToKey(t,this._data)),this._result[e]=new c(this._node[t],this._data).run()}_handleArray(){this._result=[],this._node.forEach(this._handleArElt,this)}_handleArElt(t){let e=new c(t,this._data).run();this._result.push(e)}};var yh=class{constructor(t,e){this._app=t,this._isTemplate=e}parse(t){let e={},s=null,i=t.compressedFormat;i&&!t.entDecompressed&&(t.entDecompressed=!0,t.entities=new $E(t.entities,i).run());for(let r in t.entities){let a=t.entities[r],o=this._createEntity(a,i);e[r]=o,a.parent===null&&(s=o)}for(let r in t.entities){let a=e[r],o=t.entities[r].children,l=o.length;for(let h=0;h<l;h++){let f=e[o[h]];f&&a.addChild(f)}}return this._openComponentData(s,t.entities),s}_createEntity(t,e){let s=new Ne(t.name,this._app);if(s.guid=t.resource_id,this._setPosRotScale(s,t,e),s._enabled=t.enabled??!0,this._isTemplate?s._template=!0:s._enabledInHierarchy=s._enabled,s.template=t.template,t.tags)for(let i=0;i<t.tags.length;i++)s.tags.add(t.tags[i]);return s}_setPosRotScale(t,e,s){if(s)Fu.setCompressedPRS(t,e,s);else{let i=e.position,r=e.rotation,a=e.scale;t.setLocalPosition(i[0],i[1],i[2]),t.setLocalEulerAngles(r[0],r[1],r[2]),t.setLocalScale(a[0],a[1],a[2])}}_openComponentData(t,e){let s=this._app.systems.list,i=s.length,r=e[t.guid];for(let o=0;o<i;o++){let l=s[o],h=r.components[l.id];h&&l.addComponent(t,h)}i=r.children.length;let a=t._children;for(let o=0;o<i;o++)a[o]&&(a[o]=this._openComponentData(a[o],e));return t}};var Eh=class{static load(t,e,s){typeof t=="string"&&(t={load:t,original:t}),Le.get(t.load,{retry:e>0,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<o.length;l++)typeof t[r][o[l]]!="string"&&this.setInvalid(o[l],t[r])}}return t.validated=!0,this.valid}_createEnumValidator(t){return function(e){return t.indexOf(e)>=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;e<s.length;e++){let r=s[e][0],a=s[e][1];t[r]!==void 0&&(t[a]===void 0&&(t[a]=t[r]),delete t[r])}let i=["fresnelFactor","shadowSampleType"];for(e=0;e<i.length;e++){let r=i[e];t.hasOwnProperty(r)&&delete t[r]}return t}_validate(t){return t.validated||(this._validator||(this._validator=new ZE),this._validator.validate(t)),t}};var Jj={aoMap:"white",aoDetailMap:"white",diffuseMap:"gray",diffuseDetailMap:"gray",specularMap:"gray",specularityFactorMap:"white",metalnessMap:"black",glossMap:"gray",sheenMap:"black",sheenGlossMap:"gray",clearCoatMap:"black",clearCoatGlossMap:"gray",clearCoatNormalMap:"normal",refractionMap:"white",emissiveMap:"gray",normalMap:"normal",normalDetailMap:"normal",heightMap:"gray",opacityMap:"gray",sphereMap:"gray",lightMap:"white",thicknessMap:"black",iridescenceMap:"black",iridescenceThicknessMap:"black",envAtlas:"black",anisotropyMap:"black"},N_=class extends Re{constructor(t){super(t,"material"),this._assets=t.assets,this._device=t.graphicsDevice,this._parser=new F_}load(t,e){typeof t=="string"&&(t={load:t,original:t}),Le.get(t.load,{retry:this.maxRetries>0,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<a.length;o++){l=a[o],h=i._assetReferences[l];let u=s[l],d=i[l],p=d===this._getPlaceholderTexture(l),m=s.validated;u&&(!d||!m||p)?(h||(h=new pa(l,t,e,{load:this._onTextureLoad,add:this._onTextureAdd,remove:this._onTextureRemoveOrUnload,unload:this._onTextureRemoveOrUnload},this),i._assetReferences[l]=h),r?h.url=t.getAbsoluteUrl(u):h.id=u,h.asset&&(h.asset.resource?this._assignTexture(l,t,h.asset.resource):this._assignPlaceholderTexture(l,t),e.load(h.asset))):h&&(r?h.url=null:h.id=null)}let f=hS;for(o=0;o<f.length;o++)l=f[o],h=i._assetReferences[l],s[l]&&!t.data.prefilteredCubeMap128&&(h||(h=new pa(l,t,e,{load:this._onCubemapLoad,add:this._onCubemapAdd,remove:this._onCubemapRemoveOrUnload,unload:this._onCubemapRemoveOrUnload},this),i._assetReferences[l]=h),r?h.url=s[l]:h.id=s[l],h.asset&&(h.asset.loaded&&this._assignCubemap(l,t,h.asset.resources),e.load(h.asset)));this._parser.initialize(i,s)}};var QE=class{constructor(t){this._device=t.device,this._defaultMaterial=t.defaultMaterial,this._assets=t.assets}parse(t,e,s){Il.parse("filename.glb","",t,this._device,this._assets,s?.options??{},(i,r)=>{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;i<e.nodes.length;i++){let r=e.nodes[i],a=new Pe(r.name);a.setLocalPosition(r.position[0],r.position[1],r.position[2]),a.setLocalEulerAngles(r.rotation[0],r.rotation[1],r.rotation[2]),a.setLocalScale(r.scale[0],r.scale[1],r.scale[2]),a.scaleCompensation=!!r.scaleCompensation,s.push(a)}for(i=1;i<e.parents.length;i++)s[e.parents[i]].addChild(s[i]);return s}_parseSkins(t,e){let s=t.model,i=[],r=[],a,o;for(a=0;a<s.skins.length;a++){let l=s.skins[a],h=[];for(o=0;o<l.inverseBindMatrices.length;o++){let p=l.inverseBindMatrices[o];h[o]=new W().set(p)}let f=new Vc(this._device,h,l.boneNames);i.push(f);let u=new er(f),d=[];for(o=0;o<f.boneNames.length;o++){let p=f.boneNames[o],m=e[0].findByName(p);d.push(m)}u.bones=d,r.push(u)}return{skins:i,instances:r}}_getMorphVertexCount(t,e,s){for(let i=0;i<t.meshes.length;i++){let r=t.meshes[i];if(r.morph===e)return s[r.vertices].numVertices}}_parseMorphs(t,e,s){let i=t.model,r=[],a=[],o,l,h,f,u,d;if(i.morphs){let p=function(m,_,S){let g=new Float32Array(S*3);for(let T=0;T<_.length;T++){let C=_[T]*3;g[C]=m[T*3],g[C+1]=m[T*3+1],g[C+2]=m[T*3+2]}return g};for(o=0;o<i.morphs.length;o++){for(f=i.morphs[o].targets,d=[],h=this._getMorphVertexCount(i,o,s),l=0;l<f.length;l++){let S=f[l].aabb,g=S.min,T=S.max,C=new ge(new x((T[0]+g[0])*.5,(T[1]+g[1])*.5,(T[2]+g[2])*.5),new x((T[0]-g[0])*.5,(T[1]-g[1])*.5,(T[2]-g[2])*.5)),v=f[l].indices,E=f[l].deltaPositions,y=f[l].deltaNormals;v&&(E=p(E,v,h),y=p(y,v,h)),u=new Gc({deltaPositions:E,deltaNormals:y,name:f[l].name,aabb:C}),d.push(u)}let m=new Ko(d,this._device);r.push(m);let _=new Ar(m);a.push(_)}}return{morphs:r,instances:a}}_parseVertexBuffers(t){let e=t.model,s=[],i={position:ee,normal:Ot,tangent:vs,blendWeight:bs,blendIndices:$t,color:Ct,texCoord0:_t,texCoord1:ri,texCoord2:Ca,texCoord3:Pa,texCoord4:wa,texCoord5:Ia,texCoord6:Ra,texCoord7:ba};for(let r=0;r<e.vertices.length;r++){let a=e.vertices[r],o=[];for(let d in a){let p=a[d];o.push({semantic:i[d],components:p.components,type:tq[p.type],normalize:i[d]===Ct})}let l=new Ft(this._device,o),h=a.position.data.length/a.position.components,f=new ft(this._device,l,h),u=new Jr(f);for(let d=0;d<h;d++){for(let p in a){let m=a[p];switch(m.components){case 1:u.element[i[p]].set(m.data[d]);break;case 2:u.element[i[p]].set(m.data[d*2],1-m.data[d*2+1]);break;case 3:u.element[i[p]].set(m.data[d*3],m.data[d*3+1],m.data[d*3+2]);break;case 4:u.element[i[p]].set(m.data[d*4],m.data[d*4+1],m.data[d*4+2],m.data[d*4+3]);break}}u.next()}u.end(),s.push(f)}return s}_parseIndexBuffers(t,e){let s=t.model,i=null,r=null,a,o=0;for(a=0;a<s.meshes.length;a++){let h=s.meshes[a];h.indices!==void 0&&(o+=h.indices.length)}let l=0;for(a=0;a<e.length;a++)l=Math.max(l,e[a].numVertices);return o>0&&(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;f<o.meshes.length;f++){let u=o.meshes[f],d=u.aabb,p=d.min,m=d.max,_=new ge(new x((m[0]+p[0])*.5,(m[1]+p[1])*.5,(m[2]+p[2])*.5),new x((m[0]-p[0])*.5,(m[1]-p[1])*.5,(m[2]-p[2])*.5)),S=u.indices!==void 0,g=new _e(this._device);g.vertexBuffer=i[u.vertices],g.indexBuffer[0]=S?r:null,g.primitive[0].type=eq[u.type],g.primitive[0].base=S?u.base+h:u.base,g.primitive[0].count=u.count,g.primitive[0].indexed=S,g.skin=u.skin!==void 0?e[u.skin]:null,g.morph=u.morph!==void 0?s[u.morph]:null,g.aabb=_,S&&(a.set(u.indices,h),h+=u.indices.length),l.push(g)}return r!==null&&r.unlock(),l}_parseMeshInstances(t,e,s,i,r,a,o){let l=t.model,h=[],f;for(f=0;f<l.meshInstances.length;f++){let u=l.meshInstances[f],d=e[u.node],p=s[u.mesh],m=new we(p,this._defaultMaterial,d);if(p.skin){let _=i.indexOf(p.skin);m.skinInstance=r[_]}if(p.morph){let _=a.indexOf(p.morph);m.morphInstance=o[_]}h.push(m)}return h}};var B_=class extends Re{constructor(t){super(t,"model"),this._parsers=[],this.device=t.graphicsDevice,this.assets=t.assets,this.defaultMaterial=ra(this.device),this.addParser(new JE(this),(e,s)=>xe.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<this._parsers.length;o++){let l=this._parsers[o];if(l.decider(t.original,a)){l.parser.parse(a,(h,f)=>{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<Rl._types.length;d++)f[Rl._types[d].name]=Rl._types[d];Rl._types.length=0,e(null,f,h);let u=l.split("&hash=")[0];delete s._loader._cache[Zc.makeKey(u,"script")]}}),[r]=t.load.split("?");r.endsWith(".mjs")?this._loadModule(r,i):this._loadScript(t.load,i)}open(t,e){return e}patch(t,e){}_loadScript(t,e){let s=document.head,i=document.createElement("script");this._cache[t]=i,i.async=!1,i.addEventListener("error",a=>{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<v.length;y+=4){let P=v[y+3],A=v[y+1];v[y+0]=P,v[y+2]=E(P,A),v[y+3]=255}return v},a=v=>{let E=new Uint16Array(v.length/4);for(let y=0;y<v.length;y+=4){let P=v[y+0],A=v[y+1],w=v[y+2];E[y/4]=(P&248)<<8|(A&252)<<3|w>>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<A.length;++w){let I=A[w];if(v.formats[I])return I}return"none"})(E?u:f)},p=(v,E,y)=>{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<D;++N){let k=A.getImageTranscodedSizeInBytes(N,0,0,U),z=new Uint8Array(k);if(!A.transcodeImage(z,N,0,0,U,0,-1,-1))throw A.close(),A.delete(),new Error(`Failed to transcode image url=${v}`);let V=U===c.cTFRGB565||U===c.cTFRGBA4444;b.push(V?new Uint16Array(z.buffer):z)}if(A.close(),A.delete(),H)for(U=c.cTFRGB565,L=0;L<b.length;++L)b[L]=a(r(b[L]));return{format:i(U,y.deviceDetails),width:w,height:I,levels:b,cubemap:!1,transcodeTime:l()-P,url:v,unswizzledGGGR:H}},_=(v,E,y)=>{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;k<O;++k){let z=A.getImageTranscodedSizeInBytes(0,k,L),V=new Uint8Array(z);if(!A.transcodeImage(V,0,k,L,0,0))if(k===O-1&&z===N[k-1].buffer.byteLength)V.set(new Uint8Array(N[k-1].buffer));else throw A.close(),A.delete(),new Error(`Failed to transcode image url=${v}`);let q=L===c.cTFRGB565||L===c.cTFRGBA4444;N.push(q?new Uint16Array(V.buffer):V)}if(A.close(),A.delete(),U)for(L=c.cTFRGB565,b=0;b<N.length;++b)N[b]=a(r(N[b]));return{format:i(L,y.deviceDetails),width:w,height:I,levels:N,cubemap:!1,transcodeTime:l()-P,url:v,unswizzledGGGR:U}},S=(v,E,y)=>y.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<C.length;++y)g(C[y].url,C[y].data,C[y].options);C.length=0});break;case"transcode":h?g(E.url,E.data,E.options):C.push(E);break}}}var iq=c=>({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(`
`);return new Blob([o],{type:"application/javascript"})},s=()=>{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;r<i.length;++r)i[r](e);else{s.format===ya||s.format===Ea?s.levels=s.levels.map(r=>new Uint16Array(r)):s.levels=s.levels.map(r=>new Uint8Array(r));for(let r=0;r<i.length;++r)i[r](null,s)}delete this.callbacks[t]}},gb=class{constructor(t,e,s){this.queue=t,this.worker=new Worker(e.workerUrl),this.worker.addEventListener("message",i=>{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<t;++r)Sb.enqueueClient(new gb(Sb,i,e))})}}}var mb=null;function iA(c,t,e,s,i){return vb(),mb||(mb={formats:iq(c)}),Sb.enqueueJob(t,e,s,{deviceDetails:mb,isGGGR:!!i?.isGGGR,isKTX2:!!i?.isKTX2}),xb}var nr=class{load(t,e,s){throw new Error("not implemented")}open(t,e,s){throw new Error("not implemented")}};var rA=class extends nr{constructor(t,e){super(),this.device=e,this.maxRetries=0}load(t,e,s){let i=this.device,r=a=>{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;d<Math.max(1,o.levelCount);++d)h.push({byteOffset:r.readU64(),byteLength:r.readU64(),uncompressedByteLength:r.readU64()});if(r.readU32()!==l.kvdByteOffset-l.dfdByteOffset)return null;r.skip(8);let u=r.readU8();r.skip(l.dfdByteLength-9),r.skip(l.kvdByteLength),o.supercompressionScheme===1||u===fq.KHR_DF_MODEL_UASTC?iA(this.device,e.load,t,s,{isGGGR:(i?.file?.variants?.basis?.opt&8)!==0,isKTX2:!0})||s(`Basis module not found. Asset [${i.name}](${i.getFileUrl()}) basis texture variant will not be loaded.`):s("unsupported KTX2 pixel format")}};var lA=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=new Uint32Array(e,0,32),a=r[4],o=r[3],l=Math.max(r[7],1),h=r[20]===4,f=r[21],u=r[22],d=r[28]===65024,p=827611204,m=894720068,_=113,S=116,g=826496069,T=825438800,C=825504336,v=825439312,E=825504848,y=!1,P=!1,A=!1,w=!1,I=null,D=1,O;if(h?f===p?(I=To,y=!0):f===m?(I=Gr,y=!0):f===_?(I=Me,D=2):f===S?(I=ke,D=4):f===g?(I=Eo,y=!0,P=!0):f===T||f===C?(I=f===T?Vr:Hr,y=!0,A=!0):(f===v||f===E)&&(I=f===v?Ao:Co,y=!0,w=!0):u===32&&(I=ce),!I)return O=new Z(s,{width:4,height:4,format:Ss,name:"dds-legacy-empty"}),O;O=new Z(s,{name:t,addressU:d?1:0,addressV:d?1:0,width:a,height:o,format:I,cubemap:d,mipmaps:l>1,...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;V<M;V++){let q=a,re=o;for(let te=0;te<l;te++){y?P?H=Math.floor((q+3)/4)*Math.floor((re+3)/4)*8:A?H=Math.max(q,16)*Math.max(re,8)/4:w?H=Math.max(q,8)*Math.max(re,8)/2:(N=Math.floor((q+U-1)/U),k=Math.floor((re+L-1)/L),z=N*k,H=z*b):H=q*re*4;let j=I===ke?new Float32Array(e,G,H):I===Me?new Uint16Array(e,G,H):new Uint8Array(e,G,H);d?(O._levels[te]||(O._levels[te]=[]),O._levels[te][V]=j):O._levels[te]=j,G+=H*D,q=Math.max(q*.5,1),re=Math.max(re*.5,1)}}return O.upload(),O}};var cA=class extends nr{constructor(t){super(),this.maxRetries=0}load(t,e,s){ae.fetchArrayBuffer(t.load,e,s,this.maxRetries),s.data&&!s.data.type&&(s.data.type=oc)}open(t,e,s,i={}){let r=this.parse(e);if(!r)return null;let a=new Z(s,{name:t,addressU:0,addressV:1,minFilter:0,magFilter:0,width:r.width,height:r.height,levels:r.levels,format:ce,type:oc,mipmaps:!1,...i});return a.upload(),a}parse(t){let e=new Kl(t);if(!e.readLine().startsWith("#?RADIANCE"))return null;let i={};for(;;){let h=e.readLine();if(h.length===0)break;{let f=h.split("=");f.length===2&&(i[f[0]]=f[1])}}if(!i.hasOwnProperty("FORMAT"))return null;let r=e.readLine().split(" ");if(r.length!==4)return null;let a=parseInt(r[1],10),o=parseInt(r[3],10),l=this._readPixels(e,o,a,r[0]==="-Y");return l?{width:o,height:a,levels:[l]}:null}_readPixels(t,e,s,i){if(e<8||e>32767)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;f<s;++f){if(f&&t.readArray(r),(r[2]<<8)+r[3]!==e)return null;for(d=0;d<4;++d)for(h=0;h<e;)if(p=t.readU8(),p>128){if(p-=128,h+p>e)return null;for(m=t.readU8(),u=0;u<p;++u)o[l+d+4*h++]=m}else{if(p===0||h+p>e)return null;for(u=0;u<p;++u)o[l+d+4*h++]=t.readU8()}l+=e*4*(i?1:-1)}return o}_readPixelsFlat(t,e,s){return t.remainingBytes===e*s*4?new Uint8Array(t.arraybuffer,t.offset):null}};var bG={repeat:0,clamp:1,mirror:2},DG={nearest:0,linear:1,nearest_mip_nearest:2,linear_mip_nearest:4,nearest_mip_linear:3,linear_mip_linear:5},uq={default:Gt,rgbm:_i,rgbe:oc,rgbp:In,swizzleGGGR:Rn},dq=function(c){let t=gt.calcMipLevelsCount(c._width,c._height),e=function(i){return i instanceof HTMLCanvasElement||i instanceof HTMLImageElement||i instanceof HTMLVideoElement};if(!(c._format===ce||c._format===ke)||c._volume||c._compressed||c._levels.length===1||c._levels.length===t||e(c._cubemap?c._levels[0][0]:c._levels[0]))return;let s=function(i,r,a){let o=Math.max(1,i>>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<l;++p)for(let m=0;m<o;++m)for(let _=0;_<4;++_){let S=0;for(let g=0;g<u;++g)for(let T=0;T<f;++T)S+=a[(m*f+T+(p*u+g)*i)*4+_];h[(m+p*o)*4+_]=S/d}return h};for(let i=c._levels.length;i<t;++i){let r=Math.max(1,c._width>>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<s.length;i++){let r=s[i];if(!r.results.length)continue;let a;r.inputSource&&(a=this.manager.input._getByInputSource(r.inputSource)),this.updateHitResults(r.results,a)}}else{let s=e.getHitTestResults(this._xrHitTestSource);if(!s.length)return;this.updateHitResults(s)}}updateHitResults(e,s){if(this._inputSource&&this._inputSource!==s)return;let i=fA.pop()??new x;s?i.copy(s.getOrigin()):i.copy(this.manager.camera.getPosition());let r=1/0,a=null,o=fA.pop()??new x,l=LG.pop()??new $;for(let h=0;h<e.length;h++){let f=e[h].getPose(this.manager._referenceSpace),u=i.distance(f.transform.position);u>=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<this.sources.length;e++)this.sources[e].onStop();this.sources=[],this.fire("unavailable")}}start(e={}){if(!this._supported){e.callback?.(new Error("XR HitTest is not supported"),null);return}if(!this._available){e.callback?.(new Error("XR HitTest is not available"),null);return}!e.profile&&!e.spaceType&&(e.spaceType=hA);let s,i=e.offsetRay;if(i){let a=new DOMPoint(i.origin.x,i.origin.y,i.origin.z,1),o=new DOMPoint(i.direction.x,i.direction.y,i.direction.z,0);s=new XRRay(a,o)}let r=e.callback;e.spaceType?this.manager.session.requestReferenceSpace(e.spaceType).then(a=>{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.sources.length;s++)this.sources[s].update(e)}get supported(){return this._supported}get available(){return this._available}};n(_a,"EVENT_AVAILABLE","available"),n(_a,"EVENT_UNAVAILABLE","unavailable"),n(_a,"EVENT_ADD","add"),n(_a,"EVENT_REMOVE","remove"),n(_a,"EVENT_RESULT","result"),n(_a,"EVENT_ERROR","error");var Ch=class extends J{constructor(e,s){super();n(this,"_image");n(this,"_width");n(this,"_bitmap",null);n(this,"_measuredWidth",0);n(this,"_trackable",!1);n(this,"_tracking",!1);n(this,"_emulated",!1);n(this,"_pose",null);n(this,"_position",new x);n(this,"_rotation",new $);this._image=e,this._width=s}get image(){return this._image}set width(e){this._width=e}get width(){return this._width}get trackable(){return this._trackable}get tracking(){return this._tracking}get emulated(){return this._emulated}prepare(){return this._bitmap?{image:this._bitmap,widthInMeters:this._width}:createImageBitmap(this._image).then(e=>(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<e.length;s++)this._images[s]._trackable=e[s]==="trackable"}).catch(e=>{this._available=!1,this.fire("error",e)})}_onSessionEnd(){this._available=!1;for(let e=0;e<this._images.length;e++){let s=this._images[e];s._pose=null,s._measuredWidth=0,s._tracking&&(s._tracking=!1,s.fire("untracked"))}}prepareImages(e){this._images.length?Promise.all(this._images.map(s=>s.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;r<s.length;r++){i[s[r].index]=s[r];let a=this._images[s[r].index];a._emulated=s[r].trackingState==="emulated",a._measuredWidth=s[r].measuredWidthInMeters,a._pose=e.getPose(s[r].imageSpace,this._manager._referenceSpace)}for(let r=0;r<this._images.length;r++)this._images[r]._tracking&&!i[r]?(this._images[r]._tracking=!1,this._images[r].fire("untracked")):!this._images[r]._tracking&&i[r]&&(this._images[r]._tracking=!0,this._images[r].fire("tracked"))}get supported(){return this._supported}get available(){return this._available}get images(){return this._images}};n(Bu,"EVENT_ERROR","error");var K_=class{constructor(t,e){n(this,"_index");n(this,"_hand");n(this,"_joints",[]);n(this,"_tip",null);this._index=t,this._hand=e,this._hand._fingers.push(this)}get index(){return this._index}get hand(){return this._hand}get joints(){return this._joints}get tip(){return this._tip}};var MG=ue.browser&&window.XRHand?["thumb-tip","index-finger-tip","middle-finger-tip","ring-finger-tip","pinky-finger-tip"]:[],OG={};for(let c=0;c<MG.length;c++)OG[MG[c]]=!0;var Uu=class{constructor(t,e,s,i=null){n(this,"_index");n(this,"_id");n(this,"_hand");n(this,"_finger");n(this,"_wrist");n(this,"_tip");n(this,"_radius",null);n(this,"_localTransform",new W);n(this,"_worldTransform",new W);n(this,"_localPosition",new x);n(this,"_localRotation",new $);n(this,"_position",new x);n(this,"_rotation",new $);n(this,"_dirtyLocal",!0);this._index=t,this._id=e,this._hand=s,this._finger=i,this._wrist=e==="wrist",this._tip=this._finger&&!!OG[e]}update(t){this._dirtyLocal=!0,this._radius=t.radius,this._localPosition.copy(t.transform.position),this._localRotation.copy(t.transform.orientation)}_updateTransforms(){this._dirtyLocal&&(this._dirtyLocal=!1,this._localTransform.setTRS(this._localPosition,this._localRotation,x.ONE));let e=this._hand._manager.camera.parent;e?this._worldTransform.mul2(e.getWorldTransform(),this._localTransform):this._worldTransform.copy(this._localTransform)}getPosition(){return this._updateTransforms(),this._worldTransform.getTranslation(this._position),this._position}getRotation(){return this._updateTransforms(),this._rotation.setFromMat4(this._worldTransform),this._rotation}get id(){return this._id}get index(){return this._index}get hand(){return this._hand}get finger(){return this._finger}get wrist(){return this._wrist}get tip(){return this._tip}get radius(){return this._radius||.005}};var dA=[],ku=new x,uA=new x,FG=new x;ue.browser&&window.XRHand&&(dA=[["thumb-metacarpal","thumb-phalanx-proximal","thumb-phalanx-distal","thumb-tip"],["index-finger-metacarpal","index-finger-phalanx-proximal","index-finger-phalanx-intermediate","index-finger-phalanx-distal","index-finger-tip"],["middle-finger-metacarpal","middle-finger-phalanx-proximal","middle-finger-phalanx-intermediate","middle-finger-phalanx-distal","middle-finger-tip"],["ring-finger-metacarpal","ring-finger-phalanx-proximal","ring-finger-phalanx-intermediate","ring-finger-phalanx-distal","ring-finger-tip"],["pinky-finger-metacarpal","pinky-finger-phalanx-proximal","pinky-finger-phalanx-intermediate","pinky-finger-phalanx-distal","pinky-finger-tip"]]);var Ph=class extends J{constructor(e){super();n(this,"_manager");n(this,"_inputSource");n(this,"_tracking",!1);n(this,"_fingers",[]);n(this,"_joints",[]);n(this,"_jointsById",{});n(this,"_tips",[]);n(this,"_wrist",null);let s=e._xrInputSource.hand;if(this._manager=e._manager,this._inputSource=e,s.get("wrist")){let i=new Uu(0,"wrist",this,null);this._wrist=i,this._joints.push(i),this._jointsById.wrist=i}for(let i=0;i<dA.length;i++){let r=new K_(i,this);for(let a=0;a<dA[i].length;a++){let o=dA[i][a];if(!s.get(o))continue;let l=new Uu(a,o,this,r);this._joints.push(l),this._jointsById[o]=l,l.tip&&(this._tips.push(l),r._tip=l),r._joints.push(l)}}}update(e){let s=this._inputSource._xrInputSource;for(let u=0;u<this._joints.length;u++){let d=this._joints[u],p=s.hand.get(d._id);if(p){let m;if(e.session.visibilityState!=="hidden"&&(m=e.getJointPose(p,this._manager._referenceSpace)),m)d.update(m),d.wrist&&!this._tracking&&(this._tracking=!0,this.fire("tracking"));else if(d.wrist){this._tracking&&(this._tracking=!1,this.fire("trackinglost"));break}}}let i=this._jointsById["thumb-metacarpal"],r=this._jointsById["thumb-tip"],a=this._jointsById["index-finger-phalanx-proximal"],o=this._jointsById["index-finger-tip"],l=this._jointsById["ring-finger-phalanx-proximal"],h=this._jointsById["pinky-finger-phalanx-proximal"];if(i&&r&&a&&o&&l&&h){this._inputSource._dirtyRay=!0,this._inputSource._rayLocal.origin.lerp(r._localPosition,o._localPosition,.5);let u=i,d=h;if(this._inputSource.handedness===Ab){let p=u;u=d,d=p}ku.sub2(u._localPosition,this._wrist._localPosition),uA.sub2(d._localPosition,this._wrist._localPosition),FG.cross(ku,uA).normalize(),ku.lerp(a._localPosition,l._localPosition,.5),ku.sub(this._wrist._localPosition).normalize(),this._inputSource._rayLocal.direction.lerp(FG,ku,.5).normalize()}this._fingerIsClosed(1)&&this._fingerIsClosed(2)&&this._fingerIsClosed(3)&&this._fingerIsClosed(4)?this._inputSource._squeezing||(this._inputSource._squeezing=!0,this._inputSource.fire("squeezestart"),this._manager.input.fire("squeezestart",this._inputSource)):this._inputSource._squeezing&&(this._inputSource._squeezing=!1,this._inputSource.fire("squeeze"),this._manager.input.fire("squeeze",this._inputSource),this._inputSource.fire("squeezeend"),this._manager.input.fire("squeezeend",this._inputSource))}_fingerIsClosed(e){let s=this._fingers[e];return ku.sub2(s.joints[0]._localPosition,s.joints[1]._localPosition).normalize(),uA.sub2(s.joints[2]._localPosition,s.joints[3]._localPosition).normalize(),ku.dot(uA)<-.8}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}};n(Ph,"EVENT_TRACKING","tracking"),n(Ph,"EVENT_TRACKINGLOST","trackinglost");var NG=new x,BG=new $,Rq=0,Es=class extends J{constructor(e,s){super();n(this,"_id");n(this,"_manager");n(this,"_xrInputSource");n(this,"_ray",new ws);n(this,"_rayLocal",new ws);n(this,"_grip",!1);n(this,"_hand",null);n(this,"_velocitiesAvailable",!1);n(this,"_velocitiesTimestamp",Tt());n(this,"_localTransform",null);n(this,"_worldTransform",null);n(this,"_position",new x);n(this,"_rotation",new $);n(this,"_localPosition",null);n(this,"_localPositionLast",null);n(this,"_localRotation",null);n(this,"_linearVelocity",null);n(this,"_dirtyLocal",!0);n(this,"_dirtyRay",!1);n(this,"_selecting",!1);n(this,"_squeezing",!1);n(this,"_elementInput",!0);n(this,"_elementEntity",null);n(this,"_hitTestSources",[]);this._id=++Rq,this._manager=e,this._xrInputSource=s,s.hand&&(this._hand=new Ph(this))}get id(){return this._id}get inputSource(){return this._xrInputSource}get targetRayMode(){return this._xrInputSource.targetRayMode}get handedness(){return this._xrInputSource.handedness}get profiles(){return this._xrInputSource.profiles}get grip(){return this._grip}get hand(){return this._hand}get gamepad(){return this._xrInputSource.gamepad||null}get selecting(){return this._selecting}get squeezing(){return this._squeezing}set elementInput(e){this._elementInput!==e&&(this._elementInput=e,this._elementInput||(this._elementEntity=null))}get elementInput(){return this._elementInput}get elementEntity(){return this._elementEntity}get hitTestSources(){return this._hitTestSources}update(e){if(this._hand)this._hand.update(e);else{let s=this._xrInputSource.gripSpace;if(s){let r=e.getPose(s,this._manager._referenceSpace);if(r){this._grip||(this._grip=!0,this._localTransform=new W,this._worldTransform=new W,this._localPositionLast=new x,this._localPosition=new x,this._localRotation=new $,this._linearVelocity=new x);let a=Tt(),o=(a-this._velocitiesTimestamp)/1e3;this._velocitiesTimestamp=a,this._dirtyLocal=!0,this._localPositionLast.copy(this._localPosition),this._localPosition.copy(r.transform.position),this._localRotation.copy(r.transform.orientation),this._velocitiesAvailable=!0,this._manager.input.velocitiesSupported&&r.linearVelocity?this._linearVelocity.copy(r.linearVelocity):o>0&&(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<s.length;i++)this._addInputSource(s[i])}_onSessionEnd(){let e=this._inputSources.length;for(;e--;){let i=this._inputSources[e];this._inputSources.splice(e,1),i.fire("remove"),this.fire("remove",i)}this.manager.session.removeEventListener("inputsourceschange",this._onInputSourcesChangeEvt)}_onInputSourcesChange(e){for(let s=0;s<e.removed.length;s++)this._removeInputSource(e.removed[s]);for(let s=0;s<e.added.length;s++)this._addInputSource(e.added[s])}_getByInputSource(e){for(let s=0;s<this._inputSources.length;s++)if(this._inputSources[s].inputSource===e)return this._inputSources[s];return null}_addInputSource(e){if(this._getByInputSource(e))return;let s=new Es(this.manager,e);this._inputSources.push(s),this.fire("add",s)}_removeInputSource(e){for(let s=0;s<this._inputSources.length;s++){if(this._inputSources[s].inputSource!==e)continue;let i=this._inputSources[s];this._inputSources.splice(s,1);let r=i.hitTestSources.length;for(;r--;)i.hitTestSources[r].remove();i.fire("remove"),this.fire("remove",i);return}}update(e){for(let s=0;s<this._inputSources.length;s++)this._inputSources[s].update(e)}get inputSources(){return this._inputSources}};n(lr,"EVENT_ADD","add"),n(lr,"EVENT_REMOVE","remove"),n(lr,"EVENT_SELECT","select"),n(lr,"EVENT_SELECTSTART","selectstart"),n(lr,"EVENT_SELECTEND","selectend"),n(lr,"EVENT_SQUEEZE","squeeze"),n(lr,"EVENT_SQUEEZESTART","squeezestart"),n(lr,"EVENT_SQUEEZEEND","squeezeend");var j_=new x,UG=new x,Pb=new W,kG=new W,wh=class extends J{constructor(e){super();n(this,"_manager");n(this,"_supported",!1);n(this,"_available",!1);n(this,"_lightProbeRequested",!1);n(this,"_lightProbe",null);n(this,"_intensity",0);n(this,"_rotation",new $);n(this,"_color",new F);n(this,"_sphericalHarmonics",new Float32Array(27));this._manager=e,this._manager.on("start",this._onSessionStart,this),this._manager.on("end",this._onSessionEnd,this)}_onSessionStart(){this._manager.session.requestLightProbe&&(this._supported=!0)}_onSessionEnd(){this._supported=!1,this._available=!1,this._lightProbeRequested=!1,this._lightProbe=null}start(){let e;if(this._manager.session||(e=new Error("XR session is not running")),!e&&this._manager.type!==bl&&(e=new Error("XR session type is not AR")),!e&&!this._supported&&(e=new Error("light-estimation is not supported")),(!e&&this._lightProbe||this._lightProbeRequested)&&(e=new Error("light estimation is already requested")),e){this.fire("error",e);return}this._lightProbeRequested=!0,this._manager.session.requestLightProbe().then(s=>{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._planes.length;e++)this._planes[e].destroy(),this.fire("remove",this._planes[e]);this._planesIndex.clear(),this._planes.length=0,this._available&&(this._available=!1,this.fire("unavailable"))}update(e){if(!this._available)if(!this._manager.session.enabledFeatures&&e.detectedPlanes.size)this._available=!0,this.fire("available");else return;let s=e.detectedPlanes;for(let[i,r]of this._planesIndex)s.has(i)||(this._planesIndex.delete(i),this._planes.splice(this._planes.indexOf(r),1),r.destroy(),this.fire("remove",r));for(let i of s){let r=this._planesIndex.get(i);r?r.update(e):(r=new Ih(this,i),this._planesIndex.set(i,r),this._planes.push(r),r.update(e),this.fire("add",r))}}get supported(){return this._supported}get available(){return this._available}get planes(){return this._planes}};n(on,"EVENT_AVAILABLE","available"),n(on,"EVENT_UNAVAILABLE","unavailable"),n(on,"EVENT_ADD","add"),n(on,"EVENT_REMOVE","remove");var nn=class extends J{constructor(e,s,i=null){super();n(this,"_position",new x);n(this,"_rotation",new $);n(this,"_uuid",null);n(this,"_uuidRequests",null);this._anchors=e,this._xrAnchor=s,this._uuid=i}destroy(){if(!this._xrAnchor)return;let e=this._xrAnchor;this._xrAnchor.delete(),this._xrAnchor=null,this.fire("destroy",e,this)}update(e){if(!this._xrAnchor)return;let s=e.getPose(this._xrAnchor.anchorSpace,this._anchors.manager._referenceSpace);if(s){if(this._position.equals(s.transform.position)&&this._rotation.equals(s.transform.orientation))return;this._position.copy(s.transform.position),this._rotation.copy(s.transform.orientation),this.fire("change")}}getPosition(){return this._position}getRotation(){return this._rotation}persist(e){if(!this._anchors.persistence){e?.(new Error("Persistent Anchors are not supported"),null);return}if(this._uuid){e?.(null,this._uuid);return}if(this._uuidRequests){e&&this._uuidRequests.push(e);return}this._uuidRequests=[],this._xrAnchor.requestPersistentHandle().then(s=>{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<this._creationQueue.length;s++)this._creationQueue[s].callback&&this._creationQueue[s].callback(new Error("session ended"),null);this._creationQueue.length=0,this._index.clear(),this._indexByUuid.clear();let e=this._list.length;for(;e--;)this._list[e].destroy();this._list.length=0,this.fire("unavailable")}_createAnchor(e,s=null){let i=new nn(this,e,s);return this._index.set(e,i),s&&this._indexByUuid.set(s,i),this._list.push(i),i.once("destroy",this._onAnchorDestroy,this),i}_onAnchorDestroy(e,s){this._index.delete(e),s.uuid&&this._indexByUuid.delete(s.uuid);let i=this._list.indexOf(s);i!==-1&&this._list.splice(i,1),this.fire("destroy",s)}create(e,s,i){if(!this._available){i?.(new Error("Anchors API is not available"),null);return}if(window.XRHitTestResult&&e instanceof XRHitTestResult){let r=e;if(i=s,!this._supported){i?.(new Error("Anchors API is not supported"),null);return}if(!r.createAnchor){i?.(new Error("Creating Anchor from Hit Test is not supported"),null);return}r.createAnchor().then(a=>{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<this._creationQueue.length;s++){let i=this._creationQueue[s];e.createAnchor(i.transform,this.manager._referenceSpace).then(r=>{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._list.length;s++)this._list[s].update(e);for(let s of e.trackedAnchors){if(this._index.has(s))continue;try{let a=s.anchorSpace}catch{continue}let i=this._createAnchor(s);i.update(e);let r=this._callbacksAnchors.get(s);r&&(this._callbacksAnchors.delete(s),r(null,i)),this.fire("add",i)}}get supported(){return this._supported}get available(){return this._available}get persistence(){return this._persistence}get uuids(){return!this._available||!this._persistence||!this.manager.active?null:this.manager.session.persistentAnchors}get list(){return this._list}};n(oo,"EVENT_AVAILABLE","available"),n(oo,"EVENT_UNAVAILABLE","unavailable"),n(oo,"EVENT_ERROR","error"),n(oo,"EVENT_ADD","add"),n(oo,"EVENT_DESTROY","destroy");var q_=class extends J{constructor(e,s){super();n(this,"_meshDetection");n(this,"_xrMesh");n(this,"_lastChanged",0);n(this,"_position",new x);n(this,"_rotation",new $);this._meshDetection=e,this._xrMesh=s,this._lastChanged=this._xrMesh.lastChangedTime}get xrMesh(){return this._xrMesh}get label(){return this._xrMesh.semanticLabel||""}get vertices(){return this._xrMesh.vertices}get indices(){return this._xrMesh.indices}destroy(){this._xrMesh&&(this._xrMesh=null,this.fire("remove"))}update(e){let s=this._meshDetection._manager,i=e.getPose(this._xrMesh.meshSpace,s._referenceSpace);i&&(this._position.copy(i.transform.position),this._rotation.copy(i.transform.orientation)),this._lastChanged!==this._xrMesh.lastChangedTime&&(this._lastChanged=this._xrMesh.lastChangedTime,this.fire("change"))}getPosition(){return this._position}getRotation(){return this._rotation}};n(q_,"EVENT_REMOVE","remove"),n(q_,"EVENT_CHANGE","change");var ln=class extends J{constructor(e){super();n(this,"_manager");n(this,"_supported",ue.browser&&!!window.XRMesh);n(this,"_available",!1);n(this,"_index",new Map);n(this,"_list",[]);this._manager=e,this._supported&&(this._manager.on("start",this._onSessionStart,this),this._manager.on("end",this._onSessionEnd,this))}update(e){if(!this._available)if(!this._manager.session.enabledFeatures&&e.detectedMeshes.size)this._available=!0,this.fire("available");else return;for(let s of e.detectedMeshes){let i=this._index.get(s);i?i.update(e):(i=new q_(this,s),this._index.set(s,i),this._list.push(i),i.update(e),this.fire("add",i))}for(let s of this._index.values())e.detectedMeshes.has(s.xrMesh)||this._removeMesh(s)}_removeMesh(e){this._index.delete(e.xrMesh),this._list.splice(this._list.indexOf(e),1),e.destroy(),this.fire("remove",e)}_onSessionStart(){if(this._manager.session.enabledFeatures){let e=this._manager.session.enabledFeatures.indexOf("mesh-detection")!==-1;if(!e)return;this._available=e,this.fire("available")}}_onSessionEnd(){if(this._available){this._available=!1;for(let e of this._index.values())this._removeMesh(e);this.fire("unavailable")}}get supported(){return this._supported}get available(){return this._available}get meshes(){return this._list}};n(ln,"EVENT_AVAILABLE","available"),n(ln,"EVENT_UNAVAILABLE","unavailable"),n(ln,"EVENT_ADD","add"),n(ln,"EVENT_REMOVE","remove");var zu=class extends J{constructor(e,s,i){super();n(this,"_manager");n(this,"_xrView");n(this,"_positionData",new Float32Array(3));n(this,"_viewport",new Q);n(this,"_projMat",new W);n(this,"_projViewOffMat",new W);n(this,"_viewMat",new W);n(this,"_viewOffMat",new W);n(this,"_viewMat3",new Ws);n(this,"_viewInvMat",new W);n(this,"_viewInvOffMat",new W);n(this,"_xrCamera",null);n(this,"_textureColor",null);n(this,"_textureDepth",null);n(this,"_depthInfo",null);n(this,"_emptyDepthBuffer",new Uint8Array(32));n(this,"_depthMatrix",new W);this._manager=e,this._xrView=s;let r=this._manager.app.graphicsDevice;if(this._manager.views.supportedColor&&(this._xrCamera=this._xrView.camera,this._manager.views.availableColor&&this._xrCamera&&(this._textureColor=new Z(r,{format:Ss,mipmaps:!1,addressU:1,addressV:1,minFilter:1,magFilter:1,width:this._xrCamera.width,height:this._xrCamera.height,name:`XrView-${this._xrView.eye}-Color`}))),this._manager.views.supportedDepth&&this._manager.views.availableDepth){let a=this._manager.views.depthGpuOptimized?0:1;this._textureDepth=new Z(r,{format:this._manager.views.depthPixelFormat,arrayLength:i===1?0:i,mipmaps:!1,addressU:1,addressV:1,minFilter:a,magFilter:a,width:4,height:4,name:`XrView-${this._xrView.eye}-Depth`});for(let o=0;o<this._textureDepth._levels.length;o++)this._textureDepth._levels[o]=this._emptyDepthBuffer;this._textureDepth.upload()}(this._textureColor||this._textureDepth)&&r.on("devicelost",this._onDeviceLost,this)}get textureColor(){return this._textureColor}get textureDepth(){return this._textureDepth}get depthUvMatrix(){return this._depthMatrix}get depthValueToMeters(){return this._depthInfo?.rawValueToMeters||0}get eye(){return this._xrView.eye}get viewport(){return this._viewport}get projMat(){return this._projMat}get projViewOffMat(){return this._projViewOffMat}get viewOffMat(){return this._viewOffMat}get viewInvOffMat(){return this._viewInvOffMat}get viewMat3(){return this._viewMat3}get positionData(){return this._positionData}update(e,s){this._xrView=s,this._manager.views.availableColor&&(this._xrCamera=this._xrView.camera);let i=this._manager.xrBridge.getViewport(e,this._xrView);this._viewport.x=i.x,this._viewport.y=i.y,this._viewport.z=i.width,this._viewport.w=i.height,this._projMat.set(this._xrView.projectionMatrix),this._viewMat.set(this._xrView.transform.inverse.matrix),this._viewInvMat.set(this._xrView.transform.matrix),this._updateTextureColor(),this._updateDepth(e)}_updateTextureColor(){!this._manager.views.availableColor||!this._xrCamera||!this._textureColor||this._manager.xrBridge?.syncCameraColorTexture(this._xrCamera,this._textureColor)}_updateDepth(e){if(!this._manager.views.availableDepth||!this._textureDepth)return;let s=this._manager.views.depthGpuOptimized,i=s?this._manager.graphicsBinding:e;if(!i){this._depthInfo=null;return}let r=i.getDepthInformation(this._xrView);if(!r){this._depthInfo=null;return}let a=!this._depthInfo!=!r;this._depthInfo=r;let o=this._depthInfo?.width||4,l=this._depthInfo?.height||4,h=!1;(this._textureDepth.width!==o||this._textureDepth.height!==l)&&(this._textureDepth._width=o,this._textureDepth._height=l,a=!0,h=!0),a&&(this._depthInfo?this._depthMatrix.data.set(this._depthInfo.normDepthBufferFromNormView.matrix):this._depthMatrix.setIdentity()),this._depthInfo?s?this._manager.xrBridge?.syncCameraDepthTexture(this._depthInfo,this._textureDepth,this._manager.views.depthPixelFormat??Mt):(this._textureDepth._levels[0]=new Uint8Array(this._depthInfo.data),this._textureDepth.upload()):(this._textureDepth._levels[0]=this._emptyDepthBuffer,this._textureDepth.upload()),h&&this.fire("depth:resize",o,l)}updateTransforms(e){e?(this._viewInvOffMat.mul2(e,this._viewInvMat),this.viewOffMat.copy(this._viewInvOffMat).invert()):(this._viewInvOffMat.copy(this._viewInvMat),this.viewOffMat.copy(this._viewMat)),this._viewMat3.setFromMat4(this._viewOffMat),this._projViewOffMat.mul2(this._projMat,this._viewOffMat),this._positionData[0]=this._viewInvOffMat.data[12],this._positionData[1]=this._viewInvOffMat.data[13],this._positionData[2]=this._viewInvOffMat.data[14]}_onDeviceLost(){this._depthInfo=null}getDepth(e,s){return this._manager.views.depthGpuOptimized?null:this._depthInfo?.getDepthInMeters(e,s)??null}destroy(){this._depthInfo=null,this._textureColor&&(this._textureColor.destroy(),this._textureColor=null),this._textureDepth&&(this._textureDepth.destroy(),this._textureDepth=null)}};n(zu,"EVENT_DEPTHRESIZE","depth:resize");var Rh=class extends J{constructor(e){super();n(this,"_manager");n(this,"_index",new Map);n(this,"_indexTmp",new Map);n(this,"_list",[]);n(this,"_supportedColor",!1);n(this,"_supportedDepth",ue.browser&&!!window.XRDepthInformation);n(this,"_availableColor",!1);n(this,"_availableDepth",!1);n(this,"_depthUsage","");n(this,"_depthFormat","");n(this,"_depthFormats",{[nx]:vo,[lx]:Ys,[cx]:Mt});this._manager=e;let s=e.app?.graphicsDevice;ue.browser&&window.XRCamera&&(s?.isWebGL2&&window.XRWebGLBinding?this._supportedColor=!0:s?.isWebGPU&&window.XRGPUBinding&&(this._supportedColor=!0)),this._manager.on("start",this._onSessionStart,this),this._manager.on("end",this._onSessionEnd,this)}get list(){return this._list}get supportedColor(){return this._supportedColor}get supportedDepth(){return this._supportedDepth}get availableColor(){return this._availableColor}get availableDepth(){return this._availableDepth}get depthUsage(){return this._depthUsage}get depthGpuOptimized(){return this._depthUsage===ox}get depthFormat(){return this._depthFormat}get depthPixelFormat(){return this._depthFormats[this._depthFormat]??null}update(e,s){for(let i=0;i<s.length;i++)this._indexTmp.set(s[i].eye,s[i]);for(let[i,r]of this._indexTmp){let a=this._index.get(i);a?a.update(e,r):(a=new zu(this._manager,r,s.length),this._index.set(i,a),this._list.push(a),a.update(e,r),this.fire("add",a))}for(let[i,r]of this._index){if(this._indexTmp.has(i))continue;r.destroy(),this._index.delete(i);let a=this._list.indexOf(r);a!==-1&&this._list.splice(a,1),this.fire("remove",r)}this._indexTmp.clear()}get(e){return this._index.get(e)||null}_onSessionStart(){if(this._manager.type===bl&&this._manager.session.enabledFeatures&&(this._availableColor=this._manager.session.enabledFeatures.indexOf("camera-access")!==-1,this._availableDepth=this._manager.session.enabledFeatures.indexOf("depth-sensing")!==-1,this._availableDepth)){let e=this._manager.session;this._depthUsage=e.depthUsage,this._depthFormat=e.depthDataFormat}}_onSessionEnd(){for(let e of this._index.values())e.destroy();this._index.clear(),this._availableColor=!1,this._availableDepth=!1,this._depthUsage="",this._depthFormat="",this._list.length=0}};n(Rh,"EVENT_ADD","add"),n(Rh,"EVENT_REMOVE","remove");var pA=class{constructor(t,e){n(this,"device");n(this,"eventHandler");n(this,"impl");n(this,"_evtDeviceLost",null);n(this,"_evtDeviceRestored",null);n(this,"_session",null);n(this,"_framebufferScaleFactor",1);n(this,"_onBindingError");this.device=t,this.eventHandler=e,this.impl=t.createXrBridgeImpl(this),this._evtDeviceLost=t.on("devicelost",this._onDeviceLost,this),this._evtDeviceRestored=t.on("devicerestored",this._onDeviceRestored,this)}destroy(){let t=this.device;t&&(this._evtDeviceLost?.off(),this._evtDeviceLost=null,this._evtDeviceRestored?.off(),this._evtDeviceRestored=null,this.impl.endFrame(),this.impl.destroy(t),this.impl=null,this._session=null,this._framebufferScaleFactor=1,this._onBindingError=void 0,this.device=null,this.eventHandler=null)}_onDeviceLost(){this.impl.onGraphicsDeviceLost()}_onDeviceRestored(){this.impl.onGraphicsDeviceRestored()}attachPresentation(t,e){this._session=t,this._framebufferScaleFactor=e.framebufferScaleFactor,this._onBindingError=e.onBindingError,this.impl.attachPresentation(t,e)}releasePresentation(){this.impl.releasePresentation()}beginFrame(t,e){this.impl.beginFrame(t,e)}endFrame(){this.impl.endFrame()}getFramebufferSize(t,e){this.impl.getFramebufferSize(t,e)}getViewport(t,e){return this.impl.getViewport(t,e)}syncCameraColorTexture(t,e){this.impl?.syncCameraColorTexture?.(t,e)}syncCameraDepthTexture(t,e,s){this.impl?.syncCameraDepthTexture?.(t,e,s)}get presentationLayer(){return this.impl.presentationLayer??null}get graphicsBinding(){return this.impl.graphicsBinding??null}};var no=class extends J{constructor(e){super();n(this,"app");n(this,"_supported",ue.browser&&!!navigator.xr);n(this,"_available",{});n(this,"_type",null);n(this,"_spaceType",null);n(this,"_session",null);n(this,"xrBridge",null);n(this,"_referenceSpace",null);n(this,"domOverlay");n(this,"hitTest");n(this,"imageTracking");n(this,"planeDetection");n(this,"meshDetection");n(this,"input");n(this,"lightEstimation");n(this,"views");n(this,"anchors");n(this,"_camera",null);n(this,"_localPosition",new x);n(this,"_localRotation",new $);n(this,"_depthNear",.1);n(this,"_depthFar",1e3);n(this,"_supportedFrameRates",null);n(this,"_width",0);n(this,"_height",0);n(this,"_framebufferSize",new B);n(this,"_framebufferScaleFactor",1);this.app=e,this._available[yb]=!1,this._available[Eb]=!1,this._available[bl]=!1,this.domOverlay=new Y_(this),this.hitTest=new _a(this),this.imageTracking=new Bu(this),this.planeDetection=new on(this),this.meshDetection=new ln(this),this.input=new lr(this),this.lightEstimation=new wh(this),this.anchors=new oo(this),this.views=new Rh(this),this._supported&&(navigator.xr.addEventListener("devicechange",()=>{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;s<e.length;s++)if(e[s]!==this.chars[s]){this._renderAtlas(e);return}}updateTextures(t){let e=this._normalizeCharsSet(t),s=[];for(let i=0;i<e.length;i++){let r=e[i];this.data.chars[r]||s.push(r)}s.length>0&&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;E<u.length;E++){let y=u[E];m[y]=this._getTextMetrics(y),d=Math.max(d,m[y].height),p=Math.max(p,m[y].descent)}this.glyphSize=Math.max(this.glyphSize,d);let _=this.glyphSize+this.padding*2,S=this.glyphSize+this.padding*2,g=this.glyphSize/2+this.padding,T=S-p-this.padding,C=0,v=0;for(let E=0;E<u.length;E++){let y=u[E],P=Nr.getCodePoint(u[E]),A=this.fontSize;f.ctx.font=`${this.fontWeight} ${A.toString()}px ${this.fontName}`,f.ctx.textAlign=o,f.ctx.textBaseline=l;let w=f.ctx.measureText(y).width;w>A&&(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.length<u+1&&t.info.maps.push({width:d,height:p});let m=this.fontSize/32;t.chars[e]={id:s,letter:e,x:i,y:r,width:a,height:o,xadvance:f/m,xoffset:l/m,yoffset:(h+this.padding)/m,scale:m,range:1,map:u,bounds:[0,0,a/m,o/m]}}_normalizeCharsSet(t){let e=this.app.systems.element.getUnicodeConverter();e&&(t=e(t));let s={},i=Nr.getSymbols(t);for(let a=0;a<i.length;a++){let o=i[a];s[o]||(s[o]=o)}return Object.keys(s).sort()}_getTextMetrics(t){let e=document.createElement("span");e.id="content-span",e.innerHTML=t;let s=document.createElement("div");s.id="content-block",s.style.display="inline-block",s.style.width="1px",s.style.height="0px";let i=document.createElement("div");i.appendChild(e),i.appendChild(s),i.style.font=`${this.fontSize}px ${this.fontName}`,document.body.appendChild(i);let a=-1,o=-1,l=-1;try{s.style["vertical-align"]="baseline",a=s.offsetTop-e.offsetTop,s.style["vertical-align"]="bottom",l=s.offsetTop-e.offsetTop,o=l-a}finally{document.body.removeChild(i)}return{ascent:a,descent:o,height:l}}get textures(){return this.atlases.map(t=>t.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;f<r.length;f++){let u=r[f];if(!(i&&i.indexOf(u)<0)&&!(!u.enabled||!a[f])&&u.camerasSet.has(e.camera)&&(this._qualifiedLayerIndices.push(f),o)){let d=o.prepareForPicking(e.camera,l,h,u);d&&this._pickMeshInstances.set(f,d)}}}execute(){let e=this.device,{renderer:s,camera:i,scene:r,mapping:a,renderTarget:o}=this,l=r.layers.layerList,h=r.layers.subLayerList;for(let f of this._qualifiedLayerIndices){let u=l[f],d=h[f];u._clearDepthBuffer&&s.clear(i.camera,!1,!0,!1);let p=u.meshInstances;for(let _=0;_<p.length;_++){let S=p[_];S.pick&&S.transparent===d&&(hx.push(S),a.set(S.id,S))}let m=this._pickMeshInstances.get(f);if(m&&hx.push(m),r.gsplat.enableIds){let _=u.gsplatPlacements;for(let S=0;S<_.length;S++){let g=_[S],T=g.node?.gsplat;T&&a.set(g.id,T)}}if(hx.length>0){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<i;r+=4){let a=t[r+0],o=t[r+1],l=t[r+2],f=(t[r+3]<<24|a<<16|o<<8|l)>>>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<o;l++){if(e[t.changedTouches[l].identifier]){a++;continue}let h=Pf(t.changedTouches[l]),f=this._getTargetElementByCoords(r,h.x,h.y);f&&(a++,e[t.changedTouches[l].identifier]={element:f,camera:r,x:h.x,y:h.y})}if(a===o)break}return e}_handleTouchStart(t){if(!this._enabled)return;let e=this._determineTouchedElements(t);for(let s=0,i=t.changedTouches.length;s<i;s++){let r=t.changedTouches[s],a=e[r.identifier],o=this._touchedElements[r.identifier];a&&(!o||a.element!==o.element)&&(this._fireEvent(t.type,new Ml(t,a.element,a.camera,a.x,a.y,r)),this._touchesForWhichTouchLeaveHasFired[r.identifier]=!1)}for(let s in e)this._touchedElements[s]=e[s]}_handleTouchEnd(t){if(!this._enabled)return;let e=this.app.systems.camera.cameras;for(let s in this._clickedEntities)delete this._clickedEntities[s];for(let s=0,i=t.changedTouches.length;s<i;s++){let r=t.changedTouches[s],a=this._touchedElements[r.identifier];if(!a)continue;let o=a.element,l=a.camera,h=a.x,f=a.y;delete this._touchedElements[r.identifier],delete this._touchesForWhichTouchLeaveHasFired[r.identifier];let u=Pf(r);for(let d=e.length-1;d>=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<i;s++){let r=t.changedTouches[s],a=e[r.identifier],o=this._touchedElements[r.identifier];if(o){let l=Pf(r);(!a||a.element!==o.element)&&!this._touchesForWhichTouchLeaveHasFired[r.identifier]&&(this._fireEvent("touchleave",new Ml(t,o.element,o.camera,l.x,l.y,r)),this._touchesForWhichTouchLeaveHasFired[r.identifier]=!0),this._fireEvent("touchmove",new Ml(t,o.element,o.camera,l.x,l.y,r))}}}_onElementMouseEvent(t,e){let s=null,i=this._hoveredElement;this._hoveredElement=null;let r=this.app.systems.camera.cameras,a;for(let o=r.length-1;o>=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<t.length;e++)this._onElementSelectEvent("selectmove",t[e],null)}_onXrInputRemove(t){let e=this._selectedElements[t.id];e&&(t._elementEntity=null,this._fireEvent("selectleave",new ga(null,e,null,t))),delete this._selectedElements[t.id],delete this._selectedPressedElements[t.id]}_onSelectStart(t,e){this._enabled&&this._onElementSelectEvent("selectstart",t,e)}_onSelectEnd(t,e){this._enabled&&this._onElementSelectEvent("selectend",t,e)}_onElementSelectEvent(t,e,s){let i,r=this._selectedElements[e.id],a,o=this.app.systems.camera.cameras,l;if(e.elementInput){Mb.set(e.getOrigin(),e.getDirection());for(let f=o.length-1;f>=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;a<o;a++){let l=this._elements[a];if(l.layers.some(h=>t.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<r&&(i=l,r=h),l.screen)){i=l;break}}}return i}_calculateRayScreen(t,e,s,i){let r=this.app.graphicsDevice.width,a=this.app.graphicsDevice.height,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*r/this._target.clientWidth,m=e*a/this._target.clientHeight;return p>=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._frameIndex<this._frameTimings.length&&this._frameTimings.splice(this._frameIndex);let e=this._prevTimings;this._prevTimings=this._timings,this._timings=this._frameTimings,this._frameTimings=e,this._frameIndex=0,this.mark(t)}mark(t){if(!this.enabled)return;let e=Tt();if(this._frameIndex>0){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;l<this.statNames.length;l++){let h=a(this.statNames[l],this.app.stats);this.values[l]=(h??0)*this.multiplier}})}get timings(){return this.values}};var Lh=class{constructor(t,e,s,i,r){this.app=e,this.name=t,this.device=e.graphicsDevice,this.timer=r,this.watermark=s,this.enabled=!1,this.textRefreshRate=i,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=!1,this.counter=0,this.app.on("frameupdate",this.update,this)}destroy(){this.app.off("frameupdate",this.update,this)}loseContext(){this.timer&&typeof this.timer.loseContext=="function"&&this.timer.loseContext()}update(t){let s=this.timer.timings.reduce((i,r)=>i+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<d.length;p+=4){let m=Math.max(d[p+0],d[p+1],d[p+2]);d[p+3]=Math.min(m*2,255)}this.texture=new Z(t,{name:"mini-stats-word-atlas",width:r.width,height:r.height,mipmaps:!1,minFilter:0,magFilter:0,levels:[d]})}destroy(){this.texture.destroy(),this.texture=null}render(t,e,s,i){let r=this.placements.get(e);if(r)return t.quad(s+r.l-1,i-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 o=0;o<e.length;o++){let l=e[o];if(l===" "){a+=5;continue}let h=this.placements.get(l);h&&(t.quad(s+a+h.l-1,i-h.d+1,h.w+2,h.h+2,h.x-1,this.texture.height-h.y-h.h-1,void 0,void 0,this.texture,1),a+=h.w)}return a}};var QG="1.0, 0.412, 0.380",JG="0.467, 0.867, 0.467",eV="0.424, 0.627, 0.863",tV="0.0, 0.0, 0.0",sV="0.15, 0.15, 0.0",iV="0.15, 0.0, 0.1",Q$=`
attribute vec3 vertex_position;
attribute vec4 vertex_texCoord0;
varying vec4 uv0;
varying float wordFlag;
void main(void) {
gl_Position = vec4(vertex_position.xy * 2.0 - 1.0, 0.5, 1.0);
uv0 = vertex_texCoord0;
wordFlag = vertex_position.z;
}
`,J$=`
attribute vertex_position: vec3f;
attribute vertex_texCoord0: vec4f;
varying uv0: vec4f;
varying wordFlag: f32;
@vertex fn vertexMain(input : VertexInput) -> VertexOutput {
var output : VertexOutput;
output.position = vec4(input.vertex_position.xy * 2.0 - 1.0, 0.5, 1.0);
output.uv0 = input.vertex_texCoord0;
output.wordFlag = input.vertex_position.z;
return output;
}
`,e9=`
varying vec4 uv0;
varying float wordFlag;
uniform vec4 clr;
uniform sampler2D graphTex;
uniform sampler2D wordsTex;
void main (void) {
vec3 graphColor = vec3(${QG});
if (wordFlag > 0.5) {
graphColor = vec3(${eV});
} else if (wordFlag > 0.2) {
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(${tV});
if (wordFlag > 0.5) {
bgColor = vec3(${iV});
} else if (wordFlag > 0.2) {
bgColor = vec3(${sV});
}
graph = vec4(bgColor, 1.0);
}
vec4 words = texture2D(wordsTex, vec2(uv0.x, 1.0 - uv0.y));
if (wordFlag > 0.99) {
gl_FragColor = words * clr;
} else {
gl_FragColor = graph * clr;
}
}
`,t9=`
varying uv0: vec4f;
varying wordFlag: f32;
uniform clr: vec4f;
var graphTex : texture_2d<f32>;
var graphTex_sampler : sampler;
var wordsTex : texture_2d<f32>;
var wordsTex_sampler : sampler;
@fragment fn fragmentMain(input : FragmentInput) -> FragmentOutput {
var uv0: vec4f = input.uv0;
var graphColor: vec3f = vec3f(${QG});
if (input.wordFlag > 0.5) {
graphColor = vec3f(${eV});
} else if (input.wordFlag > 0.2) {
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(${tV});
if (input.wordFlag > 0.5) {
bgColor = vec3f(${iV});
} else if (input.wordFlag > 0.2) {
bgColor = vec3f(${sV});
}
graph = vec4f(bgColor, 1.0);
}
var words: vec4f = textureSample(wordsTex, wordsTex_sampler, vec2f(uv0.x, 1.0 - uv0.y));
var output: FragmentOutput;
if (input.wordFlag > 0.99) {
output.color = words * uniform.clr;
} else {
output.color = graph * uniform.clr;
}
return output;
}
`,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<e;++a)i[a*6+0]=a*4,i[a*6+1]=a*4+1,i[a*6+2]=a*4+2,i[a*6+3]=a*4,i[a*6+4]=a*4+2,i[a*6+5]=a*4+3;this.device=t,this.maxQuads=e,this.buffer=new ft(t,s,e*4,{usage:2}),this.data=new Float32Array(this.buffer.numBytes/4),this.indexBuffer=new os(t,1,e*6,0,i),this.prim={type:Yt,indexed:!0,base:0,baseVertex:0,count:0},this.quads=0,this.mesh=new _e(t),this.mesh.vertexBuffer=this.buffer,this.mesh.indexBuffer[0]=this.indexBuffer,this.mesh.primitive=[this.prim];let r=new ct({uniqueName:"MiniStats",vertexGLSL:Q$,fragmentGLSL:e9,vertexWGSL:J$,fragmentWGSL:t9,attributes:{vertex_position:ee,vertex_texCoord0:_t}});this.material=r,r.cull=0,r.depthState=Pt.NODEPTH,r.blendState=new Oe(!0,0,6,8,0,1,1),r.update(),this.meshInstance=new we(this.mesh,r,new Pe("MiniStatsMesh")),this.uniforms={clr:new Float32Array(4)},this.targetSize={width:t.width,height:t.height}}quad(t,e,s,i,r,a,o,l,h,f=0){if(this.quads>=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.sizes.length||a<this.sizes.length||o<this.sizes.length){let h=this.sizes[this.sizes.length-1].width;for(let f=1;f<this.sizes.length-1;f++)this.sizes[f].width=h}let l=document.createElement("div");l.setAttribute("id","mini-stats"),l.style.cssText="position:fixed;bottom:0;left:0;background:transparent;",document.body.appendChild(l),l.addEventListener("mouseenter",h=>{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<this.gpuTimingMinSize&&this.gpuPassGraphs&&this.clearSubGraphs(this.gpuPassGraphs,"GPU",.33),t<this.cpuTimingMinSize&&this.cpuGraphs&&this.clearSubGraphs(this.cpuGraphs,"CPU",.66),t<this.vramTimingMinSize&&this.vramGraphs&&this.clearSubGraphs(this.vramGraphs)}get activeSizeIndex(){return this._activeSizeIndex}set opacity(t){this.clr[3]=t}get opacity(){return this.clr[3]}get overallHeight(){let t=this.graphs,e=this.gspacing;return this.height*t.length+e*(t.length-1)}set enabled(t){if(t!==this._enabled){this._enabled=t;for(let e=0;e<this.graphs.length;++e)this.graphs[e].enabled=t,this.graphs[e].timer.enabled=t}}get enabled(){return this._enabled}initGraphs(t,e,s){if(this.graphs=[],s.stats&&s.stats.forEach(i=>{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;o<t.length;++o){let l=t[o],h=o*(r+a);l.render(s,0,h,i,r);let f=1;h+=r-13,f+=e.render(s,l.name,f,h)+10;let u=l.timingText;for(let d=0;d<u.length;++d)f+=e.render(s,u[d],f,h);if(l.maxText&&this._activeSizeIndex>0){f+=5,f+=e.render(s,"max",f,h),f+=5;let d=l.maxText;for(let p=0;p<d.length;++p)f+=e.render(s,d[p],f,h)}l.timer.unitsName&&(f+=e.render(s,l.timer.unitsName,f,h))}s.render(this.app,this.drawLayer,this.texture,this.wordAtlas.texture,this.clr,r)}resize(t,e,s){let i=this.graphs;for(let r=0;r<i.length;++r)i[r].enabled=s;this.width=t,this.height=e,this.updateDiv()}updateDiv(){let t=this.device.canvas.getBoundingClientRect();this.div.style.left=`${t.left}px`,this.div.style.bottom=`${window.innerHeight-t.bottom}px`,this.div.style.width=`${this.width}px`,this.div.style.height=`${this.overallHeight}px`}loseContext(){this.graphs.forEach(t=>t.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;
uniform sampler2D source;
void main(void)
{
vec4 pixel;
vec4 texel = texture2D(source, vUv0);
vec4 firstTexel = texel;
float diff = texel.a * uSrcMultiplier;
pixel = texture2D(source, vUv0 + uOffset * -2.0);
texel = max(texel, pixel);
diff = max(diff, length(firstTexel.rgb - pixel.rgb));
pixel = texture2D(source, vUv0 + uOffset * -1.0);
texel = max(texel, pixel);
diff = max(diff, length(firstTexel.rgb - pixel.rgb));
pixel = texture2D(source, vUv0 + uOffset * 1.0);
texel = max(texel, pixel);
diff = max(diff, length(firstTexel.rgb - pixel.rgb));
pixel = texture2D(source, vUv0 + uOffset * 2.0);
texel = max(texel, pixel);
diff = max(diff, length(firstTexel.rgb - pixel.rgb));
gl_FragColor = vec4(texel.rgb, min(diff, 1.0));
}
`,a9=`
varying vUv0: vec2f;
uniform uOffset: vec2f;
uniform uSrcMultiplier: f32;
var source: texture_2d<f32>;
var sourceSampler: sampler;
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
var pixel: vec4f;
var texel = textureSample(source, sourceSampler, input.vUv0);
let firstTexel = texel;
var diff = texel.a * uniform.uSrcMultiplier;
pixel = textureSample(source, sourceSampler, input.vUv0 + uniform.uOffset * -2.0);
texel = max(texel, pixel);
diff = max(diff, length(firstTexel.rgb - pixel.rgb));
pixel = textureSample(source, sourceSampler, input.vUv0 + uniform.uOffset * -1.0);
texel = max(texel, pixel);
diff = max(diff, length(firstTexel.rgb - pixel.rgb));
pixel = textureSample(source, sourceSampler, input.vUv0 + uniform.uOffset * 1.0);
texel = max(texel, pixel);
diff = max(diff, length(firstTexel.rgb - pixel.rgb));
pixel = textureSample(source, sourceSampler, input.vUv0 + uniform.uOffset * 2.0);
texel = max(texel, pixel);
diff = max(diff, length(firstTexel.rgb - pixel.rgb));
output.color = vec4f(texel.rgb, min(diff, 1.0));
return output;
}
`,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<<this.outlineShaderPass),r.setParameter("texture_emissiveMap",this.whiteTex,1<<this.outlineShaderPass)}}),this.renderingLayer.addMeshInstances(i,!0)}removeEntity(t,e=!0){let s=this.getMeshInstances(t,e);this.renderingLayer.removeMeshInstances(s),s.forEach(i=>{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<C.length;v+=4)C[v+0]=C[v+0]*_,C[v+1]=C[v+1]*S,C[v+2]=C[v+2]*g;m.putImageData(T,0,0)}return Promise.resolve(p)}let i=t.device,{width:r,height:a}=this.calcTextureSize(t.width,t.height,e.maxTextureSize),o=En(t.format)?ce:t.format,l=new Z(i,{name:"ExtractedTexture",width:r,height:a,format:o,cubemap:!1,mipmaps:!1,minFilter:1,magFilter:1,addressU:1,addressV:1}),h=new me({colorBuffer:l,depth:!1}),f=Se.createShader(i,{uniqueName:"ShaderCoreExporterBlit",attributes:{vertex_position:ee},vertexChunk:"fullscreenQuadVS",fragmentChunk:"outputTex2DPS"});return i.scope.resolve("source").setValue(t),i.setBlendState(Oe.NOBLEND),Qt(i,h,f),l.read(0,0,r,a,{renderTarget:h,immediate:!0}).then(u=>{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<<c[s-1];for(var i=new kb(e[30]),s=1;s<30;++s)for(var r=e[s];r<e[s+1];++r)i[r]=r-e[s]<<5|s;return{b:e,r:i}},fV=hV(zb,2),o9=fV.b,Fb=fV.r;o9[28]=258,Fb[258]=28;var uV=hV(Gb,0),Uct=uV.b,aV=uV.r,Nb=new Or(32768);for(ht=0;ht<32768;++ht)Fl=(ht&43690)>>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<s;++i)c[i]&&++r[c[i]-1];var a=new Or(t);for(i=1;i<t;++i)a[i]=a[i-1]+r[i-1]<<1;var o;if(e){o=new Or(1<<t);var l=15-t;for(i=0;i<s;++i)if(c[i])for(var h=i<<4|c[i],f=t-c[i],u=a[c[i]-1]++<<f,d=u|(1<<f)-1;u<=d;++u)o[Nb[u]>>l]=h}else for(o=new Or(s),i=0;i<s;++i)c[i]&&(o[i]=Nb[a[c[i]-1]++]>>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;s<c.length;++s)c[s]&&e.push({s,f:c[s]});var i=e.length,r=e.slice();if(!i)return{t:_V,l:0};if(i==1){var a=new wi(e[0].s+1);return a[e[0].s]=1,{t:a,l:1}}e.sort(function(E,y){return E.f-y.f}),e.push({s:-1,f:25001});var o=e[0],l=e[1],h=0,f=1,u=2;for(e[0]={s:-1,f:o.f+l.f,l:o,r:l};f!=i-1;)o=e[e[h].f<e[u].f?h++:u++],l=e[h!=f&&e[h].f<e[u].f?h++:u++],e[f++]={s:-1,f:o.f+l.f,l:o,r:l};for(var d=r[0].s,s=1;s<i;++s)r[s].s>d&&(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<<S;for(r.sort(function(y,P){return p[P.s]-p[y.s]||y.f-P.f});s<i;++s){var T=r[s].s;if(p[T]>t)_+=g-(1<<m-p[T]),p[T]=t;else break}for(_>>=S;_>0;){var C=r[s].s;p[C]<t?_-=1<<t-p[C]++-1:++s}for(;s>=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<t.length;++s)e+=c[s]*t[s];return e},mV=function(c,t,e){var s=e.length,i=dV(t+2);c[i]=s&255,c[i+1]=s>>8,c[i+2]=c[i]^255,c[i+3]=c[i+1]^255;for(var r=0;r<s;++r)c[i+r+4]=e[r];return(i+4+s)*8},nV=function(c,t,e,s,i,r,a,o,l,h,f){Nl(t,f++,e),++i[256];for(var u=Ob(i,15),d=u.t,p=u.l,m=Ob(r,15),_=m.t,S=m.l,g=oV(d),T=g.c,C=g.n,v=oV(_),E=v.c,y=v.n,P=new Or(19),A=0;A<T.length;++A)++P[T[A]&31];for(var A=0;A<E.length;++A)++P[E[A]&31];for(var w=Ob(P,7),I=w.t,D=w.l,O=19;O>4&&!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+(H<M)),f+=2,H<M){U=gx(d,p,0),L=d,b=gx(_,S,0),N=_;var k=gx(I,D,0);Nl(t,f,C-257),Nl(t,f+5,y-1),Nl(t,f+10,O-4),f+=14;for(var A=0;A<O;++A)Nl(t,f+3*A,I[rV[A]]);f+=3*O;for(var z=[T,E],V=0;V<2;++V)for(var q=z[V],A=0;A<q.length;++A){var re=q[A]&31;Nl(t,f,k[re]),f+=I[re],re>15&&(Nl(t,f,q[A]>>5&127),f+=q[A]>>12)}}else U=n9,L=Vu,b=l9,N=FA;for(var A=0;A<o;++A){var te=s[A];if(te>255){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<<e)-1,_=r.p||new Or(32768),S=r.h||new Or(m+1),g=Math.ceil(e/3),T=2*g,C=function(ds){return(c[ds]^c[ds+1]<<g^c[ds+2]<<T)&m},v=new kb(25e3),E=new Or(288),y=new Or(32),P=0,A=0,w=r.i||0,I=0,D=r.w||0,O=0;w+2<a;++w){var G=C(w),M=w&32767,H=S[G];if(_[M]=H,S[G]=M,D<=w){var U=a-w;if((P>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;te<re&&c[w+te]==c[w+te-z];++te);if(te>b){if(b=te,N=z,te>V)break;for(var j=Math.min(z,te-2),oe=0,L=0;L<j;++L){var be=w-z+L&32767,qe=_[be],ot=be-qe&32767;ot>oe&&(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;++w)v[I++]=c[w],++E[c[w]];f=nV(c,l,h,v,E,y,A,I,O,w-O,f),h||(r.r=f&7|l[f/8|0]<<3,f-=7,r.h=S,r.p=_,r.i=w,r.w=D)}else{for(var w=r.w||0;w<a+h;w+=65535){var Vs=w+65535;Vs>=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<t.length;++s)e=u9[e&255^t[s]]^e>>>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<c.length;++s)e[s]=c.charCodeAt(s);return e}if(lV)return lV.encode(c);for(var i=c.length,r=new wi(c.length+(c.length>>1)),a=0,o=function(f){r[a++]=f},s=0;s<i;++s){if(a+5>r.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<s.length;++P){var u=s[P];cV(v,u.o,u,u.f,u.u,u.c.length);var A=30+u.f.length+Ub(u.extra);v.set(u.c,u.o+A),cV(v,i,u,u.f,u.u,u.c.length,u.o,u.m),i+=16+A+(u.m?u.m.length:0)}return S9(v,i,s.length,y,E),v}var vV="root",x9=`#usda 1.0
(
customLayerData = {
string creator = "PlayCanvas UsdzExporter"
}
metersPerUnit = 1
upAxis = "Y"
)
`,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<o.length;f++){let d="image/png",p=o[f],m=this.textureToCanvas(p,a).then(_=>_?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}@</${i}>`;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;r+=2)s.push(`(${e[r]}, ${1-e[r+1]})`);return s.join(", ")}buildArray3(e){let s=[],i=e.length;for(let r=0;r<i;r+=3)s.push(`(${e[r]}, ${e[r+1]}, ${e[r+2]})`);return s.join(", ")}buildMat4(e){let s=e.data,i=[];for(let r=0;r<16;r+=4)i.push(`(${s[r]}, ${s[r+1]}, ${s[r+2]}, ${s[r+3]})`);return`( ${i.join(", ")} )`}buildMaterial(e){let s=`Material_${e.id}`,i=`/Materials/${s}`,r=p=>`<${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<l;p++)i[p]=p;let f=s.length/3;r=r.length?r:Array(f*3).fill(0),a=a.length?a:Array(f*2).fill(0),o=o.length?o:Array(f*2).fill(0),s=this.buildArray3(s),r=this.buildArray3(r),a=this.buildArray2(a),o=this.buildArray2(o);let u=T9(h,i,r,s,a,o);return this.addFile("mesh",`Mesh_${e.id}`,"Mesh",u)}buildMeshInstance(e){let s=this.getMeshRef(e.mesh),i=this.getMaterialRef(e.material),r=this.buildMat4(e.node.getWorldTransform()),a=e.node.name.replace(/[^a-z0-9]/gi,"_"),o=a;for(;this.nodeNames.has(o);)o=`${a}_${Math.random().toString(36).slice(2,7)}`;return this.nodeNames.add(o),y9(o,s,r,i)}};var Vb=34962,yV=34963,E9=c=>{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.length;s+=4)if(e[s]<255)return!0;return!1}var PV=["anisotropyMap","aoMap","clearCoatGlossMap","clearCoatMap","clearCoatNormalMap","colorMap","diffuseMap","emissiveMap","iridescenceMap","iridescenceThicknessMap","metalnessMap","normalMap","refractionMap","sheenGlossMap","sheenMap","specularityFactorMap","specularMap","thicknessMap"],kA=class c extends sg{collectResources(t){let e={buffers:[],cameras:[],entities:[],materials:[],skins:[],textures:[],entityMeshInstances:[],bufferViewMap:new Map,compressableTexture:new Set},{materials:s,buffers:i,entityMeshInstances:r,textures:a}=e;t.forEach(l=>{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<s.inverseBindPose.length;f++){let u=s.inverseBindPose[f];i.set(u.data,f*16)}let r=i.buffer;c.writeBufferView(t,e,r),t.buffers.push(r);let o={bufferView:t.bufferViewMap.get(r)[0],componentType:EV(ye),count:s.inverseBindPose.length,type:"MAT4"},l=e.accessors.push(o)-1,h=s.boneNames.map(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<e.length;o++){let l=r[o],h=e[o],u=P9(h)||!t.compressableTexture.has(l)?"image/png":"image/jpeg";a.push(this.getBlob(h,u).then(d=>{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<s;r++)i[r]=e;return i.buffer}return t}buildJson(t,e){let s=this.convertTextures(t.textures,e);return Promise.all(s).then(async i=>{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;g<f;g++)_.setUint8(S+g,32);return S+=f,d>0&&(_.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;
#ifdef PREMULTIPLY
uniform sampler2D premultiplyTexture;
#endif
void main()
{
vec3 e = texture2D (sourceTexture, uv0).rgb;
#ifdef BOXFILTER
vec3 value = e;
#ifdef PREMULTIPLY
float premultiply = texture2D(premultiplyTexture, uv0).{PREMULTIPLY_SRC_CHANNEL};
value *= vec3(premultiply);
#endif
#else
float x = sourceInvResolution.x;
float y = sourceInvResolution.y;
vec3 a = texture2D(sourceTexture, vec2 (uv0.x - 2.0 * x, uv0.y + 2.0 * y)).rgb;
vec3 b = texture2D(sourceTexture, vec2 (uv0.x, uv0.y + 2.0 * y)).rgb;
vec3 c = texture2D(sourceTexture, vec2 (uv0.x + 2.0 * x, uv0.y + 2.0 * y)).rgb;
vec3 d = texture2D(sourceTexture, vec2 (uv0.x - 2.0 * x, uv0.y)).rgb;
vec3 f = texture2D(sourceTexture, vec2 (uv0.x + 2.0 * x, uv0.y)).rgb;
vec3 g = texture2D(sourceTexture, vec2 (uv0.x - 2.0 * x, uv0.y - 2.0 * y)).rgb;
vec3 h = texture2D(sourceTexture, vec2 (uv0.x, uv0.y - 2.0 * y)).rgb;
vec3 i = texture2D(sourceTexture, vec2 (uv0.x + 2.0 * x, uv0.y - 2.0 * y)).rgb;
vec3 j = texture2D(sourceTexture, vec2 (uv0.x - x, uv0.y + y)).rgb;
vec3 k = texture2D(sourceTexture, vec2 (uv0.x + x, uv0.y + y)).rgb;
vec3 l = texture2D(sourceTexture, vec2 (uv0.x - x, uv0.y - y)).rgb;
vec3 m = texture2D(sourceTexture, vec2 (uv0.x + x, uv0.y - y)).rgb;
vec3 value = e * 0.125;
value += (a + c + g + i) * 0.03125;
value += (b + d + f + h) * 0.0625;
value += (j + k + l + m) * 0.125;
#endif
#ifdef REMOVE_INVALID
value = max(value, vec3(0.0));
#endif
gl_FragColor = vec4(value, 1.0);
}
`;var IV=`
var sourceTexture: texture_2d<f32>;
var sourceTextureSampler: sampler;
uniform sourceInvResolution: vec2f;
varying uv0: vec2f;
#ifdef PREMULTIPLY
var premultiplyTexture: texture_2d<f32>;
var premultiplyTextureSampler: sampler;
#endif
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let e: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, input.uv0).rgb);
#ifdef BOXFILTER
var value: half3 = e;
#ifdef PREMULTIPLY
let premultiply: half = half(textureSample(premultiplyTexture, premultiplyTextureSampler, input.uv0).{PREMULTIPLY_SRC_CHANNEL});
value *= premultiply;
#endif
#else
let x: f32 = uniform.sourceInvResolution.x;
let y: f32 = uniform.sourceInvResolution.y;
let a: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x - 2.0 * x, input.uv0.y + 2.0 * y)).rgb);
let b: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x, input.uv0.y + 2.0 * y)).rgb);
let c: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x + 2.0 * x, input.uv0.y + 2.0 * y)).rgb);
let d: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x - 2.0 * x, input.uv0.y)).rgb);
let f: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x + 2.0 * x, input.uv0.y)).rgb);
let g: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x - 2.0 * x, input.uv0.y - 2.0 * y)).rgb);
let h: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x, input.uv0.y - 2.0 * y)).rgb);
let i: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x + 2.0 * x, input.uv0.y - 2.0 * y)).rgb);
let j: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x - x, input.uv0.y + y)).rgb);
let k: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x + x, input.uv0.y + y)).rgb);
let l: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x - x, input.uv0.y - y)).rgb);
let m: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x + x, input.uv0.y - y)).rgb);
var value: half3 = e * half(0.125);
value += (a + c + g + i) * half(0.03125);
value += (b + d + f + h) * half(0.0625);
value += (j + k + l + m) * half(0.125);
#endif
#ifdef REMOVE_INVALID
value = max(value, half3(0.0));
#endif
output.color = vec4f(vec3f(value), 1.0);
return output;
}
`;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;
void main()
{
float x = sourceInvResolution.x;
float y = sourceInvResolution.y;
vec3 a = texture2D (sourceTexture, vec2 (uv0.x - x, uv0.y + y)).rgb;
vec3 b = texture2D (sourceTexture, vec2 (uv0.x, uv0.y + y)).rgb;
vec3 c = texture2D (sourceTexture, vec2 (uv0.x + x, uv0.y + y)).rgb;
vec3 d = texture2D (sourceTexture, vec2 (uv0.x - x, uv0.y)).rgb;
vec3 e = texture2D (sourceTexture, vec2 (uv0.x, uv0.y)).rgb;
vec3 f = texture2D (sourceTexture, vec2 (uv0.x + x, uv0.y)).rgb;
vec3 g = texture2D (sourceTexture, vec2 (uv0.x - x, uv0.y - y)).rgb;
vec3 h = texture2D (sourceTexture, vec2 (uv0.x, uv0.y - y)).rgb;
vec3 i = texture2D (sourceTexture, vec2 (uv0.x + x, uv0.y - y)).rgb;
vec3 value = e * 0.25;
value += (b + d + f + h) * 0.125;
value += (a + c + g + i) * 0.0625;
gl_FragColor = vec4(value, 1.0);
}
`;var bV=`
var sourceTexture: texture_2d<f32>;
var sourceTextureSampler: sampler;
uniform sourceInvResolution: vec2f;
varying uv0: vec2f;
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let x: f32 = uniform.sourceInvResolution.x;
let y: f32 = uniform.sourceInvResolution.y;
let a: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x - x, input.uv0.y + y)).rgb);
let b: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x, input.uv0.y + y)).rgb);
let c: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x + x, input.uv0.y + y)).rgb);
let d: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x - x, input.uv0.y)).rgb);
let e: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x, input.uv0.y)).rgb);
let f: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x + x, input.uv0.y)).rgb);
let g: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x - x, input.uv0.y - y)).rgb);
let h: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x, input.uv0.y - y)).rgb);
let i: half3 = half3(textureSample(sourceTexture, sourceTextureSampler, vec2f(input.uv0.x + x, input.uv0.y - y)).rgb);
var value: half3 = e * half(0.25);
value += (b + d + f + h) * half(0.125);
value += (a + c + g + i) * half(0.0625);
output.color = vec4f(vec3f(value), 1.0);
return output;
}
`;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<this.renderTargets.length;s++){let i=this.renderTargets[s];i.destroyTextureBuffers(),i.destroy()}this.renderTargets.length=0}destroyRenderPasses(){for(let e=0;e<this.beforePasses.length;e++)this.beforePasses[e].destroy();this.beforePasses.length=0}createRenderTarget(e){return new me({depth:!1,colorBuffer:new Z(this.device,{name:`BloomTexture${e}`,width:1,height:1,format:this.textureFormat,mipmaps:!1,minFilter:1,magFilter:1,addressU:1,addressV:1})})}createRenderTargets(e){for(let s=0;s<e;s++){let i=s===0?this.bloomRenderTarget:this.createRenderTarget(s);this.renderTargets.push(i)}}calcMipLevels(e,s,i){let r=Math.min(e,s);return Math.floor(Math.log2(r)-Math.log2(i))}createRenderPasses(e){let s=this.device,i=this._sourceTexture;for(let r=0;r<e;r++){let a=new hn(s,i),o=this.renderTargets[r];a.init(o,{resizeSource:i,scaleX:.5,scaleY:.5}),a.setClearColor(F.BLACK),this.beforePasses.push(a),i=o.colorBuffer}i=this.renderTargets[e-1].colorBuffer;for(let r=e-2;r>=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;
uniform sampler2D sceneTexture;
uniform vec2 sceneTextureInvRes;
#include "composeBloomPS"
#include "composeDofPS"
#include "composeSsaoPS"
#include "composeGradingPS"
#include "composeColorEnhancePS"
#include "composeVignettePS"
#include "composeFringingPS"
#include "composeCasPS"
#include "composeColorLutPS"
#include "composeDeclarationsPS"
void main() {
#include "composeMainStartPS"
vec2 uv = uv0;
vec4 scene = texture2DLod(sceneTexture, uv, 0.0);
vec3 result = scene.rgb;
#ifdef CAS
result = applyCas(result, uv, sharpness);
#endif
#ifdef DOF
result = applyDof(result, uv0);
#endif
#ifdef SSAO_TEXTURE
result = applySsao(result, uv0);
#endif
#ifdef FRINGING
result = applyFringing(result, uv);
#endif
#ifdef BLOOM
result = applyBloom(result, uv0);
#endif
#ifdef COLOR_ENHANCE
result = applyColorEnhance(result);
#endif
#ifdef GRADING
result = applyGrading(result);
#endif
result = toneMap(max(vec3(0.0), result));
#ifdef COLOR_LUT
result = applyColorLUT(result);
#endif
#ifdef VIGNETTE
result = applyVignette(result, uv);
#endif
#include "composeMainEndPS"
#ifdef DEBUG_COMPOSE
#if DEBUG_COMPOSE == scene
result = scene.rgb;
#elif defined(BLOOM) && DEBUG_COMPOSE == bloom
result = dBloom * bloomIntensity;
#elif defined(DOF) && DEBUG_COMPOSE == dofcoc
result = vec3(dCoc, 0.0);
#elif defined(DOF) && DEBUG_COMPOSE == dofblur
result = dBlur;
#elif defined(SSAO_TEXTURE) && DEBUG_COMPOSE == ssao
result = vec3(dSsao);
#elif defined(VIGNETTE) && DEBUG_COMPOSE == vignette
result = vec3(dVignette);
#endif
#endif
result = gammaCorrectOutput(result);
gl_FragColor = vec4(result, scene.a);
}
`;var LV=`
#ifdef BLOOM
uniform sampler2D bloomTexture;
uniform float bloomIntensity;
vec3 dBloom;
vec3 applyBloom(vec3 color, vec2 uv) {
dBloom = texture2DLod(bloomTexture, uv, 0.0).rgb;
return color + dBloom * bloomIntensity;
}
#endif
`;var MV=`
#ifdef DOF
uniform sampler2D cocTexture;
uniform sampler2D blurTexture;
vec2 dCoc;
vec3 dBlur;
vec3 getDofBlur(vec2 uv) {
dCoc = texture2DLod(cocTexture, uv, 0.0).rg;
#if DOF_UPSCALE
vec2 blurTexelSize = 1.0 / vec2(textureSize(blurTexture, 0));
vec3 bilinearBlur = vec3(0.0);
float totalWeight = 0.0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
vec2 offset = vec2(i, j) * blurTexelSize;
vec2 cocSample = texture2DLod(cocTexture, uv + offset, 0.0).rg;
vec3 blurSample = texture2DLod(blurTexture, uv + offset, 0.0).rgb;
float cocWeight = clamp(cocSample.r + cocSample.g, 0.0, 1.0);
bilinearBlur += blurSample * cocWeight;
totalWeight += cocWeight;
}
}
if (totalWeight > 0.0) {
bilinearBlur /= totalWeight;
}
dBlur = bilinearBlur;
return bilinearBlur;
#else
dBlur = texture2DLod(blurTexture, uv, 0.0).rgb;
return dBlur;
#endif
}
vec3 applyDof(vec3 color, vec2 uv) {
vec3 blur = getDofBlur(uv);
return mix(color, blur, dCoc.r + dCoc.g);
}
#endif
`;var OV=`
#ifdef SSAO
#define SSAO_TEXTURE
#endif
#if DEBUG_COMPOSE == ssao
#define SSAO_TEXTURE
#endif
#ifdef SSAO_TEXTURE
uniform sampler2D ssaoTexture;
float dSsao;
vec3 applySsao(vec3 color, vec2 uv) {
dSsao = texture2DLod(ssaoTexture, uv, 0.0).r;
#ifdef SSAO
return color * dSsao;
#else
return color;
#endif
}
#endif
`;var FV=`
#ifdef GRADING
uniform vec3 brightnessContrastSaturation;
uniform vec3 tint;
vec3 colorGradingHDR(vec3 color, float brt, float sat, float con) {
color *= tint;
color = color * brt;
float grey = dot(color, vec3(0.3, 0.59, 0.11));
grey = grey / max(1.0, max(color.r, max(color.g, color.b)));
color = mix(vec3(grey), color, sat);
return mix(vec3(0.5), color, con);
}
vec3 applyGrading(vec3 color) {
return colorGradingHDR(color,
brightnessContrastSaturation.x,
brightnessContrastSaturation.z,
brightnessContrastSaturation.y);
}
#endif
`;var NV=`
#ifdef COLOR_ENHANCE
uniform vec4 colorEnhanceParams;
uniform float colorEnhanceMidtones;
vec3 applyColorEnhance(vec3 color) {
float maxChannel = max(color.r, max(color.g, color.b));
float lum = dot(color, vec3(0.2126, 0.7152, 0.0722));
if (colorEnhanceParams.x != 0.0 || colorEnhanceParams.y != 0.0) {
float logLum = log2(max(lum, 0.001)) / 10.0 + 0.5;
logLum = clamp(logLum, 0.0, 1.0);
float shadowWeight = pow(1.0 - logLum, 2.0);
float highlightWeight = pow(logLum, 2.0);
color *= pow(2.0, colorEnhanceParams.x * shadowWeight);
color *= pow(2.0, colorEnhanceParams.y * highlightWeight);
}
if (colorEnhanceMidtones != 0.0) {
const float pivot = 0.18;
const float widthStops = 1.25;
const float maxStops = 2.0;
float y = max(dot(color, vec3(0.2126, 0.7152, 0.0722)), 1e-6);
float d = log2(y / pivot);
float w = exp(-(d * d) / (2.0 * widthStops * widthStops));
float stops = colorEnhanceMidtones * maxStops * w;
color *= exp2(stops);
}
if (colorEnhanceParams.z != 0.0) {
float minChannel = min(color.r, min(color.g, color.b));
maxChannel = max(color.r, max(color.g, color.b));
float sat = (maxChannel - minChannel) / max(maxChannel, 0.001);
lum = dot(color, vec3(0.2126, 0.7152, 0.0722));
float normalizedLum = lum / max(1.0, maxChannel);
vec3 grey = vec3(normalizedLum) * maxChannel;
float satBoost = colorEnhanceParams.z * (1.0 - sat);
color = mix(grey, color, 1.0 + satBoost);
}
if (colorEnhanceParams.w != 0.0) {
maxChannel = max(color.r, max(color.g, color.b));
float scale = max(1.0, maxChannel);
vec3 normalized = color / scale;
float darkChannel = min(normalized.r, min(normalized.g, normalized.b));
float atmosphericLight = 0.95;
float t = 1.0 - colorEnhanceParams.w * darkChannel / atmosphericLight;
t = max(t, 0.1);
vec3 dehazed = (normalized - atmosphericLight) / t + atmosphericLight;
color = dehazed * scale;
}
return max(vec3(0.0), color);
}
#endif
`;var BV=`
#ifdef VIGNETTE
uniform vec4 vignetterParams;
uniform vec3 vignetteColor;
float dVignette;
float calcVignette(vec2 uv) {
float inner = vignetterParams.x;
float outer = vignetterParams.y;
float curvature = vignetterParams.z;
float intensity = vignetterParams.w;
vec2 curve = pow(abs(uv * 2.0 -1.0), vec2(1.0 / curvature));
float edge = pow(length(curve), curvature);
dVignette = 1.0 - intensity * smoothstep(inner, outer, edge);
return dVignette;
}
vec3 applyVignette(vec3 color, vec2 uv) {
return mix(vignetteColor, color, calcVignette(uv));
}
#endif
`;var UV=`
#ifdef FRINGING
uniform float fringingIntensity;
vec3 applyFringing(vec3 color, vec2 uv) {
vec2 centerDistance = uv - 0.5;
vec2 offset = fringingIntensity * centerDistance * centerDistance;
color.r = texture2D(sceneTexture, uv - offset).r;
color.b = texture2D(sceneTexture, uv + offset).b;
return color;
}
#endif
`;var kV=`
#ifdef CAS
uniform float sharpness;
#ifdef CAS_HDR
float maxComponent(float x, float y, float z) { return max(x, max(y, z)); }
vec3 toSDR(vec3 c) { return c / (1.0 + maxComponent(c.r, c.g, c.b)); }
vec3 toHDR(vec3 c) { return c / max(1.0 - maxComponent(c.r, c.g, c.b), 1e-4); }
#else
vec3 toSDR(vec3 c) { return c; }
vec3 toHDR(vec3 c) { return c; }
#endif
vec3 applyCas(vec3 color, vec2 uv, float sharpness) {
float x = sceneTextureInvRes.x;
float y = sceneTextureInvRes.y;
vec3 a = toSDR(texture2DLod(sceneTexture, uv + vec2(0.0, -y), 0.0).rgb);
vec3 b = toSDR(texture2DLod(sceneTexture, uv + vec2(-x, 0.0), 0.0).rgb);
vec3 c = toSDR(color.rgb);
vec3 d = toSDR(texture2DLod(sceneTexture, uv + vec2(x, 0.0), 0.0).rgb);
vec3 e = toSDR(texture2DLod(sceneTexture, uv + vec2(0.0, y), 0.0).rgb);
float min_g = min(a.g, min(b.g, min(c.g, min(d.g, e.g))));
float max_g = max(a.g, max(b.g, max(c.g, max(d.g, e.g))));
float sharpening_amount = sqrt(min(1.0 - max_g, min_g) / max(max_g, 1e-4));
float w = sharpening_amount * sharpness;
vec3 res = (w * (a + b + d + e) + c) / (4.0 * w + 1.0);
res = max(res, 0.0);
return toHDR(res);
}
#endif
`;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;
#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 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 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
`;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;
var sceneTexture: texture_2d<f32>;
var sceneTextureSampler: sampler;
uniform sceneTextureInvRes: vec2f;
#include "composeBloomPS"
#include "composeDofPS"
#include "composeSsaoPS"
#include "composeGradingPS"
#include "composeColorEnhancePS"
#include "composeVignettePS"
#include "composeFringingPS"
#include "composeCasPS"
#include "composeColorLutPS"
#include "composeDeclarationsPS"
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
#include "composeMainStartPS"
var output: FragmentOutput;
var uv = uv0;
let scene = textureSampleLevel(sceneTexture, sceneTextureSampler, uv, 0.0);
var result = scene.rgb;
#ifdef CAS
result = applyCas(result, uv, uniform.sharpness);
#endif
#ifdef DOF
result = applyDof(result, uv0);
#endif
#ifdef SSAO_TEXTURE
result = applySsao(result, uv0);
#endif
#ifdef FRINGING
result = applyFringing(result, uv);
#endif
#ifdef BLOOM
result = applyBloom(result, uv0);
#endif
#ifdef COLOR_ENHANCE
result = applyColorEnhance(result);
#endif
#ifdef GRADING
result = applyGrading(result);
#endif
result = toneMap(max(vec3f(0.0), result));
#ifdef COLOR_LUT
result = applyColorLUT(result);
#endif
#ifdef VIGNETTE
result = applyVignette(result, uv);
#endif
#include "composeMainEndPS"
#ifdef DEBUG_COMPOSE
#if DEBUG_COMPOSE == scene
result = scene.rgb;
#elif defined(BLOOM) && DEBUG_COMPOSE == bloom
result = dBloom * uniform.bloomIntensity;
#elif defined(DOF) && DEBUG_COMPOSE == dofcoc
result = vec3f(dCoc, 0.0);
#elif defined(DOF) && DEBUG_COMPOSE == dofblur
result = dBlur;
#elif defined(SSAO_TEXTURE) && DEBUG_COMPOSE == ssao
result = vec3f(dSsao);
#elif defined(VIGNETTE) && DEBUG_COMPOSE == vignette
result = vec3f(dVignette);
#endif
#endif
result = gammaCorrectOutput(result);
output.color = vec4f(result, scene.a);
return output;
}
`;var HV=`
#ifdef BLOOM
var bloomTexture: texture_2d<f32>;
var bloomTextureSampler: sampler;
uniform bloomIntensity: f32;
var<private> dBloom: vec3f;
fn applyBloom(color: vec3f, uv: vec2f) -> vec3f {
dBloom = textureSampleLevel(bloomTexture, bloomTextureSampler, uv, 0.0).rgb;
return color + dBloom * uniform.bloomIntensity;
}
#endif
`;var WV=`
#ifdef DOF
var cocTexture: texture_2d<f32>;
var cocTextureSampler: sampler;
var blurTexture: texture_2d<f32>;
var blurTextureSampler: sampler;
var<private> dCoc: vec2f;
var<private> dBlur: vec3f;
fn getDofBlur(uv: vec2f) -> vec3f {
dCoc = textureSampleLevel(cocTexture, cocTextureSampler, uv, 0.0).rg;
#if DOF_UPSCALE
let blurTexelSize = 1.0 / vec2f(textureDimensions(blurTexture, 0));
var bilinearBlur = vec3f(0.0);
var totalWeight = 0.0;
for (var i = -1; i <= 1; i++) {
for (var j = -1; j <= 1; j++) {
let offset = vec2f(f32(i), f32(j)) * blurTexelSize;
let cocSample = textureSampleLevel(cocTexture, cocTextureSampler, uv + offset, 0.0).rg;
let blurSample = textureSampleLevel(blurTexture, blurTextureSampler, uv + offset, 0.0).rgb;
let cocWeight = clamp(cocSample.r + cocSample.g, 0.0, 1.0);
bilinearBlur += blurSample * cocWeight;
totalWeight += cocWeight;
}
}
if (totalWeight > 0.0) {
bilinearBlur /= totalWeight;
}
dBlur = bilinearBlur;
return bilinearBlur;
#else
dBlur = textureSampleLevel(blurTexture, blurTextureSampler, uv, 0.0).rgb;
return dBlur;
#endif
}
fn applyDof(color: vec3f, uv: vec2f) -> vec3f {
let blur = getDofBlur(uv);
return mix(color, blur, dCoc.r + dCoc.g);
}
#endif
`;var XV=`
#ifdef SSAO
#define SSAO_TEXTURE
#endif
#if DEBUG_COMPOSE == ssao
#define SSAO_TEXTURE
#endif
#ifdef SSAO_TEXTURE
var ssaoTexture: texture_2d<f32>;
var ssaoTextureSampler: sampler;
var<private> dSsao: f32;
fn applySsao(color: vec3f, uv: vec2f) -> vec3f {
dSsao = textureSampleLevel(ssaoTexture, ssaoTextureSampler, uv, 0.0).r;
#ifdef SSAO
return color * dSsao;
#else
return color;
#endif
}
#endif
`;var YV=`
#ifdef GRADING
uniform brightnessContrastSaturation: vec3f;
uniform tint: vec3f;
fn colorGradingHDR(color: vec3f, brt: f32, sat: f32, con: f32) -> vec3f {
var colorOut = color * uniform.tint;
colorOut = colorOut * brt;
let grey = dot(colorOut, vec3f(0.3, 0.59, 0.11));
let normalizedGrey = grey / max(1.0, max(colorOut.r, max(colorOut.g, colorOut.b)));
colorOut = mix(vec3f(normalizedGrey), colorOut, sat);
return mix(vec3f(0.5), colorOut, con);
}
fn applyGrading(color: vec3f) -> vec3f {
return colorGradingHDR(color,
uniform.brightnessContrastSaturation.x,
uniform.brightnessContrastSaturation.z,
uniform.brightnessContrastSaturation.y);
}
#endif
`;var KV=`
#ifdef COLOR_ENHANCE
uniform colorEnhanceParams: vec4f;
uniform colorEnhanceMidtones: f32;
fn applyColorEnhance(color: vec3f) -> vec3f {
var colorOut = color;
var maxChannel = max(colorOut.r, max(colorOut.g, colorOut.b));
var lum = dot(colorOut, vec3f(0.2126, 0.7152, 0.0722));
if (uniform.colorEnhanceParams.x != 0.0 || uniform.colorEnhanceParams.y != 0.0) {
var logLum = log2(max(lum, 0.001)) / 10.0 + 0.5;
logLum = clamp(logLum, 0.0, 1.0);
let shadowWeight = pow(1.0 - logLum, 2.0);
let highlightWeight = pow(logLum, 2.0);
colorOut *= pow(2.0, uniform.colorEnhanceParams.x * shadowWeight);
colorOut *= pow(2.0, uniform.colorEnhanceParams.y * highlightWeight);
}
if (uniform.colorEnhanceMidtones != 0.0) {
let pivot = 0.18;
let widthStops = 1.25;
let maxStops = 2.0;
let y = max(dot(colorOut, vec3f(0.2126, 0.7152, 0.0722)), 1e-6);
let d = log2(y / pivot);
let w = exp(-(d * d) / (2.0 * widthStops * widthStops));
let stops = uniform.colorEnhanceMidtones * maxStops * w;
colorOut *= exp2(stops);
}
if (uniform.colorEnhanceParams.z != 0.0) {
let minChannel = min(colorOut.r, min(colorOut.g, colorOut.b));
maxChannel = max(colorOut.r, max(colorOut.g, colorOut.b));
let sat = (maxChannel - minChannel) / max(maxChannel, 0.001);
lum = dot(colorOut, vec3f(0.2126, 0.7152, 0.0722));
let normalizedLum = lum / max(1.0, maxChannel);
let grey = vec3f(normalizedLum) * maxChannel;
let satBoost = uniform.colorEnhanceParams.z * (1.0 - sat);
colorOut = mix(grey, colorOut, 1.0 + satBoost);
}
if (uniform.colorEnhanceParams.w != 0.0) {
maxChannel = max(colorOut.r, max(colorOut.g, colorOut.b));
let scale = max(1.0, maxChannel);
let normalized = colorOut / scale;
let darkChannel = min(normalized.r, min(normalized.g, normalized.b));
let atmosphericLight = 0.95;
var t = 1.0 - uniform.colorEnhanceParams.w * darkChannel / atmosphericLight;
t = max(t, 0.1);
let dehazed = (normalized - atmosphericLight) / t + atmosphericLight;
colorOut = dehazed * scale;
}
return max(vec3f(0.0), colorOut);
}
#endif
`;var jV=`
#ifdef VIGNETTE
uniform vignetterParams: vec4f;
uniform vignetteColor: vec3f;
var<private> dVignette: f32;
fn calcVignette(uv: vec2f) -> f32 {
let inner = uniform.vignetterParams.x;
let outer = uniform.vignetterParams.y;
let curvature = uniform.vignetterParams.z;
let intensity = uniform.vignetterParams.w;
let curve = pow(abs(uv * 2.0 - 1.0), vec2f(1.0 / curvature));
let edge = pow(length(curve), curvature);
dVignette = 1.0 - intensity * smoothstep(inner, outer, edge);
return dVignette;
}
fn applyVignette(color: vec3f, uv: vec2f) -> vec3f {
return mix(uniform.vignetteColor, color, calcVignette(uv));
}
#endif
`;var qV=`
#ifdef FRINGING
uniform fringingIntensity: f32;
fn applyFringing(color: vec3f, uv: vec2f) -> vec3f {
let centerDistance = uv - 0.5;
let offset = uniform.fringingIntensity * centerDistance * centerDistance;
var colorOut = color;
colorOut.r = textureSample(sceneTexture, sceneTextureSampler, uv - offset).r;
colorOut.b = textureSample(sceneTexture, sceneTextureSampler, uv + offset).b;
return colorOut;
}
#endif
`;var $V=`
#ifdef CAS
uniform sharpness: f32;
#ifdef CAS_HDR
fn maxComponent(x: f32, y: f32, z: f32) -> f32 { return max(x, max(y, z)); }
fn toSDR(c: vec3f) -> vec3f { return c / (1.0 + maxComponent(c.r, c.g, c.b)); }
fn toHDR(c: vec3f) -> vec3f { return c / max(1.0 - maxComponent(c.r, c.g, c.b), 1e-4); }
#else
fn toSDR(c: vec3f) -> vec3f { return c; }
fn toHDR(c: vec3f) -> vec3f { return c; }
#endif
fn applyCas(color: vec3f, uv: vec2f, sharpness: f32) -> vec3f {
let x = uniform.sceneTextureInvRes.x;
let y = uniform.sceneTextureInvRes.y;
let a: half3 = half3(toSDR(textureSampleLevel(sceneTexture, sceneTextureSampler, uv + vec2f(0.0, -y), 0.0).rgb));
let b: half3 = half3(toSDR(textureSampleLevel(sceneTexture, sceneTextureSampler, uv + vec2f(-x, 0.0), 0.0).rgb));
let c: half3 = half3(toSDR(color.rgb));
let d: half3 = half3(toSDR(textureSampleLevel(sceneTexture, sceneTextureSampler, uv + vec2f(x, 0.0), 0.0).rgb));
let e: half3 = half3(toSDR(textureSampleLevel(sceneTexture, sceneTextureSampler, uv + vec2f(0.0, y), 0.0).rgb));
let min_g = min(a.g, min(b.g, min(c.g, min(d.g, e.g))));
let max_g = max(a.g, max(b.g, max(c.g, max(d.g, e.g))));
let sharpening_amount = sqrt(min(half(1.0) - max_g, min_g) / max(max_g, half(1e-4)));
let w = sharpening_amount * half(sharpness);
var res = (w * (a + b + d + e) + c) / (half(4.0) * w + half(1.0));
res = max(res, half3(0.0));
return toHDR(vec3f(res));
}
#endif
`;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<f32>;
var colorLUTSampler: sampler;
#ifdef COLOR_LUT2
var colorLUT2: texture_2d<f32>;
var colorLUT2Sampler: sampler;
#endif
fn sampleColorLUT(lut: texture_2d<f32>, 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 {
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 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
`;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;
vec2 f = samplePos - texPos1;
vec2 w0 = f * (-0.5 + f * (1.0 - 0.5 * f));
vec2 w1 = 1.0 + f * f * (-2.5 + 1.5 * f);
vec2 w2 = f * (0.5 + f * (2.0 - 1.5 * f));
vec2 w3 = f * f * (-0.5 + 0.5 * f);
vec2 w12 = w1 + w2;
vec2 offset12 = w2 / (w1 + w2);
vec2 texPos0 = (texPos1 - 1.0) / texSize;
vec2 texPos3 = (texPos1 + 2.0) / texSize;
vec2 texPos12 = (texPos1 + offset12) / texSize;
vec4 result = vec4(0.0);
result += texture2DLod(tex, vec2(texPos0.x, texPos0.y), 0.0) * w0.x * w0.y;
result += texture2DLod(tex, vec2(texPos12.x, texPos0.y), 0.0) * w12.x * w0.y;
result += texture2DLod(tex, vec2(texPos3.x, texPos0.y), 0.0) * w3.x * w0.y;
result += texture2DLod(tex, vec2(texPos0.x, texPos12.y), 0.0) * w0.x * w12.y;
result += texture2DLod(tex, vec2(texPos12.x, texPos12.y), 0.0) * w12.x * w12.y;
result += texture2DLod(tex, vec2(texPos3.x, texPos12.y), 0.0) * w3.x * w12.y;
result += texture2DLod(tex, vec2(texPos0.x, texPos3.y), 0.0) * w0.x * w3.y;
result += texture2DLod(tex, vec2(texPos12.x, texPos3.y), 0.0) * w12.x * w3.y;
result += texture2DLod(tex, vec2(texPos3.x, texPos3.y), 0.0) * w3.x * w3.y;
return result;
}
`;var eH=`
fn SampleTextureCatmullRom(tex: texture_2d<f32>, texSampler: sampler, uv: vec2f, texSize: vec2f) -> vec4f {
let samplePos: vec2f = uv * texSize;
let texPos1: vec2f = floor(samplePos - 0.5) + 0.5;
let f: vec2f = samplePos - texPos1;
let w0: vec2f = f * (-0.5 + f * (1.0 - 0.5 * f));
let w1: vec2f = 1.0 + f * f * (-2.5 + 1.5 * f);
let w2: vec2f = f * (0.5 + f * (2.0 - 1.5 * f));
let w3: vec2f = f * f * (-0.5 + 0.5 * f);
let w12: vec2f = w1 + w2;
let offset12: vec2f = w2 / w12;
let texPos0: vec2f = (texPos1 - 1.0) / texSize;
let texPos3: vec2f = (texPos1 + 2.0) / texSize;
let texPos12: vec2f = (texPos1 + offset12) / texSize;
var result: vec4f = vec4f(0.0);
result = result + textureSampleLevel(tex, texSampler, vec2f(texPos0.x, texPos0.y), 0.0) * w0.x * w0.y;
result = result + textureSampleLevel(tex, texSampler, vec2f(texPos12.x, texPos0.y), 0.0) * w12.x * w0.y;
result = result + textureSampleLevel(tex, texSampler, vec2f(texPos3.x, texPos0.y), 0.0) * w3.x * w0.y;
result = result + textureSampleLevel(tex, texSampler, vec2f(texPos0.x, texPos12.y), 0.0) * w0.x * w12.y;
result = result + textureSampleLevel(tex, texSampler, vec2f(texPos12.x, texPos12.y), 0.0) * w12.x * w12.y;
result = result + textureSampleLevel(tex, texSampler, vec2f(texPos3.x, texPos12.y), 0.0) * w3.x * w12.y;
result = result + textureSampleLevel(tex, texSampler, vec2f(texPos0.x, texPos3.y), 0.0) * w0.x * w3.y;
result = result + textureSampleLevel(tex, texSampler, vec2f(texPos12.x, texPos3.y), 0.0) * w12.x * w3.y;
result = result + textureSampleLevel(tex, texSampler, vec2f(texPos3.x, texPos3.y), 0.0) * w3.x * w3.y;
return result;
}
`;var tH=`
#include "sampleCatmullRomPS"
#include "screenDepthPS"
uniform sampler2D sourceTexture;
uniform sampler2D historyTexture;
uniform mat4 matrix_viewProjectionPrevious;
uniform mat4 matrix_viewProjectionInverse;
uniform vec4 jitters;
uniform vec2 textureSize;
varying vec2 uv0;
vec2 reproject(vec2 uv, float depth) {
depth = depth * 2.0 - 1.0;
vec4 ndc = vec4(uv * 2.0 - 1.0, depth, 1.0);
ndc.xy -= jitters.xy;
vec4 worldPosition = matrix_viewProjectionInverse * ndc;
worldPosition /= worldPosition.w;
vec4 screenPrevious = matrix_viewProjectionPrevious * worldPosition;
return (screenPrevious.xy / screenPrevious.w) * 0.5 + 0.5;
}
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) {
vec4 s = texture2D(sourceTexture, uv + vec2(x, y) / textureSize);
vec3 premul = s.rgb * s.a;
minPremul = min(minPremul, premul);
maxPremul = max(maxPremul, premul);
}
}
return clamp(historyPremul, minPremul, maxPremul);
}
void main()
{
vec4 srcColor = texture2D(sourceTexture, uv0);
float linearDepth = getLinearScreenDepth(uv0);
float depth = delinearizeDepth(linearDepth);
vec2 historyUv = reproject(uv0, depth);
#ifdef QUALITY_HIGH
vec4 historySample = SampleTextureCatmullRom(TEXTURE_PASS(historyTexture), historyUv, textureSize);
#else
vec4 historySample = texture2D(historyTexture, historyUv);
#endif
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;
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);
}
`;var sH=`
#include "sampleCatmullRomPS"
#include "screenDepthPS"
var sourceTexture: texture_2d<f32>;
var sourceTextureSampler: sampler;
var historyTexture: texture_2d<f32>;
var historyTextureSampler: sampler;
uniform matrix_viewProjectionPrevious: mat4x4f;
uniform matrix_viewProjectionInverse: mat4x4f;
uniform jitters: vec4f;
uniform textureSize: vec2f;
varying uv0: vec2f;
fn reproject(uv_in: vec2f, depth: f32) -> vec2f {
var uv = vec2f(uv_in.x, 1.0 - uv_in.y);
var ndc = vec4f(uv * 2.0 - 1.0, depth, 1.0);
ndc = vec4f(ndc.xy - uniform.jitters.xy, ndc.zw);
var worldPosition = uniform.matrix_viewProjectionInverse * ndc;
worldPosition = worldPosition / worldPosition.w;
let screenPrevious = uniform.matrix_viewProjectionPrevious * worldPosition;
var result = (screenPrevious.xy / screenPrevious.w) * 0.5 + 0.5;
result.y = 1.0 - result.y;
return result;
}
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 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);
}
}
return clamp(historyPremul, minPremul, maxPremul);
}
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let srcColor = textureSample(sourceTexture, sourceTextureSampler, uv0);
let linearDepth = getLinearScreenDepth(uv0);
let depth = delinearizeDepth(linearDepth);
let historyUv = reproject(uv0, depth);
#ifdef QUALITY_HIGH
var historySample: vec4f = SampleTextureCatmullRom(historyTexture, historyTextureSampler, historyUv, uniform.textureSize);
#else
var historySample: vec4f = textureSample(historyTexture, historyTextureSampler, historyUv);
#endif
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);
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;
}
`;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;
void main()
{
float depth = getLinearScreenDepth(uv0);
float focusDistance = params.x;
float focusRange = params.y;
float invRange = params.z;
float farRange = focusDistance + focusRange * 0.5;
float cocFar = min((depth - farRange) * invRange, 1.0);
#ifdef NEAR_BLUR
float nearRange = focusDistance - focusRange * 0.5;
float cocNear = min((nearRange - depth) * invRange, 1.0);
#else
float cocNear = 0.0;
#endif
gl_FragColor = vec4(cocFar, cocNear, 0.0, 0.0);
}
`;var rH=`
#include "screenDepthPS"
varying uv0: vec2f;
uniform params: vec3f;
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let depth: f32 = getLinearScreenDepth(uv0);
let focusDistance: f32 = uniform.params.x;
let focusRange: f32 = uniform.params.y;
let invRange: f32 = uniform.params.z;
let farRange: f32 = focusDistance + focusRange * 0.5;
let cocFar: f32 = min((depth - farRange) * invRange, 1.0);
#ifdef NEAR_BLUR
let nearRange: f32 = focusDistance - focusRange * 0.5;
var cocNear: f32 = min((nearRange - depth) * invRange, 1.0);
#else
var cocNear: f32 = 0.0;
#endif
output.color = vec4f(cocFar, cocNear, 0.0, 0.0);
return output;
}
`;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
uniform sampler2D farTexture;
uniform sampler2D cocTexture;
uniform vec2 kernel[{KERNEL_COUNT}];
uniform float blurRadiusNear;
uniform float blurRadiusFar;
varying vec2 uv0;
void main()
{
vec2 coc = texture2D(cocTexture, uv0).rg;
float cocFar = coc.r;
vec3 sum = vec3(0.0, 0.0, 0.0);
#if defined(NEAR_BLUR)
float cocNear = coc.g;
if (cocNear > 0.0001) {
ivec2 nearTextureSize = textureSize(nearTexture, 0);
vec2 step = cocNear * blurRadiusNear / vec2(nearTextureSize);
for (int i = 0; i < {KERNEL_COUNT}; i++) {
vec2 uv = uv0 + step * kernel[i];
vec3 tap = texture2DLod(nearTexture, uv, 0.0).rgb;
sum += tap.rgb;
}
sum *= float({INV_KERNEL_COUNT});
} else
#endif
if (cocFar > 0.0001) {
ivec2 farTextureSize = textureSize(farTexture, 0);
vec2 step = cocFar * blurRadiusFar / vec2(farTextureSize);
float sumCoC = 0.0;
for (int i = 0; i < {KERNEL_COUNT}; i++) {
vec2 uv = uv0 + step * kernel[i];
vec3 tap = texture2DLod(farTexture, uv, 0.0).rgb;
float cocThis = texture2DLod(cocTexture, uv, 0.0).r;
tap *= cocThis;
sumCoC += cocThis;
sum += tap;
}
if (sumCoC > 0.0)
sum /= sumCoC;
sum /= cocFar;
}
pcFragColor0 = vec4(sum, 1.0);
}
`;var oH=`
#if defined(NEAR_BLUR)
var nearTexture: texture_2d<f32>;
var nearTextureSampler: sampler;
#endif
var farTexture: texture_2d<f32>;
var farTextureSampler: sampler;
var cocTexture: texture_2d<f32>;
var cocTextureSampler: sampler;
uniform kernel: array<vec2f, {KERNEL_COUNT}>;
uniform blurRadiusNear: f32;
uniform blurRadiusFar: f32;
varying uv0: vec2f;
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let coc: vec2f = textureSample(cocTexture, cocTextureSampler, input.uv0).rg;
let cocFar: f32 = coc.r;
var sum: vec3f = vec3f(0.0, 0.0, 0.0);
#if defined(NEAR_BLUR)
let cocNear: f32 = coc.g;
if (cocNear > 0.0001) {
let nearTextureSize: vec2f = vec2f(textureDimensions(nearTexture, 0));
let step: vec2f = cocNear * uniform.blurRadiusNear / nearTextureSize;
for (var i: i32 = 0; i < {KERNEL_COUNT}; i = i + 1) {
let uv: vec2f = uv0 + step * uniform.kernel[i].element;
let tap: vec3f = textureSampleLevel(nearTexture, nearTextureSampler, uv, 0.0).rgb;
sum = sum + tap;
}
sum = sum * f32({INV_KERNEL_COUNT});
} else
#endif
if (cocFar > 0.0001) {
let farTextureSize: vec2f = vec2f(textureDimensions(farTexture, 0));
let step: vec2f = cocFar * uniform.blurRadiusFar / farTextureSize;
var sumCoC: f32 = 0.0;
for (var i: i32 = 0; i < {KERNEL_COUNT}; i = i + 1) {
let uv: vec2f = uv0 + step * uniform.kernel[i].element;
var tap: vec3f = textureSampleLevel(farTexture, farTextureSampler, uv, 0.0).rgb;
let cocThis: f32 = textureSampleLevel(cocTexture, cocTextureSampler, uv, 0.0).r;
tap = tap * cocThis;
sumCoC = sumCoC + cocThis;
sum = sum + tap;
}
if (sumCoC > 0.0) {
sum = sum / sumCoC;
}
sum = sum / cocFar;
}
output.color = vec4f(sum, 1.0);
return output;
}
`;var HA=class extends Ut{constructor(e,s,i,r){super(e);n(this,"blurRadiusNear",1);n(this,"blurRadiusFar",1);n(this,"_blurRings",3);n(this,"_blurRingPoints",3);this.nearTexture=s,this.farTexture=i,this.cocTexture=r,ne.get(e,fe).set("dofBlurPS",aH),ne.get(e,se).set("dofBlurPS",oH);let{scope:a}=e;this.kernelId=a.resolve("kernel[0]"),this.kernelCountId=a.resolve("kernelCount"),this.blurRadiusNearId=a.resolve("blurRadiusNear"),this.blurRadiusFarId=a.resolve("blurRadiusFar"),this.nearTextureId=a.resolve("nearTexture"),this.farTextureId=a.resolve("farTexture"),this.cocTextureId=a.resolve("cocTexture")}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(rd.concentric(this.blurRings,this.blurRingPoints));let e=this.kernel.length>>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<this.beforePasses.length;e++)this.beforePasses[e].destroy();this.beforePasses.length=0}destroyRT(e){e&&(e.destroyTextureBuffers(),e.destroy())}setupCocPass(e,s,i,r){let a=r?Po:Wr;this.cocRT=this.createRenderTarget("CoCTexture",a),this.cocTexture=this.cocRT.colorBuffer;let o=new VA(e,s,r);return o.init(this.cocRT,{resizeSource:i}),o.setClearColor(F.BLACK),o}setupFarPass(e,s,i){this.farRt=this.createRenderTarget("FarDofTexture",s.format);let r=new hn(e,s,{boxFilter:!0,premultiplyTexture:this.cocTexture,premultiplySrcChannel:"r"});return r.init(this.farRt,{resizeSource:s,scaleX:i,scaleY:i}),r.setClearColor(F.BLACK),r}setupBlurPass(e,s,i,r){let a=this.farRt?.colorBuffer;this.blurRt=this.createRenderTarget("DofBlurTexture",s.format),this.blurTexture=this.blurRt.colorBuffer;let o=new HA(e,i?s:null,a,this.cocTexture);return o.init(this.blurRt,{resizeSource:s,scaleX:r,scaleY:r}),o.setClearColor(F.BLACK),o}createTexture(e,s){return new Z(this.device,{name:e,width:1,height:1,format:s,mipmaps:!1,minFilter:1,magFilter:1,addressU:1,addressV:1})}createRenderTarget(e,s){return new me({colorBuffer:this.createTexture(e,s),depth:!1,stencil:!1})}frameUpdate(){super.frameUpdate(),this.cocPass.focusDistance=this.focusDistance,this.cocPass.focusRange=this.focusRange,this.blurPass.blurRadiusNear=this.blurRadius,this.blurPass.blurRadiusFar=this.blurRadius*(this.highQuality?1:.5),this.blurPass.blurRings=this.blurRings,this.blurPass.blurRingPoints=this.blurRingPoints}};var Hb=[],w9="uSceneDepthMap",lg=class extends yt{constructor(e,s,i,r,a){super(e);n(this,"viewBindGroups",[]);n(this,"linearDepthTexture");n(this,"linearDepthClearValue",new F(0,0,0,0));this.scene=s,this.renderer=i,this.camera=r,this.setupRenderTarget(a)}destroy(){super.destroy(),this.camera.shaderParams.sceneDepthMapLinear=!1,this.renderTarget?.destroy(),this.renderTarget=null,this.linearDepthTexture?.destroy(),this.linearDepthTexture=null,this.viewBindGroups.forEach(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<a.length;h++){let f=a[h];if(f.id===Zt)break;if(f.enabled&&o[h]&&f.camerasSet.has(r)){let u=f.getCulledInstances(r),d=l[h]?u.transparent:u.opaque;for(let p=0;p<d.length;p++){let m=d[p];m.material?.depthWrite&&Hb.push(m)}e.renderForwardLayer(r,i,null,void 0,xr,this.viewBindGroups,{meshInstances:Hb}),Hb.length=0}}}frameUpdate(){super.frameUpdate();let{camera:e}=this;this.setClearDepth(e.clearDepthBuffer?1:void 0);let s;if(e.clearDepthBuffer){let i=e.farClip-Number.MIN_VALUE;s=this.linearDepthClearValue,this.linearDepthFormat===Mt?s.r=i:Hs.float2RGBA8(i,s)}this.setClearColor(s)}};var nH=`
#include "screenDepthPS"
varying vec2 uv0;
uniform sampler2D sourceTexture;
uniform vec2 sourceInvResolution;
uniform int filterSize;
float random(const highp vec2 w) {
const vec3 m = vec3(0.06711056, 0.00583715, 52.9829189);
return fract(m.z * fract(dot(w, m.xy)));
}
mediump float bilateralWeight(in mediump float depth, in mediump float sampleDepth) {
mediump float diff = (sampleDepth - depth);
return max(0.0, 1.0 - diff * diff);
}
void tap(inout float sum, inout float totalWeight, float weight, float depth, vec2 position) {
mediump float color = texture2D(sourceTexture, position).r;
mediump float textureDepth = -getLinearScreenDepth(position);
mediump float bilateral = bilateralWeight(depth, textureDepth);
bilateral *= weight;
sum += color * bilateral;
totalWeight += bilateral;
}
void main() {
mediump float depth = -getLinearScreenDepth(uv0);
mediump float totalWeight = 1.0;
mediump float color = texture2D(sourceTexture, uv0 ).r;
mediump float sum = color * totalWeight;
for (mediump int i = -filterSize; i <= filterSize; i++) {
mediump float weight = 1.0;
#ifdef HORIZONTAL
vec2 offset = vec2(i, 0) * sourceInvResolution;
#else
vec2 offset = vec2(0, i) * sourceInvResolution;
#endif
tap(sum, totalWeight, weight, depth, uv0 + offset);
}
mediump float ao = sum / totalWeight;
gl_FragColor.r = ao;
}
`;var lH=`
#include "screenDepthPS"
varying uv0: vec2f;
var sourceTexture: texture_2d<f32>;
var sourceTextureSampler: sampler;
uniform sourceInvResolution: vec2f;
uniform filterSize: i32;
fn random(w: vec2f) -> f32 {
const m: vec3f = vec3f(0.06711056, 0.00583715, 52.9829189);
return fract(m.z * fract(dot(w, m.xy)));
}
fn bilateralWeight(depth: f32, sampleDepth: f32) -> f32 {
let diff: f32 = (sampleDepth - depth);
return max(0.0, 1.0 - diff * diff);
}
fn tap(sum_ptr: ptr<function, f32>, totalWeight_ptr: ptr<function, f32>, weight: f32, depth: f32, position: vec2f) {
let color: f32 = textureSample(sourceTexture, sourceTextureSampler, position).r;
let textureDepth: f32 = -getLinearScreenDepth(position);
let bilateral: f32 = bilateralWeight(depth, textureDepth) * weight;
*sum_ptr = *sum_ptr + color * bilateral;
*totalWeight_ptr = *totalWeight_ptr + bilateral;
}
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let depth: f32 = -getLinearScreenDepth(input.uv0);
var totalWeight: f32 = 1.0;
let color: f32 = textureSample(sourceTexture, sourceTextureSampler, input.uv0 ).r;
var sum: f32 = color * totalWeight;
for (var i: i32 = -uniform.filterSize; i <= uniform.filterSize; i = i + 1) {
let weight: f32 = 1.0;
#ifdef HORIZONTAL
var offset: vec2f = vec2f(f32(i), 0.0) * uniform.sourceInvResolution;
#else
var offset: vec2f = vec2f(0.0, f32(i)) * uniform.sourceInvResolution;
#endif
tap(&sum, &totalWeight, weight, depth, input.uv0 + offset);
}
let ao: f32 = sum / totalWeight;
output.color = vec4f(ao, ao, ao, 1.0);
return output;
}
`;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;
uniform vec2 uInvResolution;
uniform float uAspect;
#define saturate(x) clamp(x,0.0,1.0)
highp float getWFromProjectionMatrix(const mat4 p, const vec3 v) {
return -v.z;
}
highp float getViewSpaceZFromW(const mat4 p, const float w) {
return -w;
}
const float kLog2LodRate = 3.0;
float random(const highp vec2 w) {
const vec3 m = vec3(0.06711056, 0.00583715, 52.9829189);
return fract(m.z * fract(dot(w, m.xy)));
}
highp vec2 getFragCoord() {
return gl_FragCoord.xy;
}
highp vec3 computeViewSpacePositionFromDepth(highp vec2 uv, highp float linearDepth) {
return vec3((0.5 - uv) * vec2(uAspect, 1.0) * linearDepth, linearDepth);
}
highp vec3 faceNormal(highp vec3 dpdx, highp vec3 dpdy) {
return normalize(cross(dpdx, dpdy));
}
highp vec3 computeViewSpaceNormal(const highp vec3 position) {
return faceNormal(dFdx(position), dFdy(position));
}
highp vec3 computeViewSpaceNormal(const highp vec3 position, const highp vec2 uv) {
highp vec2 uvdx = uv + vec2(uInvResolution.x, 0.0);
highp vec2 uvdy = uv + vec2(0.0, uInvResolution.y);
highp vec3 px = computeViewSpacePositionFromDepth(uvdx, -getLinearScreenDepth(uvdx));
highp vec3 py = computeViewSpacePositionFromDepth(uvdy, -getLinearScreenDepth(uvdy));
highp vec3 dpdx = px - position;
highp vec3 dpdy = py - position;
return faceNormal(dpdx, dpdy);
}
uniform vec2 uSampleCount;
uniform float uSpiralTurns;
#define PI (3.14159)
mediump vec3 tapLocation(mediump float i, const mediump float noise) {
mediump float offset = ((2.0 * PI) * 2.4) * noise;
mediump float angle = ((i * uSampleCount.y) * uSpiralTurns) * (2.0 * PI) + offset;
mediump float radius = (i + noise + 0.5) * uSampleCount.y;
return vec3(cos(angle), sin(angle), radius * radius);
}
highp vec2 startPosition(const float noise) {
float angle = ((2.0 * PI) * 2.4) * noise;
return vec2(cos(angle), sin(angle));
}
uniform vec2 uAngleIncCosSin;
highp mat2 tapAngleStep() {
highp vec2 t = uAngleIncCosSin;
return mat2(t.x, t.y, -t.y, t.x);
}
mediump vec3 tapLocationFast(mediump float i, mediump vec2 p, const mediump float noise) {
mediump float radius = (i + noise + 0.5) * uSampleCount.y;
return vec3(p, radius * radius);
}
uniform float uMaxLevel;
uniform float uInvRadiusSquared;
uniform float uMinHorizonAngleSineSquared;
uniform float uBias;
uniform float uPeak2;
void computeAmbientOcclusionSAO(inout mediump float occlusion, mediump float i, mediump float ssDiskRadius,
const highp vec2 uv, const highp vec3 origin, const mediump vec3 normal,
const mediump vec2 tapPosition, const float noise) {
mediump vec3 tap = tapLocationFast(i, tapPosition, noise);
mediump float ssRadius = max(1.0, tap.z * ssDiskRadius);
mediump vec2 uvSamplePos = uv + vec2(ssRadius * tap.xy) * uInvResolution;
mediump float level = clamp(floor(log2(ssRadius)) - kLog2LodRate, 0.0, float(uMaxLevel));
highp float occlusionDepth = -getLinearScreenDepth(uvSamplePos);
highp vec3 p = computeViewSpacePositionFromDepth(uvSamplePos, occlusionDepth);
vec3 v = p - origin;
float vv = dot(v, v);
float vn = dot(v, normal);
mediump float w = max(0.0, 1.0 - vv * uInvRadiusSquared);
w = w * w;
w *= step(vv * uMinHorizonAngleSineSquared, vn * vn);
occlusion += w * max(0.0, vn + origin.z * uBias) / (vv + uPeak2);
}
uniform float uProjectionScaleRadius;
uniform float uIntensity;
uniform float uRandomize;
float scalableAmbientObscurance(highp vec2 uv, highp vec3 origin, vec3 normal) {
float noise = random(getFragCoord()) + uRandomize;
highp vec2 tapPosition = startPosition(noise);
highp mat2 angleStep = tapAngleStep();
float ssDiskRadius = -(uProjectionScaleRadius / origin.z);
float occlusion = 0.0;
for (float i = 0.0; i < uSampleCount.x; i += 1.0) {
computeAmbientOcclusionSAO(occlusion, i, ssDiskRadius, uv, origin, normal, tapPosition, noise);
tapPosition = angleStep * tapPosition;
}
return occlusion;
}
uniform float uPower;
void main() {
highp vec2 uv = uv0;
highp float depth = -getLinearScreenDepth(uv0);
highp vec3 origin = computeViewSpacePositionFromDepth(uv, depth);
vec3 normal = computeViewSpaceNormal(origin, uv);
float occlusion = 0.0;
if (uIntensity > 0.0) {
occlusion = scalableAmbientObscurance(uv, origin, normal);
}
float ao = max(0.0, 1.0 - occlusion * uIntensity);
ao = pow(ao, uPower);
gl_FragColor = vec4(ao, ao, ao, 1.0);
}
`;var hH=`
#include "screenDepthPS"
varying uv0: vec2f;
uniform uInvResolution: vec2f;
uniform uAspect: f32;
fn getWFromProjectionMatrix(p: mat4x4f, v: vec3f) -> f32 {
return -v.z;
}
fn getViewSpaceZFromW(p: mat4x4f, w: f32) -> f32 {
return -w;
}
const kLog2LodRate: f32 = 3.0;
fn random(w: vec2f) -> f32 {
const m: vec3f = vec3f(0.06711056, 0.00583715, 52.9829189);
return fract(m.z * fract(dot(w, m.xy)));
}
fn getFragCoord() -> vec2f {
return pcPosition.xy;
}
fn computeViewSpacePositionFromDepth(uv: vec2f, linearDepth: f32) -> vec3f {
return vec3f((0.5 - uv) * vec2f(uniform.uAspect, 1.0) * linearDepth, linearDepth);
}
fn faceNormal(dpdx: vec3f, dpdy: vec3f) -> vec3f {
return normalize(cross(dpdx, dpdy));
}
fn computeViewSpaceNormalDeriv(position: vec3f) -> vec3f {
return faceNormal(dpdx(position), dpdy(position));
}
fn computeViewSpaceNormalDepth(position: vec3f, uv: vec2f) -> vec3f {
let uvdx: vec2f = uv + vec2f(uniform.uInvResolution.x, 0.0);
let uvdy: vec2f = uv + vec2f(0.0, uniform.uInvResolution.y);
let px: vec3f = computeViewSpacePositionFromDepth(uvdx, -getLinearScreenDepth(uvdx));
let py: vec3f = computeViewSpacePositionFromDepth(uvdy, -getLinearScreenDepth(uvdy));
let dpdx: vec3f = px - position;
let dpdy: vec3f = py - position;
return faceNormal(dpdx, dpdy);
}
uniform uSampleCount: vec2f;
uniform uSpiralTurns: f32;
const PI: f32 = 3.14159;
fn tapLocation(i: f32, noise: f32) -> vec3f {
let offset: f32 = ((2.0 * PI) * 2.4) * noise;
let angle: f32 = ((i * uniform.uSampleCount.y) * uniform.uSpiralTurns) * (2.0 * PI) + offset;
let radius: f32 = (i + noise + 0.5) * uniform.uSampleCount.y;
return vec3f(cos(angle), sin(angle), radius * radius);
}
fn startPosition(noise: f32) -> vec2f {
let angle: f32 = ((2.0 * PI) * 2.4) * noise;
return vec2f(cos(angle), sin(angle));
}
uniform uAngleIncCosSin: vec2f;
fn tapAngleStep() -> mat2x2f {
let t: vec2f = uniform.uAngleIncCosSin;
return mat2x2f(vec2f(t.x, t.y), vec2f(-t.y, t.x));
}
fn tapLocationFast(i: f32, p: vec2f, noise_in: f32) -> vec3f {
let radius: f32 = (i + noise_in + 0.5) * uniform.uSampleCount.y;
return vec3f(p.x, p.y, radius * radius);
}
uniform uMaxLevel: f32;
uniform uInvRadiusSquared: f32;
uniform uMinHorizonAngleSineSquared: f32;
uniform uBias: f32;
uniform uPeak2: f32;
fn computeAmbientOcclusionSAO(occlusion_ptr: ptr<function, f32>, i: f32, ssDiskRadius: f32,
uv: vec2f, origin: vec3f, normal: vec3f,
tapPosition: vec2f, noise: f32) {
let tap: vec3f = tapLocationFast(i, tapPosition, noise);
let ssRadius: f32 = max(1.0, tap.z * ssDiskRadius);
let uvSamplePos: vec2f = uv + (ssRadius * tap.xy) * uniform.uInvResolution;
let level: f32 = clamp(floor(log2(ssRadius)) - kLog2LodRate, 0.0, uniform.uMaxLevel);
let occlusionDepth: f32 = -getLinearScreenDepth(uvSamplePos);
let p: vec3f = computeViewSpacePositionFromDepth(uvSamplePos, occlusionDepth);
let v: vec3f = p - origin;
let vv: f32 = dot(v, v);
let vn: f32 = dot(v, normal);
var w_val: f32 = max(0.0, 1.0 - vv * uniform.uInvRadiusSquared);
w_val = w_val * w_val;
w_val = w_val * step(vv * uniform.uMinHorizonAngleSineSquared, vn * vn);
*occlusion_ptr = *occlusion_ptr + w_val * max(0.0, vn + origin.z * uniform.uBias) / (vv + uniform.uPeak2);
}
uniform uProjectionScaleRadius: f32;
uniform uIntensity: f32;
uniform uRandomize: f32;
fn scalableAmbientObscurance(uv: vec2f, origin: vec3f, normal: vec3f) -> f32 {
let noise: f32 = random(getFragCoord()) + uniform.uRandomize;
var tapPosition: vec2f = startPosition(noise);
let angleStep: mat2x2f = tapAngleStep();
let ssDiskRadius: f32 = -(uniform.uProjectionScaleRadius / origin.z);
var occlusion: f32 = 0.0;
for (var i: i32 = 0; i < i32(uniform.uSampleCount.x); i = i + 1) {
computeAmbientOcclusionSAO(&occlusion, f32(i), ssDiskRadius, uv, origin, normal, tapPosition, noise);
tapPosition = angleStep * tapPosition;
}
return occlusion;
}
uniform uPower: f32;
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
let uv: vec2f = input.uv0;
let depth: f32 = -getLinearScreenDepth(input.uv0);
let origin: vec3f = computeViewSpacePositionFromDepth(uv, depth);
let normal: vec3f = computeViewSpaceNormalDepth(origin, uv);
var occlusion: f32 = 0.0;
if (uniform.uIntensity > 0.0) {
occlusion = scalableAmbientObscurance(uv, origin, normal);
}
var ao: f32 = max(0.0, 1.0 - occlusion * uniform.uIntensity);
ao = pow(ao, uniform.uPower);
output.color = vec4f(ao, ao, ao, 1.0);
return output;
}
`;var cg=class extends Ut{constructor(e,s,i,r){super(e);n(this,"radius",5);n(this,"intensity",1);n(this,"power",1);n(this,"sampleCount",10);n(this,"minAngle",5);n(this,"randomize",!1);n(this,"ssaoTexture");n(this,"_scale",1);n(this,"_blueNoise",new Op(19));this.sourceTexture=s,this.cameraComponent=i,ne.get(e,fe).set("ssaoPS",cH),ne.get(e,se).set("ssaoPS",hH);let a=new Map;Se.addScreenDepthChunkDefines(e,i.shaderParams,a),this.shader=Se.createShader(e,{uniqueName:"SsaoShader",attributes:{aPosition:ee},vertexChunk:"quadVS",fragmentChunk:"ssaoPS",fragmentDefines:a});let o=this.createRenderTarget("SsaoFinalTexture");this.ssaoTexture=o.colorBuffer,this.init(o,{resizeSource:this.sourceTexture});let l=new F(0,0,0,0);if(this.setClearColor(l),r){let h=this.createRenderTarget("SsaoTempTexture"),f=new Hu(e,o.colorBuffer,i,!0);f.init(h,{resizeSource:o.colorBuffer}),f.setClearColor(l);let u=new Hu(e,h.colorBuffer,i,!1);u.init(o,{resizeSource:o.colorBuffer}),u.setClearColor(l),this.afterPasses.push(f),this.afterPasses.push(u)}this.ssaoTextureId=e.scope.resolve("ssaoTexture"),this.ssaoTextureSizeInvId=e.scope.resolve("ssaoTextureSizeInv")}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 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<this.beforePasses.length;i++){let r=this.beforePasses[i];if(r instanceof Ya){let a=r.renderActions;for(let o=0;o<a.length;o++){let l=a[o],h=l.camera;h&&(e.has(h)||e.set(h,l),s.set(h,l))}}}e.forEach(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)<e}lerp(t,e,s,i=s,r=s){return this.position.lerp(t.position,e.position,s),this.angles.x=R.lerpAngle(t.angles.x,e.angles.x,i)%360,this.angles.y=R.lerpAngle(t.angles.y,e.angles.y,i)%360,this.angles.z=R.lerpAngle(t.angles.z,e.angles.z,i)%360,this.distance=R.lerp(t.distance,e.distance,r),this}move(t){return this.position.add(t),this.position.x=R.clamp(this.position.x,this.xRange.x,this.xRange.y),this.position.y=R.clamp(this.position.y,this.yRange.x,this.yRange.y),this.position.z=R.clamp(this.position.z,this.zRange.x,this.zRange.y),this}rotate(t){return this.angles.add(t),this.angles.x%=360,this.angles.y%=360,this.angles.z%=360,this.angles.x=R.clamp(this.angles.x,this.pitchRange.x,this.pitchRange.y),this.angles.y=R.clamp(this.angles.y,this.yawRange.x,this.yawRange.y),this}set(t,e,s){return this.position.copy(t),this.angles.copy(e),this.distance=s,this}look(t,e){this.position.copy(t),this.distance=t.distance(e);let s=R9.sub2(e,t).normalize(),i=Math.atan2(-s.y,Math.sqrt(s.x*s.x+s.z*s.z))*R.RAD_TO_DEG,r=Math.atan2(-s.x,-s.z)*R.RAD_TO_DEG;return this.angles.set(-i,r,0),this}getFocus(t){return b9.setFromEulerAngles(this.angles).transformVector(x.FORWARD,t).mulScalar(this.distance).add(this.position)}};var Sx=class{constructor(t){n(this,"_value");Array.isArray(t)?this._value=t.slice():this._value=new Array(+t).fill(0)}add(t){for(let e=0;e<this._value.length;e++)this._value[e]+=t._value[e]||0;return this}append(t){for(let e=0;e<this._value.length;e++)this._value[e]+=t[e]||0;return this}copy(t){for(let e=0;e<this._value.length;e++)this._value[e]=t._value[e]||0;return this}length(){let t=0;for(let e of this._value)t+=e*e;return Math.sqrt(t)}read(){let t=this._value.slice();return this._value.fill(0),t}},xx=class{constructor(t){n(this,"deltas",{});for(let e in t)this.deltas[e]=new Sx(t[e])}read(){let t={};for(let e in this.deltas)t[e]=this.deltas[e].read();return t}},cr=class extends xx{constructor(){super(...arguments);n(this,"_element",null);n(this,"_events",new J)}on(e,s){this._events.on(e,s)}off(e,s){this._events.off(e,s)}fire(e,...s){this._events.fire(e,...s)}attach(e){this._element&&this.detach(),this._element=e}detach(){this._element&&(this._element=null,this.read())}destroy(){this.detach(),this._events.off()}},vx=class{update(t,e){t.read()}},fn=class extends vx{constructor(){super(...arguments);n(this,"_pose",new ei)}attach(e,s=!0){}detach(){}update(e,s){return super.update(e,s),this._pose}destroy(){this.detach()}};var Mh=()=>{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=r<window.innerWidth*.5;this._pointerData.set(i,{x:r,y:a,left:o});let l=Date.now();(this._lastPointer.x-r)**2+(this._lastPointer.y-a)**2<100&&l-this._lastPointer.time<250&&this.deltas.doubleTap.append([1]),this._lastPointer.x=r,this._lastPointer.y=a,this._lastPointer.time=l,o&&Wb(this._layout,"joystick")&&this.fire("joystick:position:left",this._leftJoystick.down(r,a)),!o&&Xb(this._layout,"joystick")&&this.fire("joystick:position:right",this._rightJoystick.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);if(!f)return;let{left:u}=f;f.x=a,f.y=o,u?Wb(this._layout,"joystick")?this.fire("joystick:position:left",this._leftJoystick.move(a,o)):this.deltas.leftInput.append([l,h]):Xb(this._layout,"joystick")?this.fire("joystick:position:right",this._rightJoystick.move(a,o)):this.deltas.rightInput.append([l,h])}_onPointerUp(e){let{pointerType:s,pointerId:i}=e;if(this._movementState.up(e),s!=="touch")return;this._element?.releasePointerCapture(i);let r=this._pointerData.get(i);if(!r)return;let{left:a}=r;this._pointerData.delete(i),a&&Wb(this._layout,"joystick")&&this.fire("joystick:position:left",this._leftJoystick.up()),!a&&Xb(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()}};var M9=new B,KA=class extends cr{constructor(){super({touch:[0,0],count:[0],pinch:[0]});n(this,"_movementState",Mh());n(this,"_pointerEvents",new Map);n(this,"_pointerPos",new B);n(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)}_onPointerDown(e){let{pointerId:s,pointerType:i}=e;this._movementState.down(e),i==="touch"&&(this._element?.setPointerCapture(s),this._pointerEvents.set(s,e),this.deltas.count.append([1]),this._pointerEvents.size>1&&(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;e<this._button.length;e++){if(this._button[e]===1){this._button[e]=-1;continue}this._button[e]=0}}_setKey(e,s){this._keyMap.has(e)&&(this._keyNow[this._keyMap.get(e)??0]=s)}attach(e){super.attach(e),this._element=e,this._element.addEventListener("wheel",this._onWheel,fH),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("pointerleave",this._onPointerUp),this._element.addEventListener("lostpointercapture",this._onPointerUp),this._element.addEventListener("contextmenu",this._onContextMenu),window.addEventListener("keydown",this._onKeyDown,!1),window.addEventListener("keyup",this._onKeyUp,!1)}detach(){this._element&&(this._element.removeEventListener("wheel",this._onWheel,fH),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("pointerleave",this._onPointerUp),this._element.removeEventListener("lostpointercapture",this._onPointerUp),this._element.removeEventListener("contextmenu",this._onContextMenu),window.removeEventListener("keydown",this._onKeyDown,!1),window.removeEventListener("keyup",this._onKeyUp,!1),this._keyNow.fill(0),this._keyPrev.fill(0),super.detach())}read(){for(let e=0;e<Yb.length;e++)Yb[e]=this._keyNow[e]-this._keyPrev[e],this._keyPrev[e]=this._keyNow[e];return this.deltas.key.append(Yb),super.read()}};n($A,"keyCode",uH);var qA=$A;var dH={A:0,B:1,X:2,Y:3,LB:4,RB:5,LT:6,RT:7,SELECT:8,START:9,LEFT_STICK:10,RIGHT_STICK:11},Kb=Object.keys(dH).length,Tx=class extends cr{constructor(){super({buttons:Array(Kb).fill(0),leftStick:[0,0],rightStick:[0,0]});n(this,"_buttonPrev",Array(Kb).fill(0))}read(){let e=navigator.getGamepads();for(let s=0;s<e.length;s++){let i=e[s];if(!i||i.mapping!=="standard"||i.axes.length<4||i.buttons.length<Kb)continue;let{buttons:r,axes:a}=i;for(let o=0;o<this._buttonPrev.length;o++){let l=+r[o].pressed;this.deltas.buttons[o]=l-this._buttonPrev[o],this._buttonPrev[o]=l}this.deltas.leftStick.append([a[0],a[1]]),this.deltas.rightStick.append([a[2],a[3]])}return super.read()}};n(Tx,"buttonCode",dH);var co=(c,t)=>1-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;e<this.nodes.length;e++){let s=this.nodes[e];ju.add(s.getPosition())}ju.mulScalar(1/(this.nodes.length||1))}ju.equalsApprox(this.root.getLocalPosition(),qb)||(this.root.setLocalPosition(ju),this.fire(As.EVENT_POSITIONUPDATE,ju),this._renderUpdate=!0)}_updateRotation(){Ex.set(0,0,0,1),this._coordSpace==="local"&&this.nodes.length!==0&&Ex.copy(this.nodes[this.nodes.length-1].getRotation()),!Ex.equalsApprox(this.root.getRotation(),qb)&&(this.root.setRotation(Ex),this.fire(As.EVENT_ROTATIONUPDATE,Ex.getEulerAngles()),this._renderUpdate=!0)}_updateScale(){if(this._camera.projection===ts){let e=this.root.getLocalPosition(),s=this._camera.entity.getPosition(),i=tC.sub2(e,s).dot(this._camera.entity.forward);this._scale=Math.tan(.5*this._camera.fov*R.DEG_TO_RAD)*i*V9}else this._scale=this._camera.orthoHeight*H9;this._scale=Math.max(this._scale*this._size,G9),!(Math.abs(this._scale-this.root.getLocalScale().x)<qb)&&(this.root.setLocalScale(this._scale,this._scale,this._scale),this.fire(As.EVENT_SCALEUPDATE,this._scale),this._renderUpdate=!0)}_getSelection(e,s){let i=this._camera.screenToWorld(e,s,0),r=this._camera.screenToWorld(e,s,this._camera.farClip-this._camera.nearClip),a=tC.copy(r).sub(i).normalize(),o=[];for(let l=0;l<this.intersectShapes.length;l++){let h=this.intersectShapes[l];if(h.disabled||!h.entity.enabled)continue;let f=h.entity.getWorldTransform();for(let u=0;u<h.triData.length;u++){let{tris:d,transform:p,priority:m}=h.triData[u],_=k9.copy(f).mul(p),S=z9.copy(_).invert();S.transformPoint(i,sC.origin),S.transformVector(a,sC.direction),sC.direction.normalize();for(let g=0;g<d.length;g++)d[g].intersectsRay(sC,tC)&&o.push({dist:_.transformPoint(tC).sub(i).length(),meshInstances:h.meshInstances,priority:m})}}return o.length?(o.sort((l,h)=>l.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<s.meshInstances.length;i++)this._shapeMap.set(s.meshInstances[i],s)}}enableShape(e,s){e==="face"&&(e="f");let i=this._shapes[e];i&&(i.disabled=!s)}isShapeEnabled(e){e==="face"&&(e="f");let s=this._shapes[e];return s?!s.disabled:!1}setTheme(e){let s={...this._theme,...e};if(!(typeof s!="object"||typeof s.shapeBase!="object"||typeof s.shapeHover!="object"||typeof s.guideBase!="object")){for(let i in s.shapeBase)s.shapeBase[i]instanceof F&&this._theme.shapeBase[i].copy(s.shapeBase[i]);for(let i in s.shapeHover)s.shapeHover[i]instanceof F&&this._theme.shapeHover[i].copy(s.shapeHover[i]);for(let i in s.guideBase)s.guideBase[i]instanceof F&&this._theme.guideBase[i].copy(s.guideBase[i]);typeof s.guideOcclusion=="number"&&(this._theme.guideOcclusion=R.clamp(s.guideOcclusion,0,1)),s.disabled instanceof F&&this._theme.disabled.copy(s.disabled);for(let i in this._shapes)this._shapes[i].hover(!!this._hoverAxis)}}prerender(){if(super.prerender(),!this.enabled)return;let e=this.root.getLocalPosition(),s=this.root.getRotation(),i=this._hoverAxis||this._selectedAxis,r=this._hoverIsPlane||this._selectedIsPlane;this._drawGuideLines(e,s,i,r)}destroy(){super.destroy();for(let e in this._shapes)this._shapes[e].destroy()}};n(Fh,"EVENT_TRANSFORMSTART","transform:start"),n(Fh,"EVENT_TRANSFORMMOVE","transform:move"),n(Fh,"EVENT_TRANSFORMEND","transform:end");var is=Fh;var DH=new x,LH=new x,MH=new x,ui=class{constructor(t,e=0){n(this,"_priority",0);n(this,"_transform",new W);n(this,"tris",[]);this.fromGeometry(t),this._priority=e}get transform(){return this._transform}get priority(){return this._priority}setTransform(t=new x,e=new $,s=new x){this.transform.setTRS(t,e,s)}fromGeometry(t){if(!t||!(t instanceof Jt))throw new Error("No geometry provided.");let e=t.positions??[],s=t.indices??[];this.tris=[];for(let i=0;i<s.length;i+=3){let r=s[i],a=s[i+1],o=s[i+2];DH.set(e[r*3],e[r*3+1],e[r*3+2]),LH.set(e[a*3],e[a*3+1],e[a*3+2]),MH.set(e[o*3],e[o*3+1],e[o*3+2]);let l=new cd(DH,LH,MH);this.tris.push(l)}}};var rC={uniqueName:"gizmo-unlit",attributes:{vertex_position:ee},vertexGLSL:`
attribute vec3 vertex_position;
uniform mat4 matrix_model;
uniform mat4 matrix_viewProjection;
void main(void) {
gl_Position = matrix_viewProjection * matrix_model * vec4(vertex_position, 1.0);
gl_Position.z = clamp(gl_Position.z, -abs(gl_Position.w), abs(gl_Position.w));
}
`,fragmentGLSL:`
#include "gammaPS"
precision highp float;
uniform vec4 uColor;
uniform float uDepth;
void main(void) {
if (uColor.a < 1.0 / 255.0) {
discard;
}
gl_FragColor = vec4(gammaCorrectOutput(decodeGamma(uColor)), uColor.a);
#if DEPTH_WRITE == 1
gl_FragDepth = uDepth;
#endif
}
`,vertexWGSL:`
attribute vertex_position: vec3f;
uniform matrix_model: mat4x4f;
uniform matrix_viewProjection: mat4x4f;
@vertex
fn vertexMain(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
let pos = vec4f(input.vertex_position, 1.0);
output.position = uniform.matrix_viewProjection * uniform.matrix_model * pos;
output.position.z = clamp(output.position.z, -abs(output.position.w), abs(output.position.w));
return output;
}
`,fragmentWGSL:`
#include "gammaPS"
uniform uColor: vec4f;
uniform uDepth: f32;
@fragment
fn fragmentMain(input: FragmentInput) -> FragmentOutput {
var output: FragmentOutput;
if (uniform.uColor.a < 1.0 / 255.0) {
discard;
}
output.color = vec4f(gammaCorrectOutput(decodeGamma(uniform.uColor)), uniform.uColor.a);
#if DEPTH_WRITE == 1
output.fragDepth = uniform.uDepth;
#endif
return output;
}
`};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;e<this.meshInstances.length;e++)this.meshInstances[e].visible=t;this._visible=t}}get visible(){return this._visible}_createRenderComponent(t,e){let s=this._disabled?this._disabledColor:this._defaultColor;this._material.setDefine("DEPTH_WRITE",this._depth>0?"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<e.length;r++){let a=new we(e[r],this._material);a.cull=!1,i.push(a),this.meshInstances.push(a)}t.addComponent("render",{meshInstances:i,layers:this._layers,castShadows:!1})}_update(){this.entity.setLocalPosition(this._position),this.entity.setLocalEulerAngles(this._rotation),this.entity.setLocalScale(this._scale)}hover(t){let e=this._disabled?this._disabledColor:t?this._hoverColor:this._defaultColor;this._material.setParameter("uColor",e.toArray())}destroy(){this.entity.destroy()}};var K9=1e-6,un=class extends hr{constructor(e,s={}){super(e,"plane",s);n(this,"_cull",0);n(this,"_size",.16);n(this,"_gap",0);n(this,"_flipped",new x);this._size=s.size??this._size,this._gap=s.gap??this._gap,this.triData=[new ui(new $a)],this._createRenderComponent(this.entity,[_e.fromGeometry(this.device,new $a)]),this._update()}set size(e){this._size=e??this._size,this._update()}get size(){return this._size}set gap(e){this._gap=e??this._gap,this._update()}get gap(){return this._gap}set flipped(e){this._flipped.distance(e)<K9||(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)}};var aC=new x,oC=new x,nC=new $,pg=class extends hr{constructor(e,s={}){super(e,"arrow",s);n(this,"_gap",0);n(this,"_lineThickness",.02);n(this,"_lineLength",.5);n(this,"_arrowThickness",.12);n(this,"_arrowLength",.18);n(this,"_tolerance",.1);n(this,"_head");n(this,"_line");this._gap=s.gap??this._gap,this._lineThickness=s.lineThickness??this._lineThickness,this._lineLength=s.lineLength??this._lineLength,this._arrowThickness=s.arrowThickness??this._arrowThickness,this._arrowLength=s.arrowLength??this._arrowLength,this._tolerance=s.tolerance??this._tolerance,this.triData=[new ui(new qa),new ui(new Ci,1)],this._head=new Ne(`head:${this.axis}`),this.entity.addChild(this._head),this._createRenderComponent(this._head,[_e.fromGeometry(this.device,new qa)]),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 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(){aC.set(0,this._gap+this._arrowLength*.5+this._lineLength,0),nC.set(0,0,0,1),oC.set(this._arrowThickness,this._arrowLength,this._arrowThickness),this.triData[0].setTransform(aC,nC,oC),aC.set(0,this._gap+this._lineLength*.5,0),nC.set(0,0,0,1),oC.set(this._lineThickness+this._tolerance,this._lineLength,this._lineThickness+this._tolerance),this.triData[1].setTransform(aC,nC,oC),this._head.setLocalPosition(0,this._gap+this._arrowLength*.5+this._lineLength,0),this._head.setLocalScale(this._arrowThickness,this._arrowLength,this._arrowThickness),this._line.setLocalPosition(0,this._gap+this._lineLength*.5,0),this._line.setLocalScale(this._lineThickness,this._lineLength,this._lineThickness)}};var mg=class extends hr{constructor(e,s={}){super(e,"sphereCenter",s);n(this,"_radius",.03);this._radius=s.radius??this._radius,this.triData=[new ui(new wr,2)],this._createRenderComponent(this.entity,[_e.fromGeometry(this.device,new wr({latitudeBands:32,longitudeBands:32}))]),this._update()}set radius(e){this._radius=e??this._radius,this._update()}get radius(){return this._radius}_update(){let e=this._radius*2;this.entity.setLocalScale(e,e,e)}};var ti=new x,fo=new x,_g=new x,j9=new x,FH=new $,gg=.01,q9=["x","y","z"],lC=class extends is{constructor(e,s){super(e,s,"gizmo:translate");n(this,"_shapes",{xyz:new mg(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 pg(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 pg(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 pg(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,"_nodeLocalPositions",new Map);n(this,"_nodePositions",new Map);n(this,"snapIncrement",1);n(this,"flipPlanes",!0);this._createTransform(),this.on(is.EVENT_TRANSFORMSTART,()=>{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.nodes.length;e++){let s=this.nodes[e];this._nodeLocalPositions.set(s,s.getLocalPosition().clone()),this._nodePositions.set(s,s.getPosition().clone())}}_setNodePositions(e){for(let s=0;s<this.nodes.length;s++){let i=this.nodes[s];if(this._coordSpace==="local"){let r=this._nodeLocalPositions.get(i);if(!r)continue;ti.copy(e),i.parent?.getWorldTransform().getScale(fo),fo.x=1/fo.x,fo.y=1/fo.y,fo.z=1/fo.z,FH.copy(i.getLocalRotation()).transformVector(ti,ti),ti.mul(fo),i.setLocalPosition(ti.add(r))}else{let r=this._nodePositions.get(i);if(!r)continue;i.setPosition(ti.copy(e).add(r))}}this._updatePosition()}_screenToPoint(e,s){let i=this._camera.screenToWorld(e,s,1),r=this._selectedAxis,a=this._selectedIsPlane,o=this._createRay(i);return this._createPlane(r,r==="xyz",!a).intersectsRay(o,_g)&&(FH.copy(this._rootStartRot).invert().transformVector(_g,_g),!a&&r!=="xyz"&&this._projectToAxis(_g,r)),_g}_drawGuideLines(e,s,i,r){for(let a of q9){if(this._dragging||i==="xyz"){this._drawSpanLine(e,s,a);continue}r?a!==i&&this._drawSpanLine(e,s,a):a===i&&this._drawSpanLine(e,s,a)}}prerender(){super.prerender(),this.enabled&&this._shapesLookAtCamera()}};var $9=80,Z9=20,Nh=class extends hr{constructor(e,s={}){super(e,"disk",s);n(this,"_tubeRadius",.01);n(this,"_ringRadius",.5);n(this,"_sectorAngle",360);n(this,"_tolerance",.05);n(this,"_triDataCache");this._tubeRadius=s.tubeRadius??this._tubeRadius,this._ringRadius=s.ringRadius??this._ringRadius,this._sectorAngle=s.sectorAngle??this._sectorAngle,this._triDataCache=[new ui(this._createTorusGeometry(this._sectorAngle)),new ui(this._createTorusGeometry(360))],this.triData=[this._triDataCache[0]],this._createRenderComponent(this.entity,[this._createTorusMesh(this._sectorAngle),this._createTorusMesh(360)]),this.show("sector"),this._update()}_createTorusGeometry(e){return new Za({tubeRadius:this._tubeRadius+this._tolerance,ringRadius:this._ringRadius,sectorAngle:e,segments:Z9})}_createTorusMesh(e){let s=new Za({tubeRadius:this._tubeRadius,ringRadius:this._ringRadius,sectorAngle:e,segments:$9});return _e.fromGeometry(this.device,s)}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=!0,this.meshInstances[1].visible=!1;break}case"ring":{this.triData[0]=this._triDataCache[1],this.meshInstances[0].visible=!1,this.meshInstances[1].visible=!0;break}case"none":{this.meshInstances[0].visible=!1,this.meshInstances[1].visible=!1;break}}}};var Q9=new x,Ax=class{constructor(t,e,s={}){n(this,"_thickness",.02);n(this,"_material",new ct(rC));n(this,"entity",new Ne("mesh-line"));this._thickness=s.thickness??this._thickness,this._material.blendState=Oe.ALPHABLEND,this._material.setDefine("DEPTH_WRITE","1"),this._material.setParameter("uDepth",0),this._material.update();let i=_e.fromGeometry(t.graphicsDevice,new Ci),r=new we(i,this._material);this.entity.addComponent("render",{meshInstances:[r],layers:[e.id]})}set thickness(t){this._thickness=t??this._thickness}get thickness(){return this._thickness}draw(t,e,s,i){this._material.setParameter("uColor",i.toArray());let r=Q9.sub2(e,t).normalize(),a=Math.atan2(-r.y,Math.sqrt(r.x*r.x+r.z*r.z))*R.RAD_TO_DEG,o=Math.atan2(-r.x,-r.z)*R.RAD_TO_DEG;this.entity.setLocalEulerAngles(-a+90,o,0);let l=t.distance(e)*s;this.entity.setLocalPosition(r.mulScalar(.5*l).add(t)),this.entity.setLocalScale(this._thickness*s,l,this._thickness*s)}destroy(){this._material.destroy(),this.entity.destroy()}};var cC=new x,Ke=new x,$u=new x,NH=new x,Sa=new $,hC=new $,J9=new F,fC=1e-4,e7=1e-6,t7=["x","y","z"],uC=class extends is{constructor(e,s){super(e,s,"gizmo:rotate");n(this,"_shapes",{z:new Nh(this._device,{axis:"z",layers:[this._layer.id],rotation:new x(90,0,90),defaultColor:this._theme.shapeBase.z,hoverColor:this._theme.shapeHover.z,disabledColor:this._theme.disabled,sectorAngle:180}),x:new Nh(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,sectorAngle:180}),y:new Nh(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,sectorAngle:180}),f:new Nh(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 mg(this._device,{axis:"xyz",layers:[this._layer.id],defaultColor:this._theme.shapeBase.xyz,hoverColor:this._theme.shapeHover.xyz,disabledColor:this._theme.disabled,radius:.5})});n(this,"_selectionStartAngle",0);n(this,"_nodeLocalRotations",new Map);n(this,"_nodeRotations",new Map);n(this,"_nodeOffsets",new Map);n(this,"_screenPos",new B);n(this,"_screenStartPos",new B);n(this,"_guideAngleStart",new x);n(this,"_guideAngleEnd",new x);n(this,"_guideAngleLines");n(this,"_facingDir",new x);n(this,"snapIncrement",5);n(this,"rotationMode","absolute");this.setTheme({shapeBase:{xyz:new F(0,0,0,0)},shapeHover:{xyz:new F(1,1,1,.2)}}),this._createTransform(),this._guideAngleLines=[new Ax(this._app,this._layer),new Ax(this._app,this._layer)],this._guideAngleLines.forEach(i=>{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;s<this.nodes.length;s++){let i=this.nodes[s];this._nodeLocalRotations.set(i,i.getLocalRotation().clone()),this._nodeRotations.set(i,i.getRotation().clone()),this._nodeOffsets.set(i,i.getPosition().clone().sub(e))}}_setNodeRotations(e,s,i){let r=this.root.getLocalPosition();Sa.setFromAxisAngle(s,i);for(let a=0;a<this.nodes.length;a++){let o=this.nodes[a];if((e==="x"||e==="y"||e==="z")&&this._coordSpace==="local"){let l=this._nodeLocalRotations.get(o);if(!l)continue;hC.copy(l).mul(Sa),o.setLocalRotation(hC)}else{let l=this._nodeRotations.get(o);if(!l)continue;let h=this._nodeOffsets.get(o);if(!h)continue;Ke.copy(h),Sa.transformVector(Ke,Ke),hC.copy(Sa).mul(l),o.setRotation(hC),o.setPosition(Ke.add(r))}}this._coordSpace==="local"&&this._updateRotation()}_screenToPoint(e,s){let i=this._camera.screenToWorld(e,s,1),r=this._selectedAxis,a=this._createRay(i),o=this._createPlane(r,r==="f"||r==="xyz",!1);if(!o.intersectsRay(a,cC)){a.direction.mulScalar(-1);let l=o.intersectsRay(a,cC);if(a.direction.mulScalar(-1),!l)return cC.copy(this.root.getLocalPosition())}return cC}_calculateArcAngle(e,s,i){let r=this.root.getLocalPosition(),a=this._selectedAxis,o=this._createPlane(a,a==="f",!1),l=0,h=this.facingDir,f=o.normal.dot(h);switch(this.rotationMode){case"absolute":{if(this._camera.worldToScreen(r,$u),a==="f"||f>1-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.nodes.length;e++){let s=this.nodes[e];this._nodeScales.set(s,s.getLocalScale().clone())}}_setNodeScales(e){for(let s=0;s<this.nodes.length;s++){let i=this.nodes[s],r=this._nodeScales.get(i);r&&i.setLocalScale(si.copy(r).mul(e).max(this.lowerBoundScale))}}_screenToPoint(e,s){let i=this.root.getLocalPosition(),r=this._camera.screenToWorld(e,s,1),a=this._selectedAxis,o=this._selectedIsPlane,l=this._createRay(r);if(!this._createPlane(a,a==="xyz",!o).intersectsRay(l,xa))return xa;if(a==="xyz"){let f=_C.add2(this._camera.entity.up,this._camera.entity.right).normalize(),u=si.sub2(xa,i),d=u.length()*u.normalize().dot(f);return xa.set(d,d,d),xa}return i7.copy(this._rootStartRot).invert().transformVector(xa,xa),o||this._projectToAxis(xa,a),this._uniform&&o&&(si.set(1,1,1),si[a]=0,xa.copy(si.mulScalar(si.dot(xa))),xa[a]=0),xa}prerender(){super.prerender(),this.enabled&&this._shapesLookAtCamera()}};var Ul=new x,kl=new x,zl=new x,SC=new W,Gl=class Gl extends J{constructor(e){super();n(this,"_size",0);n(this,"_svg");n(this,"_group");n(this,"_anchor",new Q(1,1,1,1));n(this,"_colorX",fg.clone());n(this,"_colorY",ug.clone());n(this,"_colorZ",dg.clone());n(this,"_colorNeg",new F(.3,.3,.3));n(this,"_radius",10);n(this,"_textSize",10);n(this,"_lineThickness",2);n(this,"_lineLength",40);n(this,"_shapes");this.dom=document.createElement("div"),this.dom.id="view-cube-container",this.dom.style.cssText=["position: absolute","margin: auto","pointer-events: none"].join(";"),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 s=this._colorX.toString(!1),i=this._colorY.toString(!1),r=this._colorZ.toString(!1);this._shapes={nx:this._circle(s),ny:this._circle(i),nz:this._circle(r),px:this._circle(s,!0,"X"),py:this._circle(i,!0,"Y"),pz:this._circle(r,!0,"Z"),xaxis:this._line(s),yaxis:this._line(i),zaxis:this._line(r)},this._shapes.px.children[0].addEventListener("pointerdown",()=>{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);
}
}));