/** * @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;e0){r=r.slice(0,r.length-2);continue}a>0&&r.push(xe.delimiter),r.push(s[a])}return i=r.join(""),!t&&i[0]===xe.delimiter&&(i=i.slice(1)),e&&i[i.length-1]!==xe.delimiter&&(i+=xe.delimiter),i},split(c){let t=c.lastIndexOf(xe.delimiter);return t!==-1?[c.substring(0,t),c.substring(t+1)]:["",c]},getBasename(c){return xe.split(c)[1]},getDirectory(c){return xe.split(c)[0]},getExtension(c){let t=c.split("?")[0].split(".").pop();return t!==c?`.${t}`:""},isRelativePath(c){return c.charAt(0)!=="/"&&c.match(/:\/\//)===null},extractPath(c){let t="",e=c.split("/"),s=0;if(e.length>1)if(xe.isRelativePath(c))if(e[0]===".")for(s=0;s{let c=!1;try{let t=Object.defineProperty({},"passive",{get:function(){return c=!0,!1}});window.addEventListener("testpassive",null,t),window.removeEventListener("testpassive",null,t)}catch{}return c},Fr=typeof navigator<"u"?navigator.userAgent:"",dn=typeof window<"u"?"browser":typeof global<"u"?"node":"worker",vg=/android/i.test(Fr)?"android":/ip(?:[ao]d|hone)/i.test(Fr)?"ios":/windows/i.test(Fr)?"windows":/mac os/i.test(Fr)?"osx":/linux/i.test(Fr)?"linux":/cros/i.test(Fr)?"cros":null,_4=dn!=="browser"?null:/Chrome\/|Chromium\/|Edg.*\//.test(Fr)?"chrome":/Safari\//.test(Fr)?"safari":/Firefox\//.test(Fr)?"firefox":"other",g4=/xbox/i.test(Fr),S4=/Macintosh/i.test(Fr)&&typeof navigator<"u"&&navigator.maxTouchPoints>0&&!/iPhone|iPad|iPod/i.test(Fr),x4=dn==="browser"&&("ontouchstart"in window||"maxTouchPoints"in navigator&&navigator.maxTouchPoints>0),v4=dn==="browser"&&(!!navigator.getGamepads||!!navigator.webkitGetGamepads),T4=typeof Worker<"u",y4=m4(),ue={name:vg,environment:dn,global:(typeof globalThis<"u"&&globalThis)??(dn==="browser"&&window)??(dn==="node"&&global)??(dn==="worker"&&self),browser:dn==="browser",worker:dn==="worker",desktop:["windows","osx","linux","cros"].includes(vg),mobile:["android","ios"].includes(vg),ios:vg==="ios",android:vg==="android",visionos:S4,xbox:g4,gamepads:v4,touch:x4,workers:T4,passiveEvents:y4,browserName:_4};var aD="abcdefghijklmnopqrstuvwxyz",oD="ABCDEFGHIJKLMNOPQRSTUVWXYZ",E4=aD+oD,CC=55296,nD=56319,sD=56320,A4=57343,C4=8205,iD=127462,rD=127487,P4=127995,w4=127999,I4=8400,R4=8447,PC=65024,wC=65039;function IC(c,t=0){let e=c.length;if(t<0||t>=e)return null;let s=c.charCodeAt(t);if(e>1&&s>=CC&&s<=nD){let i=c.charCodeAt(t+1);if(i>=sD&&i<=A4)return{code:(s-CC)*1024+i-sD+65536,long:!0}}return{code:s,long:!1}}function Xl(c,t,e){if(!c)return!1;let s=IC(c);if(s){let i=s.code;return i>=t&&i<=e}return!1}function b4(c,t){if(t===c.length-1)return 1;if(Xl(c[t],CC,nD)){let e=c.substring(t,t+2),s=c.substring(t+2,t+4);return Xl(s,P4,w4)||Xl(e,iD,rD)&&Xl(s,iD,rD)?4:Xl(s,PC,wC)?3:2}return Xl(c[t+1],PC,wC)?2:1}var Nr={ASCII_LOWERCASE:aD,ASCII_UPPERCASE:oD,ASCII_LETTERS:E4,format(c,...t){for(let e=0;et>65535?(t-=65536,String.fromCharCode((t>>10)+55296,t%1024+56320)):String.fromCharCode(t)).join("")}};var Tg=class Tg{static set(t,e=!0){}static get(t){return Tg._traceChannels.has(t)}};n(Tg,"_traceChannels",new Set),n(Tg,"stack",!1);var ed=Tg;var td=class{constructor(t,e,s,i,r=!1){n(this,"handler");n(this,"name");n(this,"callback");n(this,"scope");n(this,"_once");n(this,"_removed",!1);this.handler=t,this.name=e,this.callback=s,this.scope=i,this._once=r}off(){this._removed||this.handler.offByHandle(this)}on(t,e,s=this){return this.handler._addCallback(t,e,s,!1)}once(t,e,s=this){return this.handler._addCallback(t,e,s,!0)}set removed(t){t&&(this._removed=!0)}get removed(){return this._removed}toJSON(t){}};var J=class{constructor(){n(this,"_callbacks",new Map);n(this,"_callbackActive",new Map)}initEventHandler(){this._callbacks=new Map,this._callbackActive=new Map}_addCallback(t,e,s,i){if(this._callbacks.has(t)||this._callbacks.set(t,[]),this._callbackActive.has(t)){let a=this._callbackActive.get(t);a&&a===this._callbacks.get(t)&&this._callbackActive.set(t,a.slice())}let r=new td(this,t,e,s,i);return this._callbacks.get(t).push(r),r}on(t,e,s=this){return this._addCallback(t,e,s,!1)}once(t,e,s=this){return this._addCallback(t,e,s,!0)}off(t,e,s){if(t)this._callbackActive.has(t)&&this._callbackActive.get(t)===this._callbacks.get(t)&&this._callbackActive.set(t,this._callbackActive.get(t).slice());else for(let[i,r]of this._callbackActive)this._callbacks.has(i)&&this._callbacks.get(i)===r&&this._callbackActive.set(i,r.slice());if(t)if(e){let i=this._callbacks.get(t);if(!i)return this;for(let r=0;re&&(this._index[t]=s-1)}return!0}return!1}list(){return this._list}clear(){this._list.length=0;for(let t in this._index)delete this._index[t]}};var D4=c=>{let t={},e=t;return()=>(e===t&&(e=c()),e)},uo=class uo{static loadScript(t,e){let s=document.createElement("script");s.setAttribute("src",t),s.onload=()=>{e(null)},s.onerror=()=>{e(`Failed to load script='${t}'`)},document.body.appendChild(s)}static loadWasm(t,e,s){let i=uo.wasmSupported()&&e.glueUrl&&e.wasmUrl?e.glueUrl:e.fallbackUrl;i?uo.loadScript(i,r=>{if(r)s(r,null);else{let a=window[t];window[t]=void 0,a({locateFile:()=>e.wasmUrl,onAbort:()=>{s("wasm module aborted.")}}).then(o=>{s(null,o)})}}):s("No supported wasm modules found.",null)}static getModule(t){return uo.modules.hasOwnProperty(t)||(uo.modules[t]={config:null,initializing:!1,instance:null,callbacks:[]}),uo.modules[t]}static initialize(t,e){if(e.initializing)return;let s=e.config;(s.glueUrl||s.wasmUrl||s.fallbackUrl)&&(e.initializing=!0,uo.loadWasm(t,s,(i,r)=>{i?s.errorHandler&&s.errorHandler(i):(e.instance=r,e.callbacks.forEach(a=>{a(r)}))}))}};n(uo,"modules",{}),n(uo,"wasmSupported",D4(()=>{try{if(typeof WebAssembly=="object"&&typeof WebAssembly.instantiate=="function"){let t=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(t instanceof WebAssembly.Module)return new WebAssembly.Instance(t)instanceof WebAssembly.Instance}}catch{}return!1}));var Bh=uo,Yl=class{static setConfig(t,e){let s=Bh.getModule(t);s.config=e,s.callbacks.length>0&&Bh.initialize(t,s)}static getConfig(t){return Bh.modules?.[t]?.config}static getInstance(t,e){let s=Bh.getModule(t);s.instance?e(s.instance):(s.callbacks.push(e),s.config&&Bh.initialize(t,s))}};var Kl=class{constructor(t){n(this,"arraybuffer");n(this,"dataView");n(this,"offset",0);this.arraybuffer=t,this.dataView=new DataView(t)}get remainingBytes(){return this.dataView.byteLength-this.offset}reset(t=0){this.offset=t}skip(t){this.offset+=t}align(t){this.offset=this.offset+t-1&~(t-1)}_inc(t){return this.offset+=t,this.offset-t}readChar(){return String.fromCharCode(this.dataView.getUint8(this.offset++))}readChars(t){let e="";for(let s=0;s=t.byteLength);){let s=String.fromCharCode(this.readU8());if(s===` `)break;e+=s}return e}};var po=class{constructor(t){n(this,"items",[]);n(this,"length",0);n(this,"loopIndex",-1);n(this,"_sortBy");n(this,"_sortHandler");this._sortBy=t.sortBy,this._sortHandler=this._doSort.bind(this)}_binarySearch(t){let e=0,s=this.items.length-1,i=t[this._sortBy],r,a;for(;e<=s;)r=Math.floor((e+s)/2),a=this.items[r][this._sortBy],a<=i?e=r+1:a>i&&(s=r-1);return e}_doSort(t,e){let s=this._sortBy;return t[s]-e[s]}insert(t){let e=this._binarySearch(t);this.items.splice(e,0,t),this.length++,this.loopIndex>=e&&this.loopIndex++}append(t){this.items.push(t),this.length++}remove(t){let e=this.items.indexOf(t);e<0||(this.items.splice(e,1),this.length--,this.loopIndex>=e&&this.loopIndex--)}sort(){let t=this.loopIndex>=0?this.items[this.loopIndex]:null;this.items.sort(this._sortHandler),t!==null&&(this.loopIndex=this.items.indexOf(t))}};var va=class extends J{constructor(e){super();n(this,"_index",{});n(this,"_list",[]);n(this,"_parent");this._parent=e}add(...e){let s=!1,i=this._processArguments(e,!0);if(!i.length)return s;for(let r=0;r=e?e:c<=t?t:c},intToBytes24(c){let t=c>>16&255,e=c>>8&255,s=c&255;return[t,e,s]},intToBytes32(c){let t=c>>24&255,e=c>>16&255,s=c>>8&255,i=c&255;return[t,e,s,i]},bytesToInt24(c,t,e){return c.length&&(e=c[2],t=c[1],c=c[0]),c<<16|t<<8|e},bytesToInt32(c,t,e,s){return c.length&&(s=c[3],e=c[2],t=c[1],c=c[0]),(c<<24|t<<16|e<<8|s)>>>0},lerp(c,t,e){return c+(t-c)*R.clamp(e,0,1)},lerpAngle(c,t,e){return t-c>180&&(t-=360),t-c<-180&&(t+=360),R.lerp(c,t,R.clamp(e,0,1))},powerOfTwo(c){return c!==0&&!(c&c-1)},nextPowerOfTwo(c){return c--,c|=c>>1,c|=c>>2,c|=c>>4,c|=c>>8,c|=c>>16,c++,c},nearestPowerOfTwo(c){return Math.pow(2,Math.round(Math.log2(c)))},random(c,t){let e=t-c;return Math.random()*e+c},smoothstep(c,t,e){return e<=c?0:e>=t?1:(e=(e-c)/(t-c),e*e*(3-2*e))},smootherstep(c,t,e){return e<=c?0:e>=t?1:(e=(e-c)/(t-c),e*e*e*(e*(e*6-15)+10))},roundUp(c,t){return t===0?c:Math.ceil(c/t)*t},between(c,t,e,s){let i=Math.min(t,e),r=Math.max(t,e);return s?c>=i&&c<=r:c>i&&c7?s=R.intToBytes32(e):(s=R.intToBytes24(e),s[3]=255),this.set(s[0]/255,s[1]/255,s[2]/255,s[3]/255),this}fromArray(t,e=0){return this.r=t[e]??this.r,this.g=t[e+1]??this.g,this.b=t[e+2]??this.b,this.a=t[e+3]??this.a,this}toString(t,e){let{r:s,g:i,b:r,a}=this;if(e||s>1||i>1||r>1)return`${s.toFixed(3)}, ${i.toFixed(3)}, ${r.toFixed(3)}, ${a.toFixed(3)}`;let o=`#${((1<<24)+(Math.round(s*255)<<16)+(Math.round(i*255)<<8)+Math.round(r*255)).toString(16).slice(1)}`;if(t===!0){let l=Math.round(a*255).toString(16);this.a<16/255?o+=`0${l}`:o+=l}return o}toArray(t=[],e=0,s=!0){return t[e]=this.r,t[e+1]=this.g,t[e+2]=this.b,s&&(t[e+3]=this.a),t}};n(ps,"BLACK",Object.freeze(new ps(0,0,0,1))),n(ps,"BLUE",Object.freeze(new ps(0,0,1,1))),n(ps,"CYAN",Object.freeze(new ps(0,1,1,1))),n(ps,"GRAY",Object.freeze(new ps(.5,.5,.5,1))),n(ps,"GREEN",Object.freeze(new ps(0,1,0,1))),n(ps,"MAGENTA",Object.freeze(new ps(1,0,1,1))),n(ps,"RED",Object.freeze(new ps(1,0,0,1))),n(ps,"WHITE",Object.freeze(new ps(1,1,1,1))),n(ps,"YELLOW",Object.freeze(new ps(1,1,0,1)));var F=ps;var id=class{constructor(t,e=0){n(this,"_curve");n(this,"_left",-1/0);n(this,"_right",1/0);n(this,"_recip",0);n(this,"_p0",0);n(this,"_p1",0);n(this,"_m0",0);n(this,"_m1",0);this._curve=t,this._reset(e)}evaluate(t,e=!1){(e||t=this._right)&&this._reset(t);let s,i=this._curve.type;if(i===5)s=this._p0;else{let r=this._recip===0?0:(t-this._left)*this._recip;i===0?s=R.lerp(this._p0,this._p1,r):i===1?s=R.lerp(this._p0,this._p1,r*r*(3-2*r)):s=this._evaluateHermite(this._p0,this._p1,this._m0,this._m1,r)}return s}_reset(t){let e=this._curve.keys,s=e.length;if(!s)this._left=-1/0,this._right=1/0,this._recip=0,this._p0=this._p1=this._m0=this._m1=0;else if(t=e[s-1][0])this._left=e[s-1][0],this._right=1/0,this._recip=0,this._p0=this._p1=e[s-1][1],this._m0=this._m1=0;else{let i=0;for(;t>=e[i+1][0];)i++;this._left=e[i][0],this._right=e[i+1][0];let r=1/(this._right-this._left);this._recip=isFinite(r)?r:0,this._p0=e[i][1],this._p1=e[i+1][1],this._curve.type===4&&this._calcTangents(e,i)}}_calcTangents(t,e){let s,i=t[e],r=t[e+1],a;if(e===0?s=[t[0][0]+(t[0][0]-t[1][0]),t[0][1]+(t[0][1]-t[1][1])]:s=t[e-1],e===t.length-2?a=[t[e+1][0]+(t[e+1][0]-t[e][0]),t[e+1][1]+(t[e+1][1]-t[e][1])]:a=t[e+2],this._curve.type===4){let o=2*(r[0]-i[0])/(r[0]-s[0]),l=2*(r[0]-i[0])/(a[0]-i[0]);this._m0=this._curve.tension*(isFinite(o)?o:0)*(r[1]-s[1]),this._m1=this._curve.tension*(isFinite(l)?l:0)*(a[1]-i[1])}else{let o=(r[0]-i[0])/(i[0]-s[0]),l=(r[0]-i[0])/(a[0]-r[0]),h=i[1]+(s[1]-i[1])*(isFinite(o)?o:0),f=r[1]+(a[1]-r[1])*(isFinite(l)?l:0),u=this._curve.tension;this._m0=u*(r[1]-h),this._m1=u*(f-i[1])}}_evaluateHermite(t,e,s,i,r){let a=r*r,o=r+r,l=1-r,h=l*l;return t*((1+o)*h)+s*(r*h)+e*(a*(3-o))+i*(a*(r-1))}};var Ps=class{constructor(t){n(this,"keys",[]);n(this,"type",1);n(this,"tension",.5);n(this,"_eval",new id(this));if(t)for(let e=0;et);r++);let a=[t,e];return this.keys.splice(r,0,a),a}get(t){return this.keys[t]}sort(){this.keys.sort((t,e)=>t[0]-e[0])}value(t){return this._eval.evaluate(t,!0)}closest(t){let e=this.keys,s=e.length,i=2,r=null;for(let a=0;a=o)i=o,r=e[a];else break}return r}clone(){let t=new this.constructor;return t.keys=this.keys.map(e=>[...e]),t.type=this.type,t.tension=this.tension,t}quantize(t){t=Math.max(t,2);let e=new Float32Array(t),s=1/(t-1);e[0]=this._eval.evaluate(0,!0);for(let i=1;i1)for(let e=0;e>16&32768,i=e>>12&2047,r=e>>23&255;return r<103?s:r>142?(s|=31744,s|=(r===255?0:1)&&e&8388607,s):r<113?(i|=2048,s|=(i>>114-r)+(i>>113-r&1),s):(s|=r-112<<10|i>>1,s+=i&1,s)}static float2RGBA8(t,e){bC[0]=t;let s=hD[0];e.r=(s>>24&255)/255,e.g=(s>>16&255)/255,e.b=(s>>8&255)/255,e.a=(s&255)/255}};var rd=class{static concentric(t,e){let s=[];s.push(0,0);let i=2*Math.PI/t/e;for(let r=1;r<=t;r++){let a=r/t,o=2*Math.PI*a,l=Math.max(1,Math.floor(o/i)),h=2*Math.PI/l;for(let f=0;f0){let s=1/Math.sqrt(e);this.x=t.x*s,this.y=t.y*s,this.z=t.z*s}return this}floor(t=this){return this.x=Math.floor(t.x),this.y=Math.floor(t.y),this.z=Math.floor(t.z),this}ceil(t=this){return this.x=Math.ceil(t.x),this.y=Math.ceil(t.y),this.z=Math.ceil(t.z),this}round(t=this){return this.x=Math.round(t.x),this.y=Math.round(t.y),this.z=Math.round(t.z),this}min(t){return t.xthis.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this}project(t){let e=this.x*t.x+this.y*t.y+this.z*t.z,s=t.x*t.x+t.y*t.y+t.z*t.z,i=e/s;return this.x=t.x*i,this.y=t.y*i,this.z=t.z*i,this}set(t,e,s){return this.x=t,this.y=e,this.z=s,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}sub2(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}fromArray(t,e=0){return this.x=t[e]??this.x,this.y=t[e+1]??this.y,this.z=t[e+2]??this.z,this}toString(){return`[${this.x}, ${this.y}, ${this.z}]`}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}};n(ms,"ZERO",Object.freeze(new ms(0,0,0))),n(ms,"HALF",Object.freeze(new ms(.5,.5,.5))),n(ms,"ONE",Object.freeze(new ms(1,1,1))),n(ms,"UP",Object.freeze(new ms(0,1,0))),n(ms,"DOWN",Object.freeze(new ms(0,-1,0))),n(ms,"RIGHT",Object.freeze(new ms(1,0,0))),n(ms,"LEFT",Object.freeze(new ms(-1,0,0))),n(ms,"FORWARD",Object.freeze(new ms(0,0,-1))),n(ms,"BACK",Object.freeze(new ms(0,0,1)));var x=ms;var ad=class ad{constructor(){n(this,"data",new Float32Array(9));this.data[0]=this.data[4]=this.data[8]=1}clone(){let t=this.constructor;return new t().copy(this)}copy(t){let e=t.data,s=this.data;return s[0]=e[0],s[1]=e[1],s[2]=e[2],s[3]=e[3],s[4]=e[4],s[5]=e[5],s[6]=e[6],s[7]=e[7],s[8]=e[8],this}set(t){let e=this.data;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],this}getX(t=new x){return t.set(this.data[0],this.data[1],this.data[2])}getY(t=new x){return t.set(this.data[3],this.data[4],this.data[5])}getZ(t=new x){return t.set(this.data[6],this.data[7],this.data[8])}equals(t){let e=this.data,s=t.data;return e[0]===s[0]&&e[1]===s[1]&&e[2]===s[2]&&e[3]===s[3]&&e[4]===s[4]&&e[5]===s[5]&&e[6]===s[6]&&e[7]===s[7]&&e[8]===s[8]}isIdentity(){let t=this.data;return t[0]===1&&t[1]===0&&t[2]===0&&t[3]===0&&t[4]===1&&t[5]===0&&t[6]===0&&t[7]===0&&t[8]===1}setIdentity(){let t=this.data;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=0,t[7]=0,t[8]=1,this}toString(){return`[${this.data.join(", ")}]`}transpose(t=this){let e=t.data,s=this.data;if(e===s){let i;i=e[1],s[1]=e[3],s[3]=i,i=e[2],s[2]=e[6],s[6]=i,i=e[5],s[5]=e[7],s[7]=i}else s[0]=e[0],s[1]=e[3],s[2]=e[6],s[3]=e[1],s[4]=e[4],s[5]=e[7],s[6]=e[2],s[7]=e[5],s[8]=e[8];return this}setFromMat4(t){let e=t.data,s=this.data;return s[0]=e[0],s[1]=e[1],s[2]=e[2],s[3]=e[4],s[4]=e[5],s[5]=e[6],s[6]=e[8],s[7]=e[9],s[8]=e[10],this}setFromQuat(t){let e=t.x,s=t.y,i=t.z,r=t.w,a=e+e,o=s+s,l=i+i,h=e*a,f=e*o,u=e*l,d=s*o,p=s*l,m=i*l,_=r*a,S=r*o,g=r*l,T=this.data;return T[0]=1-(d+m),T[1]=f+g,T[2]=u-S,T[3]=f-g,T[4]=1-(h+m),T[5]=p+_,T[6]=u+S,T[7]=p-_,T[8]=1-(h+d),this}invertMat4(t){let e=t.data,s=e[0],i=e[1],r=e[2],a=e[4],o=e[5],l=e[6],h=e[8],f=e[9],u=e[10],d=u*o-l*f,p=-u*i+r*f,m=l*i-r*o,_=-u*a+l*h,S=u*s-r*h,g=-l*s+r*a,T=f*a-o*h,C=-f*s+i*h,v=o*s-i*a,E=s*d+i*_+r*T;if(E===0)this.setIdentity();else{let y=1/E,P=this.data;P[0]=d*y,P[1]=p*y,P[2]=m*y,P[3]=_*y,P[4]=S*y,P[5]=g*y,P[6]=T*y,P[7]=C*y,P[8]=v*y}return this}transformVector(t,e=new x){let s=this.data,{x:i,y:r,z:a}=t;return e.x=i*s[0]+r*s[3]+a*s[6],e.y=i*s[1]+r*s[4]+a*s[7],e.z=i*s[2]+r*s[5]+a*s[8],e}};n(ad,"IDENTITY",Object.freeze(new ad)),n(ad,"ZERO",Object.freeze(new ad().set([0,0,0,0,0,0,0,0,0])));var Ws=ad;var pi=class pi{constructor(t=0,e=0){n(this,"x");n(this,"y");t.length===2?(this.x=t[0],this.y=t[1]):(this.x=t,this.y=e)}add(t){return this.x+=t.x,this.y+=t.y,this}add2(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addScaled(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}clone(){let t=this.constructor;return new t(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}cross(t){return this.x*t.y-this.y*t.x}distance(t){let e=this.x-t.x,s=this.y-t.y;return Math.sqrt(e*e+s*s)}div(t){return this.x/=t.x,this.y/=t.y,this}div2(t,e){return this.x=t.x/e.x,this.y=t.y/e.y,this}divScalar(t){return this.x/=t,this.y/=t,this}dot(t){return this.x*t.x+this.y*t.y}equals(t){return this.x===t.x&&this.y===t.y}equalsApprox(t,e=1e-6){return Math.abs(this.x-t.x)0){let s=1/Math.sqrt(e);this.x=t.x*s,this.y=t.y*s}return this}rotate(t){let e=Math.atan2(this.x,this.y)+t*R.DEG_TO_RAD,s=Math.sqrt(this.x*this.x+this.y*this.y);return this.x=Math.sin(e)*s,this.y=Math.cos(e)*s,this}angle(){return Math.atan2(this.x,this.y)*R.RAD_TO_DEG}angleTo(t){return Math.atan2(this.x*t.y+this.y*t.x,this.x*t.x+this.y*t.y)*R.RAD_TO_DEG}floor(t=this){return this.x=Math.floor(t.x),this.y=Math.floor(t.y),this}ceil(t=this){return this.x=Math.ceil(t.x),this.y=Math.ceil(t.y),this}round(t=this){return this.x=Math.round(t.x),this.y=Math.round(t.y),this}min(t){return t.xthis.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),this}set(t,e){return this.x=t,this.y=e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}sub2(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}subScalar(t){return this.x-=t,this.y-=t,this}fromArray(t,e=0){return this.x=t[e]??this.x,this.y=t[e+1]??this.y,this}toString(){return`[${this.x}, ${this.y}]`}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}static angleRad(t,e){return Math.atan2(t.x*e.y-t.y*e.x,t.x*e.x+t.y*e.y)}};n(pi,"ZERO",Object.freeze(new pi(0,0))),n(pi,"HALF",Object.freeze(new pi(.5,.5))),n(pi,"ONE",Object.freeze(new pi(1,1))),n(pi,"UP",Object.freeze(new pi(0,1))),n(pi,"DOWN",Object.freeze(new pi(0,-1))),n(pi,"RIGHT",Object.freeze(new pi(1,0))),n(pi,"LEFT",Object.freeze(new pi(-1,0)));var B=pi;var ql=class ql{constructor(t=0,e=0,s=0,i=0){n(this,"x");n(this,"y");n(this,"z");n(this,"w");t.length===4?(this.x=t[0],this.y=t[1],this.z=t[2],this.w=t[3]):(this.x=t,this.y=e,this.z=s,this.w=i)}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}add2(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addScaled(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}clone(){let t=this.constructor;return new t(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this}div(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this.w/=t.w,this}div2(t,e){return this.x=t.x/e.x,this.y=t.y/e.y,this.z=t.z/e.z,this.w=t.w/e.w,this}divScalar(t){return this.x/=t,this.y/=t,this.z/=t,this.w/=t,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}equals(t){return this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w}equalsApprox(t,e=1e-6){return Math.abs(this.x-t.x)0){let s=1/Math.sqrt(e);this.x=t.x*s,this.y=t.y*s,this.z=t.z*s,this.w=t.w*s}return this}floor(t=this){return this.x=Math.floor(t.x),this.y=Math.floor(t.y),this.z=Math.floor(t.z),this.w=Math.floor(t.w),this}ceil(t=this){return this.x=Math.ceil(t.x),this.y=Math.ceil(t.y),this.z=Math.ceil(t.z),this.w=Math.ceil(t.w),this}round(t=this){return this.x=Math.round(t.x),this.y=Math.round(t.y),this.z=Math.round(t.z),this.w=Math.round(t.w),this}min(t){return t.xthis.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this}set(t,e,s,i){return this.x=t,this.y=e,this.z=s,this.w=i,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}sub2(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}fromArray(t,e=0){return this.x=t[e]??this.x,this.y=t[e+1]??this.y,this.z=t[e+2]??this.z,this.w=t[e+3]??this.w,this}toString(){return`[${this.x}, ${this.y}, ${this.z}, ${this.w}]`}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}};n(ql,"ZERO",Object.freeze(new ql(0,0,0,0))),n(ql,"HALF",Object.freeze(new ql(.5,.5,.5,.5))),n(ql,"ONE",Object.freeze(new ql(1,1,1,1)));var Q=ql;var yg=new B,Ta=new x,mo=new x,_o=new x,Dx=new x,Uh=class Uh{constructor(){n(this,"data",new Float32Array(16));this.data[0]=this.data[5]=this.data[10]=this.data[15]=1}static _getPerspectiveHalfSize(t,e,s,i,r){r?(t.x=i*Math.tan(e*Math.PI/360),t.y=t.x/s):(t.y=i*Math.tan(e*Math.PI/360),t.x=t.y*s)}add2(t,e){let s=t.data,i=e.data,r=this.data;return r[0]=s[0]+i[0],r[1]=s[1]+i[1],r[2]=s[2]+i[2],r[3]=s[3]+i[3],r[4]=s[4]+i[4],r[5]=s[5]+i[5],r[6]=s[6]+i[6],r[7]=s[7]+i[7],r[8]=s[8]+i[8],r[9]=s[9]+i[9],r[10]=s[10]+i[10],r[11]=s[11]+i[11],r[12]=s[12]+i[12],r[13]=s[13]+i[13],r[14]=s[14]+i[14],r[15]=s[15]+i[15],this}add(t){return this.add2(this,t)}clone(){let t=this.constructor;return new t().copy(this)}copy(t){let e=t.data,s=this.data;return s[0]=e[0],s[1]=e[1],s[2]=e[2],s[3]=e[3],s[4]=e[4],s[5]=e[5],s[6]=e[6],s[7]=e[7],s[8]=e[8],s[9]=e[9],s[10]=e[10],s[11]=e[11],s[12]=e[12],s[13]=e[13],s[14]=e[14],s[15]=e[15],this}equals(t){let e=this.data,s=t.data;return e[0]===s[0]&&e[1]===s[1]&&e[2]===s[2]&&e[3]===s[3]&&e[4]===s[4]&&e[5]===s[5]&&e[6]===s[6]&&e[7]===s[7]&&e[8]===s[8]&&e[9]===s[9]&&e[10]===s[10]&&e[11]===s[11]&&e[12]===s[12]&&e[13]===s[13]&&e[14]===s[14]&&e[15]===s[15]}isIdentity(){let t=this.data;return t[0]===1&&t[1]===0&&t[2]===0&&t[3]===0&&t[4]===0&&t[5]===1&&t[6]===0&&t[7]===0&&t[8]===0&&t[9]===0&&t[10]===1&&t[11]===0&&t[12]===0&&t[13]===0&&t[14]===0&&t[15]===1}mul2(t,e){let s=t.data,i=e.data,r=this.data,a=s[0],o=s[1],l=s[2],h=s[3],f=s[4],u=s[5],d=s[6],p=s[7],m=s[8],_=s[9],S=s[10],g=s[11],T=s[12],C=s[13],v=s[14],E=s[15],y,P,A,w;return y=i[0],P=i[1],A=i[2],w=i[3],r[0]=a*y+f*P+m*A+T*w,r[1]=o*y+u*P+_*A+C*w,r[2]=l*y+d*P+S*A+v*w,r[3]=h*y+p*P+g*A+E*w,y=i[4],P=i[5],A=i[6],w=i[7],r[4]=a*y+f*P+m*A+T*w,r[5]=o*y+u*P+_*A+C*w,r[6]=l*y+d*P+S*A+v*w,r[7]=h*y+p*P+g*A+E*w,y=i[8],P=i[9],A=i[10],w=i[11],r[8]=a*y+f*P+m*A+T*w,r[9]=o*y+u*P+_*A+C*w,r[10]=l*y+d*P+S*A+v*w,r[11]=h*y+p*P+g*A+E*w,y=i[12],P=i[13],A=i[14],w=i[15],r[12]=a*y+f*P+m*A+T*w,r[13]=o*y+u*P+_*A+C*w,r[14]=l*y+d*P+S*A+v*w,r[15]=h*y+p*P+g*A+E*w,this}mulAffine2(t,e){let s=t.data,i=e.data,r=this.data,a=s[0],o=s[1],l=s[2],h=s[4],f=s[5],u=s[6],d=s[8],p=s[9],m=s[10],_=s[12],S=s[13],g=s[14],T,C,v;return T=i[0],C=i[1],v=i[2],r[0]=a*T+h*C+d*v,r[1]=o*T+f*C+p*v,r[2]=l*T+u*C+m*v,r[3]=0,T=i[4],C=i[5],v=i[6],r[4]=a*T+h*C+d*v,r[5]=o*T+f*C+p*v,r[6]=l*T+u*C+m*v,r[7]=0,T=i[8],C=i[9],v=i[10],r[8]=a*T+h*C+d*v,r[9]=o*T+f*C+p*v,r[10]=l*T+u*C+m*v,r[11]=0,T=i[12],C=i[13],v=i[14],r[12]=a*T+h*C+d*v+_,r[13]=o*T+f*C+p*v+S,r[14]=l*T+u*C+m*v+g,r[15]=1,this}mul(t){return this.mul2(this,t)}transformPoint(t,e=new x){let s=this.data,{x:i,y:r,z:a}=t;return e.x=i*s[0]+r*s[4]+a*s[8]+s[12],e.y=i*s[1]+r*s[5]+a*s[9]+s[13],e.z=i*s[2]+r*s[6]+a*s[10]+s[14],e}transformVector(t,e=new x){let s=this.data,{x:i,y:r,z:a}=t;return e.x=i*s[0]+r*s[4]+a*s[8],e.y=i*s[1]+r*s[5]+a*s[9],e.z=i*s[2]+r*s[6]+a*s[10],e}transformVec4(t,e=new Q){let s=this.data,{x:i,y:r,z:a,w:o}=t;return e.x=i*s[0]+r*s[4]+a*s[8]+o*s[12],e.y=i*s[1]+r*s[5]+a*s[9]+o*s[13],e.z=i*s[2]+r*s[6]+a*s[10]+o*s[14],e.w=i*s[3]+r*s[7]+a*s[11]+o*s[15],e}setLookAt(t,e,s){_o.sub2(t,e).normalize(),mo.copy(s).normalize(),Ta.cross(mo,_o).normalize(),mo.cross(_o,Ta);let i=this.data;return i[0]=Ta.x,i[1]=Ta.y,i[2]=Ta.z,i[3]=0,i[4]=mo.x,i[5]=mo.y,i[6]=mo.z,i[7]=0,i[8]=_o.x,i[9]=_o.y,i[10]=_o.z,i[11]=0,i[12]=t.x,i[13]=t.y,i[14]=t.z,i[15]=1,this}setFrustum(t,e,s,i,r,a){let o=2*r,l=e-t,h=i-s,f=a-r,u=this.data;return u[0]=o/l,u[1]=0,u[2]=0,u[3]=0,u[4]=0,u[5]=o/h,u[6]=0,u[7]=0,u[8]=(e+t)/l,u[9]=(i+s)/h,u[10]=(-a-r)/f,u[11]=-1,u[12]=0,u[13]=0,u[14]=-o*a/f,u[15]=0,this}setPerspective(t,e,s,i,r){return Uh._getPerspectiveHalfSize(yg,t,e,s,r),this.setFrustum(-yg.x,yg.x,-yg.y,yg.y,s,i)}setOrtho(t,e,s,i,r,a){let o=this.data;return o[0]=2/(e-t),o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=2/(i-s),o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=-2/(a-r),o[11]=0,o[12]=-(e+t)/(e-t),o[13]=-(i+s)/(i-s),o[14]=-(a+r)/(a-r),o[15]=1,this}setFromAxisAngle(t,e){e*=R.DEG_TO_RAD;let{x:s,y:i,z:r}=t,a=Math.cos(e),o=Math.sin(e),l=1-a,h=l*s,f=l*i,u=this.data;return u[0]=h*s+a,u[1]=h*i+o*r,u[2]=h*r-o*i,u[3]=0,u[4]=h*i-o*r,u[5]=f*i+a,u[6]=f*r+o*s,u[7]=0,u[8]=h*r+o*i,u[9]=f*r-s*o,u[10]=l*r*r+a,u[11]=0,u[12]=0,u[13]=0,u[14]=0,u[15]=1,this}setTranslate(t,e,s){let i=this.data;return i[0]=1,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=1,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=1,i[11]=0,i[12]=t,i[13]=e,i[14]=s,i[15]=1,this}setScale(t,e,s){let i=this.data;return i[0]=t,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=e,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=s,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,this}setViewport(t,e,s,i){let r=this.data;return r[0]=s*.5,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=i*.5,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=.5,r[11]=0,r[12]=t+s*.5,r[13]=e+i*.5,r[14]=.5,r[15]=1,this}setReflection(t,e){let s=t.x,i=t.y,r=t.z,a=this.data;return a[0]=1-2*s*s,a[1]=-2*s*i,a[2]=-2*s*r,a[3]=0,a[4]=-2*s*i,a[5]=1-2*i*i,a[6]=-2*i*r,a[7]=0,a[8]=-2*s*r,a[9]=-2*i*r,a[10]=1-2*r*r,a[11]=0,a[12]=-2*s*e,a[13]=-2*i*e,a[14]=-2*r*e,a[15]=1,this}invert(t=this){let e=t.data,s=e[0],i=e[1],r=e[2],a=e[3],o=e[4],l=e[5],h=e[6],f=e[7],u=e[8],d=e[9],p=e[10],m=e[11],_=e[12],S=e[13],g=e[14],T=e[15],C=s*l-i*o,v=s*h-r*o,E=s*f-a*o,y=i*h-r*l,P=i*f-a*l,A=r*f-a*h,w=u*S-d*_,I=u*g-p*_,D=u*T-m*_,O=d*g-p*S,G=d*T-m*S,M=p*T-m*g,H=C*M-v*G+E*O+y*D-P*I+A*w;if(H===0)this.setIdentity();else{let U=1/H,L=this.data;L[0]=(l*M-h*G+f*O)*U,L[1]=(-i*M+r*G-a*O)*U,L[2]=(S*A-g*P+T*y)*U,L[3]=(-d*A+p*P-m*y)*U,L[4]=(-o*M+h*D-f*I)*U,L[5]=(s*M-r*D+a*I)*U,L[6]=(-_*A+g*E-T*v)*U,L[7]=(u*A-p*E+m*v)*U,L[8]=(o*G-l*D+f*w)*U,L[9]=(-s*G+i*D-a*w)*U,L[10]=(_*P-S*E+T*C)*U,L[11]=(-u*P+d*E-m*C)*U,L[12]=(-o*O+l*I-h*w)*U,L[13]=(s*O-i*I+r*w)*U,L[14]=(-_*y+S*v-g*C)*U,L[15]=(u*y-d*v+p*C)*U}return this}set(t){let e=this.data;return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],this}setIdentity(){let t=this.data;return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}setTRS(t,e,s){let i=e.x,r=e.y,a=e.z,o=e.w,l=s.x,h=s.y,f=s.z,u=i+i,d=r+r,p=a+a,m=i*u,_=i*d,S=i*p,g=r*d,T=r*p,C=a*p,v=o*u,E=o*d,y=o*p,P=this.data;return P[0]=(1-(g+C))*l,P[1]=(_+y)*l,P[2]=(S-E)*l,P[3]=0,P[4]=(_-y)*h,P[5]=(1-(m+C))*h,P[6]=(T+v)*h,P[7]=0,P[8]=(S+E)*f,P[9]=(T-v)*f,P[10]=(1-(m+g))*f,P[11]=0,P[12]=t.x,P[13]=t.y,P[14]=t.z,P[15]=1,this}transpose(t=this){let e=t.data,s=this.data;if(e===s){let i;i=e[1],s[1]=e[4],s[4]=i,i=e[2],s[2]=e[8],s[8]=i,i=e[3],s[3]=e[12],s[12]=i,i=e[6],s[6]=e[9],s[9]=i,i=e[7],s[7]=e[13],s[13]=i,i=e[11],s[11]=e[14],s[14]=i}else s[0]=e[0],s[1]=e[4],s[2]=e[8],s[3]=e[12],s[4]=e[1],s[5]=e[5],s[6]=e[9],s[7]=e[13],s[8]=e[2],s[9]=e[6],s[10]=e[10],s[11]=e[14],s[12]=e[3],s[13]=e[7],s[14]=e[11],s[15]=e[15];return this}getTranslation(t=new x){return t.set(this.data[12],this.data[13],this.data[14])}getX(t=new x){return t.set(this.data[0],this.data[1],this.data[2])}getY(t=new x){return t.set(this.data[4],this.data[5],this.data[6])}getZ(t=new x){return t.set(this.data[8],this.data[9],this.data[10])}getScale(t=new x){return this.getX(Ta),this.getY(mo),this.getZ(_o),t.set(Ta.length(),mo.length(),_o.length()),t}get scaleSign(){return this.getX(Ta),this.getY(mo),this.getZ(_o),Ta.cross(Ta,mo),Ta.dot(_o)<0?-1:1}setFromEulerAngles(t,e,s){t*=R.DEG_TO_RAD,e*=R.DEG_TO_RAD,s*=R.DEG_TO_RAD;let i=Math.sin(-t),r=Math.cos(-t),a=Math.sin(-e),o=Math.cos(-e),l=Math.sin(-s),h=Math.cos(-s),f=this.data;return f[0]=o*h,f[1]=-o*l,f[2]=a,f[3]=0,f[4]=r*l+h*i*a,f[5]=r*h-i*a*l,f[6]=-o*i,f[7]=0,f[8]=i*l-r*h*a,f[9]=h*i+r*a*l,f[10]=r*o,f[11]=0,f[12]=0,f[13]=0,f[14]=0,f[15]=1,this}getEulerAngles(t=new x){this.getScale(Dx);let e=Dx.x,s=Dx.y,i=Dx.z;if(e===0||s===0||i===0)return t.set(0,0,0);let r=this.data,a=Math.asin(-r[2]/e),o=Math.PI*.5,l,h;return a-o?(l=Math.atan2(r[6]/s,r[10]/i),h=Math.atan2(r[1]/e,r[0]/e)):(h=0,l=-Math.atan2(r[4]/s,r[5]/s)):(h=0,l=Math.atan2(r[4]/s,r[5]/s)),t.set(l,a,h).mulScalar(R.RAD_TO_DEG)}toString(){return`[${this.data.join(", ")}]`}};n(Uh,"IDENTITY",Object.freeze(new Uh)),n(Uh,"ZERO",Object.freeze(new Uh().set([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])));var W=Uh;var od=class od{constructor(t=0,e=0,s=0,i=1){n(this,"x");n(this,"y");n(this,"z");n(this,"w");t.length===4?(this.x=t[0],this.y=t[1],this.z=t[2],this.w=t[3]):(this.x=t,this.y=e,this.z=s,this.w=i)}clone(){let t=this.constructor;return new t(this.x,this.y,this.z,this.w)}conjugate(t=this){return this.x=t.x*-1,this.y=t.y*-1,this.z=t.z*-1,this.w=t.w,this}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}equals(t){return this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w}equalsApprox(t,e=1e-6){return Math.abs(this.x-t.x)=.99999?(e=2*Math.atan2(r,l),s=Math.PI/2,i=0):(e=Math.atan2(2*(l*r+a*o),1-2*(r*r+a*a)),s=Math.asin(h),i=Math.atan2(2*(l*o+r*a),1-2*(a*a+o*o))),t.set(e,s,i).mulScalar(R.RAD_TO_DEG)}invert(t=this){return this.conjugate(t).normalize()}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}lerp(t,e,s){let i=(1-s)*(t.dot(e)<0?-1:1);return this.x=t.x*i+e.x*s,this.y=t.y*i+e.y*s,this.z=t.z*i+e.z*s,this.w=t.w*i+e.w*s,this.normalize()}mul(t){let e=this.x,s=this.y,i=this.z,r=this.w,a=t.x,o=t.y,l=t.z,h=t.w;return this.x=r*a+e*h+s*l-i*o,this.y=r*o+s*h+i*a-e*l,this.z=r*l+i*h+e*o-s*a,this.w=r*h-e*a-s*o-i*l,this}mulScalar(t,e=this){return this.x=e.x*t,this.y=e.y*t,this.z=e.z*t,this.w=e.w*t,this}mul2(t,e){let s=t.x,i=t.y,r=t.z,a=t.w,o=e.x,l=e.y,h=e.z,f=e.w;return this.x=a*o+s*f+i*h-r*l,this.y=a*l+i*f+r*o-s*h,this.z=a*h+r*f+s*l-i*o,this.w=a*f-s*o-i*l-r*h,this}normalize(t=this){let e=t.length();return e===0?(this.x=this.y=this.z=0,this.w=1):(e=1/e,this.x=t.x*e,this.y=t.y*e,this.z=t.z*e,this.w=t.w*e),this}set(t,e,s,i){return this.x=t,this.y=e,this.z=s,this.w=i,this}setFromAxisAngle(t,e){e*=.5*R.DEG_TO_RAD;let s=Math.sin(e),i=Math.cos(e);return this.x=s*t.x,this.y=s*t.y,this.z=s*t.z,this.w=i,this}setFromEulerAngles(t,e,s){if(t instanceof x){let u=t;t=u.x,e=u.y,s=u.z}let i=.5*R.DEG_TO_RAD;t*=i,e*=i,s*=i;let r=Math.sin(t),a=Math.cos(t),o=Math.sin(e),l=Math.cos(e),h=Math.sin(s),f=Math.cos(s);return this.x=r*l*f-a*o*h,this.y=a*o*f+r*l*h,this.z=a*l*h-r*o*f,this.w=a*l*f+r*o*h,this}setFromMat4(t){let e=t.data,s=e[0],i=e[1],r=e[2],a=e[4],o=e[5],l=e[6],h=e[8],f=e[9],u=e[10];s*(o*u-l*f)-i*(a*u-l*h)+r*(a*f-o*h)<0&&(s=-s,i=-i,r=-r);let p;return p=s*s+i*i+r*r,p===0?this.set(0,0,0,1):(p=1/Math.sqrt(p),s*=p,i*=p,r*=p,p=a*a+o*o+l*l,p===0?this.set(0,0,0,1):(p=1/Math.sqrt(p),a*=p,o*=p,l*=p,p=h*h+f*f+u*u,p===0?this.set(0,0,0,1):(p=1/Math.sqrt(p),h*=p,f*=p,u*=p,u<0?s>o?this.set(1+s-o-u,i+a,h+r,l-f):this.set(i+a,1-s+o-u,l+f,h-r):s<-o?this.set(h+r,l+f,1-s-o+u,i-a):this.set(l-f,h-r,i-a,1+s+o+u),this.mulScalar(1/this.length()))))}setFromDirections(t,e){let s=1+t.dot(e);return sMath.abs(t.y)?(this.x=-t.z,this.y=0,this.z=t.x,this.w=0):(this.x=0,this.y=-t.z,this.z=t.y,this.w=0):(this.x=t.y*e.z-t.z*e.y,this.y=t.z*e.x-t.x*e.z,this.z=t.x*e.y-t.y*e.x,this.w=s),this.normalize()}slerp(t,e,s){let i=t.x,r=t.y,a=t.z,o=t.w,l=e.x,h=e.y,f=e.z,u=e.w,d=o*u+i*l+r*h+a*f;if(d<0&&(u=-u,l=-l,h=-h,f=-f,d=-d),Math.abs(d)>=1)return this.w=o,this.x=i,this.y=r,this.z=a,this;let p=Math.acos(d),m=Math.sqrt(1-d*d);if(Math.abs(m)<.001)return this.w=o*.5+u*.5,this.x=i*.5+l*.5,this.y=r*.5+h*.5,this.z=a*.5+f*.5,this;let _=Math.sin((1-s)*p)/m,S=Math.sin(s*p)/m;return this.w=o*_+u*S,this.x=i*_+l*S,this.y=r*_+h*S,this.z=a*_+f*S,this}transformVector(t,e=new x){let s=t.x,i=t.y,r=t.z,a=this.x,o=this.y,l=this.z,h=this.w,f=h*s+o*r-l*i,u=h*i+l*s-a*r,d=h*r+a*i-o*s,p=-a*s-o*i-l*r;return e.x=f*h+p*-a+u*-l-d*-o,e.y=u*h+p*-o+d*-a-f*-l,e.z=d*h+p*-l+f*-o-u*-a,e}fromArray(t,e=0){return this.x=t[e]??this.x,this.y=t[e+1]??this.y,this.z=t[e+2]??this.z,this.w=t[e+3]??this.w,this}toString(){return`[${this.x}, ${this.y}, ${this.z}, ${this.w}]`}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}};n(od,"IDENTITY",Object.freeze(new od(0,0,0,1))),n(od,"ZERO",Object.freeze(new od(0,0,0,0)));var $=od;var nd=new x,ld=new x,fD=new x,uD=new x,F4=new x,ge=class c{constructor(t,e){n(this,"center",new x);n(this,"halfExtents",new x(.5,.5,.5));n(this,"_min",new x);n(this,"_max",new x);t&&this.center.copy(t),e&&this.halfExtents.copy(e)}add(t){let e=this.center,s=e.x,i=e.y,r=e.z,a=this.halfExtents,o=a.x,l=a.y,h=a.z,f=s-o,u=s+o,d=i-l,p=i+l,m=r-h,_=r+h,S=t.center,g=S.x,T=S.y,C=S.z,v=t.halfExtents,E=v.x,y=v.y,P=v.z,A=g-E,w=g+E,I=T-y,D=T+y,O=C-P,G=C+P;Au&&(u=w),Ip&&(p=D),O_&&(_=G),e.x=(f+u)*.5,e.y=(d+p)*.5,e.z=(m+_)*.5,a.x=(u-f)*.5,a.y=(p-d)*.5,a.z=(_-m)*.5}copy(t){this.center.copy(t.center),this.halfExtents.copy(t.halfExtents)}clone(){return new c(this.center,this.halfExtents)}intersects(t){let e=this.getMax(),s=this.getMin(),i=t.getMax(),r=t.getMin();return s.x<=i.x&&e.x>=r.x&&s.y<=i.y&&e.y>=r.y&&s.z<=i.z&&e.z>=r.z}_intersectsRay(t,e){let s=nd.copy(this.getMin()).sub(t.origin),i=ld.copy(this.getMax()).sub(t.origin),r=t.direction;r.x===0?(s.x=s.x<0?-Number.MAX_VALUE:Number.MAX_VALUE,i.x=i.x<0?-Number.MAX_VALUE:Number.MAX_VALUE):(s.x/=r.x,i.x/=r.x),r.y===0?(s.y=s.y<0?-Number.MAX_VALUE:Number.MAX_VALUE,i.y=i.y<0?-Number.MAX_VALUE:Number.MAX_VALUE):(s.y/=r.y,i.y/=r.y),r.z===0?(s.z=s.z<0?-Number.MAX_VALUE:Number.MAX_VALUE,i.z=i.z<0?-Number.MAX_VALUE:Number.MAX_VALUE):(s.z/=r.z,i.z/=r.z);let a=fD.set(Math.min(s.x,i.x),Math.min(s.y,i.y),Math.min(s.z,i.z)),o=uD.set(Math.max(s.x,i.x),Math.max(s.y,i.y),Math.max(s.z,i.z)),l=Math.min(Math.min(o.x,o.y),o.z),h=Math.max(Math.max(a.x,a.y),a.z),f=l>=h&&h>=0;return f&&e.copy(t.direction).mulScalar(h).add(t.origin),f}_fastIntersectsRay(t){let e=nd,s=ld,i=fD,r=uD,a=F4,o=t.direction;return e.sub2(t.origin,this.center),r.set(Math.abs(e.x),Math.abs(e.y),Math.abs(e.z)),i.mul2(e,o),!(r.x>this.halfExtents.x&&i.x>=0||r.y>this.halfExtents.y&&i.y>=0||r.z>this.halfExtents.z&&i.z>=0||(a.set(Math.abs(o.x),Math.abs(o.y),Math.abs(o.z)),s.cross(o,e),s.set(Math.abs(s.x),Math.abs(s.y),Math.abs(s.z)),s.x>this.halfExtents.y*a.z+this.halfExtents.z*a.y)||s.y>this.halfExtents.x*a.z+this.halfExtents.z*a.x||s.z>this.halfExtents.x*a.y+this.halfExtents.y*a.x)}intersectsRay(t,e){return e?this._intersectsRay(t,e):this._fastIntersectsRay(t)}setMinMax(t,e){this.center.add2(e,t).mulScalar(.5),this.halfExtents.sub2(e,t).mulScalar(.5)}getMin(){return this._min.copy(this.center).sub(this.halfExtents)}getMax(){return this._max.copy(this.center).add(this.halfExtents)}containsPoint(t){let e=this.center,s=this.halfExtents;return!(t.xe.x+s.x||t.ye.y+s.y||t.ze.z+s.z)}closestPoint(t,e=new x){let s=this.center,i=this.halfExtents;return e.set(Math.max(s.x-i.x,Math.min(t.x,s.x+i.x)),Math.max(s.y-i.y,Math.min(t.y,s.y+i.y)),Math.max(s.z-i.z,Math.min(t.z,s.z+i.z)))}setFromTransformedAabb(t,e,s=!1){let i=t.center,r=t.halfExtents,a=e.data,o=a[0],l=a[4],h=a[8],f=a[1],u=a[5],d=a[9],p=a[2],m=a[6],_=a[10];if(s){let S=o*o+l*l+h*h;if(S>0){let g=1/Math.sqrt(S);o*=g,l*=g,h*=g}if(S=f*f+u*u+d*d,S>0){let g=1/Math.sqrt(S);f*=g,u*=g,d*=g}if(S=p*p+m*m+_*_,S>0){let g=1/Math.sqrt(S);p*=g,m*=g,_*=g}}this.center.set(a[12]+o*i.x+l*i.y+h*i.z,a[13]+f*i.x+u*i.y+d*i.z,a[14]+p*i.x+m*i.y+_*i.z),this.halfExtents.set(Math.abs(o)*r.x+Math.abs(l)*r.y+Math.abs(h)*r.z,Math.abs(f)*r.x+Math.abs(u)*r.y+Math.abs(d)*r.z,Math.abs(p)*r.x+Math.abs(m)*r.y+Math.abs(_)*r.z)}static computeMinMax(t,e,s,i=t.length/3){if(i>0){let r=t[0],a=t[1],o=t[2],l=r,h=a,f=o,u=i*3;for(let d=3;dl&&(l=p),m>h&&(h=m),_>f&&(f=_)}e.set(r,a,o),s.set(l,h,f)}}compute(t,e){c.computeMinMax(t,nd,ld,e),this.setMinMax(nd,ld)}intersectsBoundingSphere(t){return this._distanceToBoundingSphereSq(t)<=t.radius*t.radius}_distanceToBoundingSphereSq(t){let e=this.getMin(),s=this.getMax(),i=0,r=["x","y","z"];for(let a=0;a<3;++a){let o=0,l=t.center[r[a]],h=e[r[a]],f=s[r[a]],u=0;lf&&(u=l-f,o+=u*u),i+=o}return i}_expand(t,e){nd.add2(this.getMin(),t),ld.add2(this.getMax(),e),this.setMinMax(nd,ld)}};var Lx=new x,N4=new x,Br=class{constructor(t=new x,e=.5){n(this,"center");n(this,"radius");this.center=t,this.radius=e}containsPoint(t){let e=Lx.sub2(t,this.center).lengthSq(),s=this.radius;return e0&&i>0)return!1;let a=i*i-r;if(a<0)return!1;let o=Math.abs(-i-Math.sqrt(a));return e&&e.copy(t.direction).mulScalar(o).add(t.origin),!0}intersectsBoundingSphere(t){Lx.sub2(t.center,this.center);let e=t.radius+this.radius;return Lx.lengthSq()<=e*e}};var go=class{constructor(t=x.UP,e=0){n(this,"normal",new x);n(this,"distance");this.normal.copy(t),this.distance=e}clone(){let t=this.constructor;return new t().copy(this)}copy(t){return this.normal.copy(t.normal),this.distance=t.distance,this}intersectsLine(t,e,s){let i=this.distance,r=this.normal.dot(t)+i,a=this.normal.dot(e)+i,o=r/(r-a),l=o>=0&&o<=1;return l&&s&&s.lerp(t,e,o),l}intersectsRay(t,e){let s=this.normal.dot(t.direction);if(s===0)return!1;let i=-(this.normal.dot(t.origin)+this.distance)/s;return i>=0&&e&&e.copy(t.direction).mulScalar(i).add(t.origin),i>=0}normalize(){let t=1/this.normal.length();return this.normal.mulScalar(t),this.distance*=t,this}set(t,e,s,i){return this.normal.set(t,e,s),this.distance=i,this}setFromPointNormal(t,e){return this.normal.copy(e),this.distance=-this.normal.dot(t),this}};var So=class{constructor(){n(this,"planes",[]);for(let t=0;t<6;t++)this.planes[t]=new go}clone(){let t=this.constructor;return new t().copy(this)}copy(t){for(let e=0;e<6;e++)this.planes[e].copy(t.planes[e]);return this}setFromMat4(t){let e=t.data,s=e[0],i=e[1],r=e[2],a=e[3],o=e[4],l=e[5],h=e[6],f=e[7],u=e[8],d=e[9],p=e[10],m=e[11],_=e[12],S=e[13],g=e[14],T=e[15],C=this.planes;C[0].set(a-s,f-o,m-u,T-_).normalize(),C[1].set(a+s,f+o,m+u,T+_).normalize(),C[2].set(a+i,f+l,m+d,T+S).normalize(),C[3].set(a-i,f-l,m-d,T-S).normalize(),C[4].set(a-r,f-h,m-p,T-g).normalize(),C[5].set(a+r,f+h,m+p,T+g).normalize()}containsPoint(t){for(let e=0;e<6;e++){let{normal:s,distance:i}=this.planes[e];if(s.dot(t)+i<=0)return!1}return!0}add(t){let e=this.planes,s=t.planes;for(let i=0;i<6;i++)s[i].distance>e[i].distance&&e[i].copy(s[i]);return this}containsSphere(t){let{center:e,radius:s}=t,i=0;for(let r=0;r<6;r++){let{normal:a,distance:o}=this.planes[r],l=a.dot(e)+o;if(l<=-s)return 0;l>s&&i++}return i===6?2:1}};var ws=class{constructor(t,e){n(this,"origin",new x);n(this,"direction",x.FORWARD.clone());t&&this.origin.copy(t),e&&this.direction.copy(e)}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.set(t.origin,t.direction)}clone(){return new this.constructor(this.origin,this.direction)}};var Mx=new ws,dD=new x,DC=new Br,B4=new W,Ox=class{constructor(t=new W,e){n(this,"halfExtents",new x(.5,.5,.5));n(this,"_modelTransform");n(this,"_worldTransform");n(this,"_aabb");e&&this.halfExtents.copy(e),this._modelTransform=t.clone().invert(),this._worldTransform=t.clone(),this._aabb=new ge(new x,this.halfExtents)}set worldTransform(t){this._worldTransform.copy(t),this._modelTransform.copy(t).invert()}get worldTransform(){return this._worldTransform}intersectsRay(t,e){if(this._modelTransform.transformPoint(t.origin,Mx.origin),this._modelTransform.transformVector(t.direction,Mx.direction),e){let s=this._aabb._intersectsRay(Mx,e);return B4.copy(this._modelTransform).invert().transformPoint(e,e),s}return this._aabb._fastIntersectsRay(Mx)}containsPoint(t){return this._modelTransform.transformPoint(t,dD),this._aabb.containsPoint(dD)}intersectsBoundingSphere(t){return this._modelTransform.transformPoint(t.center,DC.center),DC.radius=t.radius,!!this._aabb.intersectsBoundingSphere(DC)}};var LC=new x,MC=new x,OC=new x,FC=new x,NC=new x,BC=1e-6,cd=class{constructor(t=x.ZERO,e=x.ZERO,s=x.ZERO){n(this,"v0",new x);n(this,"v1",new x);n(this,"v2",new x);this.set(t,e,s)}set(t,e,s){return this.v0.copy(t),this.v1.copy(e),this.v2.copy(s),this}intersectsRay(t,e){LC.sub2(this.v1,this.v0),MC.sub2(this.v2,this.v0),OC.cross(t.direction,MC);let s=LC.dot(OC);if(s>-BC&&s1)return!1;NC.cross(FC,LC);let a=i*t.direction.dot(NC);if(a<0||r+a>1)return!1;let o=i*MC.dot(NC);return o>BC?(e instanceof x&&e.copy(t.direction).mulScalar(o).add(t.origin),!0):!1}toString(){return`[${this.v0.toString()}, ${this.v1.toString()}, ${this.v2.toString()}]`}};var Je=0,ie=1,xo=2,Fx=0,_s=1,pD=2,GZ=3,UC=4,mD=5,$l=6,VZ=7,Zl=8,HZ=9,WZ=10,kC=11,zC=12,ii=0,XZ=1,_D=2,gD=3,SD=4,Nx=1,YZ=2,mi=4,$e=8,U4=16,k4=32,z4=64,GC=128,pn=256,Xs=0,hd=1,VC=2,Bx=3,mn=1,_n=2,Yh=4,KZ=0,jZ=1,qZ=2,$Z=3,ZZ=4,QZ=5,Ze=0,gn=1,HC=2,G4=3,Sn=0,xD=1,ve=0,De=1,zi=2,Ur=3,kr=4,gs=5,V4=0,fd=1,ud=2,WC=3,H4=4,W4=5,X4=6,zr=7,dd=0,Is=1,Ii=2,XC=[1,2,4],pd=0,md=1,vo=2,ya=3,xn=4,Ea=5,Ss=6,ce=7,To=8,Ql=9,Gr=10,vn=11,Me=12,Kh=13,ke=14,Mt=15,Ys=16,fr=17,Gi=18,yo=19,st=20,Eo=21,Jl=22,ec=23,Vr=24,Hr=25,Ao=26,Co=27,_d=28,gd=29,Sd=30,tc=31,jh=32,sc=33,qh=34,$h=35,Zh=36,zt=37,Qh=38,xd=39,Jh=40,ef=41,tf=42,Tn=43,sf=44,vd=45,rf=46,Rs=47,af=48,At=49,yn=50,of=51,Wr=52,Po=53,kh=54,zh=55,Gh=56,Vh=61,Hh=62,Wh=63,ic=64,Td=65,yd=66,Ed=67,Xh=68,Xr=69,nf=70,lf=71,cf=72,hf=73,ff=74,uf=75,xs=new Map([[pd,{name:"A8",size:1,ldr:!0}],[Wr,{name:"R8",size:1,ldr:!0}],[md,{name:"L8",size:1,ldr:!0}],[vo,{name:"LA8",size:2,ldr:!0}],[Po,{name:"RG8",size:2,ldr:!0}],[ya,{name:"RGB565",size:2,ldr:!0}],[xn,{name:"RGBA5551",size:2,ldr:!0}],[Ea,{name:"RGBA4",size:2,ldr:!0}],[Ss,{name:"RGB8",size:4,ldr:!0}],[ce,{name:"RGBA8",size:4,ldr:!0,srgbFormat:st}],[yn,{name:"R16F",size:2}],[of,{name:"RG16F",size:4}],[vn,{name:"RGB16F",size:8}],[Me,{name:"RGBA16F",size:8}],[Kh,{name:"RGB32F",size:16}],[ke,{name:"RGBA32F",size:16}],[Mt,{name:"R32F",size:4}],[nf,{name:"RG32F",size:8}],[lf,{name:"RGB9E5",size:4}],[cf,{name:"RG8S",size:2}],[hf,{name:"RGBA8S",size:4}],[ff,{name:"RGB10A2",size:4}],[uf,{name:"RGB10A2U",size:4,isUint:!0}],[Ys,{name:"DEPTH",size:4}],[Xr,{name:"DEPTH16",size:2}],[fr,{name:"DEPTHSTENCIL",size:4}],[Gi,{name:"111110F",size:4}],[yo,{name:"SRGB8",size:4,ldr:!0,srgb:!0}],[st,{name:"SRGBA8",size:4,ldr:!0,srgb:!0}],[tc,{name:"BGRA8",size:4,ldr:!0}],[ic,{name:"SBGRA8",size:4,ldr:!0,srgb:!0}],[To,{name:"DXT1",blockSize:8,ldr:!0,srgbFormat:kh}],[Ql,{name:"DXT3",blockSize:16,ldr:!0,srgbFormat:zh}],[Gr,{name:"DXT5",blockSize:16,ldr:!0,srgbFormat:Gh}],[Eo,{name:"ETC1",blockSize:8,ldr:!0}],[Jl,{name:"ETC2_RGB",blockSize:8,ldr:!0,srgbFormat:Vh}],[ec,{name:"ETC2_RGBA",blockSize:16,ldr:!0,srgbFormat:Hh}],[Vr,{name:"PVRTC_2BPP_RGB_1",ldr:!0,blockSize:8}],[Hr,{name:"PVRTC_2BPP_RGBA_1",ldr:!0,blockSize:8}],[Ao,{name:"PVRTC_4BPP_RGB_1",ldr:!0,blockSize:8}],[Co,{name:"PVRTC_4BPP_RGBA_1",ldr:!0,blockSize:8}],[_d,{name:"ASTC_4x4",blockSize:16,ldr:!0,srgbFormat:Wh}],[gd,{name:"ATC_RGB",blockSize:8,ldr:!0}],[Sd,{name:"ATC_RGBA",blockSize:16,ldr:!0}],[Td,{name:"BC6H_RGBF",blockSize:16}],[yd,{name:"BC6H_RGBUF",blockSize:16}],[Ed,{name:"BC7_RGBA",blockSize:16,ldr:!0,srgbFormat:Xh}],[kh,{name:"DXT1_SRGB",blockSize:8,ldr:!0,srgb:!0}],[zh,{name:"DXT3_SRGBA",blockSize:16,ldr:!0,srgb:!0}],[Gh,{name:"DXT5_SRGBA",blockSize:16,ldr:!0,srgb:!0}],[Vh,{name:"ETC2_SRGB",blockSize:8,ldr:!0,srgb:!0}],[Hh,{name:"ETC2_SRGBA",blockSize:16,ldr:!0,srgb:!0}],[Wh,{name:"ASTC_4x4_SRGB",blockSize:16,ldr:!0,srgb:!0}],[Xh,{name:"BC7_SRGBA",blockSize:16,ldr:!0,srgb:!0}],[jh,{name:"R8I",size:1,isInt:!0}],[qh,{name:"R16I",size:2,isInt:!0}],[Zh,{name:"R32I",size:4,isInt:!0}],[Qh,{name:"RG8I",size:2,isInt:!0}],[Jh,{name:"RG16I",size:4,isInt:!0}],[tf,{name:"RG32I",size:8,isInt:!0}],[sf,{name:"RGBA8I",size:4,isInt:!0}],[rf,{name:"RGBA16I",size:8,isInt:!0}],[af,{name:"RGBA32I",size:16,isInt:!0}],[sc,{name:"R8U",size:1,isUint:!0}],[$h,{name:"R16U",size:2,isUint:!0}],[zt,{name:"R32U",size:4,isUint:!0}],[xd,{name:"RG8U",size:2,isUint:!0}],[ef,{name:"RG16U",size:4,isUint:!0}],[Tn,{name:"RG32U",size:8,isUint:!0}],[vd,{name:"RGBA8U",size:4,isUint:!0}],[Rs,{name:"RGBA16U",size:8,isUint:!0}],[At,{name:"RGBA32U",size:16,isUint:!0}]]),En=c=>xs.get(c)?.blockSize!==void 0,df=c=>xs.get(c)?.srgb===!0,ur=c=>{let t=xs.get(c);return t?.isInt===!0||t?.isUint===!0},Y4={sampler:"sampler2D",returnType:"vec4"},K4={sampler:"usampler2D",returnType:"uvec4"},j4={sampler:"isampler2D",returnType:"ivec4"},q4={textureType:"texture_2d",returnType:"vec4f"},$4={textureType:"texture_2d",returnType:"vec4u"},Z4={textureType:"texture_2d",returnType:"vec4i"},An=c=>{let t=xs.get(c);return t?.isUint?K4:t?.isInt?j4:Y4},Ad=c=>{let t=xs.get(c);return t?.isUint?$4:t?.isInt?Z4:q4},Cn=c=>xs.get(c)?.srgbFormat||c,YC=c=>{for(let[t,e]of xs)if(e.srgbFormat===c)return t;return c},KC=c=>{let t=xs.get(c);return!!(t?.ldr&&!t?.srgb)},pf=c=>{switch(c){case Mt:case nf:case Kh:case ke:return Float32Array;case Zh:case tf:case af:return Int32Array;case zt:case Tn:case At:case lf:case ff:case uf:return Uint32Array;case qh:case Jh:case rf:return Int16Array;case $h:case ef:case Rs:case ya:case xn:case Ea:case yn:case of:case vn:case Me:return Uint16Array;case jh:case Qh:case sf:case cf:case hf:return Int8Array;default:return Uint8Array}},Aa=0,Pn=1,Eg=2,mf=3,Yt=4,Ks=5,dr=6,ee="POSITION",Ot="NORMAL",vs="TANGENT",bs="BLENDWEIGHT",$t="BLENDINDICES",Ct="COLOR",Ux="TEXCOORD",_t="TEXCOORD0",ri="TEXCOORD1",Ca="TEXCOORD2",Pa="TEXCOORD3",wa="TEXCOORD4",Ia="TEXCOORD5",Ra="TEXCOORD6",ba="TEXCOORD7",Ag="ATTR0",_f="ATTR1",Cd="ATTR2",Pd="ATTR3",wd="ATTR4",vD="ATTR5",TD="ATTR6",yD="ATTR7",rc="ATTR8",ac="ATTR9",ED="ATTR10",Id="ATTR11",Rd="ATTR12",AD="ATTR13",bd="ATTR14",Da="ATTR15",Cg=1,wn=0,Q4=1,jC=2,qC=3,J4=4,$C=5,e5=6,t5=7,Pg=0,ZC=1,kx=2,Gt="default",_i="rgbm",oc="rgbe",In="rgbp",Rn="swizzleGGGR",s5=0,i5=1,r5=2,a5=3,zx="1d",Ds="2d",Yr="2d-array",Kr="cube",Dd="cube-array",bn="3d",rs=0,Vi=1,gi=2,Hi=3,Wi=4,QC="none",Ld="cube",Gx="equirect",JC="octahedral",fe="glsl",se="wgsl",js=0,ai=1,qs=2,Ri=3,He=4,kt=5,ye=6,nc=7,wo=0,bi=1,Te=2,pr=3,Kt=4,oi=5,jr=6,Di=7,qr=8,Dn=9,Ln=10,Mn=11,lc=12,La=13,as=14,eP=15,tP=16,On=17,sP=18,iP=19,rP=20,Fn=21,Nn=22,gf=23,wg=24,aP=25,pe=26,Ma=27,Oa=28,Li=29,Fa=30,Bn=31,Un=32,Na=33,kn=34,zn=35,Ba=36,Gn=37,Vn=38,cc=39,Sf=40,xf=41,oP=42,nP=43,lP=44,cP=45,hP=46,fP=47,uP=48,dP=49,Vx=["bool","int","float","vec2","vec3","vec4","ivec2","ivec3","ivec4","bvec2","bvec3","bvec4","mat2","mat3","mat4","sampler2D","samplerCube","","sampler2DShadow","samplerCubeShadow","sampler3D","","","","","sampler2DArray","uint","uvec2","uvec3","uvec4","","","","","","","","","","","","","isampler2D","usampler2D","isamplerCube","usamplerCube","isampler3D","usampler3D","isampler2DArray","usampler2DArray"],Hx=[["bool"],["i32"],["f32"],["vec2f","vec2"],["vec3f","vec3"],["vec4f","vec4"],["vec2i","vec2"],["vec3i","vec3"],["vec4i","vec4"],["vec2"],["vec3"],["vec4"],["mat2x2f","mat2x2"],["mat3x3f","mat3x3"],["mat4x4f","mat4x4"],["texture_2d"],["texture_cube"],["array"],["texture_depth_2d"],["texture_depth_cube"],["texture_3d"],["array>"],["array>"],["array>"],["array>"],["texture_2d_array"],["u32"],["vec2u","vec2"],["vec3u","vec3"],["vec4u","vec4"],["array"],["array"],["array"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["array","array>"],["texture_2d"],["texture_2d"],["texture_cube"],["texture_cube"],["texture_3d"],["texture_3d"],["texture_2d_array"],["texture_2d_array"]],Wx=new Map;Hx.forEach((c,t)=>{c.forEach(e=>Wx.set(e,t))});var o5=new Uint8Array([He,He,ye,ye,ye,ye,He,He,He,He,He,He,ye,ye,ye,He,He,ye,He,He,He,ye,ye,ye,ye,He,kt,kt,kt,kt,He,kt,He,He,kt,He,He,kt,He,He,kt,He,He,kt,He,kt,He,kt,He,kt]),vf="webgl2",Ig="webgpu",Xx="webgpu:bare",Tf="null",Xi=1,Yi=2,X=4,pP="ldr",Md="ldr_srgb",mP="hdr",Od=1,Rg=2,bg=4,Dg=8,Lg=16,Mg=32,Og=64,Fg=128,_P=255,Io=0,Ua=1,$r=2,Ng=["view","mesh","mesh_ub"],Hn="default",yf="_unused_float_uniform",Ro=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Uint16Array],Wn=[1,1,2,2,4,4,4,2],n5=["INT8","UINT8","INT16","UINT16","INT32","UINT32","FLOAT32","FLOAT16"],l5={Int8Array:js,Uint8Array:ai,Int16Array:qs,Uint16Array:Ri,Int32Array:He,Uint32Array:kt,Float32Array:ye},Ef=[Uint8Array,Uint16Array,Uint32Array],gP=[1,2,4],Bg=new Map([["float","f32"],["vec2","vec2f"],["vec3","vec3f"],["vec4","vec4f"],["int","i32"],["ivec2","vec2i"],["ivec3","vec3i"],["ivec4","vec4i"],["uint","u32"],["uvec2","vec2u"],["uvec3","vec3u"],["uvec4","vec4u"]]),ze={};ze[ee]=0;ze[Ot]=1;ze[bs]=2;ze[$t]=3;ze[Ct]=4;ze[_t]=5;ze[ri]=6;ze[Ca]=7;ze[Pa]=8;ze[wa]=9;ze[Ia]=10;ze[Ra]=11;ze[ba]=12;ze[vs]=13;ze[Ag]=0;ze[_f]=1;ze[Cd]=2;ze[Pd]=3;ze[wd]=4;ze[vD]=5;ze[TD]=6;ze[yD]=7;ze[rc]=8;ze[ac]=9;ze[ED]=10;ze[Id]=11;ze[Rd]=12;ze[AD]=13;ze[bd]=14;ze[Da]=15;var Yx=c=>{typeof window>"u"||window.isSecureContext};var c5=0,Fd=class{constructor(t,e){n(this,"slot",-1);n(this,"scopeId",null);this.name=t,this.visibility=e}},Qe=class extends Fd{},K=class extends Fd{constructor(e,s,i=!1){super(e,s);n(this,"format","");this.readOnly=i}},Ki=class extends Fd{constructor(t,e,s=Ds,i=rs,r=!0,a=null){super(t,e),this.textureDimension=s,this.sampleType=i,this.hasSampler=r,this.samplerName=a??`${t}_sampler`}},Xn=class extends Fd{constructor(t,e=ce,s=Ds,i=!0,r=!1){super(t,X),this.format=e,this.textureDimension=s,this.write=i,this.read=r}},Ue=class{constructor(t,e){n(this,"uniformBufferFormats",[]);n(this,"textureFormats",[]);n(this,"storageTextureFormats",[]);n(this,"storageBufferFormats",[]);this.id=c5++;let s=0;e.forEach(r=>{r.slot=s++,r instanceof Ki&&r.hasSampler&&s++,r instanceof Qe?this.uniformBufferFormats.push(r):r instanceof Ki?this.textureFormats.push(r):r instanceof Xn?this.storageTextureFormats.push(r):r instanceof K&&this.storageBufferFormats.push(r)}),this.device=t;let i=t.scope;this.bufferFormatsMap=new Map,this.uniformBufferFormats.forEach((r,a)=>this.bufferFormatsMap.set(r.name,a)),this.textureFormatsMap=new Map,this.textureFormats.forEach((r,a)=>{this.textureFormatsMap.set(r.name,a),r.scopeId=i.resolve(r.name)}),this.storageTextureFormatsMap=new Map,this.storageTextureFormats.forEach((r,a)=>{this.storageTextureFormatsMap.set(r.name,a),r.scopeId=i.resolve(r.name)}),this.storageBufferFormatsMap=new Map,this.storageBufferFormats.forEach((r,a)=>{this.storageBufferFormatsMap.set(r.name,a),r.scopeId=i.resolve(r.name)}),this.impl=t.createBindGroupFormatImpl(this)}destroy(){this.impl.destroy()}getTexture(t){let e=this.textureFormatsMap.get(t);return e!==void 0?this.textureFormats[e]:null}getStorageTexture(t){let e=this.storageTextureFormatsMap.get(t);return e!==void 0?this.storageTextureFormats[e]:null}loseContext(){}};var et=class{constructor(){n(this,"_cache",new Map)}get(t,e){return this._cache.has(t)||(this._cache.set(t,e()),t.on("destroy",()=>{this.remove(t)}),t.on("devicelost",()=>{this._cache.get(t)?.loseContext?.(t)})),this._cache.get(t)}remove(t){this._cache.get(t)?.destroy?.(t),this._cache.delete(t)}};var gt=class c{static calcLevelDimension(t,e){return Math.max(t>>e,1)}static calcMipLevelsCount(t,e,s=1){return 1+Math.floor(Math.log2(Math.max(t,e,s)))}static calcLevelGpuSize(t,e,s,i){let r=xs.get(i),a=xs.get(i)?.size??0;if(a>0)return t*e*s*a;let o=r.blockSize??0,l=Math.floor((t+3)/4),h=Math.floor((e+3)/4),f=Math.floor((s+3)/4);return(i===Vr||i===Hr)&&(l=Math.max(Math.floor(l/2),1)),l*h*f*o}static calcGpuSize(t,e,s,i,r,a){let o=0;for(;o+=c.calcLevelGpuSize(t,e,s,i),!(!r||t===1&&e===1&&s===1);)t=Math.max(t>>1,1),e=Math.max(e>>1,1),s=Math.max(s>>1,1);return o*(a?6:1)}static calcTextureSize(t,e,s=1){let i=Math.ceil(Math.sqrt(t));return s>1&&(i=R.roundUp(i,s)),e.set(i,Math.ceil(t/i))}};var Si=class{constructor(){n(this,"map",new Map);n(this,"id",0)}get(t){let e=this.map.get(t);return e===void 0&&(e=this.id++,this.map.set(t,e)),e}};var h5=new Si,Zr=class{constructor(t,e=0,s=1,i=0,r=1){n(this,"texture");n(this,"baseMipLevel");n(this,"mipLevelCount");n(this,"baseArrayLayer");n(this,"arrayLayerCount");n(this,"key");this.texture=t,this.baseMipLevel=e,this.mipLevelCount=s,this.baseArrayLayer=i,this.arrayLayerCount=r,this.key=h5.get(`${e}:${s}:${i}:${r}`)}};var f5=0,Z=class c{constructor(t,e={}){n(this,"name");n(this,"_gpuSize",0);n(this,"releaseSourceAfterUpload",!1);n(this,"id",f5++);n(this,"_invalid",!1);n(this,"_lockedLevel",-1);n(this,"_lockedMode",Pg);n(this,"renderVersionDirty",0);n(this,"_storage",!1);n(this,"_numLevels",0);n(this,"_numLevelsRequested");this.device=t,this.name=e.name??"",this._width=Math.floor(e.width??4),this._height=Math.floor(e.height??4),this._format=e.format??ce,this._compressed=En(this._format),this._integerFormat=ur(this._format),this._integerFormat&&(e.minFilter=0,e.magFilter=0),this._volume=e.volume??!1,this._depth=Math.floor(e.depth??1),this._arrayLength=Math.floor(e.arrayLength??0),this._storage=e.storage??!1,this._cubemap=e.cubemap??!1,this._flipY=e.flipY??!1,this._premultiplyAlpha=e.premultiplyAlpha??!1,this._mipmaps=e.mipmaps??!0,this._numLevelsRequested=e.numLevels,e.numLevels!==void 0&&(this._numLevels=e.numLevels),this._updateNumLevels(),this._minFilter=e.minFilter??5,this._magFilter=e.magFilter??1,this._anisotropy=e.anisotropy??1,this._addressU=e.addressU??0,this._addressV=e.addressV??0,this._addressW=e.addressW??0,this._compareOnRead=e.compareOnRead??!1,this._compareFunc=e.compareFunc??1,this._type=e.type??Gt,this.projection=QC,this._cubemap?this.projection=Ld:e.projection&&e.projection!==Ld&&(this.projection=e.projection),this._levels=e.levels;let s=!!e.levels;this._levels||this._clearLevels(),this.recreateImpl(s)}static createDataTexture2D(t,e,s,i,r,a){return new c(t,{name:e,width:s,height:i,format:r,mipmaps:!1,minFilter:0,magFilter:0,addressU:1,addressV:1,levels:a})}destroy(){let t=this.device;t&&(t.onTextureDestroyed(this),this.impl.destroy(t),this.adjustVramSizeTracking(t._vram,-this._gpuSize),this.releaseSourceAfterUpload&&this.releaseImageSources(),this._levels=null,this.device=null)}releaseImageSources(){if(this.releaseSourceAfterUpload=!1,!(typeof ImageBitmap>"u"||!this._levels))for(let t=0;tt,this._numLevels=Math.min(e??t,t),this._mipmaps=this._numLevels>1}get lockedMode(){return this._lockedMode}set minFilter(t){this._minFilter!==t&&(ur(this._format)||(this._minFilter=t,this.propertyChanged(Od)))}get minFilter(){return this._minFilter}set magFilter(t){this._magFilter!==t&&(ur(this._format)||(this._magFilter=t,this.propertyChanged(Rg)))}get magFilter(){return this._magFilter}set addressU(t){this._addressU!==t&&(this._addressU=t,this.propertyChanged(bg))}get addressU(){return this._addressU}set addressV(t){this._addressV!==t&&(this._addressV=t,this.propertyChanged(Dg))}get addressV(){return this._addressV}set addressW(t){this._volume&&t!==this._addressW&&(this._addressW=t,this.propertyChanged(Lg))}get addressW(){return this._addressW}set compareOnRead(t){this._compareOnRead!==t&&(this._compareOnRead=t,this.propertyChanged(Mg))}get compareOnRead(){return this._compareOnRead}set compareFunc(t){this._compareFunc!==t&&(this._compareFunc=t,this.propertyChanged(Og))}get compareFunc(){return this._compareFunc}set anisotropy(t){this._anisotropy!==t&&(this._anisotropy=t,this.propertyChanged(Fg))}get anisotropy(){return this._anisotropy}set mipmaps(t){if(this._mipmaps!==t&&!this.device.isWebGPU){if(!ur(this._format)){let e=this._mipmaps,s=this._numLevels;this._mipmaps=t,this._updateNumLevels(),this.array&&this._numLevels!==s?this.recreateImpl():this._mipmaps!==e&&(this.propertyChanged(Od),this._mipmaps?(this._needsMipmapsUpload=!0,this.device?.texturesToUpload?.add(this)):this._needsMipmapsUpload=!1)}}}get mipmaps(){return this._mipmaps}get numLevels(){return this._numLevels}get storage(){return this._storage}get width(){return this._width}get height(){return this._height}get depth(){return this._depth}get format(){return this._format}get cubemap(){return this._cubemap}get gpuSize(){let t=this.pot&&this._mipmaps&&!(this._compressed&&this._levels.length===1);return gt.calcGpuSize(this._width,this._height,this._depth,this._format,t,this._cubemap)}get array(){return this._arrayLength>0}get arrayLength(){return this._arrayLength}get volume(){return this._volume}set type(t){this._type!==t&&(this._type=t,this.device._shadersDirty=!0)}get type(){return this._type}set srgb(t){let e=df(this.format);if(t!==e)if(t){let s=Cn(this.format);this._format!==s&&(this._format=s,this.recreateImpl(),this.device._shadersDirty=!0)}else{let s=YC(this.format);this._format!==s&&(this._format=s,this.recreateImpl(),this.device._shadersDirty=!0)}}get srgb(){return df(this.format)}set flipY(t){this._flipY!==t&&(this._flipY=t,this.markForUpload())}get flipY(){return this._flipY}set premultiplyAlpha(t){this._premultiplyAlpha!==t&&(this._premultiplyAlpha=t,this.markForUpload())}get premultiplyAlpha(){return this._premultiplyAlpha}get pot(){return R.powerOfTwo(this._width)&&R.powerOfTwo(this._height)}get encoding(){switch(this.type){case _i:return"rgbm";case oc:return"rgbe";case In:return"rgbp"}return KC(this.format)?"srgb":"linear"}dirtyAll(){this._levelsUpdated=this._cubemap?[[!0,!0,!0,!0,!0,!0]]:[!0],this.markForUpload(),this._needsMipmapsUpload=this._mipmaps,this._mipmapsUploaded=!1,this.propertyChanged(_P)}lock(t={}){t.level??(t.level=0),t.face??(t.face=0),t.mode??(t.mode=kx),this._lockedMode=t.mode,this._lockedLevel=t.level;let e=this.cubemap?this._levels[t.face]:this._levels;if(!e[t.level]){let s=Math.max(1,this._width>>t.level),i=Math.max(1,this._height>>t.level),r=Math.max(1,this._depth>>t.level),a=new ArrayBuffer(gt.calcLevelGpuSize(s,i,r,this._format));e[t.level]=new(pf(this._format))(a)}return e[t.level]}setSource(t,e=0){if(this.device._isHTMLElementInterface(t)&&(!this.device.supportsHtmlTextures||this._cubemap||this._volume))return;let s=!1,i,r;if(this._cubemap){if(t[0]){i=t[0].width||0,r=t[0].height||0;for(let a=0;a<6;a++){let o=t[a];if(!o||o.width!==i||o.height!==r||!this.device._isBrowserInterface(o)){s=!0;break}}}else s=!0;if(!s)for(let a=0;a<6;a++)this._levels[e][a]!==t[a]&&(this._levelsUpdated[e][a]=!0)}else if(this.device._isBrowserInterface(t)||(s=!0),!s)if(t!==this._levels[e]&&(this._levelsUpdated[e]=!0),t instanceof HTMLVideoElement)i=t.videoWidth,r=t.videoHeight;else if(this.device._isHTMLElementInterface(t)){let a=t.getBoundingClientRect();i=Math.floor(a.width)||1,r=Math.floor(a.height)||1}else i=t.width,r=t.height;if(s)if(this._width=4,this._height=4,this._cubemap)for(let a=0;a<6;a++)this._levels[e][a]=null,this._levelsUpdated[e][a]=!0;else this._levels[e]=null,this._levelsUpdated[e]=!0;else e===0&&(this._width=i,this._height=r),this._levels[e]=t;(this._invalid!==s||!s)&&(this._invalid=s,this.upload())}getSource(t=0){return this._levels[t]}unlock(){this._lockedMode,Pg,this._lockedMode===kx&&this.upload(),this._lockedLevel=-1,this._lockedMode=Pg}markForUpload(){this._needsUpload=!0,this.device?.texturesToUpload?.add(this)}upload(){this.markForUpload(),this._needsMipmapsUpload=this._mipmaps,this.impl.uploadImmediate?.(this.device,this)}read(t,e,s,i,r={}){return this.impl.read?.(t,e,s,i,r)}write(t,e,s,i,r){return this.impl.write?.(t,e,s,i,r)}getView(t=0,e=1,s=0,i=1){return new Zr(this,t,e,s,i)}};var u5={white:[255,255,255,255],gray:[128,128,128,255],black:[0,0,0,255],normal:[128,128,255,255],pink:[255,128,255,255]},SP=class{constructor(){n(this,"map",new Map)}destroy(){this.map.forEach(t=>{t.destroy()})}},d5=new et,bo=(c,t)=>{let e=d5.get(c,()=>new SP);if(!e.map.has(t)){let s=new Z(c,{name:`built-in-texture-${t}`,width:1,height:1,format:ce}),i=s.lock(),r=u5[t];i.set(r),s.unlock(),e.map.set(t,s)}return e.map.get(t)};var p5=0,hc=class{constructor(){n(this,"bindGroup");n(this,"offsets",[])}},ji=class{constructor(t,e,s){n(this,"renderVersionUpdated",-1);n(this,"uniformBuffers");n(this,"uniformBufferOffsets",[]);this.id=p5++,this.device=t,this.format=e,this.dirty=!0,this.impl=t.createBindGroupImpl(this),this.textures=[],this.storageTextures=[],this.storageBuffers=[],this.uniformBuffers=[],this.defaultUniformBuffer=s,s&&this.setUniformBuffer(Hn,s)}destroy(){this.impl.destroy(),this.impl=null,this.format=null,this.defaultUniformBuffer=null}setUniformBuffer(t,e){let s=this.format.bufferFormatsMap.get(t);this.uniformBuffers[s]!==e&&(this.uniformBuffers[s]=e,this.dirty=!0)}setStorageBuffer(t,e){let s=this.format.storageBufferFormatsMap.get(t);this.storageBuffers[s]!==e&&(this.storageBuffers[s]=e,this.dirty=!0)}setTexture(t,e){let s=this.format.textureFormatsMap.get(t),i=e instanceof Zr?e.texture:e;this.textures[s]!==e?(this.textures[s]=e,this.dirty=!0):this.renderVersionUpdated>t&e},all(c,t,e=1){let s=e<e)if(ArrayBuffer.isView(t))t=t.subarray(0,e),s.set(t);else for(let i=0;i>>0}var v5=new Si,T5=[2,4,8,12,16],y5=new et,Ft=class c{constructor(t,e,s){this.device=t,this._elements=[],this.hasUv0=!1,this.hasUv1=!1,this.hasColor=!1,this.hasTangents=!1,this.verticesByteSize=0,this.vertexCount=s,this.interleaved=s===void 0,this.instancing=!1,this.size=e.reduce((a,o)=>a+Math.ceil(o.components*Wn[o.type]/4)*4,0);let i=0,r;for(let a=0,o=e.length;anew c(t,[{semantic:Id,components:4,type:ye},{semantic:Rd,components:4,type:ye},{semantic:bd,components:4,type:ye},{semantic:Da,components:4,type:ye}]))}static isElementValid(t,e){let s=e.components*Wn[e.type];return!(t.isWebGPU&&!T5.includes(s))}update(){this._evaluateHash()}_evaluateHash(){let t=[],e=[],s=this._elements.length;for(let r=0;re.clear()),this.mapsToClear.clear()}computeDispatch(e,s="Unnamed"){}getRenderableHdrFormat(e=[Gi,Me,ke],s=!0,i=1){for(let r=0;r1)continue;if(this.textureFloatRenderable&&(!s||this.textureFloatFilterable))return a;break}}}validateAttributes(e,s,i){}};n($x,"EVENT_RESIZE","resizecanvas");var tt=$x;var C5=0,me=class{constructor(t={}){n(this,"name");n(this,"_device");n(this,"_colorBuffer");n(this,"_colorBuffers");n(this,"_depthBuffer");n(this,"_depth");n(this,"_stencil");n(this,"_samples");n(this,"autoResolve");n(this,"_face");n(this,"_mipLevel");n(this,"_mipmaps");n(this,"_width");n(this,"_height");n(this,"flipY");this.id=C5++;let e=t.colorBuffer?.device??t.colorBuffers?.[0].device??t.depthBuffer?.device??t.graphicsDevice;this._device=e;let{maxSamples:s}=this._device;if(this._samples=Math.min(t.samples??1,s),e.isWebGPU&&(this._samples=this._samples>1?s:1),this._colorBuffer=t.colorBuffer,t.colorBuffer&&(this._colorBuffers=[t.colorBuffer]),this._depthBuffer=t.depthBuffer,this._face=t.face??0,this._depthBuffer){let i=this._depthBuffer._format;i===Ys||i===Xr?(this._depth=!0,this._stencil=!1):i===fr?(this._depth=!0,this._stencil=!0):i===Mt&&this._depthBuffer.device.isWebGPU&&this._samples>1?(this._depth=!0,this._stencil=!1):(this._depth=!1,this._stencil=!1)}else this._depth=t.depth??!0,this._stencil=t.stencil??!1;t.colorBuffers&&(this._colorBuffers||(this._colorBuffers=[...t.colorBuffers],this._colorBuffer=t.colorBuffers[0])),this.autoResolve=t.autoResolve??!0,this.name=t.name,this.name||(this.name=this._colorBuffer?.name),this.name||(this.name=this._depthBuffer?.name),this.name||(this.name="Untitled"),this.flipY=t.flipY??!1,this._mipLevel=t.mipLevel??0,this._mipLevel>0&&this._depth&&(this._mipLevel=0),this._mipmaps=t.mipLevel===void 0,this.evaluateDimensions(),this.validateMrt(),this.impl=e.createRenderTargetImpl(this)}destroy(){let t=this._device;t&&(t.targets.delete(this),t.renderTarget===this&&t.setRenderTarget(null),this.destroyFrameBuffers())}destroyFrameBuffers(){let t=this._device;t&&this.impl.destroy(t)}destroyTextureBuffers(){this._depthBuffer?.destroy(),this._depthBuffer=null,this._colorBuffers?.forEach(t=>{t.destroy()}),this._colorBuffers=null,this._colorBuffer=null}resize(t,e){if(!(this.mipLevel>0)&&(this._depthBuffer?.resize(t,e),this._colorBuffers?.forEach(s=>{s.resize(t,e)}),this._width!==t||this._height!==e)){this.destroyFrameBuffers();let s=this._device;s.renderTarget===this&&s.setRenderTarget(null),this.evaluateDimensions(),this.validateMrt(),this.impl=s.createRenderTargetImpl(this)}}validateMrt(){}evaluateDimensions(){let t=this._colorBuffer??this._depthBuffer;t&&(this._width=t.width,this._height=t.height,this._mipLevel>0&&(this._width=gt.calcLevelDimension(this._width,this._mipLevel),this._height=gt.calcLevelDimension(this._height,this._mipLevel)))}init(){this.impl.init(this._device,this)}get initialized(){return this.impl.initialized}get device(){return this._device}loseContext(){this.impl.loseContext()}resolve(t=!0,e=!!this._depthBuffer){this._device&&this._samples>1&&this.impl.resolve(this._device,this,t,e)}copy(t,e,s){if(!this._device)if(t._device)this._device=t._device;else return!1;return this._device.copyRenderTarget(t,this,e,s)}get samples(){return this._samples}get depth(){return this._depth}get stencil(){return this._stencil}get colorBuffer(){return this._colorBuffer}getColorBuffer(t){return this._colorBuffers?.[t]}get depthBuffer(){return this._depthBuffer}get face(){return this._face}get mipLevel(){return this._mipLevel}get mipmaps(){return this._mipmaps}get width(){return this._width??this._device.width}get height(){return this._height??this._device.height}isColorBufferSrgb(t=0){if(this.device.backBuffer===this)return df(this.device.backBufferFormat);let e=this.getColorBuffer(t);return e?df(e.format):!1}};var Zx=class{constructor(){n(this,"bindGroup")}update(t){this.destroy();let e=t.device,s=this.createDescriptor(e,t);this.bindGroup=e.wgpu.createBindGroup(s)}destroy(){this.bindGroup=null}createDescriptor(t,e){let s=[],i=e.format,r=e.format.uniformBufferFormats;e.uniformBuffers.forEach((f,u)=>{let d=r[u].slot,p=f.persistent?f.impl.buffer:f.allocation.gpuBuffer.buffer;s.push({binding:d,resource:{buffer:p,offset:0,size:f.format.byteSize}})});let a=e.format.textureFormats;e.textures.forEach((f,u)=>{let d=f instanceof Zr,m=(d?f.texture:f).impl,_=i.textureFormats[u],S=a[u].slot,g=m.getView(t,d?f:void 0);if(s.push({binding:S,resource:g}),_.hasSampler){let T=m.getSampler(t,_.sampleType);s.push({binding:S+1,resource:T})}});let o=e.format.storageTextureFormats;e.storageTextures.forEach((f,u)=>{let d=f instanceof Zr,m=(d?f.texture:f).impl,_=o[u].slot,S=m.getView(t,d?f:void 0);s.push({binding:_,resource:S})});let l=e.format.storageBufferFormats;return e.storageBuffers.forEach((f,u)=>{let d=f.impl.buffer,p=l[u].slot;s.push({binding:p,resource:{buffer:d}})}),{layout:e.format.impl.bindGroupLayout,entries:s}}};var kd=class{static shaderStage(t){let e=0;return t&Xi&&(e|=GPUShaderStage.VERTEX),t&Yi&&(e|=GPUShaderStage.FRAGMENT),t&X&&(e|=GPUShaderStage.COMPUTE),e}};var he=[];he[pd]="";he[md]="";he[vo]="";he[Wr]="r8unorm";he[Po]="rg8unorm";he[ya]="";he[xn]="";he[Ea]="";he[Ss]="rgba8unorm";he[ce]="rgba8unorm";he[To]="bc1-rgba-unorm";he[Ql]="bc2-rgba-unorm";he[Gr]="bc3-rgba-unorm";he[vn]="";he[Me]="rgba16float";he[yn]="r16float";he[of]="rg16float";he[Kh]="";he[ke]="rgba32float";he[Mt]="r32float";he[nf]="rg32float";he[Ys]="depth32float";he[Xr]="depth16unorm";he[fr]="depth24plus-stencil8";he[Gi]="rg11b10ufloat";he[yo]="";he[st]="rgba8unorm-srgb";he[Eo]="";he[Jl]="etc2-rgb8unorm";he[ec]="etc2-rgba8unorm";he[Vr]="";he[Hr]="";he[Ao]="";he[Co]="";he[_d]="astc-4x4-unorm";he[gd]="";he[Sd]="";he[tc]="bgra8unorm";he[ic]="bgra8unorm-srgb";he[jh]="r8sint";he[sc]="r8uint";he[qh]="r16sint";he[$h]="r16uint";he[Zh]="r32sint";he[zt]="r32uint";he[Qh]="rg8sint";he[xd]="rg8uint";he[Jh]="rg16sint";he[ef]="rg16uint";he[tf]="rg32sint";he[Tn]="rg32uint";he[sf]="rgba8sint";he[vd]="rgba8uint";he[rf]="rgba16sint";he[Rs]="rgba16uint";he[af]="rgba32sint";he[At]="rgba32uint";he[Td]="bc6h-rgb-float";he[yd]="bc6h-rgb-ufloat";he[Ed]="bc7-rgba-unorm";he[lf]="rgb9e5ufloat";he[cf]="rg8snorm";he[hf]="rgba8snorm";he[ff]="rgb10a2unorm";he[uf]="rgb10a2uint";he[kh]="bc1-rgba-unorm-srgb";he[zh]="bc2-rgba-unorm-srgb";he[Gh]="bc3-rgba-unorm-srgb";he[Vh]="etc2-rgb8unorm-srgb";he[Hh]="etc2-rgba8unorm-srgb";he[Xh]="bc7-rgba-unorm-srgb";he[Wh]="astc-4x4-unorm-srgb";var zd=[];zd[rs]="filtering";zd[Vi]="non-filtering";zd[gi]="comparison";zd[Hi]="comparison";zd[Wi]="comparison";var Gd=[];Gd[rs]="float";Gd[Vi]="unfilterable-float";Gd[gi]="depth";Gd[Hi]="sint";Gd[Wi]="uint";var P5=new Si,Qx=class{constructor(t){let e=t.device,{key:s,desc:i}=this.createDescriptor(t);this.key=P5.get(s),this.bindGroupLayout=e.wgpu.createBindGroupLayout(i)}destroy(){this.bindGroupLayout=null}loseContext(){}createDescriptor(t){let e=[],s="";return t.uniformBufferFormats.forEach(r=>{let a=kd.shaderStage(r.visibility);s+=`#${r.slot}U:${a}`,e.push({binding:r.slot,visibility:a,buffer:{type:"uniform",hasDynamicOffset:!0}})}),t.textureFormats.forEach(r=>{let a=kd.shaderStage(r.visibility),o=r.sampleType,l=r.textureDimension,h=!1,f=Gd[o];if(s+=`#${r.slot}T:${a}-${f}-${l}-${h}`,e.push({binding:r.slot,visibility:a,texture:{sampleType:f,viewDimension:l,multisampled:h}}),r.hasSampler){let u=zd[o];s+=`#${r.slot+1}S:${a}-${u}`,e.push({binding:r.slot+1,visibility:a,sampler:{type:u}})}}),t.storageTextureFormats.forEach(r=>{let{format:a,textureDimension:o}=r,{read:l,write:h}=r;s+=`#${r.slot}ST:${a}-${o}-${l?"r1":"r0"}-${h?"w1":"w0"}`,e.push({binding:r.slot,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:l?h?"read-write":"read-only":"write-only",format:he[a],viewDimension:o}})}),t.storageBufferFormats.forEach(r=>{let a=r.readOnly,o=kd.shaderStage(r.visibility);s+=`#${r.slot}SB:${o}-${a?"ro":"rw"}`,e.push({binding:r.slot,visibility:o,buffer:{type:a?"read-only-storage":"storage"}})}),{key:s,desc:{entries:e}}}};var Lo=class{constructor(t=0){n(this,"buffer",null);n(this,"usageFlags",0);this.usageFlags=t}destroy(t){this.buffer&&(t.deferDestroy(this.buffer),this.buffer=null)}get initialized(){return!!this.buffer}loseContext(){this.buffer=null}allocate(t,e){this.buffer=t.wgpu.createBuffer({size:e,usage:this.usageFlags})}unlock(t,e){let s=t.wgpu;if(!this.buffer){let o=e.byteLength+3&-4;this.usageFlags|=GPUBufferUsage.COPY_DST,this.allocate(t,o)}let i=e.byteOffset??0,r=new Uint8Array(e.buffer??e,i,e.byteLength),a=new Uint8Array(this.buffer.size);a.set(r),s.queue.writeBuffer(this.buffer,0,a,0,a.length)}read(t,e,s,i,r){return t.readStorageBuffer(this,e,s,i,r)}write(t,e,s,i,r){t.writeStorageBuffer(this,e,s,i,r)}clear(t,e,s){t.clearStorageBuffer(this,e,s)}};var Jx=class extends Lo{constructor(e,s){super(16|(s?.storage?128:0));n(this,"format",null);this.format=e.format===1?"uint16":"uint32"}unlock(e){let s=e.device;super.unlock(s,e.storage)}};var ev={equals(c,t){if(c.length!==t.length)return!1;for(let e=0;e{let a=r.interleaved,o=r.instancing?"instance":"vertex",l=[],h=r.elements.length;for(let f=0;f1?`x${u.numComponents}`:""}`}),(!a||f===h-1)&&(s.push({attributes:l,arrayStride:u.stride,stepMode:o}),l=[])}};return t&&i(t),e&&i(e),s}};var w5=0,Vd=class{constructor(t){this.device=t}getPipelineLayout(t){let e=[];t.forEach(r=>{e.push(r.bindGroupLayout)});let s={bindGroupLayouts:e};return w5++,this.device.wgpu.createPipelineLayout(s)}};var I5=0,R5=["point-list","line-list",void 0,"line-strip","triangle-list","triangle-strip",void 0],kD=["add","subtract","reverse-subtract","min","max"],sv=["zero","one","src","one-minus-src","dst","one-minus-dst","src-alpha","src-alpha-saturated","one-minus-src-alpha","dst-alpha","one-minus-dst-alpha","constant","one-minus-constant"],vP=["never","less","equal","less-equal","greater","not-equal","greater-equal","always"],b5=["none","back","front"],D5=["ccw","cw"],Hd=["keep","zero","replace","increment-clamp","increment-wrap","decrement-clamp","decrement-wrap","invert"],L5=["","uint16","uint32"],TP=class{constructor(){n(this,"pipeline");n(this,"hashes")}},iv=class extends Vd{constructor(e){super(e);n(this,"lookupHashes",new Uint32Array(15));this.vertexBufferLayout=new tv,this.cache=new Map}get(e,s,i,r,a,o,l,h,f,u,d,p,m,_){let S=e.type;r&&S!==mf&&S!==Ks&&(r=void 0);let g=this.lookupHashes;g[0]=S,g[1]=a.id,g[2]=u,g[3]=f.key,g[4]=h.key,g[5]=s?.renderingHash??0,g[6]=i?.renderingHash??0,g[7]=o.impl.key,g[8]=l[0]?.key??0,g[9]=l[1]?.key??0,g[10]=l[2]?.key??0,g[11]=d?p.key:0,g[12]=d?m.key:0,g[13]=r??0,g[14]=_;let T=dc(g),C=this.cache.get(T);if(C)for(let A=0;A0){let v=0;o.redWrite&&(v|=GPUColorWrite.RED),o.greenWrite&&(v|=GPUColorWrite.GREEN),o.blueWrite&&(v|=GPUColorWrite.BLUE),o.alphaWrite&&(v|=GPUColorWrite.ALPHA);let E=this.getBlend(o);T.forEach(y=>{g.fragment.targets.push({format:y.format,writeMask:v,blend:E})})}return I5++,_.createRenderPipeline(g)}};var M5=0,yP=class{constructor(){n(this,"pipeline",null);n(this,"hashes",null)}},rv=class extends Vd{constructor(){super(...arguments);n(this,"lookupHashes",new Uint32Array(2));n(this,"cache",new Map)}get(e,s){let i=this.lookupHashes;i[0]=e.impl.computeKey,i[1]=s.impl.key;let r=dc(i),a=this.cache.get(r);if(a)for(let h=0;h{t.object?.destroy()}),this.cache.clear()}clear(){this.cache.clear()}get(t){let e=this.cache.get(t);return e?(e.incRefCount(),e.object):null}set(t,e){this.cache.set(t,new EP(e))}release(t){let e=this.cache.get(t);e&&(e.decRefCount(),e.refCount===0&&(this.cache.delete(t),e.object?.destroy()))}};var AP=class extends av{loseContext(t){this.clear()}},O5=new et,Af=c=>O5.get(c,()=>new AP);var F5=new Si,CP=class{constructor(){n(this,"format");n(this,"multisampledBuffer")}destroy(t){t.deferDestroy(this.multisampledBuffer),this.multisampledBuffer=null}},ov=class{constructor(t){n(this,"format");n(this,"hasStencil");n(this,"depthTexture",null);n(this,"depthTextureInternal",!1);n(this,"multisampledDepthBuffer",null);n(this,"multisampledDepthBufferKey");this.format=t,this.hasStencil=t==="depth24plus-stencil8"}destroy(t){this.depthTextureInternal&&(t.deferDestroy(this.depthTexture),this.depthTexture=null),this.multisampledDepthBuffer&&(this.multisampledDepthBuffer=null,Af(t).release(this.multisampledDepthBufferKey))}},nv=class{constructor(t){n(this,"initialized",!1);n(this,"key");n(this,"colorAttachments",[]);n(this,"depthAttachment",null);n(this,"assignedColorTexture",null);n(this,"renderPassDescriptor",{});n(this,"isBackbuffer",!1);this.renderTarget=t}destroy(t){this.initialized=!1,this.assignedColorTexture=null,this.colorAttachments.forEach(e=>{e.destroy(t)}),this.colorAttachments.length=0,this.depthAttachment?.destroy(t),this.depthAttachment=null}updateKey(){let e=`${this.renderTarget.samples}:${this.depthAttachment?this.depthAttachment.format:"nodepth"}`;this.colorAttachments.forEach(s=>{e+=`:${s.format}`}),this.key=F5.get(e)}assignColorTexture(t,e){this.assignedColorTexture=t;let s=this.renderTarget.device,i=s?.xrColorTextureViewDescriptor,r=i&&t===s.xrColorTexture,a=t.createView(r?i:{format:e}),o=this.renderPassDescriptor.colorAttachments[0];this.renderTarget.samples>1?o.resolveTarget=a:o.view=a,this.setColorAttachment(0,void 0,e),this.updateKey()}setColorAttachment(t,e,s){this.colorAttachments[t]||(this.colorAttachments[t]=new CP),e&&(this.colorAttachments[t].multisampledBuffer=e),s&&(this.colorAttachments[t].format=s)}init(t,e){let s=t.wgpu;this.initDepthStencil(t,s,e),e._colorBuffers&&e._colorBuffers.forEach((r,a)=>{this.setColorAttachment(a,void 0,r.impl.format)}),this.renderPassDescriptor.colorAttachments=[];let i=this.isBackbuffer?1:e._colorBuffers?.length??0;for(let r=0;r1){let f="depth24plus-stencil8";this.depthAttachment.format=f,this.depthAttachment.hasStencil=f==="depth24plus-stencil8";let u=`${l.id}:${r}:${a}:${i}:${f}`,d=Af(t),p=d.get(u);if(!p){let m={size:[r,a,1],dimension:"2d",sampleCount:i,format:f,usage:GPUTextureUsage.RENDER_ATTACHMENT|(f!==l.impl.format?GPUTextureUsage.TEXTURE_BINDING:0)};p=e.createTexture(m),d.set(u,p)}this.depthAttachment.multisampledDepthBuffer=p,this.depthAttachment.multisampledDepthBufferKey=u,h=p.createView()}else{let f=l.impl.gpuTexture;this.depthAttachment.depthTexture=f,h=f.createView()}else{this.depthAttachment=new ov("depth24plus-stencil8");let f={size:[r,a,1],dimension:"2d",sampleCount:i,format:this.depthAttachment.format,usage:GPUTextureUsage.RENDER_ATTACHMENT};i>1?f.usage|=GPUTextureUsage.TEXTURE_BINDING:f.usage|=GPUTextureUsage.COPY_SRC;let u=e.createTexture(f);this.depthAttachment.depthTexture=u,this.depthAttachment.depthTextureInternal=!0,h=u.createView()}this.renderPassDescriptor.depthStencilAttachment={view:h}}}initColor(t,e,s,i){let r={},{samples:a,width:o,height:l,mipLevel:h}=s,f=s.getColorBuffer(i),u=null;if(f&&(f.cubemap?u=f.impl.createView({dimension:"2d",baseArrayLayer:s.face,arrayLayerCount:1,mipLevelCount:1,baseMipLevel:h}):u=f.impl.createView({mipLevelCount:1,baseMipLevel:h})),a>1){let d=this.isBackbuffer?this.colorAttachments[i]?.format??t.backBufferViewFormat:f.impl.format,p={size:[o,l,1],dimension:"2d",sampleCount:a,format:d,usage:GPUTextureUsage.RENDER_ATTACHMENT},m=e.createTexture(p);this.setColorAttachment(i,m,p.format),r.view=m.createView(),r.resolveTarget=u}else r.view=u;return r}setupForRenderPass(t,e){let s=this.renderPassDescriptor.colorAttachments?.length??0;for(let r=0;r0)switch(e){case Te:this.updateType=On;break;case bi:this.updateType=Fa;break;case pe:this.updateType=Bn;break;case wo:this.updateType=Un;break;case pr:this.updateType=Fn;break;case jr:this.updateType=Na;break;case Ma:this.updateType=kn;break;case Dn:this.updateType=zn;break;case Kt:this.updateType=Nn;break;case Di:this.updateType=Ba;break;case Oa:this.updateType=Gn;break;case Ln:this.updateType=Vn;break;case oi:this.updateType=gf;break;case qr:this.updateType=cc;break;case Li:this.updateType=Sf;break;case Mn:this.updateType=xf;break;case as:this.updateType=wg;break;default:break}this.count=s;let i=this.numComponents;s&&(i=R.roundUp(i,4)),this.byteSize=i*4,s&&(this.byteSize*=s)}get isArrayType(){return this.count>0}calculateOffset(t){let e=this.byteSize<=8?this.byteSize:16;this.count&&(e=16),t=R.roundUp(t,e),this.offset=t/4}},Xe=class{constructor(t,e){n(this,"byteSize",0);n(this,"map",new Map);this.scope=t.scope,this.uniforms=e;let s=0;for(let i=0;inew IP(v,s)),_=c.processUniforms(t,m,e.processingOptions,s),S=`${l} ${h} ${_.code}`,g=r.src.replace(wP,S),T=`${f} ${u} ${_.code}`,C=a.src.replace(wP,T);return{vshader:g,fshader:C,attributes:o,meshUniformBufferFormat:_.meshUniformBufferFormat,meshBindGroupFormat:_.meshBindGroupFormat}}static extract(t){let e=[],s=[],i=[],r=[],a=`${wP} `,o;for(;(o=zD.exec(t))!==null;){let l=o[1];switch(l){case"attribute":case"varying":case"uniform":case"out":{PP.lastIndex=o.index;let h=PP.exec(t);l==="attribute"?e.push(h[2]):l==="varying"?s.push(h[2]):l==="out"?i.push(h[2]):l==="uniform"&&r.push(h[2]),t=c.cutOut(t,o.index,PP.lastIndex,a),zD.lastIndex=o.index+a.length,a="";break}}}return{src:t,attributes:e,varyings:s,outs:i,uniforms:r}}static processUniforms(t,e,s,i){let r=[],a=[];e.forEach(d=>{d.isSampler?r.push(d):a.push(d)});let o=[];a.forEach(d=>{if(!s.hasUniform(d.name)){let p=Vx.indexOf(d.type),m=new Y(d.name,p,d.arraySize);o.push(m)}}),o.length===0&&o.push(new Y(yf,Te));let l=o.length?new Xe(t,o):null,h=[];r.forEach(d=>{if(!s.hasTexture(d.name)){let p=rs;d.isSignedInt?p=Hi:d.isUnsignedInt?p=Wi:(d.precision==="highp"&&(p=Vi),U5.has(d.type)&&(p=gi));let m=k5[d.type];h.push(new Ki(d.name,Xi|Yi,m,p))}});let f=new Ue(t,h),u="";return s.uniformFormats.forEach((d,p)=>{d&&(u+=c.getUniformShaderDeclaration(d,p,0))}),l&&(u+=c.getUniformShaderDeclaration(l,$r,0)),s.bindGroupFormats.forEach((d,p)=>{d&&(u+=c.getTexturesShaderDeclaration(d,p))}),u+=c.getTexturesShaderDeclaration(f,Ua),{code:u,meshUniformBufferFormat:l,meshBindGroupFormat:f}}static processVaryings(t,e,s){let i="",r=s?"out":"in";return t.forEach((a,o)=>{let l=c.splitToWords(a),h=l.slice(0,-1).join(" "),f=l[l.length-1];s?e.set(f,o):o=e.get(f),i+=`layout(location = ${o}) ${r} ${h} ${f}; `}),i}static processOuts(t){let e="";return t.forEach((s,i)=>{e+=`layout(location = ${i}) out ${s}; `}),e}static getTypeCount(t){let e=t.substring(t.length-1),s=parseInt(e,10);return isNaN(s)?1:s}static processAttributes(t,e,s,i){let r="",a={};return t.forEach(o=>{let l=c.splitToWords(o),h=l[0],f=l[1];if(e.hasOwnProperty(f)){let u=e[f],d=ze[u];a[d]=u,s.set(d,f);let p,m=i.getVertexElement(u);if(m){let _=m.dataType;if(_!==ye&&_!==nc&&!m.normalize&&!m.asInt){let S=c.getTypeCount(h),g=`_private_${f}`;p=`vec${S} ${f} = vec${S}(${g}); `,f=g;let T=_===js||_===qs||_===He;S===1?h=T?"int":"uint":h=T?`ivec${S}`:`uvec${S}`}}r+=`layout(location = ${d}) in ${h} ${f}; `,p&&(r+=p)}}),r}static splitToWords(t){return t=t.replace(/\s+/g," ").trim(),t.split(" ")}static cutOut(t,e,s,i){return t.substring(0,e)+i+t.substring(s)}static getUniformShaderDeclaration(t,e,s){let i=Ng[e],r=`layout(set = ${e}, binding = ${s}, std140) uniform ub_${i} { `;return t.uniforms.forEach(a=>{let o=Vx[a.type];r+=` ${o} ${a.shortName}${a.count?`[${a.count}]`:""}; `}),`${r}}; `}static getTexturesShaderDeclaration(t,e){let s="";return t.textureFormats.forEach(i=>{let r=z5[i.textureDimension],a=r==="texture2DArray",o=i.sampleType===Wi?"u":i.sampleType===Hi?"i":"";r=`${o}${r}`;let l="",h="";a&&(l="_texture",h=`#define ${i.name} ${o}sampler2DArray(${i.name}${l}, ${i.name}_sampler) `),s+=`layout(set = ${e}, binding = ${i.slot}) uniform ${r} ${i.name}${l}; `,i.hasSampler&&(s+=`layout(set = ${e}, binding = ${i.slot+1}) uniform sampler ${i.name}_sampler; `),s+=h}),s}};var GD=/^[ \t]*(attribute|varying|uniform)[\t ]+/gm,RP=/^[ \t]*(attribute|varying|uniform)[ \t]*([^;]+)(;+)/gm,bP=/^[ \t]*var\s*(?:(]*>)\s*([\w\d_]+)\s*:\s*(.*?)\s*;|(<(?!storage,)[^>]*>)?\s*([\w\d_]+)\s*:\s*(texture_.*|storage_texture_.*|storage\w.*|external_texture|sampler(?:_comparison)?)\s*;)\s*$/gm,G5=/(?:@interpolate\([^)]*\)\s*)?([\w]+)\s*:\s*([\w<>]+)/,DP="@@@",LP=/(@vertex|@fragment)\s*fn\s+\w+\s*\(\s*(\w+)\s*:[\s\S]*?\{/,VD=[{wgslName:"position",wgslType:"vec4f",wgslBuiltin:"position",pcName:"pcPosition",isFallback:!0},{wgslName:"frontFacing",wgslType:"bool",wgslBuiltin:"front_facing",pcName:"pcFrontFacing"},{wgslName:"sampleIndex",wgslType:"u32",wgslBuiltin:"sample_index",pcName:"pcSampleIndex"},{wgslName:"primitiveIndex",wgslType:"u32",wgslBuiltin:"primitive_index",pcName:"pcPrimitiveIndex",requiresFeature:"supportsPrimitiveIndex"}],HD=[{wgslName:"vertexIndex",wgslType:"u32",wgslBuiltin:"vertex_index",pcName:"pcVertexIndex",isFallback:!0},{wgslName:"instanceIndex",wgslType:"u32",wgslBuiltin:"instance_index",pcName:"pcInstanceIndex"}],WD=(c,t,e,s)=>c.filter(i=>i.requiresFeature&&!s[i.requiresFeature]?!1:new RegExp(`\\b(?:${i.pcName}|${e}\\.${i.wgslName})\\b`).test(t)),XD=(c,t,e,s)=>{if(c.length===0&&!s){let i=t.find(r=>r.isFallback&&(!r.requiresFeature||e[r.requiresFeature]));if(i)return[i]}return c},YD=c=>c.map(t=>` @builtin(${t.wgslBuiltin}) ${t.wgslName} : ${t.wgslType}, `).join(""),KD=c=>c.map(t=>` var ${t.pcName}: ${t.wgslType}; `).join(""),jD=c=>c.map(t=>` ${t.pcName} = input.${t.wgslName}; `).join(""),V5={texture_1d:{viewDimension:zx,baseSampleType:rs},texture_2d:{viewDimension:Ds,baseSampleType:rs},texture_2d_array:{viewDimension:Yr,baseSampleType:rs},texture_3d:{viewDimension:bn,baseSampleType:rs},texture_cube:{viewDimension:Kr,baseSampleType:rs},texture_cube_array:{viewDimension:Dd,baseSampleType:rs},texture_multisampled_2d:{viewDimension:Ds,baseSampleType:rs},texture_depth_2d:{viewDimension:Ds,baseSampleType:gi},texture_depth_2d_array:{viewDimension:Yr,baseSampleType:gi},texture_depth_cube:{viewDimension:Kr,baseSampleType:gi},texture_depth_cube_array:{viewDimension:Dd,baseSampleType:gi},texture_external:{viewDimension:Ds,baseSampleType:Vi}},H5=(c,t)=>{let e=V5[c],s=e.baseSampleType;if(e.baseSampleType===rs&&c!=="texture_multisampled_2d")switch(t){case"u32":s=Wi;break;case"i32":s=Hi;break;case"f32":s=rs;break;case"uff":s=Vi;break}return{viewDimension:e.viewDimension,sampleType:s}},W5=(c,t)=>{if(t===gi)switch(c){case Ds:return"texture_depth_2d";case Yr:return"texture_depth_2d_array";case Kr:return"texture_depth_cube";case Dd:return"texture_depth_cube_array";default:}let e;switch(c){case zx:e="texture_1d";break;case Ds:e="texture_2d";break;case Yr:e="texture_2d_array";break;case bn:e="texture_3d";break;case Kr:e="texture_cube";break;case Dd:e="texture_cube_array";break;default:}let s;switch(t){case rs:case Vi:s="f32";break;case Wi:s="u32";break;case Hi:s="i32";break;default:}return`${e}<${s}>`},qD={f32:"WrappedF32",i32:"WrappedI32",u32:"WrappedU32",vec2f:"WrappedVec2F",vec2i:"WrappedVec2I",vec2u:"WrappedVec2U"},$D=c=>(c=c.replace(/\s+/g," ").trim(),c.split(/[\s:]+/)),X5=/array<([^,]+),\s*([^>]+)>/,MP=class{constructor(t,e){n(this,"ubName",null);n(this,"arraySize",0);this.line=t;let s=$D(t);if(s.length<2){e.failed=!0;return}if(this.name=s[0],this.type=s.slice(1).join(" "),this.type.includes("array<")){let i=X5.exec(this.type);this.type=i[1].trim(),this.arraySize=Number(i[2]),isNaN(this.arraySize)&&(e.failed=!0)}}},Y5=/^\s*var\s+(\w+)\s*:\s*(texture_\w+)(?:<(\w+)>)?;\s*$/,K5=/^\s*var\s+([\w\d_]+)\s*:\s*(texture_storage_2d|texture_storage_2d_array)<([\w\d_]+),\s*(\w+)>\s*;\s*$/,j5=/^\s*var\s*\s*([\w\d_]+)\s*:\s*(.*)\s*;\s*$/,q5=/^\s*var\s+([\w\d_]+)\s*:\s*texture_external;\s*$/,$5=/^\s*var\s+([\w\d_]+)\s*:\s*(sampler|sampler_comparison)\s*;\s*$/,cv=class{constructor(t,e){this.originalLine=t,this.line=t,this.isTexture=!1,this.isSampler=!1,this.isStorageTexture=!1,this.isStorageBuffer=!1,this.isExternalTexture=!1,this.type="",this.matchedElements=[];let s=this.line.match(Y5);if(s){this.name=s[1],this.type=s[2],this.textureFormat=s[3],this.isTexture=!0,this.matchedElements.push(...s);let l=H5(this.type,this.textureFormat);this.textureDimension=l.viewDimension,this.sampleType=l.sampleType}let i=this.line.match(K5);i&&(this.isStorageTexture=!0,this.name=i[1],this.textureType=i[2],this.format=i[3],this.access=i[4],this.matchedElements.push(...i));let r=this.line.match(j5);r&&(this.isStorageBuffer=!0,this.accessMode=r[1]||"none",this.name=r[2],this.type=r[3],this.matchedElements.push(...r));let a=this.line.match(q5);a&&(this.name=a[1],this.isExternalTexture=!0,this.matchedElements.push(...r));let o=this.line.match($5);o&&(this.name=o[1],this.samplerType=o[2],this.isSampler=!0,this.matchedElements.push(...o)),this.matchedElements.length===0&&(e.failed=!0)}equals(t){return!(this.name!==t.name||this.type!==t.type||this.isTexture!==t.isTexture||this.isSampler!==t.isSampler||this.isStorageTexture!==t.isStorageTexture||this.isStorageBuffer!==t.isStorageBuffer||this.isExternalTexture!==t.isExternalTexture||this.textureFormat!==t.textureFormat||this.textureDimension!==t.textureDimension||this.sampleType!==t.sampleType||this.textureType!==t.textureType||this.format!==t.format||this.access!==t.access||this.accessMode!==t.accessMode||this.samplerType!==t.samplerType)}},hv=class c{static run(t,e,s){let i=new Map,r=c.extract(e.vshader),a=c.extract(e.fshader),o=r.src.match(LP)?.[2]??"",l=a.src.match(LP)?.[2]??"",h=new Map,f=c.processAttributes(r.attributes,e.attributes,h,e.processingOptions,s,t,r.src,o),u=c.processVaryings(r.varyings,i,!0,t),d=c.processVaryings(a.varyings,i,!1,t,a.src,l),p=r.uniforms.concat(a.uniforms),_=Array.from(new Set(p)).map(A=>new MP(A,s)),S=c.processUniforms(t,_,e.processingOptions,s);r.src=c.renameUniformAccess(r.src,_),a.src=c.renameUniformAccess(a.src,_);let g=c.mergeResources(r.resources,a.resources,s),T=c.processResources(t,g,e.processingOptions,s),C=c.generateFragmentOutputStruct(a.src,t.maxColorAttachments);r.src=c.copyInputs(r.src,s),a.src=c.copyInputs(a.src,s);let v=`${f} ${u} ${S.code} ${T.code} `,E=r.src.replace(DP,v),y=`${d} ${C} ${S.code} ${T.code} `,P=a.src.replace(DP,y);return{vshader:E,fshader:P,attributes:h,meshUniformBufferFormat:S.meshUniformBufferFormat,meshBindGroupFormat:T.meshBindGroupFormat}}static extract(t){let e=[],s=[],i=[],r=[],a=`${DP} `,o;for(;(o=GD.exec(t))!==null;){let l=o[1];RP.lastIndex=o.index;let h=RP.exec(t);l==="attribute"?e.push(h[2]):l==="varying"?s.push(h[2]):l==="uniform"&&i.push(h[2]),t=c.cutOut(t,o.index,RP.lastIndex,a),GD.lastIndex=o.index+a.length,a=""}for(;(o=bP.exec(t))!==null;)r.push(o[0]),t=c.cutOut(t,o.index,bP.lastIndex,a),bP.lastIndex=o.index+a.length,a="";return{src:t,attributes:e,varyings:s,uniforms:i,resources:r}}static processUniforms(t,e,s,i){let r=[];e.forEach(l=>{if(s.hasUniform(l.name))l.ubName="ub_view";else{l.ubName="ub_mesh_ub";let h=Wx.get(l.type),f=new Y(l.name,h,l.arraySize);r.push(f)}}),r.length===0&&r.push(new Y(yf,Te));let a=new Xe(t,r),o="";return s.uniformFormats.forEach((l,h)=>{l&&(o+=c.getUniformShaderDeclaration(l,h,0))}),a&&(o+=c.getUniformShaderDeclaration(a,$r,0)),{code:o,meshUniformBufferFormat:a}}static renameUniformAccess(t,e){return e.forEach(s=>{let i=`uniform.${s.name}`,r=`${s.ubName}.${s.name}`,a=new RegExp(`\\b${i}\\b`,"g");t=t.replace(a,r)}),t}static mergeResources(t,e,s){let i=t.map(a=>new cv(a,s));return e.map(a=>new cv(a,s)).forEach(a=>{let o=i.find(l=>l.name===a.name);o?o.equals(a)||(s.failed=!0):i.push(a)}),i}static processResources(t,e,s,i){let r=[];for(let l=0;l{l&&(o+=c.getTextureShaderDeclaration(l,h))}),o+=c.getTextureShaderDeclaration(a,Ua),{code:o,meshBindGroupFormat:a}}static getUniformShaderDeclaration(t,e,s){let i=Ng[e],r=`struct_ub_${i}`,a=`struct ${r} { `;return t.uniforms.forEach(o=>{let l=Hx[o.type][0];o.count>0?(qD.hasOwnProperty(l)&&(l=qD[l]),a+=` ${o.shortName}: array<${l}, ${o.count}>, `):a+=` ${o.shortName}: ${l}, `}),a+=`}; `,a+=`@group(${e}) @binding(${s}) var ub_${i} : ${r}; `,a}static getTextureShaderDeclaration(t,e){let s="";return t.textureFormats.forEach(i=>{let r=W5(i.textureDimension,i.sampleType);if(s+=`@group(${e}) @binding(${i.slot}) var ${i.name}: ${r}; `,i.hasSampler){let a=i.sampleType===gi?"sampler_comparison":"sampler";s+=`@group(${e}) @binding(${i.slot+1}) var ${i.samplerName}: ${a}; `}}),t.storageBufferFormats.forEach(i=>{let r=i.readOnly?"read":"read_write";s+=`@group(${e}) @binding(${i.slot}) var ${i.name} : ${i.format}; `}),s}static processVaryings(t,e,s,i,r="",a=""){let o="",l="",h="";if(t.forEach((u,d)=>{let p=u.match(G5);if(p){let m=p[1],_=p[2];s?e.set(m,d):d=e.get(m),o+=` @location(${d}) ${u}, `,s||(l+=` var ${m}: ${_}; `,h+=` ${m} = input.${m}; `)}}),s)return o+=` @builtin(position) position : vec4f, `,` struct VertexOutput { ${o} }; `;let f=XD(WD(VD,r,a,i),VD,i,o.length>0);return o+=YD(f),` struct FragmentInput { ${o} }; ${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":"vec2f","vec3":"vec3f","vec4":"vec4f"}[t]||t;return{f32:e?"i32":"u32",vec2f:e?"vec2i":"vec2u",vec3f:e?"vec3i":"vec3u",vec4f:e?"vec4i":"vec4u"}[i]||null}static processAttributes(t,e={},s,i,r,a,o="",l=""){let h="",f="",u="",d={};t.forEach(m=>{let _=$D(m),S=_[0],g=_[1],T=g;if(e.hasOwnProperty(S)){let C=e[S],v=ze[C];d[v]=C,s.set(v,S);let E=i.getVertexElement(C);if(E){let y=E.dataType;if(y!==ye&&y!==nc&&!E.normalize&&!E.asInt){let P=y===js||y===qs||y===He;g=c.floatAttributeToInt(g,P)}}h+=` @location(${v}) ${S}: ${g}, `,f+=` var ${m}; `,u+=` ${S} = ${T}(input.${S}); `}});let p=XD(WD(HD,o,l,a),HD,a,h.length>0);return` struct VertexInput { ${h} ${YD(p)} }; ${f} ${KD(p)} fn _pcCopyInputs(input: VertexInput) { ${u} ${jD(p)} } `}static copyInputs(t,e){let s=t.match(LP);if(!s||!s[2])return t;let i=s[2],r=s.index+s[0].length-1,a=t.slice(0,r+1),o=t.slice(r+1),l=` _pcCopyInputs(${i});`;return a+l+o}static cutOut(t,e,s,i){return t.substring(0,e)+i+t.substring(s)}};var Z5=new Si,fv=class{constructor(t){n(this,"_vertexCode",null);n(this,"_fragmentCode",null);n(this,"_computeCode",null);n(this,"_computeKey");n(this,"vertexEntryPoint","main");n(this,"fragmentEntryPoint","main");n(this,"computeEntryPoint","main");this.shader=t;let e=t.definition;e.shaderLanguage===se?(e.cshader?(this._computeCode=e.cshader??null,this.computeUniformBufferFormats=e.computeUniformBufferFormats,this.computeBindGroupFormat=e.computeBindGroupFormat,e.computeEntryPoint&&(this.computeEntryPoint=e.computeEntryPoint)):(this.vertexEntryPoint="vertexMain",this.fragmentEntryPoint="fragmentMain",e.processingOptions?this.processWGSL():(this._vertexCode=e.vshader??null,this._fragmentCode=e.fshader??null,t.meshUniformBufferFormat=e.meshUniformBufferFormat,t.meshBindGroupFormat=e.meshBindGroupFormat)),t.ready=!0):e.processingOptions&&this.processGLSL()}destroy(t){this._vertexCode=null,this._fragmentCode=null}createShaderModule(t,e){return this.shader.device.wgpu.createShaderModule({code:t})}getVertexShaderModule(){return this.createShaderModule(this._vertexCode,"Vertex")}getFragmentShaderModule(){return this.createShaderModule(this._fragmentCode,"Fragment")}getComputeShaderModule(){return this.createShaderModule(this._computeCode,"Compute")}processGLSL(){let t=this.shader,e=lv.run(t.device,t.definition,t);this._vertexCode=this.transpile(e.vshader,"vertex",t.definition.vshader),this._fragmentCode=this.transpile(e.fshader,"fragment",t.definition.fshader),this._vertexCode&&this._fragmentCode?t.ready=!0:t.failed=!0,t.meshUniformBufferFormat=e.meshUniformBufferFormat,t.meshBindGroupFormat=e.meshBindGroupFormat,t.attributes=e.attributes}processWGSL(){let t=this.shader,e=hv.run(t.device,t.definition,t);this._vertexCode=e.vshader,this._fragmentCode=e.fshader,t.meshUniformBufferFormat=e.meshUniformBufferFormat,t.meshBindGroupFormat=e.meshBindGroupFormat,t.attributes=e.attributes}transpile(t,e,s){let i=this.shader.device;if(!i.glslang||!i.twgsl)return null;try{let r=i.glslang.compileGLSL(t,e);return i.twgsl.convertSpirV2WGSL(r)}catch{}}get vertexCode(){return this._vertexCode}get fragmentCode(){return this._fragmentCode}get computeKey(){if(this._computeKey===void 0){let t=`${this._computeCode}|${this.computeEntryPoint}`;this._computeKey=Z5.get(t)}return this._computeKey}loseContext(){}restoreContext(t,e){}};var Wd=[];Wd[0]="repeat";Wd[1]="clamp-to-edge";Wd[2]="mirror-repeat";var jn=[];jn[0]={level:"nearest",mip:"nearest"};jn[1]={level:"linear",mip:"nearest"};jn[2]={level:"nearest",mip:"nearest"};jn[3]={level:"nearest",mip:"linear"};jn[4]={level:"linear",mip:"nearest"};jn[5]={level:"linear",mip:"linear"};var Q5=c=>{},uv=class{constructor(t){n(this,"gpuTexture");n(this,"view");n(this,"samplers",[]);n(this,"desc");n(this,"format");n(this,"viewCache",new Map);this.texture=t,this.format=he[t.format],this.create(t.device)}create(t){let e=this.texture,s=t.wgpu,i=e.numLevels;En(e.format)&&(e.width%4!==0||e.height%4!==0)&&(e._width=R.roundUp(e.width,4),e._height=R.roundUp(e.height,4)),this.desc={size:{width:e.width,height:e.height,depthOrArrayLayers:e.cubemap?6:e.array?e.arrayLength:1},format:this.format,mipLevelCount:i,sampleCount:1,dimension:e.volume?"3d":"2d",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC|(En(e.format)?0:GPUTextureUsage.RENDER_ATTACHMENT)|(e.storage?GPUTextureUsage.STORAGE_BINDING:0)},this.gpuTexture=s.createTexture(this.desc);let r;this.texture.format===fr&&(r={format:"depth24plus",aspect:"depth-only"}),this.view=this.createView(r),this.viewCache.clear()}destroy(t){t.deferDestroy(this.gpuTexture),this.gpuTexture=null,this.view=null,this.viewCache.clear(),this.samplers.length=0}propertyChanged(t){this.samplers.length=0}getView(t,e){if(this.uploadImmediate(t,this.texture),e){let s=this.viewCache.get(e.key);return s||(s=this.createView({baseMipLevel:e.baseMipLevel,mipLevelCount:e.mipLevelCount,baseArrayLayer:e.baseArrayLayer,arrayLayerCount:e.arrayLayerCount}),this.viewCache.set(e.key,s)),s}return this.view}createView(t){let e=t??{},s=this.desc,i=this.texture,r=()=>i.cubemap?"cube":i.volume?"3d":i.array?"2d-array":"2d",a={format:e.format??s.format,dimension:e.dimension??r(),aspect:e.aspect??"all",baseMipLevel:e.baseMipLevel??0,mipLevelCount:e.mipLevelCount??s.mipLevelCount,baseArrayLayer:e.baseArrayLayer??0,arrayLayerCount:e.arrayLayerCount??s.depthOrArrayLayers};return this.gpuTexture.createView(a)}getSampler(t,e){let s=this.samplers[e];if(!s){let i=this.texture,r,a={addressModeU:Wd[i.addressU],addressModeV:Wd[i.addressV],addressModeW:Wd[i.addressW]};!e&&i.compareOnRead&&(e=gi),e===gi||e===Hi||e===Wi?(a.compare="less",a.magFilter="linear",a.minFilter="linear",r="Compare"):e===Vi?(a.magFilter="nearest",a.minFilter="nearest",a.mipmapFilter="nearest",r="Unfilterable"):!t.textureFloatFilterable&&(i.format===ke||i.format===Me)||this.texture.format===fr||ur(this.texture.format)?(a.magFilter="nearest",a.minFilter="nearest",a.mipmapFilter="nearest",r="Nearest"):(a.magFilter=jn[i.magFilter].level,a.minFilter=jn[i.minFilter].level,a.mipmapFilter=jn[i.minFilter].mip);let o=a.minFilter==="linear"&&a.magFilter==="linear"&&a.mipmapFilter==="linear";a.maxAnisotropy=o?R.clamp(Math.round(i._anisotropy),1,t.maxTextureAnisotropy):1,s=t.wgpu.createSampler(a),this.samplers[e]=s}return s}loseContext(){}uploadImmediate(t,e){(e._needsUpload||e._needsMipmapsUpload)&&(this.uploadData(t),e._needsUpload=!1,e._needsMipmapsUpload=!1)}uploadData(t){let e=this.texture;if(this.desc&&(this.desc.size.width!==e.width||this.desc.size.height!==e.height)&&(t.deferDestroy(this.gpuTexture),this.create(t),e.renderVersionDirty=t.renderVersion),e._levels){let s=!1,i=!1,r=e.numLevels;for(let a=0;aMath.floor((_+3)/4);d={offset:0,bytesPerRow:u.blockSize*m(l),rowsPerImage:m(h)},p={width:Math.max(4,l),height:Math.max(4,h)}}t.submit(),a.queue.writeTexture(o,e,d,p)}read(t,e,s,i,r){let a=r.mipLevel??0,o=r.face??0,l=r.data??null,h=r.immediate??!1,f=this.texture,u=xs.get(f.format),d=s*u.size,p=R.roundUp(d,256),m=p*i,_=f.device,S=_.createBufferImpl(9);S.allocate(_,m);let g={texture:this.gpuTexture,mipLevel:a,origin:[t,e,o]},T={buffer:S.buffer,offset:0,bytesPerRow:p},C={width:s,height:i,depthOrArrayLayers:1};return _.getCommandEncoder().copyTextureToBuffer(g,T,C),_.readBuffer(S,m,null,h).then(E=>{let y=pf(f.format),P=l?.buffer??new ArrayBuffer(i*d),A=new Uint8Array(P,l?.byteOffset??0,i*d);for(let w=0;w|>=)\s*([\w"']+)/i,iW=/[+\-]/g,UP=/include[ \t]+"([\w-]+)(?:\s*,\s*([\w-]+))?"/g,rW=/\{i\}/g,JD=/(pcFragColor[1-8])\b/g,aW=/^\d+(?:\.\d+)?$/,mr=class mr{static run(t,e=new Map,s={}){mr.sourceName=s.sourceName,t=this.stripComments(t),t=t.split(/\r?\n/).map(o=>o.trimEnd()).join(` `);let i=new Map,r=new Map;if(t=this._preprocess(t,i,r,e,s.stripDefines),t===null)return null;let a=new Map;return i.forEach((o,l)=>{Number.isInteger(parseFloat(o))&&!o.includes(".")&&a.set(l,o)}),t=this.stripComments(t),t=this.stripUnusedColorAttachments(t,s),t=this.RemoveEmptyLines(t),t=this.processArraySize(t,a),t=this.injectDefines(t,r),t}static stripUnusedColorAttachments(t,e){if(e.stripUnusedColorAttachments){let s=new Map;if(t.match(JD)?.forEach(a=>{let o=parseInt(a.charAt(a.length-1),10);s.set(o,(s.get(o)??0)+1)}),Array.from(s.values()).some(a=>a===1)){let a=t.split(` `),o=[];for(let l=0;l0&&s.get(f)===1)continue}o.push(a[l])}t=o.join(` `)}}return t}static stripComments(t){return t.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm,"$1")}static processArraySize(t,e){return t!==null&&e.forEach((s,i)=>{t=t.replace(new RegExp(`\\[${i}\\]`,"g"),`[${s}]`)}),t}static injectDefines(t,e){if(t!==null&&e.size>0){let s=t.split(` `);e.forEach((i,r)=>{let a=new RegExp(r,"g");for(let o=0;oe.trim()===""?"":e).join(` `),t=t.replace(/(\n\n){3,}/g,` `)),t}static _preprocess(t,e=new Map,s,i,r){let a=t,o=[],l=!1,h;for(;(h=ka.exec(t))!==null&&!l;){let f=h[1];switch(f){case"define":{OP.lastIndex=h.index;let u=OP.exec(t);l||(l=u===null);let d=u[1];QD.lastIndex=u.index;let m=QD.exec(d)[0],_=d.substring(m.length).trim();_===""&&(_="true");let S=mr._keep(o),g=r;if(S){let T=m.startsWith("{")&&m.endsWith("}");T&&(g=!0),T?s.set(m,_):e.set(m,_),g&&(t=t.substring(0,u.index-1)+t.substring(OP.lastIndex),ka.lastIndex=u.index-1)}g||(ka.lastIndex=u.index+u[0].length);break}case"undef":{FP.lastIndex=h.index;let u=FP.exec(t),d=u[1].trim();mr._keep(o)&&(e.delete(d),r&&(t=t.substring(0,u.index-1)+t.substring(FP.lastIndex),ka.lastIndex=u.index-1)),r||(ka.lastIndex=u.index+u[0].length);break}case"extension":{ZD.lastIndex=h.index;let u=ZD.exec(t);if(l||(l=u===null),u){let d=u[1];mr._keep(o)&&e.set(d,"true")}ka.lastIndex=u.index+u[0].length;break}case"ifdef":case"ifndef":case"if":{NP.lastIndex=h.index;let u=NP.exec(t),d=u[2],p=mr.evaluate(d,e);l||(l=p.error);let m=p.result;f==="ifndef"&&(m=!m),o.push({anyKeep:m,keep:m,start:h.index,end:NP.lastIndex}),ka.lastIndex=u.index+u[0].length;break}case"endif":case"else":case"elif":{BP.lastIndex=h.index;let u=BP.exec(t),d=o.pop();if(!d){l=!0;continue}let p=d.keep?t.substring(d.end,h.index):"";t=t.substring(0,d.start)+p+t.substring(BP.lastIndex),ka.lastIndex=d.start+p.length;let m=u[1];if(m==="else"||m==="elif"){let _=!1;if(!d.anyKeep)if(m==="else")_=!d.keep;else{let S=mr.evaluate(u[2],e);_=S.result,l||(l=S.error)}o.push({anyKeep:d.anyKeep||_,keep:_,start:ka.lastIndex,end:ka.lastIndex})}break}case"include":{UP.lastIndex=h.index;let u=UP.exec(t);if(l||(l=u===null),!u){l=!0;continue}let d=u[1].trim(),p=u[2]?.trim();if(mr._keep(o)){let _=i?.get(d);if(_!==void 0){if(_=this.stripComments(_),p){let S=e.get(p),g=parseFloat(S);if(Number.isInteger(g)){let T="";for(let C=0;C0&&(l=!0),l?null:t}static _keep(t){for(let e=0;e":u=l>h;break;case">=":u=l>=h;break;default:s=!0}return{result:u,error:s}}return{result:e.has(t),error:s}}static processParentheses(t,e){let s=!1,i=t.trim();for(;i.startsWith("(")&&i.endsWith(")");){let r=0,a=!0;for(let o=0;oo&&(o=a,l=m),r=!0)}else i[m]===")"&&(f>0?f--:a>0&&(a===o&&l!==-1&&(h=m),a--));if(!r||l===-1||h===-1)break;let u=i.substring(l+1,h),{result:d,error:p}=mr.evaluate(u,e);s=s||p,i=i.substring(0,l)+(d?"true":"false")+i.substring(h+1)}return{expression:i,error:s}}static evaluate(t,e){let s=iW.exec(t)===null,i=t,r=!1;if(t.replace(eW,"").indexOf("(")!==-1){let l=mr.processParentheses(t,e);i=l.expression,r=l.error}if(r)return{result:!1,error:!0};let o=i.split("||");for(let l of o){let h=l.split("&&"),f=!0;for(let u of h){let{result:d,error:p}=mr.evaluateAtomicExpression(u.trim(),e);if(!d||p){f=!1;break}}if(f)return{result:!0,error:!s}}return{result:!1,error:!s}}};n(mr,"sourceName");var Xd=mr;var mv=` #ifndef outType_0 #define outType_0 vec4 #endif 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) -> vec2 { var uv: vec2 = (clipPos.xy / clipPos.w) * 0.5 + vec2(0.5); uv.y = 1.0 - uv.y; return uv; } fn getImageEffectUV(uv: vec2) -> vec2 { var modifiedUV: vec2 = 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; alias half3 = vec3; alias half4 = vec4; alias half2x2 = mat2x2; alias half3x3 = mat3x3; alias half4x4 = mat4x4; #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{let m=c.getWGSLEnables(t,d?"vertex":"fragment");if(!d){let _=s(p);for(let S=0;S{s+=`#define ${r} ${i} `}),s+=` `,e?.forEach((i,r)=>{s+=`#define ${r} ${i} `}),s+=` `,s}static getShaderNameCode(t){return`#define SHADER_NAME ${t} `}static versionCode(t){return t.isWebGPU?`#version 450 `:`#version 300 es `}static precisionCode(t,e){e&&e!=="highp"&&e!=="mediump"&&e!=="lowp"&&(e=null),e&&(e==="highp"&&t.maxPrecision!=="highp"&&(e="mediump"),e==="mediump"&&t.maxPrecision==="lowp"&&(e="lowp"));let s=e||t.precision;return` precision ${s} float; precision ${s} int; precision ${s} usampler2D; precision ${s} isampler2D; precision ${s} sampler2DShadow; precision ${s} samplerCubeShadow; precision ${s} sampler2DArray; `}static collectAttributes(t){let e={},s=0,i=t.indexOf("attribute");for(;i>=0&&!(i>0&&t[i-1]==="/");){let r=!1;if(i>0){let a=t.lastIndexOf(` `,i);a=a!==-1?a+1:0,t.substring(a,i).includes("#")&&(r=!0)}if(!r){let a=t.indexOf(";",i),o=t.lastIndexOf(" ",a),l=t.substring(o+1,a);if(!e[l]){let h=oW[l];h!==void 0?e[l]=h:(e[l]=`ATTR${s}`,s++)}}i=t.indexOf("attribute",i+1)}return e}};var nW=0,Be=class{constructor(t,e){n(this,"meshUniformBufferFormat");n(this,"meshBindGroupFormat");n(this,"attributes",new Map);if(this.id=nW++,this.device=t,this.definition=e,this.name=e.name||"Untitled",this.init(),e.cshader){let s=ns.getWGSLEnables(t,"compute"),i=ns.getDefinesCode(t,e.cdefines),r=s+i+e.cshader,a=e.cincludes??new Map;a.has("halfTypesCS")||a.set("halfTypesCS",Ug),e.cshader=Xd.run(r,a,{sourceName:`compute shader for ${this.label}`,stripDefines:!0})}else{let s=e.shaderLanguage===se;e.vshader=Xd.run(e.vshader,e.vincludes,{sourceName:`vertex shader for ${this.label}`,stripDefines:s}),e.shaderLanguage===fe&&(e.attributes??(e.attributes=ns.collectAttributes(e.vshader)));let i=t.isWebGL2&&(ue.name==="osx"||ue.name==="ios");if(e.fshader=Xd.run(e.fshader,e.fincludes,{stripUnusedColorAttachments:i,stripDefines:s,sourceName:`fragment shader for ${this.label}`}),!e.vshader||!e.fshader){this.failed=!0;return}}this.impl=t.createShaderImpl(this)}init(){this.ready=!1,this.failed=!1}get label(){return`Shader Id ${this.id} (${this.definition.shaderLanguage===se?"WGSL":"GLSL"}) ${this.name}`}destroy(){this.device.onDestroyShader(this),this.impl.destroy(this)}loseContext(){this.init(),this.impl.loseContext()}restoreContext(){this.impl.restoreContext(this.device,this)}};var GP=class{constructor(){n(this,"gpuBuffer");n(this,"stagingBuffer");n(this,"offset");n(this,"size")}},Tv=class{constructor(){n(this,"storage");n(this,"gpuBuffer");n(this,"offset")}},yv=class{constructor(t,e,s){n(this,"bufferSize");n(this,"gpuBuffers",[]);n(this,"stagingBuffers",[]);n(this,"usedBuffers",[]);n(this,"activeBuffer",null);this.device=t,this.bufferSize=e,this.bufferAlignment=s}destroy(){this.gpuBuffers.forEach(t=>{t.destroy(this.device)}),this.gpuBuffers=null,this.stagingBuffers.forEach(t=>{t.destroy(this.device)}),this.stagingBuffers=null,this.usedBuffers=null,this.activeBuffer=null}alloc(t,e){if(this.activeBuffer){let r=R.roundUp(this.activeBuffer.size,this.bufferAlignment);this.bufferSize-r{let s=c.storageFloat32;s[e]=t[0],s[e+1]=t[1]};ut[Kt]=(c,t,e)=>{let s=c.storageFloat32;s[e]=t[0],s[e+1]=t[1],s[e+2]=t[2]};ut[oi]=(c,t,e)=>{let s=c.storageFloat32;s[e]=t[0],s[e+1]=t[1],s[e+2]=t[2],s[e+3]=t[3]};ut[bi]=function(c,t,e){let s=c.storageInt32;s[e]=t};ut[jr]=function(c,t,e){let s=c.storageInt32;s[e]=t[0],s[e+1]=t[1]};ut[Di]=function(c,t,e){let s=c.storageInt32;s[e]=t[0],s[e+1]=t[1],s[e+2]=t[2]};ut[qr]=function(c,t,e){let s=c.storageInt32;s[e]=t[0],s[e+1]=t[1],s[e+2]=t[2],s[e+3]=t[3]};ut[lc]=(c,t,e)=>{let s=c.storageFloat32;s[e]=t[0],s[e+1]=t[1],s[e+4]=t[2],s[e+5]=t[3],s[e+8]=t[4],s[e+9]=t[5]};ut[La]=(c,t,e)=>{let s=c.storageFloat32;s[e]=t[0],s[e+1]=t[1],s[e+2]=t[2],s[e+4]=t[3],s[e+5]=t[4],s[e+6]=t[5],s[e+8]=t[6],s[e+9]=t[7],s[e+10]=t[8]};ut[On]=function(c,t,e,s){let i=c.storageFloat32;for(let r=0;r{let i=c.storageFloat32;for(let r=0;r{let i=c.storageFloat32;for(let r=0;r{let i=c.storageUint32;i[e]=t};ut[Ma]=(c,t,e,s)=>{let i=c.storageUint32;i[e]=t[0],i[e+1]=t[1]};ut[Oa]=(c,t,e,s)=>{let i=c.storageUint32;i[e]=t[0],i[e+1]=t[1],i[e+2]=t[2]};ut[Li]=(c,t,e,s)=>{let i=c.storageUint32;i[e]=t[0],i[e+1]=t[1],i[e+2]=t[2],i[e+3]=t[3]};ut[Fa]=function(c,t,e,s){let i=c.storageInt32;for(let r=0;r{let i=c.storageInt32;for(let r=0;r{let i=c.storageUint32;for(let r=0;r{let i=c.storageInt32;for(let r=0;r{let i=c.storageUint32;for(let r=0;r ubMesh : ub_mesh; var pos : array = array( vec2(-1.0, 1.0), vec2(1.0, 1.0), vec2(-1.0, -1.0), vec2(1.0, -1.0) ); struct VertexOutput { @builtin(position) position : vec4f } @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 pos : array = array( vec2(-1.0, 1.0), vec2(1.0, 1.0), vec2(-1.0, -1.0), vec2(1.0, -1.0) ); struct VertexOutput { @builtin(position) position : vec4f, @location(0) texCoord : vec2f }; @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; @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=0;o--){let l=this.usedBuffers[o],{stagingBuffer:h,gpuBuffer:f,offset:u,size:d}=l,p=h.buffer;p.unmap(),r.copyBufferToBuffer(p,u,f.buffer,u,d),i.push(f)}let a=r.finish();s.addCommandBuffer(a,!0);for(let o=0;o{this.stagingBuffers&&(i.onAvailable(),this.stagingBuffers.push(i))})}this.pendingStagingBuffers.length=0}}};var Yd=class{constructor(){n(this,"frameAllocations",[]);n(this,"pastFrameAllocations",new Map);n(this,"_enabled",!1);n(this,"_enableRequest",!1);n(this,"_frameTime",0);n(this,"_passTimings",new Map);n(this,"_nameCache",new Map);n(this,"maxCount",9999)}loseContext(){this.pastFrameAllocations.clear()}set enabled(t){this._enableRequest=t}get enabled(){return this._enableRequest}get passTimings(){return this._passTimings}processEnableRequest(){this._enableRequest!==this._enabled&&(this._enabled=this._enableRequest,this._enabled||(this._frameTime=0))}request(t){this.pastFrameAllocations.set(t,this.frameAllocations),this.frameAllocations=[]}_parsePassName(t){let e=this._nameCache.get(t);return e===void 0&&(t.startsWith("RenderPass")?e=t.substring(10):e=t,this._nameCache.set(t,e)),e}report(t,e){if(e){let s=this.pastFrameAllocations.get(t);if(!s)return;e.length>0&&(this._frameTime=e.reduce((i,r)=>i+r,0)),this._passTimings.clear();for(let i=0;i=this.maxCount)return-1;let e=this.frameAllocations.length;return this.frameAllocations.push(t),e}get slotCount(){return this.frameAllocations.length}};var Iv=class{constructor(t,e,s){n(this,"querySet");n(this,"stagingBuffers",[]);n(this,"activeStagingBuffer",null);n(this,"bytesPerSlot");this.device=t,this.capacity=s,this.bytesPerSlot=e?8:4;let i=t.wgpu;this.querySet=i.createQuerySet({type:e?"timestamp":"occlusion",count:s}),this.queryBuffer=i.createBuffer({size:this.bytesPerSlot*s,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST})}destroy(){this.device.deferDestroy(this.querySet),this.querySet=null,this.device.deferDestroy(this.queryBuffer),this.queryBuffer=null,this.activeStagingBuffer=null,this.stagingBuffers.forEach(t=>{t.destroy()}),this.stagingBuffers=null}getStagingBuffer(){let t=this.stagingBuffers.pop();return t||(t=this.device.wgpu.createBuffer({size:this.queryBuffer.size,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})),t}resolve(t){let s=this.device.getCommandEncoder();s.resolveQuerySet(this.querySet,0,t,this.queryBuffer,0);let i=this.getStagingBuffer();this.activeStagingBuffer=i,s.copyBufferToBuffer(this.queryBuffer,0,i,0,this.bytesPerSlot*t)}request(t,e){let s=this.activeStagingBuffer;return this.activeStagingBuffer=null,s.mapAsync(GPUMapMode.READ).then(()=>{let i=new BigInt64Array(s.getMappedRange()),r=[];for(let a=0;a{this.report(s.renderVersion,s.timings)}),super.request(e)}}};var bv=class{constructor(t){n(this,"device");n(this,"pipelineCache",new Map);this.device=t;let e=` var pos : array = array( vec2(-1.0, 1.0), vec2(1.0, 1.0), vec2(-1.0, -1.0), vec2(1.0, -1.0) ); 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;lt.destroy()),this.uniformBuffers.length=0,this.bindGroup.destroy(),this.bindGroup=null}updateBindGroup(){let{bindGroup:t}=this;t.updateUniformBuffers(),t.update()}dispatch(t,e,s){let i=this.compute.device;i.setBindGroup(0,this.bindGroup);let r=i.passEncoder;r.setPipeline(this.pipeline);let{indirectSlotIndex:a,indirectBuffer:o,indirectFrameStamp:l}=this.compute;if(a>=0){let h;o?h=o.impl.buffer:h=i.indirectDispatchBuffer.impl.buffer;let f=a*cW;r.dispatchWorkgroupsIndirect(h,f)}else r.dispatchWorkgroups(t,e,s)}};var Lv=class{constructor(t){n(this,"device");n(this,"gpuIndirect",null);n(this,"gpuIndirectSigned",null);n(this,"storage",null);this.device=t}allocate(t){this.gpuIndirect&&this.gpuIndirect.length===5*t||(this.storage?.destroy(),this.gpuIndirect=new Uint32Array(5*t),this.gpuIndirectSigned=new Int32Array(this.gpuIndirect.buffer),this.storage=new Ee(this.device,this.gpuIndirect.byteLength,264))}add(t,e,s,i,r=0,a=0){let o=t*5;this.gpuIndirect[o+0]=e,this.gpuIndirect[o+1]=s,this.gpuIndirect[o+2]=i,this.gpuIndirectSigned[o+3]=r,this.gpuIndirect[o+4]=a}update(t){if(this.storage&&t>0){let s=t*5;this.storage.write(0,this.gpuIndirect,0,s)}return 0}destroy(){this.storage?.destroy(),this.storage=null}};var Mv=class{constructor(t){n(this,"availableStagingBuffers",[]);n(this,"pendingStagingBuffers",[]);n(this,"_destroyed",!1);n(this,"_lastUploadSubmitVersion",-1);this.uploadStream=t,this.useSingleBuffer=t.useSingleBuffer}_onDeviceLost(){}destroy(){this._destroyed=!0,this.availableStagingBuffers.forEach(t=>t.destroy()),this.pendingStagingBuffers.forEach(t=>t.destroy())}update(t){let e=this.pendingStagingBuffers;for(let i=0;i{this._destroyed?r.destroy():this.availableStagingBuffers.push(r)})}e.length=0;let s=this.availableStagingBuffers;for(let i=s.length-1;i>=0;i--)s[i].size0,this.update(o);let l=this.availableStagingBuffers.pop()??this.uploadStream.device.wgpu.createBuffer({size:o,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC,mappedAtCreation:!0}),h=l.getMappedRange();new Uint8Array(h).set(new Uint8Array(t.buffer,t.byteOffset,o)),l.unmap(),r.getCommandEncoder().copyBufferToBuffer(l,0,e.impl.buffer,a,o),this.pendingStagingBuffers.push(l),this._lastUploadSubmitVersion=r.submitVersion}};var Ov=class{constructor(t){n(this,"_binding",null);n(this,"_layer",null);n(this,"_cachedFramebufferSize",new B);this.xrBridge=t}destroy(t){this._binding=null,this._layer=null,this._cachedFramebufferSize.set(0,0),t._clearXrState()}beginFrame(t,e){let s=this.xrBridge.device;if(s._clearXrState(),!this._binding||!this._layer||!e)return;let i=t.getViewerPose(e);if(!i||!i.views?.length)return;let r=s.xrSubImages;for(let o=0;o0&&r>0){e.set(i,r);return}}if(this._cachedFramebufferSize.x>0&&this._cachedFramebufferSize.y>0){e.copy(this._cachedFramebufferSize);return}e.set(0,0)}getViewport(t,e){if(this._binding&&this._layer)try{let s=this._binding.getViewSubImage(this._layer,e);if(s?.viewport)return s.viewport}catch{}return{x:0,y:0,width:0,height:0}}attachPresentation(t,e){let s=globalThis.XRGPUBinding;if(typeof s>"u"){this.xrBridge._onBindingError?.(new Error("XRGPUBinding is not available in this browser."));return}let r=this.xrBridge.device.wgpu;try{this._binding=new s(t,r)}catch(l){this.xrBridge._onBindingError?.(l);return}let o={colorFormat:this._binding.getPreferredColorFormat(),scaleFactor:e.framebufferScaleFactor};try{this._layer=this._binding.createProjectionLayer({...o,textureType:"texture-array"})}catch{this._layer=this._binding.createProjectionLayer({...o,textureType:"texture"})}t.updateRenderState({layers:[this._layer],depthNear:e.depthNear,depthFar:e.depthFar})}syncCameraColorTexture(t,e){if(!this._binding?.getCameraImage)return;let s=this._binding.getCameraImage(t);if(!s)return;let i=e.impl?.gpuTexture;if(!i)return;let a=this.xrBridge.device.getCommandEncoder(),o=t.width,l=t.height;a.copyTextureToTexture({texture:s},{texture:i},[o,l,1])}syncCameraDepthTexture(t,e,s){t?.texture}releasePresentation(){this._binding=null}onGraphicsDeviceLost(){let t=this.xrBridge,e=t._session;if(!e)return;let s=e.renderState,i=t.device;this._binding=null,this._layer=null,this._cachedFramebufferSize.set(0,0),i._clearXrState(),e.updateRenderState({layers:[],depthNear:s.depthNear,depthFar:s.depthFar})}onGraphicsDeviceRestored(){let t=this.xrBridge;if(!t._session)return;let e=t.eventHandler;setTimeout(()=>{if(t._session)try{let s=t._session.renderState;t.attachPresentation(t._session,{framebufferScaleFactor:t._framebufferScaleFactor,depthNear:s.depthNear,depthFar:s.depthFar,onBindingError:t._onBindingError})}catch(s){e.fire("error",s)}},0)}};var VP=new Map,eL=20,hW=12,Kd=class extends tt{constructor(e,s={}){super(e,s);n(this,"_deferredDestroys",[]);n(this,"renderPipeline",new iv(this));n(this,"computePipeline",new rv(this));n(this,"_indirectDrawBuffer",null);n(this,"_indirectDrawBufferCount",0);n(this,"_indirectDrawNextIndex",0);n(this,"_indirectDispatchBuffer",null);n(this,"_indirectDispatchBufferCount",0);n(this,"_indirectDispatchNextIndex",0);n(this,"clearRenderer");n(this,"mipmapRenderer");n(this,"pipeline",null);n(this,"bindGroupFormats",[]);n(this,"emptyBindGroup");n(this,"submitVersion",0);n(this,"xrColorTexture",null);n(this,"xrColorTextureViewFormat",null);n(this,"xrColorTextureViewDescriptor",null);n(this,"xrSubImages",[]);n(this,"xrCurrentViewIndex",-1);n(this,"externalBackbuffer",null);n(this,"commandEncoder",null);n(this,"commandBuffers",[]);n(this,"limits");n(this,"glslang",null);n(this,"twgsl",null);s=this.initOptions,s.alpha=s.alpha??!0,this.backBufferAntialias=s.antialias??!1,this.isWebGPU=!0,this._deviceType=Ig,this.featureLevel=s.featureLevel,this.scope.resolve(yf).setValue(0)}destroy(){this.clearRenderer.destroy(),this.clearRenderer=null,this.mipmapRenderer.destroy(),this.mipmapRenderer=null,this.resolver.destroy(),this.resolver=null,this._clearXrState(),this.externalBackbuffer=null,super.destroy()}_clearXrState(){this.xrColorTexture=null,this.xrColorTextureViewFormat=null,this.xrColorTextureViewDescriptor=null,this.xrSubImages.length=0,this.xrCurrentViewIndex=-1}initDeviceCaps(){let e=this.wgpu?.limits;this.limits=e,this.precision="highp",this.maxPrecision="highp",this.maxSamples=4,this.maxTextures=16,this.maxTextureSize=e.maxTextureDimension2D,this.maxCubeMapSize=e.maxTextureDimension2D,this.maxVolumeSize=e.maxTextureDimension3D,this.maxColorAttachments=e.maxColorAttachments,this.maxPixelRatio=1,this.maxAnisotropy=16,this.fragmentUniformsCount=e.maxUniformBufferBindingSize/16,this.vertexUniformsCount=e.maxUniformBufferBindingSize/16,this.supportsUniformBuffers=!0,this.supportsAreaLights=!0,this.supportsGpuParticles=!0,this.supportsCompute=!0,this.textureFloatRenderable=!0,this.textureHalfFloatRenderable=!0,this.supportsImageBitmap=!0,this.samples=this.backBufferAntialias?4:1;let s=window.navigator.gpu.wgslLanguageFeatures;this.supportsStorageTextureRead=s?.has("readonly_and_readwrite_storage_textures"),this.supportsSubgroupUniformity=s?.has("subgroup_uniformity"),this.supportsSubgroupId=s?.has("subgroup_id"),this.supportsLinearIndexing=s?.has("linear_indexing"),this.supportsUnrestrictedPointerParameters=s?.has("unrestricted_pointer_parameters"),this.supportsPointerCompositeAccess=s?.has("pointer_composite_access"),this.supportsPacked4x8IntegerDotProduct=s?.has("packed_4x8_integer_dot_product"),this.supportsTextureAndSamplerLet=s?.has("texture_and_sampler_let"),this.initCapsDefines()}async initWebGpu(e,s){if(!window.navigator.gpu)throw Yx("WebGPU"),new Error("Unable to retrieve GPU. Ensure you are using a browser that supports WebGPU rendering.");if(e&&s){let i=window.document?.baseURI??window.location.href,r=f=>new URL(f,i).toString(),a=r(s),o=r(s.replace(".js",".wasm")),l=r(e),h=await Promise.all([new Function("modulePath","return import(modulePath)")(`${a}`).then(()=>twgsl(o)),new Function("modulePath","return import(modulePath)")(`${l}`).then(f=>f.default())]);this.twgsl=h[0],this.glslang=h[1]}return this.createDevice()}async createDevice(){let e={powerPreference:this.initOptions.powerPreference!=="default"?this.initOptions.powerPreference:void 0,xrCompatible:!!this.initOptions.xrCompatible};this.gpuAdapter=await window.navigator.gpu.requestAdapter(e);let i=this.initOptions.featureLevel==="bare",r=[],a=i?()=>!1:p=>{let m=this.gpuAdapter.features.has(p);return m&&r.push(p),m};this.textureFloatFilterable=a("float32-filterable"),this.textureFloatBlendable=a("float32-blendable"),this.extCompressedTextureS3TC=a("texture-compression-bc"),this.extCompressedTextureS3TCSliced3D=a("texture-compression-bc-sliced-3d"),this.extCompressedTextureETC=a("texture-compression-etc2"),this.extCompressedTextureASTC=a("texture-compression-astc"),this.extCompressedTextureASTCSliced3D=a("texture-compression-astc-sliced-3d"),this.supportsTimestampQuery=a("timestamp-query"),this.supportsDepthClip=a("depth-clip-control"),this.supportsDepth32Stencil=a("depth32float-stencil8"),this.supportsIndirectFirstInstance=a("indirect-first-instance"),this.supportsShaderF16=a("shader-f16"),this.supportsStorageRGBA8=a("bgra8unorm-storage"),this.textureRG11B10Renderable=a("rg11b10ufloat-renderable"),this.supportsClipDistances=a("clip-distances"),this.supportsTextureFormatTier1=a("texture-format-tier1"),this.supportsTextureFormatTier2=a("texture-format-tier2"),this.supportsTextureFormatTier1||(this.supportsTextureFormatTier1=this.supportsTextureFormatTier2),this.supportsPrimitiveIndex=a("primitive-index"),this.supportsSubgroups=a("subgroups"),this.maxSubgroupSize=this.supportsSubgroups?this.gpuAdapter?.info?.subgroupMaxSize??0:0,this.minSubgroupSize=this.supportsSubgroups?this.gpuAdapter?.info?.subgroupMinSize??0:0;let o=window.navigator.gpu.wgslLanguageFeatures?Array.from(window.navigator.gpu.wgslLanguageFeatures):[],l={};if(!i){let p=this.gpuAdapter?.limits;if(p)for(let m in p)m==="minSubgroupSize"||m==="maxSubgroupSize"||(l[m]=p[m])}let h={requiredFeatures:r,requiredLimits:l,defaultQueue:{label:"Default Queue"}};this.wgpu=await this.gpuAdapter.requestDevice(h),this.supportsHtmlTextures=typeof this.wgpu.queue?.copyElementImageToTexture=="function",this.wgpu.lost?.then(this.handleDeviceLost.bind(this)),this.wgpu.addEventListener?.("uncapturederror",p=>{let m=p.error}),this.initDeviceCaps(),this.gpuContext=this.canvas.getContext("webgpu");let f="standard",u=window.navigator.gpu.getPreferredCanvasFormat(),d=this.initOptions.displayFormat;return this.backBufferFormat=u==="rgba8unorm"?d===Md?st:ce:d===Md?ic:tc,this.backBufferViewFormat=d===Md?`${u}-srgb`:u,d===mP&&this.textureFloatFilterable&&window.matchMedia("(dynamic-range: high)")?.matches&&(this.backBufferFormat=Me,this.backBufferViewFormat="rgba16float",u="rgba16float",this.isHdr=!0,f="extended"),this.canvasConfig={device:this.wgpu,colorSpace:"srgb",alphaMode:this.initOptions.alpha?"premultiplied":"opaque",format:u,toneMapping:{mode:f},usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST,viewFormats:d===Md?[this.backBufferViewFormat]:[]},this.gpuContext?.configure(this.canvasConfig),this.createBackbuffer(),this.clearRenderer=new Ev(this),this.mipmapRenderer=new Av(this),this.resolver=new bv(this),this.postInit(),this}async handleDeviceLost(e){e.reason!=="destroyed"&&(super.loseContext(),this.fire("devicelost"),await this.createDevice(),super.restoreContext(),this.fire("devicerestored"))}postInit(){super.postInit(),this.initializeRenderState(),this.setupPassEncoderDefaults(),this.gpuProfiler=new Rv(this),this.dynamicBuffers=new wv(this,100*1024,this.limits.minUniformBufferOffsetAlignment),this.emptyBindGroup=new ji(this,new Ue(this,[])),this.emptyBindGroup.update()}createBackbuffer(){this.supportsStencil=this.initOptions.stencil,this.backBuffer=new me({name:"WebgpuFramebuffer",graphicsDevice:this,depth:this.initOptions.depth,stencil:this.supportsStencil,samples:this.samples}),this.backBuffer.impl.isBackbuffer=!0}frameStart(){super.frameStart(),this.gpuProfiler.frameStart(),this.submit();let e=this.xrColorTexture??this.gpuContext?.getCurrentTexture?.()??this.externalBackbuffer?.impl.gpuTexture;(this.backBufferSize.x!==e.width||this.backBufferSize.y!==e.height)&&(this.backBufferSize.set(e.width,e.height),this.backBuffer.destroy(),this.backBuffer=null,this.createBackbuffer());let s=this.backBuffer,i=s.impl,r=e===this.xrColorTexture&&this.xrColorTextureViewFormat?this.xrColorTextureViewFormat:this.backBufferViewFormat;i.setColorAttachment(0,void 0,r),s._width=e.width,s._height=e.height,this.initRenderTarget(s),i.assignColorTexture(e,r)}frameEnd(){super.frameEnd(),this.gpuProfiler.frameEnd(),this.submit(),this.contextLost||this.gpuProfiler.request(),this._indirectDrawNextIndex=0,this._indirectDispatchNextIndex=0}createBufferImpl(e){return new Lo(e)}createUniformBufferImpl(e){return new dv(e)}createVertexBufferImpl(e,s,i){return new pv(e,s,i)}createIndexBufferImpl(e,s){return new Jx(e,s)}createShaderImpl(e){return new fv(e)}createDrawCommandImpl(e){return new Lv(this)}createTextureImpl(e){return this.textures.add(e),new uv(e)}createXrBridgeImpl(e){return new Ov(e)}createRenderTargetImpl(e){return new nv(e)}createUploadStreamImpl(e){return new Mv(e)}createBindGroupFormatImpl(e){return new Qx(e)}createBindGroupImpl(e){return new Zx}createComputeImpl(e){return new Dv(e)}get indirectDrawBuffer(){return this.allocateIndirectDrawBuffer(),this._indirectDrawBuffer}allocateIndirectDrawBuffer(){this._indirectDrawNextIndex===0&&this._indirectDrawBufferCount{let{elements:a}=r.format;for(let o=0;o{(e._needsUpload||e._needsMipmapsUpload)&&e.upload()}),this.texturesToUpload.clear()}setupTimeStampWrites(e,s){if(this.gpuProfiler._enabled&&this.gpuProfiler.timestampQueriesSet){let i=this.gpuProfiler.getSlot(s);i===-1||(e=e??{},e.timestampWrites={querySet:this.gpuProfiler.timestampQueriesSet.querySet,beginningOfPassWriteIndex:i*2,endOfPassWriteIndex:i*2+1})}return e}startRenderPass(e){this._uploadDirtyTextures();let s=e.renderTarget||this.backBuffer;this.renderTarget=s;let i=s.impl;s!==this.backBuffer&&this.initRenderTarget(s),i.setupForRenderPass(e,s);let r=i.renderPassDescriptor;this.setupTimeStampWrites(r,e.name);let a=this.getCommandEncoder();this.passEncoder=a.beginRenderPass(r),this.passEncoder.label=`${e.name}-PassEncoder RT:${s.name}`,this.setupPassEncoderDefaults();let{width:o,height:l}=s;this.setViewport(0,0,o,l),this.setScissor(0,0,o,l),this.insideRenderPass=!0}endRenderPass(e){this.passEncoder.end(),this.passEncoder=null,this.insideRenderPass=!1,this.bindGroupFormats.length=0;let s=this.renderTarget;if(s&&s.depthBuffer&&e.depthStencilOps.resolveDepth&&e.samples>1&&s.autoResolve){let i=s.impl.depthAttachment,r=s.depthBuffer.impl.gpuTexture;i&&r&&this.resolver.resolveDepth(this.commandEncoder,i.multisampledDepthBuffer,r)}for(let i=0;i0&&(this.dynamicBuffers.submit(),this.wgpu.queue.submit(this.commandBuffers),this.commandBuffers.length=0,this.submitVersion++,this.dynamicBuffers.onCommandBuffersSubmitted());let e=this._deferredDestroys;if(e.length>0){for(let s=0;s{let h=()=>{a?.mapAsync(GPUMapMode.READ).then(()=>{i??(i=new Uint8Array(s));let f=a.getMappedRange(0,s),u=i.constructor;i.set(new u(f)),a.unmap(),e.destroy(this),o(i)})};r?(this.submit(),h()):setTimeout(()=>{h()})})}writeStorageBuffer(e,s=0,i,r=0,a){this.wgpu.queue.writeBuffer(e.buffer,s,i,r,a)}copyRenderTarget(e,s,i,r){let a={width:e?e.width:s.width,height:e?e.height:s.height,depthOrArrayLayers:1},o=this.getCommandEncoder();if(i){let l={texture:e?e.colorBuffer.impl.gpuTexture:this.backBuffer.impl.assignedColorTexture,mipLevel:e?e.mipLevel:0},h={texture:s?s.colorBuffer.impl.gpuTexture:this.backBuffer.impl.assignedColorTexture,mipLevel:s?s.mipLevel:0};o.copyTextureToTexture(l,h,a)}if(r){let l=e||this.renderTarget,h=l.impl.depthAttachment.depthTexture,f=l.mipLevel;if(e.samples>1){let u=s.colorBuffer.impl.gpuTexture;this.resolver.resolveDepth(o,h,u)}else{let u=s?s.depthBuffer.impl.gpuTexture:this.renderTarget.impl.depthAttachment.depthTexture,d=s?s.mipLevel:this.renderTarget.mipLevel,p={texture:h,mipLevel:f},m={texture:u,mipLevel:d};o.copyTextureToTexture(p,m,a)}}return!0}get hasTranspilers(){return this.glslang&&this.twgsl}};var jd=class{constructor(){n(this,"bufferId",null)}destroy(t){this.bufferId&&(t.gl.deleteBuffer(this.bufferId),this.bufferId=null)}get initialized(){return!!this.bufferId}loseContext(){this.bufferId=null}unlock(t,e,s,i){let r=t.gl;if(this.bufferId)r.bindBuffer(s,this.bufferId),r.bufferSubData(s,0,i);else{let a;switch(e){case 0:a=r.STATIC_DRAW;break;case 1:a=r.DYNAMIC_DRAW;break;case 2:a=r.STREAM_DRAW;break;case 3:a=r.DYNAMIC_COPY;break}this.bufferId=r.createBuffer(),r.bindBuffer(s,this.bufferId),r.bufferData(s,i,a)}}};var Fv=class extends jd{constructor(){super(...arguments);n(this,"vao",null)}destroy(e){super.destroy(e),e.unbindVertexArray()}loseContext(){super.loseContext(),this.vao=null}unlock(e){let s=e.device;super.unlock(s,e.usage,s.gl.ARRAY_BUFFER,e.storage)}};var Nv=class extends jd{constructor(t){super();let e=t.device.gl,s=t.format;s===0?this.glFormat=e.UNSIGNED_BYTE:s===1?this.glFormat=e.UNSIGNED_SHORT:s===2&&(this.glFormat=e.UNSIGNED_INT)}unlock(t){let e=t.device;super.unlock(e,t.usage,e.gl.ELEMENT_ARRAY_BUFFER,t.storage)}};var Bv=class{constructor(t,e,s,i){if(this.locationId=i,this.scopeId=t.scope.resolve(e),this.version=new Nd,e.substring(e.length-3)==="[0]")switch(s){case Te:s=On;break;case bi:s=Fa;break;case pe:s=Bn;break;case wo:s=Un;break;case pr:s=Fn;break;case jr:s=Na;break;case Ma:s=kn;break;case Dn:s=zn;break;case Kt:s=Nn;break;case Di:s=Ba;break;case Oa:s=Gn;break;case Ln:s=Vn;break;case oi:s=gf;break;case qr:s=cc;break;case Li:s=Sf;break;case Mn:s=xf;break}this.dataType=s,this.value=[null,null,null,null],this.array=[]}};var tL=new Set(["gl_VertexID","gl_InstanceID","gl_DrawID","gl_BaseVertex","gl_BaseInstance"]),HP=class{constructor(){n(this,"map",new Map)}destroy(t){this.map.forEach(e=>{t.gl.deleteShader(e)})}loseContext(t){this.map.clear()}},fW=new et,uW=new et,Uv=class{constructor(t){n(this,"compileDuration",0);this.init(),this.compile(t.device,t),this.link(t.device,t),t.device.shaders.push(t)}destroy(t){this.glProgram&&(t.device.gl.deleteProgram(this.glProgram),this.glProgram=null)}init(){this.uniforms=[],this.samplers=[],this.attributes=[],this.glProgram=null,this.glVertexShader=null,this.glFragmentShader=null}loseContext(){this.init()}restoreContext(t,e){this.compile(t,e),this.link(t,e)}compile(t,e){let s=e.definition;this.glVertexShader=this._compileShaderSource(t,s.vshader,!0),this.glFragmentShader=this._compileShaderSource(t,s.fshader,!1)}link(t,e){if(this.glProgram)return;let s=t.gl;if(s.isContextLost())return;let i=0,r=s.createProgram();this.glProgram=r,s.attachShader(r,this.glVertexShader),s.attachShader(r,this.glFragmentShader);let a=e.definition,o=a.attributes;if(a.useTransformFeedback){let h=a.feedbackVaryings;if(!h){h=[];for(let f in o)o.hasOwnProperty(f)&&h.push(`out_${f}`)}s.transformFeedbackVaryings(r,h,s.INTERLEAVED_ATTRIBS)}let l={};for(let h in o)if(o.hasOwnProperty(h)){let f=o[h],u=ze[f];l[u]=h,s.bindAttribLocation(r,u,h)}s.linkProgram(r)}_compileShaderSource(t,e,s){let i=t.gl;if(i.isContextLost())return null;let a=(s?fW:uW).get(t,()=>new HP),o=a.map.get(e);return o||(o=i.createShader(s?i.VERTEX_SHADER:i.FRAGMENT_SHADER),i.shaderSource(o,e),i.compileShader(o),a.map.set(e,o)),o}finalize(t,e){let s=t.gl;if(s.isContextLost())return!0;let i=this.glProgram,r=e.definition,a=0;if(!s.getProgramParameter(i,s.LINK_STATUS)){if(!this._isCompiled(t,e,this.glVertexShader,r.vshader,"vertex")||!this._isCompiled(t,e,this.glFragmentShader,r.fshader,"fragment"))return!1;let u=`Failed to link shader program. Error: ${s.getProgramInfoLog(i)}`;return!1}let l=s.getProgramParameter(i,s.ACTIVE_ATTRIBUTES);e.attributes.clear();for(let u=0;u ":" ";i+=`${h}${l+1}: ${r[l]} `}s.source=t}return[i,s]}};var kv=class{constructor(t){n(this,"indexSizeBytes");n(this,"glCounts",null);n(this,"glOffsetsBytes",null);n(this,"glInstanceCounts",null);this.indexSizeBytes=t}allocate(t){this.glCounts&&this.glCounts.length===t||(this.glCounts=new Int32Array(t),this.glOffsetsBytes=new Int32Array(t),this.glInstanceCounts=new Int32Array(t))}add(t,e,s,i){this.glCounts[t]=e,this.glOffsetsBytes[t]=i*this.indexSizeBytes,this.glInstanceCounts[t]=s}update(t){return 0}};function sL(c,t){let e=c.width,s=c.height;if(e>t||s>t){let i=t/Math.max(e,s),r=Math.floor(e*i),a=Math.floor(s*i),o=document.createElement("canvas");return o.width=r,o.height=a,o.getContext("2d").drawImage(c,0,0,e,s,0,0,r,a),o}return c}var zv=class{constructor(t){n(this,"_glTexture",null);n(this,"_glTarget");n(this,"_glFormat");n(this,"_glInternalFormat");n(this,"_glPixelType");n(this,"_glCreated");n(this,"dirtyParameterFlags",0);this.texture=t}destroy(t){if(this._glTexture){for(let e=0;et.maxCubeMapSize||h.height>t.maxCubeMapSize)&&(h=sL(h,t.maxCubeMapSize),i===0&&(e._width=h.width,e._height=h.height)),t.setUnpackFlipY(!1),t.setUnpackPremultiplyAlpha(e._premultiplyAlpha),this._glCreated?s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+l,i,0,0,this._glFormat,this._glPixelType,h):s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+l,i,this._glInternalFormat,this._glFormat,this._glPixelType,h)}else for(a=1/Math.pow(2,i),l=0;l<6;l++){if(!e._levelsUpdated[0][l])continue;let h=r[l];e._compressed?this._glCreated&&h?s.compressedTexSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+l,i,0,0,Math.max(e._width*a,1),Math.max(e._height*a,1),this._glInternalFormat,h):s.compressedTexImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+l,i,this._glInternalFormat,Math.max(e._width*a,1),Math.max(e._height*a,1),0,h):(t.setUnpackFlipY(!1),t.setUnpackPremultiplyAlpha(e._premultiplyAlpha),t.setUnpackAlignment(1),this._glCreated&&h?s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+l,i,0,0,Math.max(e._width*a,1),Math.max(e._height*a,1),this._glFormat,this._glPixelType,h):s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+l,i,this._glInternalFormat,Math.max(e._width*a,1),Math.max(e._height*a,1),0,this._glFormat,this._glPixelType,h))}}else if(e._volume)e._compressed?s.compressedTexImage3D(s.TEXTURE_3D,i,this._glInternalFormat,Math.max(e._width*a,1),Math.max(e._height*a,1),Math.max(e._depth*a,1),0,r):(t.setUnpackFlipY(!1),t.setUnpackPremultiplyAlpha(e._premultiplyAlpha),t.setUnpackAlignment(1),s.texImage3D(s.TEXTURE_3D,i,this._glInternalFormat,Math.max(e._width*a,1),Math.max(e._height*a,1),Math.max(e._depth*a,1),0,this._glFormat,this._glPixelType,r));else if(e.array){if(Array.isArray(r)&&e._arrayLength===r.length)if(e._compressed)for(let l=0;lt.maxTextureSize||r.height>t.maxTextureSize)&&(r=sL(r,t.maxTextureSize),i===0&&(e._width=r.width,e._height=r.height));let l=r.width||r.videoWidth,h=r.height||r.videoHeight;t.setUnpackFlipY(e._flipY),t.setUnpackPremultiplyAlpha(e._premultiplyAlpha),this._glCreated&&e._width===l&&e._height===h&&!t._isImageVideoInterface(r)?s.texSubImage2D(s.TEXTURE_2D,i,0,0,this._glFormat,this._glPixelType,r):(s.texImage2D(s.TEXTURE_2D,i,this._glInternalFormat,this._glFormat,this._glPixelType,r),i===0&&(e._width=l,e._height=h))}else a=1/Math.pow(2,i),e._compressed?this._glCreated&&r?s.compressedTexSubImage2D(s.TEXTURE_2D,i,0,0,Math.max(Math.floor(e._width*a),1),Math.max(Math.floor(e._height*a),1),this._glInternalFormat,r):s.compressedTexImage2D(s.TEXTURE_2D,i,this._glInternalFormat,Math.max(Math.floor(e._width*a),1),Math.max(Math.floor(e._height*a),1),0,r):(t.setUnpackFlipY(!1),t.setUnpackPremultiplyAlpha(e._premultiplyAlpha),t.setUnpackAlignment(1),this._glCreated&&r?s.texSubImage2D(s.TEXTURE_2D,i,0,0,Math.max(e._width*a,1),Math.max(e._height*a,1),this._glFormat,this._glPixelType,r):s.texImage2D(s.TEXTURE_2D,i,this._glInternalFormat,Math.max(e._width*a,1),Math.max(e._height*a,1),0,this._glFormat,this._glPixelType,r));i===0?e._mipmapsUploaded=!1:e._mipmapsUploaded=!0}i++}if(e._needsUpload)if(e._cubemap)for(let l=0;l<6;l++)e._levelsUpdated[0][l]=!1;else e._levelsUpdated[0]=!1;!e._compressed&&!e._integerFormat&&e._mipmaps&&e._needsMipmapsUpload&&e._levels.length===1&&(s.generateMipmap(this._glTarget),e._mipmapsUploaded=!0),e._gpuSize&&e.adjustVramSizeTracking(t._vram,-e._gpuSize),e._gpuSize=e.gpuSize,e.adjustVramSizeTracking(t._vram,e._gpuSize),e.releaseSourceAfterUpload&&e.releaseImageSources(),this._glCreated=!0}uploadImmediate(t,e){(e._needsUpload||e._needsMipmapsUpload)&&(t.setTexture(e,0),e._needsUpload=!1,e._needsMipmapsUpload=!1)}read(t,e,s,i,r){let a=this.texture;return a.device.readTextureAsync(a,t,e,s,i,r)}write(t,e,s,i,r){let{texture:a}=this,{device:o}=a;return o.setTexture(a,0),o.writeTextureAsync(a,t,e,s,i,r)}};var dW=new et,WP=class{constructor(t,e){n(this,"msaaFB");n(this,"resolveFB");this.msaaFB=t,this.resolveFB=e}destroy(t){this.msaaFB&&(t.deleteRenderbuffer(this.msaaFB),this.msaaFB=null),this.resolveFB&&(t.deleteRenderbuffer(this.resolveFB),this.resolveFB=null)}},Gv=class{constructor(){n(this,"_glFrameBuffer",null);n(this,"_glDepthBuffer",null);n(this,"_glResolveFrameBuffer",null);n(this,"colorMrtFramebuffers",null);n(this,"_glMsaaColorBuffers",[]);n(this,"_glMsaaDepthBuffer",null);n(this,"msaaDepthBufferKey");n(this,"suppliedColorFramebuffer");n(this,"_isInitialized",!1)}destroy(t){let e=t.gl;this._isInitialized=!1,this._glFrameBuffer&&(this._glFrameBuffer!==this.suppliedColorFramebuffer&&e.deleteFramebuffer(this._glFrameBuffer),this._glFrameBuffer=null),this._glDepthBuffer&&(e.deleteRenderbuffer(this._glDepthBuffer),this._glDepthBuffer=null),this._glResolveFrameBuffer&&(this._glResolveFrameBuffer!==this.suppliedColorFramebuffer&&e.deleteFramebuffer(this._glResolveFrameBuffer),this._glResolveFrameBuffer=null),this._glMsaaColorBuffers.forEach(s=>{e.deleteRenderbuffer(s)}),this._glMsaaColorBuffers.length=0,this.colorMrtFramebuffers?.forEach(s=>{s.destroy(e)}),this.colorMrtFramebuffers=null,this._glMsaaDepthBuffer&&(this._glMsaaDepthBuffer=null,this.msaaDepthBufferKey&&Af(t).release(this.msaaDepthBufferKey)),this.suppliedColorFramebuffer=void 0}get initialized(){return this._isInitialized}init(t,e){let s=t.gl;this._isInitialized=!0;let i=[];if(this.suppliedColorFramebuffer!==void 0)this._glFrameBuffer=this.suppliedColorFramebuffer;else{this._glFrameBuffer=s.createFramebuffer(),t.setFramebuffer(this._glFrameBuffer);let r=e._colorBuffers?.length??0,a=s.COLOR_ATTACHMENT0;for(let l=0;l1)){this._glDepthBuffer||(this._glDepthBuffer=s.createRenderbuffer());let f=e._stencil?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT32F;s.bindRenderbuffer(s.RENDERBUFFER,this._glDepthBuffer),s.renderbufferStorage(s.RENDERBUFFER,f,e.width,e.height),s.framebufferRenderbuffer(s.FRAMEBUFFER,l,s.RENDERBUFFER,this._glDepthBuffer),s.bindRenderbuffer(s.RENDERBUFFER,null)}}}if(e._samples>1){this._glResolveFrameBuffer=this._glFrameBuffer,this._glFrameBuffer=s.createFramebuffer(),t.setFramebuffer(this._glFrameBuffer);let r=e._colorBuffers?.length??0;if(this.suppliedColorFramebuffer!==void 0){let a=s.createRenderbuffer();this._glMsaaColorBuffers.push(a);let o=t.backBufferFormat===ce?s.RGBA8:s.RGB8;s.bindRenderbuffer(s.RENDERBUFFER,a),s.renderbufferStorageMultisample(s.RENDERBUFFER,e._samples,o,e.width,e.height),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.RENDERBUFFER,a)}else for(let a=0;a1&&(this._createMsaaMrtFramebuffers(t,e,r),t.setFramebuffer(this._glFrameBuffer),s.drawBuffers(i))}}_createMsaaMrtFramebuffers(t,e,s){let i=t.gl;this.colorMrtFramebuffers=[];for(let r=0;ru?.format??-1).join(",")??"",r=e._depth?e._depthBuffer?`dt${e._depthBuffer.format}`:e._stencil?"ds":"d":"",a=`${s}:${i}:${r}:${e._samples}`,o=dW.get(t,()=>{let u=new Set;return u.loseContext=()=>u.clear(),u});if(o.has(a))return;let l=t.gl,h=l.checkFramebufferStatus(l.FRAMEBUFFER),f;switch(h){case l.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:f="FRAMEBUFFER_INCOMPLETE_ATTACHMENT";break;case l.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:f="FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";break;case l.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:f="FRAMEBUFFER_INCOMPLETE_DIMENSIONS";break;case l.FRAMEBUFFER_UNSUPPORTED:f="FRAMEBUFFER_UNSUPPORTED";break}h===l.FRAMEBUFFER_COMPLETE&&o.add(a)}loseContext(){this._glFrameBuffer=null,this._glDepthBuffer=null,this._glResolveFrameBuffer=null,this._glMsaaColorBuffers.length=0,this._glMsaaDepthBuffer=null,this.msaaDepthBufferKey=void 0,this.colorMrtFramebuffers=null,this.suppliedColorFramebuffer=void 0,this._isInitialized=!1}internalResolve(t,e,s,i,r){t.setScissor(0,0,i.width,i.height);let a=t.gl;a.bindFramebuffer(a.READ_FRAMEBUFFER,e),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,s),a.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,r,a.NEAREST)}resolve(t,e,s,i){let r=t.gl;if(this.colorMrtFramebuffers){if(s)for(let a=0;at.deleteBuffer(e.pbo)),this.pendingPBOs.forEach(e=>{e.sync&&t.deleteSync(e.sync),t.deleteBuffer(e.pbo)})}_onDeviceLost(){this.availablePBOs.length=0,this.pendingPBOs.length=0}update(t){let e=this.uploadStream.device.gl,s=this.pendingPBOs;for(let r=s.length-1;r>=0;r--){let a=s[r],o=e.clientWaitSync(a.sync,0,0);(o===e.CONDITION_SATISFIED||o===e.ALREADY_SIGNALED)&&(e.deleteSync(a.sync),this.availablePBOs.push({pbo:a.pbo,size:a.size}),s.splice(r,1))}let i=this.availablePBOs;for(let r=i.length-1;r>=0;r--)i[r].size{t._session&&e.gl.makeXRCompatible().then(()=>{if(!t._session)return;let i=t._session.renderState;t.attachPresentation(t._session,{framebufferScaleFactor:t._framebufferScaleFactor,depthNear:i.depthNear,depthFar:i.depthFar,onBindingError:t._onBindingError})}).catch(i=>{s.fire("error",i)})},0)}};var pW={type:Yt,base:0,count:6,indexed:!0},mW=` attribute vec2 vertex_position; varying vec2 pcTexCoord; void main() { gl_Position = vec4(vertex_position, 0.0, 1.0); pcTexCoord = vertex_position * 0.5 + 0.5; } `,_W=` uniform sampler2D pcSource; varying vec2 pcTexCoord; void main() { gl_FragColor = texture2D(pcSource, pcTexCoord); } `,Wv=class{constructor(t){n(this,"_device");n(this,"_shader",null);n(this,"_scratchTex",null);n(this,"_scratchRt",null);n(this,"_sourceId",null);this._device=t}_getShader(){if(!this._shader){let t=this._device;this._shader=new Be(t,ns.createDefinition(t,{name:"XrMsaaCopy",attributes:{vertex_position:ee},vertexCode:mW,fragmentCode:_W})),this._sourceId=t.scope.resolve("pcSource")}return this._shader}_ensureScratch(t,e){let s=this._device;this._scratchTex&&(this._scratchTex.width!==t||this._scratchTex.height!==e)&&(this._scratchRt.destroy(),this._scratchRt=null,this._scratchTex.destroy(),this._scratchTex=null),this._scratchTex||(this._scratchTex=Z.createDataTexture2D(s,"XrMsaaScratch",t,e,s.backBufferFormat),this._scratchRt=new me({colorBuffer:this._scratchTex,depth:!1,stencil:!1})),this._scratchRt.impl.initialized||this._scratchRt.impl.init(s,this._scratchRt)}copy(t,e,s,i){this._ensureScratch(s,i);let r=this._device,a=r.gl;a.bindFramebuffer(a.READ_FRAMEBUFFER,t),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,this._scratchRt.impl._glFrameBuffer),a.blitFramebuffer(0,0,s,i,0,0,s,i,a.COLOR_BUFFER_BIT,a.NEAREST),r.setDrawStates(Oe.NOBLEND,Pt.NODEPTH),r.setFramebuffer(e),r.setShader(this._getShader()),r.clearVertexBuffer(),r.setVertexBuffer(r.quadVertexBuffer),this._sourceId.setValue(this._scratchTex);let{vx:o,vy:l,vw:h,vh:f,sx:u,sy:d,sw:p,sh:m}=r;r.setViewport(0,0,s,i),r.setScissor(0,0,s,i),r.draw(pW,r.quadIndexBuffer),r.setViewport(o,l,h,f),r.setScissor(u,d,p,m),r.setFramebuffer(t)}destroy(){this._shader?.destroy(),this._shader=null,this._scratchRt?.destroy(),this._scratchRt=null,this._scratchTex?.destroy(),this._scratchTex=null,this._sourceId=null}};var XP=class{constructor(){n(this,"renderVersion");n(this,"queries",[])}destroy(t){this.queries.forEach(e=>t.deleteQuery(e)),this.queries=null}},Xv=class extends Yd{constructor(e){super();n(this,"device");n(this,"freeQueries",[]);n(this,"frameQueries",[]);n(this,"previousFrameQueries",[]);n(this,"timings",[]);this.device=e,this.ext=e.extDisjointTimerQuery}destroy(){this.freeQueries.forEach(e=>this.device.gl.deleteQuery(e)),this.frameQueries.forEach(e=>this.device.gl.deleteQuery(e)),this.previousFrameQueries.forEach(e=>e.destroy(this.device.gl)),this.freeQueries=null,this.frameQueries=null,this.previousFrameQueries=null}loseContext(){super.loseContext(),this.freeQueries=[],this.frameQueries=[],this.previousFrameQueries=[]}restoreContext(){this.ext=this.device.extDisjointTimerQuery}getQuery(){return this.freeQueries.pop()??this.device.gl.createQuery()}start(e){if(this.ext){let s=this.getSlot(e),i=this.getQuery();return this.frameQueries[s]=i,this.device.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,i),s}}end(e){e!==void 0&&this.device.gl.endQuery(this.ext.TIME_ELAPSED_EXT)}frameStart(){this.processEnableRequest(),this._enabled&&(this.frameGPUMarkerSlot=this.start("GpuFrame"))}frameEnd(){this._enabled&&this.end(this.frameGPUMarkerSlot)}request(){if(this._enabled){let e=this.ext,s=this.device.gl,i=this.device.renderVersion,r=this.frameQueries;if(r.length>0){this.frameQueries=[];let a=new XP;a.queries=r,a.renderVersion=i,this.previousFrameQueries.push(a)}if(this.previousFrameQueries.length>0){let a=this.previousFrameQueries[0],o=a.queries,l=o[o.length-1],h=s.getQueryParameter(l,s.QUERY_RESULT_AVAILABLE),f=s.getParameter(e.GPU_DISJOINT_EXT);if(h&&!f){this.previousFrameQueries.shift();let u=this.timings;u.length=0;for(let d=0;d{this.report(u.renderVersion,null),u.destroy(s)}),this.previousFrameQueries.length=0)}super.request(i)}}};var gW=c=>{switch(c){case Wr:return 1;case Po:return 2;default:return 0}},qd=[],pc=class extends tt{constructor(e,s={}){super(e,s);n(this,"gl");n(this,"_defaultFramebuffer",null);n(this,"_defaultFramebufferChanged",!1);n(this,"_xrMsaaCopy",null);s=this.initOptions,this.updateClientRect(),this.initTextureUnits(),this.contextLost=!1,this._contextLostHandler=m=>{m.preventDefault(),this.loseContext()},this._contextRestoredHandler=()=>{this.restoreContext()};let i=typeof navigator<"u"&&navigator.userAgent;if(this.forceDisableMultisampling=i&&i.includes("AppleWebKit")&&(i.includes("15.4")||i.includes("15_4")),this.forceDisableMultisampling&&(s.antialias=!1),ue.browserName==="firefox"){let _=(typeof navigator<"u"?navigator.userAgent:"").match(/Firefox\/(\d+(\.\d+)*)/),S=_?_[1]:null;if(S){let g=parseFloat(S);(ue.name==="windows"&&(g>=120||g===115)||ue.name==="android"&&g>=132)&&(s.antialias=!1)}}this.backBufferAntialias=s.antialias??!1,s.antialias=!1;let r=s.gl??e.getContext("webgl2",s);if(!r)throw new Error("WebGL not supported");this.gl=r,this.isWebGL2=!0,this._deviceType=vf,this.updateBackbufferFormat(null);let a=ue.browserName==="chrome",o=ue.browserName==="safari",l=ue.browser&&navigator.appVersion.indexOf("Mac")!==-1;this._tempEnableSafariTextureUnitWorkaround=o,this._tempMacChromeBlitFramebufferWorkaround=l&&a&&!s.alpha,e.addEventListener("webglcontextlost",this._contextLostHandler,!1),e.addEventListener("webglcontextrestored",this._contextRestoredHandler,!1),this.initializeExtensions(),this.initializeCapabilities(),this.initializeRenderState(),this.initializeContextCaches(),this.createBackbuffer(null),this.supportsImageBitmap=!o&&typeof ImageBitmap<"u",this._samplerTypes=new Set([r.SAMPLER_2D,r.SAMPLER_CUBE,r.UNSIGNED_INT_SAMPLER_2D,r.INT_SAMPLER_2D,r.SAMPLER_2D_SHADOW,r.SAMPLER_CUBE_SHADOW,r.SAMPLER_3D,r.INT_SAMPLER_3D,r.UNSIGNED_INT_SAMPLER_3D,r.SAMPLER_2D_ARRAY,r.INT_SAMPLER_2D_ARRAY,r.UNSIGNED_INT_SAMPLER_2D_ARRAY]),this.glAddress=[r.REPEAT,r.CLAMP_TO_EDGE,r.MIRRORED_REPEAT],this.glBlendEquation=[r.FUNC_ADD,r.FUNC_SUBTRACT,r.FUNC_REVERSE_SUBTRACT,r.MIN,r.MAX],this.glBlendFunctionColor=[r.ZERO,r.ONE,r.SRC_COLOR,r.ONE_MINUS_SRC_COLOR,r.DST_COLOR,r.ONE_MINUS_DST_COLOR,r.SRC_ALPHA,r.SRC_ALPHA_SATURATE,r.ONE_MINUS_SRC_ALPHA,r.DST_ALPHA,r.ONE_MINUS_DST_ALPHA,r.CONSTANT_COLOR,r.ONE_MINUS_CONSTANT_COLOR],this.glBlendFunctionAlpha=[r.ZERO,r.ONE,r.SRC_COLOR,r.ONE_MINUS_SRC_COLOR,r.DST_COLOR,r.ONE_MINUS_DST_COLOR,r.SRC_ALPHA,r.SRC_ALPHA_SATURATE,r.ONE_MINUS_SRC_ALPHA,r.DST_ALPHA,r.ONE_MINUS_DST_ALPHA,r.CONSTANT_ALPHA,r.ONE_MINUS_CONSTANT_ALPHA],this.glComparison=[r.NEVER,r.LESS,r.EQUAL,r.LEQUAL,r.GREATER,r.NOTEQUAL,r.GEQUAL,r.ALWAYS],this.glStencilOp=[r.KEEP,r.ZERO,r.REPLACE,r.INCR,r.INCR_WRAP,r.DECR,r.DECR_WRAP,r.INVERT],this.glClearFlag=[0,r.COLOR_BUFFER_BIT,r.DEPTH_BUFFER_BIT,r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT,r.STENCIL_BUFFER_BIT,r.STENCIL_BUFFER_BIT|r.COLOR_BUFFER_BIT,r.STENCIL_BUFFER_BIT|r.DEPTH_BUFFER_BIT,r.STENCIL_BUFFER_BIT|r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT],this.glCull=[0,r.BACK,r.FRONT,r.FRONT_AND_BACK],this.glFrontFace=[r.CCW,r.CW],this.glFilter=[r.NEAREST,r.LINEAR,r.NEAREST_MIPMAP_NEAREST,r.NEAREST_MIPMAP_LINEAR,r.LINEAR_MIPMAP_NEAREST,r.LINEAR_MIPMAP_LINEAR],this.glPrimitive=[r.POINTS,r.LINES,r.LINE_LOOP,r.LINE_STRIP,r.TRIANGLES,r.TRIANGLE_STRIP,r.TRIANGLE_FAN],this.glType=[r.BYTE,r.UNSIGNED_BYTE,r.SHORT,r.UNSIGNED_SHORT,r.INT,r.UNSIGNED_INT,r.FLOAT,r.HALF_FLOAT],this.pcUniformType={},this.pcUniformType[r.BOOL]=wo,this.pcUniformType[r.INT]=bi,this.pcUniformType[r.FLOAT]=Te,this.pcUniformType[r.FLOAT_VEC2]=pr,this.pcUniformType[r.FLOAT_VEC3]=Kt,this.pcUniformType[r.FLOAT_VEC4]=oi,this.pcUniformType[r.INT_VEC2]=jr,this.pcUniformType[r.INT_VEC3]=Di,this.pcUniformType[r.INT_VEC4]=qr,this.pcUniformType[r.BOOL_VEC2]=Dn,this.pcUniformType[r.BOOL_VEC3]=Ln,this.pcUniformType[r.BOOL_VEC4]=Mn,this.pcUniformType[r.FLOAT_MAT2]=lc,this.pcUniformType[r.FLOAT_MAT3]=La,this.pcUniformType[r.FLOAT_MAT4]=as,this.pcUniformType[r.SAMPLER_2D]=eP,this.pcUniformType[r.SAMPLER_CUBE]=tP,this.pcUniformType[r.UNSIGNED_INT]=pe,this.pcUniformType[r.UNSIGNED_INT_VEC2]=Ma,this.pcUniformType[r.UNSIGNED_INT_VEC3]=Oa,this.pcUniformType[r.UNSIGNED_INT_VEC4]=Li,this.pcUniformType[r.SAMPLER_2D_SHADOW]=sP,this.pcUniformType[r.SAMPLER_CUBE_SHADOW]=iP,this.pcUniformType[r.SAMPLER_2D_ARRAY]=aP,this.pcUniformType[r.SAMPLER_3D]=rP,this.pcUniformType[r.INT_SAMPLER_2D]=oP,this.pcUniformType[r.UNSIGNED_INT_SAMPLER_2D]=nP,this.pcUniformType[r.INT_SAMPLER_CUBE]=lP,this.pcUniformType[r.UNSIGNED_INT_SAMPLER_2D]=cP,this.pcUniformType[r.INT_SAMPLER_3D]=hP,this.pcUniformType[r.UNSIGNED_INT_SAMPLER_3D]=fP,this.pcUniformType[r.INT_SAMPLER_2D_ARRAY]=uP,this.pcUniformType[r.UNSIGNED_INT_SAMPLER_2D_ARRAY]=dP,this.targetToSlot={},this.targetToSlot[r.TEXTURE_2D]=0,this.targetToSlot[r.TEXTURE_CUBE_MAP]=1,this.targetToSlot[r.TEXTURE_3D]=2;let h,f,u,d,p;this.commitFunction=[],this.commitFunction[wo]=function(m,_){m.value!==_&&(r.uniform1i(m.locationId,_),m.value=_)},this.commitFunction[bi]=this.commitFunction[wo],this.commitFunction[Te]=function(m,_){m.value!==_&&(r.uniform1f(m.locationId,_),m.value=_)},this.commitFunction[pr]=function(m,_){p=m.value,h=_[0],f=_[1],(p[0]!==h||p[1]!==f)&&(r.uniform2fv(m.locationId,_),p[0]=h,p[1]=f)},this.commitFunction[Kt]=function(m,_){p=m.value,h=_[0],f=_[1],u=_[2],(p[0]!==h||p[1]!==f||p[2]!==u)&&(r.uniform3fv(m.locationId,_),p[0]=h,p[1]=f,p[2]=u)},this.commitFunction[oi]=function(m,_){p=m.value,h=_[0],f=_[1],u=_[2],d=_[3],(p[0]!==h||p[1]!==f||p[2]!==u||p[3]!==d)&&(r.uniform4fv(m.locationId,_),p[0]=h,p[1]=f,p[2]=u,p[3]=d)},this.commitFunction[jr]=function(m,_){p=m.value,h=_[0],f=_[1],(p[0]!==h||p[1]!==f)&&(r.uniform2iv(m.locationId,_),p[0]=h,p[1]=f)},this.commitFunction[Dn]=this.commitFunction[jr],this.commitFunction[Di]=function(m,_){p=m.value,h=_[0],f=_[1],u=_[2],(p[0]!==h||p[1]!==f||p[2]!==u)&&(r.uniform3iv(m.locationId,_),p[0]=h,p[1]=f,p[2]=u)},this.commitFunction[Ln]=this.commitFunction[Di],this.commitFunction[qr]=function(m,_){p=m.value,h=_[0],f=_[1],u=_[2],d=_[3],(p[0]!==h||p[1]!==f||p[2]!==u||p[3]!==d)&&(r.uniform4iv(m.locationId,_),p[0]=h,p[1]=f,p[2]=u,p[3]=d)},this.commitFunction[Mn]=this.commitFunction[qr],this.commitFunction[lc]=function(m,_){r.uniformMatrix2fv(m.locationId,!1,_)},this.commitFunction[La]=function(m,_){r.uniformMatrix3fv(m.locationId,!1,_)},this.commitFunction[as]=function(m,_){r.uniformMatrix4fv(m.locationId,!1,_)},this.commitFunction[On]=function(m,_){r.uniform1fv(m.locationId,_)},this.commitFunction[Fn]=function(m,_){r.uniform2fv(m.locationId,_)},this.commitFunction[Nn]=function(m,_){r.uniform3fv(m.locationId,_)},this.commitFunction[gf]=function(m,_){r.uniform4fv(m.locationId,_)},this.commitFunction[pe]=function(m,_){m.value!==_&&(r.uniform1ui(m.locationId,_),m.value=_)},this.commitFunction[Ma]=function(m,_){p=m.value,h=_[0],f=_[1],(p[0]!==h||p[1]!==f)&&(r.uniform2uiv(m.locationId,_),p[0]=h,p[1]=f)},this.commitFunction[Oa]=function(m,_){p=m.value,h=_[0],f=_[1],u=_[2],(p[0]!==h||p[1]!==f||p[2]!==u)&&(r.uniform3uiv(m.locationId,_),p[0]=h,p[1]=f,p[2]=u)},this.commitFunction[Li]=function(m,_){p=m.value,h=_[0],f=_[1],u=_[2],d=_[3],(p[0]!==h||p[1]!==f||p[2]!==u||p[3]!==d)&&(r.uniform4uiv(m.locationId,_),p[0]=h,p[1]=f,p[2]=u,p[3]=d)},this.commitFunction[Fa]=function(m,_){r.uniform1iv(m.locationId,_)},this.commitFunction[Bn]=function(m,_){r.uniform1uiv(m.locationId,_)},this.commitFunction[Un]=this.commitFunction[Fa],this.commitFunction[Na]=function(m,_){r.uniform2iv(m.locationId,_)},this.commitFunction[kn]=function(m,_){r.uniform2uiv(m.locationId,_)},this.commitFunction[zn]=this.commitFunction[Na],this.commitFunction[Ba]=function(m,_){r.uniform3iv(m.locationId,_)},this.commitFunction[Gn]=function(m,_){r.uniform3uiv(m.locationId,_)},this.commitFunction[Vn]=this.commitFunction[Ba],this.commitFunction[cc]=function(m,_){r.uniform4iv(m.locationId,_)},this.commitFunction[Sf]=function(m,_){r.uniform4uiv(m.locationId,_)},this.commitFunction[xf]=this.commitFunction[cc],this.commitFunction[wg]=function(m,_){r.uniformMatrix4fv(m.locationId,!1,_)},this.constantTexSource=this.scope.resolve("source"),this.postInit()}postInit(){super.postInit(),this.gpuProfiler=new Xv(this)}destroy(){super.destroy();let e=this.gl;this.feedback&&e.deleteTransformFeedback(this.feedback),this.clearVertexArrayObjectCache(),this._xrMsaaCopy?.destroy(),this._xrMsaaCopy=null,this.canvas.removeEventListener("webglcontextlost",this._contextLostHandler,!1),this.canvas.removeEventListener("webglcontextrestored",this._contextRestoredHandler,!1),this._contextLostHandler=null,this._contextRestoredHandler=null,this.gl=null,super.postDestroy()}createBackbuffer(e){this.supportsStencil=this.initOptions.stencil,this.backBuffer=new me({name:"WebglFramebuffer",graphicsDevice:this,depth:this.initOptions.depth,stencil:this.supportsStencil,samples:this.samples}),this.backBuffer.impl.suppliedColorFramebuffer=e}updateBackbufferFormat(e){let s=this.gl;s.bindFramebuffer(s.FRAMEBUFFER,e);let i=this.gl.getParameter(this.gl.ALPHA_BITS);this.backBufferFormat=i?ce:Ss}updateBackbuffer(){let e=this.canvas.width!==this.backBufferSize.x||this.canvas.height!==this.backBufferSize.y;(this._defaultFramebufferChanged||e)&&(this._defaultFramebufferChanged&&this.updateBackbufferFormat(this._defaultFramebuffer),this._defaultFramebufferChanged=!1,this.backBufferSize.set(this.canvas.width,this.canvas.height),this.backBuffer.destroy(),this.createBackbuffer(this._defaultFramebuffer))}createVertexBufferImpl(e,s){return new Fv}createIndexBufferImpl(e){return new Nv(e)}createShaderImpl(e){return new Uv(e)}createDrawCommandImpl(e){return new kv(e.indexSizeBytes)}createTextureImpl(e){return this.textures.add(e),new zv(e)}createXrBridgeImpl(e){return new Hv(e)}createRenderTargetImpl(e){return new Gv}createUploadStreamImpl(e){return new Vv(e)}getPrecision(){let e=this.gl,s="highp";if(e.getShaderPrecisionFormat){let i=e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT),r=e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT),a=e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT),o=e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT);if(i&&r&&a&&o){let l=i.precision>0&&a.precision>0,h=r.precision>0&&o.precision>0;l||(h?s="mediump":s="lowp")}}return s}getExtension(){for(let e=0;e0&&e.fullSizeClearRect&&r.invalidateFramebuffer(r.DRAW_FRAMEBUFFER,qd),i&&e.colorOps?.resolve&&e.samples>1&&s.autoResolve&&s.resolve(!0,!1),s.depthBuffer&&e.depthStencilOps.resolveDepth&&e.samples>1&&s.autoResolve&&s.resolve(!1,!0);for(let a=0;a1&&e.autoResolve&&e.resolve();let s=e._colorBuffer;s&&s.impl._glTexture&&s.mipmaps&&(this.activeTexture(this.maxCombinedTextures-1),this.bindTexture(s),this.gl.generateMipmap(s.impl._glTarget))}}setUnpackFlipY(e){if(this.unpackFlipY!==e){this.unpackFlipY=e;let s=this.gl;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,e)}}setUnpackPremultiplyAlpha(e){if(this.unpackPremultiplyAlpha!==e){this.unpackPremultiplyAlpha=e;let s=this.gl;s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e)}}setUnpackAlignment(e){this.unpackAlignment!==e&&(this.unpackAlignment=e,this.gl.pixelStorei(this.gl.UNPACK_ALIGNMENT,e))}activeTexture(e){this.textureUnit!==e&&(this.gl.activeTexture(this.gl.TEXTURE0+e),this.textureUnit=e)}bindTexture(e){let s=e.impl,i=s._glTarget,r=s._glTexture,a=this.textureUnit,o=this.targetToSlot[i];this.textureUnits[a][o]!==r&&(this.gl.bindTexture(i,r),this.textureUnits[a][o]=r)}bindTextureOnUnit(e,s){let i=e.impl,r=i._glTarget,a=i._glTexture,o=this.targetToSlot[r];this.textureUnits[s][o]!==a&&(this.activeTexture(s),this.gl.bindTexture(r,a),this.textureUnits[s][o]=a)}setTextureParameters(e){let s=this.gl,i=e.impl.dirtyParameterFlags,r=e.impl._glTarget;if(i&Od){let a=e._minFilter;(!e._mipmaps||e._compressed&&e._levels.length===1)&&(a===2||a===3?a=0:(a===4||a===5)&&(a=1)),s.texParameteri(r,s.TEXTURE_MIN_FILTER,this.glFilter[a])}if(i&Rg&&s.texParameteri(r,s.TEXTURE_MAG_FILTER,this.glFilter[e._magFilter]),i&bg&&s.texParameteri(r,s.TEXTURE_WRAP_S,this.glAddress[e._addressU]),i&Dg&&s.texParameteri(r,s.TEXTURE_WRAP_T,this.glAddress[e._addressV]),i&Lg&&s.texParameteri(r,s.TEXTURE_WRAP_R,this.glAddress[e._addressW]),i&Mg&&s.texParameteri(r,s.TEXTURE_COMPARE_MODE,e._compareOnRead?s.COMPARE_REF_TO_TEXTURE:s.NONE),i&Og&&s.texParameteri(r,s.TEXTURE_COMPARE_FUNC,this.glComparison[e._compareFunc]),i&Fg){let a=this.extTextureFilterAnisotropic;a&&s.texParameterf(r,a.TEXTURE_MAX_ANISOTROPY_EXT,R.clamp(Math.round(e._anisotropy),1,this.maxAnisotropy))}}setTexture(e,s){let i=e.impl;i._glTexture||i.initialize(this,e),i.dirtyParameterFlags>0||e._needsUpload||e._needsMipmapsUpload?(this.activeTexture(s),this.bindTexture(e),i.dirtyParameterFlags&&(this.setTextureParameters(e),i.dirtyParameterFlags=0),(e._needsUpload||e._needsMipmapsUpload)&&(i.upload(this,e),e._needsUpload=!1,e._needsMipmapsUpload=!1)):this.bindTextureOnUnit(e,s)}createVertexArray(e){let s,i,r=e.length>1;if(r){s="";for(let a=0;a0)for(let p=0;p0)for(let d=0;d0?this.extMultiDraw.multiDrawElementsInstancedWEBGL(p,_.glCounts,0,S,_.glOffsetsBytes,0,_.glInstanceCounts,0,r.count):this.extMultiDraw.multiDrawElementsWEBGL(p,_.glCounts,0,S,_.glOffsetsBytes,0,r.count)}else i>0?this.extMultiDraw.multiDrawArraysInstancedWEBGL(p,_.glOffsetsBytes,0,_.glCounts,0,_.glInstanceCounts,0,r.count):this.extMultiDraw.multiDrawArraysWEBGL(p,_.glOffsetsBytes,0,_.glCounts,0,r.count)}else this._multiDrawLoopFallback(p,e,s,i,r);else if(e.indexed){let _=s.impl.glFormat,S=e.base*s.bytesPerIndex;i>0?h.drawElementsInstanced(p,m,_,S,i):h.drawElements(p,m,_,S)}else{let _=e.base;i>0?h.drawArraysInstanced(p,_,m,i):h.drawArrays(p,_,m)}this.transformFeedbackBuffer&&(h.endTransformFeedback(),h.bindBufferBase(h.TRANSFORM_FEEDBACK_BUFFER,0,null)),this._drawCallsPerFrame++}o&&this.clearVertexBuffer()}clear(e){let s=this.defaultClearOptions;e=e||s;let i=e.flags??s.flags;if(i!==0){let r=this.gl;if(i&1){let a=e.color??s.color,o=a[0],l=a[1],h=a[2],f=a[3],u=this.clearColor;(o!==u.r||l!==u.g||h!==u.b||f!==u.a)&&(this.gl.clearColor(o,l,h,f),this.clearColor.set(o,l,h,f)),this.setBlendState(Oe.NOBLEND)}if(i&2){let a=e.depth??s.depth;a!==this.clearDepth&&(this.gl.clearDepth(a),this.clearDepth=a),this.setDepthState(Pt.WRITEDEPTH)}if(i&4){let a=e.stencil??s.stencil;a!==this.clearStencil&&(this.gl.clearStencil(a),this.clearStencil=a),r.stencilMask(255),this.stencilWriteMaskFront=255,this.stencilWriteMaskBack=255}r.clear(this.glClearFlag[i])}}submit(){this.gl.flush()}readPixels(e,s,i,r,a){let o=this.gl;o.readPixels(e,s,i,r,o.RGBA,o.UNSIGNED_BYTE,a)}clientWaitAsync(e,s){let i=this.gl,r=i.fenceSync(i.SYNC_GPU_COMMANDS_COMPLETE,0);return this.submit(),new Promise((a,o)=>{function l(){let h=i.clientWaitSync(r,e,0);h===i.TIMEOUT_EXPIRED?setTimeout(l,s):(i.deleteSync(r),h===i.WAIT_FAILED?o(new Error("webgl clientWaitSync sync failed")):a())}l()})}async readPixelsAsync(e,s,i,r,a,o=!1){let l=this.gl,h,f;if(o)h=l.RGBA,f=l.UNSIGNED_BYTE;else{let d=this.renderTarget.colorBuffer?.impl;h=d?._glFormat??l.RGBA,f=d?._glPixelType??l.UNSIGNED_BYTE}let u=l.createBuffer();return l.bindBuffer(l.PIXEL_PACK_BUFFER,u),l.bufferData(l.PIXEL_PACK_BUFFER,a.byteLength,l.STREAM_READ),l.readPixels(e,s,i,r,h,f,0),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),await this.clientWaitAsync(0,16),l.bindBuffer(l.PIXEL_PACK_BUFFER,u),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,a),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),l.deleteBuffer(u),a}readTextureAsync(e,s,i,r,a,o){let l=o.face??0,h=o.mipLevel??0,f=o.renderTarget??new me({colorBuffer:e,depth:!1,face:l,mipLevel:h}),u=gW(e._format),d=u>0,p=pf(e._format),m=o.data??new p(gt.calcLevelGpuSize(r,a,1,e._format)/p.BYTES_PER_ELEMENT),_=d?new Uint8Array(r*a*4):m;return this.setRenderTarget(f),this.initRenderTarget(f),this.setFramebuffer(f.impl._glFrameBuffer),o.immediate&&this.gl.flush(),new Promise((S,g)=>{this.readPixelsAsync(s,i,r,a,_,d).then(C=>{if(!this._destroyed)if(o.renderTarget||f.destroy(),d){let v=r*a;for(let E=0;E{e.deleteVertexArray(s)}),this._vaoMap.clear()}set fullscreen(e){e?this.gl.canvas.requestFullscreen():document.exitFullscreen()}get fullscreen(){return!!document.fullscreenElement}};var Yv=class{unlock(t){}};var Kv=class{destroy(t){}init(t,e){}loseContext(){}resolve(t,e,s,i){}};var jv=class{destroy(t){}loseContext(){}restoreContext(t,e){}};var qv=class{destroy(t){}propertyChanged(t){}loseContext(){}};var $v=class{destroy(t){}unlock(t){}};var Zv=class{add(t,e,s,i){}};var $d=class extends tt{constructor(t,e={}){super(t,e),e=this.initOptions,this.isNull=!0,this._deviceType=Tf,this.samples=1,this.backBuffer=new me({name:"Framebuffer",graphicsDevice:this,depth:this.initOptions.depth,stencil:this.supportsStencil,samples:this.samples}),this.initDeviceCaps()}destroy(){super.destroy()}initDeviceCaps(){this.disableParticleSystem=!0,this.precision="highp",this.maxPrecision="highp",this.maxSamples=4,this.maxTextures=16,this.maxTextureSize=4096,this.maxCubeMapSize=4096,this.maxVolumeSize=4096,this.maxColorAttachments=8,this.maxPixelRatio=1,this.maxAnisotropy=16,this.supportsUniformBuffers=!1,this.supportsAreaLights=!0,this.supportsGpuParticles=!1,this.textureFloatRenderable=!0,this.textureHalfFloatRenderable=!0,this.supportsImageBitmap=!1}postInit(){super.postInit()}frameStart(){super.frameStart()}frameEnd(){super.frameEnd()}updateBegin(){}updateEnd(){}readPixels(t,e,s,i,r){}createVertexBufferImpl(t,e){return new $v(t,e)}createIndexBufferImpl(t){return new Yv(t)}createShaderImpl(t){return new jv(t)}createTextureImpl(t){return new qv(t)}createRenderTargetImpl(t){return new Kv(t)}createDrawCommandImpl(t){return new Zv}createUploadStreamImpl(t){return null}draw(t,e,s,i,r=!0,a=!0){}setShader(t,e=!1){}setBlendState(t){}setDepthState(t){}setStencilState(t,e){}setBlendColor(t,e,s,i){}setCullMode(t){}setFrontFace(t){}setAlphaToCoverage(t){}initializeContextCaches(){super.initializeContextCaches()}clear(t){}setViewport(t,e,s,i){}setScissor(t,e,s,i){}copyRenderTarget(t,e,s,i){return!0}};function iL(c,t={}){let e=t.deviceTypes??[];e.includes(vf)||e.push(vf),e.includes(Tf)||e.push(Tf);let s=[];for(let i=0;inew Kd(c,{...t,featureLevel:a}).initWebGpu(t.glslangUrl,t.twgslUrl))}r===vf&&s.push(()=>new pc(c,t)),r===Tf&&s.push(()=>new $d(c,t))}return new Promise((i,r)=>{let a=0,o=()=>{a>=s.length?r(new Error("Failed to create a graphics device")):Promise.resolve(s[a++]()).then(l=>{l?i(l):o()}).catch(l=>{o()})};o()})}var YP=class{constructor(){n(this,"value");n(this,"scopeId",null)}},Ye=class{constructor(t,e,s="Unnamed"){n(this,"shader",null);n(this,"name");n(this,"parameters",new Map);n(this,"countX",1);n(this,"countY");n(this,"countZ");n(this,"indirectSlotIndex",-1);n(this,"indirectBuffer",null);n(this,"indirectFrameStamp",0);this.device=t,this.shader=e,this.name=s,t.supportsCompute&&(this.impl=t.createComputeImpl(this))}setParameter(t,e){let s=this.parameters.get(t);s||(s=new YP,s.scopeId=this.device.scope.resolve(t),this.parameters.set(t,s)),s.value=e}getParameter(t){return this.parameters.get(t)?.value}deleteParameter(t){this.parameters.delete(t)}destroy(){this.impl?.destroy(),this.impl=null}applyParameters(){for(let[,t]of this.parameters)t.scopeId.setValue(t.value)}setupDispatch(t,e,s){this.countX=t,this.countY=e,this.countZ=s,this.indirectSlotIndex=-1,this.indirectBuffer=null}setupIndirectDispatch(t,e=null){this.indirectSlotIndex=t,this.indirectBuffer=e,this.indirectFrameStamp=this.device.renderVersion}static calcDispatchSize(t,e,s=65535){if(t<=s)return e.set(t,1);let i=Math.ceil(t/s);return e.set(Math.ceil(t/i),i)}};var Cf=class{constructor(t,e=0){n(this,"device");n(this,"indexSizeBytes");n(this,"_maxCount",0);n(this,"impl",null);n(this,"_count",1);n(this,"slotIndex",0);n(this,"primitiveCount",0);this.device=t,this.indexSizeBytes=e,this.impl=t.createDrawCommandImpl(this)}get maxCount(){return this._maxCount}get count(){return this._count}destroy(){this.impl?.destroy?.(),this.impl=null}allocate(t){this._maxCount=t,this.impl.allocate?.(t)}add(t,e,s,i,r=0,a=0){this.impl.add(t,e,s,i,r,a)}update(t){this._count=t,this.primitiveCount=this.impl.update?.(t)??0}};var Nt=class{constructor(t){n(this,"_name");n(this,"device");n(this,"_enabled",!0);n(this,"_skipStart",!1);n(this,"_skipEnd",!1);n(this,"executeEnabled",!0);n(this,"requiresCubemaps",!1);n(this,"beforePasses",[]);n(this,"afterPasses",[]);this.device=t}set name(t){this._name=t}get name(){return this._name||(this._name=this.constructor.name),this._name}set enabled(t){this._enabled!==t&&(this._enabled=t,t?this.onEnable():this.onDisable())}get enabled(){return this._enabled}onEnable(){}onDisable(){}frameUpdate(){}before(){}execute(){}after(){}destroy(){}render(){this.enabled&&(this.before(),this.executeEnabled&&this.execute(),this.after(),this.device.renderPassIndex++)}};var KP=class{constructor(){n(this,"clearValue",new F(0,0,0,1));n(this,"clearValueLinear",new F(0,0,0,1));n(this,"clear",!1);n(this,"store",!1);n(this,"resolve",!0);n(this,"genMipmaps",!1)}},jP=class{constructor(){n(this,"clearDepthValue",1);n(this,"clearStencilValue",0);n(this,"clearDepth",!1);n(this,"clearStencil",!1);n(this,"storeDepth",!1);n(this,"resolveDepth",!1);n(this,"storeStencil",!1)}},yt=class extends Nt{constructor(){super(...arguments);n(this,"renderTarget");n(this,"_options");n(this,"samples",0);n(this,"colorArrayOps",[]);n(this,"depthStencilOps");n(this,"requiresCubemaps",!0);n(this,"fullSizeClearRect",!0)}get colorOps(){return this.colorArrayOps[0]}set scaleX(e){this._options.scaleX=e}get scaleX(){return this._options.scaleX}set scaleY(e){this._options.scaleY=e}get scaleY(){return this._options.scaleY}set options(e){this._options=e,e&&(this.scaleX=this.scaleX??1,this.scaleY=this.scaleY??1)}get options(){return this._options}init(e=null,s){this.options=s,this.renderTarget=e,this.samples=Math.max(this.renderTarget?this.renderTarget.samples:this.device.samples,1),this.allocateAttachments(),this.postInit()}allocateAttachments(){let e=this.renderTarget;this.depthStencilOps=new jP,e?.depthBuffer&&(this.depthStencilOps.storeDepth=!0);let s=e?e._colorBuffers?.length??0:1;this.colorArrayOps.length=0;for(let i=0;ithis.vertexBuffer.numVertices&&(s=this.vertexBuffer.numVertices);let r=i.numComponents;if(this.vertexBuffer.getFormat().interleaved){let a=0;for(let o=0;os*r){let a=s*r;if(ArrayBuffer.isView(e))e=e.subarray(0,a),i.array.set(e);else for(let o=0;o0?this.wheelDelta=1:e.deltaY<0&&(this.wheelDelta=-1)),tT()?(this.dx=e.movementX||e.webkitMovementX||e.mozMovementX||0,this.dy=e.movementY||e.webkitMovementY||e.mozMovementY||0):(this.dx=this.x-t._lastX,this.dy=this.y-t._lastY),(e.type==="mousedown"||e.type==="mouseup")&&(this.button=e.button),this.buttons=t._buttons.slice(0),this.element=e.target,this.ctrlKey=e.ctrlKey??!1,this.altKey=e.altKey??!1,this.shiftKey=e.shiftKey??!1,this.metaKey=e.metaKey??!1,this.event=e}};var qi=class extends J{constructor(e){super();n(this,"_lastX",0);n(this,"_lastY",0);n(this,"_buttons",[!1,!1,!1]);n(this,"_lastbuttons",[!1,!1,!1]);n(this,"_target",null);n(this,"_attached",!1);n(this,"_upHandler");n(this,"_downHandler");n(this,"_moveHandler");n(this,"_wheelHandler");n(this,"_contextMenuHandler");this._upHandler=this._handleUp.bind(this),this._downHandler=this._handleDown.bind(this),this._moveHandler=this._handleMove.bind(this),this._wheelHandler=this._handleWheel.bind(this),this._contextMenuHandler=s=>{s.preventDefault()},this.attach(e)}static isPointerLocked(){return tT()}attach(e){if(this._target=e,this._attached)return;this._attached=!0;let s={passive:!1},i=ue.passiveEvents?s:!1;window.addEventListener("mouseup",this._upHandler,i),window.addEventListener("mousedown",this._downHandler,i),window.addEventListener("mousemove",this._moveHandler,i),window.addEventListener("wheel",this._wheelHandler,i)}detach(){if(!this._attached)return;this._attached=!1,this._target=null;let e={passive:!1},s=ue.passiveEvents?e:!1;window.removeEventListener("mouseup",this._upHandler,s),window.removeEventListener("mousedown",this._downHandler,s),window.removeEventListener("mousemove",this._moveHandler,s),window.removeEventListener("wheel",this._wheelHandler,s)}disableContextMenu(){this._target&&this._target.addEventListener("contextmenu",this._contextMenuHandler)}enableContextMenu(){this._target&&this._target.removeEventListener("contextmenu",this._contextMenuHandler)}enablePointerLock(e,s){if(!document.body.requestPointerLock){s&&s();return}let i=()=>{e(),document.removeEventListener("pointerlockchange",i)},r=()=>{s(),document.removeEventListener("pointerlockerror",r)};e&&document.addEventListener("pointerlockchange",i,!1),s&&document.addEventListener("pointerlockerror",r,!1),document.body.requestPointerLock()}disablePointerLock(e){if(!document.exitPointerLock)return;let s=()=>{e(),document.removeEventListener("pointerlockchange",s)};e&&document.addEventListener("pointerlockchange",s,!1),document.exitPointerLock()}update(){this._lastbuttons[0]=this._buttons[0],this._lastbuttons[1]=this._buttons[1],this._lastbuttons[2]=this._buttons[2]}isPressed(e){return this._buttons[e]}wasPressed(e){return this._buttons[e]&&!this._lastbuttons[e]}wasReleased(e){return!this._buttons[e]&&this._lastbuttons[e]}_handleUp(e){this._buttons[e.button]=!1;let s=new za(this,e);s.event&&this.fire("mouseup",s)}_handleDown(e){this._buttons[e.button]=!0;let s=new za(this,e);s.event&&this.fire("mousedown",s)}_handleMove(e){let s=new za(this,e);s.event&&(this.fire("mousemove",s),this._lastX=s.x,this._lastY=s.y)}_handleWheel(e){let s=new za(this,e);s.event&&this.fire("mousewheel",s)}_getTargetCoords(e){let s=this._target.getBoundingClientRect(),i=Math.floor(s.left),r=Math.floor(s.top);return e.clientX=i+this._target.clientWidth||e.clientY=r+this._target.clientHeight?null:{x:e.clientX-i,y:e.clientY-r}}};n(qi,"EVENT_MOUSEMOVE","mousemove"),n(qi,"EVENT_MOUSEDOWN","mousedown"),n(qi,"EVENT_MOUSEUP","mouseup"),n(qi,"EVENT_MOUSEWHEEL","mousewheel");var sT=class{constructor(t,e={}){n(this,"_keyboard");n(this,"_mouse");n(this,"_gamepads");n(this,"_element",null);n(this,"_actions",{});n(this,"_axes",{});n(this,"_axesValues",{});this._keyboard=e.keyboard||null,this._mouse=e.mouse||null,this._gamepads=e.gamepads||null,t&&this.attach(t)}attach(t){this._element=t,this._keyboard&&this._keyboard.attach(t),this._mouse&&this._mouse.attach(t)}detach(){this._keyboard&&this._keyboard.detach(),this._mouse&&this._mouse.detach(),this._element=null}disableContextMenu(){this._mouse||this._enableMouse(),this._mouse.disableContextMenu()}enableContextMenu(){this._mouse||this._enableMouse(),this._mouse.enableContextMenu()}update(t){this._keyboard&&this._keyboard.update(),this._mouse&&this._mouse.update(),this._gamepads&&this._gamepads.update(),this._axesValues={};for(let e in this._axes)this._axesValues[e]=[]}appendAction(t,e){this._actions[t]=this._actions[t]||[],this._actions[t].push(e)}registerKeys(t,e){if(this._keyboard||this._enableKeyboard(),this._actions[t])throw new Error(`Action: ${t} already registered`);if(e===void 0)throw new Error("Invalid button");e.length||(e=[e]),this.appendAction(t,{type:zg,keys:e})}registerMouse(t,e){if(this._mouse||this._enableMouse(),e===void 0)throw new Error("Invalid button");this.appendAction(t,{type:kg,button:e})}registerPadButton(t,e,s){if(s===void 0)throw new Error("Invalid button");this.appendAction(t,{type:Gg,button:s,pad:e})}registerAxis(t){let e=t.name;this._axes[e]||(this._axes[e]=[]);let s=this._axes[e].push(e);t=t||{},t.pad=t.pad||0;let i=function(r,a,o,l){switch(a){case"mousex":r._mouse.on("mousemove",h=>{r._axesValues[e][s]=h.dx/10});break;case"mousey":r._mouse.on("mousemove",h=>{r._axesValues[e][s]=h.dy/10});break;case"key":r._axes[e].push(()=>r._keyboard.isPressed(l)?o:0);break;case"padrx":r._axes[e].push(()=>r._gamepads.getAxis(t.pad,2));break;case"padry":r._axes[e].push(()=>r._gamepads.getAxis(t.pad,3));break;case"padlx":r._axes[e].push(()=>r._gamepads.getAxis(t.pad,0));break;case"padly":r._axes[e].push(()=>r._gamepads.getAxis(t.pad,1));break;default:throw new Error("Unknown axis")}};i(this,t.positive,1,t.positiveKey),(t.negativeKey||t.negative!==t.positive)&&i(this,t.negative,-1,t.negativeKey)}isPressed(t){if(!this._actions[t])return!1;let e=this._actions[t].length;for(let s=0;sMath.abs(e)&&(e=r)}else this._axesValues[t]&&Math.abs(this._axesValues[t][i])>Math.abs(e)&&(e=this._axesValues[t][i])}return e}_enableMouse(){if(this._mouse=new qi,!this._element)throw new Error("Controller must be attached to an Element");this._mouse.attach(this._element)}_enableKeyboard(){if(this._keyboard=new mc,!this._element)throw new Error("Controller must be attached to an Element");this._keyboard.attach(this._element)}};var nL=Object.freeze([]),sw=function(){return nL};typeof navigator<"u"&&(sw=(navigator.getGamepads||navigator.webkitGetGamepads||sw).bind(navigator));var aL={buttons:{PAD_FACE_1:0,PAD_FACE_2:1,PAD_FACE_3:2,PAD_FACE_4:3,PAD_L_SHOULDER_1:4,PAD_R_SHOULDER_1:5,PAD_L_SHOULDER_2:6,PAD_R_SHOULDER_2:7,PAD_SELECT:8,PAD_START:9,PAD_L_STICK_BUTTON:10,PAD_R_STICK_BUTTON:11,PAD_UP:12,PAD_DOWN:13,PAD_LEFT:14,PAD_RIGHT:15,PAD_VENDOR:16,XRPAD_TRIGGER:0,XRPAD_SQUEEZE:1,XRPAD_TOUCHPAD_BUTTON:2,XRPAD_STICK_BUTTON:3,XRPAD_A:4,XRPAD_B:5},axes:{PAD_L_STICK_X:0,PAD_L_STICK_Y:1,PAD_R_STICK_X:2,PAD_R_STICK_Y:3,XRPAD_TOUCHPAD_X:0,XRPAD_TOUCHPAD_Y:1,XRPAD_STICK_X:2,XRPAD_STICK_Y:3}},Vg={DEFAULT:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_3","PAD_FACE_4","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_UP","PAD_DOWN","PAD_LEFT","PAD_RIGHT","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"]},DEFAULT_DUAL:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_3","PAD_FACE_4","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"],synthesizedButtons:{PAD_UP:{axis:0,min:0,max:1},PAD_DOWN:{axis:0,min:-1,max:0},PAD_LEFT:{axis:0,min:-1,max:0},PAD_RIGHT:{axis:0,min:0,max:1}}},PS3:{buttons:["PAD_FACE_1","PAD_FACE_2","PAD_FACE_4","PAD_FACE_3","PAD_L_SHOULDER_1","PAD_R_SHOULDER_1","PAD_L_SHOULDER_2","PAD_R_SHOULDER_2","PAD_SELECT","PAD_START","PAD_L_STICK_BUTTON","PAD_R_STICK_BUTTON","PAD_UP","PAD_DOWN","PAD_LEFT","PAD_RIGHT","PAD_VENDOR"],axes:["PAD_L_STICK_X","PAD_L_STICK_Y","PAD_R_STICK_X","PAD_R_STICK_Y"],mapping:"standard"},DEFAULT_XR:{buttons:["XRPAD_TRIGGER","XRPAD_SQUEEZE","XRPAD_TOUCHPAD_BUTTON","XRPAD_STICK_BUTTON","XRPAD_A","XRPAD_B"],axes:["XRPAD_TOUCHPAD_X","XRPAD_TOUCHPAD_Y","XRPAD_STICK_X","XRPAD_STICK_Y"],mapping:"xr-standard"}},oL={"Product: 0268":"PS3"},iT={};function lL(c){let t=iT[c.id];if(t)return t;for(let i in oL)if(c.id.indexOf(i)!==-1){let r=oL[i];if(!c.mapping){let a=Vg[`RAW_${r}`];if(a)return a}return Vg[r]}if(c.mapping==="xr-standard")return Vg.DEFAULT_XR;let e=Vg.DEFAULT,s=c.buttons.length{setTimeout(t,c)})}var Hg=class{constructor(t,e){n(this,"value",0);n(this,"pressed",!1);n(this,"touched",!1);n(this,"wasPressed",!1);n(this,"wasReleased",!1);n(this,"wasTouched",!1);typeof t=="number"?(this.value=t,this.pressed=t===1,this.touched=t>0):(this.value=t.value,this.pressed=t.pressed,this.touched=t.touched??t.value>0),e&&(typeof e=="number"?(this.wasPressed=e!==1&&this.pressed,this.wasReleased=e===1&&!this.pressed,this.wasTouched=e===0&&this.touched):(this.wasPressed=!e.pressed&&this.pressed,this.wasReleased=e.pressed&&!this.pressed,this.wasTouched=!(e.touched??e.value>0)&&this.touched))}update(t){let{value:e,pressed:s}=t,i=t.touched??e>0;this.wasPressed=!this.pressed&&s,this.wasReleased=this.pressed&&!s,this.wasTouched=!this.touched&&i,this.value=e,this.pressed=s,this.touched=i}},tw=Object.freeze(new Hg(0)),rT=class{constructor(t,e){n(this,"_compiledMapping",{buttons:[],axes:[]});n(this,"id");n(this,"index");n(this,"_buttons");n(this,"_axes");n(this,"_previousAxes");n(this,"mapping");n(this,"map");n(this,"hand");n(this,"pad");this.id=t.id,this.index=t.index,this._buttons=t.buttons.map(s=>new Hg(s)),this._axes=[...t.axes],this._previousAxes=[...t.axes],this.mapping=e.mapping,this.map=e,this.hand=t.hand||"none",this.pad=t,this._compileMapping()}get connected(){return this.pad.connected}_compileMapping(){let{axes:t,buttons:e}=this._compiledMapping,s=aL.axes,i=aL.buttons;t.length=0,e.length=0,this.map.axes&&this.map.axes.forEach((l,h)=>{t[s[l]]=()=>this.pad.axes[h]||0});for(let l=0,h=t.length;l0);let a=this.map.buttons;a&&a.forEach((l,h)=>{e[i[l]]=()=>this._buttons[h]||tw});let o=this.map.synthesizedButtons;o&&Object.entries(o).forEach(l=>{let{axis:h,max:f,min:u}=l[1];e[i[l[0]]]=()=>new Hg(Math.abs(R.clamp(this._axes[h]??0,u,f)),Math.abs(R.clamp(this._previousAxes[h]??0,u,f)))});for(let l=0,h=e.length;ltw)}update(t){this.pad=t;let e=this._previousAxes,s=this._axes;e.length=0,e.push(...s),s.length=0,s.push(...t.axes);let i=this._buttons;for(let r=0,a=i.length;rt())}get buttons(){return this._compiledMapping.buttons.map(t=>t())}async pulse(t,e,s){let i=this.pad.vibrationActuator?[this.pad.vibrationActuator]:this.pad.hapticActuators||nL;if(i.length){let r=s?.startDelay??0,a=s?.strongMagnitude??t,o=s?.weakMagnitude??t;return(await Promise.all(i.map(async h=>h?h.playEffect?h.playEffect(h.type,{duration:e,startDelay:r,strongMagnitude:a,weakMagnitude:o}):h.pulse?(await fX(r),h.pulse(t,e)):!1:!0))).some(h=>h===!0||h==="complete")}return!1}getButton(t){let e=this._compiledMapping.buttons[t];return e?e():tw}isPressed(t){return this.getButton(t).pressed}wasPressed(t){return this.getButton(t).wasPressed}wasReleased(t){return this.getButton(t).wasReleased}isTouched(t){return this.getButton(t).touched}wasTouched(t){return this.getButton(t).wasTouched}getValue(t){return this.getButton(t).value}getAxis(t){let e=this.axes[t];return e&&Math.abs(e)>iw?e:0}},Qd=class extends J{constructor(){super();n(this,"gamepadsSupported");n(this,"current",[]);n(this,"_previous",[]);n(this,"_ongamepadconnectedHandler");n(this,"_ongamepaddisconnectedHandler");this.gamepadsSupported=ue.gamepads,this._ongamepadconnectedHandler=this._ongamepadconnected.bind(this),this._ongamepaddisconnectedHandler=this._ongamepaddisconnected.bind(this),window.addEventListener("gamepadconnected",this._ongamepadconnectedHandler,!1),window.addEventListener("gamepaddisconnected",this._ongamepaddisconnectedHandler,!1),this.poll()}set deadZone(e){iw=e}get deadZone(){return iw}get previous(){let e=this.current;for(let s=0,i=e.length;sa.index===s.index);for(;r!==-1;)i.splice(r,1),r=i.findIndex(a=>a.index===s.index);i.push(s),this.fire("gamepadconnected",s)}_ongamepaddisconnected(e){let s=this.current,i=s.findIndex(r=>r.index===e.gamepad.index);i!==-1&&(this.fire("gamepaddisconnected",s[i]),s.splice(i,1))}update(){this.poll()}poll(e=[]){e.length>0&&(e.length=0);let s=sw();for(let i=0,r=s.length;ir.pulse(e,s,i)))}findById(e){return this.current.find(s=>s&&s.id===e)||null}findByIndex(e){return this.current.find(s=>s&&s.index===e)||null}};n(Qd,"EVENT_GAMEPADCONNECTED","gamepadconnected"),n(Qd,"EVENT_GAMEPADDISCONNECTED","gamepaddisconnected");function Pf(c){let t=0,e=0,s=c.target;for(;!(s instanceof HTMLElement)&&s;)s=s.parentNode;for(;s;)t+=s.offsetLeft-s.scrollLeft,e+=s.offsetTop-s.scrollTop,s=s.offsetParent;return{x:c.pageX-t,y:c.pageY-e}}var Jd=class{constructor(t){n(this,"id");n(this,"x");n(this,"y");n(this,"target");n(this,"touch");let e=Pf(t);this.id=t.identifier,this.x=e.x,this.y=e.y,this.target=t.target,this.touch=t}},qn=class{constructor(t,e){n(this,"element");n(this,"event");n(this,"touches",[]);n(this,"changedTouches",[]);this.element=e.target,this.event=e,this.touches=Array.from(e.touches).map(s=>new Jd(s)),this.changedTouches=Array.from(e.changedTouches).map(s=>new Jd(s))}getTouchById(t,e){return e.find(s=>s.id===t)||null}};var _c=class extends J{constructor(e){super();n(this,"_element",null);n(this,"_startHandler");n(this,"_endHandler");n(this,"_moveHandler");n(this,"_cancelHandler");this._startHandler=this._handleTouchStart.bind(this),this._endHandler=this._handleTouchEnd.bind(this),this._moveHandler=this._handleTouchMove.bind(this),this._cancelHandler=this._handleTouchCancel.bind(this),this.attach(e)}attach(e){this._element&&this.detach(),this._element=e,this._element.addEventListener("touchstart",this._startHandler,!1),this._element.addEventListener("touchend",this._endHandler,!1),this._element.addEventListener("touchmove",this._moveHandler,!1),this._element.addEventListener("touchcancel",this._cancelHandler,!1)}detach(){this._element&&(this._element.removeEventListener("touchstart",this._startHandler,!1),this._element.removeEventListener("touchend",this._endHandler,!1),this._element.removeEventListener("touchmove",this._moveHandler,!1),this._element.removeEventListener("touchcancel",this._cancelHandler,!1)),this._element=null}_handleTouchStart(e){this.fire("touchstart",new qn(this,e))}_handleTouchEnd(e){this.fire("touchend",new qn(this,e))}_handleTouchMove(e){e.preventDefault(),this.fire("touchmove",new qn(this,e))}_handleTouchCancel(e){this.fire("touchcancel",new qn(this,e))}};n(_c,"EVENT_TOUCHSTART","touchstart"),n(_c,"EVENT_TOUCHEND","touchend"),n(_c,"EVENT_TOUCHMOVE","touchmove"),n(_c,"EVENT_TOUCHCANCEL","touchcancel");var nt=class nt{get(t,e,s){typeof e=="function"&&(s=e,e={});let i=this.request("GET",t,e,s),{progress:r}=e;if(r){let a=l=>{l.lengthComputable&&r.fire("progress",l.loaded,l.total)},o=l=>{a(l),i.removeEventListener("loadstart",a),i.removeEventListener("progress",a),i.removeEventListener("loadend",o)};i.addEventListener("loadstart",a),i.addEventListener("progress",a),i.addEventListener("loadend",o)}return i}post(t,e,s,i){return typeof s=="function"&&(i=s,s={}),s.postdata=e,this.request("POST",t,s,i)}put(t,e,s,i){return typeof s=="function"&&(i=s,s={}),s.postdata=e,this.request("PUT",t,s,i)}del(t,e,s){return typeof e=="function"&&(s=e,e={}),this.request("DELETE",t,e,s)}request(t,e,s,i){let r,a,o,l=!1;if(typeof s=="function"&&(i=s,s={}),s.retry&&(s=Object.assign({retries:0,maxRetries:5},s)),s.callback=i,s.async==null&&(s.async=!0),s.headers==null&&(s.headers={}),s.postdata!=null)if(s.postdata instanceof Document)o=s.postdata;else if(s.postdata instanceof FormData)o=s.postdata;else if(s.postdata instanceof Object){let f=s.headers["Content-Type"];switch(f===void 0&&(s.headers["Content-Type"]=nt.ContentType.FORM_URLENCODED,f=s.headers["Content-Type"]),f){case nt.ContentType.FORM_URLENCODED:{o="";let u=!0;for(let d in s.postdata)if(s.postdata.hasOwnProperty(d)){u?u=!1:o+="&";let p=encodeURIComponent(d),m=encodeURIComponent(s.postdata[d]);o+=`${p}=${m}`}break}default:case nt.ContentType.JSON:f==null&&(s.headers["Content-Type"]=nt.ContentType.JSON),o=JSON.stringify(s.postdata);break}}else o=s.postdata;if(s.cache===!1){let f=Tt();r=new jl(e),r.query?r.query=`${r.query}&ts=${f}`:r.query=`ts=${f}`,e=r.toString()}s.query&&(r=new jl(e),a=Wl(r.getQuery(),s.query),r.setQuery(a),e=r.toString());let h=new XMLHttpRequest;h.open(t,e,s.async),h.withCredentials=s.withCredentials!==void 0?s.withCredentials:!1,h.responseType=s.responseType||this._guessResponseType(e);for(let f in s.headers)s.headers.hasOwnProperty(f)&&h.setRequestHeader(f,s.headers[f]);h.onreadystatechange=()=>{this._onReadyStateChange(t,e,s,h)},h.onerror=()=>{this._onError(t,e,s,h),l=!0};try{h.send(o)}catch(f){l||s.error(h.status,h,f)}return h}_guessResponseType(t){let e=new jl(t),s=xe.getExtension(e.path).toLowerCase();return nt.binaryExtensions.indexOf(s)>=0?nt.ResponseType.ARRAY_BUFFER:s===".json"?nt.ResponseType.JSON:s===".xml"?nt.ResponseType.DOCUMENT:nt.ResponseType.TEXT}_isBinaryContentType(t){return[nt.ContentType.BASIS,nt.ContentType.BIN,nt.ContentType.DDS,nt.ContentType.GLB,nt.ContentType.MP3,nt.ContentType.MP4,nt.ContentType.OGG,nt.ContentType.OPUS,nt.ContentType.WAV].indexOf(t)>=0}_isBinaryResponseType(t){return t===nt.ResponseType.ARRAY_BUFFER||t===nt.ResponseType.BLOB||t===nt.ResponseType.JSON}_onReadyStateChange(t,e,s,i){if(i.readyState===4)switch(i.status){case 0:{i.responseURL&&i.responseURL.startsWith("file:///")?this._onSuccess(t,e,s,i):this._onError(t,e,s,i);break}case 200:case 201:case 206:case 304:{this._onSuccess(t,e,s,i);break}default:{this._onError(t,e,s,i);break}}}_onSuccess(t,e,s,i){let r,a,o=i.getResponseHeader("Content-Type");o&&(a=o.split(";")[0].trim());try{this._isBinaryContentType(a)||this._isBinaryResponseType(i.responseType)?r=i.response:a===nt.ContentType.JSON||e.split("?")[0].endsWith(".json")?r=JSON.parse(i.responseText):i.responseType===nt.ResponseType.DOCUMENT||a===nt.ContentType.XML?r=i.responseXML:r=i.responseText,s.callback(null,r)}catch(l){s.callback(l)}}_onError(t,e,s,i){if(!s.retrying)if(s.retry&&s.retries{s.retrying=!1,this.request(t,e,s,s.callback)},r)}else s.callback(i.status===0?"Network error":i.status,null)}};n(nt,"ContentType",{AAC:"audio/aac",BASIS:"image/basis",BIN:"application/octet-stream",DDS:"image/dds",FORM_URLENCODED:"application/x-www-form-urlencoded",GIF:"image/gif",GLB:"model/gltf-binary",JPEG:"image/jpeg",JSON:"application/json",MP3:"audio/mpeg",MP4:"audio/mp4",OGG:"audio/ogg",OPUS:'audio/ogg; codecs="opus"',PNG:"image/png",TEXT:"text/plain",WAV:"audio/x-wav",XML:"application/xml"}),n(nt,"ResponseType",{TEXT:"text",ARRAY_BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json"}),n(nt,"binaryExtensions",[".model",".wav",".ogg",".mp3",".mp4",".m4a",".aac",".dds",".basis",".glb",".opus"]),n(nt,"retryDelay",100);var Vt=nt,Le=new Vt;var ep="linear",uX="inverse",dX="exponential";var aT=class{constructor(t){n(this,"_manager");n(this,"position",new x);n(this,"orientation",new W);this._manager=t}getPosition(){return this.position}setPosition(t){this.position.copy(t);let e=this.listener;e&&("positionX"in e?(e.positionX.value=t.x,e.positionY.value=t.y,e.positionZ.value=t.z):e.setPosition&&e.setPosition(t.x,t.y,t.z))}setOrientation(t){this.orientation.copy(t);let e=this.listener;if(e){let s=t.data;"forwardX"in e?(e.forwardX.value=-s[8],e.forwardY.value=-s[9],e.forwardZ.value=-s[10],e.upX.value=s[4],e.upY.value=s[5],e.upZ.value=s[6]):e.setOrientation&&e.setOrientation(-s[8],-s[9],-s[10],s[4],s[5],s[6])}}getOrientation(){return this.orientation}get listener(){let t=this._manager.context;return t?t.listener:null}};var oT="running",cL=["click","touchstart","mousedown"],tp=class extends J{constructor(){super();n(this,"_context",null);n(this,"_unlockHandlerFunc");n(this,"_userSuspended",!1);n(this,"listener");n(this,"_volume",1);this._unlockHandlerFunc=this._unlockHandler.bind(this),this.listener=new aT(this)}set volume(e){e=R.clamp(e,0,1),this._volume=e,this.fire("volumechange",e)}get volume(){return this._volume}get suspended(){return this._userSuspended}get context(){if(!this._context){let e=typeof AudioContext<"u"&&AudioContext||typeof webkitAudioContext<"u"&&webkitAudioContext;if(!e)return null;this._context=new e,this._context.state!==oT&&this._registerUnlockListeners()}return this._context}suspend(){this._userSuspended||(this._userSuspended=!0,this._context&&this._context.state===oT&&this._suspend())}resume(){this._userSuspended&&(this._userSuspended=!1,this._context&&this._context.state!==oT&&this._resume())}destroy(){this.fire("destroy");let e=this._context;e&&(this._removeUnlockListeners(),e.close(),this._context=null)}_resume(){let e=this._context;e&&e.resume().then(()=>{let s=e.createBufferSource();s.buffer=e.createBuffer(1,1,e.sampleRate),s.connect(e.destination),s.start(0),s.onended=i=>{s.disconnect(0),this.fire("resume")}},s=>{}).catch(s=>{})}_suspend(){let e=this._context;e&&e.suspend().then(()=>{this.fire("suspend")},s=>{}).catch(s=>{})}_unlockHandler(){this._removeUnlockListeners(),!this._userSuspended&&this._context&&this._context.state!==oT&&this._resume()}_registerUnlockListeners(){cL.forEach(e=>{window.addEventListener(e,this._unlockHandlerFunc,!1)})}_removeUnlockListeners(){cL.forEach(e=>{window.removeEventListener(e,this._unlockHandlerFunc,!1)})}};var sp=class{constructor(t){n(this,"buffer");this.buffer=t}get duration(){return this.buffer&&this.buffer.duration||0}};var Ga=0,nT=1,wf=2;function gc(c,t){return c%t||0}var _r=class extends J{constructor(e,s,i){super();n(this,"source",null);this._manager=e,this._volume=i.volume!==void 0?R.clamp(Number(i.volume)||0,0,1):1,this._pitch=i.pitch!==void 0?Math.max(.01,Number(i.pitch)||0):1,this._loop=!!(i.loop!==void 0&&i.loop),this._sound=s,this._state=wf,this._suspended=!1,this._suspendEndEvent=0,this._suspendInstanceEvents=!1,this._playWhenLoaded=!0,this._startTime=Math.max(0,Number(i.startTime)||0),this._duration=Math.max(0,Number(i.duration)||0),this._startOffset=null,this._onPlayCallback=i.onPlay,this._onPauseCallback=i.onPause,this._onResumeCallback=i.onResume,this._onStopCallback=i.onStop,this._onEndCallback=i.onEnd,this._startedAt=0,this._currentTime=0,this._currentOffset=0,this._inputNode=null,this._connectorNode=null,this._firstNode=null,this._lastNode=null,this._waitingContextSuspension=!1,this._manager.context&&(this._initializeNodes(),this._endedHandler=this._onEnded.bind(this))}set currentTime(e){if(!(e<0))if(this._state===Ga){let s=this._suspendInstanceEvents;this._suspendInstanceEvents=!0,this.stop(),this._startOffset=e,this.play(),this._suspendInstanceEvents=s}else this._startOffset=e,this._currentTime=e}get currentTime(){return this._startOffset!==null?this._startOffset:this._state===nT?this._currentTime:this._state===wf||!this.source?0:(this._updateCurrentTime(),this._currentTime)}set duration(e){this._duration=Math.max(0,Number(e)||0);let s=this._state===Ga;this.stop(),s&&this.play()}get duration(){return this._sound?this._duration?gc(this._duration,this._sound.duration):this._sound.duration:0}get isPaused(){return this._state===nT}get isPlaying(){return this._state===Ga}get isStopped(){return this._state===wf}get isSuspended(){return this._suspended}set loop(e){this._loop=!!e,this.source&&(this.source.loop=this._loop)}get loop(){return this._loop}set pitch(e){this._manager.context&&(this._currentOffset=this.currentTime,this._startedAt=this._manager.context.currentTime),this._pitch=Math.max(Number(e)||0,.01),this.source&&(this.source.playbackRate.value=this._pitch)}get pitch(){return this._pitch}set sound(e){this._sound=e,this._state!==wf?this.stop():this._createSource()}get sound(){return this._sound}set startTime(e){this._startTime=Math.max(0,Number(e)||0);let s=this._state===Ga;this.stop(),s&&this.play()}get startTime(){return this._startTime}set volume(e){e=R.clamp(e,0,1),this._volume=e,this.gain&&(this.gain.gain.value=e*this._manager.volume)}get volume(){return this._volume}_onPlay(){this.fire("play"),this._onPlayCallback&&this._onPlayCallback(this)}_onPause(){this.fire("pause"),this._onPauseCallback&&this._onPauseCallback(this)}_onResume(){this.fire("resume"),this._onResumeCallback&&this._onResumeCallback(this)}_onStop(){this.fire("stop"),this._onStopCallback&&this._onStopCallback(this)}_onEnded(){if(this._suspendEndEvent>0){this._suspendEndEvent--;return}this.fire("end"),this._onEndCallback&&this._onEndCallback(this),this.stop()}_onManagerVolumeChange(){this.volume=this._volume}_onManagerSuspend(){this._state===Ga&&!this._suspended&&(this._suspended=!0,this.pause())}_onManagerResume(){this._suspended&&(this._suspended=!1,this.resume())}_initializeNodes(){this.gain=this._manager.context.createGain(),this._inputNode=this.gain,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination)}play(){return!this._manager.context||(this._state!==wf&&this.stop(),this._state=Ga,this._playWhenLoaded=!1,this._waitingContextSuspension)?!1:this._manager.suspended?(this._manager.once("resume",this._playAudioImmediate,this),this._waitingContextSuspension=!0,!1):(this._playAudioImmediate(),!0)}_playAudioImmediate(){if(this._waitingContextSuspension=!1,this._state!==Ga)return;this.source||this._createSource();let e=gc(this._startOffset,this.duration);e=gc(this._startTime+e,this._sound.duration),this._startOffset=null,this._duration?this.source.start(0,e,this._duration):this.source.start(0,e),this._startedAt=this._manager.context.currentTime,this._currentTime=0,this._currentOffset=e,this.volume=this._volume,this.loop=this._loop,this.pitch=this._pitch,this._manager.on("volumechange",this._onManagerVolumeChange,this),this._manager.on("suspend",this._onManagerSuspend,this),this._manager.on("resume",this._onManagerResume,this),this._manager.on("destroy",this._onManagerDestroy,this),this._suspendInstanceEvents||this._onPlay()}pause(){return this._playWhenLoaded=!1,this._state!==Ga?!1:(this._state=nT,this._waitingContextSuspension||(this._updateCurrentTime(),this._suspendEndEvent++,this.source.stop(0),this.source=null,this._startOffset=null,this._suspendInstanceEvents||this._onPause()),!0)}resume(){if(this._state!==nT)return!1;let e=this.currentTime;return this._state=Ga,this._waitingContextSuspension||(this.source||this._createSource(),this._startOffset!==null&&(e=gc(this._startOffset,this.duration),e=gc(this._startTime+e,this._sound.duration),this._startOffset=null),this._duration?this.source.start(0,e,this._duration):this.source.start(0,e),this._startedAt=this._manager.context.currentTime,this._currentOffset=e,this.volume=this._volume,this.loop=this._loop,this.pitch=this._pitch,this._playWhenLoaded=!1,this._suspendInstanceEvents||this._onResume()),!0}stop(){if(this._playWhenLoaded=!1,this._state===wf)return!1;let e=this._state===Ga;return this._state=wf,this._waitingContextSuspension||(this._manager.off("volumechange",this._onManagerVolumeChange,this),this._manager.off("suspend",this._onManagerSuspend,this),this._manager.off("resume",this._onManagerResume,this),this._manager.off("destroy",this._onManagerDestroy,this),this._startedAt=0,this._currentTime=0,this._currentOffset=0,this._startOffset=null,this._suspendEndEvent++,e&&this.source&&this.source.stop(0),this.source=null,this._suspendInstanceEvents||this._onStop()),!0}setExternalNodes(e,s){if(!e||!this._connectorNode)return;s||(s=e);let i=this._manager.context.destination;this._firstNode!==e&&(this._firstNode?this._connectorNode.disconnect(this._firstNode):this._connectorNode.disconnect(i),this._firstNode=e,this._connectorNode.connect(e)),this._lastNode!==s&&(this._lastNode&&this._lastNode.disconnect(i),this._lastNode=s,this._lastNode.connect(i))}clearExternalNodes(){if(!this._connectorNode)return;let e=this._manager.context.destination;this._firstNode&&(this._connectorNode.disconnect(this._firstNode),this._firstNode=null),this._lastNode&&(this._lastNode.disconnect(e),this._lastNode=null),this._connectorNode.connect(e)}getExternalNodes(){return[this._firstNode,this._lastNode]}_createSource(){if(!this._sound)return null;let e=this._manager.context;return e?(this._sound.buffer&&(this.source=e.createBufferSource(),this.source.buffer=this._sound.buffer,this.source.connect(this._inputNode),this.source.onended=this._endedHandler,this.source.loopStart=gc(this._startTime,this.source.buffer.duration),this._duration&&(this.source.loopEnd=Math.max(this.source.loopStart,gc(this._startTime+this._duration,this.source.buffer.duration)))),this.source):null}_updateCurrentTime(){this._currentTime=gc((this._manager.context.currentTime-this._startedAt)*this._pitch+this._currentOffset,this.duration)}_onManagerDestroy(){this.source&&this._state===Ga&&(this.source.stop(0),this.source=null)}};n(_r,"EVENT_PLAY","play"),n(_r,"EVENT_PAUSE","pause"),n(_r,"EVENT_RESUME","resume"),n(_r,"EVENT_STOP","stop"),n(_r,"EVENT_END","end");var pX=1e4,ip=class extends _r{constructor(e,s,i={}){super(e,s,i);n(this,"_position",new x);n(this,"_velocity",new x);e.context&&(i.position&&(this.position=i.position),this.maxDistance=i.maxDistance!==void 0?Number(i.maxDistance):pX,this.refDistance=i.refDistance!==void 0?Number(i.refDistance):1,this.rollOffFactor=i.rollOffFactor!==void 0?Number(i.rollOffFactor):1,this.distanceModel=i.distanceModel!==void 0?i.distanceModel:ep)}_initializeNodes(){this.gain=this._manager.context.createGain(),this.panner=this._manager.context.createPanner(),this.panner.connect(this.gain),this._inputNode=this.panner,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination)}set position(e){this._position.copy(e);let s=this.panner;s&&("positionX"in s?(s.positionX.value=e.x,s.positionY.value=e.y,s.positionZ.value=e.z):s.setPosition&&s.setPosition(e.x,e.y,e.z))}get position(){return this._position}set velocity(e){this._velocity.copy(e)}get velocity(){return this._velocity}set maxDistance(e){this.panner&&(this.panner.maxDistance=e)}get maxDistance(){return this.panner?this.panner.maxDistance:0}set refDistance(e){this.panner&&(this.panner.refDistance=e)}get refDistance(){return this.panner?this.panner.refDistance:0}set rollOffFactor(e){this.panner&&(this.panner.rolloffFactor=e)}get rollOffFactor(){return this.panner?this.panner.rolloffFactor:0}set distanceModel(e){this.panner&&(this.panner.distanceModel=e)}get distanceModel(){return this.panner?this.panner.distanceModel:ep}};var rp=0,ea=1,ls=2,wt=3,Ms=4,ap=5,op=6,np=7,lp=8,cp=9,hp=10,Wg={[rp]:"SUBTRACTIVE",[ea]:"ADDITIVE",[ls]:"NORMAL",[wt]:"NONE",[Ms]:"PREMULTIPLIED",[ap]:"MULTIPLICATIVE",[op]:"ADDITIVEALPHA",[np]:"MULTIPLICATIVE2X",[lp]:"SCREEN",[cp]:"MIN",[hp]:"MAX"},Mi="none",rw="linear",mX="exp",_X="exp2",hL=0,Sc=2,aw={[hL]:"NONE",[Sc]:"SCHLICK"},ow=0,gX=1,Xg=15,Os=0,Zt=1,$n=2,Zn=3,Va=4,Ce=0,We=1,SX=We,je=2,xX=3,lT={[Ce]:"DIRECTIONAL",[We]:"OMNI",[je]:"SPOT"},If=100,$i=0,cT=1,hT=2,fT=3,nw={[$i]:"PUNCTUAL",[cT]:"RECT",[hT]:"DISK",[fT]:"SPHERE"},uT=0,dT=1,lw={[uT]:"LINEAR",[dT]:"INVERSESQUARED"},Oi=0,vX=0,Yg=2,TX=2,fp=3,yX=3,fL=4,EX=4,pT=5,AX=5,xc=6,mT=7,_T=8,uL=9,Fi=new Map([[pT,{name:"PCF1_32F",kind:"PCF1",format:Ys,pcf:!0}],[Oi,{name:"PCF3_32F",kind:"PCF3",format:Ys,pcf:!0}],[fL,{name:"PCF5_32F",kind:"PCF5",format:Ys,pcf:!0}],[mT,{name:"PCF1_16F",kind:"PCF1",format:Xr,pcf:!0}],[_T,{name:"PCF3_16F",kind:"PCF3",format:Xr,pcf:!0}],[uL,{name:"PCF5_16F",kind:"PCF5",format:Xr,pcf:!0}],[Yg,{name:"VSM_16F",kind:"VSM",format:Me,vsm:!0}],[fp,{name:"VSM_32F",kind:"VSM",format:ke,vsm:!0}],[xc,{name:"PCSS_32F",kind:"PCSS",format:Mt,pcss:!0}]]),CX=1,PX=2,wX=4,IX=8,cw=255,RX=0,Kg=1,up=0,bX=1,DX=2,LX=3,jg=0,MX=1,Ni=0,hw=1,vc=0,fw=1,OX=2,ts=0,ni=1,Oo=0,Fo=1,dp=2,pp=0,gT=1,uw={[pp]:"NONE",[gT]:"BOX"},ST="mul",FX="add",NX="screen",BX="overlay",UX="min",kX="max",Zi=0,No=1,qg={[Zi]:"NONE",[No]:"SRGB"},Qn=0,zX=1,GX=2,VX=3,HX=4,WX=5,Rf=6,bf=["LINEAR","FILMIC","HEJL","ACES","ACES2","NEUTRAL","NONE"],xT=0,Bo=1,vT=2,dw={[xT]:"NONE",[Bo]:"AO",[vT]:"GLOSSDEPENDENT"},gr="none",Df="envAtlas",Lf="envAtlasHQ",Mf="cubeMap",TT="sphereMap",pw={[gr]:"NONE",[Df]:"ENVATLAS",[Lf]:"ENVATLASHQ",[Mf]:"CUBEMAP",[TT]:"SPHEREMAP"},mp="ambientSH",_p="envAtlas",gp="constant",mw={[mp]:"AMBIENTSH",[_p]:"ENVALATLAS",[gp]:"CONSTANT"},Tc=1,Uo=2,Of=4,$g=8,Zg=16,ko=32,yc=64,Ff=128,Ec=256,Nf=512,zo=1024,Go=2048,Bf=4096,Vo=8192,Uf=16384,$s=0,Qi=1,Qg=2,cs=1,xi=2,vi=4,Sr=0,xr=1,kf=2,ta=3,Sp=4,XX="forward",YX="debug_albedo",KX="debug_world_normal",jX="debug_opacity",qX="debug_specularity",$X="debug_gloss",ZX="debug_metalness",QX="debug_ao",JX="debug_emission",eY="debug_lighting",tY="debug_uv0",Ti=0,It=1,Rt=2,_w={[Ti]:"SIMPLE",[It]:"SLICED",[Rt]:"TILED"},sY=0,zf=1,xp=0,iY=1,rY=2,Ho=0,gw=1,yT=2,Jg=3,Sw=4,xw=5,Ac=0,vp=1,Ge=0,dt=1,Jn="infinite",vw="box",Tw="dome",Bi="none",dL="bayer8",pL="bluenoise",mL="ignnoise",eS={[Bi]:"NONE",[dL]:"BAYER8",[pL]:"BLUENOISE",[mL]:"IGNNOISE"},yw="prerender",Ew="postrender",Aw="prerender:layer",Cw="postrender:layer",tS="precull",sS="postcull",Pw="cull:end",Fs=1,el=2,Gf="pcShadowCamera",Tp=0,ww=1,Iw=2,Rw=0,Vf=1,aY="large",iS="compact",ET=0,tl=1,Cc=2,Hf=3,Wf=0,Pc=1,yp=2,Ep=3,AT=4,CT=5,PT=0,bw=1,wT=2;var sa=class{constructor(t,e,s){n(this,"uniformFormats",[]);n(this,"bindGroupFormats",[]);n(this,"vertexFormat");this.uniformFormats[Io]=t,this.bindGroupFormats[Io]=e,this.vertexFormat=s}hasUniform(t){for(let e=0;ee.name===t)}generateKey(t){let e=JSON.stringify(this.uniformFormats)+JSON.stringify(this.bindGroupFormats);return t.isWebGPU&&(e+=this.vertexFormat?.shaderProcessingHashString),e}};var _L=new et;function Ji(c){return _L.get(c)}function gL(c,t){_L.get(c,()=>t)}var yi=class{static definesHash(t){let e=Array.from(t).sort((s,i)=>s[0]>i[0]?1:-1);return xt(JSON.stringify(e))}};var oY=new et,Dw=class{constructor(t,e,s={}){n(this,"index");n(this,"name");n(this,"defines",new Map);this.name=t,this.index=e,Object.assign(this,s),this.buildShaderDefines()}buildShaderDefines(){let t;this.isShadow?t="SHADOW":this.isForward?t="FORWARD":this.index===ta?t="PICK":this.index===Sp&&(t="PICK",this.defines.set("DEPTH_PICK_PASS","")),this.defines.set(`${t}_PASS`,""),this.defines.set(`${this.name.toUpperCase()}_PASS`,"")}},Ns=class c{constructor(){n(this,"passesNamed",new Map);n(this,"passesIndexed",[]);n(this,"nextIndex",0);let t=(e,s,i)=>{let r=this.allocate(e,i)};t("forward",Sr,{isForward:!0}),t("prepass",xr),t("shadow",kf),t("pick",ta),t("depth_pick",Sp)}static get(t){return oY.get(t,()=>new c)}allocate(t,e){let s=this.passesNamed.get(t);return s===void 0&&(s=new Dw(t,this.nextIndex,e),this.passesNamed.set(s.name,s),this.passesIndexed[s.index]=s,this.nextIndex++),s}getByIndex(t){return this.passesIndexed[t]}getByName(t){return this.passesNamed.get(t)}};var rS=class extends Map{constructor(e){super();n(this,"_validations");n(this,"_keyDirty",!1);n(this,"_key","");this._validations=e}set(e,s){return(!this.has(e)||this.get(e)!==s)&&this.markDirty(),super.set(e,s)}add(e,s=!0){for(let[i,r]of Object.entries(e))(s||!this.has(i))&&this.set(i,r);return this}delete(e){let s=this.has(e),i=super.delete(e);return s&&i&&this.markDirty(),i}clear(){this.size>0&&this.markDirty(),super.clear()}markDirty(){this._dirty=!0,this._keyDirty=!0}isDirty(){return this._dirty}resetDirty(){this._dirty=!1}get key(){return this._keyDirty&&(this._keyDirty=!1,this._key=Array.from(this.entries()).sort(([e],[s])=>es?1:0).map(([e,s])=>`${e}=${xt(s)}`).join(",")),this._key}copy(e){for(let s of this.keys())e.has(s)||this.delete(s);for(let[s,i]of e)this.set(s,i);return this}};var nY=new et,Ap=class Ap{constructor(){n(this,"glsl",new rS(Ap._validations));n(this,"wgsl",new rS(Ap._validations));n(this,"version","")}static get(t,e=fe){let s=nY.get(t,()=>new Ap);return e===fe?s.glsl:s.wgsl}static registerValidation(t,e){}get useWGSL(){return this.glsl.size===0||this.wgsl.size>0}get key(){return`GLSL:${this.glsl.key}|WGSL:${this.wgsl.key}|API:${this.version}`}isDirty(){return this.glsl.isDirty()||this.wgsl.isDirty()}resetDirty(){this.glsl.resetDirty(),this.wgsl.resetDirty()}copy(t){return this.version=t.version,this.glsl.copy(t.glsl),this.wgsl.copy(t.wgsl),this}};n(Ap,"_validations",new Map);var ne=Ap;var Ha=class{static merge(...t){let e=new Map(t[0]??[]);for(let s=1;ss.set(a,r)),Ns.get(e.device).getByIndex(e.pass).defines.forEach((r,a)=>s.set(a,r)),s}static processShader(t,e){let s=t.definition,r=`${s.name??"shader"}-id-${t.id}`,a=new Lw(r,s),o="shader",l=Ji(t.device);l.register(o,a);let h=l.getProgram(o,{},e);return l.unregister(o),h}static addScreenDepthChunkDefines(t,e,s){e.sceneDepthMapLinear&&s.set("SCENE_DEPTHMAP_LINEAR",""),t.textureFloatRenderable&&s.set("SCENE_DEPTHMAP_FLOAT","")}};function SL(c,t,e,s=!1,i={}){}function xL(c,t,e,s,i,r=!1,a={}){typeof r=="boolean"?a.useTransformFeedback=r:typeof r=="object"&&(a={...a,...r});let o=Ji(c),l=o.getCachedShader(s);return l||(l=new Be(c,ns.createDefinition(c,{...a,name:s,vertexCode:t,fragmentCode:e,attributes:i})),o.setCachedShader(s,l)),l}var lY={type:Yt,base:0,count:6,indexed:!0},aS=new Q,oS=new Q,Mw=new hc,hs=class{constructor(t){n(this,"uniformBuffer");n(this,"bindGroup");let e=t.device;if(this.shader=t,e.supportsUniformBuffers){let s=new sa;this.shader=Se.processShader(t,s);let i=this.shader.meshUniformBufferFormat;i&&(this.uniformBuffer=new Qr(e,i,!1));let r=this.shader.meshBindGroupFormat;this.bindGroup=new ji(e,r)}}destroy(){this.uniformBuffer?.destroy(),this.uniformBuffer=null,this.bindGroup?.destroy(),this.bindGroup=null}render(t,e,s){let i=this.shader.device;t&&(aS.set(i.vx,i.vy,i.vw,i.vh),oS.set(i.sx,i.sy,i.sw,i.sh),e=e??t,i.setViewport(t.x,t.y,t.z,t.w),i.setScissor(e.x,e.y,e.z,e.w)),i.setVertexBuffer(i.quadVertexBuffer);let r=this.shader;if(i.setShader(r),i.supportsUniformBuffers){i.setBindGroup(Io,i.emptyBindGroup);let a=this.bindGroup;a.update(),i.setBindGroup(Ua,a);let o=this.uniformBuffer;o?(o.update(Mw),i.setBindGroup($r,Mw.bindGroup,Mw.offsets)):i.setBindGroup($r,i.emptyBindGroup)}i.draw(lY,i.quadIndexBuffer,s),t&&(i.setViewport(aS.x,aS.y,aS.z,aS.w),i.setScissor(oS.x,oS.y,oS.z,oS.w))}};var Cp=class extends yt{constructor(t,e,s,i){super(t),this.quad=e,this.rect=s,this.scissorRect=i}execute(){let{device:t}=this;t.setDrawStates(t.blendState),this.quad.render(this.rect,this.scissorRect)}};var cY=new Q;function Qt(c,t,e,s,i){let r=arguments[5],a=new hs(e);s||(s=cY,s.x=0,s.y=0,s.z=t?t.width:c.width,s.w=t?t.height:c.height);let o=new Cp(c,a,s,i);o.init(t),o.colorOps.clear=!1,o.depthStencilOps.clearDepth=!1,c.isWebGPU&&t===null&&c.samples>1&&(o.colorOps.store=!0),o.render(),a.destroy()}var Xf=class{constructor(t,e,s){n(this,"_aabb",new ge);n(this,"origMeshInstances");n(this,"meshInstance",null);n(this,"dynamic");n(this,"batchGroupId");this.origMeshInstances=t,this.dynamic=e,this.batchGroupId=s}destroy(t,e){this.meshInstance&&(this.removeFromLayers(t,e),this.meshInstance.destroy(),this.meshInstance=null)}addToLayers(t,e){for(let s=0;s=0;s--)this.matrices[s].mulAffine2(vL,this.bones[s].getWorldTransform()),this.matrices[s].mulAffine2(this.matrices[s],this.skin.inverseBindPose[s])}}updateMatrices(t,e){this._updateBeforeCull&&this._updateMatrices(t,e)}updateMatrixPalette(t,e){this._updateMatrices(t,e);let s=this.matrixPalette,i=this.bones.length;for(let r=0;r0){let A=T.array[T.index+y];if(f[A]=!0,s=S.array[S.index],i=S.array[S.index+1],r=S.array[S.index+2],a=h[A],o=l[A],o.x>s&&(o.x=s),o.y>i&&(o.y=i),o.z>r&&(o.z=r),a.xw&&(o.x=w),o.y>I&&(o.y=I),o.z>D&&(o.z=D),a.xE.name===ee);if(v&&v.normalize){let E=(()=>{switch(v.dataType){case js:return y=>Math.max(y/127,-1);case ai:return y=>y/255;case qs:return y=>Math.max(y/32767,-1);case Ri:return y=>y/65535;default:return y=>y}})();for(let y=0;y0&&this.indexBuffer[0]&&(this._geometryData.indexCount=this.indexBuffer[0].numIndices,this._geometryData.maxIndices=this.indexBuffer[0].numIndices))}clear(e,s,i=0,r=0){this._initGeometryData(),this._geometryData.initDefaults(),this._geometryData.recreate=!0,this._geometryData.maxVertices=i,this._geometryData.maxIndices=r,this._geometryData.verticesUsage=e?0:1,this._geometryData.indicesUsage=s?0:1}setVertexStream(e,s,i,r,a=ye,o=!1,l=!1){this._initGeometryData();let h=r||s.length/i;this._geometryData._changeVertexCount(h,e),this._geometryData.vertexStreamsUpdated=!0,this._geometryData.vertexStreamDictionary[e]=new Ow(s,i,a,o,l)}getVertexStream(e,s){let i=0,r=!1;if(this._geometryData){let a=this._geometryData.vertexStreamDictionary[e];a&&(r=!0,i=this._geometryData.vertexCount,ArrayBuffer.isView(s)?s.set(a.data):(s.length=0,s.push(a.data)))}return r||this.vertexBuffer&&(i=new Jr(this.vertexBuffer).readData(e,s)),i}setPositions(e,s=ia.DEFAULT_COMPONENTS_POSITION,i){this.setVertexStream(ee,e,s,i,ye,!1)}setNormals(e,s=ia.DEFAULT_COMPONENTS_NORMAL,i){this.setVertexStream(Ot,e,s,i,ye,!1)}setUvs(e,s,i=ia.DEFAULT_COMPONENTS_UV,r){this.setVertexStream(Ux+e,s,i,r,ye,!1)}setColors(e,s=ia.DEFAULT_COMPONENTS_COLORS,i){this.setVertexStream(Ct,e,s,i,ye,!1)}setColors32(e,s){this.setVertexStream(Ct,e,ia.DEFAULT_COMPONENTS_COLORS,s,ai,!0)}setIndices(e,s){this._initGeometryData(),this._geometryData.indexStreamUpdated=!0,this._geometryData.indices=e,this._geometryData.indexCount=s||e.length}getPositions(e){return this.getVertexStream(ee,e)}getNormals(e){return this.getVertexStream(Ot,e)}getUvs(e,s){return this.getVertexStream(Ux+e,s)}getColors(e){return this.getVertexStream(Ct,e)}getIndices(e){let s=0;if(this._geometryData&&this._geometryData.indices){let i=this._geometryData.indices;if(s=this._geometryData.indexCount,ArrayBuffer.isView(e))e.set(i);else{e.length=0;for(let r=0,a=i.length;r0&&this.indexBuffer[0]&&(s=this.indexBuffer[0].readData(e));return s}update(e=Yt,s=!0){if(this._geometryData){if(s){let a=this._geometryData.vertexStreamDictionary[ee];a&&a.componentCount===3&&(this._aabb.compute(a.data,this._geometryData.vertexCount),this._aabbVer++)}let i=this._geometryData.recreate;this._geometryData.vertexCount>this._geometryData.maxVertices&&(i=!0,this._geometryData.maxVertices=this._geometryData.vertexCount),i&&this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=null);let r=this._geometryData.recreate;this._geometryData.indexCount>this._geometryData.maxIndices&&(r=!0,this._geometryData.maxIndices=this._geometryData.indexCount),r&&this.indexBuffer.length>0&&this.indexBuffer[0]&&(this.indexBuffer[0].destroy(),this.indexBuffer[0]=null),this._geometryData.vertexStreamsUpdated&&this._updateVertexBuffer(),this._geometryData.indexStreamUpdated&&this._updateIndexBuffer(),this.primitive[0].type=e,this.indexBuffer.length>0&&this.indexBuffer[0]?this._geometryData.indexStreamUpdated&&(this.primitive[0].count=this._geometryData.indexCount,this.primitive[0].indexed=!0):this._geometryData.vertexStreamsUpdated&&(this.primitive[0].count=this._geometryData.vertexCount,this.primitive[0].indexed=!1),this._geometryData.vertexCount=0,this._geometryData.indexCount=0,this._geometryData.vertexStreamsUpdated=!1,this._geometryData.indexStreamUpdated=!1,this._geometryData.recreate=!1,this.updateRenderStates()}}_buildVertexFormat(e){let s=[];for(let i in this._geometryData.vertexStreamDictionary){let r=this._geometryData.vertexStreamDictionary[i];s.push({semantic:i,components:r.componentCount,type:r.dataType,normalize:r.dataTypeNormalize,asInt:r.asInt})}return new Ft(this.device,s,e)}_updateVertexBuffer(){if(!this.vertexBuffer){let i=this._geometryData.maxVertices,r=this._buildVertexFormat(i);this.vertexBuffer=new ft(this.device,r,i,{usage:this._geometryData.verticesUsage,storage:this._storageVertex})}let e=new Jr(this.vertexBuffer),s=this._geometryData.vertexCount;for(let i in this._geometryData.vertexStreamDictionary){let r=this._geometryData.vertexStreamDictionary[i];e.writeData(i,r.data,s),delete this._geometryData.vertexStreamDictionary[i]}e.end()}_updateIndexBuffer(){if(this.indexBuffer.length<=0||!this.indexBuffer[0]){let s=this._geometryData.maxVertices,i=s>65535||s===0?2:1,r=this._storageIndex?{storage:!0}:void 0;this.indexBuffer[0]=new os(this.device,i,this._geometryData.maxIndices,this._geometryData.indicesUsage,void 0,r)}let e=this._geometryData.indices;e&&(this.indexBuffer[0].writeData(e,this._geometryData.indexCount),this._geometryData.indices=null)}prepareRenderState(e){e===Fo?this.generateWireframe():e===dp&&(this.primitive[dp]={type:Aa,base:0,baseVertex:0,count:this.vertexBuffer?this.vertexBuffer.numVertices:0,indexed:!1})}updateRenderStates(){this.primitive[dp]&&this.prepareRenderState(dp),this.primitive[Fo]&&this.prepareRenderState(Fo)}generateWireframe(){this._destroyIndexBuffer(Fo);let e=this.vertexBuffer.numVertices,s,i;if(this.indexBuffer.length>0&&this.indexBuffer[0]){let a=[[0,1],[1,2],[2,0]],o=this.primitive[Oo].base,l=this.primitive[Oo].count,h=this.primitive[Oo].baseVertex||0,f=this.indexBuffer[Oo],u=Ef[f.format],d=new u(f.storage),p=new u(l*2),m=new Set,_=0;for(let S=o;SC?C*e+T:T*e+C;m.has(v)||(m.add(v),p[_++]=T,p[_++]=C)}m.clear(),i=f.format,s=p.slice(0,_)}else{let a=e-e%3,o=a/3*6;i=o>65535?2:1,s=o>65535?new Uint32Array(o):new Uint16Array(o);let l=0;for(let h=0;h{let s=e[c];return s instanceof Function&&(s=s()),s===t}}function wL(c,t){if(t(c))return c;let e=c._children,s=e.length;for(let i=0;i{r(a)&&i.push(a)}),i}findOne(e,s){let i=PL(e,s);return wL(this,i)}findByTag(...e){let s=[],i=(r,a)=>{a&&r.tags.has(...e)&&s.push(r);for(let o=0;oo.name===s[r]),!i)return null;return i}forEach(e,s){e.call(s,this);let i=this._children,r=i.length;for(let a=0;a=0?e.insertChild(this,s):e.addChild(this))}setLocalEulerAngles(e,s,i){this.localRotation.setFromEulerAngles(e,s,i),this._dirtyLocal||this._dirtifyLocal()}setLocalPosition(e,s,i){e instanceof x?this.localPosition.copy(e):this.localPosition.set(e,s,i),this._dirtyLocal||this._dirtifyLocal()}setLocalRotation(e,s,i,r){e instanceof $?this.localRotation.copy(e):this.localRotation.set(e,s,i,r),this._dirtyLocal||this._dirtifyLocal()}setLocalScale(e,s,i){e instanceof x?this.localScale.copy(e):this.localScale.set(e,s,i),this._dirtyLocal||this._dirtifyLocal()}_dirtifyLocal(){this._dirtyLocal||(this._dirtyLocal=!0,this._dirtyWorld||this._dirtifyWorld())}_unfreezeParentToRoot(){let e=this._parent;for(;e;)e._frozen=!1,e=e._parent}_dirtifyWorld(){this._dirtyWorld||this._unfreezeParentToRoot(),this._dirtifyWorldInternal()}_dirtifyWorldInternal(){if(!this._dirtyWorld){this._frozen=!1,this._dirtyWorld=!0;for(let e=0;et)}var RT=class{constructor(){n(this,"cache",new Map)}destroy(){this.cache.forEach((t,e)=>{e.destroy()}),this.cache.clear()}incRef(t){let e=(this.cache.get(t)||0)+1;this.cache.set(t,e)}decRef(t){if(t){let e=this.cache.get(t);e&&(e--,e===0?(this.cache.delete(t),t.destroy()):this.cache.set(t,e))}}};var yr=class{static incRef(t){this.cache.incRef(t)}static decRef(t){this.cache.decRef(t)}static destroy(){this.cache.destroy()}};n(yr,"cache",new RT);var wp=class{constructor(){n(this,"_counter",0)}get(){return this._counter++}};var bT=new wp;var dY=new ge,DT=new ge,Uw=new Br,kw=new Set,Ip=new Uint32Array(4),LT=class{constructor(t){n(this,"vertexBuffer",null);n(this,"_destroyVertexBuffer",!1);this.count=t}destroy(){this._destroyVertexBuffer&&this.vertexBuffer?.destroy(),this.vertexBuffer=null}},zw=class{constructor(){n(this,"shader");n(this,"bindGroup",null);n(this,"uniformBuffer",null);n(this,"hashes")}getBindGroup(t){if(!this.bindGroup){let s=this.shader.meshBindGroupFormat;this.bindGroup=new ji(t,s)}return this.bindGroup}getUniformBuffer(t){if(!this.uniformBuffer){let s=this.shader.meshUniformBufferFormat;this.uniformBuffer=new Qr(t,s,!1)}return this.uniformBuffer}destroy(){this.bindGroup?.destroy(),this.bindGroup=null,this.uniformBuffer?.destroy(),this.uniformBuffer=null}},Kf=class Kf{constructor(t,e,s=null){n(this,"castShadow",!1);n(this,"shadowCascadeMask",cw);n(this,"cull",!0);n(this,"drawOrder",0);n(this,"_drawBucket",127);n(this,"node");n(this,"visible",!0);n(this,"visibleThisFrame",!1);n(this,"flipFacesFactor",1);n(this,"gsplatInstance",null);n(this,"id",bT.get());n(this,"isVisibleFunc",null);n(this,"instancingData",null);n(this,"indirectData",null);n(this,"drawCommands",null);n(this,"meshMetaData",null);n(this,"parameters",{});n(this,"pick",!0);n(this,"stencilFront",null);n(this,"stencilBack",null);n(this,"transparent",!1);n(this,"_aabb",new ge);n(this,"_aabbVer",-1);n(this,"_aabbMeshVer",-1);n(this,"_customAabb",null);n(this,"_updateAabb",!0);n(this,"_updateAabbFunc",null);n(this,"_sortKeyShadow",0);n(this,"_sortKeyForward",0);n(this,"_sortKeyDynamic",0);n(this,"_layer",Xg);n(this,"_material",null);n(this,"_skinInstance",null);n(this,"_morphInstance",null);n(this,"_receiveShadow",!0);n(this,"_renderStyle",Oo);n(this,"_screenSpace",!1);n(this,"_shaderCache",new Map);n(this,"_shaderDefs",cs<<16);n(this,"_calculateSortDistance",null);if(this.node=s,this._mesh=t,t.incRefCount(),this.material=e,t.vertexBuffer){let i=t.vertexBuffer.format;this._shaderDefs|=i.hasUv0?Of:0,this._shaderDefs|=i.hasUv1?$g:0,this._shaderDefs|=i.hasColor?Zg:0,this._shaderDefs|=i.hasTangents?Nf:0}this.updateKey()}set drawBucket(t){this._drawBucket=Math.floor(t)&255,this.updateKey()}get drawBucket(){return this._drawBucket}set renderStyle(t){this._renderStyle=t,this.mesh.prepareRenderState(t)}get renderStyle(){return this._renderStyle}set mesh(t){t!==this._mesh&&(this._mesh&&this._mesh.decRefCount(),this._mesh=t,t&&t.incRefCount())}get mesh(){return this._mesh}set aabb(t){this._aabb=t}get aabb(){if(!this._updateAabb)return this._aabb;if(this._updateAabbFunc)return this._updateAabbFunc(this._aabb);let t=this._customAabb,e=!!t;if(!t){if(t=dY,this.skinInstance){if(!this.mesh.boneAabb){let r=this._morphInstance?this._morphInstance.morph._targets:null;this.mesh._initBoneAabbs(r)}let s=this.mesh.boneUsed,i=!0;for(let r=0;r{t.destroy()}),this._shaderCache.clear()}getShaderInstance(t,e,s,i,r,a,o){let l=this._shaderDefs;Ip[0]=t,Ip[1]=e,Ip[2]=l,Ip[3]=i.hash;let h=dc(Ip),f=this._shaderCache.get(h);if(!f){let u=this._material;if(f=new zw,f.shader=u.variants.get(h),f.hashes=new Uint32Array(Ip),!f.shader){let d=u.getShaderVariant({device:this.mesh.device,scene:s,objDefs:l,cameraShaderParams:i,pass:t,sortedLights:o,viewUniformFormat:r,viewBindGroupFormat:a,vertexFormat:this.mesh.vertexBuffer?.format});u.variants.set(h,d),f.shader=d}this._shaderCache.set(h,f)}return f}set material(t){this.clearShaders();let e=this._material;e&&e.removeMeshInstanceRef(this),this._material=t,t&&(t.addMeshInstanceRef(this),this.transparent=t.transparent,this.updateKey())}get material(){return this._material}_updateShaderDefs(t){t!==this._shaderDefs&&(this._shaderDefs=t,this.clearShaders())}set calculateSortDistance(t){this._calculateSortDistance=t}get calculateSortDistance(){return this._calculateSortDistance}set receiveShadow(t){this._receiveShadow!==t&&(this._receiveShadow=t,this._updateShaderDefs(t?this._shaderDefs&~Tc:this._shaderDefs|Tc))}get receiveShadow(){return this._receiveShadow}set batching(t){this._updateShaderDefs(t?this._shaderDefs|Uf:this._shaderDefs&~Uf)}get batching(){return(this._shaderDefs&Uf)!==0}set skinInstance(t){this._skinInstance=t,this._updateShaderDefs(t?this._shaderDefs|Uo:this._shaderDefs&~Uo),this._setupSkinUpdate()}get skinInstance(){return this._skinInstance}set morphInstance(t){this._morphInstance?.destroy(),this._morphInstance=t;let e=this._shaderDefs;e=t&&t.morph.morphPositions?e|zo:e&~zo,e=t&&t.morph.morphNormals?e|Go:e&~Go,e=t&&t.morph.intRenderFormat?e|Vo:e&~Vo,this._updateShaderDefs(e)}get morphInstance(){return this._morphInstance}set screenSpace(t){this._screenSpace!==t&&(this._screenSpace=t,this._updateShaderDefs(t?this._shaderDefs|Ec:this._shaderDefs&~Ec))}get screenSpace(){return this._screenSpace}set key(t){this._sortKeyForward=t}get key(){return this._sortKeyForward}set mask(t){let e=this._shaderDefs&65535;this._updateShaderDefs(e|t<<16)}get mask(){return this._shaderDefs>>16}set instancingCount(t){this.instancingData&&(this.instancingData.count=t)}get instancingCount(){return this.instancingData?this.instancingData.count:0}destroy(){let t=this.mesh;t&&(this.mesh=null,t.refCount<1&&t.destroy()),this.setRealtimeLightmap(Kf.lightmapParamNames[0],null),this.setRealtimeLightmap(Kf.lightmapParamNames[1],null),this._skinInstance?.destroy(),this._skinInstance=null,this.morphInstance?.destroy(),this.morphInstance=null,this.clearShaders(),this.material=null,this.instancingData?.destroy(),this.destroyDrawCommands()}destroyDrawCommands(){if(this.drawCommands){for(let t of this.drawCommands.values())t?.destroy();this.drawCommands=null}}static _prepareRenderStyleForArray(t,e){if(t){for(let s=0;s0):!1}updateKey(){let{material:t}=this;this._sortKeyForward=this._drawBucket<<23|(t.alphaToCoverage||t.alphaTest?4194304:0)|t.id&4194303}setInstancing(t,e=!1){t?(t===!0?this.instancingData=new LT(0):(this.instancingData=new LT(t.numVertices),this.instancingData.vertexBuffer=t,t.format.instancing=!0),this.cull=e):(this.instancingData=null,this.cull=!0),this._updateShaderDefs(t instanceof ft?this._shaderDefs|ko:this._shaderDefs&~ko)}setIndirect(t,e,s=1){let i=t?.camera??null;if(e===-1)this._deleteDrawCommandsKey(i);else{this.drawCommands??(this.drawCommands=new Map);let r=this.drawCommands.get(i)??new Cf(this.mesh.device);r.slotIndex=e,r.update(s),this.drawCommands.set(i,r),this.mesh.device.mapsToClear.add(this.drawCommands)}}setMultiDraw(t,e=1){let s=t?.camera??null,i;if(e===0)this._deleteDrawCommandsKey(s);else{if(this.drawCommands??(this.drawCommands=new Map),i=this.drawCommands.get(s),!i){let a=this.mesh.indexBuffer?.[0]?.format,o=a!==void 0?XC[a]:0;i=new Cf(this.mesh.device,o),this.drawCommands.set(s,i)}i.allocate(e)}return i}_deleteDrawCommandsKey(t){let e=this.drawCommands;e&&(e.get(t)?.destroy(),e.delete(t),e.size===0&&this.destroyDrawCommands())}getDrawCommands(t){let e=this.drawCommands;if(e)return e.get(t)??e.get(null)}getIndirectMetaData(){let t=this.mesh?.primitive[this.renderStyle],e=this.meshMetaData??(this.meshMetaData=new Int32Array(4));return e[0]=t.count,e[1]=t.base,e[2]=t.baseVertex,e}ensureMaterial(t){this.material||(this.material=ra(t))}clearParameters(){this.parameters={}}getParameters(){return this.parameters}getParameter(t){return this.parameters[t]}setParameter(t,e,s=4294967295){let i=this.parameters[t];i?(i.data=e,i.passFlags=s):this.parameters[t]={scopeId:null,data:e,passFlags:s}}setRealtimeLightmap(t,e){let s=this.getParameter(t);s!==e&&(s&&yr.decRef(s.data),e?(yr.incRef(e),this.setParameter(t,e)):this.deleteParameter(t))}deleteParameter(t){this.parameters[t]&&delete this.parameters[t]}setParameters(t,e){let s=this.parameters;for(let i in s){let r=s[i];r.passFlags&e&&(r.scopeId||(r.scopeId=t.scope.resolve(i)),r.scopeId.setValue(r.data))}}setLightmapped(t){t?this.mask=(this.mask|xi)&~(cs|vi):(this.setRealtimeLightmap(Kf.lightmapParamNames[0],null),this.setRealtimeLightmap(Kf.lightmapParamNames[1],null),this._shaderDefs&=~(yc|Ff|Bf),this.mask=(this.mask|cs)&~(xi|vi))}setCustomAabb(t){t?this._customAabb?this._customAabb.copy(t):this._customAabb=t.clone():(this._customAabb=null,this._aabbVer=-1),this._setupSkinUpdate()}_setupSkinUpdate(){this._skinInstance&&(this._skinInstance._updateBeforeCull=!this._customAabb)}};n(Kf,"lightmapParamNames",["texture_lightMap","texture_dirLightMap"]);var we=Kf;var pY=[0,1,3,2,3,1],mY=[0,1,3,0,3,2],bL=new Ws;function DL(c,t){if(c&&!t||!c&&t)return!1;if(c=c.data,t=t.data,c===t)return!0;if(c instanceof Float32Array&&t instanceof Float32Array){if(c.length!==t.length)return!1;for(let e=0;e=0&&(i._obj[t].splice(r,1),this.markGroupDirty(e))}}_filterBatchableInstances(t,e){let s=!1,i=!1;for(let r=0;r0?(e.push(t.element._text._model.meshInstances[0]),t.element.removeModelFromLayers(t.element._text._model),i=!0):t.element._image&&(e.push(t.element._image._renderable.meshInstance),t.element.removeModelFromLayers(t.element._image._renderable.model),t.element._image._renderable.unmaskMeshInstance&&(e.push(t.element._image._renderable.unmaskMeshInstance),(!t.element._image._renderable.unmaskMeshInstance.stencilFront||!t.element._image._renderable.unmaskMeshInstance.stencilBack)&&(t.element._dirtifyMask(),t.element._onPrerender())),i=!0),i&&(s._ui=!0)}_collectAndRemoveMeshInstances(t,e){for(let s=0;sg.drawOrder-T.drawOrder);let m=t,_,S=i?function(g){f?f.add(g.aabb):f=g.aabb.clone(),_.push(g)}:function(g){_.push(g)};for(;m.length>0;){d[p]=[m[0]],_=[];let g=m[0].material,T=m[0].layer,C=m[0]._shaderDefs,v=m[0].parameters,E=m[0].stencilFront,y=m[0].mesh.vertexBuffer.getNumVertices(),P=m[0].drawOrder;l.copy(m[0].aabb);let A=Gw(m[0]),w=m[0].mesh.vertexBuffer.format.batchingHash,I=m[0].mesh.primitive[0].indexed,D=m[0].castShadow,O=m[0].shadowCascadeMask;f=null;for(let G=1;G=a){_=_.concat(m.slice(G));break}if(g!==M.material||T!==M.layer||w!==M.mesh.vertexBuffer.format.batchingHash||I!==M.mesh.primitive[0].indexed||C!==M._shaderDefs||y+M.mesh.vertexBuffer.getNumVertices()>o){S(M);continue}if(h.copy(l),h.add(M.aabb),h.halfExtents.x>r||h.halfExtents.y>r||h.halfExtents.z>r){S(M);continue}if(E&&(!(u=M.stencilFront)||E.func!==u.func||E.zpass!==u.zpass)){S(M);continue}if(A!==Gw(M)){S(M);continue}if(D!==M.castShadow||O!==M.shadowCascadeMask){S(M);continue}if(!_Y(v,M.parameters)){S(M);continue}if(i&&f&&f.intersects(M.aabb)&&M.drawOrder!==P){S(M);continue}l.add(M.aabb),y+=M.mesh.vertexBuffer.getNumVertices(),d[p].push(M)}p++,m=_}return d}collectBatchedMeshData(t,e){let s=null,i=0,r=0,a=null;for(let o=0;o=3){if(r===ee){let O=v.data,G=O[0],M=O[1],H=O[2],U=O[4],L=O[5],b=O[6],N=O[8],k=O[9],z=O[10],V=O[12],q=O[13],re=O[14],te,j,oe;for(let be=0;be0&&a.setIndices(y),a.update(Yt,!1),e&&(u=u.clone(),u.update());let P=new we(a,u,this.rootNode);P.castShadow=l.origMeshInstances[0].castShadow,P.parameters=l.origMeshInstances[0].parameters,P.layer=l.origMeshInstances[0].layer,P._shaderDefs=l.origMeshInstances[0]._shaderDefs,P.batching=!0,P.cull=l.origMeshInstances[0].cull;let A=this._batchGroups[s];if(A&&A._ui&&(P.cull=!1),e){let w=[];for(let I=0;I0&&this.generate(this._dirtyGroups);for(let t=0;t1&&(a=Mt,r=!1);let o=e.renderTarget?.depthBuffer??e.renderTarget?.colorBuffer;this.shouldReallocate(this.depthRenderTarget,o)&&(this.releaseRenderTarget(this.depthRenderTarget),this.depthRenderTarget=this.allocateRenderTarget(this.depthRenderTarget,e.renderTarget,s,a,r));let l=r?this.depthRenderTarget.depthBuffer:this.depthRenderTarget.colorBuffer;s.scope.resolve(ML).setValue(l)}execute(){let e=this.device;if(e.isWebGL2&&e.renderTarget.samples>1){let s=e.renderTarget.impl._glFrameBuffer,i=this.depthRenderTarget;e.renderTarget=i,e.updateBegin(),this.depthRenderTarget.impl.internalResolve(e,s,i.impl._glFrameBuffer,this.depthRenderTarget,e.gl.DEPTH_BUFFER_BIT)}else e.copyRenderTarget(e.renderTarget,this.depthRenderTarget,!1,!0)}};var bp=class{constructor(){n(this,"_gammaCorrection",No);n(this,"_toneMapping",Qn);n(this,"_srgbRenderTarget",!1);n(this,"_ssaoEnabled",!1);n(this,"_fog",Mi);n(this,"_sceneDepthMapLinear",!1);n(this,"_hash");n(this,"_defines",new Map);n(this,"_definesDirty",!0)}get hash(){if(this._hash===void 0){let t=`${this.gammaCorrection}_${this.toneMapping}_${this.srgbRenderTarget}_${this.fog}_${this.ssaoEnabled}_${this.sceneDepthMapLinear}`;this._hash=xt(t)}return this._hash}get defines(){let t=this._defines;return this._definesDirty&&(this._definesDirty=!1,t.clear(),this._sceneDepthMapLinear&&t.set("SCENE_DEPTHMAP_LINEAR",""),this.shaderOutputGamma===No&&t.set("SCENE_COLORMAP_GAMMA",""),t.set("FOG",this._fog.toUpperCase()),t.set("TONEMAP",bf[this._toneMapping]),t.set("GAMMA",qg[this.shaderOutputGamma])),t}markDirty(){this._hash=void 0,this._definesDirty=!0}set fog(t){this._fog!==t&&(this._fog=t,this.markDirty())}get fog(){return this._fog}set ssaoEnabled(t){this._ssaoEnabled!==t&&(this._ssaoEnabled=t,this.markDirty())}get ssaoEnabled(){return this._ssaoEnabled}set gammaCorrection(t){this._gammaCorrectionAssigned=!0,this._gammaCorrection!==t&&(this._gammaCorrection=t,this.markDirty())}get gammaCorrection(){return this._gammaCorrection}set toneMapping(t){this._toneMapping!==t&&(this._toneMapping=t,this.markDirty())}get toneMapping(){return this._toneMapping}set srgbRenderTarget(t){this._srgbRenderTarget!==t&&(this._srgbRenderTarget=t,this.markDirty())}get srgbRenderTarget(){return this._srgbRenderTarget}set sceneDepthMapLinear(t){this._sceneDepthMapLinear!==t&&(this._sceneDepthMapLinear=t,this.markDirty())}get sceneDepthMapLinear(){return this._sceneDepthMapLinear}get shaderOutputGamma(){return this._gammaCorrection===No&&!this._srgbRenderTarget?No:Zi}};var Dp=new x,lS=new x,OL=new x,FL=new W,gY=[new x,new x,new x,new x,new x,new x,new x,new x],Wa=class Wa{constructor(t){n(this,"shaderPassInfo",null);n(this,"renderPassColorGrab",null);n(this,"renderPassDepthGrab",null);n(this,"fogParams",null);n(this,"shaderParams",new bp);n(this,"framePasses",[]);n(this,"beforePasses",[]);n(this,"jitter",0);n(this,"device");this.device=t,this._aspectRatio=16/9,this._aspectRatioMode=Ac,this._calculateProjection=null,this._calculateTransform=null,this._clearColor=new F(.75,.75,.75,1),this._clearColorBuffer=!0,this._clearDepth=1,this._clearDepthBuffer=!0,this._clearStencil=0,this._clearStencilBuffer=!0,this._cullFaces=!0,this._farClip=1e3,this._flipFaces=!1,this._fov=45,this._frustumCulling=!0,this._horizontalFov=!1,this._layers=[Os,Zt,$n,Va,Zn],this._layersSet=new Set(this._layers),this._nearClip=.1,this._node=null,this._orthoHeight=10,this._projection=ts,this._rect=new Q(0,0,1,1),this._renderTarget=null,this._scissorRect=new Q(0,0,1,1),this._scissorRectClear=!1,this._aperture=16,this._shutter=1/1e3,this._sensitivity=1e3,this._projMat=new W,this._projMatDirty=!0,this._projMatSkybox=new W,this._viewMat=new W,this._viewMatDirty=!0,this._viewProjMat=new W,this._viewProjMatDirty=!0,this._shaderMatricesVersion=0,this._viewProjInverse=new W,this._viewProjCurrent=null,this._viewProjPrevious=new W,this._jitters=[0,0,0,0],this.frustum=new So,this._xr=null,this._xrProperties={horizontalFov:this._horizontalFov,fov:this._fov,aspectRatio:this._aspectRatio,farClip:this._farClip,nearClip:this._nearClip}}static applyShaderProjectionTransform(t,e,s,i){if(!s&&!i)return e.copy(t),e;if(s&&i){let r=Wa._applyShaderProjectionScratch;return r.mul2(Wa._flipYProjectionMatrix,t),e.mul2(Wa._webGpuDepthRangeMatrix,r),e}return s?(e.mul2(Wa._flipYProjectionMatrix,t),e):(e.mul2(Wa._webGpuDepthRangeMatrix,t),e)}destroy(){this.renderPassColorGrab?.destroy(),this.renderPassColorGrab=null,this.renderPassDepthGrab?.destroy(),this.renderPassDepthGrab=null,this.framePasses.length=0}_storeShaderMatrices(t,e,s,i){this._shaderMatricesVersion!==i&&(this._shaderMatricesVersion=i,this._viewProjPrevious.copy(this._viewProjCurrent??t),this._viewProjCurrent??(this._viewProjCurrent=new W),this._viewProjCurrent.copy(t),this._viewProjInverse.invert(t),this._jitters[2]=this._jitters[0],this._jitters[3]=this._jitters[1],this._jitters[0]=e,this._jitters[1]=s)}get fullSizeClearRect(){let t=this._scissorRectClear?this.scissorRect:this._rect;return t.x===0&&t.y===0&&t.z===1&&t.w===1}set aspectRatio(t){this._aspectRatio!==t&&(this._aspectRatio=t,this._projMatDirty=!0)}get aspectRatio(){if(this.xr?.active)return this._xrProperties.aspectRatio;if(this._aspectRatioMode===Ac){let t=this.calculateAspectRatio();this._aspectRatio!==t&&(this._aspectRatio=t,this._projMatDirty=!0)}return this._aspectRatio}set aspectRatioMode(t){this._aspectRatioMode!==t&&(this._aspectRatioMode=t,this._projMatDirty=!0)}get aspectRatioMode(){return this._aspectRatioMode}set calculateProjection(t){this._calculateProjection=t,this._projMatDirty=!0}get calculateProjection(){return this._calculateProjection}set calculateTransform(t){this._calculateTransform=t}get calculateTransform(){return this._calculateTransform}set clearColor(t){this._clearColor.copy(t)}get clearColor(){return this._clearColor}set clearColorBuffer(t){this._clearColorBuffer=t}get clearColorBuffer(){return this._clearColorBuffer}set clearDepth(t){this._clearDepth=t}get clearDepth(){return this._clearDepth}set clearDepthBuffer(t){this._clearDepthBuffer=t}get clearDepthBuffer(){return this._clearDepthBuffer}set clearStencil(t){this._clearStencil=t}get clearStencil(){return this._clearStencil}set clearStencilBuffer(t){this._clearStencilBuffer=t}get clearStencilBuffer(){return this._clearStencilBuffer}set cullFaces(t){this._cullFaces=t}get cullFaces(){return this._cullFaces}set farClip(t){this._farClip!==t&&(this._farClip=t,this._projMatDirty=!0)}get farClip(){return this.xr?.active?this._xrProperties.farClip:this._farClip}set flipFaces(t){this._flipFaces=t}get flipFaces(){return this._flipFaces}set fov(t){this._fov!==t&&(this._fov=t,this._projMatDirty=!0)}get fov(){return this.xr?.active?this._xrProperties.fov:this._fov}set frustumCulling(t){this._frustumCulling=t}get frustumCulling(){return this._frustumCulling}set horizontalFov(t){this._horizontalFov!==t&&(this._horizontalFov=t,this._projMatDirty=!0)}get horizontalFov(){return this.xr?.active?this._xrProperties.horizontalFov:this._horizontalFov}set layers(t){this._layers=t.slice(0),this._layersSet=new Set(this._layers)}get layers(){return this._layers}get layersSet(){return this._layersSet}set nearClip(t){this._nearClip!==t&&(this._nearClip=t,this._projMatDirty=!0)}get nearClip(){return this.xr?.active?this._xrProperties.nearClip:this._nearClip}set node(t){this._node=t}get node(){return this._node}set orthoHeight(t){this._orthoHeight!==t&&(this._orthoHeight=t,this._projMatDirty=!0)}get orthoHeight(){return this._orthoHeight}set projection(t){this._projection!==t&&(this._projection=t,this._projMatDirty=!0)}get projection(){return this._projection}get projectionMatrix(){return this._evaluateProjectionMatrix(),this._projMat}set rect(t){this._rect.copy(t),this._projMatDirty=!0}get rect(){return this._rect}set renderTarget(t){this._renderTarget=t,this._projMatDirty=!0}get renderTarget(){return this._renderTarget}set scissorRect(t){this._scissorRect.copy(t)}get scissorRect(){return this._scissorRect}get viewMatrix(){if(this._viewMatDirty){let t=this._node.getWorldTransform();this._viewMat.copy(t).invert(),this._viewMatDirty=!1}return this._viewMat}set aperture(t){this._aperture=t}get aperture(){return this._aperture}set sensitivity(t){this._sensitivity=t}get sensitivity(){return this._sensitivity}set shutter(t){this._shutter=t}get shutter(){return this._shutter}set xr(t){this._xr!==t&&(this._xr=t,this._projMatDirty=!0)}get xr(){return this._xr}calculateAspectRatio(t){let e=t??this._renderTarget,s=e?e.width:this.device.width,i=e?e.height:this.device.height;return s*this._rect.z/(i*this._rect.w)}clone(){return new Wa(this.device).copy(this)}copy(t){return this._aspectRatio=t._aspectRatio,this._farClip=t._farClip,this._fov=t._fov,this._horizontalFov=t._horizontalFov,this._nearClip=t._nearClip,this._xrProperties.aspectRatio=t._xrProperties.aspectRatio,this._xrProperties.farClip=t._xrProperties.farClip,this._xrProperties.fov=t._xrProperties.fov,this._xrProperties.horizontalFov=t._xrProperties.horizontalFov,this._xrProperties.nearClip=t._xrProperties.nearClip,this.aspectRatioMode=t.aspectRatioMode,this.calculateProjection=t.calculateProjection,this.calculateTransform=t.calculateTransform,this.clearColor=t.clearColor,this.clearColorBuffer=t.clearColorBuffer,this.clearDepth=t.clearDepth,this.clearDepthBuffer=t.clearDepthBuffer,this.clearStencil=t.clearStencil,this.clearStencilBuffer=t.clearStencilBuffer,this.cullFaces=t.cullFaces,this.flipFaces=t.flipFaces,this.frustumCulling=t.frustumCulling,this.layers=t.layers,this.orthoHeight=t.orthoHeight,this.projection=t.projection,this.rect=t.rect,this.renderTarget=t.renderTarget,this.scissorRect=t.scissorRect,this.aperture=t.aperture,this.shutter=t.shutter,this.sensitivity=t.sensitivity,this.shaderPassInfo=t.shaderPassInfo,this.jitter=t.jitter,this._projMatDirty=!0,this}_enableRenderPassColorGrab(t,e){e?this.renderPassColorGrab||(this.renderPassColorGrab=new wc(t)):(this.renderPassColorGrab?.destroy(),this.renderPassColorGrab=null)}_enableRenderPassDepthGrab(t,e,s){s?this.renderPassDepthGrab||(this.renderPassDepthGrab=new MT(t,this)):(this.renderPassDepthGrab?.destroy(),this.renderPassDepthGrab=null)}_updateViewProjMat(){(this._projMatDirty||this._viewMatDirty||this._viewProjMatDirty)&&(this._viewProjMat.mul2(this.projectionMatrix,this.viewMatrix),this._viewProjMatDirty=!1)}worldToScreen(t,e,s,i=new x){this._updateViewProjMat(),this._viewProjMat.transformPoint(t,i);let r=this._viewProjMat.data,a=t.x*r[3]+t.y*r[7]+t.z*r[11]+1*r[15];i.x=(i.x/a+1)*.5,i.y=(1-i.y/a)*.5;let{x:o,y:l,z:h,w:f}=this._rect;return i.x=i.x*h*e+o*e,i.y=i.y*f*s+(1-l-f)*s,i}screenToWorld(t,e,s,i,r,a=new x){let{x:o,y:l,z:h,w:f}=this._rect,u=this.farClip-this.nearClip;if(Dp.set((t-o*i)/(h*i),1-(e-(1-l-f)*r)/(f*r),s/u),Dp.mulScalar(2),Dp.sub(x.ONE),this._projection===ts){W._getPerspectiveHalfSize(lS,this.fov,this.aspectRatio,this.nearClip,this.horizontalFov),lS.x*=Dp.x,lS.y*=Dp.y;let d=this._node.getWorldTransform();lS.z=-this.nearClip,d.transformPoint(lS,OL);let p=this._node.getPosition();a.sub2(OL,p),a.normalize(),a.mulScalar(s),a.add(p)}else this._updateViewProjMat(),FL.copy(this._viewProjMat).invert(),FL.transformPoint(Dp,a);return a}_evaluateProjectionMatrix(){let t=this.aspectRatio;if(this._projMatDirty){if(this._projection===ts)this._projMat.setPerspective(this.fov,t,this.nearClip,this.farClip,this.horizontalFov),this._projMatSkybox.copy(this._projMat);else{let e=this._orthoHeight,s=e*t;this._projMat.setOrtho(-s,s,-e,e,this.nearClip,this.farClip),this._projMatSkybox.setPerspective(this.fov,t,this.nearClip,this.farClip)}this._projMatDirty=!1}}getProjectionMatrixSkybox(){return this._evaluateProjectionMatrix(),this._projMatSkybox}getExposure(){let t=Math.log2(this._aperture*this._aperture/this._shutter*100/this._sensitivity);return 1/(Math.pow(2,t)*1.2)}getScreenSize(t){if(this._projection===ts){let e=this._node.getPosition().distance(t.center);if(eObject.keys(c).map(e=>`#define {${t}${e}} ${c[e]}`).join(` `),zL=` ${kL(jt,"CLUSTER_TEXTURE_")} ${kL(vY,"")} `,OT=class{constructor(t){n(this,"areaLightsEnabled",!1);this.device=t,ne.get(t,fe).set("lightBufferDefinesPS",zL),ne.get(t,se).set("lightBufferDefinesPS",zL),this.cookiesEnabled=!1,this.shadowsEnabled=!1,this.areaLightsEnabled=!1,this.maxLights=255;let e=jt.COUNT;this.lightsFloat=new Float32Array(4*e*this.maxLights),this.lightsUint=new Uint32Array(this.lightsFloat.buffer),this.lightsTexture=this.createTexture(this.device,e,this.maxLights,ke,"LightsTexture"),this._lightsTextureId=this.device.scope.resolve("lightsTexture"),this.invMaxColorValue=0,this.invMaxAttenuation=0,this.boundsMin=new x,this.boundsDelta=new x}destroy(){this.lightsTexture?.destroy(),this.lightsTexture=null}createTexture(t,e,s,i,r){return new Z(t,{name:r,width:e,height:s,mipmaps:!1,format:i,addressU:1,addressV:1,type:Gt,magFilter:0,minFilter:0,anisotropy:1})}setBounds(t,e){this.boundsMin.copy(t),this.boundsDelta.copy(e)}uploadTextures(){this.lightsTexture.lock().set(this.lightsFloat),this.lightsTexture.unlock()}updateUniforms(){this._lightsTextureId.setValue(this.lightsTexture)}getSpotDirection(t,e){e._node.getWorldTransform().getY(t).mulScalar(-1),t.normalize()}getLightAreaSizes(t){let e=t._node.getWorldTransform();return e.transformVector(SY,aa),jf[0]=aa.x,jf[1]=aa.y,jf[2]=aa.z,e.transformVector(xY,aa),jf[3]=aa.x,jf[4]=aa.y,jf[5]=aa.z,jf}addLightData(t,e){let s=t._type===je,i=t.atlasViewportAllocated,r=this.cookiesEnabled&&!!t._cookie&&i,a=this.areaLightsEnabled&&t.shape!==$i,o=this.shadowsEnabled&&t.castShadows&&i,l=t._node.getPosition(),h=null,f=null;s?o?h=t.getRenderData(null,0).shadowMatrix:r&&(h=Wo.evalSpotCookieMatrix(t)):(o||r)&&(f=t.atlasViewport);let u=this.lightsFloat,d=this.lightsUint,p=e*this.lightsTexture.width*4;u[p+4*jt.POSITION_RANGE+0]=l.x,u[p+4*jt.POSITION_RANGE+1]=l.y,u[p+4*jt.POSITION_RANGE+2]=l.z,u[p+4*jt.POSITION_RANGE+3]=t.attenuationEnd;let m=t.clusteredData;if(d[p+4*jt.COLOR_ANGLES_BIAS+0]=m[0],d[p+4*jt.COLOR_ANGLES_BIAS+1]=m[1],d[p+4*jt.COLOR_ANGLES_BIAS+2]=m[2],t.castShadows){let _=t.getRenderData(null,0),S=t._getUniformBiasValues(_),g=Hs.float2Half(S.bias),T=Hs.float2Half(S.normalBias);d[p+4*jt.COLOR_ANGLES_BIAS+3]=g|T<<16}if(s&&(this.getSpotDirection(aa,t),u[p+4*jt.DIRECTION_FLAGS+0]=aa.x,u[p+4*jt.DIRECTION_FLAGS+1]=aa.y,u[p+4*jt.DIRECTION_FLAGS+2]=aa.z),d[p+4*jt.DIRECTION_FLAGS+3]=t.getClusteredFlags(o,r),h){let _=h.data;for(let S=0;S<16;S++)u[p+4*jt.PROJ_MAT_0+S]=_[S]}if(f&&(u[p+4*jt.ATLAS_VIEWPORT+0]=f.x,u[p+4*jt.ATLAS_VIEWPORT+1]=f.y,u[p+4*jt.ATLAS_VIEWPORT+2]=f.z/3),a){let _=this.getLightAreaSizes(t);u[p+4*jt.AREA_DATA_WIDTH+0]=_[0],u[p+4*jt.AREA_DATA_WIDTH+1]=_[1],u[p+4*jt.AREA_DATA_WIDTH+2]=_[2],u[p+4*jt.AREA_DATA_HEIGHT+0]=_[3],u[p+4*jt.AREA_DATA_HEIGHT+1]=_[4],u[p+4*jt.AREA_DATA_HEIGHT+2]=_[5]}}};var TY=new B,FT=new x,NT=new x,BT=new x,Vw=new ge;var UT=class{constructor(){this.light=null,this.min=new x,this.max=new x}},sl=class{constructor(t){n(this,"clusterTexture");this.device=t,this.name="Untitled",this.reportCount=0,this.boundsMin=new x,this.boundsMax=new x,this.boundsDelta=new x,this._cells=new x(1,1,1),this._cellsLimit=new x,this.cells=this._cells,this.maxCellLightCount=4,this._usedLights=[],this._usedLights.push(new UT),this.lightsBuffer=new OT(t),this.registerUniforms(t)}set maxCellLightCount(t){t!==this._maxCellLightCount&&(this._maxCellLightCount=t,this._cellsDirty=!0)}get maxCellLightCount(){return this._maxCellLightCount}set cells(t){FT.copy(t).floor(),this._cells.equals(FT)||(this._cells.copy(FT),this._cellsLimit.copy(FT).sub(x.ONE),this._cellsDirty=!0)}get cells(){return this._cells}destroy(){this.lightsBuffer.destroy(),this.releaseClusterTexture()}releaseClusterTexture(){this.clusterTexture&&(this.clusterTexture.destroy(),this.clusterTexture=null)}registerUniforms(t){this._numClusteredLightsId=t.scope.resolve("numClusteredLights"),this._clusterMaxCellsId=t.scope.resolve("clusterMaxCells"),this._clusterWorldTextureId=t.scope.resolve("clusterWorldTexture"),this._clusterBoundsMinId=t.scope.resolve("clusterBoundsMin"),this._clusterBoundsMinData=new Float32Array(3),this._clusterBoundsDeltaId=t.scope.resolve("clusterBoundsDelta"),this._clusterBoundsDeltaData=new Float32Array(3),this._clusterCellsCountByBoundsSizeId=t.scope.resolve("clusterCellsCountByBoundsSize"),this._clusterCellsCountByBoundsSizeData=new Float32Array(3),this._clusterCellsDotId=t.scope.resolve("clusterCellsDot"),this._clusterCellsDotData=new Int32Array(3),this._clusterCellsMaxId=t.scope.resolve("clusterCellsMax"),this._clusterCellsMaxData=new Int32Array(3),this._clusterTextureWidthId=t.scope.resolve("clusterTextureWidth")}updateParams(t){t&&(this.cells=t.cells,this.maxCellLightCount=t.maxLightsPerCell,this.lightsBuffer.cookiesEnabled=t.cookiesEnabled,this.lightsBuffer.shadowsEnabled=t.shadowsEnabled,this.lightsBuffer.areaLightsEnabled=t.areaLightsEnabled)}updateCells(){if(this._cellsDirty){this._cellsDirty=!1;let t=this._cells.x,e=this._cells.y,s=this._cells.z,i=t*e*s,r=this.maxCellLightCount*i,{x:a,y:o}=gt.calcTextureSize(r,TY,this.maxCellLightCount);this._clusterCellsMaxData[0]=t,this._clusterCellsMaxData[1]=e,this._clusterCellsMaxData[2]=s,this._clusterCellsDotData[0]=this.maxCellLightCount,this._clusterCellsDotData[1]=t*s*this.maxCellLightCount,this._clusterCellsDotData[2]=t*this.maxCellLightCount,this.clusters=new Uint8ClampedArray(r),this.counts=new Int32Array(i),this.releaseClusterTexture(),this.clusterTexture=this.lightsBuffer.createTexture(this.device,a,o,sc,"ClusterTexture")}}uploadTextures(){this.clusterTexture.lock().set(this.clusters),this.clusterTexture.unlock(),this.lightsBuffer.uploadTextures()}updateUniforms(){this._numClusteredLightsId.setValue(this._usedLights.length),this.lightsBuffer.updateUniforms(),this._clusterWorldTextureId.setValue(this.clusterTexture),this._clusterMaxCellsId.setValue(this.maxCellLightCount);let t=this.boundsDelta;this._clusterCellsCountByBoundsSizeData[0]=this._cells.x/t.x,this._clusterCellsCountByBoundsSizeData[1]=this._cells.y/t.y,this._clusterCellsCountByBoundsSizeData[2]=this._cells.z/t.z,this._clusterCellsCountByBoundsSizeId.setValue(this._clusterCellsCountByBoundsSizeData),this._clusterBoundsMinData[0]=this.boundsMin.x,this._clusterBoundsMinData[1]=this.boundsMin.y,this._clusterBoundsMinData[2]=this.boundsMin.z,this._clusterBoundsDeltaData[0]=t.x,this._clusterBoundsDeltaData[1]=t.y,this._clusterBoundsDeltaData[2]=t.z,this._clusterBoundsMinId.setValue(this._clusterBoundsMinData),this._clusterBoundsDeltaId.setValue(this._clusterBoundsDeltaData),this._clusterCellsDotId.setValue(this._clusterCellsDotData),this._clusterCellsMaxId.setValue(this._clusterCellsMaxData),this._clusterTextureWidthId.setValue(this.clusterTexture.width)}evalLightCellMinMax(t,e,s){e.copy(t.min),e.sub(this.boundsMin),e.div(this.boundsDelta),e.mul2(e,this.cells),e.floor(),s.copy(t.max),s.sub(this.boundsMin),s.div(this.boundsDelta),s.mul2(s,this.cells),s.ceil(),e.max(x.ZERO),s.min(this._cellsLimit)}collectLights(t){let e=this.lightsBuffer.maxLights,s=this._usedLights,i=1;t.forEach(r=>{let a=!!(r.mask&(cs|xi)),o=r.type===je&&r._outerConeAngle===0;if(r.enabled&&r.type!==Ce&&r.visibleThisFrame&&r.intensity>0&&a&&!o&&i1){e.copy(t[1].min),s.copy(t[1].max);for(let i=2;i>>16)>>>0;return t=((t&1431655765)<<1|(t&2863311530)>>>1)>>>0,t=((t&858993459)<<2|(t&3435973836)>>>2)>>>0,t=((t&252645135)<<4|(t&4042322160)>>>4)>>>0,t=((t&16711935)<<8|(t&4278255360)>>>8)>>>0,t*23283064365386963e-26}};var yY={linear:"decodeLinear",srgb:"decodeGamma",rgbm:"decodeRGBM",rgbe:"decodeRGBE",rgbp:"decodeRGBP",xy:"unpackNormalXY",xyz:"unpackNormalXYZ"},EY={linear:"encodeLinear",srgb:"encodeGamma",rgbm:"encodeRGBM",rgbe:"encodeRGBE",rgbp:"encodeRGBP"},li=class{static decodeFunc(t){return yY[t]??"decodeGamma"}static encodeFunc(t){return EY[t]??"encodeGamma"}};var VL=c=>{switch(c){case Ld:return"Cubemap";case JC:return"Octahedral";default:return"Equirect"}},kT=(c,t,e)=>{if(c<=0)t[e+0]=0,t[e+1]=0,t[e+2]=0,t[e+3]=0;else if(c>=1)t[e+0]=255,t[e+1]=0,t[e+2]=0,t[e+3]=0;else{let s=1*c%1,i=255*c%1,r=65025*c%1,a=16581375*c%1;s-=i/255,i-=r/255,r-=a/255,t[e+0]=Math.min(255,Math.floor(s*256)),t[e+1]=Math.min(255,Math.floor(i*256)),t[e+2]=Math.min(255,Math.floor(r*256)),t[e+3]=Math.min(255,Math.floor(a*256))}},AY=c=>{let t=c.length,e=Math.min(t,512),s=Math.ceil(t/e),i=new Uint8Array(e*s*4),r=0;for(let a=0;a{let i=e*2*Math.PI,r=Math.pow(1-t,1/(s+1)),a=Math.sqrt(1-r*r);c.set(Math.cos(i)*a,Math.sin(i)*a,r).normalize()},PY=(c,t,e)=>{let s=e*2*Math.PI,i=Math.sqrt(1-t),r=Math.sqrt(t);c.set(Math.cos(s)*r,Math.sin(s)*r,i).normalize()},wY=(c,t,e,s)=>{let i=e*2*Math.PI,r=Math.sqrt((1-t)/(1+(s*s-1)*t)),a=Math.sqrt(1-r*r);c.set(Math.cos(i)*a,Math.sin(i)*a,r).normalize()},IY=(c,t)=>{let e=c*t,s=t/(1-c*c+e*e);return s*s*(1/Math.PI)},RY=(c,t)=>{let e=new x,s=[];for(let i=0;i{let e=t/c,s=new x,i=[];for(let r=0;r{let e=DY[c];return e&&e[t]||c},MY=(c,t,e)=>{let s=e/c,i=1-Math.log2(t)/11,r=i*i,a=new x,o=new x,l=new x(0,0,1),h=[],f=LY(c,t);for(let u=0;u0){let p=IY(Math.min(1,d),r)/4+.001,m=.5*Math.log2(s/p);h.push(o.x,o.y,o.z,m)}}for(;h.length{let s=AY(e);return new Z(c,{name:t,width:s.width,height:s.height,mipmaps:!1,minFilter:0,magFilter:0,levels:[s.data]})},zT=class{constructor(t=!0){n(this,"map",new Map);this.destroyContent=t}destroy(){this.destroyContent&&this.map.forEach((t,e)=>{t.destroy()})}get(t,e){if(!this.map.has(t)){let s=e();return this.map.set(t,s),s}return this.map.get(t)}},FY=new zT(!1),NY=new et,Hw=(c,t,e)=>NY.get(c,()=>new zT).get(t,()=>OY(c,t,FY.get(t,e))),BY=(c,t,e)=>{let s=`lambert-samples-${t}-${e}`;return Hw(c,s,()=>bY(t,e))},UY=(c,t,e)=>{let s=`phong-samples-${t}-${e}`;return Hw(c,s,()=>RY(t,e))},kY=(c,t,e,s)=>{let i=`ggx-samples-${t}-${e}-${s}`;return Hw(c,i,()=>MY(t,e,s))};function oa(c,t,e={}){let s=e.seamPixels??0,i=(e.rect?.z??t.width)-s*2,r=(e.rect?.w??t.height)-s*2;if(i<1||r<1)return!1;let a={none:"reproject",lambert:"prefilterSamplesUnweighted",phong:"prefilterSamplesUnweighted",ggx:"prefilterSamples"},o=e.hasOwnProperty("specularPower")?e.specularPower:1,l=e.hasOwnProperty("face")?e.face:null,h=e.hasOwnProperty("distribution")?e.distribution:o===1?"none":"phong",f=a[h]||"reproject",u=f.startsWith("prefilterSamples"),d=li.decodeFunc(c.encoding),p=li.encodeFunc(t.encoding),m=`sample${VL(c.projection)}`,_=`getDirection${VL(t.projection)}`,S=e.hasOwnProperty("numSamples")?e.numSamples:1024,g=`ReprojectShader:${f}_${d}_${p}_${m}_${_}_${S}`,T=c.device,C=Ji(T).getCachedShader(g);if(!C){let A=new Map;u&&A.set("USE_SAMPLES_TEX",""),c.cubemap&&A.set("CUBEMAP_SOURCE",""),A.set("{PROCESS_FUNC}",f),A.set("{DECODE_FUNC}",d),A.set("{ENCODE_FUNC}",p),A.set("{SOURCE_FUNC}",m),A.set("{TARGET_FUNC}",_),A.set("{NUM_SAMPLES}",S),A.set("{NUM_SAMPLES_SQRT}",Math.round(Math.sqrt(S)).toFixed(1)),C=Se.createShader(T,{uniqueName:g,attributes:{vertex_position:ee},vertexChunk:"reprojectVS",fragmentChunk:"reprojectPS",fragmentDefines:A})}T.setBlendState(Oe.NOBLEND),T.scope.resolve(c.cubemap?"sourceCube":"sourceTex").setValue(c);let E=T.scope.resolve("params"),y=T.scope.resolve("uvMod");s>0?y.setValue([(i+s*2)/i,(r+s*2)/r,-s/i,-s/r]):y.setValue([1,1,0,0]);let P=[0,t.width*t.height*(t.cubemap?6:1),c.width*c.height*(c.cubemap?6:1)];if(u){let A=c.width*c.height*(c.cubemap?6:1),w=h==="ggx"?kY(T,S,o,A):h==="lambert"?BY(T,S,A):UY(T,S,o);T.scope.resolve("samplesTex").setValue(w),T.scope.resolve("samplesTexInverseSize").setValue([1/w.width,1/w.height])}for(let A=0;A<(t.cubemap?6:1);A++)if(l===null||A===l){let w=new me({colorBuffer:t,face:A,depth:!1,flipY:T.isWebGPU});P[0]=A,E.setValue(P),Qt(T,w,C,e?.rect),w.destroy()}return!0}var Ww=(c,t=0)=>1+Math.floor(Math.log2(Math.max(c,t))),zY=c=>c.textureHalfFloatRenderable,GY=c=>c.textureFloatRenderable,VY=c=>zY(c)?Me:GY(c)?ke:ce,HY=c=>ce,WY=(c,t,e,s)=>new Z(c,{name:`lighting-${t}`,cubemap:!0,width:t,height:t,format:e,type:e===ce?In:Gt,addressU:1,addressV:1,mipmaps:!!s}),bc=class{static generateSkyboxCubemap(t,e){let s=t.device,i=WY(s,e||(t.cubemap?t.width:t.width/4),ce,!1);return oa(t,i,{numSamples:1024}),i}static generateLightingSource(t,e){let s=t.device,i=VY(s),r=e?.target||new Z(s,{name:"lighting-source",cubemap:!0,width:e?.size||128,height:e?.size||128,format:i,type:i===ce?In:Gt,addressU:1,addressV:1,mipmaps:!0});return oa(t,r,{numSamples:t.mipmaps?1:1024}),r}static generateAtlas(t,e){let s=t.device,i=HY(s),r=e?.target||new Z(s,{name:"envAtlas",width:e?.size||512,height:e?.size||512,format:i,type:i===ce?In:Gt,projection:Gx,addressU:1,addressV:1,mipmaps:!1}),a=r.width/512,o=new Q(0,0,512*a,256*a),l=Ww(256)-Ww(4);for(let h=0;h>h*2),rect:o,seamPixels:a}),o.y+=o.w,o.z=Math.max(1,Math.floor(o.z*.5)),o.w=Math.max(1,Math.floor(o.w*.5));return o.set(128*a,384*a,64*a,32*a),oa(t,r,{numSamples:e?.numAmbientSamples||2048,distribution:"lambert",rect:o,seamPixels:a}),r}static generatePrefilteredAtlas(t,e){let s=t[0].device,i=t[0].format,r=t[0].type,a=e?.target||new Z(s,{name:"envPrefilteredAtlas",width:e?.size||512,height:e?.size||512,format:i,type:r,projection:Gx,addressU:1,addressV:1,mipmaps:!1}),o=a.width/512,l=new Q(0,0,512*o,256*o),h=Ww(512);for(let f=0;f{for(let h in Xw)Xw.hasOwnProperty(h)&&o.indexOf(h)>=0&&(this.attributes[h]=Xw[h]);this.chunks.set(l,o)}),this.shaderPassInfo=Ns.get(this.device).getByIndex(e.pass),this.shadowPass=this.shaderPassInfo.isShadow,this.lighting=e.lights.length>0||e.dirLightMapEnabled||e.clusteredLightingEnabled,this.reflections=e.reflectionSource!==gr,this.needsNormal=this.lighting||this.reflections||e.useSpecular||e.ambientSH||e.useHeights||e.enableGGXSpecular||e.clusteredLightingEnabled&&!this.shadowPass||e.useClearCoatNormals,this.needsNormal=this.needsNormal&&!this.shadowPass,this.needsSceneColor=e.useDynamicRefraction,this.needsScreenSize=e.useDynamicRefraction,this.needsTransforms=e.useDynamicRefraction,this.vshader=null,this.fshader=null}fDefineSet(t,e,s=""){t&&this.fDefines.set(e,s)}generateVertexShader(t,e,s){let{options:i,vDefines:r,attributes:a}=this,o=new Map;if(o.set("vPositionW","vec3"),(i.nineSlicedMode===It||i.nineSlicedMode===Rt)&&r.set("NINESLICED",!0),this.options.linearDepth&&(r.set("LINEAR_DEPTH",!0),o.set("vLinearDepth","float")),this.needsNormal&&r.set("NORMALS",!0),this.options.useInstancing){let u=ne.get(this.device,this.shaderLanguage);this.chunks.get("transformInstancingVS")===u.get("transformInstancingVS")&&(a.instance_line1=Id,a.instance_line2=Rd,a.instance_line3=bd,a.instance_line4=Da)}this.needsNormal&&(a.vertex_normal=Ot,o.set("vNormalW","vec3"),i.hasTangents&&(i.useHeights||i.useNormals||i.useClearCoatNormals||i.enableGGXSpecular)?(r.set("TANGENTS",!0),a.vertex_tangent=vs,o.set("vTangentW","vec3"),o.set("vBinormalW","vec3")):i.enableGGXSpecular&&(r.set("GGX_SPECULAR",!0),o.set("vObjectSpaceUpW","vec3")));let l=2;for(let u=0;u{let{id:d,uv:p,name:m}=u,_=d+p*100;if(!f.has(_)){f.add(_),o.set(`vUV${p}_${d}`,"vec2");let S=`texture_${m}MapTransform`;r.set(`{TRANSFORM_NAME_${h}}`,S),r.set(`{TRANSFORM_UV_${h}}`,p),r.set(`{TRANSFORM_ID_${h}}`,d),h++}}),r.set("UV_TRANSFORMS_COUNT",h),i.vertexColors&&(a.vertex_color=Ct,r.set("VERTEX_COLOR",!0),o.set("vVertexColor","vec4"),i.useVertexColorGamma&&r.set("STD_VERTEX_COLOR_GAMMA","")),i.useMsdf&&i.msdfTextAttribute&&(a.vertex_outlineParameters=rc,a.vertex_shadowParameters=ac,r.set("MSDF",!0)),(i.useMorphPosition||i.useMorphNormal)&&(r.set("MORPHING",!0),i.useMorphTextureBasedInt&&r.set("MORPHING_INT",!0),i.useMorphPosition&&r.set("MORPHING_POSITION",!0),i.useMorphNormal&&r.set("MORPHING_NORMAL",!0),a.morph_vertex_id=Da),i.skin&&(a.vertex_boneIndices=$t,i.batch?r.set("BATCH",!0):(a.vertex_boneWeights=bs,r.set("SKIN",!0))),i.useInstancing&&r.set("INSTANCING",!0),i.screenSpace&&r.set("SCREENSPACE",!0),i.pixelSnap&&r.set("PIXELSNAP",!0),o.forEach((u,d)=>{this.varyingsCode+=`#define VARYING_${d.toUpperCase()} `,this.varyingsCode+=this.shaderLanguage===se?`varying ${d}: ${Bg.get(u)}; `:`varying ${u} ${d}; `}),this.includes.set("varyingsVS",this.varyingsCode),this.includes.set("varyingsPS",this.varyingsCode),this.vshader=` #include "litMainVS" `}_setupLightingDefines(t,e){let s=this.fDefines,i=this.options;if(this.fDefines.set("LIGHT_COUNT",i.lights.length),t&&s.set("AREA_LIGHTS",!0),e&&this.lighting&&(s.set("LIT_CLUSTERED_LIGHTS",!0),i.clusteredLightingCookiesEnabled&&s.set("CLUSTER_COOKIES",!0),i.clusteredLightingAreaLightsEnabled&&s.set("CLUSTER_AREALIGHTS",!0),i.lightMaskDynamic&&s.set("CLUSTER_MESH_DYNAMIC_LIGHTS",!0),i.clusteredLightingShadowsEnabled&&!i.noShadow)){let r=Fi.get(i.clusteredLightingShadowType);s.set("CLUSTER_SHADOWS",!0),s.set(`SHADOW_KIND_${r.kind}`,!0),s.set(`CLUSTER_SHADOW_TYPE_${r.kind}`,!0)}for(let r=0;r0&&s.set(`LIGHT${r}_SHADOW_CASCADE_BLEND`,!0),a.numCascades>1&&s.set(`LIGHT${r}_SHADOW_CASCADES`,!0)),(u.pcf||u.pcss||this.device.isWebGPU)&&s.set(`LIGHT${r}_SHADOW_SAMPLE_SOURCE_ZBUFFER`,!0),o===We&&s.set(`LIGHT${r}_SHADOW_SAMPLE_POINT`,!0)),f&&(s.set(`SHADOW_KIND_${u.kind}`,!0),o===Ce&&s.set("SHADOW_DIRECTIONAL",!0))}}prepareForwardPass(t){let{options:e}=this,i=e.clusteredLightingEnabled&&e.clusteredLightingAreaLightsEnabled||e.lights.some(o=>o._shape&&o._shape!==$i),r=!e.lightMapEnabled||e.lightMapWithoutAmbient,a=this.needsNormal&&(e.useNormals||e.useClearCoatNormals||e.enableGGXSpecular&&!e.useHeights);e.useSpecular&&(this.fDefineSet(!0,"LIT_SPECULAR"),this.fDefineSet(this.reflections,"LIT_REFLECTIONS"),this.fDefineSet(e.useClearCoat,"LIT_CLEARCOAT"),this.fDefineSet(e.fresnelModel>0,"LIT_SPECULAR_FRESNEL"),this.fDefineSet(e.useSheen,"LIT_SHEEN"),this.fDefineSet(e.useIridescence,"LIT_IRIDESCENCE")),this.fDefineSet(this.lighting&&e.useSpecular||this.reflections,"LIT_SPECULAR_OR_REFLECTION"),this.fDefineSet(this.needsSceneColor,"LIT_SCENE_COLOR"),this.fDefineSet(this.needsScreenSize,"LIT_SCREEN_SIZE"),this.fDefineSet(this.needsTransforms,"LIT_TRANSFORMS"),this.fDefineSet(this.needsNormal,"LIT_NEEDS_NORMAL"),this.fDefineSet(this.lighting,"LIT_LIGHTING"),this.fDefineSet(e.useMetalness,"LIT_METALNESS"),this.fDefineSet(e.enableGGXSpecular,"LIT_GGX_SPECULAR"),this.fDefineSet(e.useAnisotropy,"LIT_ANISOTROPY"),this.fDefineSet(e.useSpecularityFactor,"LIT_SPECULARITY_FACTOR"),this.fDefineSet(e.useCubeMapRotation,"CUBEMAP_ROTATION"),this.fDefineSet(e.occludeSpecularFloat,"LIT_OCCLUDE_SPECULAR_FLOAT"),this.fDefineSet(e.separateAmbient,"LIT_SEPARATE_AMBIENT"),this.fDefineSet(e.twoSidedLighting,"LIT_TWO_SIDED_LIGHTING"),this.fDefineSet(e.lightMapEnabled,"LIT_LIGHTMAP"),this.fDefineSet(e.dirLightMapEnabled,"LIT_DIR_LIGHTMAP"),this.fDefineSet(e.skyboxIntensity>0,"LIT_SKYBOX_INTENSITY"),this.fDefineSet(e.clusteredLightingShadowsEnabled,"LIT_CLUSTERED_SHADOWS"),this.fDefineSet(e.clusteredLightingAreaLightsEnabled,"LIT_CLUSTERED_AREA_LIGHTS"),this.fDefineSet(a,"LIT_TBN"),this.fDefineSet(r,"LIT_ADD_AMBIENT"),this.fDefineSet(e.hasTangents,"LIT_TANGENTS"),this.fDefineSet(e.useNormals,"LIT_USE_NORMALS"),this.fDefineSet(e.useClearCoatNormals,"LIT_USE_CLEARCOAT_NORMALS"),this.fDefineSet(e.useRefraction,"LIT_REFRACTION"),this.fDefineSet(e.useDynamicRefraction,"LIT_DYNAMIC_REFRACTION"),this.fDefineSet(e.dispersion,"LIT_DISPERSION"),this.fDefineSet(e.useHeights,"LIT_HEIGHTS"),this.fDefineSet(e.opacityFadesSpecular,"LIT_OPACITY_FADES_SPECULAR"),this.fDefineSet(e.alphaToCoverage,"LIT_ALPHA_TO_COVERAGE"),this.fDefineSet(e.alphaTest,"LIT_ALPHA_TEST"),this.fDefineSet(e.useMsdf,"LIT_MSDF"),this.fDefineSet(e.ssao,"LIT_SSAO"),this.fDefineSet(e.useAo,"LIT_AO"),this.fDefineSet(e.occludeDirect,"LIT_OCCLUDE_DIRECT"),this.fDefineSet(e.msdfTextAttribute,"LIT_MSDF_TEXT_ATTRIBUTE"),this.fDefineSet(e.diffuseMapEnabled,"LIT_DIFFUSE_MAP"),this.fDefineSet(e.shadowCatcher,"LIT_SHADOW_CATCHER"),this.fDefineSet(!0,"LIT_FRESNEL_MODEL",aw[e.fresnelModel]),this.fDefineSet(!0,"LIT_NONE_SLICE_MODE",_w[e.nineSlicedMode]),this.fDefineSet(!0,"LIT_BLEND_TYPE",Wg[e.blendType]),this.fDefineSet(!0,"LIT_CUBEMAP_PROJECTION",uw[e.cubeMapProjection]),this.fDefineSet(!0,"LIT_OCCLUDE_SPECULAR",dw[e.occludeSpecular]),this.fDefineSet(!0,"LIT_REFLECTION_SOURCE",pw[e.reflectionSource]),this.fDefineSet(!0,"LIT_AMBIENT_SOURCE",mw[e.ambientSource]),this.fDefineSet(!0,"{lightingUv}",t??""),this.fDefineSet(!0,"{reflectionDecode}",li.decodeFunc(e.reflectionEncoding)),this.fDefineSet(!0,"{reflectionCubemapDecode}",li.decodeFunc(e.reflectionCubemapEncoding)),this.fDefineSet(!0,"{ambientDecode}",li.decodeFunc(e.ambientEncoding)),this._setupLightingDefines(i,e.clusteredLightingEnabled)}preparePrepassPass(){let{options:t}=this;this.fDefineSet(t.alphaTest,"LIT_ALPHA_TEST"),this.fDefineSet(!0,"STD_OPACITY_DITHER",eS[t.opacityShadowDither])}prepareShadowPass(){let{options:t}=this,e=this.shaderPassInfo.lightType,s=this.shaderPassInfo.shadowType,i=Fi.get(s),r=e===Ce||!i.vsm&&e===je;this.fDefineSet(r,"PERSPECTIVE_DEPTH"),this.fDefineSet(!0,"LIGHT_TYPE",`${lT[e]}`),this.fDefineSet(!0,"SHADOW_TYPE",`${i.name}`),this.fDefineSet(t.alphaTest,"LIT_ALPHA_TEST")}generateFragmentShader(t,e,s){let i=this.options;this.includes.set("frontendDeclPS",t??""),this.includes.set("frontendCodePS",e??""),i.pass===ta||(i.pass===xr?this.preparePrepassPass():this.shadowPass?this.prepareShadowPass():this.prepareForwardPass(s)),this.fshader=` #include "litMainPS" `}};var Xa=class{constructor(){n(this,"hasTangents",!1);n(this,"shaderChunks",null);n(this,"pass",0);n(this,"alphaTest",!1);n(this,"blendType",wt);n(this,"separateAmbient",!1);n(this,"screenSpace",!1);n(this,"skin",!1);n(this,"batch",!1);n(this,"useInstancing",!1);n(this,"useMorphPosition",!1);n(this,"useMorphNormal",!1);n(this,"useMorphTextureBasedInt",!1);n(this,"nineSlicedMode",0);n(this,"clusteredLightingEnabled",!0);n(this,"clusteredLightingCookiesEnabled",!1);n(this,"clusteredLightingShadowsEnabled",!1);n(this,"clusteredLightingShadowType",0);n(this,"clusteredLightingAreaLightsEnabled",!1);n(this,"vertexColors",!1);n(this,"useVertexColorGamma",!1);n(this,"lightMapEnabled",!1);n(this,"dirLightMapEnabled",!1);n(this,"useHeights",!1);n(this,"useNormals",!1);n(this,"useClearCoatNormals",!1);n(this,"useAo",!1);n(this,"diffuseMapEnabled",!1);n(this,"pixelSnap",!1);n(this,"ambientSH",!1);n(this,"ssao",!1);n(this,"twoSidedLighting",!1);n(this,"occludeDirect",!1);n(this,"occludeSpecular",0);n(this,"occludeSpecularFloat",!1);n(this,"useMsdf",!1);n(this,"msdfTextAttribute",!1);n(this,"alphaToCoverage",!1);n(this,"opacityFadesSpecular",!1);n(this,"opacityDither",Bi);n(this,"opacityShadowDither",Bi);n(this,"cubeMapProjection",0);n(this,"useSpecular",!1);n(this,"useSpecularityFactor",!1);n(this,"enableGGXSpecular",!1);n(this,"fresnelModel",0);n(this,"useRefraction",!1);n(this,"useClearCoat",!1);n(this,"useSheen",!1);n(this,"useIridescence",!1);n(this,"useMetalness",!1);n(this,"useDynamicRefraction",!1);n(this,"dispersion",!1);n(this,"fog",Mi);n(this,"gamma",Zi);n(this,"toneMap",-1);n(this,"reflectionSource",gr);n(this,"reflectionEncoding",null);n(this,"reflectionCubemapEncoding",null);n(this,"ambientSource","constant");n(this,"ambientEncoding",null);n(this,"skyboxIntensity",1);n(this,"useCubeMapRotation",!1);n(this,"lightMapWithoutAmbient",!1);n(this,"lights",[]);n(this,"noShadow",!1);n(this,"lightMaskDynamic",0);n(this,"userAttributes",{});n(this,"linearDepth",!1);n(this,"shadowCatcher",!1)}};var tr=class{constructor(){n(this,"defines",new Map);n(this,"forceUv1",!1);n(this,"specularTint",!1);n(this,"metalnessTint",!1);n(this,"glossTint",!1);n(this,"emissiveEncoding","linear");n(this,"lightMapEncoding","linear");n(this,"vertexColorGamma",!1);n(this,"packedNormal",!1);n(this,"normalDetailPackedNormal",!1);n(this,"clearCoatPackedNormal",!1);n(this,"glossInvert",!1);n(this,"sheenGlossInvert",!1);n(this,"clearCoatGlossInvert",!1);n(this,"useAO",!1);n(this,"litOptions",new Xa)}get pass(){return this.litOptions.pass}};var cS={generateKey(c){return`lit${Object.keys(c).sort().map(t=>t==="shaderChunks"?c.shaderChunks?.key??"":t==="lights"?cS.generateLightsKey(c):t+c[t]).join(` `)}`},generateLightsKey(c){return`lights:${c.lights.map(t=>!c.clusteredLightingEnabled||t._type===Ce?`${t.key},`:"").join("")}`}};var Dc=[],Yw=c=>Object.keys(c).filter(t=>t!=="litOptions").sort(),Kw=class extends yi{constructor(){super(...arguments);n(this,"optionsContext",new tr);n(this,"optionsContextMin",new tr)}generateKey(e){let s;return e===this.optionsContextMin?(this.propsMin||(this.propsMin=Yw(e)),s=this.propsMin):e===this.optionsContext?(this.props||(this.props=Yw(e)),s=this.props):s=Yw(e),`standard: ${yi.definesHash(e.defines)} ${s.map(a=>a+e[a]).join(` `)}${cS.generateKey(e.litOptions)}`}_getUvSourceExpression(e,s,i){let r=i[e],a=i[s],o=i.litOptions.pass===Sr,l;return o&&i.litOptions.nineSlicedMode===It||o&&i.litOptions.nineSlicedMode===Rt?l="nineSlicedUv":(r===0?l=`vUv${a}`:l=`vUV${a}_${r}`,i.heightMap&&e!=="heightMapTransform"&&(l+=" + dUvOffset")),l}_validateMapChunk(e,s,i,r){}_addMapDefines(e,s,i,r,a,o,l=null){let h=`${s}Map`,f=s.toUpperCase(),u=`${h}Uv`,d=`${h}Identifier`,p=`${h}Transform`,m=`${h}Channel`,_=`${s}VertexColorChannel`,S=`${s}Tint`,g=`${s}VertexColor`,T=`${s}Mode`,C=`${s}Invert`,v=r[S],E=r[g],y=r[h],P=r[d],A=r[T],w=a.get(i);if(y){e.set(`STD_${f}_TEXTURE`,"");let I=this._getUvSourceExpression(p,u,r);e.set(`{STD_${f}_TEXTURE_UV}`,I),e.set(`{STD_${f}_TEXTURE_CHANNEL}`,r[m]);let D=`{STD_${f}_TEXTURE_NAME}`;if(w.includes(D)){let O=`texture_${h}`,G=o[P];G?O=G:(o[P]=O,e.set(`STD_${f}_TEXTURE_ALLOCATE`,"")),e.set(D,O)}if(l){let O=r[m]==="aaa"?"passThrough":li.decodeFunc(l);e.set(`{STD_${f}_TEXTURE_DECODE}`,O)}}E&&(e.set(`STD_${f}_VERTEX`,""),e.set(`{STD_${f}_VERTEX_CHANNEL}`,r[_])),A&&e.set(`{STD_${f}_DETAILMODE}`,A),v&&e.set(`STD_${f}_CONSTANT`,""),r[C]&&e.set(`STD_${f}_INVERT`,"")}_correctChannel(e,s,i){if(i[e]>0){if(i[e]s.length){let r=s,a=r.charAt(r.length-1),o=i[e]-r.length;for(let l=0;l{a&&s.set(o,l)};r(e.lightMap,"STD_LIGHTMAP",""),r(e.lightVertexColor,"STD_LIGHT_VERTEX_COLOR",""),r(e.dirLightMap&&e.litOptions.useSpecular,"STD_LIGHTMAP_DIR",""),r(e.heightMap,"STD_HEIGHT_MAP",""),r(e.useSpecularColor,"STD_SPECULAR_COLOR",""),r(e.aoMap||e.aoVertexColor||e.useAO,"STD_AO",""),r(!0,"STD_OPACITY_DITHER",eS[i.isForward?e.litOptions.opacityDither:e.litOptions.opacityShadowDither])}createShaderDefinition(e,s){let i=Ns.get(e).getByIndex(s.litOptions.pass),r=i.isForward,a=new Lp(e,s.litOptions);this.createVertexShader(a,s);let o={};s.litOptions.fresnelModel=s.litOptions.fresnelModel===0?Sc:s.litOptions.fresnelModel;let l=a.fDefines;this.prepareFragmentDefines(s,l,i);let h="";if(r){if(s.heightMap&&this._addMapDefines(l,"height","parallaxPS",s,a.chunks,o),(s.litOptions.blendType!==wt||s.litOptions.alphaTest||s.litOptions.alphaToCoverage||s.litOptions.opacityDither!==Bi)&&this._addMapDefines(l,"opacity","opacityPS",s,a.chunks,o),a.needsNormal){if((s.normalMap||s.clearCoatNormalMap)&&!s.litOptions.hasTangents){let p=s.normalMap?"normalMap":"clearCoatNormalMap";h=this._getUvSourceExpression(`${p}Transform`,`${p}Uv`,s)}this._addMapDefines(l,"normalDetail","normalMapPS",s,a.chunks,o,s.normalDetailPackedNormal?"xy":"xyz"),this._addMapDefines(l,"normal","normalMapPS",s,a.chunks,o,s.packedNormal?"xy":"xyz")}s.diffuseDetail&&this._addMapDefines(l,"diffuseDetail","diffusePS",s,a.chunks,o,s.diffuseDetailEncoding),this._addMapDefines(l,"diffuse","diffusePS",s,a.chunks,o,s.diffuseEncoding),s.litOptions.useRefraction&&(this._addMapDefines(l,"refraction","transmissionPS",s,a.chunks,o),this._addMapDefines(l,"thickness","thicknessPS",s,a.chunks,o)),s.litOptions.useIridescence&&(this._addMapDefines(l,"iridescence","iridescencePS",s,a.chunks,o),this._addMapDefines(l,"iridescenceThickness","iridescenceThicknessPS",s,a.chunks,o)),(a.lighting&&s.litOptions.useSpecular||a.reflections)&&(s.litOptions.useSheen&&(this._addMapDefines(l,"sheen","sheenPS",s,a.chunks,o,s.sheenEncoding),this._addMapDefines(l,"sheenGloss","sheenGlossPS",s,a.chunks,o)),s.litOptions.useMetalness&&(this._addMapDefines(l,"metalness","metalnessPS",s,a.chunks,o),this._addMapDefines(l,"ior","iorPS",s,a.chunks,o)),s.litOptions.useSpecularityFactor&&this._addMapDefines(l,"specularityFactor","specularityFactorPS",s,a.chunks,o),s.useSpecularColor&&this._addMapDefines(l,"specular","specularPS",s,a.chunks,o,s.specularEncoding),this._addMapDefines(l,"gloss","glossPS",s,a.chunks,o)),s.aoDetail&&this._addMapDefines(l,"aoDetail","aoPS",s,a.chunks,o),(s.aoMap||s.aoVertexColor||s.useAO)&&this._addMapDefines(l,"ao","aoPS",s,a.chunks,o),this._addMapDefines(l,"emissive","emissivePS",s,a.chunks,o,s.emissiveEncoding),s.litOptions.useClearCoat&&(this._addMapDefines(l,"clearCoat","clearCoatPS",s,a.chunks,o),this._addMapDefines(l,"clearCoatGloss","clearCoatGlossPS",s,a.chunks,o),this._addMapDefines(l,"clearCoatNormal","clearCoatNormalPS",s,a.chunks,o,s.clearCoatPackedNormal?"xy":"xyz")),s.litOptions.enableGGXSpecular&&this._addMapDefines(l,"anisotropy","anisotropyPS",s,a.chunks,o),(s.lightMap||s.lightVertexColor)&&this._addMapDefines(l,"light","lightmapPS",s,a.chunks,o,s.lightMapEncoding)}else{let p=s.litOptions.opacityShadowDither;(s.litOptions.alphaTest||p)&&this._addMapDefines(l,"opacity","opacityPS",s,a.chunks,o)}a.generateFragmentShader(a.chunks.get("stdDeclarationPS"),a.chunks.get("stdFrontEndPS"),h);let f=Ha.merge(a.chunks,a.includes),u=a.vDefines;s.defines.forEach((p,m)=>u.set(m,p)),s.defines.forEach((p,m)=>l.set(m,p));let d=ns.createDefinition(e,{name:"StandardShader",attributes:a.attributes,shaderLanguage:a.shaderLanguage,vertexCode:a.vshader,fragmentCode:a.fshader,vertexIncludes:f,fragmentIncludes:f,fragmentDefines:l,vertexDefines:u});return a.shaderPassInfo.isForward&&(d.tag=Cg),d}},GT=new Kw;var sr=[];sr[rp]={src:1,dst:1,op:2};sr[wt]={src:1,dst:0,op:0};sr[ls]={src:6,dst:8,op:0,alphaSrc:1};sr[Ms]={src:1,dst:8,op:0};sr[ea]={src:1,dst:1,op:0};sr[op]={src:6,dst:1,op:0};sr[np]={src:4,dst:2,op:0};sr[lp]={src:5,dst:1,op:0};sr[ap]={src:4,dst:0,op:0};sr[cp]={src:1,dst:1,op:3};sr[hp]={src:1,dst:1,op:4};var XY=0,Us=class c{constructor(){n(this,"meshInstances",new Set);n(this,"name","Untitled");n(this,"userId","");n(this,"id",XY++);n(this,"variants",new Map);n(this,"defines",new Map);n(this,"_definesDirty",!1);n(this,"parameters",{});n(this,"alphaTest",0);n(this,"alphaToCoverage",!1);n(this,"_blendState",new Oe);n(this,"_depthState",new Pt);n(this,"cull",1);n(this,"frontFace",0);n(this,"stencilFront",null);n(this,"stencilBack",null);n(this,"_shaderChunks",null);n(this,"_oldChunks",{});n(this,"_dirtyShader",!0);n(this,"_shaderVersion",0);n(this,"_scene",null);n(this,"dirty",!0);new.target}get hasShaderChunks(){return this._shaderChunks!=null}get shaderChunks(){return this._shaderChunks||(this._shaderChunks=new ne),this._shaderChunks}getShaderChunks(t=fe){let e=this.shaderChunks;return t===fe?e.glsl:e.wgsl}set shaderChunksVersion(t){this.shaderChunks.version=t}get shaderChunksVersion(){return this.shaderChunks.version}set chunks(t){this._oldChunks=t}get chunks(){return Object.assign(this._oldChunks,Object.fromEntries(this.shaderChunks.glsl)),this._oldChunks}set depthBias(t){this._depthState.depthBias=t}get depthBias(){return this._depthState.depthBias}set slopeDepthBias(t){this._depthState.depthBiasSlope=t}get slopeDepthBias(){return this._depthState.depthBiasSlope}set redWrite(t){this._blendState.redWrite=t}get redWrite(){return this._blendState.redWrite}set greenWrite(t){this._blendState.greenWrite=t}get greenWrite(){return this._blendState.greenWrite}set blueWrite(t){this._blendState.blueWrite=t}get blueWrite(){return this._blendState.blueWrite}set alphaWrite(t){this._blendState.alphaWrite=t}get alphaWrite(){return this._blendState.alphaWrite}get transparent(){return this._blendState.blend}_updateTransparency(){for(let t of this.meshInstances)t.transparent=this.transparent}set blendState(t){this._blendState.copy(t),this._updateTransparency()}get blendState(){return this._blendState}set blendType(t){let e=sr[t];this._blendState.setColorBlend(e.op,e.src,e.dst),this._blendState.setAlphaBlend(e.alphaOp??e.op,e.alphaSrc??e.src,e.alphaDst??e.dst);let s=t!==wt;this._blendState.blend!==s&&(this._blendState.blend=s,this._updateTransparency()),this._updateMeshInstanceKeys()}get blendType(){if(!this.transparent)return wt;let{colorOp:t,colorSrcFactor:e,colorDstFactor:s,alphaOp:i,alphaSrcFactor:r,alphaDstFactor:a}=this._blendState;for(let o=0;othis.defines.set(s,e)),this._shaderChunks=t.hasShaderChunks?new ne:null,this._shaderChunks?.copy(t._shaderChunks),this}clone(){return new this.constructor().copy(this)}_updateMeshInstanceKeys(){for(let t of this.meshInstances)t.updateKey()}updateUniforms(t,e){this._dirtyShader&&(this.clearVariants(),this._dirtyShader=!1)}getShaderVariant(t){}update(){if(Object.keys(this._oldChunks).length>0)for(let[t,e]of Object.entries(this._oldChunks))this.shaderChunks.glsl.set(t,e),delete this._oldChunks[t];(this._definesDirty||this._shaderChunks?.isDirty())&&(this._definesDirty=!1,this._shaderChunks?.resetDirty(),this.clearVariants()),this.dirty=!0}clearParameters(){this.parameters={}}getParameters(){return this.parameters}clearVariants(){this.variants.clear();for(let t of this.meshInstances)t.clearShaders()}getParameter(t){return this.parameters[t]}_setParameterSimple(t,e){let s=this.parameters[t];s?s.data=e:this.parameters[t]={scopeId:null,data:e}}setParameter(t,e){if(e===void 0&&typeof t=="object"){let s=t;if(s.length){for(let i=0;i0,t.blendType=e.blendType,t.screenSpace=i&&(i&Ec)!==0,t.skin=i&&(i&Uo)!==0,t.useInstancing=i&&(i&ko)!==0,t.useMorphPosition=i&&(i&zo)!==0,t.useMorphNormal=i&&(i&Go)!==0,t.useMorphTextureBasedInt=i&&(i&Vo)!==0,t.hasTangents=i&&(i&Nf)!==0,t.nineSlicedMode=e.nineSlicedMode||Ti,e.useLighting&&s.clusteredLightingEnabled?(t.clusteredLightingEnabled=!0,t.clusteredLightingCookiesEnabled=s.lighting.cookiesEnabled,t.clusteredLightingShadowsEnabled=s.lighting.shadowsEnabled,t.clusteredLightingShadowType=s.lighting.shadowType,t.clusteredLightingAreaLightsEnabled=s.lighting.areaLightsEnabled):(t.clusteredLightingEnabled=!1,t.clusteredLightingCookiesEnabled=!1,t.clusteredLightingShadowsEnabled=!1,t.clusteredLightingAreaLightsEnabled=!1)}static updateMaterialOptions(t,e){t.separateAmbient=!1,t.pixelSnap=e.pixelSnap,t.ambientSH=e.ambientSH,t.twoSidedLighting=e.twoSidedLighting,t.occludeDirect=e.occludeDirect,t.occludeSpecular=e.occludeSpecular,t.occludeSpecularFloat=e.occludeSpecularIntensity!==1,t.useMsdf=!1,t.msdfTextAttribute=!1,t.alphaToCoverage=e.alphaToCoverage,t.opacityFadesSpecular=e.opacityFadesSpecular,t.opacityDither=e.opacityDither,t.cubeMapProjection=pp,t.useSpecular=e.hasSpecular,t.useSpecularityFactor=e.hasSpecularityFactor,t.enableGGXSpecular=e.ggxSpecular,t.useAnisotropy=!1,t.fresnelModel=e.fresnelModel,t.useRefraction=e.hasRefraction,t.useClearCoat=e.hasClearCoat,t.useSheen=e.hasSheen,t.useIridescence=e.hasIrridescence,t.useMetalness=e.hasMetalness,t.useDynamicRefraction=e.dynamicRefraction,t.dispersion=e.dispersion>0,t.vertexColors=!1,t.lightMapEnabled=e.hasLighting,t.dirLightMapEnabled=e.dirLightMap,t.useHeights=e.hasHeights,t.useNormals=e.hasNormals,t.useClearCoatNormals=e.hasClearCoatNormals,t.useAo=e.hasAo,t.diffuseMapEnabled=e.hasDiffuseMap}static updateEnvOptions(t,e,s,i){t.fog=e.useFog?i.fog:Mi,t.gamma=i.shaderOutputGamma,t.toneMap=e.useTonemap?i.toneMapping:Rf,e.useSkybox&&s.envAtlas&&s.skybox?(t.reflectionSource=Lf,t.reflectionEncoding=s.envAtlas.encoding,t.reflectionCubemapEncoding=s.skybox.encoding):e.useSkybox&&s.envAtlas?(t.reflectionSource=Df,t.reflectionEncoding=s.envAtlas.encoding):e.useSkybox&&s.skybox?(t.reflectionSource=Mf,t.reflectionEncoding=s.skybox.encoding):(t.reflectionSource=gr,t.reflectionEncoding=null),e.ambientSH?(t.ambientSource=mp,t.ambientEncoding=null):t.reflectionSource!==gr&&s.envAtlas?(t.ambientSource=_p,t.ambientEncoding=s.envAtlas.encoding):(t.ambientSource=gp,t.ambientEncoding=null);let r=t.reflectionSource!==gr;t.skyboxIntensity=r,t.useCubeMapRotation=r&&s._skyboxRotationShaderInclude}static updateLightingOptions(t,e,s,i,r){if(t.lightMapWithoutAmbient=!1,e.useLighting){let a=[],o=i?i>>16:cs;t.lightMaskDynamic=!!(o&cs),t.lightMapWithoutAmbient=!1,r&&(c.collectLights(Ce,r[Ce],a,o),s.clusteredLightingEnabled||(c.collectLights(We,r[We],a,o),c.collectLights(je,r[je],a,o))),t.lights=a}else t.lights=[];(t.lights.length===0&&!s.clusteredLightingEnabled||(i&Tc)!==0)&&(t.noShadow=!0)}static collectLights(t,e,s,i){for(let r=0;r{if(c.length!==t.length)return!1;for(let e=0;ec.r!==1||c.g!==1||c.b!==1,KY=c=>c.r!==0||c.g!==0||c.b!==0,VT=class{constructor(){this._mapXForms=null}updateMinRef(t,e,s,i,r,a){this._updateSharedOptions(t,e,s,i,r),this._updateMinOptions(t,s,r),this._updateUVOptions(t,s,i,!0)}updateRef(t,e,s,i,r,a,o){this._updateSharedOptions(t,e,i,r,a),this._updateEnvOptions(t,i,e,s),this._updateMaterialOptions(t,i,e),t.litOptions.hasTangents=r&&(r&Nf)!==0,this._updateLightOptions(t,e,i,r,o),this._updateUVOptions(t,i,r,!1,s)}_updateSharedOptions(t,e,s,i,r){t.forceUv1=s.forceUv1,s.userAttributes&&(t.litOptions.userAttributes=Object.fromEntries(s.userAttributes.entries())),t.litOptions.shaderChunks=s.shaderChunks,t.litOptions.pass=r,t.litOptions.alphaTest=s.alphaTest>0,t.litOptions.blendType=s.blendType,t.litOptions.screenSpace=i&&(i&Ec)!==0,t.litOptions.skin=i&&(i&Uo)!==0,t.litOptions.batch=i&&(i&Uf)!==0,t.litOptions.useInstancing=i&&(i&ko)!==0,t.litOptions.useMorphPosition=i&&(i&zo)!==0,t.litOptions.useMorphNormal=i&&(i&Go)!==0,t.litOptions.useMorphTextureBasedInt=i&&(i&Vo)!==0,t.litOptions.nineSlicedMode=s.nineSlicedMode||0,e.clusteredLightingEnabled&&s.useLighting?(t.litOptions.clusteredLightingEnabled=!0,t.litOptions.clusteredLightingCookiesEnabled=e.lighting.cookiesEnabled,t.litOptions.clusteredLightingShadowsEnabled=e.lighting.shadowsEnabled,t.litOptions.clusteredLightingShadowType=e.lighting.shadowType,t.litOptions.clusteredLightingAreaLightsEnabled=e.lighting.areaLightsEnabled):(t.litOptions.clusteredLightingEnabled=!1,t.litOptions.clusteredLightingCookiesEnabled=!1,t.litOptions.clusteredLightingShadowsEnabled=!1,t.litOptions.clusteredLightingAreaLightsEnabled=!1)}_updateUVOptions(t,e,s,i,r){let a=!1,o=!1,l=!1;s&&(a=(s&Of)!==0,o=(s&$g)!==0,l=(s&Zg)!==0),t.litOptions.vertexColors=!1,this._mapXForms=[];let h={};for(let f in Dc)this._updateTexOptions(t,e,f,a,o,l,i,h);this._mapXForms=null,t.litOptions.ssao=r?.ssaoEnabled,t.useAO=t.litOptions.ssao,t.litOptions.lightMapEnabled=t.lightMap,t.litOptions.dirLightMapEnabled=t.dirLightMap,t.litOptions.useHeights=t.heightMap,t.litOptions.useNormals=t.normalMap,t.litOptions.useClearCoatNormals=t.clearCoatNormalMap,t.litOptions.useAo=t.aoMap||t.aoVertexColor||t.litOptions.ssao,t.litOptions.diffuseMapEnabled=t.diffuseMap}_updateTexOptions(t,e,s,i,r,a,o,l){let h=s==="opacity";if(!o||h){let f=`${s}Map`,u=`${s}VertexColor`,d=`${s}VertexColorChannel`,p=`${f}Channel`,m=`${f}Transform`,_=`${f}Uv`,S=`${f}Identifier`;if(s!=="light"&&(t[f]=!1,t[S]=void 0,t[p]="",t[m]=0,t[_]=0),t[u]=!1,t[d]="",h&&e.blendType===wt&&e.alphaTest===0&&!e.alphaToCoverage&&e.opacityDither===Bi)return;if(s!=="height"&&e[u]&&a&&(t[u]=e[u],t[d]=e[d],t.litOptions.vertexColors=!0),e[f]){let g=!0;if(e[_]===0&&!i&&(g=!1),e[_]===1&&!r&&(g=!1),g){let T=e[f].id,C=l[T];C===void 0&&(l[T]=s,C=s),t[f]=!!e[f],t[S]=C,t[m]=this._getMapTransformID(e.getUniform(m),e[_]),t[p]=e[p],t[_]=e[_]}}}}_updateMinOptions(t,e,s){let i=s===xr;t.litOptions.opacityShadowDither=i?e.opacityDither:e.opacityShadowDither,t.litOptions.linearDepth=i,t.litOptions.lights=[]}_updateMaterialOptions(t,e,s){let i=!!(e.useMetalness||e.specularMap||e.sphereMap||e.cubeMap||KY(e.specular)||e.specularityFactor>0&&e.useMetalness||e.enableGGXSpecular||e.clearCoat>0),r=!e.useMetalness||e.useMetalnessSpecularColor,a=i&&(e.specularTint||YY(e.specular)),o=i&&e.useMetalnessSpecularColor&&(e.specularityFactorTint||e.specularityFactor!==1),l=f=>f?f.format===Gr||f.type===Rn:!1,h=(f,u)=>Math.abs(f-u)<1e-4;t.specularTint=a,t.specularityFactorTint=o,t.metalnessTint=e.useMetalness&&e.metalness<1,t.glossTint=!0,t.diffuseEncoding=e.diffuseMap?.encoding,t.diffuseDetailEncoding=e.diffuseDetailMap?.encoding,t.emissiveEncoding=e.emissiveMap?.encoding,t.lightMapEncoding=e.lightMap?.encoding,t.packedNormal=l(e.normalMap),t.refractionTint=!h(e.refraction,1),t.refractionIndexTint=!h(e.refractionIndex,1/1.5),t.thicknessTint=e.useDynamicRefraction&&e.thickness!==1,t.specularEncoding=e.specularMap?.encoding,t.sheenEncoding=e.sheenMap?.encoding,t.aoMapUv=e.aoUvSet,t.aoDetail=!!e.aoDetailMap,t.diffuseDetail=!!e.diffuseDetailMap,t.normalDetail=!!e.normalMap,t.normalDetailPackedNormal=l(e.normalDetailMap),t.diffuseDetailMode=e.diffuseDetailMode,t.aoDetailMode=e.aoDetailMode,t.clearCoatGloss=!!e.clearCoatGloss,t.clearCoatPackedNormal=l(e.clearCoatNormalMap),t.iorTint=!h(e.refractionIndex,1/1.5),s.forcePassThroughSpecular&&(t.specularEncoding="linear",t.sheenEncoding="linear"),t.iridescenceTint=e.iridescence!==1,t.glossInvert=e.glossInvert,t.sheenGlossInvert=e.sheenGlossInvert,t.clearCoatGlossInvert=e.clearCoatGlossInvert,t.useSpecularColor=r,t.litOptions.separateAmbient=!1,t.litOptions.pixelSnap=e.pixelSnap,t.litOptions.ambientSH=!!e.ambientSH,t.litOptions.twoSidedLighting=e.twoSidedLighting,t.litOptions.occludeSpecular=e.occludeSpecular,t.litOptions.occludeSpecularFloat=e.occludeSpecularIntensity!==1,t.litOptions.useMsdf=!!e.msdfMap,t.litOptions.msdfTextAttribute=!!e.msdfTextAttribute,t.litOptions.alphaToCoverage=e.alphaToCoverage,t.litOptions.opacityFadesSpecular=e.opacityFadesSpecular,t.litOptions.opacityDither=e.opacityDither,t.litOptions.cubeMapProjection=e.cubeMapProjection,t.litOptions.occludeDirect=e.occludeDirect,t.litOptions.useSpecular=i,t.litOptions.useSpecularityFactor=(o||!!e.specularityFactorMap)&&e.useMetalnessSpecularColor,t.litOptions.enableGGXSpecular=e.enableGGXSpecular,t.litOptions.useAnisotropy=e.enableGGXSpecular&&(e.anisotropyIntensity>0||!!e.anisotropyMap),t.litOptions.fresnelModel=e.fresnelModel,t.litOptions.useRefraction=(e.refraction||!!e.refractionMap)&&(e.useDynamicRefraction||t.litOptions.reflectionSource!==gr),t.litOptions.useClearCoat=!!e.clearCoat,t.litOptions.useSheen=e.useSheen,t.litOptions.useIridescence=e.useIridescence&&e.iridescence!==0,t.litOptions.useMetalness=e.useMetalness,t.litOptions.useDynamicRefraction=e.useDynamicRefraction,t.litOptions.dispersion=e.dispersion>0,t.litOptions.shadowCatcher=e.shadowCatcher,t.litOptions.useVertexColorGamma=e.vertexColorGamma}_updateEnvOptions(t,e,s,i){t.litOptions.fog=e.useFog?i.fog:Mi,t.litOptions.gamma=i.shaderOutputGamma,t.litOptions.toneMap=e.useTonemap?i.toneMapping:Rf;let r=!1;if(e.envAtlas&&e.cubeMap?(t.litOptions.reflectionSource=Lf,t.litOptions.reflectionEncoding=e.envAtlas.encoding,t.litOptions.reflectionCubemapEncoding=e.cubeMap.encoding):e.envAtlas?(t.litOptions.reflectionSource=Df,t.litOptions.reflectionEncoding=e.envAtlas.encoding):e.cubeMap?(t.litOptions.reflectionSource=Mf,t.litOptions.reflectionEncoding=e.cubeMap.encoding):e.sphereMap?(t.litOptions.reflectionSource=TT,t.litOptions.reflectionEncoding=e.sphereMap.encoding):e.useSkybox&&s.envAtlas&&s.skybox?(t.litOptions.reflectionSource=Lf,t.litOptions.reflectionEncoding=s.envAtlas.encoding,t.litOptions.reflectionCubemapEncoding=s.skybox.encoding,r=!0):e.useSkybox&&s.envAtlas?(t.litOptions.reflectionSource=Df,t.litOptions.reflectionEncoding=s.envAtlas.encoding,r=!0):e.useSkybox&&s.skybox?(t.litOptions.reflectionSource=Mf,t.litOptions.reflectionEncoding=s.skybox.encoding,r=!0):(t.litOptions.reflectionSource=gr,t.litOptions.reflectionEncoding=null),e.ambientSH)t.litOptions.ambientSource=mp,t.litOptions.ambientEncoding=null;else{let a=e.envAtlas||(e.useSkybox&&s.envAtlas?s.envAtlas:null);a&&!e.sphereMap?(t.litOptions.ambientSource=_p,t.litOptions.ambientEncoding=a.encoding):(t.litOptions.ambientSource=gp,t.litOptions.ambientEncoding=null)}t.litOptions.skyboxIntensity=r,t.litOptions.useCubeMapRotation=r&&s._skyboxRotationShaderInclude}_updateLightOptions(t,e,s,i,r){if(t.lightMap=!1,t.lightMapChannel="",t.lightMapUv=0,t.lightMapTransform=0,t.litOptions.lightMapWithoutAmbient=!1,t.dirLightMap=!1,i&&(t.litOptions.noShadow=(i&Tc)!==0,(i&yc)!==0&&(t.lightMapEncoding=e.lightmapPixelFormat===ce?"rgbm":"linear",t.lightMap=!0,t.lightMapChannel="rgb",t.lightMapUv=1,t.lightMapTransform=0,t.litOptions.lightMapWithoutAmbient=!s.lightMap,(i&Ff)!==0&&(t.dirLightMap=!0),(i&Bf)!==0&&(t.litOptions.lightMapWithoutAmbient=!1))),s.useLighting){let a=[],o=i?i>>16:cs;t.litOptions.lightMaskDynamic=!!(o&cs),r&&(Lc.collectLights(Ce,r[Ce],a,o),e.clusteredLightingEnabled||(Lc.collectLights(We,r[We],a,o),Lc.collectLights(je,r[je],a,o))),t.litOptions.lights=a}else t.litOptions.lights=[];t.litOptions.lights.length===0&&!e.clusteredLightingEnabled&&(t.litOptions.noShadow=!0)}_getMapTransformID(t,e){if(!t)return 0;let s=this._mapXForms[e];s||(s=[],this._mapXForms[e]=s);for(let i=0;i{this[`_${e}`]=WT[e].value()}),this._uniformCache={}}copy(e){return super.copy(e),Object.keys(WT).forEach(s=>{this[s]=e[s]}),this._alphaDither=e._alphaDither,this.userAttributes=new Map(e.userAttributes),this}setAttribute(e,s){this.userAttributes.set(s,e)}_setParameter(e,s){fS.add(e),this.setParameter(e,s)}_setParameters(e){e.forEach(s=>{this._setParameter(s.name,s.value)})}_processParameters(e){let s=this[e];s.forEach(i=>{fS.has(i)||delete this.parameters[i]}),this[e]=fS,fS=s,fS.clear()}_updateMap(e){let s=`${e}Map`,i=this[s];if(i){this._setParameter(`texture_${s}`,i);let r=`${s}Transform`,a=this.getUniform(r);a&&this._setParameters(a)}}_allocUniform(e,s){let i=this._uniformCache[e];return i||(i=s(),this._uniformCache[e]=i),i}getUniform(e,s,i){return XL[e](this,s,i)}updateUniforms(e,s){let i=l=>this.getUniform(l,e,s);this._setParameter("material_ambient",i("ambient")),this._setParameter("material_diffuse",i("diffuse")),this._setParameter("material_aoIntensity",this.aoIntensity);let r=this.specular.r!==1||this.specular.g!==1||this.specular.b!==1,a=!this.specularMap||this.specularTint||r;this.useMetalness?((!this.metalnessMap||this.metalness<1)&&this._setParameter("material_metalness",this.metalness),a&&this._setParameter("material_specular",i("specular")),(!this.specularityFactorMap||this.specularityFactorTint||this.specularityFactor!==1)&&this._setParameter("material_specularityFactor",this.specularityFactor),this._setParameter("material_sheen",i("sheen")),this._setParameter("material_sheenGloss",this.sheenGloss),this._setParameter("material_refractionIndex",this.refractionIndex)):a&&this._setParameter("material_specular",i("specular")),this.enableGGXSpecular&&(this._setParameter("material_anisotropyIntensity",this.anisotropyIntensity),this._setParameter("material_anisotropyRotation",[Math.cos(this.anisotropyRotation*R.DEG_TO_RAD),Math.sin(this.anisotropyRotation*R.DEG_TO_RAD)])),this.clearCoat>0&&(this._setParameter("material_clearCoat",this.clearCoat),this._setParameter("material_clearCoatGloss",this.clearCoatGloss),this._setParameter("material_clearCoatBumpiness",this.clearCoatBumpiness)),this._setParameter("material_gloss",this.gloss),this._setParameter("material_emissive",i("emissive")),this._setParameter("material_emissiveIntensity",this.emissiveIntensity),this.refraction>0&&this._setParameter("material_refraction",this.refraction),this.dispersion>0&&this._setParameter("material_dispersion",this.dispersion),this.useDynamicRefraction&&(this._setParameter("material_thickness",this.thickness),this._setParameter("material_attenuation",i("attenuation")),this._setParameter("material_invAttenuationDistance",this.attenuationDistance===0?0:1/this.attenuationDistance)),this.useIridescence&&(this._setParameter("material_iridescence",this.iridescence),this._setParameter("material_iridescenceRefractionIndex",this.iridescenceRefractionIndex),this._setParameter("material_iridescenceThicknessMin",this.iridescenceThicknessMin),this._setParameter("material_iridescenceThicknessMax",this.iridescenceThicknessMax)),this._setParameter("material_opacity",this.opacity);let o=this._opacity>0?this.alphaDither/this._opacity:1;this._setParameter("material_alphaDitherScale",o),this.opacityFadesSpecular===!1&&this._setParameter("material_alphaFade",this.alphaFade),this.occludeSpecular&&this._setParameter("material_occludeSpecularIntensity",this.occludeSpecularIntensity),this.cubeMapProjection===gT&&this._setParameter(i("cubeMapProjectionBox"));for(let l in Dc)this._updateMap(l);this.ambientSH&&this._setParameter("ambientSH[0]",this.ambientSH),this.normalMap&&this._setParameter("material_bumpiness",this.bumpiness),this.normalMap&&this.normalDetailMap&&this._setParameter("material_normalDetailMapBumpiness",this.normalDetailMapBumpiness),this.heightMap&&this._setParameter("material_heightMapFactor",i("heightMapFactor")),this.envAtlas&&this.cubeMap?(this._setParameter("texture_envAtlas",this.envAtlas),this._setParameter("texture_cubeMap",this.cubeMap)):this.envAtlas?this._setParameter("texture_envAtlas",this.envAtlas):this.cubeMap?this._setParameter("texture_cubeMap",this.cubeMap):this.sphereMap&&this._setParameter("texture_sphereMap",this.sphereMap),this._setParameter("material_reflectivity",this.reflectivity),this._processParameters("_activeParams"),super.updateUniforms(e,s)}updateEnvUniforms(e,s){!(this.envAtlas||this.cubeMap||this.sphereMap)&&this.useSkybox&&(s.envAtlas&&s.skybox?(this._setParameter("texture_envAtlas",s.envAtlas),this._setParameter("texture_cubeMap",s.skybox)):s.envAtlas?this._setParameter("texture_envAtlas",s.envAtlas):s.skybox&&this._setParameter("texture_cubeMap",s.skybox)),this._processParameters("_activeLightingParams")}getShaderVariant(e){let{device:s,scene:i,pass:r,objDefs:a,sortedLights:o,cameraShaderParams:l}=e;this.updateEnvUniforms(s,i);let h=Ns.get(s).getByIndex(r),f=r===ta||r===xr||h.isShadow,u=f?GT.optionsContextMin:GT.optionsContext;u.defines=Se.getCoreDefines(this,e),f?this.shaderOptBuilder.updateMinRef(u,i,this,a,r,o):this.shaderOptBuilder.updateRef(u,i,l,this,a,r,o),this.useFog||u.defines.set("FOG","NONE"),u.defines.set("TONEMAP",bf[u.litOptions.toneMap]),this.onUpdateShader&&(u=this.onUpdateShader(u));let d=new sa(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),p=Ji(s);return p.register("standard",GT),p.getProgram("standard",u,d,this.userId)}destroy(){for(let e in this._assetReferences)this._assetReferences[e]._unbind();this._assetReferences=null,super.destroy()}};n(it,"TEXTURE_PARAMETERS",qf),n(it,"CUBEMAP_PARAMETERS",hS);var XT=(c,t)=>{XL[c]=t},jw=(c,t,e,s)=>{Object.defineProperty(it.prototype,c,{get:s||function(){return this[`_${c}`]},set:e}),WT[c]={value:t}},jY=c=>{let t=`_${c.name}`,e=c.dirtyShaderFunc||(()=>!0),s=function(i){let r=this[t];r!==i&&(this._dirtyShader=this._dirtyShader||e(r,i),this[t]=i)};jw(c.name,()=>c.defaultValue,s,c.getterFunc)},qY=c=>{let t=`_${c.name}`,e=c.dirtyShaderFunc||(()=>!0),s=function(i){let r=this[t];r.equals(i)||(this._dirtyShader=this._dirtyShader||e(r,i),this[t]=r.copy(i))};jw(c.name,()=>c.defaultValue.clone(),s,c.getterFunc)},Er=c=>c.defaultValue&&c.defaultValue.clone?qY(c):jY(c);function Ht(c,t="rgb",e=!0,s=0){Dc[c]=t.length||-1,Er({name:`${c}Map`,defaultValue:null,dirtyShaderFunc:(l,h)=>!!l!=!!h||l&&(l.type!==h.type||l.format!==h.format)}),Er({name:`${c}MapTiling`,defaultValue:new B(1,1)}),Er({name:`${c}MapOffset`,defaultValue:new B(0,0)}),Er({name:`${c}MapRotation`,defaultValue:0}),Er({name:`${c}MapUv`,defaultValue:s}),t&&(Er({name:`${c}MapChannel`,defaultValue:t}),e&&(Er({name:`${c}VertexColor`,defaultValue:!1}),Er({name:`${c}VertexColorChannel`,defaultValue:t})));let i=`${c}MapTiling`,r=`${c}MapOffset`,a=`${c}MapRotation`,o=`${c}MapTransform`;XT(o,(l,h,f)=>{let u=l[i],d=l[r],p=l[a];if(u.x===1&&u.y===1&&d.x===0&&d.y===0&&p===0)return null;let m=l._allocUniform(o,()=>[{name:`texture_${o}0`,value:new Float32Array(3)},{name:`texture_${o}1`,value:new Float32Array(3)}]),_=Math.cos(p*R.DEG_TO_RAD),S=Math.sin(p*R.DEG_TO_RAD),g=m[0].value;g[0]=_*u.x,g[1]=-S*u.y,g[2]=d.x;let T=m[1].value;return T[0]=S*u.x,T[1]=_*u.y,T[2]=1-u.y-d.y,m})}function Mp(c,t){Er({name:c,defaultValue:t,getterFunc:function(){return this._dirtyShader=!0,this[`_${c}`]}}),XT(c,(e,s,i)=>{let r=e._allocUniform(c,()=>new Float32Array(3)),a=e[c];return HT.linear(a),r[0]=HT.r,r[1]=HT.g,r[2]=HT.b,r})}function vt(c,t,e){Er({name:c,defaultValue:t,dirtyShaderFunc:(s,i)=>(s===0||s===1)!=(i===0||i===1)}),XT(c,e)}function uS(c,t){Er({name:c,defaultValue:null,dirtyShaderFunc:(e,s)=>!!e==!!s}),XT(c,t)}function lt(c,t){Er({name:c,defaultValue:t})}function $Y(){Mp("ambient",new F(1,1,1)),Mp("diffuse",new F(1,1,1)),Mp("specular",new F(0,0,0)),Mp("emissive",new F(0,0,0)),Mp("sheen",new F(1,1,1)),Mp("attenuation",new F(1,1,1)),vt("emissiveIntensity",1),vt("specularityFactor",1),vt("sheenGloss",0),vt("gloss",.25),vt("aoIntensity",1),vt("heightMapFactor",1,(s,i,r)=>s.heightMapFactor*.025),vt("opacity",1),vt("alphaFade",1),Er({name:"alphaDither",defaultValue:null,dirtyShaderFunc:()=>!1,getterFunc:function(){return this._alphaDither??this._opacity}}),vt("alphaTest",0),vt("bumpiness",1),vt("normalDetailMapBumpiness",1),vt("reflectivity",1),vt("occludeSpecularIntensity",1),vt("refraction",0),vt("refractionIndex",1/1.5,(s,i,r)=>Math.max(.001,s.refractionIndex)),vt("dispersion",0),vt("thickness",0),vt("attenuationDistance",0),vt("metalness",1),vt("anisotropyIntensity",0),vt("anisotropyRotation",0),vt("clearCoat",0),vt("clearCoatGloss",1),vt("clearCoatBumpiness",1),vt("aoUvSet",0,null),vt("iridescence",0),vt("iridescenceRefractionIndex",1/1.5),vt("iridescenceThicknessMin",0),vt("iridescenceThicknessMax",0),uS("ambientSH"),uS("cubeMapProjectionBox",(s,i,r)=>{let a=s._allocUniform("cubeMapProjectionBox",()=>[{name:"envBoxMin",value:new Float32Array(3)},{name:"envBoxMax",value:new Float32Array(3)}]),o=s.cubeMapProjectionBox.getMin(),l=a[0].value;l[0]=o.x,l[1]=o.y,l[2]=o.z;let h=s.cubeMapProjectionBox.getMax(),f=a[1].value;return f[0]=h.x,f[1]=h.y,f[2]=h.z,a}),lt("specularTint",!1),lt("specularityFactorTint",!1),lt("useMetalness",!1),lt("useMetalnessSpecularColor",!1),lt("useSheen",!1),lt("enableGGXSpecular",!1),lt("occludeDirect",!1),lt("opacityFadesSpecular",!0),lt("occludeSpecular",Bo),lt("fresnelModel",Sc),lt("useDynamicRefraction",!1),lt("cubeMapProjection",pp),lt("useFog",!0),lt("useLighting",!0),lt("useTonemap",!0),lt("useSkybox",!0),lt("forceUv1",!1),lt("pixelSnap",!1),lt("twoSidedLighting",!1),lt("nineSlicedMode",void 0),lt("msdfTextAttribute",!1),lt("useIridescence",!1),lt("glossInvert",!1),lt("sheenGlossInvert",!1),lt("clearCoatGlossInvert",!1),lt("opacityDither",Bi),lt("opacityShadowDither",Bi),lt("shadowCatcher",!1),lt("vertexColorGamma",!1),Ht("diffuse"),Ht("specular"),Ht("emissive"),Ht("thickness","g"),Ht("specularityFactor","g"),Ht("normal",""),Ht("metalness","g"),Ht("gloss","g"),Ht("opacity","a"),Ht("refraction","g"),Ht("height","g",!1),Ht("ao","g"),Ht("light","rgb",!0,1),Ht("msdf",""),Ht("diffuseDetail","rgb",!1),Ht("normalDetail",""),Ht("aoDetail","g",!1),Ht("clearCoat","g"),Ht("clearCoatGloss","g"),Ht("clearCoatNormal",""),Ht("sheen","rgb"),Ht("sheenGloss","g"),Ht("iridescence","g"),Ht("iridescenceThickness","g"),Ht("anisotropy",""),lt("diffuseDetailMode",ST),lt("aoDetailMode",ST),uS("cubeMap"),uS("sphereMap"),uS("envAtlas");let c=function(){return this._prefilteredCubemaps},t=function(s){let i=this._prefilteredCubemaps;s=s||[];let r=!1,a=!0;for(let o=0;o<6;++o){let l=s[o]||null;i[o]!==l&&(i[o]=l,r=!0),a=a&&!!i[o]}r&&(a?this.envAtlas=bc.generatePrefilteredAtlas(i,{target:this.envAtlas}):this.envAtlas&&(this.envAtlas.destroy(),this.envAtlas=null),this._dirtyShader=!0)},e=[null,null,null,null,null,null];jw("prefilteredCubemaps",()=>e.slice(),t,c)}$Y();var ZY="muPIHORMLNDCz4DxVR/ZvYfAUVEFR47KRIC4nwAAAAAP7WxlhD6Ci+2HCe7BF8jRAPZwdH2UPpI5PdLCJdkvG4UTaNDJ/0crAzne71GCrb4kbdMjjCEGzdX6fNxDMLJq5xkeoIVTdfiZkodEeArmZmp/FQzFjD4x8iOW7Dg64n+3mWqyEwLxXT8zoJXfbw8QJKDCaarUYyTlMzNFHbgUe9IQV7g4YOgtSKpIFZJ0qERm7u4PpmiF89ktHWCywaGmD6h+hfh2/Zd8KYlKqqo4Cem4T42bT/Z9FpCQF1hhSjfBzZ5XFn/y3jegWC6u86KuELRundQS/1Rp+XuKKGIgRv3CvP5y749yqLlFO495JOT3+f2CXgd71npU0/KjjpkZucbJ5m78IVyuSrSozc9jgBUhDrz0hFsyb7LFUH9//wJbBgLdNWJZObfKxrNt8TliLA9w9sXFv6g26iXpf6r/BqcAusj/QzGBZuoUGeEtw8BCXCZ3jUiw4hvM18ZVqlUD3C40LAFXW6FRjuAZGRNstb0/qVk4skwyT+MHrvRorI4rKHVMWZmKyAkzL/78u/9pMQuX14pZN50b2PHn6fRxeaCQLsfT4dpvIkWWFuFVENZIh+8xgR6lU+85W0PPdAu1j99kcCG40JBQa4JMyRzq6qriOBLtqF87vpCJan0WEduVr/mOYkS00urVA0mA6M3031+GmGmW48PaJDYOEIb3bIXWPaLoAOEinX1TN3+/vwhG6nqJu0TdHpedS7QsGZIoxH3nQYYjQP1jmbahlbNngw5ogsGk1y50XZyUmQBY+/JBJ3Unu4dApm+WmPwHPU9gLb+4mHh4BiY6M86pq+WeTyWdI3s0CXPEtHGXZ8zMZgUoyRomBi1VdazzuN+WOmQ9Pa0Z0tlNopUi8AJ4x2Xn4mmOKEbXLxlbVsWu8XhuDGYFOGCRVdSqDPXrHU5SDdUlti3k5///SBwzTMwK3L4a1H7w4lnpEas6////AfX8asyIBfeFXVJ3tgvxQ/blZuUKyIODIfr/UzdWNu7pciLBpdZRZ4pIfZ1R6szq+XNxkGG///8EZFpu7VHAhFWqHEOrB9unw+YQa5o8/9IR/V5/zq+986rJSyfgJKt2u9hxU1wzyQWPjJGvzG9+eWWxGFOHVKqI4jBQALwZZswesnvZ2UmmkEXdiRpz8B+oWE7PY70ZTMndisYSXg2TqoI+3y9BxbnY2Y4EfbdcRhAvG59NqDENNYbxKvK5HJfPG5M+Wi2AcpLVJrD6caiEOzgSoVNSgQK8fm2M3zGcF4xtClv/8Hs9oD7C3jitTATYNQxmKqKf1LhIxzf1bmfiNn7UKFmcJu4sLqVLwxGSue3taBEyknkw5hXTsUCvqmmL/f8n/w0giR7Hu/9EHvpkz3yuu64TioMkzdTJ30i0+hFnQqW1+v9mMwq+z9qGX0UFu9MomvVG2xod6vc12AAAAACq7sGa5qptFR0jF3nQt/D+7PibKYahaxP3hEixPbGi9nwNf2LAa7LkEZRKxzXeCD64Xpii5n+8Kpg8eHIv7AWXZltgMoGltmoJ0XGdOCL8WkzphvR9N2o3ARSZ42l5e5Pe4B58MCRlP3EKv+mcloknH+fto5BWsmEutW6KvjOVsznFCktkSczVk4aGvj9VXlRcLeDoKG8RkBgdcNG2bf8HUL4MT2DM+ar7NImJhKpxakX4Vk0CnP+/XNhl5UsP0lXgeZXPoDBMSW5An+DXlTCO5FQGwSPYwHLKYVIimEdAoVe49rQLaaNcye5LxU2/c5TijTgJtD5eQQIe1snxauj5jZsxJBUJdoP/zqpjqv8qBruoPsVsP8N44PCUW5Dd0DzqjSS/Dl5mI9cn1w2ndN/0KAEm1QAAAACwu6KM/083IBbH5bPa/9oHUwcU8I9v3j6/v18QYammrf+P6VL///8BrpuM3fOLCxaLNOFNF1zPbPYTP65ni6njft4eVcyrVXRQFrs52tr35StiSp55edVDCBC0H5rIfac6nzUwxQSt7y15QoKb+5zebEQUmVbrPjXuUa19Ey7sqXMiSUKHaw72PJKDdrutJoQr3u6lEYJ8K0MakWKj9zjTFi4X94TsKYco0GrLeB60M6D8M/80rhXUW8iMequg8y5F838WI0+gp3GBN5Kj/xIOxTWQuUaPV/LwvARr1VH93BFgGZR1MFW0Ua30GbYmdnAgo9VWy8SQtpDUgGE2r2zq2eTEMCL7sMKmE1hchVhuF/TCq9iXKEm86kzOf3Rp9ZnCxbpDUj+FKNxVyXe6pVZkRXv/m95SnB/EB8aME29N85MtAcDoXWlor8De2Q5Dg1tar+8wgiZufbMam81j//ASUohoR/zSh2KG4bvT6mkIPz6C5/98DC3LaWlaEZ1zA5JORZRu6J/a0GY285sEYzw71YqOT1ihAG0z5SDt1xNiDQWZdFpndArp6xWhqSDkRb4kSJEHb9liPvw7uLV/6i5MVf//A9Qjr8xkAEUh+KDI+zdtJ68d6MBOktg1iyp/SCq8O9f5pbamn1VVVQPRTWqNBvhQKa07s6P0lc9Luu/3gw4HeyOUfz8MxMwV4UQhua+t9cr4bz/nIB2wnDSK1K7I94M+s6C84htaX/CNlMQUSs2KJO+yaebfTbkNX5yWcqEJevo0vbKUiETuFXiL019A3E+lmsyZMwXrXLLiQAZ5t9+jI3JobhJTMiDH5ZOQ+8Jau5555NMjHSscP9qCVaa40doh+1a3Ukf6jqBmLddgh79/fwTfCyqiuldNkUoy+nUp+4nerwg0OjtGv2x485PJOJvUEokNhYIdWjpx7BWk0VZGWOp3jSFTJ2bnu6KCduZtG/UcBC9RZ3W/jMSfSMw4Etr/DoD/XYP2V5Ovw+YoM3F5g2dGLdvuG6ZkVGLE6Dk5Zr+sdSyGliJP1y2OFf/KFO0RWO+3gsGhesTnfZVpTd8/HwgO216gwaqo+vY3TljfJWowY+i0p0Os4SLn/1wLqDHMlszggmT/D8MRFzs+pLv6LNJSsNZ/r41mWi/rF6ZcKp/yzJdK0VU44hskq3RGpgO6mIpJDsf/mZkFrz0yYOMLbuaj/wp1v7JMFM5eqvBhmTd7U8frQAtHtys4zgpjZmzUhOVTfNNLifElGXADlqHGKrkBT/nYwX8ZRm3RjvyPvjKyEqEGKUpVnvOGx+NKPHiWM//ZDpDVGvvrjmk8RPF/wiYZD3+Us8YCXjrVOfjdd1UPAfjLp8jgSn4me7DPTpz1Ggy9XL80guFO7ECT10AvILKfD18Qx+KY/f8aRqu0oOO8hfKRFZa9PUJwCsp6VdZz6LFkm2b9Pl2LIifCwzRy7TpdG2uAtOxP2OemY26bJMa9ZGSLIRlMsgpDpnDJwd0oa5pQ13x1hrHf52HpulUWonGWsfXZbSQYKu9bnEN76ciQih0opN3deDVrbrxorfVlnCmL1R9zq3ePGWIv21c7pW8kEiFTM5JX8dAw867s/60cf79/BH+MDFCZBHlz1L+qGOJf/1txhhmrf3//As+RIJwevDb+fgNXVeHw67QptZegayhrEwr5Gy+EPo1RLaMtPbqOZYoVzXzwzjMFWZxyUG9YUIf6////AQWy84iAygLk9COtXt92+0mT/xg0zMzMBeLkb8y9SL2TDXgSX422hDgpGNLJyuPioA+YJ91G8znrpNqHkwYyscaJDEc9Vc+j4cXle3hvcd2JqDQH2lBZxDn6mUTs0b75raMvbs727codX01Anj8f3wir9P2xQaQ22v/TxCMglKDFoTjaP01XTLgxnTvPv02JgEUrW6UDgOnobFpLdvKdlypgIzPcq14fgXU5tvVW0FEs7VRlsG1IyA69fN4n+awHhT34cE+xUvdj86C8LgAsFheTjI9Ht9EyYAAAAAAVBVKRx2wLgUTI0/2QfyJo2riRw3JDqzEShmx/Lifo6mRkQVbS7X53t+EvKxcXogtdts31e9MRHdcHgsA8rt4/mt2unlzQ/wsU8Gu7+W6Oj7eD8EQdDp5XlCsVaS/AV/t5ZpPOHR3rGpyAJe9IPV+xMrBL1Oz/8MQhFs31h0N1cVnq371uqIJYHyafKH1jteAK3VpMXBcuC+yt0ZeKyRUY4QhdrJJ4tJ1wg3Hu6kDsbovxupTMkGdRrm8oZSoYPbJ+PwH/xotgTdkA1205vUEfnqkI04T/fnnd1fiZW5AwNcggd7fi4j5zasmcntZexIxqFZQMzMJpfndmI5jn17cgn5EV5t9XN0C///8Q9wlJpMGXdoiaMTG2sVyHQsn8mWRISCLNG777S0OuDRP2GlLcJ2UeOg7Fo8hTNPeJ//iTJhyqxhKRUntdXOihq2wfKfH///8B0GGrwT+fSOQRdctKxjjGCSS11d6BlQ9BDfE0J6Z25FaNTKGpFKNCMr2G/041KpWwBLVe1k08vncseQbKZdXi8x1t9XA45U/Wd43D9wAh3Tal0aiLVzGPusOZ1F+W3TWoqlX/A95+dNef11TsuGful+ctGssldk3fqpfqh+43XTxL42+leSHoF/dWHYGX6maqUEuLX7UB+r/6Llr4LKocbVIeu+hB9QTPfz9fCP8RyWmX4SmbhMFsNtCijV7lVcwejLKlvl0GfCndnWV7/39VBrtTRuUx92oke3GBgKkC5fdGK0YvNK+xenKaDmsHDjNFUM3NMz3ZiXXFuLgojosPVCDEl2W5BjX3Ms+j0GSqACHmh0+RPWyuNm/Qe8vFf9AW7N1uRaxWirrUytqEJnJ4/Flm8hSoiZ2NQBsS6w/yQlC4gCaFo8q4nyY6AFdo4hiwhBXzbNKKvZvktCjSCukRR/BbYVbNwZi2Yh3hGodEacLW8qijiWJODf0P2bhfaiPspPT4lYJBgi/KfcFwCfvyUIgkJOv///8CG/JEepRBLaMFE+2TgrqsJXOVOWHt6g/bFwVLLMVBsMR50dis/39/AlBX+/rMTJkUQrnlxpR2iu0Tp8tATkRYGmDIrcAiRP8PjoWIlb7/0ecTdSCE9Y58+a+n/FovJQTVF4F2jAxMZhTgrM/KVS5BQu6bVbkWY5HXnxRshks3urDdW4RkWp4M4TeLmFK5KF/uHkkiO5Kv96RioH984v/CSDBnG+BwlnU9B+o7Y+0X0Nob+0pLsStxjvPXMy2eCpzhOWV4XbObBHN4UE2sLQ/DIqXhOzxVf38GlTi6aG7EnePO7TRJm9yOfUUcqq1I2iQHrVDqn3TUNRi/lMw8KbMW/3/nqCz/Ef8PoW5Qxcz2yHR/f78EPB2Stbd+ZFmfNTUYILzsb9YNhpaHcaymYrBiNHmFE3Y4ccYJ25Prqm7zHobGHED8/93ZNlWro9vcKivGZs31UiK1k5zjUhexUgbqJb+fUTjxce/7Zly8a5KMC1fX5nfjPgibdvzbXV1jRT2asXvmSAusaLdq1TSIJ8fXINk5AtT34EWPAsfP9IFQqM5K11O6saoHJA==",il=null,YL=()=>{if(!il){let c=atob(ZY);il=Uint8Array.from(c,t=>t.charCodeAt(0))}},KL=()=>(YL(),il),Op=class{constructor(t=0){n(this,"seed",0);this.seed=t*4,YL()}_next(){this.seed=(this.seed+4)%il.length}value(){return this._next(),il[this.seed]/255}vec4(t=new Q){return this._next(),t.set(il[this.seed],il[this.seed+1],il[this.seed+2],il[this.seed+3]).mulScalar(1/255)}};var QY=[new x(-1,0,0),new x(1,0,0),new x(0,-1,0),new x(0,1,0),new x(0,0,-1),new x(0,0,1)],YT=class{constructor(){n(this,"colors",new Float32Array(18))}update(t,e){let s=this.colors,{r:i,g:r,b:a}=t;for(let o=0;o<6;o++)s[o*3]=i,s[o*3+1]=r,s[o*3+2]=a;for(let o=0;o{let i=new Z(c,{name:`${t}${e}`,width:e,height:e,format:ce,addressU:0,addressV:0,type:Gt,magFilter:0,minFilter:0,anisotropy:1,mipmaps:!1});return i.lock().set(s),i.unlock(),i},e6=new et,jL=c=>e6.get(c,()=>{let t=KL(),e=Math.sqrt(t.length/4);return JY(c,"BlueNoise",e,t)});var Xo=class c{constructor(t,e){this.texture=t,this.cached=!1,this.renderTargets=e}destroy(){this.texture&&(this.texture.destroy(),this.texture=null);let t=this.renderTargets;for(let e=0;er.length===a.length&&r.every((o,l)=>o===a[l]))(s,this.atlasSplit)){this.version++,this.slots.length=0,this.atlasSplit.length=0,this.atlasSplit.push(...s);let r=this.atlasSplit[0];if(r>1){let a=1/r;for(let o=0;o1)for(let u=0;uo.size-a.size)}}collectLights(t,e){let s=e.cookiesEnabled,i=e.shadowsEnabled,r=!1,a=!1,o=t6;return o.length=0,(s||i)&&(h=>{for(let f=0;ff.maxScreenSize-h.maxScreenSize),r&&this.allocateShadowAtlas(this.shadowAtlasResolution,e.shadowType),a&&this.allocateCookieAtlas(this.cookieAtlasResolution),(r||a)&&this.subdivide(o.length,e),o}setupSlot(t,e){t.atlasViewport.copy(e);let s=t.numShadowFaces;for(let i=0;i0){let i=this.slots;for(let o=0;o{t.forEach(e=>{e.destroy()})}),this.cache.clear()}getKey(t){let e=t._type===We,s=t._shadowType,i=t._shadowResolution;return`${e}-${s}-${i}`}get(t,e){let s=this.getKey(e),i=this.cache.get(s);if(i&&i.length)return i.pop();let r=Xo.create(t,e);return r.cached=!0,r}add(t,e){let s=this.getKey(t),i=this.cache.get(s);i?i.push(e):this.cache.set(s,[e])}};var Fp=class extends yt{constructor(t,e,s,i,r){super(t),this.requiresCubemaps=!1,this.shadowRenderer=e,this.light=s,this.face=i,this.applyVsm=r,this.shadowCamera=e.prepareFace(s,null,i),e.setupRenderPass(this,this.shadowCamera,!0)}execute(){this.shadowRenderer.renderFace(this.light,null,this.face,!1)}after(){this.applyVsm&&this.shadowRenderer.renderVsm(this.light,this.shadowCamera)}};var qT=class{constructor(t,e){n(this,"shadowLights",[]);n(this,"renderer");n(this,"shadowRenderer");n(this,"device");this.renderer=t,this.shadowRenderer=e,this.device=t.device}cull(t,e,s=null){let i=this.renderer.scene.clusteredLightingEnabled;t.visibleThisFrame=!0,i||t._shadowMap||(t._shadowMap=Xo.create(this.device,t));let r=t._type,a=r===je?1:6;for(let o=0;oi&&(i=a)}return $w.min=s,$w.max=i,$w}var QT=class{constructor(t,e){n(this,"renderer");n(this,"shadowRenderer");n(this,"device");this.renderer=t,this.shadowRenderer=e,this.device=t.device}cull(t,e,s,i=null){t.visibleThisFrame=!0,t._shadowMap||(t._shadowMap=Xo.create(this.device,t));let r=s._nearClip;this.generateSplitDistances(t,r,Math.min(s._farClip,t.shadowDistance));let a=t.shadowUpdateOverrides;for(let o=0;oS&&(S=L)}let g=f.right,T=f.up,C=f.forward,v=.25*t._shadowResolution/S,E=Math.ceil(al.dot(T)*v)/v,y=Math.ceil(al.dot(g)*v)/v,P=T.mulScalar(E),A=g.mulScalar(y),w=al.dot(C),I=C.mulScalar(w);al.add2(P,A).add(I),f.setPosition(al),f.translateLocal(0,0,1e6),h.nearClip=.01,h.farClip=2e6,h.orthoHeight=S,this.renderer.updateCameraFrustum(h),this.shadowRenderer.cullShadowCasters(e,t,l.visibleCasters,h,i);let D=1<1&&(!this.renderer.scene.clusteredLightingEnabled||t._type===Ce)&&this.applyVsmBlur(t,e)}getVsmBlurShader(t,e){let s=this.blurVsmShader,i=s[t][e];if(!i){this.blurVsmWeights[e]=a6(e);let r=new Map;r.set("{SAMPLES}",e),t===1&&r.set("GAUSS",""),i=Se.createShader(this.device,{uniqueName:`blurVsm${t}${e}`,attributes:{vertex_position:ee},vertexChunk:"fullscreenQuadVS",fragmentChunk:"blurVSMPS",fragmentDefines:r}),s[t][e]=i}return i}applyVsmBlur(t,e){let s=this.device;s.setBlendState(Oe.NOBLEND);let a=t.getRenderData(t._type===Ce?e:null,0).shadowCamera.renderTarget,o=this.renderer.shadowMapCache.get(s,t),l=o.renderTargets[0],h=t.vsmBlurMode,f=t._vsmBlurSize,u=this.getVsmBlurShader(h,f);pS.z=t._shadowResolution-2,pS.w=pS.z,this.sourceId.setValue(a.colorBuffer),$f[0]=1/t._shadowResolution,$f[1]=0,this.pixelOffsetId.setValue($f),h===Kg&&this.weightId.setValue(this.blurVsmWeights[f]),Qt(s,l,u,null,pS),this.sourceId.setValue(l.colorBuffer),$f[1]=$f[0],$f[0]=0,this.pixelOffsetId.setValue($f),Qt(s,a,u,null,pS),this.renderer.shadowMapCache.add(t,o)}initViewBindGroupFormat(){this.device.supportsUniformBuffers&&!this.viewUniformFormat&&(this.viewUniformFormat=new Xe(this.device,[new Y("matrix_viewProjection",as)]),this.viewBindGroupFormat=new Ue(this.device,[new Qe(Hn,Xi|Yi)]))}frameUpdate(){this.initViewBindGroupFormat()}};var Zf=class extends Nt{constructor(e){super(e);n(this,"children",[]);this.name="FramePassMultiView"}addChild(e){this.children.push(e)}render(){if(!this.enabled)return;let e=this.device,s=e.xrSubImages,i=s?.length??0,r=this.children,a=r.length;if(i===0){for(let u=0;u{t.destroy()}),this._allocated.length=0}get count(){return this._allocated.length}get empty(){if(!this._empty){let t=new sl(this.device);t.name="ClusterEmpty",t.update([]),this._empty=t}return this._empty}_assignClustersForPass(t){let e=t.renderActions;if(!e)return;let s=e.length;for(let i=0;is.destroy()),JT.length=0}update(t,e){this.assign(t),this._clusters.forEach(s=>{let i=s.layer;s.lightClusters.update(i.clusteredLightsSet,e)})}};var Oc=new Q,Qw=[],ty=class c extends yt{constructor(e,s){super(e);n(this,"_quadRenderer2D",null);n(this,"_quadRendererCube",null);n(this,"_filteredLights",[]);n(this,"_forceCopy",!1);n(this,"_evtDeviceRestored",null);this._cubeSlotsOffsets=s,this.requiresCubemaps=!1,this.blitTextureId=e.scope.resolve("blitTexture"),this.invViewProjId=e.scope.resolve("invViewProj"),this._evtDeviceRestored=e.on("devicerestored",this.onDeviceRestored,this)}destroy(){this._quadRenderer2D?.destroy(),this._quadRenderer2D=null,this._quadRendererCube?.destroy(),this._quadRendererCube=null,this._evtDeviceRestored?.off(),this._evtDeviceRestored=null}static create(e,s){let i=new c(e.device,s);return i.init(e),i.colorOps.clear=!1,i.depthStencilOps.clearDepth=!1,i}onDeviceRestored(){this._forceCopy=!0}update(e){let s=this._filteredLights;this.filter(e,s),this.executeEnabled=s.length>0}filter(e,s){for(let i=0;i1?this.quadRendererCube:this.quadRenderer2D;l>1&&this.initInvViewProjMatrices(),this.blitTextureId.setValue(o.cookie);for(let f=0;f1){let u=Oc.z/3,d=i[f];Oc.x+=u*d.x,Oc.y+=u*d.y,Oc.z=u,Oc.w=u,this.invViewProjId.setValue(Qw[f].data)}Oc.mulScalar(s),h.render(Oc)}}r.length=0}};var Bp=class extends yt{constructor(t,e,s){super(t),this.requiresCubemaps=!1,this.shadowRenderer=e,this.shadowRendererLocal=s}update(t){let e=this.shadowRendererLocal.shadowLights,s=this.shadowRendererLocal.prepareLights(e,t),i=e.length;this.enabled=i>0,i&&this.shadowRenderer.setupRenderPass(this,s,!1)}execute(){let t=this.shadowRendererLocal.shadowLights,e=t.length;for(let s=0;s0){let _=e?e.width:this.device.width,S=e?e.height:this.device.height,g=tM[this.device.renderVersion%tM.length];d=u*(g.x*2-1)/_,p=u*(g.y*2-1)/S,l=l6.copy(l),l.data[8]=d,l.data[9]=p,h=c6.copy(h),h.data[8]=d,h.data[9]=p,this.blueNoiseJitterVersion!==this.device.renderVersion&&(this.blueNoiseJitterVersion=this.device.renderVersion,this.blueNoise.vec4(this.blueNoiseJitterVec))}let m=u>0?this.blueNoiseJitterVec:Q.ZERO;if(this.blueNoiseJitterData[0]=m.x,this.blueNoiseJitterData[1]=m.y,this.blueNoiseJitterData[2]=m.z,this.blueNoiseJitterData[3]=m.w,this.blueNoiseJitterId.setValue(this.blueNoiseJitterData),this.projId.setValue(l.data),this.projSkyboxId.setValue(h.data),t.calculateTransform)t.calculateTransform(Fc,xp);else{let _=t._node.getPosition(),S=t._node.getRotation();Fc.setTRS(_,S,x.ONE)}this.viewInvId.setValue(Fc.data),Up.copy(Fc).invert(),this.viewId.setValue(Up.data),JL.setFromMat4(Up),this.viewId3.setValue(JL.data),Yo.mul2(l,Up),this.viewProjId.setValue(Yo.data),t._storeShaderMatrices(Yo,d,p,this.device.renderVersion),this.flipYId.setValue(s?-1:1),this.dispatchViewPos(t._node.getPosition()),t.frustum.setFromMat4(Yo)}this.tbnBasis.setValue(s?-1:1),this.cameraParamsId.setValue(t.fillShaderParams(this.cameraParams));let r=t.xr?.session?t.xr.views.list[0]:null,a=r?r.viewport.z:e?e.width:this.device.width,o=r?r.viewport.w:e?e.height:this.device.height;return a*=t.rect.z,o*=t.rect.w,this.viewportSize[0]=a,this.viewportSize[1]=o,this.viewportSize[2]=1/a,this.viewportSize[3]=1/o,this.viewportSizeId.setValue(this.viewportSize),this.exposureId.setValue(this.scene.physicalUnits?t.getExposure():this.scene.exposure),i}clear(t,e,s,i){let r=(e??t._clearColorBuffer?1:0)|(s??t._clearDepthBuffer?2:0)|(i??t._clearStencilBuffer?4:0);if(r){let a=this.device,o=t._clearColor;mS[0]=o.r,mS[1]=o.g,mS[2]=o.b,mS[3]=o.a,iy.depth=t._clearDepth,iy.stencil=t._clearStencil,iy.flags=r,a.clear(iy)}}setupCullModeAndFrontFace(t,e,s){let i=s.material,r=e*s.flipFacesFactor*s.node.worldScaleSign,a=i.frontFace;r<0&&(a=a===0?1:0),this.device.setCullMode(t?i.cull:0),this.device.setFrontFace(a)}setupCullMode(t,e,s){this.setupCullModeAndFrontFace(t,e,s)}updateCameraFrustum(t){if(t.xr&&t.xr.views.list.length){let s=t.xr.views.list;Yo.mul2(s[0].projMat,s[0].viewOffMat),t.frustum.setFromMat4(Yo);for(let i=1;i0)&&this.alphaTestId.setValue(e.alphaTest)}updateCpuSkinMatrices(t){Jw++;let e=t.length;if(e!==0)for(let s=0;s{t.defaultUniformBuffer.destroy(),t.destroy()}),this.viewBindGroups.length=0}setupClears(t,e){this.clearColor=t?.clearColorBuffer||e.clearColorBuffer,this.clearDepth=t?.clearDepthBuffer||e.clearDepthBuffer,this.clearStencil=t?.clearStencilBuffer||e.clearStencilBuffer}};var Ya=class extends yt{constructor(e,s,i,r){super(e);n(this,"layerComposition");n(this,"scene");n(this,"renderer");n(this,"renderActions",[]);n(this,"gammaCorrection");n(this,"toneMapping");n(this,"noDepthClear",!1);this.layerComposition=s,this.scene=i,this.renderer=r}get rendersAnything(){return this.renderActions.length>0}addRenderAction(e){this.renderActions.push(e)}addLayer(e,s,i,r=!0){let a=new zp;if(a.renderTarget=this.renderTarget,a.camera=e,a.layer=s,a.transparent=i,r){let o=this.renderActions.length===0;a.setupClears(o?e:void 0,s)}this.addRenderAction(a)}addLayers(e,s,i,r,a,o=!0){let{layerList:l,subLayerList:h}=e,f=r,u=i;for(;u{Qf.drawCalls.push(T),Qf.shaderInstances.push(C),Qf.isNewMaterial.push(v),Qf.lightMaskChanged.push(E)};Qf.clear();let f=this.device,u=this.scene,d=u.clusteredLightingEnabled,p=r?.getLightHash(d)??0,m=null,_,S,g=s.length;for(let T=0;T=0?m:0,S=p&&m>=0?m+1:p?p.length:0,g=e.drawCalls.length;for(let T=0;T{t.addRenderPass(p)}),d&&t.endMultiView();else{let p=f.id===Zt,m=p&&(u.renderSceneColorMap||u.renderSceneDepthMap);r&&(r=!1,i=l,a=h.renderTarget);let _=o[l+1],g=(_?!_.useCameraPasses&&_.layer.id===Zt:!1)&&(u.renderSceneColorMap||u.renderSceneDepthMap),T=_?_.firstCameraUse&&this.cameraDirShadowLights.has(_.camera.camera):!1;if(!_||_.renderTarget!==a||_.camera!==u||T||g||m){let C=p&&i===l;if(d&&(u.renderSceneColorMap||u.renderSceneDepthMap||h.triggerPostprocess&&u?.onPostprocessing),d&&t.beginMultiView(this.device),C||this.addMainRenderPass(t,e,a,i,l),p){if(u.renderSceneColorMap){let v=u.camera.renderPassColorGrab;v.source=u.renderTarget,t.addRenderPass(v)}u.renderSceneDepthMap&&t.addRenderPass(u.camera.renderPassDepthGrab)}if(h.triggerPostprocess&&u?.onPostprocessing){let v=new ay(this.device,this,h);t.addRenderPass(v)}d&&t.endMultiView(),r=!0}}}}_isMultiview(t){let e=t.camera?.xr;return this.device.isWebGPU&&!!e?.session&&e.views.list.length>=2}addMainRenderPass(t,e,s,i,r){let a=new Ya(this.device,e,this.scene,this);a.init(s);let o=e._renderActions;for(let l=i;l<=r;l++)a.addRenderAction(o[l]);t.addRenderPass(a)}update(t){this.frameUpdate(),this.shadowRenderer.frameUpdate(),this.scene._updateSkyMesh(),this.updateLayerComposition(t),this.collectLights(t),this.beginFrame(t),this.setSceneConstants(),this.gsplatDirector?.update(t),this.cullComposition(t),this.gpuUpdate(this.processingMeshInstances)}};var oI=0,_S=[],oy=new Set;function d6(c,t){return c.drawOrder-t.drawOrder}function p6(c,t){let e=c._sortKeyForward,s=t._sortKeyForward;return e===s?t.mesh.id-c.mesh.id:s-e}function m6(c,t){return t._sortKeyDynamic-c._sortKeyDynamic}function _6(c,t){return c._sortKeyDynamic-t._sortKeyDynamic}var g6=[null,d6,p6,m6,_6],nI=class{constructor(){n(this,"opaque",[]);n(this,"transparent",[])}},Dt=class{constructor(t={}){n(this,"id");n(this,"name");n(this,"_enabled",!0);n(this,"_refCounter",1);n(this,"opaqueSortMode",yT);n(this,"transparentSortMode",Jg);n(this,"customSortCallback",null);n(this,"customCalculateSortValues",null);n(this,"_clearColorBuffer",!1);n(this,"_clearDepthBuffer",!1);n(this,"_clearStencilBuffer",!1);n(this,"onEnable");n(this,"onDisable");n(this,"meshInstances",[]);n(this,"meshInstancesSet",new Set);n(this,"shadowCasters",[]);n(this,"shadowCastersSet",new Set);n(this,"_visibleInstances",new WeakMap);n(this,"_lights",[]);n(this,"_lightsSet",new Set);n(this,"_clusteredLightsSet",new Set);n(this,"_splitLights",[[],[],[]]);n(this,"_splitLightsDirty",!0);n(this,"_lightHash",0);n(this,"_lightHashDirty",!1);n(this,"_lightIdHash",0);n(this,"_lightIdHashDirty",!1);n(this,"requiresLightCube",!1);n(this,"cameras",[]);n(this,"camerasSet",new Set);n(this,"gsplatPlacements",[]);n(this,"gsplatPlacementsSet",new Set);n(this,"gsplatShadowCasters",[]);n(this,"gsplatShadowCastersSet",new Set);n(this,"gsplatPlacementsDirty",!0);n(this,"_dirtyComposition",!1);n(this,"_shaderVersion",-1);t.id!==void 0?(this.id=t.id,oI=Math.max(this.id+1,oI)):this.id=oI++,this.name=t.name,this._enabled=t.enabled??!0,this._refCounter=this._enabled?1:0,this.opaqueSortMode=t.opaqueSortMode??yT,this.transparentSortMode=t.transparentSortMode??Jg,this._clearColorBuffer=!!t.clearColorBuffer,this._clearDepthBuffer=!!t.clearDepthBuffer,this._clearStencilBuffer=!!t.clearStencilBuffer,this.onEnable=t.onEnable,this.onDisable=t.onDisable,this._enabled&&this.onEnable&&this.onEnable()}set enabled(t){t!==this._enabled&&(this._dirtyComposition=!0,this.gsplatPlacementsDirty=!0,this._enabled=t,t?(this.incrementCounter(),this.onEnable&&this.onEnable()):(this.decrementCounter(),this.onDisable&&this.onDisable()))}get enabled(){return this._enabled}set clearColorBuffer(t){this._clearColorBuffer=t,this._dirtyComposition=!0}get clearColorBuffer(){return this._clearColorBuffer}set clearDepthBuffer(t){this._clearDepthBuffer=t,this._dirtyComposition=!0}get clearDepthBuffer(){return this._clearDepthBuffer}set clearStencilBuffer(t){this._clearStencilBuffer=t,this._dirtyComposition=!0}get clearStencilBuffer(){return this._clearStencilBuffer}get hasClusteredLights(){return this._clusteredLightsSet.size>0}get clusteredLightsSet(){return this._clusteredLightsSet}incrementCounter(){this._refCounter===0&&(this._enabled=!0,this.onEnable&&this.onEnable()),this._refCounter++}decrementCounter(){if(this._refCounter===1)this._enabled=!1,this.onDisable&&this.onDisable();else if(this._refCounter===0)return;this._refCounter--}addGSplatPlacement(t){this.gsplatPlacementsSet.has(t)||(this.gsplatPlacements.push(t),this.gsplatPlacementsSet.add(t),this.gsplatPlacementsDirty=!0)}removeGSplatPlacement(t){let e=this.gsplatPlacements.indexOf(t);e>=0&&(this.gsplatPlacements.splice(e,1),this.gsplatPlacementsSet.delete(t),this.gsplatPlacementsDirty=!0)}addGSplatShadowCaster(t){this.gsplatShadowCastersSet.has(t)||(this.gsplatShadowCasters.push(t),this.gsplatShadowCastersSet.add(t),this.gsplatPlacementsDirty=!0)}removeGSplatShadowCaster(t){let e=this.gsplatShadowCasters.indexOf(t);e>=0&&(this.gsplatShadowCasters.splice(e,1),this.gsplatShadowCastersSet.delete(t),this.gsplatPlacementsDirty=!0)}addMeshInstances(t,e){let s=this.meshInstances,i=this.meshInstancesSet;for(let r=0;r0){let r=this._shaderVersion;oy.forEach(a=>{r>=0&&a._shaderVersion!==r&&(a.getShaderVariant!==Us.prototype.getShaderVariant&&a.clearVariants(),a._shaderVersion=r)}),oy.clear()}}removeMeshInstances(t,e){let s=this.meshInstances,i=this.meshInstancesSet;for(let r=0;r=0&&s.splice(o,1)}}e||this.removeShadowCasters(t)}addShadowCasters(t){let e=this.shadowCasters,s=this.shadowCastersSet;for(let i=0;i=0&&e.splice(a,1)}}}clearMeshInstances(t=!1){this.meshInstances.length=0,this.meshInstancesSet.clear(),t||(this.shadowCasters.length=0,this.shadowCastersSet.clear())}markLightsDirty(){this._lightHashDirty=!0,this._lightIdHashDirty=!0,this._splitLightsDirty=!0}hasLight(t){return this._lightsSet.has(t)}addLight(t){let e=t.light;this._lightsSet.has(e)||(this._lightsSet.add(e),this._lights.push(e),this.markLightsDirty()),e.type!==Ce&&this._clusteredLightsSet.add(e)}removeLight(t){let e=t.light;this._lightsSet.has(e)&&(this._lightsSet.delete(e),this._lights.splice(this._lights.indexOf(e),1),this.markLightsDirty()),e.type!==Ce&&this._clusteredLightsSet.delete(e)}clearLights(){this._lightsSet.forEach(t=>t.removeLayer(this)),this._lightsSet.clear(),this._clusteredLightsSet.clear(),this._lights.length=0,this.markLightsDirty()}get splitLights(){if(this._splitLightsDirty){this._splitLightsDirty=!1;let t=this._splitLights;for(let s=0;si.key-r.key)}return this._splitLights}evaluateLightHash(t,e,s){let i=0,r=this._lights;for(let a=0;a0&&(_S.sort(),i=dc(_S),_S.length=0),i}getLightHash(t){return this._lightHashDirty&&(this._lightHashDirty=!1,this._lightHash=this.evaluateLightHash(!t,!0,!1)),this._lightHash}getLightIdHash(){return this._lightIdHashDirty&&(this._lightIdHashDirty=!1,this._lightIdHash=this.evaluateLightHash(!0,!1,!0)),this._lightIdHash}addCamera(t){this.camerasSet.has(t.camera)||(this.camerasSet.add(t.camera),this.cameras.push(t),this._dirtyComposition=!0)}removeCamera(t){if(this.camerasSet.has(t.camera)){this.camerasSet.delete(t.camera);let e=this.cameras.indexOf(t);this.cameras.splice(e,1),this._dirtyComposition=!0}}clearCameras(){this.cameras.length=0,this.camerasSet.clear(),this._dirtyComposition=!0}_calculateSortDistances(t,e,s){let i=t.length,{x:r,y:a,z:o}=e,{x:l,y:h,z:f}=s;for(let u=0;uc.priority-t.priority,Uc=c=>c.sort(S6);var ol=class extends J{constructor(e="Untitled"){super();n(this,"layerList",[]);n(this,"layerIdMap",new Map);n(this,"layerNameMap",new Map);n(this,"layerOpaqueIndexMap",new Map);n(this,"layerTransparentIndexMap",new Map);n(this,"subLayerList",[]);n(this,"subLayerEnabled",[]);n(this,"cameras",[]);n(this,"camerasSet",new Set);n(this,"_renderActions",[]);n(this,"_dirty",!1);this.name=e,this._opaqueOrder={},this._transparentOrder={}}destroy(){this.destroyRenderActions()}destroyRenderActions(){this._renderActions.forEach(e=>e.destroy()),this._renderActions.length=0}markDirty(){this._dirty=!0}_update(){let e=this.layerList.length;if(!this._dirty){for(let s=0;s1&&Uc(this.cameras);let s=[],i=0;this.destroyRenderActions();for(let r=0;r0){this.addDummyRenderAction(i,a),i++;continue}let o=!0,l=i,h=null,f=!1;for(let u=0;u0&&a.layers.indexOf(d.id)>=0){s.push(d),!f&&d.id===a.disablePostEffectsLayer&&(f=!0,h&&(h.triggerPostprocess=!0));let m=this.subLayerList[u];h=this.addRenderAction(i,d,m,a,o,f),i++,o=!1}}l=0;m--)if(f[m].camera===r&&f[m].renderTarget===l){h=!0;break}o&&r.postEffectsEnabled&&(l=null);let u=this.getNextRenderAction(e);u.triggerPostprocess=!1,u.layer=s,u.transparent=i,u.camera=r,u.renderTarget=l,u.firstCameraUse=a,u.lastCameraUse=!1;let d=a||!h,p=s.clearColorBuffer||s.clearDepthBuffer||s.clearStencilBuffer;return(d||p)&&u.setupClears(d?r:void 0,s),u}propagateRenderTarget(e,s){for(let i=e;i>=0;i--){let r=this._renderActions[i],a=r.layer;if(r.renderTarget&&a.id!==Zt)break;if(a.id===Zt)continue;if(r.useCameraPasses)break;let o=r?.camera.camera;if(o&&(!s.camera.rect.equals(o.rect)||!s.camera.scissorRect.equals(o.scissorRect)))break;r.renderTarget=s.renderTarget}}_logRenderActions(){}_isLayerAdded(e){return this.layerIdMap.get(e.id)===e}_isSublayerAdded(e,s){return(s?this.layerTransparentIndexMap:this.layerOpaqueIndexMap).get(e)!==void 0}push(e){this._isLayerAdded(e)||(this.layerList.push(e),this.layerList.push(e),this._opaqueOrder[e.id]=this.subLayerList.push(!1)-1,this._transparentOrder[e.id]=this.subLayerList.push(!0)-1,this.subLayerEnabled.push(!0),this.subLayerEnabled.push(!0),this._updateLayerMaps(),this._dirty=!0,this.fire("add",e))}insert(e,s){if(this._isLayerAdded(e))return;this.layerList.splice(s,0,e,e),this.subLayerList.splice(s,0,!1,!0);let i=this.layerList.length;this._updateOpaqueOrder(s,i-1),this._updateTransparentOrder(s,i-1),this.subLayerEnabled.splice(s,0,!0,!0),this._updateLayerMaps(),this._dirty=!0,this.fire("add",e)}remove(e){let s=this.layerList.indexOf(e);for(delete this._opaqueOrder[s],delete this._transparentOrder[s];s>=0;)this.layerList.splice(s,1),this.subLayerList.splice(s,1),this.subLayerEnabled.splice(s,1),s=this.layerList.indexOf(e),this._dirty=!0,this.fire("remove",e);let i=this.layerList.length;this._updateOpaqueOrder(0,i-1),this._updateTransparentOrder(0,i-1),this._updateLayerMaps()}pushOpaque(e){this._isSublayerAdded(e,!1)||(this.layerList.push(e),this._opaqueOrder[e.id]=this.subLayerList.push(!1)-1,this.subLayerEnabled.push(!0),this._updateLayerMaps(),this._dirty=!0,this.fire("add",e))}insertOpaque(e,s){if(this._isSublayerAdded(e,!1))return;this.layerList.splice(s,0,e),this.subLayerList.splice(s,0,!1);let i=this.subLayerList.length;this._updateOpaqueOrder(s,i-1),this.subLayerEnabled.splice(s,0,!0),this._updateLayerMaps(),this._dirty=!0,this.fire("add",e)}removeOpaque(e){for(let s=0,i=this.layerList.length;s=0)return this.subLayerEnabled[i]}return!1}_updateLayerMaps(){this.layerIdMap.clear(),this.layerNameMap.clear(),this.layerOpaqueIndexMap.clear(),this.layerTransparentIndexMap.clear();for(let e=0;e{t.defaultUniformBuffer.destroy(),t.destroy()}),this.viewBindGroups.length=0}get shadowBuffer(){let t=this.shadowCamera.renderTarget;return t?this.light._isPcf?t.depthBuffer:t.colorBuffer:null}},kc=class c{constructor(t,e){n(this,"layers",new Set);n(this,"clusteredLighting");n(this,"shadowDepthState",Pt.DEFAULT.clone());n(this,"clusteredFlags",0);n(this,"clusteredData",new Uint32Array(3));n(this,"clusteredData16",new Uint16Array(this.clusteredData.buffer));n(this,"_evtDeviceRestored",null);this.device=t,this.clusteredLighting=e,this.id=T6++,this._evtDeviceRestored=t.on("devicerestored",this.onDeviceRestored,this),this._type=Ce,this._color=new F(.8,.8,.8),this._intensity=1,this._affectSpecularity=!0,this._luminance=0,this._castShadows=!1,this._enabled=!1,this._mask=cs,this.isStatic=!1,this.key=0,this.bakeDir=!0,this.bakeNumSamples=1,this.bakeArea=0,this.attenuationStart=10,this.attenuationEnd=10,this._falloffMode=uT,this._shadowType=Oi,this._vsmBlurSize=11,this.vsmBlurMode=Kg,this.vsmBias=.01*.25,this._cookie=null,this.cookieIntensity=1,this._cookieFalloff=!0,this._cookieChannel="rgb",this._cookieTransform=null,this._cookieTransformUniform=new Float32Array(4),this._cookieOffset=null,this._cookieOffsetUniform=new Float32Array(2),this._cookieTransformSet=!1,this._cookieOffsetSet=!1,this._innerConeAngle=40,this._outerConeAngle=45,this.cascades=null,this._shadowMatrixPalette=null,this._shadowCascadeDistances=null,this.numCascades=1,this._cascadeBlend=0,this.cascadeDistribution=.5,this._shape=$i,this._colorLinear=new Float32Array(3),this._updateLinearColor(),this._position=new x(0,0,0),this._direction=new x(0,0,0),this._innerConeAngleCos=Math.cos(this._innerConeAngle*R.DEG_TO_RAD),this._updateOuterAngle(this._outerConeAngle),this._usePhysicalUnits=void 0,this._shadowMap=null,this._shadowRenderParams=[],this._shadowCameraParams=[],this.shadowDistance=40,this._shadowResolution=1024,this._shadowBias=-5e-4,this._shadowIntensity=1,this._normalOffsetBias=0,this.shadowUpdateMode=Qg,this.shadowUpdateOverrides=null,this._isVsm=!1,this._isPcf=!0,this._softShadowParams=new Float32Array(4),this.shadowSamples=16,this.shadowBlockerSamples=16,this.penumbraSize=1,this.penumbraFalloff=1,this._cookieMatrix=null,this._atlasViewport=null,this.atlasViewportAllocated=!1,this.atlasVersion=0,this.atlasSlotIndex=0,this.atlasSlotUpdated=!1,this._node=null,this._renderData=[],this.visibleThisFrame=!1,this.maxScreenSize=0,this._updateShadowBias()}destroy(){this._evtDeviceRestored?.off(),this._evtDeviceRestored=null,this._destroyShadowMap(),this.releaseRenderData(),this._renderData=null}onDeviceRestored(){this.shadowUpdateMode===$s&&(this.shadowUpdateMode=Qi)}releaseRenderData(){if(this._renderData){for(let t=0;t45?(t.radius=e*this._outerConeAngleSin,ny.mulScalar(-e*i)):(t.radius=e/(2*i),ny.mulScalar(-t.radius)),t.center.add2(r.getPosition(),ny)}else this._type===We&&(t.center=this._node.getPosition(),t.radius=this.attenuationEnd)}getBoundingBox(t){if(this._type===je){let e=this.attenuationEnd,s=this._outerConeAngle,i=this._node,r=Math.abs(Math.sin(s*R.DEG_TO_RAD)*e);t.center.set(0,-e*.5,0),t.halfExtents.set(r,e*.5,r),t.setFromTransformedAabb(t,i.getWorldTransform(),!0)}else this._type===We&&(t.center.copy(this._node.getPosition()),t.halfExtents.set(this.attenuationEnd,this.attenuationEnd,this.attenuationEnd))}_updateShadowBias(){if(this._type===We&&!this.clusteredLighting)this.shadowDepthState.depthBias=0,this.shadowDepthState.depthBiasSlope=0;else{let t=this.shadowBias*-1e3;this.shadowDepthState.depthBias=t,this.shadowDepthState.depthBiasSlope=t}}_updateLinearColor(){let t=this._intensity;this._usePhysicalUnits&&(t=this._luminance/c.getLightUnitConversion(this._type,this._outerConeAngle*R.DEG_TO_RAD,this._innerConeAngle*R.DEG_TO_RAD));let e=this._color,s=this._colorLinear;t>=1?gS.linear(e).mulScalar(t):gS.copy(e).mulScalar(t).linear(),s[0]=gS.r,s[1]=gS.g,s[2]=gS.b,this.updateClusterData(!0)}setColor(){arguments.length===1?this._color.set(arguments[0].r,arguments[0].g,arguments[0].b):arguments.length===3&&this._color.set(arguments[0],arguments[1],arguments[2]),this._updateLinearColor()}layersDirty(){this.layers.forEach(t=>{t.hasLight(this)&&t.markLightsDirty()})}updateKey(){let t=this._type<<29|this._shadowType<<25|this._falloffMode<<23|(this._normalOffsetBias!==0?1:0)<<22|(this._cookie?1:0)<<21|(this._cookieFalloff?1:0)<<20|lI[this._cookieChannel.charAt(0)]<<18|(this._cookieTransform?1:0)<<12|this._shape<<10|(this.numCascades>0?1:0)<<9|(this._cascadeBlend>0?1:0)<<8|(this.affectSpecularity?1:0)<<7|this.mask<<6|(this._castShadows?1:0)<<3;this._cookieChannel.length===3&&(t|=lI[this._cookieChannel.charAt(1)]<<16,t|=lI[this._cookieChannel.charAt(2)]<<14),t!==this.key&&this.layersDirty(),this.key=t}updateClusteredFlags(){let t=!!(this.mask&cs),e=!!(this.mask&xi);this.clusteredFlags=(this.type===je?1:0)<<30|(this._shape&3)<<28|(this._falloffMode&1)<<27|(v6[this._cookieChannel]??0)<<23|(t?1:0)<<22|(e?1:0)<<21}getClusteredFlags(t,e){return this.clusteredFlags|((t?Math.floor(this.shadowIntensity*255):0)&255)<<0|((e?Math.floor(this.cookieIntensity*255):0)&255)<<8}updateClusterData(t,e){let{clusteredData16:s}=this,i=Hs.float2Half;if(t&&(s[0]=i(R.clamp(this._colorLinear[0]/If,0,65504)),s[1]=i(R.clamp(this._colorLinear[1]/If,0,65504)),s[2]=i(R.clamp(this._colorLinear[2]/If,0,65504))),e){let a=0,o=.99,l=Math.cos(this._innerConeAngle*o*R.DEG_TO_RAD);l>.5&&(l=1-l,a|=1);let h=Math.cos(this._outerConeAngle*o*R.DEG_TO_RAD);h>.5&&(h=1-h,a|=2),s[3]=a,s[4]=i(l),s[5]=i(h)}}};var zc=class{constructor(t,e,s){n(this,"_areaLightsEnabled",!1);n(this,"_cells",new x(10,3,10));n(this,"_maxLightsPerCell",255);n(this,"_shadowsEnabled",!0);n(this,"_shadowType",Oi);n(this,"_shadowAtlasResolution",2048);n(this,"_cookiesEnabled",!1);n(this,"_cookieAtlasResolution",2048);n(this,"debugLayer");n(this,"atlasSplit",null);this._supportsAreaLights=t,this._maxTextureSize=e,this._dirtyLightsFnc=s}applySettings(t){this.shadowsEnabled=t.lightingShadowsEnabled??this.shadowsEnabled,this.cookiesEnabled=t.lightingCookiesEnabled??this.cookiesEnabled,this.areaLightsEnabled=t.lightingAreaLightsEnabled??this.areaLightsEnabled,this.shadowAtlasResolution=t.lightingShadowAtlasResolution??this.shadowAtlasResolution,this.cookieAtlasResolution=t.lightingCookieAtlasResolution??this.cookieAtlasResolution,this.maxLightsPerCell=t.lightingMaxLightsPerCell??this.maxLightsPerCell,this.shadowType=t.lightingShadowType??this.shadowType,t.lightingCells&&(this.cells=new x(t.lightingCells))}set cells(t){this._cells.copy(t)}get cells(){return this._cells}set maxLightsPerCell(t){this._maxLightsPerCell=R.clamp(t,1,255)}get maxLightsPerCell(){return this._maxLightsPerCell}set cookieAtlasResolution(t){this._cookieAtlasResolution=R.clamp(t,32,this._maxTextureSize)}get cookieAtlasResolution(){return this._cookieAtlasResolution}set shadowAtlasResolution(t){this._shadowAtlasResolution=R.clamp(t,32,this._maxTextureSize)}get shadowAtlasResolution(){return this._shadowAtlasResolution}set shadowType(t){this._shadowType!==t&&(this._shadowType=t,this._dirtyLightsFnc())}get shadowType(){return this._shadowType}set cookiesEnabled(t){this._cookiesEnabled!==t&&(this._cookiesEnabled=t,this._dirtyLightsFnc())}get cookiesEnabled(){return this._cookiesEnabled}set areaLightsEnabled(t){this._supportsAreaLights&&this._areaLightsEnabled!==t&&(this._areaLightsEnabled=t,this._dirtyLightsFnc())}get areaLightsEnabled(){return this._areaLightsEnabled}set shadowsEnabled(t){this._shadowsEnabled!==t&&(this._shadowsEnabled=t,this._dirtyLightsFnc())}get shadowsEnabled(){return this._shadowsEnabled}};var Ar=class c{constructor(t){this.morph=t,t.incRefCount(),this.device=t.device;let e=t._targets.length;this.shader=this._createShader(e),this._weights=[],this._weightMap=new Map;for(let a=0;a(this[o]=t._createTexture(a,t._renderTextureFormat),new me({colorBuffer:this[o],depth:!1}));t.morphPositions&&(this.rtPositions=s("MorphRTPos","texturePositions")),t.morphNormals&&(this.rtNormals=s("MorphRTNrm","textureNormals")),this._textureParams=new Float32Array([t.morphTextureWidth,t.morphTextureHeight]);let i=t.aabb.halfExtents;this._aabbSize=new Float32Array([i.x*4,i.y*4,i.z*4]);let r=t.aabb.getMin();this._aabbMin=new Float32Array([r.x*2,r.y*2,r.z*2]),this._aabbNrmSize=new Float32Array([2,2,2]),this._aabbNrmMin=new Float32Array([-1,-1,-1]),this.aabbSizeId=this.device.scope.resolve("aabbSize"),this.aabbMinId=this.device.scope.resolve("aabbMin"),this.morphTextureId=this.device.scope.resolve("morphTexture"),this.morphFactor=this.device.scope.resolve("morphFactor[0]"),this.morphIndex=this.device.scope.resolve("morphIndex[0]"),this.countId=this.device.scope.resolve("count"),this.zeroTextures=!1}destroy(){this.shader=null;let t=this.morph;t&&(this.morph=null,t.decRefCount(),t.refCount<1&&t.destroy()),this.rtPositions?.destroy(),this.rtPositions=null,this.texturePositions?.destroy(),this.texturePositions=null,this.rtNormals?.destroy(),this.rtNormals=null,this.textureNormals?.destroy(),this.textureNormals=null}clone(){return new c(this.morph)}_getWeightIndex(t){if(typeof t=="string"){let e=this._weightMap.get(t);return e}return t}getWeight(t){let e=this._getWeightIndex(t);return this._weights[e]}setWeight(t,e){let s=this._getWeightIndex(t);this._weights[s]=e,this._dirty=!0}_createShader(t){let e=new Map;e.set("{MORPH_TEXTURE_MAX_COUNT}",t),this.morph.intRenderFormat&&e.set("MORPH_INT","");let s=this.morph.intRenderFormat?"uvec4":"vec4";return Se.createShader(this.device,{uniqueName:`TextureMorphShader_${t}-${this.morph.intRenderFormat?"int":"float"}`,attributes:{vertex_position:ee},vertexChunk:"morphVS",fragmentChunk:"morphPS",fragmentDefines:e,fragmentOutputTypes:[s]})}_updateTextureRenderTarget(t,e,s){let{morph:i,device:r}=this;this.setAabbUniforms(s),this.morphTextureId.setValue(s?i.targetsTexturePositions:i.targetsTextureNormals),r.setBlendState(Oe.NOBLEND),this.countId.setValue(e),this.morphFactor.setValue(this._shaderMorphWeights),this.morphIndex.setValue(this._shaderMorphIndex),Qt(r,t,this.shader)}_updateTextureMorph(t){let e=this.device;(t>0||!this.zeroTextures)&&(this.rtPositions&&this._updateTextureRenderTarget(this.rtPositions,t,!0),this.rtNormals&&this._updateTextureRenderTarget(this.rtNormals,t,!1),this.zeroTextures=t===0)}setAabbUniforms(t=!0){this.aabbSizeId.setValue(t?this._aabbSize:this._aabbNrmSize),this.aabbMinId.setValue(t?this._aabbMin:this._aabbNrmMin)}prepareRendering(t){this.setAabbUniforms()}update(){this._dirty=!1;let t=this.morph._targets,e=1e-5,s=this._shaderMorphWeights,i=this._shaderMorphIndex,r=0;for(let a=0;ae&&(s[r]=this.getWeight(a),i[r]=a,r++);this._updateTextureMorph(r)}};var Ei=class c{constructor(){n(this,"graph",null);n(this,"meshInstances",[]);n(this,"skinInstances",[]);n(this,"morphInstances",[]);this.cameras=[],this.lights=[],this._shadersVersion=0,this._immutable=!1}getGraph(){return this.graph}setGraph(t){this.graph=t}getCameras(){return this.cameras}setCameras(t){this.cameras=t}getLights(){return this.lights}setLights(t){this.lights=t}getMaterials(){let t=[];for(let e=0;el)return;this.morphTextureWidth=h,this.morphTextureHeight=f;let u=!1,d=Hs.float2Half;this._textureFormat===Me&&(u=!0);let p=[],m=[],_=h*f*4;for(let g=0;g0&&(this.targetsTexturePositions=this._createTexture("MorphPositionsTexture",this._textureFormat,i.length,[p])),m.length>0&&(this.targetsTextureNormals=this._createTexture("MorphNormalsTexture",this._textureFormat,i.length,[m]));let S=[{semantic:Da,components:1,type:kt,asInt:!0}];return this.vertexBufferIds=new ft(this.device,new Ft(this.device,S,r.length),r.length,{data:new Uint32Array(r)}),!0}get targets(){return this._targets}_updateMorphFlags(){this._morphPositions=!1,this._morphNormals=!1;for(let e=0;e=G)&&this.calcSpawnPosition(s,i,r,a,I);let k=M>0&&M0&&(d.emitterShape===hw?(Wt.copy(Ka).mulScalar(2).sub(x.ONE).normalize(),fs.add(Wt.mulScalar(d.initialVelocity))):fs.add(x.FORWARD.mulScalar(d.initialVelocity))),Cr.x+=(Vp.x-Cr.x)*Ka.x,Cr.y+=(Vp.y-Cr.y)*Ka.y,Cr.z+=(Vp.z-Cr.z)*Ka.z,g+=(T-g)*Ka.y,U=(U+(C-U)*(D*1e4%1))*sM,L=(E-v)*(D*1e3%1),d.meshInstance.node&&(d.localSpace?(fs.x/=ll.x,fs.y/=ll.y,fs.z/=ll.z):hI.transformPoint(fs,fs)),d.localSpace?(fI.transformPoint(Cr,Cr),fs.add(Cr).add(SS)):(fs.add(Cr.mul(ll)),fs.add(SS.mul(ll))),cy.copy(fs),iM.copy(Gp).add(fs.mulScalar(o)),Ai.copy(iM),s[I*Ae]=Ai.x,s[I*Ae+1]=Ai.y,s[I*Ae+2]=Ai.z,s[I*Ae+3]+=g*o,d.wrap&&d.wrapBounds&&(d.localSpace||Ai.sub(a),Ai.x=uI(Ai.x,d.wrapBounds.x)-d.wrapBounds.x*.5,Ai.y=uI(Ai.y,d.wrapBounds.y)-d.wrapBounds.y*.5,Ai.z=uI(Ai.z,d.wrapBounds.z)-d.wrapBounds.z*.5,d.localSpace||Ai.add(a)),d.sort>0&&(d.sort===1?(Jf.copy(Ai).sub(p),d.particleDistance[I]=-(Jf.x*Jf.x+Jf.y*Jf.y+Jf.z*Jf.z)):d.sort===2?d.particleDistance[I]=M:d.sort===3&&(d.particleDistance[I]=-M))),l?M<0&&(s[I*Ae+3+d.numParticlesPot*2*Ae]=-1):(M>=G&&(M-=Math.max(G,d.numParticles*O),s[I*Ae+3+d.numParticlesPot*2*Ae]=d.loop?1:-1),M<0&&d.loop&&(s[I*Ae+3+d.numParticlesPot*2*Ae]=1)),s[I*Ae+3+d.numParticlesPot*2*Ae]<0&&(k=!1),s[I*Ae+3+d.numParticlesPot*Ae]=M;for(let z=0;zup&&d.camera){let w=d.useMesh?6:4,I=d.particleDistance;for(let D=0;DD[1]-O[1]);for(let D=0;D0&&s.set("SOFT",""),t.stretch>0&&s.set("STRETCH",""),t.customFace&&s.set("CUSTOM_FACE",""),t.pack8&&s.set("PACK8",""),t.localSpace&&s.set("LOCAL_SPACE",""),t.animTexLoop&&s.set("ANIMTEX_LOOP",""),t.wrap&&s.set("WRAP",""),t.alignToMotion&&s.set("ALIGN_TO_MOTION",""),s.set("NORMAL",nM[t.normal]),e.particle_vertexData=ee,t.mesh&&t.meshUv&&(e.particle_uv=_t),t.useCpu&&(e.particle_vertexData2=_f,e.particle_vertexData3=Cd,e.particle_vertexData4=Pd,e.particle_vertexData5=wd),s}createFragmentDefines(t){let e=new Map(t.defines);return t.soft>0&&e.set("SOFT",""),t.halflambert&&e.set("HALF_LAMBERT",""),e.set("NORMAL",nM[t.normal]),e.set("BLEND",Wg[t.blend]),e}createShaderDefinition(t,e){let s=t.isWebGPU?se:fe,i=ne.get(t,s),r={},a=this.createVertexDefines(e,r),o=this.createFragmentDefines(e),l=`PARTICLE_${e.useCpu?"CPU":"GPU"} `;a.set(l,""),o.set(l,"");let h=new Map(i);return ns.createDefinition(t,{name:"ParticleShader",shaderLanguage:s,attributes:r,vertexCode:i.get("particle_shaderVS"),fragmentCode:i.get("particle_shaderPS"),fragmentDefines:o,fragmentIncludes:h,vertexIncludes:h,vertexDefines:a})}},lM=new dI;var dy=class extends Us{constructor(e){super();n(this,"emitter",null);this.emitter=e}getShaderVariant(e){let{device:s,scene:i,cameraShaderParams:r,objDefs:a}=e,{emitter:o}=this,l={defines:Se.getCoreDefines(this,e),pass:Sr,useCpu:this.emitter.useCpu,normal:o.lighting?o.normalMap!==null?2:1:0,halflambert:this.emitter.halfLambert,stretch:this.emitter.stretch,alignToMotion:this.emitter.alignToMotion,soft:this.emitter.depthSoftening,mesh:this.emitter.useMesh,meshUv:a&Of,gamma:r?.shaderOutputGamma??Zi,toneMap:r?.toneMapping??Qn,fog:i&&!this.emitter.noFog?i.fog.type:"none",wrap:this.emitter.wrap&&this.emitter.wrapBounds,localSpace:this.emitter.localSpace,screenSpace:o.inTools?!1:this.emitter.screenSpace,blend:this.emitter.blendType,animTex:this.emitter._isAnimated(),animTexLoop:this.emitter.animLoop,pack8:this.emitter.pack8,customFace:this.emitter.orientation!==vc},h=new sa(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),f=Ji(s);return f.register("particle",lM),f.getProgram("particle",l,h,this.userId)}};var cM=[[-1,-1],[1,-1],[1,1],[-1,1]];function na(c,t,e,s,i=ke,r,a){let o=0;a&&(i===ce||i===st)&&(o=1);let l=new Z(c,{width:t,height:e,format:i,cubemap:!1,mipmaps:!1,minFilter:o,magFilter:o,addressU:1,addressV:1,name:"ParticleSystemTexture"}),h=l.lock();if(i===ce||i===st){let f=new Uint8Array(s.length);for(let u=0;ut.maxTextureSize&&(this.numParticles=t.maxTextureSize),Ie("rate",1),Ie("rate2",this.rate),Ie("lifetime",50),Ie("emitterExtents",new x(0,0,0)),Ie("emitterExtentsInner",new x(0,0,0)),Ie("emitterRadius",0),Ie("emitterRadiusInner",0),Ie("emitterShape",Ni),Ie("initialVelocity",1),Ie("wrap",!1),Ie("localSpace",!1),Ie("screenSpace",!1),Ie("wrapBounds",null),Ie("colorMap",this.defaultParamTexture),Ie("normalMap",null),Ie("loop",!0),Ie("preWarm",!1),Ie("sort",up),Ie("mode",jg),Ie("scene",null),Ie("lighting",!1),Ie("halfLambert",!1),Ie("intensity",1),Ie("stretch",0),Ie("alignToMotion",!1),Ie("depthSoftening",0),Ie("mesh",null),Ie("particleNormal",new x(0,1,0)),Ie("orientation",vc),Ie("depthWrite",!1),Ie("noFog",!1),Ie("blendType",ls),Ie("node",null),Ie("startAngle",0),Ie("startAngle2",this.startAngle),Ie("animTilesX",1),Ie("animTilesY",1),Ie("animStartFrame",0),Ie("animNumFrames",1),Ie("animNumAnimations",1),Ie("animIndex",0),Ie("randomizeAnimIndex",!1),Ie("animSpeed",1),Ie("animLoop",!0),this._gpuUpdater=new uy(this,s),this._cpuUpdater=new fy(this),this.emitterPosUniform=new Float32Array(3),this.wrapBoundsUniform=new Float32Array(3),this.emitterScaleUniform=new Float32Array([1,1,1]),Ie("colorGraph",A6),Ie("colorGraph2",this.colorGraph),Ie("scaleGraph",uM),Ie("scaleGraph2",this.scaleGraph),Ie("alphaGraph",uM),Ie("alphaGraph2",this.alphaGraph),Ie("localVelocityGraph",dM),Ie("localVelocityGraph2",this.localVelocityGraph),Ie("velocityGraph",dM),Ie("velocityGraph2",this.velocityGraph),Ie("rotationSpeedGraph",fM),Ie("rotationSpeedGraph2",this.rotationSpeedGraph),Ie("radialSpeedGraph",fM),Ie("radialSpeedGraph2",this.radialSpeedGraph),gy=null,xS=null,this.animTilesParams=new Float32Array(2),this.animParams=new Float32Array(4),this.animIndexParams=new Float32Array(2),this.vbToSort=null,this.vbOld=null,this.particleDistance=null,this.camera=null,this.swapTex=!1,this.useMesh=!0,this.useCpu=!t.supportsGpuParticles,this.pack8=!0,this.localBounds=new ge,this.worldBoundsNoTrail=new ge,this.worldBoundsTrail=[new ge,new ge],this.worldBounds=new ge,this.worldBoundsSize=new x,this.prevWorldBoundsSize=new x,this.prevWorldBoundsCenter=new x,this.prevEmitterExtents=this.emitterExtents,this.prevEmitterRadius=this.emitterRadius,this.worldBoundsMul=new x,this.worldBoundsAdd=new x,this.timeToSwitchBounds=0,this.shaderParticleUpdateRespawn=null,this.shaderParticleUpdateNoRespawn=null,this.shaderParticleUpdateOnStop=null,this.numParticleVerts=0,this.numParticleIndices=0,this.material=null,this.meshInstance=null,this.drawOrder=0,this.seed=Math.random(),this.fixedTimeStep=1/60,this.maxSubSteps=10,this.simTime=0,this.simTimeTotal=0,this.beenReset=!1,this._layer=null,this.rebuild()}get defaultParamTexture(){return D6.get(this.graphicsDevice,()=>{let s=new Float32Array(1024);for(let r=0;r<16;r++)for(let a=0;a<16;a++){let o=a+1-8.5,l=r+1-8.5,h=hM(1-hM(Math.sqrt(o*o+l*l)/16)-.5),f=r*16+a;s[f*4]=1,s[f*4+1]=1,s[f*4+2]=1,s[f*4+3]=h}let i=na(this.graphicsDevice,16,16,s,st,1,!0);return i.minFilter=1,i.magFilter=1,i})}onChangeCamera(){this.resetMaterial()}calculateBoundsMad(){this.worldBoundsMul.x=1/this.worldBoundsSize.x,this.worldBoundsMul.y=1/this.worldBoundsSize.y,this.worldBoundsMul.z=1/this.worldBoundsSize.z,this.worldBoundsAdd.copy(this.worldBounds.center).mul(this.worldBoundsMul).mulScalar(-1),this.worldBoundsAdd.x+=.5,this.worldBoundsAdd.y+=.5,this.worldBoundsAdd.z+=.5}calculateWorldBounds(){if(!this.node)return;if(this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),!this.useCpu){let s=!1;this.emitterShape===Ni?s=!this.emitterExtents.equals(this.prevEmitterExtents):s=this.emitterRadius!==this.prevEmitterRadius,s&&this.calculateLocalBounds()}let t=this.node.getWorldTransform();this.localSpace?this.worldBoundsNoTrail.copy(this.localBounds):this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,t),this.worldBoundsTrail[0].add(this.worldBoundsNoTrail),this.worldBoundsTrail[1].add(this.worldBoundsNoTrail);let e=this.simTimeTotal;e>=this.timeToSwitchBounds&&(this.worldBoundsTrail[0].copy(this.worldBoundsTrail[1]),this.worldBoundsTrail[1].copy(this.worldBoundsNoTrail),this.timeToSwitchBounds=e+this.lifetime),this.worldBounds.copy(this.worldBoundsTrail[0]),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.localSpace?(this.meshInstance.aabb.setFromTransformedAabb(this.worldBounds,t),this.meshInstance.mesh.aabb.setFromTransformedAabb(this.worldBounds,t)):(this.meshInstance.aabb.copy(this.worldBounds),this.meshInstance.mesh.aabb.copy(this.worldBounds)),this.meshInstance._aabbVer=1-this.meshInstance._aabbVer,this.pack8&&this.calculateBoundsMad()}resetWorldBounds(){this.node&&(this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,this.localSpace?W.IDENTITY:this.node.getWorldTransform()),this.worldBoundsTrail[0].copy(this.worldBoundsNoTrail),this.worldBoundsTrail[1].copy(this.worldBoundsNoTrail),this.worldBounds.copy(this.worldBoundsTrail[0]),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),this.simTimeTotal=0,this.timeToSwitchBounds=0)}calculateLocalBounds(){let t=Number.MAX_VALUE,e=Number.MAX_VALUE,s=Number.MAX_VALUE,i=-Number.MAX_VALUE,r=-Number.MAX_VALUE,a=-Number.MAX_VALUE,o=0,l=0,h=this.lifetime/this.precision,f=[this.qVelocity,this.qVelocity2],u=[this.qLocalVelocity,this.qLocalVelocity2],d=[0,0],p=[0,0],m=[0,0],_=[0,0],S=[0,0],g,T,C;for(let E=0;Eup||t.maxVertexTextures<=1||t.fragmentUniformsCount<64||t.forceCpuParticles;let e=this._destroyResources();this.pack8=(this.pack8||!t.textureFloatRenderable)&&!this.useCpu,cl=this.useCpu||this.pack8?4:2,this.useMesh=!!this.mesh,this.numParticlesPot=R.nextPowerOfTwo(this.numParticles),this.rebuildGraphs(),this.calculateLocalBounds(),this.resetWorldBounds(),this.node&&(this.worldBounds.setFromTransformedAabb(this.localBounds,this.localSpace?W.IDENTITY:this.node.getWorldTransform()),this.worldBoundsTrail[0].copy(this.worldBounds),this.worldBoundsTrail[1].copy(this.worldBounds),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),this.pack8&&this.calculateBoundsMad()),this.vbToSort=new Array(this.numParticles);for(let l=0;l=1&&(this.animTilesX>1||this.animTilesY>1)&&(this.colorMap&&this.colorMap!==this.defaultParamTexture||this.normalMap)}rebuildGraphs(){let t=this.precision,e=this.graphicsDevice;this.qLocalVelocity=this.localVelocityGraph.quantize(t),this.qVelocity=this.velocityGraph.quantize(t),this.qColor=this.colorGraph.quantizeClamped(t,0,1),this.qRotSpeed=this.rotationSpeedGraph.quantize(t),this.qScale=this.scaleGraph.quantize(t),this.qAlpha=this.alphaGraph.quantize(t),this.qRadialSpeed=this.radialSpeedGraph.quantize(t),this.qLocalVelocity2=this.localVelocityGraph2.quantize(t),this.qVelocity2=this.velocityGraph2.quantize(t),this.qColor2=this.colorGraph2.quantizeClamped(t,0,1),this.qRotSpeed2=this.rotationSpeedGraph2.quantize(t),this.qScale2=this.scaleGraph2.quantize(t),this.qAlpha2=this.alphaGraph2.quantize(t),this.qRadialSpeed2=this.radialSpeedGraph2.quantize(t);for(let s=0;s0&&t.setParameter("softening",1/(this.depthSoftening*this.depthSoftening*100)),this.stretch>0&&(t.cull=0),this._compParticleFaceParams()}_compParticleFaceParams(){let t,e;if(this.orientation===vc)t=new Float32Array([1,0,0]),e=new Float32Array([0,0,1]);else{let s;this.orientation===fw?s=this.particleNormal.normalize():s=(this.node===null?W.IDENTITY:this.node.getWorldTransform()).transformVector(this.particleNormal).normalize();let i=new x(1,0,0);Math.abs(i.dot(s))===1&&i.set(0,0,1);let r=new x().cross(s,i).normalize();i.cross(r,s).normalize(),t=new Float32Array([i.x,i.y,i.z]),e=new Float32Array([r.x,r.y,r.z])}this.material.setParameter("faceTangent",t),this.material.setParameter("faceBinorm",e)}getVertexInfo(){let t=[];return this.useCpu?t.push({semantic:Ag,components:4,type:ye},{semantic:_f,components:4,type:ye},{semantic:Cd,components:4,type:ye},{semantic:Pd,components:1,type:ye},{semantic:wd,components:this.useMesh?4:2,type:ye}):(t.push({semantic:Ag,components:4,type:ye}),this.useMesh&&t.push({semantic:_f,components:2,type:ye})),t}_allocate(t){let e=t*this.numParticleVerts,s=t*this.numParticleIndices;if(this.vertexBuffer===void 0||this.vertexBuffer.getNumVertices()!==e){let i=this.getVertexInfo(),r=new Ft(this.graphicsDevice,i);this.vertexBuffer=new ft(this.graphicsDevice,r,e,{usage:1}),this.indexBuffer=new os(this.graphicsDevice,2,s);let a=new Float32Array(this.vertexBuffer.lock()),o,l,h;if(this.useMesh){o=new Float32Array(this.mesh.vertexBuffer.lock()),l=o.length/this.mesh.vertexBuffer.numVertices;for(let d=0;dthis.endTime&&(this.onFinished&&this.onFinished(),this.meshInstance.visible=!1),this.meshInstance&&(this.meshInstance.drawOrder=this.drawOrder)}_destroyResources(){this.particleTexIN?.destroy(),this.particleTexIN=null,this.particleTexOUT?.destroy(),this.particleTexOUT=null,this.particleTexStart&&this.particleTexStart.destroy&&(this.particleTexStart.destroy(),this.particleTexStart=null),this.rtParticleTexIN?.destroy(),this.rtParticleTexIN=null,this.rtParticleTexOUT?.destroy(),this.rtParticleTexOUT=null,this.internalTex0?.destroy(),this.internalTex0=null,this.internalTex1?.destroy(),this.internalTex1=null,this.internalTex2?.destroy(),this.internalTex2=null,this.internalTex3?.destroy(),this.internalTex3=null,this.colorParam?.destroy(),this.colorParam=null,this.vertexBuffer=void 0,this.indexBuffer=void 0;let t=this.meshInstance?.visible??!0;return this.meshInstance?.destroy(),this.meshInstance=null,this.material?.destroy(),this.material=null,t}destroy(){this.camera=null,this._destroyResources()}};var pI=class extends yi{generateKey(t){let e=t.shaderDesc,s=e.vertexGLSL?xt(e.vertexGLSL):0,i=e.fragmentGLSL?xt(e.fragmentGLSL):0,r=e.vertexWGSL?xt(e.vertexWGSL):0,a=e.fragmentWGSL?xt(e.fragmentWGSL):0,o=yi.definesHash(t.defines),l=t.shaderChunks?.key??"",h=`${e.uniqueName}_${o}_${s}_${i}_${r}_${a}_${l}`;return t.skin&&(h+="_skin"),t.useInstancing&&(h+="_inst"),t.useMorphPosition&&(h+="_morphp"),t.useMorphNormal&&(h+="_morphn"),t.useMorphTextureBasedInt&&(h+="_morphi"),h}createAttributesDefinition(t,e){let s=e.shaderDesc.attributes,i=s?{...s}:void 0;e.skin&&(i.vertex_boneWeights=bs,i.vertex_boneIndices=$t),(e.useMorphPosition||e.useMorphNormal)&&(i.morph_vertex_id=Da),t.attributes=i}createVertexDefinition(t,e,s,i){let r=e.shaderDesc,a=new Map(s);a.set("transformInstancingVS","");let o=new Map(e.defines);e.skin&&o.set("SKIN",!0),e.useInstancing&&o.set("INSTANCING",!0),(e.useMorphPosition||e.useMorphNormal)&&(o.set("MORPHING",!0),e.useMorphTextureBasedInt&&o.set("MORPHING_INT",!0),e.useMorphPosition&&o.set("MORPHING_POSITION",!0),e.useMorphNormal&&o.set("MORPHING_NORMAL",!0)),t.vertexCode=i?r.vertexWGSL:r.vertexGLSL,t.vertexIncludes=a,t.vertexDefines=o}createFragmentDefinition(t,e,s,i){let r=e.shaderDesc,a=new Map(s),o=new Map(e.defines);t.fragmentCode=i?r.fragmentWGSL:r.fragmentGLSL,t.fragmentIncludes=a,t.fragmentDefines=o}createShaderDefinition(t,e){let s=e.shaderDesc,i=t.isWebGPU&&!!s.vertexWGSL&&!!s.fragmentWGSL&&(e.shaderChunks?.useWGSL??!0),r={name:`ShaderMaterial-${s.uniqueName}`,shaderLanguage:i?se:fe,fragmentOutputTypes:s.fragmentOutputTypes,meshUniformBufferFormat:s.meshUniformBufferFormat,meshBindGroupFormat:s.meshBindGroupFormat},a=i?se:fe,o=Ha.merge(ne.get(t,a),e.shaderChunks[a]);return this.createAttributesDefinition(r,e),this.createVertexDefinition(r,e,o,i),this.createFragmentDefinition(r,e,o,i),ns.createDefinition(t,r)}},gM=new pI;var ct=class extends Us{constructor(e){super();n(this,"_shaderDesc");this.shaderDesc=e}set shaderDesc(e){if(this._shaderDesc=void 0,e&&(this._shaderDesc={uniqueName:e.uniqueName,attributes:e.attributes,fragmentOutputTypes:e.fragmentOutputTypes,vertexGLSL:e.vertexGLSL,fragmentGLSL:e.fragmentGLSL,vertexWGSL:e.vertexWGSL,fragmentWGSL:e.fragmentWGSL},e.vertexCode||e.fragmentCode||e.shaderLanguage)){let s=e.shaderLanguage??fe;s===fe?(this._shaderDesc.vertexGLSL=e.vertexCode,this._shaderDesc.fragmentGLSL=e.fragmentCode):s===se&&(this._shaderDesc.vertexWGSL=e.vertexCode,this._shaderDesc.fragmentWGSL=e.fragmentCode)}this.clearVariants()}get shaderDesc(){return this._shaderDesc}copy(e){return super.copy(e),this.shaderDesc=e.shaderDesc,this}getShaderVariant(e){let{objDefs:s}=e,i={defines:Se.getCoreDefines(this,e),skin:(s&Uo)!==0,useInstancing:(s&ko)!==0,useMorphPosition:(s&zo)!==0,useMorphNormal:(s&Go)!==0,useMorphTextureBasedInt:(s&Vo)!==0,pass:e.pass,gamma:e.cameraShaderParams.shaderOutputGamma,toneMapping:e.cameraShaderParams.toneMapping,fog:e.cameraShaderParams.fog,shaderDesc:this.shaderDesc,shaderChunks:this.shaderChunks},r=new sa(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),a=Ji(e.device);return a.register("shader-material",gM),a.getProgram("shader-material",i,r,this.userId)}};var SM=` uniform highp {sampler} {name}; {returnType} load{funcName}() { return texelFetch({name}, splat.uv, 0); } {returnType} load{funcName}WithIndex(uint index) { return texelFetch({name}, ivec2(index % splatTextureSize, index / splatTextureSize), 0); } `;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");let u=s.replace(AM,o.name).replace(L6,l.sampler??"").replace(CM,f).replace(vy,l.returnType).replace(Ty,h);r.push(u)}return r.join(` `)}getReadCode(){return this._read}getComputeInputDeclarations(t,e){let s=[],i=[...this.streams,...this._extraStreams];e&&(i=i.filter(r=>e.includes(r.name)));for(let r=0;r");let f=vM.replace(M6,String(t+r)).replace(AM,a.name).replace(CM,h).replace(vy,o.returnType).replace(Ty,l);s.push(f)}return s.join(` `)}getComputeBindFormats(t){let e=[...this.streams,...this._extraStreams];return t&&(e=e.filter(s=>t.includes(s.name))),e.map(s=>{let i=xs.get(s.format),r=rs;return i?.isUint?r=Wi:i?.isInt&&(r=Hi),new Ki(s.name,X,void 0,r,!1)})}setWriteCode(t,e){this._write=this._device.isWebGPU?e:t}getWriteCode(){return this._write}getOutputDeclarations(t){let e=this._device.isWebGPU,s=[],i=e?_I:mI,r=e?Ad:An;for(let a=0;as.name===t);return e||(e=this._extraStreams.find(s=>s.name===t)),e}_invalidateCaches(){this._hash=void 0,this._resourceStreams=null,this._instanceStreams=null}static createDefaultFormat(t){return new c(t,[{name:"dataColor",format:Me},{name:"dataCenter",format:ke},{name:"dataScale",format:Me},{name:"dataRotation",format:Me}],{readGLSL:Sy,readWGSL:xy})}static createSimpleFormat(t){return new c(t,[{name:"dataCenter",format:ke},{name:"dataColor",format:Me}],{readGLSL:TM,readWGSL:yM})}};var wM=` uvec4 cachedTransformA; vec3 getCenter() { cachedTransformA = loadDataTransformA(); 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 cachedTransformA: vec4u; fn getCenter() -> vec3f { cachedTransformA = loadDataTransformA(); return vec3f(bitcast(cachedTransformA.r), bitcast(cachedTransformA.g), bitcast(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(center.x), bitcast(center.y), bitcast(center.z), packedScaleAlpha)); writeDataTransformB(vec4u(packedQuat, 0u, 0u, 0u)); #endif } `;var MM=` var cachedTransformA: vec4u; var cachedTransformB: vec2u; var cachedColor: vec4f; fn getCenter() -> vec3f { cachedTransformA = loadDataTransformA(); cachedTransformB = loadDataTransformB().xy; return vec3f(bitcast(cachedTransformA.r), bitcast(cachedTransformA.g), bitcast(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(center.x), bitcast(center.y), bitcast(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{let i=s.length/3,r=c.length/3,a=new x,o=new x,l=new x,h=new B,f=new B,u=new B,d=new x,p=new x,m=new Float32Array(r*3),_=new Float32Array(r*3),S=[];for(let E=0;E{let P=new x,A=new x,w=new x,I=new x;for(let D=0;D<=E;D++)for(let O=0;O<=y;O++){P.lerp(h[f[v][0]],h[f[v][1]],D/E),A.lerp(h[f[v][0]],h[f[v][2]],O/y),w.sub2(A,h[f[v][0]]),I.add2(P,w);let G=D/E,M=O/y;p.push(I.x,I.y,I.z),m.push(u[v][0],u[v][1],u[v][2]),_.push(G,1-M),G=G*FM+gI,M=M*FM+gI,G/=3,M/=3,G+=v%3/3,M+=Math.floor(v/3)/3,S.push(G,1-M),D0;this._fisheye=t;let s=t>0;e!==s&&(this._fisheyeProj??(this._fisheyeProj=new Yp),this._type===Jn&&this._setFisheyeDefine(s))}}get fisheye(){return this._fisheye}updateSkyMesh(){let t=this.scene._getSkyboxTex();t&&(this.resetSkyMesh(),this.skyMesh=new Ay(this.device,this.scene,this.node,t,this.type),this.skyMesh.depthWrite=this._depthWrite,this._fisheye>0&&this.type===Jn&&this._setFisheyeDefine(!0),this.scene.fire("set:skybox",t))}resetSkyMesh(){this.skyMesh?.destroy(),this.skyMesh=null}update(){if(this.type!==Jn){let{center:t,centerArray:e}=this,s=new x;this.node.getWorldTransform().transformPoint(t,s),e[0]=s.x,e[1]=s.y,e[2]=s.z,this.projectedSkydomeCenterId.setValue(e)}}_setFisheyeDefine(t){if(this.skyMesh?.meshInstance){let e=this.skyMesh.meshInstance.material;e.setDefine("SKY_FISHEYE",t),e.update()}}_onPreRender(t){if(this._fisheye>0&&this._fisheyeProj&&this.skyMesh?.meshInstance){let e=t.camera,s=this._fisheyeProj;s.update(this._fisheye,e.fov,e.projectionMatrix);let i=this.skyMesh.meshInstance.material;i.setParameter("fisheye_k",s.k),i.setParameter("fisheye_invK",s.invK),i.setParameter("fisheye_projMat00",s.projMat00),i.setParameter("fisheye_projMat11",s.projMat11)}}};var Cy=new Pe;Cy.worldTransform=W.IDENTITY;Cy._dirtyWorld=Cy._dirtyNormal=!1;var Py=class{constructor(t,e,s){this.material=e,this.layer=s,this.positions=[],this.colors=[],this.mesh=new _e(t),this.meshInstance=null}addLines(t,e){let s=this.positions,i=t.length;for(let a=0;a0&&this.material.transparent===e&&(this.mesh.setPositions(this.positions),this.mesh.setColors(this.colors),this.mesh.update(Pn,!1),this.meshInstance||(this.meshInstance=new we(this.mesh,this.material,Cy)),t.push(this.meshInstance))}clear(){this.positions.length=0,this.colors.length=0}};var wy=class{constructor(t){this.device=t,this.map=new Map}getBatch(t,e){let s=this.map.get(t);return s||(s=new Py(this.device,t,e),this.map.set(t,s)),s}onPreRender(t,e){this.map.forEach(s=>{s.onPreRender(t,e)})}clear(){this.map.forEach(t=>t.clear())}};var la=[],$p=new x,Iy=class{constructor(t){n(this,"shaderDescs",new Map);this.device=t,this.quadMesh=null,this.textureShader=null,this.depthTextureShader=null,this.cubeLocalPos=null,this.cubeWorldPos=null,this.batchesMap=new Map,this.allBatches=new Set,this.updatedLayers=new Set,this._materialDepth=null,this._materialNoDepth=null,this.layerMeshInstances=new Map}createMaterial(t){let e=new ct({uniqueName:"ImmediateLine",vertexGLSL:ne.get(this.device,fe).get("immediateLineVS"),fragmentGLSL:ne.get(this.device,fe).get("immediateLinePS"),vertexWGSL:ne.get(this.device,se).get("immediateLineVS"),fragmentWGSL:ne.get(this.device,se).get("immediateLinePS"),attributes:{vertex_position:ee,vertex_color:Ct}});return e.blendType=ls,e.depthTest=t,e.update(),e}get materialDepth(){return this._materialDepth||(this._materialDepth=this.createMaterial(!0)),this._materialDepth}get materialNoDepth(){return this._materialNoDepth||(this._materialNoDepth=this.createMaterial(!1)),this._materialNoDepth}getBatch(t,e){let s=this.batchesMap.get(t);s||(s=new wy(this.device),this.batchesMap.set(t,s)),this.allBatches.add(s);let i=e?this.materialDepth:this.materialNoDepth;return s.getBatch(i,t)}getShaderDesc(t,e,s){return this.shaderDescs.has(t)||this.shaderDescs.set(t,{uniqueName:`DebugShader:${t}`,vertexGLSL:` attribute vec2 vertex_position; uniform mat4 matrix_model; varying vec2 uv0; 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; 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; @fragment fn fragmentMain(input : FragmentInput) -> FragmentOutput { var output: FragmentOutput; let uv : vec2 = vec2(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{r===t&&i.onPreRender(e,s)}),!this.updatedLayers.has(t)){this.updatedLayers.add(t);let i=this.layerMeshInstances.get(t);if(i){for(let r=0;rt.clear()),this.allBatches.clear(),this.updatedLayers.clear()}};var Zp=class{constructor(){n(this,"type",Mi);n(this,"color",new F(0,0,0));n(this,"density",0);n(this,"start",1);n(this,"end",1e3)}};var Bt=class extends J{constructor(e){super();n(this,"ambientBake",!1);n(this,"ambientBakeOcclusionBrightness",0);n(this,"ambientBakeOcclusionContrast",0);n(this,"ambientLight",new F(0,0,0));n(this,"ambientLuminance",0);n(this,"exposure",1);n(this,"lightmapSizeMultiplier",1);n(this,"lightmapMaxResolution",2048);n(this,"lightmapMode",zf);n(this,"lightmapFilterEnabled",!1);n(this,"lightmapHDR",!1);n(this,"root",null);n(this,"physicalUnits",!1);n(this,"_envAtlas",null);n(this,"_skyboxCubeMap",null);n(this,"_fogParams",new Zp);n(this,"forcePassThroughSpecular",!1);this.device=e,this._gravity=new x(0,-9.8,0),this._layers=null,this._prefilteredCubemaps=[],this._internalEnvAtlas=null,this._skyboxIntensity=1,this._skyboxLuminance=0,this._skyboxMip=0,this._skyboxHighlightMultiplier=1,this._skyboxRotationShaderInclude=!1,this._skyboxRotation=new $,this._skyboxRotationMat3=new Ws,this._skyboxRotationMat4=new W,this._ambientBakeNumSamples=1,this._ambientBakeSpherePart=.4,this._lightmapFilterRange=10,this._lightmapFilterSmoothness=.2,this._clusteredLightingEnabled=!0,this._lightingParams=new zc(this.device.supportsAreaLights,this.device.maxTextureSize,()=>{this.updateShaders=!0}),this.gsplatCentersEnabled=!0,this._gsplatParams=new yy(this.device),this._sky=new qp(this),this._stats={meshInstances:0,lights:0,dynamicLights:0,bakedLights:0,updateShadersTime:0},this.updateShaders=!0,this._shaderVersion=0,this.immediate=new Iy(this.device)}get defaultDrawLayer(){return this.layers.getLayerById(Zn)}set ambientBakeNumSamples(e){this._ambientBakeNumSamples=R.clamp(Math.floor(e),1,255)}get ambientBakeNumSamples(){return this._ambientBakeNumSamples}set ambientBakeSpherePart(e){this._ambientBakeSpherePart=R.clamp(e,.001,1)}get ambientBakeSpherePart(){return this._ambientBakeSpherePart}set clusteredLightingEnabled(e){this.device.isWebGPU&&!e||!this._clusteredLightingEnabled&&e||(this._clusteredLightingEnabled=e)}get clusteredLightingEnabled(){return this._clusteredLightingEnabled}set envAtlas(e){e!==this._envAtlas&&(this._envAtlas=e,e&&(e.addressU=1,e.addressV=1,e.minFilter=1,e.magFilter=1,e.mipmaps=!1),this._prefilteredCubemaps=[],this._internalEnvAtlas&&(this._internalEnvAtlas.destroy(),this._internalEnvAtlas=null),this._resetSkyMesh())}get envAtlas(){return this._envAtlas}set layers(e){let s=this._layers;this._layers=e,this.fire("set:layers",s,e)}get layers(){return this._layers}get sky(){return this._sky}get lighting(){return this._lightingParams}get gsplat(){return this._gsplatParams}get fog(){return this._fogParams}set lightmapFilterRange(e){this._lightmapFilterRange=Math.max(e,.001)}get lightmapFilterRange(){return this._lightmapFilterRange}set lightmapFilterSmoothness(e){this._lightmapFilterSmoothness=Math.max(e,.001)}get lightmapFilterSmoothness(){return this._lightmapFilterSmoothness}set prefilteredCubemaps(e){e=e||[];let s=this._prefilteredCubemaps;(s.length!==e.length||s.some((r,a)=>r!==e[a]))&&(e.length===6&&e.every(a=>!!a)?(this._internalEnvAtlas=bc.generatePrefilteredAtlas(e,{target:this._internalEnvAtlas}),this._envAtlas=this._internalEnvAtlas):(this._internalEnvAtlas&&(this._internalEnvAtlas.destroy(),this._internalEnvAtlas=null),this._envAtlas=null),this._prefilteredCubemaps=e.slice(),this._resetSkyMesh())}get prefilteredCubemaps(){return this._prefilteredCubemaps}set skybox(e){e!==this._skyboxCubeMap&&(this._skyboxCubeMap=e,this._resetSkyMesh())}get skybox(){return this._skyboxCubeMap}set skyboxIntensity(e){e!==this._skyboxIntensity&&(this._skyboxIntensity=e,this._resetSkyMesh())}get skyboxIntensity(){return this._skyboxIntensity}set skyboxLuminance(e){e!==this._skyboxLuminance&&(this._skyboxLuminance=e,this._resetSkyMesh())}get skyboxLuminance(){return this._skyboxLuminance}set skyboxMip(e){e!==this._skyboxMip&&(this._skyboxMip=e,this._resetSkyMesh())}get skyboxMip(){return this._skyboxMip}set skyboxHighlightMultiplier(e){e!==this._skyboxHighlightMultiplier&&(this._skyboxHighlightMultiplier=e,this._resetSkyMesh())}get skyboxHighlightMultiplier(){return this._skyboxHighlightMultiplier}set skyboxRotation(e){if(!this._skyboxRotation.equals(e)){let s=e.equals($.IDENTITY);this._skyboxRotation.copy(e),s?this._skyboxRotationMat3.setIdentity():(this._skyboxRotationMat4.setTRS(x.ZERO,e,x.ONE),this._skyboxRotationMat3.invertMat4(this._skyboxRotationMat4)),!this._skyboxRotationShaderInclude&&!s&&(this._skyboxRotationShaderInclude=!0,this._resetSkyMesh())}}get skyboxRotation(){return this._skyboxRotation}destroy(){this._sky.destroy(),this.root=null,this.off()}drawLine(e,s,i=F.WHITE,r=!0,a=this.defaultDrawLayer){this.immediate.getBatch(a,r).addLines([e,s],[i,i])}drawLines(e,s,i=!0,r=this.defaultDrawLayer){this.immediate.getBatch(r,i).addLines(e,s)}drawLineArrays(e,s,i=!0,r=this.defaultDrawLayer){this.immediate.getBatch(r,i).addLinesArrays(e,s)}applySettings(e){let s=e.physics,i=e.render;this._gravity.set(s.gravity[0],s.gravity[1],s.gravity[2]),this.ambientLight.set(i.global_ambient[0],i.global_ambient[1],i.global_ambient[2]),this.ambientLuminance=i.ambientLuminance,this.fog.type=i.fog,this.fog.color.set(i.fog_color[0],i.fog_color[1],i.fog_color[2]),this.fog.start=i.fog_start,this.fog.end=i.fog_end,this.fog.density=i.fog_density,this.lightmapSizeMultiplier=i.lightmapSizeMultiplier,this.lightmapMaxResolution=i.lightmapMaxResolution,this.lightmapMode=i.lightmapMode,this.exposure=i.exposure,this._skyboxIntensity=i.skyboxIntensity??1,this._skyboxLuminance=i.skyboxLuminance??2e4,this._skyboxMip=i.skyboxMip??0,i.skyboxRotation&&(this.skyboxRotation=new $().setFromEulerAngles(i.skyboxRotation[0],i.skyboxRotation[1],i.skyboxRotation[2])),this.sky.applySettings(i),this.clusteredLightingEnabled=i.clusteredLightingEnabled??!1,this.lighting.applySettings(i),["lightmapFilterEnabled","lightmapFilterRange","lightmapFilterSmoothness","ambientBake","ambientBakeNumSamples","ambientBakeSpherePart","ambientBakeOcclusionBrightness","ambientBakeOcclusionContrast"].forEach(r=>{i.hasOwnProperty(r)&&(this[r]=i[r])}),this._resetSkyMesh()}_getSkyboxTex(){let e=this._prefilteredCubemaps;return this._skyboxMip?e[[0,1,3,4,5,6][this._skyboxMip]]||this._envAtlas||e[0]||this._skyboxCubeMap:this._skyboxCubeMap||e[0]||this._envAtlas}_updateSkyMesh(){this.sky.skyMesh||this.sky.updateSkyMesh(),this.sky.update()}_resetSkyMesh(){this.sky.resetSkyMesh(),this.updateShaders=!0}setSkybox(e){e?(this.skybox=e[0]||null,e[1]&&!e[1].cubemap?this.envAtlas=e[1]:this.prefilteredCubemaps=e.slice(1)):(this.skybox=null,this.envAtlas=null)}get lightmapPixelFormat(){return this.lightmapHDR&&this.device.getRenderableHdrFormat()||ce}};n(Bt,"EVENT_SETLAYERS","set:layers"),n(Bt,"EVENT_SETSKYBOX","set:skybox"),n(Bt,"EVENT_PRERENDER","prerender"),n(Bt,"EVENT_POSTRENDER","postrender"),n(Bt,"EVENT_PRERENDER_LAYER","prerender:layer"),n(Bt,"EVENT_POSTRENDER_LAYER","postrender:layer"),n(Bt,"EVENT_PRECULL","precull"),n(Bt,"EVENT_POSTCULL","postcull");var Vc=class{constructor(t,e,s){this.device=t,this.inverseBindPose=e,this.boneNames=s}};var N6=[0,0,1,0,0,1,0,0,1,0,0,1],B6=[0,1,3,2,3,1],Qp=class extends J{constructor(t,e){super(),this._device=t,this._pixelsPerUnit=e&&e.pixelsPerUnit!==void 0?e.pixelsPerUnit:1,this._renderMode=e&&e.renderMode!==void 0?e.renderMode:Ti,this._atlas=e&&e.atlas!==void 0?e.atlas:null,this._frameKeys=e&&e.frameKeys!==void 0?e.frameKeys:null,this._meshes=[],this._updatingProperties=!1,this._meshesDirty=!1,this._atlas&&this._frameKeys&&this._createMeshes()}set frameKeys(t){this._frameKeys=t,this._atlas&&this._frameKeys&&(this._updatingProperties?this._meshesDirty=!0:this._createMeshes()),this.fire("set:frameKeys",t)}get frameKeys(){return this._frameKeys}set atlas(t){t!==this._atlas&&(this._atlas&&(this._atlas.off("set:frames",this._onSetFrames,this),this._atlas.off("set:frame",this._onFrameChanged,this),this._atlas.off("remove:frame",this._onFrameRemoved,this)),this._atlas=t,this._atlas&&this._frameKeys&&(this._atlas.on("set:frames",this._onSetFrames,this),this._atlas.on("set:frame",this._onFrameChanged,this),this._atlas.on("remove:frame",this._onFrameRemoved,this),this._updatingProperties?this._meshesDirty=!0:this._createMeshes()),this.fire("set:atlas",t))}get atlas(){return this._atlas}set pixelsPerUnit(t){this._pixelsPerUnit!==t&&(this._pixelsPerUnit=t,this.fire("set:pixelsPerUnit",t),this._atlas&&this._frameKeys&&this.renderMode===Ti&&(this._updatingProperties?this._meshesDirty=!0:this._createMeshes()))}get pixelsPerUnit(){return this._pixelsPerUnit}set renderMode(t){if(this._renderMode===t)return;let e=this._renderMode;this._renderMode=t,this.fire("set:renderMode",t),(e===Ti||t===Ti)&&this._atlas&&this._frameKeys&&(this._updatingProperties?this._meshesDirty=!0:this._createMeshes())}get renderMode(){return this._renderMode}get meshes(){return this._meshes}_createMeshes(){let t=this._meshes.length;for(let i=0;i{let i=new SI;i._name=s.name,this._interpolatedKeys.push(i),this._interpolatedKeyDict[s.name]=i,this._currKeyIndices[s.name]=0;for(let r=0;rs){this._time=this.looping?0:s;for(let r=0;r=0?1:-1;for(let r=0;r=0;u+=i){let d=l[u],p=l[u+1];if(d.time<=this._time&&p.time>=this._time){let m=(this._time-d.time)/(p.time-d.time);h._pos.lerp(d.position,p.position,m),h._quat.slerp(d.rotation,p.rotation,m),h._scale.lerp(d.scale,p.scale,m),h._written=!0,this._currKeyIndices[o]=u,f=!0;break}}(l.length===1||!f&&this._time===0&&this.looping)&&(h._pos.copy(l[0].position),h._quat.copy(l[0].rotation),h._scale.copy(l[0].scale),h._written=!0)}}}blend(t,e,s){let i=this._interpolatedKeys.length;for(let r=0;r items: array; @group(0) @binding(1) var blockSums: array; struct PrefixSumUniforms { elementCount: u32 }; @group(0) @binding(2) var 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 temp: array; @compute @workgroup_size(WORKGROUP_SIZE_X, WORKGROUP_SIZE_Y, 1) fn reduce_downsweep( @builtin(workgroup_id) w_id: vec3, @builtin(num_workgroups) w_dim: vec3, @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, @builtin(num_workgroups) w_dim: vec3, @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;a0;){e++;let i=Math.ceil(s/Ry);if(i<=1)break;s=i}return e}dispatch(t){for(let e=0;e=0;e--){let s=this.passes[e];s.addBlockCompute&&(s.addBlockCompute.setParameter("elementCount",s.count),s.addBlockCompute.setupDispatch(s.dispatchX,s.dispatchY,1),t.computeDispatch([s.addBlockCompute],"PrefixSumAddBlock"))}}};var zM=` @group(0) @binding(0) var input: array; @group(0) @binding(1) var block_sums: array; struct RadixSortUniforms { workgroupCount: u32, elementCount: u32 }; @group(0) @binding(2) var uniforms: RadixSortUniforms; #ifdef USE_INDIRECT_SORT @group(0) @binding(3) var sortElementCount: array; #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 histogram: array, 16>; @compute @workgroup_size(WORKGROUP_SIZE_X, WORKGROUP_SIZE_Y, 1) fn main( @builtin(workgroup_id) w_id: vec3, @builtin(num_workgroups) w_dim: vec3, @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 inputKeys: array; @group(0) @binding(1) var outputKeys: array; @group(0) @binding(2) var prefix_block_sum: array; @group(0) @binding(3) var inputValues: array; @group(0) @binding(4) var outputValues: array; struct RadixSortUniforms { workgroupCount: u32, elementCount: u32 }; @group(0) @binding(5) var uniforms: RadixSortUniforms; #ifdef USE_INDIRECT_SORT @group(0) @binding(6) var sortElementCount: array; #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 digit_masks: array, 128>; var digit_offsets: array; @compute @workgroup_size(WORKGROUP_SIZE_X, WORKGROUP_SIZE_Y, 1) fn main( @builtin(workgroup_id) w_id: vec3, @builtin(num_workgroups) w_dim: vec3, @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 b_sort: array>; @group(0) @binding(1) var b_globalHist: array>; struct OneSweepUniforms { numKeys: u32, threadBlocks: u32, numPasses: u32, _pad: u32 }; @group(0) @binding(2) var uniforms: OneSweepUniforms; #ifdef USE_INDIRECT_SORT @group(0) @binding(3) var b_sortElementCount: array; #endif const RADIX: u32 = 256u; const MAX_PASSES: u32 = 4u; const G_HIST_DIM: u32 = {G_HIST_DIM}u; const G_HIST_PART_SIZE: u32 = {G_HIST_PART_SIZE}u; const G_HIST_PART_SIZE_VEC: u32 = G_HIST_PART_SIZE / 4u; const SHARED_HIST_SIZE: u32 = 2u * MAX_PASSES * RADIX; var g_gHist: array, SHARED_HIST_SIZE>; fn histOffset(row: u32, pass_: u32) -> u32 { return row * RADIX + pass_ * 2u * RADIX; } @compute @workgroup_size(G_HIST_DIM, 1, 1) fn main( @builtin(local_invocation_index) gtid: u32, @builtin(workgroup_id) gid: vec3, @builtin(num_workgroups) nwg: vec3, ) { let flatGid = gid.x + gid.y * nwg.x; let numPasses = uniforms.numPasses; #ifdef USE_INDIRECT_SORT let numKeys = b_sortElementCount[0]; #else let numKeys = uniforms.numKeys; #endif let sharedEnd = 2u * numPasses * RADIX; for (var i = gtid; i < sharedEnd; i = i + G_HIST_DIM) { atomicStore(&g_gHist[i], 0u); } workgroupBarrier(); let row = gtid / 64u; let numKeysVecFull = numKeys >> 2u; let partitionStartVec = flatGid * G_HIST_PART_SIZE_VEC; let partitionEndVec = min(partitionStartVec + G_HIST_PART_SIZE_VEC, numKeysVecFull); for (var i = partitionStartVec + gtid; i < partitionEndVec; i = i + G_HIST_DIM) { let q = b_sort[i]; if (numPasses >= 1u) { let off = histOffset(row, 0u); atomicAdd(&g_gHist[(q.x & 0xFFu) + off], 1u); atomicAdd(&g_gHist[(q.y & 0xFFu) + off], 1u); atomicAdd(&g_gHist[(q.z & 0xFFu) + off], 1u); atomicAdd(&g_gHist[(q.w & 0xFFu) + off], 1u); } if (numPasses >= 2u) { let off = histOffset(row, 1u); atomicAdd(&g_gHist[((q.x >> 8u) & 0xFFu) + off], 1u); atomicAdd(&g_gHist[((q.y >> 8u) & 0xFFu) + off], 1u); atomicAdd(&g_gHist[((q.z >> 8u) & 0xFFu) + off], 1u); atomicAdd(&g_gHist[((q.w >> 8u) & 0xFFu) + off], 1u); } if (numPasses >= 3u) { let off = histOffset(row, 2u); atomicAdd(&g_gHist[((q.x >> 16u) & 0xFFu) + off], 1u); atomicAdd(&g_gHist[((q.y >> 16u) & 0xFFu) + off], 1u); atomicAdd(&g_gHist[((q.z >> 16u) & 0xFFu) + off], 1u); atomicAdd(&g_gHist[((q.w >> 16u) & 0xFFu) + off], 1u); } if (numPasses >= 4u) { let off = histOffset(row, 3u); atomicAdd(&g_gHist[((q.x >> 24u) & 0xFFu) + off], 1u); atomicAdd(&g_gHist[((q.y >> 24u) & 0xFFu) + off], 1u); atomicAdd(&g_gHist[((q.z >> 24u) & 0xFFu) + off], 1u); atomicAdd(&g_gHist[((q.w >> 24u) & 0xFFu) + off], 1u); } } let tailIdx = numKeysVecFull; if ((numKeys & 3u) != 0u && tailIdx >= partitionStartVec && tailIdx < partitionStartVec + G_HIST_PART_SIZE_VEC && (tailIdx - partitionStartVec) % G_HIST_DIM == gtid) { let q = b_sort[tailIdx]; let base = tailIdx << 2u; if (numPasses >= 1u) { let off = histOffset(row, 0u); if (base + 0u < numKeys) { atomicAdd(&g_gHist[(q.x & 0xFFu) + off], 1u); } if (base + 1u < numKeys) { atomicAdd(&g_gHist[(q.y & 0xFFu) + off], 1u); } if (base + 2u < numKeys) { atomicAdd(&g_gHist[(q.z & 0xFFu) + off], 1u); } } if (numPasses >= 2u) { let off = histOffset(row, 1u); if (base + 0u < numKeys) { atomicAdd(&g_gHist[((q.x >> 8u) & 0xFFu) + off], 1u); } if (base + 1u < numKeys) { atomicAdd(&g_gHist[((q.y >> 8u) & 0xFFu) + off], 1u); } if (base + 2u < numKeys) { atomicAdd(&g_gHist[((q.z >> 8u) & 0xFFu) + off], 1u); } } if (numPasses >= 3u) { let off = histOffset(row, 2u); if (base + 0u < numKeys) { atomicAdd(&g_gHist[((q.x >> 16u) & 0xFFu) + off], 1u); } if (base + 1u < numKeys) { atomicAdd(&g_gHist[((q.y >> 16u) & 0xFFu) + off], 1u); } if (base + 2u < numKeys) { atomicAdd(&g_gHist[((q.z >> 16u) & 0xFFu) + off], 1u); } } if (numPasses >= 4u) { let off = histOffset(row, 3u); if (base + 0u < numKeys) { atomicAdd(&g_gHist[((q.x >> 24u) & 0xFFu) + off], 1u); } if (base + 1u < numKeys) { atomicAdd(&g_gHist[((q.y >> 24u) & 0xFFu) + off], 1u); } if (base + 2u < numKeys) { atomicAdd(&g_gHist[((q.z >> 24u) & 0xFFu) + off], 1u); } } } workgroupBarrier(); for (var i = gtid; i < RADIX; i = i + G_HIST_DIM) { for (var p = 0u; p < numPasses; p = p + 1u) { let row0 = atomicLoad(&g_gHist[i + histOffset(0u, p)]); let row1 = atomicLoad(&g_gHist[i + histOffset(1u, p)]); let total = row0 + row1; if (total != 0u) { atomicAdd(&b_globalHist[i + p * RADIX], total); } } } } `;var jM=` @group(0) @binding(0) var b_globalHist: array; @group(0) @binding(1) var b_passHist: array>; struct OneSweepScanUniforms { threadBlocks: u32, _pad0: u32, _pad1: u32, _pad2: u32 }; @group(0) @binding(2) var uniforms: OneSweepScanUniforms; #ifdef USE_INDIRECT_SORT @group(0) @binding(3) var b_sortElementCount: array; #endif const RADIX: u32 = 256u; const FLAG_INCLUSIVE: u32 = 2u; const PART_SIZE: u32 = {PART_SIZE}u; const MAX_SUBGROUPS: u32 = {MAX_SUBGROUPS}u; var g_scan: array; var sg_totals: array; @compute @workgroup_size(RADIX, 1, 1) fn main( @builtin(local_invocation_index) gtid: u32, @builtin(workgroup_id) gid: vec3, @builtin(subgroup_invocation_id) sgInvId: u32, @builtin(subgroup_size) sgSize: u32, ) { let pass_ = gid.x; #ifdef USE_INDIRECT_SORT let numKeys = b_sortElementCount[0]; let threadBlocks = (numKeys + PART_SIZE - 1u) / PART_SIZE; #else let threadBlocks = uniforms.threadBlocks; #endif let waveIndex = gtid / sgSize; let t = b_globalHist[gtid + pass_ * RADIX]; let sgExcl = subgroupExclusiveAdd(t); let sgTotal = subgroupAdd(t); if (sgInvId == 0u) { sg_totals[waveIndex] = sgTotal; } workgroupBarrier(); if (gtid == 0u) { var acc: u32 = 0u; for (var i = 0u; i < MAX_SUBGROUPS; i = i + 1u) { let v = sg_totals[i]; sg_totals[i] = acc; acc = acc + v; } } workgroupBarrier(); let excl = sgExcl + sg_totals[waveIndex]; g_scan[gtid] = excl; let dst = pass_ * threadBlocks * RADIX + gtid; atomicStore(&b_passHist[dst], (excl << 2u) | FLAG_INCLUSIVE); } `;var qM=` @group(0) @binding(0) var inputKeys: array; @group(0) @binding(1) var outputKeys: array; @group(0) @binding(2) var inputValues: array; @group(0) @binding(3) var outputValues: array; @group(0) @binding(4) var b_passHist: array>; @group(0) @binding(5) var b_index: array>; struct OneSweepBinningUniforms { numKeys: u32, threadBlocks: u32, pass_: u32, flags: u32 }; @group(0) @binding(6) var uniforms: OneSweepBinningUniforms; #ifdef USE_INDIRECT_SORT @group(0) @binding(7) var b_sortElementCount: array; #endif const RADIX: u32 = 256u; const RADIX_MASK: u32 = 255u; const RADIX_LOG: u32 = 8u; const D_DIM: u32 = {D_DIM}u; const KEYS_PER_THREAD: u32 = {KEYS_PER_THREAD}u; const PART_SIZE: u32 = D_DIM * KEYS_PER_THREAD; const MAX_SUBGROUPS: u32 = {MAX_SUBGROUPS}u; const WAVE_HISTS_SIZE: u32 = MAX_SUBGROUPS * RADIX; const G_D_SIZE: u32 = max(PART_SIZE, WAVE_HISTS_SIZE); const FLAG_NOT_READY: u32 = 0u; const FLAG_REDUCTION: u32 = 1u; const FLAG_INCLUSIVE: u32 = 2u; const FLAG_MASK: u32 = 3u; var g_d: array, G_D_SIZE>; var digit_base: array; var sg_totals: array; var wg_partIndex: u32; fn passHistOffset(tb: u32, pass_: u32, partitionIdx: u32) -> u32 { return pass_ * tb * RADIX + partitionIdx * RADIX; } @compute @workgroup_size(D_DIM, 1, 1) fn main( @builtin(local_invocation_index) TID: u32, @builtin(subgroup_invocation_id) sgInvId: u32, @builtin(subgroup_size) sgSize: u32, ) { let waveIndex = TID / sgSize; let ltMask = (1u << sgInvId) - 1u; let activeMask = select(0xFFFFFFFFu, (1u << sgSize) - 1u, sgSize < 32u); let pass_ = uniforms.pass_; let currentBit = pass_ << 3u; #ifdef USE_INDIRECT_SORT let numKeys = b_sortElementCount[0]; let threadBlocks = (numKeys + PART_SIZE - 1u) / PART_SIZE; #else let numKeys = uniforms.numKeys; let threadBlocks = uniforms.threadBlocks; #endif let isFirstPass = (uniforms.flags & 1u) != 0u; let isLastPass = (uniforms.flags & 2u) != 0u; if (TID == 0u) { wg_partIndex = atomicAdd(&b_index[pass_], 1u); } let partitionIndex = workgroupUniformLoad(&wg_partIndex); for (var i = TID; i < WAVE_HISTS_SIZE; i = i + D_DIM) { atomicStore(&g_d[i], 0u); } workgroupBarrier(); let tileStart = partitionIndex * PART_SIZE; let validInBlock = select( 0u, min(PART_SIZE, numKeys - tileStart), tileStart < numKeys ); let subPartSize = sgSize * KEYS_PER_THREAD; let waveBase = tileStart + waveIndex * subPartSize; var keys: array; var values: array; var validMask: u32 = 0u; for (var i = 0u; i < KEYS_PER_THREAD; i = i + 1u) { let gid = waveBase + sgInvId + i * sgSize; let is_valid = gid < numKeys; keys[i] = select(0xFFFFFFFFu, inputKeys[gid], is_valid); values[i] = select( select(0u, inputValues[gid], is_valid), gid, isFirstPass ); if (is_valid) { validMask = validMask | (1u << i); } } var offsets: array; for (var i = 0u; i < KEYS_PER_THREAD; i = i + 1u) { let k = keys[i]; let isValid = ((validMask >> i) & 1u) == 1u; let digit = (k >> currentBit) & RADIX_MASK; var waveFlag: u32 = activeMask; for (var b = 0u; b < 8u; b = b + 1u) { let t = ((digit >> b) & 1u) == 1u; let ballot = subgroupBallot(t).x; waveFlag = waveFlag & select(~ballot, ballot, t); } let validBallot = subgroupBallot(isValid).x; waveFlag = waveFlag & validBallot; let peerBits = countOneBits(waveFlag & ltMask); let totalBits = countOneBits(waveFlag); let lowestRankPeer = firstTrailingBit(waveFlag); var preIncrementVal: u32 = 0u; if (isValid && peerBits == 0u) { preIncrementVal = atomicAdd(&g_d[waveIndex * RADIX + digit], totalBits); } offsets[i] = subgroupShuffle(preIncrementVal, lowestRankPeer) + peerBits; workgroupBarrier(); } var myHistRed: u32 = 0u; { var histReduction = atomicLoad(&g_d[TID]); for (var w = 1u; w < MAX_SUBGROUPS; w = w + 1u) { let idx = TID + w * RADIX; let cnt = atomicLoad(&g_d[idx]); histReduction = histReduction + cnt; atomicStore(&g_d[idx], histReduction - cnt); } myHistRed = histReduction; } if (partitionIndex + 1u < threadBlocks) { let dst = passHistOffset(threadBlocks, pass_, partitionIndex + 1u) + TID; atomicAdd(&b_passHist[dst], FLAG_REDUCTION | (myHistRed << 2u)); } let warpExcl = subgroupExclusiveAdd(myHistRed); let warpTotal = subgroupAdd(myHistRed); if (sgInvId == 0u) { sg_totals[waveIndex] = warpTotal; } workgroupBarrier(); if (TID == 0u) { var acc: u32 = 0u; for (var w = 0u; w < MAX_SUBGROUPS; w = w + 1u) { let t = sg_totals[w]; sg_totals[w] = acc; acc = acc + t; } } workgroupBarrier(); let myDigitBase = warpExcl + sg_totals[waveIndex]; var scatterPos: array; for (var i = 0u; i < KEYS_PER_THREAD; i = i + 1u) { let k = keys[i]; let digit = (k >> currentBit) & RADIX_MASK; let warpBase = select(0u, atomicLoad(&g_d[waveIndex * RADIX + digit]), waveIndex > 0u); scatterPos[i] = offsets[i] + warpBase; } digit_base[TID] = myDigitBase; workgroupBarrier(); for (var i = 0u; i < KEYS_PER_THREAD; i = i + 1u) { let k = keys[i]; let digit = (k >> currentBit) & RADIX_MASK; scatterPos[i] = scatterPos[i] + digit_base[digit]; } workgroupBarrier(); if (TID < RADIX) { var lookbackReduction: u32 = 0u; var k: u32 = partitionIndex; var done: bool = false; loop { if (done) { break; } let flagPayload = atomicLoad(&b_passHist[passHistOffset(threadBlocks, pass_, k) + TID]); let flag = flagPayload & FLAG_MASK; if (flag == FLAG_INCLUSIVE) { lookbackReduction = lookbackReduction + (flagPayload >> 2u); if (partitionIndex + 1u < threadBlocks) { let dst = passHistOffset(threadBlocks, pass_, partitionIndex + 1u) + TID; atomicAdd(&b_passHist[dst], 1u | (lookbackReduction << 2u)); } digit_base[TID] = lookbackReduction - myDigitBase; done = true; } else if (flag == FLAG_REDUCTION) { lookbackReduction = lookbackReduction + (flagPayload >> 2u); if (k == 0u) { done = true; } else { k = k - 1u; } } } } for (var i = 0u; i < KEYS_PER_THREAD; i = i + 1u) { if (((validMask >> i) & 1u) == 1u) { atomicStore(&g_d[scatterPos[i]], keys[i]); } } workgroupBarrier(); var linearDigits: array; for (var r = 0u; r < KEYS_PER_THREAD; r = r + 1u) { let linearIdx = TID + r * D_DIM; if (linearIdx < validInBlock) { let k = atomicLoad(&g_d[linearIdx]); let digit = (k >> currentBit) & RADIX_MASK; linearDigits[r] = digit; let globalPos = digit_base[digit] + linearIdx; if (!isLastPass) { outputKeys[globalPos] = k; } } } workgroupBarrier(); for (var i = 0u; i < KEYS_PER_THREAD; i = i + 1u) { if (((validMask >> i) & 1u) == 1u) { atomicStore(&g_d[scatterPos[i]], values[i]); } } workgroupBarrier(); for (var r = 0u; r < KEYS_PER_THREAD; r = r + 1u) { let linearIdx = TID + r * D_DIM; if (linearIdx < validInBlock) { let v = atomicLoad(&g_d[linearIdx]); let digit = linearDigits[r]; let globalPos = digit_base[digit] + linearIdx; outputValues[globalPos] = v; } } } `;var $M=256,ZM=15,Ly=$M*ZM,U6=128,vI=32768,My=256,vS=4,Oy=class extends em{constructor(e,s=!1){super(e,s);n(this,"_threadBlocks",0);n(this,"_allocatedThreadBlocks",0);n(this,"_globalHist",null);n(this,"_passHist",null);n(this,"_index",null);n(this,"_binningDispatchSize",new B(1,1));n(this,"_globalHistDispatchSize",new B(1,1));n(this,"_globalHistBindGroupFormat",null);n(this,"_scanBindGroupFormat",null);n(this,"_binningBindGroupFormat",null);n(this,"_globalHistUniformFormat",null);n(this,"_scanUniformFormat",null);n(this,"_binningUniformFormat",null);n(this,"_globalHistShader",null);n(this,"_scanShader",null);n(this,"_binningShader",null);n(this,"_globalHistCompute",null);n(this,"_scanCompute",null);n(this,"_binningComputes",[]);let i=this._indirectInfo;i[0]=2,i[1]=Ly,i[2]=vI,this._globalHistUniformFormat=new Xe(e,[new Y("numKeys",pe),new Y("threadBlocks",pe),new Y("numPasses",pe),new Y("_pad",pe)]),this._scanUniformFormat=new Xe(e,[new Y("threadBlocks",pe),new Y("_pad0",pe),new Y("_pad1",pe),new Y("_pad2",pe)]),this._binningUniformFormat=new Xe(e,[new Y("numKeys",pe),new Y("threadBlocks",pe),new Y("pass_",pe),new Y("flags",pe)]);let r=e.minSubgroupSize||e.maxSubgroupSize||32,a=Math.max(1,Math.ceil(256/r)),o=s?"Indirect":"",l=[new K("b_sort",X,!0),new K("b_globalHist",X,!1),new Qe("uniforms",X)],h=[new K("b_globalHist",X,!0),new K("b_passHist",X,!1),new Qe("uniforms",X)],f=[new K("inputKeys",X,!0),new K("outputKeys",X,!1),new K("inputValues",X,!0),new K("outputValues",X,!1),new K("b_passHist",X,!1),new K("b_index",X,!1),new Qe("uniforms",X)];s&&(l.push(new K("b_sortElementCount",X,!0)),h.push(new K("b_sortElementCount",X,!0)),f.push(new K("b_sortElementCount",X,!0))),this._globalHistBindGroupFormat=new Ue(e,l),this._scanBindGroupFormat=new Ue(e,h),this._binningBindGroupFormat=new Ue(e,f);let u=new Map;u.set("{G_HIST_DIM}",U6),u.set("{G_HIST_PART_SIZE}",vI),s&&u.set("USE_INDIRECT_SORT",""),this._globalHistShader=new Be(e,{name:`OneSweepGlobalHist${o}`,shaderLanguage:se,cshader:KM,cdefines:u,computeBindGroupFormat:this._globalHistBindGroupFormat,computeUniformBufferFormats:{uniforms:this._globalHistUniformFormat}});let d=new Map;d.set("{MAX_SUBGROUPS}",a),d.set("{PART_SIZE}",Ly),s&&d.set("USE_INDIRECT_SORT",""),this._scanShader=new Be(e,{name:`OneSweepScan${o}`,shaderLanguage:se,cshader:jM,cdefines:d,computeBindGroupFormat:this._scanBindGroupFormat,computeUniformBufferFormats:{uniforms:this._scanUniformFormat}});let p=new Map;p.set("{D_DIM}",$M),p.set("{KEYS_PER_THREAD}",ZM),p.set("{MAX_SUBGROUPS}",a),s&&p.set("USE_INDIRECT_SORT",""),this._binningShader=new Be(e,{name:`OneSweepBinning${o}`,shaderLanguage:se,cshader:qM,cdefines:p,computeBindGroupFormat:this._binningBindGroupFormat,computeUniformBufferFormats:{uniforms:this._binningUniformFormat}}),this._globalHistCompute=new Ye(e,this._globalHistShader,this._globalHistShader.name),this._scanCompute=new Ye(e,this._scanShader,this._scanShader.name)}destroy(){this._destroyBuffers(),this._globalHistShader?.destroy(),this._scanShader?.destroy(),this._binningShader?.destroy(),this._globalHistBindGroupFormat?.destroy(),this._scanBindGroupFormat?.destroy(),this._binningBindGroupFormat?.destroy(),this._globalHistShader=null,this._scanShader=null,this._binningShader=null,this._globalHistCompute=null,this._scanCompute=null,this._binningComputes.length=0,this._globalHistBindGroupFormat=null,this._scanBindGroupFormat=null,this._binningBindGroupFormat=null,this._globalHistUniformFormat=null,this._scanUniformFormat=null,this._binningUniformFormat=null,super.destroy()}_destroyBuffers(){this._destroyPingPongBuffers(),this._globalHist?.destroy(),this._passHist?.destroy(),this._index?.destroy(),this._globalHist=null,this._passHist=null,this._index=null,this._allocatedThreadBlocks=0,this._threadBlocks=0}get radixBits(){return 8}_ensureBinningComputes(e){for(;this._binningComputes.length32)}get sortedIndices(){return this._impl.sortedIndices}get sortedKeys(){return this._impl.sortedKeys}get radixBits(){return this._impl.radixBits}set capacity(t){this._impl.capacity=t}get capacity(){return this._impl.capacity}sort(t,e,s=16,i,r,a=!1){return this._impl.sort(t,e,s,i,r,a)}sortIndirect(t,e,s,i,r,a,o,l=!1){return this._impl.sortIndirect(t,e,s,i,r,a,o,l)}prepareIndirect(){return this._impl.prepareIndirect()}destroy(){this._impl.destroy()}};var k6=new Q,TS=class{constructor(t){this.device=t,this.needsDepthBuffer=!1}render(t,e,s){}drawQuad(t,e,s){let i;if(s){let r=t?t.width:this.device.width,a=t?t.height:this.device.height;i=k6.set(s.x*r,s.y*a,s.z*r,s.w*a)}this.device.setBlendState(Oe.NOBLEND),Qt(this.device,t,e,i)}};n(TS,"quadVertexShader",` attribute vec2 aPosition; varying vec2 vUv0; void main(void) { gl_Position = vec4(aPosition, 0.0, 1.0); vUv0 = getImageEffectUV((aPosition.xy + 1.0) * 0.5); } `);var Ut=class extends yt{constructor(){super(...arguments);n(this,"_shader",null);n(this,"quadRender",null);n(this,"cullMode",0);n(this,"frontFace",0);n(this,"blendState",Oe.NOBLEND);n(this,"depthState",Pt.NODEPTH);n(this,"stencilFront",null);n(this,"stencilBack",null);n(this,"viewport");n(this,"scissor")}set shader(e){this.quadRender?.destroy(),this.quadRender=null,this._shader=e,e&&(this.quadRender=new hs(e))}get shader(){return this._shader}execute(){this.device.setDrawStates(this.blendState,this.depthState,this.cullMode,this.frontFace,this.stencilFront,this.stencilBack),this.quadRender?.render(this.viewport,this.scissor)}};var QM=` uniform highp usampler2D keysTexture; uniform int bitsPerStep; uniform int groupSize; 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; 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; #ifdef SOURCE_LINEAR #define FIRST_PASS #else var indicesTexture: texture_2d; #endif var prefixSums: texture_2d; 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;rt.usedUvs[l]?"1":"0").join("")}`;return`lit_${e}_${a}_${s}_${i}_${r}`}createShaderDefinition(t,e){let s=!!e.shaderChunkWGSL,i=new Lp(t,e.litOptions,s),r={name:"LitShader",shaderLanguage:i.shaderLanguage,tag:i.shaderPassInfo.isForward?Cg:void 0},a=e.usedUvs||[!0],o=[];i.generateVertexShader(a,a,o),i.generateFragmentShader("",i.shaderLanguage===se?e.shaderChunkWGSL:e.shaderChunkGLSL,"vUv0");let l=Ha.merge(i.chunks,i.includes),h=i.vDefines;e.defines.forEach((u,d)=>h.set(d,u));let f=i.fDefines;return e.defines.forEach((u,d)=>f.set(d,u)),r.attributes=i.attributes,r.vertexCode=i.vshader,r.vertexIncludes=l,r.vertexDefines=h,r.fragmentCode=i.fshader,r.fragmentIncludes=l,r.fragmentDefines=f,ns.createDefinition(t,r)}},r2=new yI;var sm=new Uy,ky=class extends Us{constructor(){super(...arguments);n(this,"usedUvs",[!0]);n(this,"shaderChunkGLSL",null);n(this,"shaderChunkWGSL",null);n(this,"useLighting",!0);n(this,"useFog",!0);n(this,"useTonemap",!0);n(this,"useSkybox",!0);n(this,"ambientSH",null);n(this,"pixelSnap",!1);n(this,"nineSlicedMode",null);n(this,"twoSidedLighting",!1);n(this,"occludeDirect",!1);n(this,"occludeSpecular",Bo);n(this,"occludeSpecularIntensity",1);n(this,"opacityFadesSpecular",!0);n(this,"opacityDither",Bi);n(this,"opacityShadowDither",Bi);n(this,"shadowCatcher",!1);n(this,"ggxSpecular",!1);n(this,"fresnelModel",Sc);n(this,"dynamicRefraction",!1);n(this,"hasAo",!1);n(this,"hasSpecular",!1);n(this,"hasSpecularityFactor",!1);n(this,"hasLighting",!1);n(this,"hasHeights",!1);n(this,"hasNormals",!1);n(this,"hasSheen",!1);n(this,"hasRefraction",!1);n(this,"hasIrridescence",!1);n(this,"hasMetalness",!1);n(this,"hasClearCoat",!1);n(this,"hasClearCoatNormals",!1)}getShaderVariant(e){sm.usedUvs=this.usedUvs.slice(),sm.shaderChunkGLSL=this.shaderChunkGLSL,sm.shaderChunkWGSL=this.shaderChunkWGSL,sm.defines=Se.getCoreDefines(this,e),Lc.update(sm.litOptions,this,e.scene,e.cameraShaderParams,e.objDefs,e.pass,e.sortedLights);let s=new sa(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),i=Ji(e.device);return i.register("lit",r2),i.getProgram("lit",sm,s,this.userId)}};var ja=8/64,qo=1-ja*2,Xc=class extends Jt{constructor(t,e,s,i,r,a){super();let o=new x,l=new x,h=new x,f=new x,u=new x,d=new x,p=[],m=[],_=[],S=[],g=[],T;if(s>0)for(let C=0;C<=i;C++)for(let v=0;v<=r;v++){let E=v/r*2*Math.PI-Math.PI,y=Math.sin(E),P=Math.cos(E);u.set(y*t,-s/2,P*t),f.set(y*e,s/2,P*e),o.lerp(u,f,C/i),l.sub2(f,u).normalize(),d.set(P,0,-y),h.cross(d,l).normalize(),p.push(o.x,o.y,o.z),m.push(h.x,h.y,h.z);let A=v/r,w=C/i;_.push(A,1-w);let I=w;if(w=A,A=I,A=A*qo+ja,w=w*qo+ja,A/=3,S.push(A,1-w),C0)for(let C=0;C1&&g.push(T,T+C,T+C-1)}if(T+=r,e>0)for(let C=0;C1&&g.push(T,T+C-1,T+C)}}this.positions=p,this.normals=m,this.uvs=_,this.uvs1=S,this.indices=g}};var Yc=class extends Xc{constructor(t={}){let e=t.radius??.3,s=t.height??1,i=t.heightSegments??1,r=t.sides??20;super(e,e,s-2*e,i,r,!0),t.calculateTangents&&(this.tangents=Zs(this.positions,this.normals,this.uvs,this.indices))}};var qa=class extends Xc{constructor(t={}){let e=t.baseRadius??.5,s=t.peakRadius??0,i=t.height??1,r=t.heightSegments??5,a=t.capSegments??18;super(e,s,i,r,a,!1),t.calculateTangents&&(this.tangents=Zs(this.positions,this.normals,this.uvs,this.indices))}};var Ci=class extends Xc{constructor(t={}){let e=t.radius??.5,s=t.height??1,i=t.heightSegments??5,r=t.capSegments??20;super(e,e,s,i,r,!1),t.calculateTangents&&(this.tangents=Zs(this.positions,this.normals,this.uvs,this.indices))}};var $a=class extends Jt{constructor(t={}){super();let e=t.halfExtents??new B(.5,.5),s=t.widthSegments??5,i=t.lengthSegments??5,r=[],a=[],o=[],l=[],h=0;for(let f=0;f<=s;f++)for(let u=0;u<=i;u++){let d=-e.x+2*e.x*f/s,p=0,m=-(-e.y+2*e.y*u/i),_=f/s,S=u/i;r.push(d,p,m),a.push(0,1,0),o.push(_,1-S),f{this.removeFromCache(i)})}destroy(){this.clearCache()}register(t,e){this._generators.has(t)||this._generators.set(t,e)}unregister(t){this._generators.has(t)&&this._generators.delete(t)}isRegistered(t){return this._generators.has(t)}generateShaderDefinition(t,e,s,i){let r=this.definitionsCache.get(s);if(!r){let a;i.litOptions?.lights&&(a=i.litOptions.lights,i.litOptions.lights=a.map(l=>{let h=l.clone?l.clone():l;return h.key=l.key,h})),this.storeNewProgram(e,i),i.litOptions?.lights&&(i.litOptions.lights=a),this._precached;let o=this._device;r=t.createShaderDefinition(o,i),r.name=r.name??(i.pass?`${e}-pass:${i.pass}`:e),this.definitionsCache.set(s,r)}return r}getCachedShader(t){return this.processedCache.get(t)}setCachedShader(t,e){this.processedCache.set(t,e)}getProgram(t,e,s,i){let r=this._generators.get(t);if(!r)return null;let a=r.generateKey(e),o=xt(a),l=s.generateKey(this._device),h=xt(l),f=`${o}#${h}`,u=this.getCachedShader(f);if(!u){let d=this.generateShaderDefinition(r,t,o,e),p="",m;e.pass!==void 0&&(m=Ns.get(this._device).getByIndex(e.pass),p=`-${m.name}`),this._device.fire("shader:generate",{userMaterialId:i,shaderPassInfo:m,definition:d});let _={name:`${d.name}${p}-proc`,attributes:d.attributes,vshader:d.vshader,vincludes:d.vincludes,fincludes:d.fincludes,fshader:d.fshader,processingOptions:s,shaderLanguage:d.shaderLanguage,meshUniformBufferFormat:d.meshUniformBufferFormat,meshBindGroupFormat:d.meshBindGroupFormat};u=new Be(this._device,_),this.setCachedShader(f,u)}return u}storeNewProgram(t,e){let s={};if(t==="standard"){let i=this._getDefaultStdMatOptions(e.pass);for(let r in e)(e.hasOwnProperty(r)&&i[r]!==e[r]||r==="pass")&&(s[r]=e[r]);for(let r in e.litOptions)s[r]=e.litOptions[r]}else s=e;this._programsCollection.push(JSON.stringify({name:t,options:s}))}dumpPrograms(){let t=`let device = pc.app ? pc.app.graphicsDevice : pc.Application.getApplication().graphicsDevice; `;t+="let shaders = [",this._programsCollection[0]&&(t+=` ${this._programsCollection[0]}`);for(let s=1;s{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 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 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, ¢er); 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; 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; 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;athis._allocatedBoundsEntries){this.boundsBuffer?.destroy(),this._allocatedBoundsEntries=e,this.boundsBuffer=new Ee(this.device,e*EI*4,8);let a=new ArrayBuffer(e*EI*4);this._boundsFloatView=new Float32Array(a),this._boundsUintView=new Uint32Array(a),this._tmpSpheres=new Float32Array(e*4)}let s=this._boundsFloatView,i=this._boundsUintView,r=this._tmpSpheres;for(let a=0;athis._allocatedTransformCount&&(this.transformsBuffer?.destroy(),this._allocatedTransformCount=e,this.transformsBuffer=new Ee(this.device,e*12*4,8),this._transformsData=new Float32Array(e*12));let s=this._transformsData,i=0;for(let r=0;r0&&(this.splats.push(u),this._partialData.push(m,S))}}this._subDrawTexture.unlock()}else for(let o=0;o0&&(this.splats.push(l),this._partialData.push(0,0))}for(let o=0;o0}execute(){let{device:e,splats:s,cameraNode:i,_partialData:r}=this;e.setDrawStates();let a=i.getWorldTransform(),o=G6.copy(a).invert();e.scope.resolve("matrix_view").setValue(o.data);for(let l=0;l0?this.renderSplat(s[l],this._subDrawTexture,h,r[l*2]):this.renderSplat(s[l])}}renderSplat(e,s,i,r=0){let{device:a,resource:o}=e,l=a.scope,h=s??e.subDrawTexture,f=i??e.subDrawCount,u=e.getWorkBufferModifier?.()??null,d=o.format.hash,p=o.format.getInputDeclarations(),m=o.getWorkBufferRenderInfo(this.colorOnly,u,d,p,this.workBuffer.format);m.material.setParameters(a);let _=this.colorsByLod?.[e.lodIndex]??this.colorsByLod?.[0]??V6;l.resolve("uColorMultiply").setValue(_);let S=e.node.getWorldTransform();if(S.getScale(Gy),ru.setFromMat4(S),ru.w<0&&ru.mulScalar(-1),this._modelScaleData[0]=Gy.x,this._modelScaleData[1]=Gy.y,this._modelScaleData[2]=Gy.z,this._modelRotationData[0]=ru.x,this._modelRotationData[1]=ru.y,this._modelRotationData[2]=ru.z,this._modelRotationData[3]=ru.w,l.resolve("matrix_model").setValue(S.data),l.resolve("model_scale").setValue(this._modelScaleData),l.resolve("model_rotation").setValue(this._modelRotationData),l.resolve("uId").setValue(e.placementId),e.parameters)for(let C of e.parameters.values())C.scopeId.setValue(C.data);let g=e.getInstanceStreams?.();if(g){g.syncWithFormat(e.resource.format);for(let[C,v]of g.textures)l.resolve(C).setValue(v)}l.resolve("uSubDrawData").setValue(h),l.resolve("uSubDrawBase").setValue(r);let T=this.workBuffer.textureSize;this._textureSize[0]=T,this._textureSize[1]=T,l.resolve("uTextureSize").setValue(this._textureSize),m.quadRender.render(void 0,void 0,f)}};var dl=class{constructor(t,e=!1){n(this,"device");n(this,"format",null);n(this,"textures",new Map);n(this,"_textureDimensions",new B);n(this,"_isInstance",!1);n(this,"_formatVersion",-1);this.device=t,this._isInstance=e}get textureDimensions(){return this._textureDimensions}destroy(){for(let t of this.textures.values())t.destroy();this.textures.clear()}init(t,e){this.format=t,this._textureDimensions=gt.calcTextureSize(e,new B);let s=this._isInstance?t.instanceStreams:t.resourceStreams;for(let i of s){let r=this.createTexture(i.name,i.format,this._textureDimensions);this.textures.set(i.name,r)}this._formatVersion=t.extraStreamsVersion}getTexture(t){return this.syncWithFormat(this.format),this.textures.get(t)}getTexturesInOrder(){let t=[];if(this.format){let e=this._isInstance?this.format.instanceStreams:this.format.resourceStreams;for(let s of e){let i=this.textures.get(s.name);i&&t.push(i)}}return t}syncWithFormat(t){if(t){if(this.format===t&&this._formatVersion===t.extraStreamsVersion)return;this.format=t;let e=this._isInstance?t.instanceStreams:t.resourceStreams;for(let s of e)if(!this.textures.has(s.name)){let i=this.createTexture(s.name,s.format,this._textureDimensions);this.textures.set(s.name,i)}this._formatVersion=t.extraStreamsVersion}}resize(t,e){this._textureDimensions.set(t,e);for(let s of this.textures.values())s.resize(t,e)}createTexture(t,e,s,i){return Z.createDataTexture2D(this.device,t,s.x,s.y,e,i?[i]:void 0)}};var H6=0,Vy=class{constructor(t,e,s,i,r){n(this,"material");n(this,"quadRender");this.material=s;let a=new Map(s.defines),o=r.getStream("dataColor");o.format===Rs&&a.set("GSPLAT_COLOR_UINT",""),i&&a.set("GSPLAT_COLOR_ONLY",""),r.getStream("pcId")&&a.set("GSPLAT_ID","");let l=s.hasShaderChunks?t.isWebGPU?s.shaderChunks.wgsl:s.shaderChunks.glsl:void 0,h=i?[o]:[...r.streams,...r.extraStreams],f=[];for(let m of h){let _=An(m.format);f.push(_.returnType)}let u=a.has("GSPLAT_LOD"),d={uniqueName:`SplatCopyToWorkBuffer:${e}`,attributes:{vertex_position:ee},vertexDefines:a,fragmentDefines:a,fragmentGLSL:a2,fragmentWGSL:o2,fragmentIncludes:l,fragmentOutputTypes:f};u?(d.vertexGLSL=n2,d.vertexWGSL=l2):d.vertexChunk="fullscreenQuadVS";let p=Se.createShader(t,d);this.quadRender=new hs(p)}destroy(){this.material?.destroy(),this.quadRender?.destroy()}},AS=class{constructor(t,e){n(this,"device");n(this,"format");n(this,"id",H6++);n(this,"streams");n(this,"renderTarget");n(this,"colorRenderTarget");n(this,"orderTexture");n(this,"orderBuffer");n(this,"uploadStream");n(this,"renderPass");n(this,"colorRenderPass");n(this,"frustumCuller");this.device=t,this.format=e,this.frustumCuller=new zy(t),this.streams=new dl(t),this.streams.init(e,1),this._createRenderTargets(),this.uploadStream=new rm(t,!t.isWebGPU),t.isWebGPU?this.orderBuffer=new Ee(t,4,8):this.orderTexture=new Z(t,{name:"SplatGlobalOrder",width:1,height:1,format:zt,mipmaps:!1,addressU:1,addressV:1}),this.renderPass=new ES(t,this),this.renderPass.init(this.renderTarget),this.colorRenderPass=new ES(t,this,!0),this.colorRenderPass.init(this.colorRenderTarget)}_createRenderTargets(){this.renderTarget?.destroy(),this.colorRenderTarget?.destroy();let t=this.streams.getTexturesInOrder();this.renderTarget=new me({name:`GsplatWorkBuffer-MRT-${this.id}`,colorBuffers:t,depth:!1,flipY:!0});let e=this.streams.getTexture("dataColor");this.colorRenderTarget=new me({name:`GsplatWorkBuffer-Color-${this.id}`,colorBuffer:e,depth:!1,flipY:!0}),this.renderPass?.init(this.renderTarget),this.colorRenderPass?.init(this.colorRenderTarget)}syncWithFormat(){let t=this.streams._formatVersion;this.streams.syncWithFormat(this.format),t!==this.streams._formatVersion&&this._createRenderTargets()}getTexture(t){return this.streams.getTexture(t)}destroy(){this.renderPass?.destroy(),this.colorRenderPass?.destroy(),this.streams.destroy(),this.orderTexture?.destroy(),this.orderBuffer?.destroy(),this.renderTarget?.destroy(),this.colorRenderTarget?.destroy(),this.uploadStream.destroy(),this.frustumCuller.destroy()}get textureSize(){return this.streams.textureDimensions.x}setOrderData(t){let e=this.textureSize;this.device.isWebGPU?this.uploadStream.upload(t,this.orderBuffer,0,t.length):this.uploadStream.upload(t,this.orderTexture,0,t.length)}resize(t){if(this.renderTarget.resize(t,t),this.colorRenderTarget.resize(t,t),this.streams.resize(t,t),this.device.isWebGPU){let e=t*t*4;this.orderBuffer.byteSizenew CS)._pendingDestroy.add(e)}static process(t){let e=this._cache.get(t,()=>new CS)._pendingDestroy;for(let s of e)s.refCount===0&&(s._actualDestroy(),e.delete(s))}destroy(){this._pendingDestroy.clear()}};n(CS,"_cache",new et);var am=CS;var W6=0,om=new Map,rt=class c{constructor(t,e,s={}){n(this,"device");n(this,"gsplatData");n(this,"_centers",null);n(this,"centersVersion",0);n(this,"aabb");n(this,"mesh",null);n(this,"id",W6++);n(this,"workBufferRenderInfos",new Map);n(this,"_format",null);n(this,"streams");n(this,"parameters",new Map);n(this,"_refCount",0);n(this,"_meshRefCount",0);this.device=t,this.gsplatData=e,this.streams=new dl(t),s.prepareCenters!==!1?this._centers=e.getCenters():this._centers=null,this.aabb=new ge,e.calcAabb(this.aabb)}set centers(t){this._centers=t}get centers(){return this._centers}get hasCenters(){return this._centers!=null}destroy(){if(this.refCount>0){am.queueDestroy(this.device,this);return}this._actualDestroy()}_actualDestroy(){this.streams.destroy(),this.mesh?.destroy(),this.workBufferRenderInfos.forEach(t=>t.destroy()),this.workBufferRenderInfos.clear()}incRefCount(){this._refCount++}decRefCount(){this._refCount--}get refCount(){return this._refCount}ensureMesh(){this.mesh||(this.mesh=c.createMesh(this.device),this.mesh.aabb.copy(this.aabb)),this._meshRefCount++}releaseMesh(){this._meshRefCount--,this._meshRefCount<1&&(this.mesh=null)}getWorkBufferRenderInfo(t,e,s,i,r){this.configureMaterialDefines(om),om.set("GSPLAT_LOD",""),t&&om.set("GSPLAT_COLOR_ONLY","");let a="";for(let[h,f]of om)a&&(a+=";"),a+=`${h}=${f}`;let o=`${s};${r.hash};${e?.hash??0};${a}`,l=this.workBufferRenderInfos.get(o);if(!l){let h=new ct;this.configureMaterial(h,e,i);let f=this.device.isWebGPU?h.shaderChunks.wgsl:h.shaderChunks.glsl,u=t?[r.getStream("dataColor")]:[...r.streams,...r.extraStreams],d=r.getOutputDeclarations(u);t&&r.extraStreams.length>0&&(d+=` ${r.getOutputStubs(r.extraStreams)}`),f.set("gsplatWorkBufferOutputVS",d);let p=r.getWriteCode();p&&f.set("gsplatWriteVS",p),om.forEach((m,_)=>h.setDefine(_,m)),l=new Vy(this.device,o,h,t,r),this.workBufferRenderInfos.set(o,l)}return om.clear(),l}static createMesh(t){let e=c.instanceSize,s=new Float32Array(12*e),i=new Uint32Array(6*e);for(let a=0;a0&&t.setParameter("splatTextureSize",this.textureDimensions.x)}configureMaterialDefines(t){}instantiate(){}};var Hy=class extends rt{constructor(e,s,i){let r=new ge;super(e,{numSplats:s,getCenters:()=>null,calcAabb:o=>o.copy(r)},{prepareCenters:!1});n(this,"_maxSplats",0);n(this,"_numSplats",0);this._format=i,this._maxSplats=s,this._numSplats=s,this.streams.init(this._format,s)}set centers(e){this._centers=e}get centers(){return this._centers===null&&(this._centers=new Float32Array(this._maxSplats*3),this.centersVersion++),this._centers}get maxSplats(){return this._maxSplats}get numSplats(){return this._numSplats}update(e=this._numSplats,s=!0){this._numSplats=R.clamp(e,0,this._maxSplats),s&&this.centersVersion++}configureMaterialDefines(e){e.set("SH_BANDS","0")}configureMaterial(e,s=null,i){super.configureMaterial(e,s,i);let r=this.device.isWebGPU?e.shaderChunks.wgsl:e.shaderChunks.glsl;r.set("gsplatContainerDeclarationsVS",this.format.getInputDeclarations()),r.set("gsplatDeclarationsVS",'#include "gsplatContainerDeclVS"'),r.set("gsplatReadVS",this.format.getReadCode())}};var nm=new W,f2=new $,CI=new ge,u2=new ge,X6=new F(1,1,0,.4),PI=.28209479177387814,wI=class{constructor(t,e,s,i,r){let a=t.getProp("x"),o=t.getProp("y"),l=t.getProp("z"),h=t.getProp("rot_1"),f=t.getProp("rot_2"),u=t.getProp("rot_3"),d=t.getProp("rot_0"),p=t.getProp("scale_0"),m=t.getProp("scale_1"),_=t.getProp("scale_2"),S=t.getProp("f_dc_0"),g=t.getProp("f_dc_1"),T=t.getProp("f_dc_2"),C=t.getProp("opacity"),v=E=>{if(E>0)return 1/(1+Math.exp(-E));let y=Math.exp(E);return y/(1+y)};this.read=E=>{e&&(e.x=a[E],e.y=o[E],e.z=l[E]),s&&s.set(h[E],f[E],u[E],d[E]),i&&i.set(Math.exp(p[E]),Math.exp(m[E]),Math.exp(_[E])),r&&r.set(.5+S[E]*PI,.5+g[E]*PI,.5+T[E]*PI,v(C[E]))}}},d2=(c,t,e)=>{f2.set(e.x,e.y,e.z,e.w).normalize(),c.setTRS(t,f2,x.ONE)},Qa=class c{constructor(t,e=[]){n(this,"elements");n(this,"numSplats");n(this,"comments");this.elements=t,this.numSplats=this.getElement("vertex").count,this.comments=e}static calcSplatAabb(t,e,s,i){d2(nm,e,s),CI.center.set(0,0,0),CI.halfExtents.set(i.x*2,i.y*2,i.z*2),t.setFromTransformedAabb(CI,nm)}getProp(t,e="vertex"){return this.getElement(e)?.properties.find(s=>s.name===t)?.storage}getElement(t){return this.elements.find(e=>e.name===t)}addProp(t,e){this.getElement("vertex").properties.push({type:"float",name:t,storage:e,byteSize:4})}createIter(t,e,s,i){return new wI(this,t,e,s,i)}calcAabb(t,e){let s,i,r,a,o,l,h=!0,f=this.getProp("x"),u=this.getProp("y"),d=this.getProp("z"),p=this.getProp("scale_0"),m=this.getProp("scale_1"),_=this.getProp("scale_2");for(let S=0;S{for(let s=0;s<45;++s)if(!this.getProp(`f_rest_${s}`))return s;return 45})()]??0}calcMortonOrder(){let t=C=>{let v=C[0],E=C[0];for(let y=1;yE&&(E=C[y]);return{min:v,max:E}},e=(C,v,E)=>{let y=P=>(P&=1023,P=(P^P<<16)&4278190335,P=(P^P<<8)&50393103,P=(P^P<<4)&51130563,P=(P^P<<2)&153391689,P);return(y(E)<<2)+(y(v)<<1)+y(C)},s=this.getProp("x"),i=this.getProp("y"),r=this.getProp("z"),{min:a,max:o}=t(s),{min:l,max:h}=t(i),{min:f,max:u}=t(r),d=a===o?0:1024/(o-a),p=l===h?0:1024/(h-l),m=f===u?0:1024/(u-f),_=new Map;for(let C=0;CC-v),g=new Uint32Array(this.numSplats),T=0;for(let C=0;C{if(e.has(a)){let o=e.get(a);return e.delete(a),o}return new ArrayBuffer(a)},i=a=>{e.set(a.byteLength,a)},r=a=>{let o=new a.constructor(s(a.byteLength));for(let l=0;l{a.properties.forEach(o=>{o.storage&&(o.storage=r(o.storage))})})}reorderData(){this.reorder(this.calcMortonOrder())}};var Y6=` attribute vec2 vertex_position; void main(void) { gl_Position = vec4(vertex_position, 0.0, 1.0); } `,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; @fragment fn fragmentMain(input: FragmentInput) -> FragmentOutput { var output: FragmentOutput; var uv = vec2i(input.position.xy) * vec2i(SH_COEFFS, 1); var coefficients: array; 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; var sh_labels: texture_2d; var sh_result: texture_2d; 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) -> 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)j+oe,0);for(let j=0;j>>0;for(let j=0;j>>0,Lt=S[Ve]+g[Ve]*(ot-Ve)>>>0;d[j]=Lt,p[Lt]++}}for(let V=1;V{let q=t[V]*3;return e[q++]*A+e[q++]*w+e[q]*I-b},k=()=>{let V=T(0,M-1,q=>-N(q));return Math.min(M,Math.abs(V))},z=N(M-1)>=0?k():M;if(i)for(let V=0;V{let E=v.data??v;if(E.order&&(t=new Uint32Array(E.order)),E.centers)if(e=new Float32Array(E.centers),o=!0,E.chunks){let y=new Float32Array(E.chunks);s=new Float32Array(E.chunks,0,y.length*4/6),f.x=y[0],f.y=y[1],f.z=y[2],u.x=y[3],u.y=y[4],u.z=y[5];for(let P=0;Pu.x&&(u.x=D),O>u.y&&(u.y=O),G>u.z&&(u.z=G)}}else{let y=e.length/3,P=Math.ceil(y/256);s=new Float32Array(P*4),f.x=f.y=f.z=1/0,u.x=u.y=u.z=-1/0;let A,w,I,D,O,G;for(let M=0;MD&&(D=b),NO&&(O=N),kG&&(G=k),bu.x&&(u.x=b),Nu.y&&(u.y=N),ku.z&&(u.z=k))}s[M*4+0]=(A+D)*.5,s[M*4+1]=(w+O)*.5,s[M*4+2]=(I+G)*.5,s[M*4+3]=Math.sqrt((D-A)**2+(O-w)**2+(G-I)**2)*.5}}E.hasOwnProperty("mapping")&&(i=E.mapping?new Uint32Array(E.mapping):null,o=!0),E.cameraPosition&&(r=E.cameraPosition),E.cameraDirection&&(a=E.cameraDirection),C()})}var Xy=class extends J{constructor(e,s){super();n(this,"worker");n(this,"target");n(this,"orderData");n(this,"centers");n(this,"scene");n(this,"uploadStream");n(this,"pendingSorted",null);this.scene=s??null,this.uploadStream=new rm(e,!e.isWebGPU);let i=a=>{let o=a.data??a;this.scene&&o.sortTime!==void 0&&this.scene.fire("gsplat:sorted",o.sortTime);let l=o.order,h=this.orderData;this.worker.postMessage({order:h},[h]),this.orderData=l,this.pendingSorted={count:o.count,data:new Uint32Array(l)},this.fire("updated")},r=`(${m2.toString()})()`;ue.environment==="node"?(this.worker=new Worker(r,{eval:!0}),this.worker.on("message",i)):(this.worker=new Worker(URL.createObjectURL(new Blob([r],{type:"application/javascript"}))),this.worker.addEventListener("message",i))}destroy(){this.worker.terminate(),this.worker=null,this.uploadStream.destroy(),this.uploadStream=null}init(e,s,i,r){this.target=e,this.centers=i.slice();let a=new Uint32Array(s);for(let h=0;h= 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; var means_u: texture_2d; 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 = vec2(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 = bitcast>(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;OMath.sign(r)*(Math.exp(Math.abs(r))-1);t.center.set((i(e[0])+i(s[0]))*.5,(i(e[1])+i(s[1]))*.5,(i(e[2])+i(s[2]))*.5),t.halfExtents.set((i(s[0])-i(e[0]))*.5,(i(s[1])-i(e[1]))*.5,(i(s[2])-i(e[2]))*.5)}getCenters(){let t=this._centers;return this._centers=null,t}calcFocalPoint(t,e){let{mins:s,maxs:i}=this.meta.means,r=a=>Math.sign(a)*(Math.exp(Math.abs(a))-1);t.set((r(s[0])+r(i[0]))*.5,(r(s[1])+r(i[1]))*.5,(r(s[2])+r(i[2]))*.5)}get isSog(){return!0}async decompress(){let t=["x","y","z","f_dc_0","f_dc_1","f_dc_2","opacity","scale_0","scale_1","scale_2","rot_0","rot_1","rot_2","rot_3"];this._patchCodebooks();let{shBands:e}=this,{means_l:s,means_u:i,quats:r,scales:a,sh0:o,sh_labels:l,sh_centroids:h}=this;if(s._levels[0]=await Kc(s),i._levels[0]=await Kc(i),r._levels[0]=await Kc(r),a._levels[0]=await Kc(a),o._levels[0]=await Kc(o),e>0){l._levels[0]=await Kc(l),h._levels[0]=await Kc(h);let g=[];for(let T=0;T<45;++T)g.push(`f_rest_${T}`);t.splice(t.indexOf("f_dc_0")+1,0,...g)}let f={};t.forEach(g=>{f[g]=new Float32Array(this.numSplats)});let u=new x,d=new $,p=new x,m=new Q,_=e>0?new Float32Array(45):null,S=this.createIter(u,d,p,m,_);for(let g=0;g=1?40:-Math.log(1/m.w-1),_)for(let T=0;T<45;++T)f[`f_rest_${T}`][g]=_[T];return new Qa([{name:"vertex",count:this.numSplats,properties:t.map(g=>({name:g,type:"float",byteSize:4,storage:f[g]}))}])}async generateCenters(){let{device:t,width:e,height:s}=this.means_l,{scope:i}=t,r=new Z(t,{name:"sogCentersTexture",width:e,height:s,format:At,mipmaps:!1}),a=Se.createShader(t,{uniqueName:"GsplatSogCentersShader",attributes:{vertex_position:ee},vertexChunk:"fullscreenQuadVS",fragmentGLSL:_2,fragmentWGSL:g2,fragmentOutputTypes:["uvec4"]}),o=new me({colorBuffer:r,depth:!1,mipLevel:0});J6(i,{means_l:this.means_l,means_u:this.means_u,numSplats:this.numSplats,means_mins:this.meta.means.mins,means_maxs:this.meta.means.maxs});let l=new hs(a),h=new Cp(t,l);h.name="SogGenerateCenters",h.init(o),h.colorOps.clear=!1,h.depthStencilOps.clearDepth=!1,h.render(),l.destroy(),o.destroy();let f=await Kc(r);if(this.destroyed||t._destroyed){r.destroy();return}let u=new Float32Array(f.buffer),d=new Float32Array(this.numSplats*3);for(let p=0;p{let e=this.meta[t]?.codebook;e?.[0]===null&&(e[0]=e[1]+(e[1]-e[255])/255)})}prepareCodebook(){let t=this.means_l?.device;this.destroyed||!t||t._destroyed||(this._patchCodebooks(),this.meta.version===2&&this._createCodebookTexture())}async prepareGpuData(){let t=this.means_l?.device;this.destroyed||!t||t._destroyed||await this.generateCenters()}};var e8=new W,lm=new x,cm=new x,hm=class{constructor(t,e={}){n(this,"resource");n(this,"orderTexture");n(this,"orderBuffer");n(this,"_material");n(this,"meshInstance");n(this,"options",{});n(this,"sorter",null);n(this,"lastCameraPosition",new x);n(this,"lastCameraDirection",new x);n(this,"resolveSH",null);n(this,"cameras",[]);this.resource=t;let s=t.device,i=t.streams.textureDimensions,r=i.x*i.y;if(s.isWebGPU?this.orderBuffer=new Ee(s,r*4,8):this.orderTexture=t.streams.createTexture("splatOrder",zt,i),e.material?(this._material=e.material,this._material.setDefine("{GSPLAT_INSTANCE_SIZE}",String(rt.instanceSize)),this.setMaterialOrderData(this._material),this._material.setParameter("alphaClipForward",1/255)):(this._material=new ct({uniqueName:"SplatMaterial",vertexGLSL:'#include "gsplatVS"',fragmentGLSL:'#include "gsplatPS"',vertexWGSL:'#include "gsplatVS"',fragmentWGSL:'#include "gsplatPS"',attributes:{vertex_position:ee}}),this.configureMaterial(this._material),this._material.update()),t.ensureMesh(),this.meshInstance=new we(t.mesh,this._material),this.meshInstance.setInstancing(!0,!0),this.meshInstance.gsplatInstance=this,this.meshInstance.instancingCount=0,t.hasCenters){let a=t.centers.slice(),o=t.chunks?.slice(),l=this.orderBuffer??this.orderTexture;this.sorter=new Xy(s,e.scene),this.sorter.init(l,r,a,o)}this.setHighQualitySH(e.highQualitySH??!1)}destroy(){this.resource?.releaseMesh(),this.orderTexture?.destroy(),this.orderBuffer?.destroy(),this.resolveSH?.destroy(),this.material?.destroy(),this.meshInstance?.destroy(),this.sorter?.destroy()}setMaterialOrderData(t){this.orderBuffer?t.setParameter("splatOrder",this.orderBuffer):(t.setParameter("splatOrder",this.orderTexture),t.setParameter("splatTextureSize",this.orderTexture.width))}set material(t){this._material!==t&&(this._material=t,this._material.setDefine("{GSPLAT_INSTANCE_SIZE}",String(rt.instanceSize)),this.setMaterialOrderData(this._material),this._material.setParameter("alphaClipForward",1/255),this.meshInstance&&(this.meshInstance.material=t))}get material(){return this._material}configureMaterial(t,e={}){this.resource.configureMaterial(t,null,this.resource.format.getInputDeclarations()),t.setDefine("{GSPLAT_INSTANCE_SIZE}",rt.instanceSize),t.setParameter("numSplats",0),this.setMaterialOrderData(t),t.setParameter("alphaClip",.3),t.setParameter("alphaClipForward",1/255),t.setParameter("minPixelSize",2),t.setDefine(`DITHER_${e.dither?"BLUENOISE":"NONE"}`,""),t.cull=0,t.blendType=e.dither?wt:Ms,t.depthWrite=!!e.dither}sort(t){if(this.sorter){let e=t.getWorldTransform();e.getTranslation(lm),e.getZ(cm);let s=this.meshInstance.node.getWorldTransform(),i=e8.invert(s);i.transformPoint(lm,lm),i.transformVector(cm,cm),(!lm.equalsApprox(this.lastCameraPosition)||!cm.equalsApprox(this.lastCameraDirection))&&(this.lastCameraPosition.copy(lm),this.lastCameraDirection.copy(cm),this.sorter.setCamera(lm,cm))}}update(){let t=this.sorter?.applyPendingSorted()??-1;if(t>=0&&(this.meshInstance.instancingCount=Math.ceil(t/rt.instanceSize),this.material.setParameter("numSplats",t)),this.cameras.length>0){let e=this.cameras[0];this.sort(e._node),this.resolveSH?.render(e._node,this.meshInstance.node.getWorldTransform()),this.cameras.length=0}}setHighQualitySH(t){let{resource:e}=this,{gsplatData:s}=e;s instanceof ca&&s.shBands>0&&t===!!this.resolveSH&&(this.resolveSH?(this.resolveSH.destroy(),this.resolveSH=null):this.resolveSH=new Wy(e.device,this))}};var S2=` uniform uint splatTextureSize; uniform uint dstTextureSize; uniform uint srcNumSplats; 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 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;s0&&(a.push({name:"splatSH_1to3",format:At}),this.shBands>1&&(a.push({name:"splatSH_4to7",format:At}),this.shBands>2?(a.push({name:"splatSH_8to11",format:At}),a.push({name:"splatSH_12to15",format:At})):a.push({name:"splatSH_8to11",format:zt}))),this._format=new Pr(e,a,{readGLSL:'#include "gsplatUncompressedVS"',readWGSL:'#include "gsplatUncompressedVS"'}),this.streams.init(this.format,r),this.updateColorData(s),this.updateTransformData(s),this.shBands>0&&this.updateSHData(s)}configureMaterialDefines(e){e.set("SH_BANDS",this.shBands)}updateColorData(e){let s=this.streams.getTexture("splatColor");if(!s)return;let i=Hs.float2Half,r=s.lock(),a=e.getProp("f_dc_0"),o=e.getProp("f_dc_1"),l=e.getProp("f_dc_2"),h=e.getProp("opacity"),f=.28209479177387814;for(let u=0;u1&&(l[T*4+0]=g[9]<<21|g[10]<<11|g[11],l[T*4+1]=g[12]<<21|g[13]<<11|g[14],l[T*4+2]=g[15]<<21|g[16]<<11|g[17],l[T*4+3]=g[18]<<21|g[19]<<11|g[20],this.shBands>2?(h[T*4+0]=g[21]<<21|g[22]<<11|g[23],h[T*4+1]=g[24]<<21|g[25]<<11|g[26],h[T*4+2]=g[27]<<21|g[28]<<11|g[29],h[T*4+3]=g[30]<<21|g[31]<<11|g[32],f[T*4+0]=g[33]<<21|g[34]<<11|g[35],f[T*4+1]=g[36]<<21|g[37]<<11|g[38],f[T*4+2]=g[39]<<21|g[40]<<11|g[41],f[T*4+3]=g[42]<<21|g[43]<<11|g[44]):h[T]=g[21]<<21|g[22]<<11|g[23])}}s.unlock(),i?.unlock(),r?.unlock(),a?.unlock()}};var jc=class extends rt{constructor(t,e,s={}){super(t,e,s);let{meta:i,means_l:r}=e,a=i.version===2,o=e.shBands>0;r&&this.streams.textureDimensions.set(r.width,r.height),this.streams.textures.set("means_l",e.means_l),this.streams.textures.set("means_u",e.means_u),this.streams.textures.set("quats",e.quats),this.streams.textures.set("scales",e.scales),this.streams.textures.set("sh0",e.sh0),o&&(this.streams.textures.set("sh_labels",e.sh_labels),this.streams.textures.set("sh_centroids",e.sh_centroids)),a&&this.streams.textures.set("sogCodebook",e.codebookTexture);let l=[{name:"means_l",format:ce},{name:"means_u",format:ce},{name:"quats",format:ce},{name:"scales",format:ce},{name:"sh0",format:ce}];o&&(l.push({name:"sh_labels",format:ce}),l.push({name:"sh_centroids",format:ce})),a&&l.push({name:"sogCodebook",format:ke}),this._format=new Pr(t,l,{readGLSL:'#include "gsplatSogVS"',readWGSL:'#include "gsplatSogVS"'}),this._populateParameters()}releaseTextureSources(){let t=this.gsplatData;t.means_l?.setReleaseSourceAfterUpload(),t.means_u?.setReleaseSourceAfterUpload(),t.quats?.setReleaseSourceAfterUpload(),t.scales?.setReleaseSourceAfterUpload(),t.sh0?.setReleaseSourceAfterUpload(),t.sh_centroids?.setReleaseSourceAfterUpload(),t.sh_labels?.setReleaseSourceAfterUpload()}_actualDestroy(){this.streams.textures.delete("means_l"),this.streams.textures.delete("means_u"),this.streams.textures.delete("quats"),this.streams.textures.delete("scales"),this.streams.textures.delete("sh0"),this.streams.textures.delete("sh_labels"),this.streams.textures.delete("sh_centroids"),this.streams.textures.delete("sogCodebook"),this.gsplatData.destroy(),super._actualDestroy()}_populateParameters(){let{meta:t}=this.gsplatData;t.means&&(this.parameters.set("means_mins",t.means.mins),this.parameters.set("means_maxs",t.means.maxs)),t.version!==2&&(t.scales&&(this.parameters.set("scales_mins",t.scales.mins),this.parameters.set("scales_maxs",t.scales.maxs)),t.sh0&&(this.parameters.set("sh0_mins",t.sh0.mins),this.parameters.set("sh0_maxs",t.sh0.maxs)),t.shN&&(this.parameters.set("shN_mins",t.shN.mins),this.parameters.set("shN_maxs",t.shN.maxs)))}configureMaterialDefines(t){let e=this.gsplatData;t.set("SH_BANDS",e.shBands),e.meta.version===2&&t.set("SOG_V2","")}};var s8="NONE",bI="FILL_WINDOW",Ky="KEEP_ASPECT",jy="AUTO",DI="FIXED";var v2;function ys(){return v2}function qy(c){v2=c}var T2=!1,fm={app:null,createLoadingScreen(c){if(T2)return;T2=!0;let t=ys();c(t)}};var $y=class{constructor(){n(this,"renderPasses",[]);n(this,"renderTargetMap",new Map);n(this,"multiview",null)}beginMultiView(t){this.multiview=new Zf(t)}endMultiView(){let t=this.multiview;this.multiview=null,t?.children.length&&this.renderPasses.push(t)}addRenderPass(t){t.frameUpdate();let e=t.beforePasses;for(let i=0;if.clear)||a.afterPasses.length>0||l.beforePasses.length>0||(a._skipEnd=!0,l._skipStart=!0)}let s=null,i=null;for(let r=0;rnew LI(e,e===s?null:s)),t.scope.resolve("areaLightsLutTex1").setValue(e),t.scope.resolve("areaLightsLutTex2").setValue(s)}static createPlaceholder(t){let e=c.createTexture(t,Me,2,"placeholder");e.lock().fill(0),e.unlock(),c.applyTextures(t,e,e)}static set(t,e,s){function i(d,p,m){let _=c.createTexture(d,m,64);return _.lock().set(p),_.unlock(),_}function r(d){let p=d.length,m=new Uint16Array(p),_=Hs.float2Half;for(let S=0;S0);qc(["fa","hi"],c=>c>=0&&c<=1?0:1);qc(["fr","pt"],c=>c>=0&&c<2?0:1);qc(["da"],c=>c===1||!Number.isInteger(c)&&c>=0&&c<=1?0:1);qc(["de","en","it","el","es","tr","fi","sv","nb","no","ur"],c=>c===1?0:1);qc(["ru","uk"],c=>{if(Number.isInteger(c)){let t=c%10,e=c%100;if(t===1&&e!==11)return 0;if(t>=2&&t<=4&&(e<12||e>14))return 1;if(t===0||t>=5&&t<=9||e>=11&&e<=14)return 2}return 3});qc(["pl"],c=>{if(Number.isInteger(c)){if(c===1)return 0;let t=c%10,e=c%100;if(t>=2&&t<=4&&(e<12||e>14))return 1;if(t>=0&&t<=1||t>=5&&t<=9||e>=12&&e<=14)return 2}return 3});qc(["ar"],c=>{if(c===0)return 0;if(c===1)return 1;if(c===2)return 2;if(Number.isInteger(c)){let t=c%100;if(t>=3&&t<=10)return 3;if(t>=11&&t<=99)return 4}return 5});var i8=MI[Zo(um)];function Qy(c){return MI[c]||i8}var Ja=new RegExp("^\\s*(?:(?:[a-z]+[a-z0-9\\-+.]*:)?//|data:|blob:)","i"),r8="animation",a8="audio",o8="image",n8="json",l8="model",c8="material",h8="text",f8="texture",u8="textureatlas",d8="cubemap",p8="shader",m8="css",_8="html",g8="script",S8="container";var Jy=class{constructor(t="",e="",s=null,i=null,r=null,a=null){this.url=t,this.filename=e,this.hash=s,this.size=i,this.opt=r,this.contents=a}equals(t){return this.url===t.url&&this.filename===t.filename&&this.hash===t.hash&&this.size===t.size&&this.opt===t.opt&&this.contents===t.contents}};var x8=-1,v8={pvr:"extCompressedTexturePVRTC",dxt:"extCompressedTextureS3TC",etc2:"extCompressedTextureETC",etc1:"extCompressedTextureETC1",basis:"canvas"},A2=["pvr","dxt","etc2","etc1","basis"],ae=class extends J{constructor(e,s,i,r={},a={}){super();n(this,"_file",null);n(this,"_i18n",{});n(this,"_preload",!1);n(this,"_resources",[]);n(this,"id",x8--);n(this,"loaded",!1);n(this,"loading",!1);n(this,"options",{});n(this,"registry",null);n(this,"tags",new va(this));n(this,"type");n(this,"urlObject",null);this._name=e||"",this.type=s,this._data=r||{},this.options=a||{},i&&(this.file=i)}set name(e){if(this._name===e)return;let s=this._name;this._name=e,this.fire("name",this,this._name,s)}get name(){return this._name}set file(e){if(e&&e.variants&&["texture","textureatlas","bundle"].indexOf(this.type)!==-1){let r=this.registry?._loader?._app||ys(),a=r?.graphicsDevice;if(a)for(let o=0,l=A2.length;ou?.file?.variants[h]))break}}}let s=this._file,i=e?new Jy(e.url,e.filename,e.hash,e.size,e.opt,e.contents):null;(!!i!=!!s||i&&!i.equals(s))&&(this._file=i,this.fire("change",this,"file",i,s),this.reload())}get file(){return this._file}set data(e){let s=this._data;this._data=e,e!==s&&(this.fire("change",this,"data",e,s),this.loaded&&this.registry._loader.patch(this,this.registry))}get data(){return this._data}set resource(e){let s=this._resources[0];this._resources[0]=e,this.fire("change",this,"resource",e,s)}get resource(){return this._resources[0]}set resources(e){let s=this._resources;this._resources=e,this.fire("change",this,"resources",e,s)}get resources(){return this._resources}set preload(e){e=!!e,this._preload!==e&&(this._preload=e,this._preload&&!this.loaded&&!this.loading&&this.registry&&this.registry.load(this))}get preload(){return this._preload}set loadFaces(e){e=!!e,(!this.hasOwnProperty("_loadFaces")||e!==this._loadFaces)&&(this._loadFaces=e,this.loaded&&this.registry._loader.patch(this,this.registry))}get loadFaces(){return this._loadFaces}getFileUrl(){let e=this.file;if(!e||!e.url)return null;let s=e.url;if(this.registry&&this.registry.prefix&&!Ja.test(s)&&(s=this.registry.prefix+s),this.type!=="script"&&e.hash){let i=s.indexOf("?")!==-1?"&":"?";s+=`${i}t=${e.hash}`}return s}getAbsoluteUrl(e){if(e.startsWith("blob:")||e.startsWith("data:"))return e;let s=xe.getDirectory(this.file.url);return xe.join(s,e)}getLocalizedAssetId(e){return e=Zy(e,this._i18n),this._i18n[e]||null}addLocalizedAssetId(e,s){this._i18n[e]=s,this.fire("add:localized",e,s)}removeLocalizedAssetId(e){let s=this._i18n[e];s&&(delete this._i18n[e],this.fire("remove:localized",e,s))}ready(e,s){s=s||this,this.loaded?e.call(s,this):this.once("load",i=>{e.call(s,i)})}reload(){this.loaded&&(this.loaded=!1,this.registry.load(this))}unload(){if(!this.loaded&&this._resources.length===0)return;this.fire("unload",this),this.registry.fire(`unload:${this.id}`,this);let e=this._resources;this.urlObject&&(URL.revokeObjectURL(this.urlObject),this.urlObject=null),this.resources=[],this.loaded=!1,this.file&&this.registry._loader.clearCache(this.getFileUrl(),this.type);for(let s=0;s{s(null,i.file.contents)}):Le.get(e,{cache:!0,responseType:"arraybuffer",retry:r>0,maxRetries:r,progress:i},s)}};n(ae,"EVENT_LOAD","load"),n(ae,"EVENT_UNLOAD","unload"),n(ae,"EVENT_REMOVE","remove"),n(ae,"EVENT_ERROR","error"),n(ae,"EVENT_CHANGE","change"),n(ae,"EVENT_PROGRESS","progress"),n(ae,"EVENT_ADDLOCALIZED","add:localized"),n(ae,"EVENT_REMOVELOCALIZED","remove:localized");var e0=class{constructor(t=null){n(this,"_index",{});n(this,"_key");this._key=t}addItem(t){let e=t.tags._list;for(let s of e)this.add(s,t)}removeItem(t){let e=t.tags._list;for(let s of e)this.remove(s,t)}add(t,e){this._index[t]&&this._index[t].list.indexOf(e)!==-1||(this._index[t]||(this._index[t]={list:[]},this._key&&(this._index[t].keys={})),this._index[t].list.push(e),this._key&&(this._index[t].keys[e[this._key]]=e))}remove(t,e){if(!this._index[t]||this._key&&!this._index[t].keys[e[this._key]])return;let s=this._index[t].list.indexOf(e);s!==-1&&(this._index[t].list.splice(s,1),this._key&&delete this._index[t].keys[e[this._key]],this._index[t].list.length===0&&delete this._index[t])}find(t){let e={},s=[],i,r,a,o,l,h=(f,u)=>this._index[f].list.length-this._index[u].list.length;for(let f=0;fi.preload===e.preload):s}add(e){this._assets.has(e)||(this._assets.add(e),this._idToAsset.set(e.id,e),e.file?.url&&this._urlToAsset.set(e.file.url,e),this._nameToAsset.has(e.name)||this._nameToAsset.set(e.name,new Set),this._nameToAsset.get(e.name).add(e),e.on("name",this._onNameChange,this),e.registry=this,this._tags.addItem(e),e.tags.on("add",this._onTagAdd,this),e.tags.on("remove",this._onTagRemove,this),this.fire("add",e),this.fire(`add:${e.id}`,e),e.file?.url&&this.fire(`add:url:${e.file.url}`,e),e.preload&&this.load(e))}remove(e){if(!this._assets.has(e))return!1;if(this._assets.delete(e),this._idToAsset.delete(e.id),e.file?.url&&this._urlToAsset.delete(e.file.url),e.off("name",this._onNameChange,this),this._nameToAsset.has(e.name)){let s=this._nameToAsset.get(e.name);s.delete(e),s.size===0&&this._nameToAsset.delete(e.name)}return this._tags.removeItem(e),e.tags.off("add",this._onTagAdd,this),e.tags.off("remove",this._onTagRemove,this),e.fire("remove",e),this.fire("remove",e),this.fire(`remove:${e.id}`,e),e.file?.url&&this.fire(`remove:url:${e.file.url}`,e),!0}get(e){return this._idToAsset.get(Number(e))}getByUrl(e){return this._urlToAsset.get(e)}load(e,s){if((e.loading||e.loaded)&&!s?.force)return;let i=e.file,r=()=>{this.fire("load",e),this.fire(`load:${e.id}`,e),i&&i.url&&this.fire(`load:url:${i.url}`,e),e.fire("load",e)},a=l=>{if(l instanceof Array?e.resources=l:e.resource=l,this._loader.patch(e,this),e.type==="bundle"){let h=e.data.assets;for(let f=0;f{if(e.loaded=!0,e.loading=!1,l)this.fire("error",l,e),this.fire(`error:${e.id}`,l,e),e.fire("error",l,e);else{if(e.type==="script"){let u=this._loader.getHandler("script");u._cache[e.id]&&u._cache[e.id].parentNode===document.head&&document.head.removeChild(u._cache[e.id]),f&&(u._cache[e.id]=f)}a(h)}};if(i||e.type==="cubemap"){this.fire("load:start",e),this.fire(`load:${e.id}:start`,e),e.loading=!0;let l=e.getFileUrl();if(e.type==="bundle"){let h=e.data.assets;for(let f=0;f{f.once("load",u=>{i==="material"?this._loadTextures(u,(d,p)=>{r(d,u)}):r(null,u)}),f.once("error",u=>{u&&(this.loadFromUrlError=u),r(u,f)}),this.load(f)};l.resource?r(null,l):i==="model"?this._loadModel(l,h):h(l)}_loadModel(e,s){let i=e.getFileUrl(),r=xe.getExtension(i);if(r===".json"||r===".glb"){let a=xe.getDirectory(i),o=xe.getBasename(i),l=xe.join(a,o.replace(r,".mapping.json"));this._loader.load(l,"json",(h,f)=>{h?(e.data={mapping:[]},s(e)):this._loadMaterials(e,f,(u,d)=>{e.data=f,s(e)})})}else s(e)}_loadMaterials(e,s,i){let r=[],a=0,o=(l,h)=>{this._loadTextures(h,(f,u)=>{r.push(h),r.length===a&&i(null,r)})};for(let l=0;l{i.push(f),i.length===r&&s(null,i)},l=qf;for(let h=0;he(s))}find(e,s){let i=this._nameToAsset.get(e);if(!i)return null;for(let r of i)if(!s||r.type===s)return r;return null}findAll(e,s){let i=this._nameToAsset.get(e);if(!i)return[];let r=Array.from(i);return s?r.filter(a=>a.type===s):r}log(){}};n(ha,"EVENT_LOAD","load"),n(ha,"EVENT_ADD","add"),n(ha,"EVENT_REMOVE","remove"),n(ha,"EVENT_ERROR","error");var pm=class{constructor(t){n(this,"_idToBundle",new Map);n(this,"_assetToBundles",new Map);n(this,"_urlsToBundles",new Map);n(this,"_fileRequests",new Map);this._assets=t,this._assets.bundles=this,this._assets.on("add",this._onAssetAdd,this),this._assets.on("remove",this._onAssetRemove,this)}_onAssetAdd(t){if(t.type==="bundle"){this._idToBundle.set(t.id,t),this._assets.on(`load:start:${t.id}`,this._onBundleLoadStart,this),this._assets.on(`load:${t.id}`,this._onBundleLoad,this),this._assets.on(`error:${t.id}`,this._onBundleError,this);let e=t.data.assets;for(let s=0;s{let i=this._fileRequests.get(e);if(i){for(let r=0;r{this.pump(i.done,i.value)}).catch(i=>{this.fire("error",i)})}pump(e,s){if(e)return this.fire("done"),null;this.bytesReceived+=s.byteLength;let i=new Uint8Array(this.data.length+s.length);for(i.set(this.data),i.set(s,this.data.length),this.data=i;this.readFile(););return this.reader.read().then(r=>{this.pump(r.done,r.value)}).catch(r=>{this.fire("error",r)})}readFile(){if(!this.headerRead&&this.bytesReceived>this.bytesRead+this.headerSize){this.headerRead=!0;let e=new DataView(this.data.buffer,this.bytesRead,this.headerSize);this.decoder??(this.decoder=new TextDecoder("windows-1252"));let s=this.decoder.decode(e);if(this.fileName=s.substring(0,100).replace(/\0/g,""),this.fileSize=parseInt(s.substring(124,136),8),this.fileType=s.substring(156,157),this.ustarFormat=s.substring(257,263),this.ustarFormat.indexOf("ustar")!==-1){let i=s.substring(345,500).replace(/\0/g,"");i.length>0&&(this.fileName=i.trim()+this.fileName.trim())}this.bytesRead+=512}if(this.headerRead){if(this.bytesReceived{let a=()=>{fetch(t,e).then(i).catch(o=>{s++,s{let i=new $c;e(null,i);let r=new t0(s,this._assets.prefix);r.on("file",a=>{i.addFile(a.name,a.data)}),r.on("done",()=>{i.loaded=!0}),r.on("error",a=>{e(a)})}).catch(s=>{e(s)})}open(t,e){return e}};var Zc=class c{constructor(t){this._handlers={},this._requests={},this._cache={},this._app=t}addHandler(t,e){this._handlers[t]=e,e._loader=this}removeHandler(t){delete this._handlers[t]}getHandler(t){return this._handlers[t]}static makeKey(t,e){return`${t}-${e}`}load(t,e,s,i,r){let a=this._handlers[e];if(!a){let l=`No resource handler for asset type: '${e}' when loading [${t}]`;s(l);return}if(!t){this._loadNull(a,s,i);return}let o=c.makeKey(t,e);if(this._cache[o]!==void 0)s(null,this._cache[o]);else if(this._requests[o])this._requests[o].push(s);else{this._requests[o]=[s];let l=this,h=function(u,d){if(u){l._onFailure(o,u);return}if(d.load instanceof DataView){if(a.openBinary){if(!l._requests[o])return;try{let p=a.openBinary(d.load);l._onSuccess(o,p)}catch(p){l._onFailure(o,p)}return}d.load=URL.createObjectURL(new Blob([d.load])),i&&(i.urlObject&&URL.revokeObjectURL(i.urlObject),i.urlObject=d.load)}a.load(d,(p,m,_)=>{if(l._requests[o]){if(p){l._onFailure(o,p);return}try{l._onSuccess(o,a.open(d.original,m,i),_)}catch(S){l._onFailure(o,S)}}},i)},f=t.split("?")[0];if(this._app.enableBundles&&this._app.bundles.hasUrl(f)&&!(r&&r.bundlesIgnore)){if(!this._app.bundles.urlIsLoadedOrLoading(f)){let u=this._app.bundles.listBundlesForAsset(i),d;r&&r.bundlesFilter&&(d=r.bundlesFilter(u)),d||(u?.sort((p,m)=>p.file.size-m.file.size),d=u?.[0]),d&&this._app.assets?.load(d)}this._app.bundles.loadUrl(f,(u,d)=>{h(u,{load:d,original:f})})}else h(null,{load:t,original:i&&i.file.filename||t})}}_loadNull(t,e,s){let i=function(r,a,o){if(r)e(r);else try{e(null,t.open(null,a,s),o)}catch(l){e(l)}};t.load(null,i,s)}_onSuccess(t,e,s){e!==null?this._cache[t]=e:delete this._cache[t];for(let i=0;ic&&c[0].toLowerCase()+c.substring(1);function r0(c){if(typeof c!="function")return;if(Object.prototype.hasOwnProperty.call(c,"scriptName")&&c.scriptName)return c.scriptName;if("name"in Function.prototype)return c.name;if(c===Function||c===Function.prototype.constructor)return"Function";let t=`${c}`.match(T8);return t?t[1]:void 0}function Qc(c){if(typeof c!="function")return;if(Object.prototype.hasOwnProperty.call(c,"__name")&&c.__name)return c.__name;if(Object.prototype.hasOwnProperty.call(c,"scriptName")&&c.scriptName)return c.scriptName;let t=r0(c);return t?y8(t):void 0}var Sm=class extends J{constructor(e){super();n(this,"_scripts",new Map);n(this,"_list",[]);n(this,"_scriptSchemas",new Map);this.app=e}destroy(){this.app=null,this.off()}addSchema(e,s){s&&this._scriptSchemas.set(e,s)}getSchema(e){return this._scriptSchemas.get(e)}add(e){let s=Qc(e);return!s||gm.has(s)?!1:(e.__name=s,this._scripts.has(s)?(setTimeout(()=>{if(e.prototype.swap){let i=this._scripts.get(s),r=this._list.indexOf(i);this._list[r]=e,this._scripts.set(s,e),this.fire("swap",s,e),this.fire(`swap:${s}`,e)}}),!1):(this._scripts.set(s,e),this._list.push(e),this.fire("add",s,e),this.fire(`add:${s}`,e),setTimeout(()=>{if(!this._scripts.has(s)||!this.app||!this.app.systems||!this.app.systems.script)return;let i=this.app.systems.script._components,r,a=[],o=[];for(i.loopIndex=0;i.loopIndexc.constructor.order-t.constructor.order,A8=c=>c.sort(E8),bS=[],R2=[],C8=()=>R2.pop()??[],I2=c=>{c.length=0,R2.push(c)},a0=class a0 extends Pe{constructor(e,s=ys()){super(e);n(this,"anim");n(this,"animation");n(this,"audiolistener");n(this,"button");n(this,"camera");n(this,"collision");n(this,"element");n(this,"gsplat");n(this,"layoutchild");n(this,"layoutgroup");n(this,"light");n(this,"model");n(this,"particlesystem");n(this,"render");n(this,"rigidbody");n(this,"screen");n(this,"script");n(this,"scrollbar");n(this,"scrollview");n(this,"sound");n(this,"sprite");n(this,"c",{});n(this,"_app");n(this,"_destroying",!1);n(this,"_guid",null);n(this,"_template",!1);this._app=s}addComponent(e,s){let i=this._app.systems[e];return!i||this.c[e]?null:i.addComponent(this,s)}removeComponent(e){let s=this._app.systems[e];s&&this.c[e]&&s.removeComponent(this)}findComponent(e){let s=this.findOne(i=>i.c?.[e]);return s&&s.c[e]}findComponents(e){return this.find(s=>s.c?.[e]).map(s=>s.c[e])}findScript(e){return this.findOne(i=>i.c?.script?.has(e))?.c.script.get(e)}findScripts(e){return this.find(i=>i.c?.script?.has(e)).map(i=>i.c.script.get(e))}set guid(e){let s=this._app._entityIndex;this._guid&&delete s[this._guid],this._guid=e,s[this._guid]=this}get guid(){return this._guid||(this.guid=bx.create()),this._guid}getGuid(){return this.guid}setGuid(e){this.guid=e}_notifyHierarchyStateChanged(e,s){let i=!1;e===this&&bS.length===0&&(i=!0),e._beingEnabled=!0,e._onHierarchyStateChanged(s),e._onHierarchyStatePostChanged&&bS.push(e);let r=e._children;for(let a=0,o=r.length;a1&&A8(s),s}_cloneRecursively(e){let s=new this.constructor(void 0,this._app);super._cloneInternal(s);for(let i in this.c)this.c[i].system.cloneComponent(this,s);for(let i=0;io instanceof Ne),a=e.children.filter(o=>o instanceof Ne);for(let o=0,l=r.length;o{t.data=l,t._loading=!1;for(let h=0;h{if(i){s&&s(i);return}e&&e(r);let a=this._app,o=()=>{let l=a.loader.getHandler("hierarchy");a.systems.script.preloading=!0;let h=l.open(r.url,r.data);a.systems.script.preloading=!1,a.loader.clearCache(r.url,"hierarchy"),a.root.addChild(h),a.systems.fire("initialize",h),a.systems.fire("postInitialize",h),a.systems.fire("postPostInitialize",h),s&&s(null,h)};a._preloadScripts(r.data,o)})}loadSceneHierarchy(t,e){this._loadSceneHierarchy(t,null,e)}loadSceneSettings(t,e){this._loadSceneData(t,!1,(s,i)=>{s?e&&e(s):(this._app.applySceneSettings(i.data.settings),e&&e(null))})}changeScene(t,e){let s=this._app,i=r=>{let{children:a}=s.root;for(;a.length;)a[0].destroy();s.applySceneSettings(r.data.settings)};this._loadSceneHierarchy(t,i,e)}loadScene(t,e){let s=this._app,i=s.loader.getHandler("scene");s.assets&&s.assets.prefix&&!Ja.test(t)&&(t=xe.join(s.assets.prefix,t)),i.load(t,(r,a)=>{if(r)e&&e(r);else{let o=()=>{s.systems.script.preloading=!0;let l=i.open(t,a),h=this.findByUrl(t);h&&!h.loaded&&(h.data=a),s.systems.script.preloading=!1,s.loader.clearCache(t,"scene"),s.loader.patch({resource:l,type:"scene"},s.assets),s.root.addChild(l.root),s.systems.rigidbody&&typeof Ammo<"u"&&s.systems.rigidbody.gravity.set(l._gravity.x,l._gravity.y,l._gravity.z),e&&e(null,l)};s._preloadScripts(a,o)}})}};var o0=class{constructor(t){this.frame={fps:0,ms:0,dt:0,updateStart:0,updateTime:0,renderStart:0,renderTime:0,physicsStart:0,physicsTime:0,scriptUpdateStart:0,scriptUpdate:0,scriptPostUpdateStart:0,scriptPostUpdate:0,animUpdateStart:0,animUpdate:0,cullTime:0,sortTime:0,skinTime:0,morphTime:0,instancingTime:0,triangles:0,gsplats:0,gsplatSort:0,gsplatBufferCopy:0,otherPrimitives:0,shaders:0,materials:0,cameras:0,shadowMapUpdates:0,shadowMapTime:0,depthMapTime:0,forwardTime:0,lightClustersTime:0,lightClusters:0,_timeToCountFrames:0,_fpsAccum:0},this.drawCalls={forward:0,depth:0,shadow:0,immediate:0,misc:0,total:0,skinned:0,instanced:0,removedByInstancing:0},this.misc={renderTargetCreationTime:0},this.particles={updatesPerFrame:0,_updatesPerFrame:0,frameTime:0,_frameTime:0},this.shaders=t._shaderStats,this.vram=t._vram,this.gpu=t.gpuProfiler?.passTimings??new Map,Object.defineProperty(this.vram,"totalUsed",{get:function(){return this.tex+this.vb+this.ib+this.ub+this.sb}}),Object.defineProperty(this.vram,"geom",{get:function(){return this.vb+this.ib}}),Object.defineProperty(this.vram,"buffers",{get:function(){return this.ub+this.sb}})}get scene(){return ys().scene._stats}get lightmapper(){return ys().lightmapper?.stats}get batcher(){let t=ys()._batcher;return t?t._stats:null}updateBasic(t,e,s,i,r){let a=this.frame;a.dt=e,a.ms=s,t>a._timeToCountFrames?(a.fps=a._fpsAccum,a._fpsAccum=0,a._timeToCountFrames=t+1e3):a._fpsAccum++,this.drawCalls.total=r._drawCallsPerFrame,r._drawCallsPerFrame=0,a.gsplats=i._gsplatCount,a.gsplatBufferCopy=i._gsplatBufferCopy??0}updateDetailed(t,e){let s=this.frame;s.cameras=t._camerasRendered,s.materials=t._materialSwitches,s.shaders=e._shaderSwitchesPerFrame,s.shadowMapUpdates=t._shadowMapUpdates,s.shadowMapTime=t._shadowMapTime,s.depthMapTime=t._depthMapTime,s.forwardTime=t._forwardTime;let i=e._primsPerFrame;s.triangles=i[Yt]/3+Math.max(i[Ks]-2,0)+Math.max(i[dr]-2,0),s.cullTime=t._cullTime,s.sortTime=t._sortTime,s.skinTime=t._skinTime,s.morphTime=t._morphTime,s.lightClusters=t._lightClusters,s.lightClustersTime=t._lightClustersTime,s.otherPrimitives=0;for(let r=0;r 0.5) { if (dAtten > 0.00001) { 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; #endif #if LIT_AMBIENT_SOURCE == ENVALATLAS #include "envAtlasPS" #ifndef ENV_ATLAS #define ENV_ATLAS var texture_envAtlas: texture_2d; 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 nineSlicedUv: vec2f; `;var IO=` #define NINESLICED #define NINESLICETILED varying vMask: vec2f; varying vTiledUv: vec2f; uniform innerOffset: vec4f; uniform outerScale: vec2f; uniform atlasRect: vec4f; var 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; var sourceSampler: sampler; #ifdef GAUSS uniform weight: array; #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, 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, 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, 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; var lightsTexture: texture_2d; #ifdef CLUSTER_SHADOWS var shadowAtlasTexture: texture_depth_2d; var shadowAtlasTextureSampler: sampler_comparison; #endif #ifdef CLUSTER_COOKIES var cookieAtlasTexture: texture_2d; 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 lightProjectionMatrix: mat4x4f; var clusterLightData_flags: u32; var clusterLightData_anglesData: f32; var clusterLightData_colorBFlagsData: u32; fn sampleLightTextureF(lightIndex: i32, index: i32) -> vec4f { return textureLoad(lightsTexture, vec2(index, lightIndex), 0); } fn decodeClusterLightCore(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(halfData.y); let colorRG: vec2f = unpack2x16float(bitcast(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(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(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(biasesData)); return ClusterLightShadowData(biases.x, biases.y); } fn decodeClusterLightCookieData() -> vec4f { let cookieFlags: u32 = (clusterLightData_flags >> 23u) & 0x0Fu; let mask_uvec: vec4 = vec4(cookieFlags) & vec4(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(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; 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; var blitTexture: texture_cube; 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(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(value * 255.0); let intBits: u32 = (rgba_u32.r << 24u) | (rgba_u32.g << 16u) | (rgba_u32.b << 8u) | rgba_u32.a; return bitcast(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 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; 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; 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, 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, 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; var areaLightsLutTex1Sampler: sampler; var areaLightsLutTex2: texture_2d; 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 dLightmapDir: vec3f; var texture_dirLightMap: texture_2d; 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 sReflection: vec3f; var dVertexNormalW: vec3f; var dTangentW: vec3f; var dBinormalW: vec3f; var dViewDirW: vec3f; var dReflDirW: vec3f; var ccReflDirW: vec3f; var dLightDirNormW: vec3f; var dAtten: f32; var dTBN: mat3x3f; var dReflection: vec4f; var dDiffuseLight: vec3f; var dSpecularLight: vec3f; var ccFresnel: f32; var ccReflection: vec3f; var ccSpecularLight: vec3f; var ccSpecularityNoFres: f32; var 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; var ssaoTextureSampler : sampler; uniform ssaoTextureSizeInv: vec2f; #endif #ifdef LIT_SHADOW_CATCHER var 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 dMaskGlobal: vec2f; var dTiledUvGlobal: vec2f; uniform innerOffset: vec4f; uniform outerScale: vec2f; uniform atlasRect: vec4f; #endif var dPositionW: vec3f; var 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 litArgs_albedo: vec3f; var litArgs_opacity: f32; var litArgs_emission: vec3f; var litArgs_worldNormal: vec3f; var litArgs_ao: f32; var litArgs_lightmap: vec3f; var litArgs_lightmapDir: vec3f; var litArgs_metalness: f32; var litArgs_specularity: vec3f; var litArgs_specularityFactor: f32; var litArgs_gloss: f32; var litArgs_sheen_gloss: f32; var litArgs_sheen_specularity: vec3f; var litArgs_transmission: f32; var litArgs_thickness: f32; var litArgs_ior: f32; var litArgs_dispersion: f32; var litArgs_iridescence_intensity: f32; var litArgs_iridescence_thickness: f32; var litArgs_clearcoat_worldNormal: vec3f; var litArgs_clearcoat_specularity: f32; var litArgs_clearcoat_gloss: f32; `;var kF=` #if LIT_NONE_SLICE_MODE == TILED var 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; 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 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 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 dLTCUV: vec2f; #ifdef LIT_CLEARCOAT var 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 dLTCSpecFres: vec3f; #ifdef LIT_CLEARCOAT var 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; 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; 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; uniform morphFactor: array; uniform morphIndex: array; uniform count: u32; @fragment fn fragmentMain(input : FragmentInput) -> FragmentOutput { var color = vec3f(0, 0, 0); let textureDims = textureDimensions(morphTexture); let pixelCoords = vec2i(input.uv0 * vec2f(textureDims)); for (var i: u32 = 0; i < uniform.count; i = i + 1) { var textureIndex: u32 = uniform.morphIndex[i].element; var delta = textureLoad(morphTexture, pixelCoords, textureIndex, 0).xyz; color += uniform.morphFactor[i].element * delta; } var output: FragmentOutput; output.color = vec4f(color, 1.0); return output; } `;var YF=` attribute vertex_position: vec2f; varying uv0: vec2f; @vertex fn vertexMain(input: VertexInput) -> VertexOutput { var output: VertexOutput; output.position = vec4f(input.vertex_position, 0.5, 1.0); output.uv0 = input.vertex_position * 0.5 + vec2f(0.5, 0.5); return output; } `;var KF=` attribute vertex_outlineParameters: vec3f; attribute vertex_shadowParameters: vec3f; varying outline_color: vec4f; varying outline_thickness: f32; varying shadow_color: vec4f; varying shadow_offset: vec2f; var dOutlineColor: vec4f; var dOutlineThickness: f32; var dShadowColor: vec4f; var 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 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; var morphNormalTexSampler: sampler; #else var morphNormalTex: texture_2d; 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; 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; 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; 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; var texture_envAtlasSampler: sampler; #endif var texture_cubeMap: texture_cube; 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; 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; 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; var sourceCubeSampler : sampler; #else var sourceTex: texture_2d; var sourceTexSampler : sampler; #endif #ifdef USE_SAMPLES_TEX var samplesTex: texture_2d; 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, mipLevel: ptr) { 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; #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, 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, 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, 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, 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, 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, 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, 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) -> 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, shadowMapSampler: sampler, avgBlockerDepth: ptr, numBlockers: ptr, 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, 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, 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, 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; 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; 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; 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; 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 ) { 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 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; var texture_opacityMapSampler : sampler; #endif #endif #ifdef FORWARD_PASS var dAlbedo: vec3f; var dNormalW: vec3f; var dSpecularity: vec3f = vec3f(0.0, 0.0, 0.0); var dGlossiness: f32 = 0.0; #ifdef LIT_REFRACTION var dTransmission: f32; var dThickness: f32; #endif #ifdef LIT_SCENE_COLOR var uSceneColorMap : texture_2d; var uSceneColorMapSampler : sampler; #endif #ifdef LIT_SCREEN_SIZE uniform uScreenSize: vec4f; #endif #ifdef LIT_TRANSFORMS var matrix_viewProjection: mat4x4f; var matrix_model: mat4x4f; #endif #ifdef STD_HEIGHT_MAP var dUvOffset: vec2f; #ifdef STD_HEIGHT_TEXTURE_ALLOCATE var texture_heightMap : texture_2d; var texture_heightMapSampler : sampler; #endif #endif #ifdef STD_DIFFUSE_TEXTURE_ALLOCATE var texture_diffuseMap : texture_2d; var texture_diffuseMapSampler : sampler; #endif #ifdef STD_DIFFUSEDETAIL_TEXTURE_ALLOCATE var texture_diffuseDetailMap : texture_2d; var texture_diffuseDetailMapSampler : sampler; #endif #ifdef STD_NORMAL_TEXTURE_ALLOCATE var texture_normalMap : texture_2d; var texture_normalMapSampler : sampler; #endif #ifdef STD_NORMALDETAIL_TEXTURE_ALLOCATE var texture_normalDetailMap : texture_2d; var texture_normalDetailMapSampler : sampler; #endif #ifdef STD_THICKNESS_TEXTURE_ALLOCATE var texture_thicknessMap : texture_2d; var texture_thicknessMapSampler : sampler; #endif #ifdef STD_REFRACTION_TEXTURE_ALLOCATE var texture_refractionMap : texture_2d; var texture_refractionMapSampler : sampler; #endif #ifdef LIT_IRIDESCENCE var dIridescence: f32; var dIridescenceThickness: f32; #ifdef STD_IRIDESCENCE_THICKNESS_TEXTURE_ALLOCATE var texture_iridescenceThicknessMap : texture_2d; var texture_iridescenceThicknessMapSampler : sampler; #endif #ifdef STD_IRIDESCENCE_TEXTURE_ALLOCATE var texture_iridescenceMap : texture_2d; var texture_iridescenceMapSampler : sampler; #endif #endif #ifdef LIT_CLEARCOAT var ccSpecularity: f32; var ccGlossiness: f32; var ccNormalW: vec3f; #endif #ifdef LIT_GGX_SPECULAR var dAnisotropy: f32; var dAnisotropyRotation: vec2f; #endif #ifdef LIT_SPECULAR_OR_REFLECTION #ifdef LIT_SHEEN var sSpecularity: vec3f; var sGlossiness: f32; #ifdef STD_SHEEN_TEXTURE_ALLOCATE var texture_sheenMap : texture_2d; var texture_sheenMapSampler : sampler; #endif #ifdef STD_SHEENGLOSS_TEXTURE_ALLOCATE var texture_sheenGlossMap : texture_2d; var texture_sheenGlossMapSampler : sampler; #endif #endif #ifdef LIT_METALNESS var dMetalness: f32; var dIor: f32; #ifdef STD_METALNESS_TEXTURE_ALLOCATE var texture_metalnessMap : texture_2d; var texture_metalnessMapSampler : sampler; #endif #endif #ifdef LIT_SPECULARITY_FACTOR var dSpecularityFactor: f32; #ifdef STD_SPECULARITYFACTOR_TEXTURE_ALLOCATE var texture_specularityFactorMap : texture_2d; var texture_specularityFactorMapSampler : sampler; #endif #endif #ifdef STD_SPECULAR_COLOR #ifdef STD_SPECULAR_TEXTURE_ALLOCATE var texture_specularMap : texture_2d; var texture_specularMapSampler : sampler; #endif #endif #ifdef STD_GLOSS_TEXTURE_ALLOCATE var texture_glossMap : texture_2d; var texture_glossMapSampler : sampler; #endif #endif #ifdef STD_AO var dAo: f32; #ifdef STD_AO_TEXTURE_ALLOCATE var texture_aoMap : texture_2d; var texture_aoMapSampler : sampler; #endif #ifdef STD_AODETAIL_TEXTURE_ALLOCATE var texture_aoDetailMap : texture_2d; var texture_aoDetailMapSampler : sampler; #endif #endif var dEmission: vec3f; #ifdef STD_EMISSIVE_TEXTURE_ALLOCATE var texture_emissiveMap : texture_2d; var texture_emissiveMapSampler : sampler; #endif #ifdef LIT_CLEARCOAT #ifdef STD_CLEARCOAT_TEXTURE_ALLOCATE var texture_clearCoatMap : texture_2d; var texture_clearCoatMapSampler : sampler; #endif #ifdef STD_CLEARCOATGLOSS_TEXTURE_ALLOCATE var texture_clearCoatGlossMap : texture_2d; var texture_clearCoatGlossMapSampler : sampler; #endif #ifdef STD_CLEARCOATNORMAL_TEXTURE_ALLOCATE var texture_clearCoatNormalMap : texture_2d; var texture_clearCoatNormalMapSampler : sampler; #endif #endif #ifdef LIT_GGX_SPECULAR #ifdef STD_ANISOTROPY_TEXTURE_ALLOCATE var texture_anisotropyMap : texture_2d; var texture_anisotropyMapSampler : sampler; #endif #endif #if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR) var dLightmap: vec3f; #ifdef STD_LIGHT_TEXTURE_ALLOCATE var texture_lightMap : texture_2d; 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; #else var morphPositionTex: texture_2d; #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{r--,l?s(l):r===0&&(this.onLibrariesLoaded(),s(null))};for(let l=0;l0,l.tags.add(o.tags),o.i18n)for(let h in o.i18n)l.addLocalizedAssetId(h,o.i18n[h]);this.assets.add(l)}}start(){this.frame=0,this.fire("start",{timestamp:Tt(),target:this}),this._librariesLoaded||this.onLibrariesLoaded(),this.systems.fire("initialize",this.root),this.fire("initialize"),this.systems.fire("postInitialize",this.root),this.systems.fire("postPostInitialize",this.root),this.fire("postinitialize"),this.requestAnimationFrame()}requestAnimationFrame(){this.xr?.session?this.frameRequestId=this.xr.session.requestAnimationFrame(this.tick):this.frameRequestId=ue.browser||ue.worker?requestAnimationFrame(this.tick):null}inputUpdate(e){this.mouse&&this.mouse.update(),this.keyboard&&this.keyboard.update(),this.gamepads&&this.gamepads.update()}update(e){this.frame++,this.graphicsDevice.update(),this.stats.frame.scriptUpdateStart=Tt(),this.systems.fire(this._inTools?"toolsUpdate":"update",e),this.stats.frame.scriptUpdate=Tt()-this.stats.frame.scriptUpdateStart,this.stats.frame.animUpdateStart=Tt(),this.systems.fire("animationUpdate",e),this.stats.frame.animUpdate=Tt()-this.stats.frame.animUpdateStart,this.stats.frame.scriptPostUpdateStart=Tt(),this.systems.fire("postUpdate",e),this.stats.frame.scriptPostUpdate=Tt()-this.stats.frame.scriptPostUpdateStart,this.fire("update",e),this.inputUpdate(e)}render(){this.updateCanvasSize(),this.graphicsDevice.frameStart(),this.fire("prerender"),this.root.syncHierarchy(),this._batcher&&this._batcher.updateAll(),this.renderComposition(this.scene.layers),this.fire("postrender"),this.stats.frame.renderTime=Tt()-this.stats.frame.renderStart,this.graphicsDevice.frameEnd()}renderComposition(e){this.renderer.update(e),this.renderer.buildFrameGraph(this.frameGraph,e),this.frameGraph.render(this.graphicsDevice)}setCanvasFillMode(e,s,i){this._fillMode=e,this.resizeCanvas(s,i)}setCanvasResolution(e,s,i){this._resolutionMode=e,e===jy&&s===void 0&&(s=this.graphicsDevice.canvas.clientWidth,i=this.graphicsDevice.canvas.clientHeight),this.graphicsDevice.resizeCanvas(s,i)}isHidden(){return document.hidden}onVisibilityChange(){this.isHidden()?this._soundManager&&this._soundManager.suspend():this._soundManager&&this._soundManager.resume()}resizeCanvas(e,s){if(!this._allowResize||this.xr&&this.xr.session)return;let i=window.innerWidth,r=window.innerHeight;if(this._fillMode===Ky){let a=this.graphicsDevice.canvas.width/this.graphicsDevice.canvas.height,o=i/r;a>o?(e=i,s=e/a):(s=r,e=s*a)}else this._fillMode===bI&&(e=i,s=r);return this.graphicsDevice.canvas.style.width=`${e}px`,this.graphicsDevice.canvas.style.height=`${s}px`,this.updateCanvasSize(),{width:e,height:s}}updateCanvasSize(){if(!(!this._allowResize||this.xr?.active)&&this._resolutionMode===jy){let e=this.graphicsDevice.canvas;this.graphicsDevice.resizeCanvas(e.clientWidth,e.clientHeight)}}onLibrariesLoaded(){this._librariesLoaded=!0,this.systems.rigidbody&&this.systems.rigidbody.onLibraryLoaded()}applySceneSettings(e){let s;if(this.systems.rigidbody&&typeof Ammo<"u"){let[i,r,a]=e.physics.gravity;this.systems.rigidbody.gravity.set(i,r,a)}this.scene.applySettings(e),e.render.hasOwnProperty("skybox")&&(e.render.skybox?(s=this.assets.get(e.render.skybox),s?this.setSkybox(s):this.assets.once(`add:${e.render.skybox}`,this.setSkybox,this)):this.setSkybox(null))}setAreaLightLuts(e,s){e&&s&&wS.set(this.graphicsDevice,e,s)}setSkybox(e){if(e!==this._skyboxAsset){let s=()=>{this.setSkybox(null)},i=()=>{this.scene.setSkybox(this._skyboxAsset?this._skyboxAsset.resources:null)};this._skyboxAsset&&(this.assets.off(`load:${this._skyboxAsset.id}`,i,this),this.assets.off(`remove:${this._skyboxAsset.id}`,s,this),this._skyboxAsset.off("change",i,this)),this._skyboxAsset=e,this._skyboxAsset&&(this.assets.on(`load:${this._skyboxAsset.id}`,i,this),this.assets.once(`remove:${this._skyboxAsset.id}`,s,this),this._skyboxAsset.on("change",i,this),this.scene.skyboxMip===0&&!this._skyboxAsset.loadFaces&&(this._skyboxAsset.loadFaces=!0),this.assets.load(this._skyboxAsset)),i()}}_firstBake(){this.lightmapper?.bake(null,this.scene.lightmapMode)}_firstBatch(){this.batcher?.generate()}_processTimestamp(e){return e}drawLine(e,s,i,r,a){this.scene.drawLine(e,s,i,r,a)}drawLines(e,s,i=!0,r=this.scene.defaultDrawLayer){this.scene.drawLines(e,s,i,r)}drawLineArrays(e,s,i=!0,r=this.scene.defaultDrawLayer){this.scene.drawLineArrays(e,s,i,r)}drawWireSphere(e,s,i=F.WHITE,r=20,a=!0,o=this.scene.defaultDrawLayer){this.scene.immediate.drawWireSphere(e,s,i,r,a,o)}drawWireAlignedBox(e,s,i=F.WHITE,r=!0,a=this.scene.defaultDrawLayer,o){this.scene.immediate.drawWireAlignedBox(e,s,i,r,a,o)}drawMeshInstance(e,s=this.scene.defaultDrawLayer){this.scene.immediate.drawMesh(null,null,null,e,s)}drawMesh(e,s,i,r=this.scene.defaultDrawLayer){this.scene.immediate.drawMesh(s,i,e,null,r)}drawQuad(e,s,i=this.scene.defaultDrawLayer){this.scene.immediate.drawMesh(s,e,this.scene.immediate.getQuadMesh(),null,i)}drawTexture(e,s,i,r,a,o,l=this.scene.defaultDrawLayer,h=!0){if(h===!1&&!this.graphicsDevice.isWebGPU)return;let f=new W;f.setTRS(new x(e,s,0),$.IDENTITY,new x(i,-r,0)),o||(o=new ct,o.cull=0,o.setParameter("colorMap",a),o.shaderDesc=h?this.scene.immediate.getTextureShaderDesc(a.encoding):this.scene.immediate.getUnfilterableTextureShaderDesc(),o.update()),this.drawQuad(f,o,l)}drawDepthTexture(e,s,i,r,a=this.scene.defaultDrawLayer){let o=new ct;o.cull=0,o.shaderDesc=this.scene.immediate.getDepthTextureShaderDesc(),o.update(),this.drawTexture(e,s,i,r,null,o,a)}destroy(){if(this._inFrameUpdate){this._destroyRequested=!0;return}let e=this.graphicsDevice.canvas.id;this.fire("destroy",this),this.off("librariesloaded"),this._gsplatSortedEvt?.off(),this._gsplatSortedEvt=null,typeof document<"u"&&document.removeEventListener("visibilitychange",this._visibilityChangeHandler,!1),this._visibilityChangeHandler=null,this.root.destroy(),this.root=null,this.mouse&&(this.mouse.off(),this.mouse.detach(),this.mouse=null),this.keyboard&&(this.keyboard.off(),this.keyboard.detach(),this.keyboard=null),this.touch&&(this.touch.off(),this.touch.detach(),this.touch=null),this.elementInput&&(this.elementInput.detach(),this.elementInput=null),this.gamepads&&(this.gamepads.destroy(),this.gamepads=null),this.systems.destroy(),this.scene.layers&&this.scene.layers.destroy(),this.bundles.destroy(),this.bundles=null,this.i18n.destroy(),this.i18n=null,this.loader.getHandler("script")?.clearCache(),this.loader.destroy(),this.loader=null,this.systems=null,this.context=null,this.scripts.destroy(),this.scripts=null,this.scenes.destroy(),this.scenes=null,this.lightmapper?.destroy(),this.lightmapper=null,this._batcher&&(this._batcher.destroy(),this._batcher=null),this._entityIndex={},this.defaultLayerDepth.onDisable=null,this.defaultLayerDepth.onEnable=null,this.defaultLayerDepth=null,this.defaultLayerWorld=null,this.xr?.end(),this.xr?.destroy(),this.renderer.destroy(),this.renderer=null;let i=this.assets.list();for(let r=0;r{this.stats.frame.gsplatSort+=s})}};n(ou,"_applications",{});var Pi=ou;var Tm=class{constructor(){n(this,"elementInput");n(this,"keyboard");n(this,"mouse");n(this,"touch");n(this,"gamepads");n(this,"scriptPrefix");n(this,"assetPrefix");n(this,"scriptsOrder");n(this,"soundManager");n(this,"graphicsDevice");n(this,"lightmapper");n(this,"batchManager");n(this,"xr");n(this,"componentSystems",[]);n(this,"resourceHandlers",[])}};var DS=new Br,ym=class{constructor(t,e,s){this.scene=t,this.light=e,this.store(),e.numCascades=1,this.scene.clusteredLightingEnabled&&!s.shadowsEnabled&&(e.castShadows=!1),e.type!==Ce&&(e._node.getWorldTransform(),e.getBoundingSphere(DS),this.lightBounds=new ge,this.lightBounds.center.copy(DS.center),this.lightBounds.halfExtents.set(DS.radius,DS.radius,DS.radius))}store(){this.mask=this.light.mask,this.shadowUpdateMode=this.light.shadowUpdateMode,this.enabled=this.light.enabled,this.intensity=this.light.intensity,this.rotation=this.light._node.getLocalRotation().clone(),this.numCascades=this.light.numCascades,this.castShadows=this.light._castShadows}restore(){let t=this.light;t.mask=this.mask,t.shadowUpdateMode=this.shadowUpdateMode,t.enabled=this.enabled,t.intensity=this.intensity,t._node.setLocalRotation(this.rotation),t.numCascades=this.numCascades,t._castShadows=this.castShadows}startBake(){this.light.enabled=!0,this.light._destroyShadowMap(),this.light.beginFrame()}endBake(t){let e=this.light;e.enabled=!1,e.shadowMap&&(e.shadowMap.cached&&t.add(e,e.shadowMap),e.shadowMap=null)}};var l0=new B,c0=class extends ym{constructor(t,e){super(t.scene,e,t.lightingParams)}get numVirtualLights(){return this.light.type===Ce?this.light.bakeNumSamples:1}prepareVirtualLight(t,e){let s=this.light;if(s._node.setLocalRotation(this.rotation),t>0){let a=s.bakeArea;Rc.circlePointDeterministic(l0,t,e),l0.mulScalar(a*.5),s._node.rotateLocal(l0.x,0,l0.y)}s._node.getWorldTransform();let i=2.2,r=Math.pow(this.intensity,i);s.intensity=Math.pow(r/e,1/i)}};var iB=new x,LS=class extends ym{constructor(t){let e=t.scene,s=new Ne("AmbientLight");s.addComponent("light",{type:"directional",affectDynamic:!0,affectLightmapped:!1,bake:!0,bakeNumSamples:e.ambientBakeNumSamples,castShadows:!0,normalOffsetBias:.05,shadowBias:.2,shadowDistance:1,shadowResolution:2048,shadowType:Oi,color:F.WHITE,intensity:1,bakeDir:!1}),super(e,s.light.light,t.lightingParams)}get numVirtualLights(){return this.light.bakeNumSamples}prepareVirtualLight(t,e){Rc.spherePointDeterministic(iB,t,e,0,this.scene.ambientBakeSpherePart),this.light._node.lookAt(iB.mulScalar(-1)),this.light._node.rotateLocal(90,0,0);let s=2.2,i=2*Math.PI*this.scene.ambientBakeSpherePart,r=Math.pow(i,s);this.light.intensity=Math.pow(r/e,1/s)}};var nu=class{constructor(t,e=null){this.node=t,this.component=t.render||t.model,e=e||this.component.meshInstances,this.store(),this.meshInstances=e,this.bounds=null,this.renderTargets=[]}store(){this.castShadows=this.component.castShadows}restore(){this.component.castShadows=this.castShadows}};var rB=` float normpdf3(in vec3 v, in float sigma) { return 0.39894 * exp(-0.5 * dot(v, v) / (sigma * sigma)) / sigma; } 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; var sourceSampler: sampler; uniform kernel: array; 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; 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;i0&&e.push(new nu(t,a))}}for(let r=0;r0){this.renderer.shadowRenderer.frameUpdate();let u=e===zf?2:1;this.setLightmapping(l,!1,u),this.initBake(s),this.bakeInternal(u,l,h);let d=yc;e===zf&&(d|=Ff),this.scene.ambientBake&&(d|=Bf),this.setLightmapping(l,!0,u,d),this.finishBake(l)}let f=Tt();this.stats.totalRenderTime=f-i,this.stats.shadersLinked=s._shaderStats.linked-r,this.stats.compileTime=s._shaderStats.compileTime-o,this.stats.fboTime=s._renderTargetCreationTime-a,this.stats.lightmapCount=l.length}allocateTextures(t,e){for(let s=0;s0){e.copy(t[0].aabb);for(let s=1;s1&&P>1&&v.light.bakeDir&&(P=1);for(let A=0;A1&&v.prepareVirtualLight(A,P),v.startBake();let w=!1,I=this.lightCameraPrepare(a,v);for(T=0;T0&&A>0||E&&g>0);g++){let M=D.renderTargets[g],H=D.renderTargets[g].colorBuffer.width,U=this.renderTargets.get(H),L=U.colorBuffer;g===0?C=i.updateShaders:C&&(i.updateShaders=!0);let b=this.passMaterials[g];for(E&&A+1===P&&g===0&&(b=this.ambientAOMaterial),p=0;p{let r=typeof i=="object"?i.name:i;Object.defineProperty(e,r,{get:function(){return this.data[r]},set:function(a){let o=this.data,l=o[r];o[r]=a,this.fire("set",r,l,a)},configurable:!0})}),e._accessorsBuilt=!0}buildAccessors(e){d0._buildAccessors(this,e)}onSetEnabled(e,s,i){s!==i&&this.entity.enabled&&(i?this.onEnable():this.onDisable())}onEnable(){}onDisable(){}onPostStateChange(){}get data(){let e=this.system.store[this.entity.guid];return e?e.data:null}set enabled(e){}get enabled(){return!0}};n(d0,"order",0);var le=d0;var Fe=class extends J{constructor(e){super();n(this,"id");this.app=e,this.store={},this.schema=[]}addComponent(e,s={}){let i=new this.ComponentType(this,e),r=new this.DataType;return this.store[e.guid]={entity:e,data:r},e[this.id]=i,e.c[this.id]=i,this.initializeComponentData(i,s,[]),this.fire("add",e,i),i}removeComponent(e){let s=this.id,i=this.store[e.guid],r=e.c[s];r.fire("beforeremove"),this.fire("beforeremove",e,r),delete this.store[e.guid],e[s]=void 0,delete e.c[s],this.fire("remove",e,i.data)}cloneComponent(e,s){let i=this.store[e.guid];return this.addComponent(s,i.data)}initializeComponentData(e,s={},i){for(let r=0,a=i.length;r{r&&typeof r=="object"&&r.type===e&&s.push(r)}),s}destroy(){this.off()}};function D8(c,t){if(!c)return c;switch(t){case"rgb":return c instanceof F?c.clone():new F(c[0],c[1],c[2]);case"rgba":return c instanceof F?c.clone():new F(c[0],c[1],c[2],c[3]);case"vec2":return c instanceof B?c.clone():new B(c[0],c[1]);case"vec3":return c instanceof x?c.clone():new x(c[0],c[1],c[2]);case"vec4":return c instanceof Q?c.clone():new Q(c[0],c[1],c[2],c[3]);case"boolean":case"number":case"string":return c;case"entity":return c;default:throw new Error(`Could not convert unhandled type: ${t}`)}}var cB=0,OI=1,FI=2;var p0=class{constructor(){this._left=1/0,this._right=-1/0,this._len=0,this._recip=0,this._p0=0,this._p1=0,this._t=0,this._hermite={valid:!1,p0:0,m0:0,p1:0,m1:0}}update(t,e){if(t=this._right){let s=e.length;if(!s)this._left=-1/0,this._right=1/0,this._len=0,this._recip=0,this._p0=this._p1=0;else if(t=e[s-1])this._left=e[s-1],this._right=1/0,this._len=0,this._recip=0,this._p0=this._p1=s-1;else{let i=this._findKey(t,e);this._left=e[i],this._right=e[i+1],this._len=this._right-this._left;let r=1/this._len;this._recip=isFinite(r)?r:0,this._p0=i,this._p1=i+1}}this._t=this._recip===0?0:(t-this._left)*this._recip,this._hermite.valid=!1}_findKey(t,e){let s=0;for(;t>=e[s+1];)s++;return s}eval(t,e,s){let i=s._data,r=s._components,a=this._p0*r;if(e===0)for(let o=0;o=t:!1}nextEventBehindTime(t){return this.nextEvent?t===this.track.duration?this.isReverse?this.nextEvent.time>=t:this.nextEvent.time<=t:this.isReverse?this.nextEvent.time>t:this.nextEvent.time=this.track.events.length?this._eventCursor=0:this._eventCursor<0&&(this._eventCursor=this.track.events.length-1)}clipFrameTime(t){let e=MS.eventFrame;e.start=0,e.end=t,e.residual=0,this.isReverse?t<0&&(e.start=this.track.duration,e.end=0,e.residual=t+this.track.duration):t>this.track.duration&&(e.start=0,e.end=this.track.duration,e.residual=t-this.track.duration)}alignCursorToCurrentTime(){for(this.resetEventCursor();this.nextEventBehindTime(this._time)&&this._eventCursor!==this.eventCursorEnd;)this.moveEventCursor()}fireNextEvent(){this._eventHandler.fire(this.nextEvent.name,{track:this.track,...this.nextEvent}),this.moveEventCursor()}fireNextEventInFrame(t,e){return this.nextEventAheadOfTime(t)&&this.nextEventBehindTime(e)?(this.fireNextEvent(),!0):!1}activeEventsForFrame(t,e){let s=MS.eventFrame;this.clipFrameTime(e);let i=this.eventCursor;for(;this.fireNextEventInFrame(t,s.end)&&i!==this.eventCursor;);this.loop&&Math.abs(s.residual)>0&&this.activeEventsForFrame(s.start,s.residual)}progressForTime(t){return t*this._speed/this._track.duration}_update(t){if(this._playing){let e=this._time,s=this._track.duration,i=this._speed,r=this._loop;this._track.events.length>0&&s>0&&this.activeEventsForFrame(e,e+i*t),e+=i*t,i>=0?e>s&&(r?e=e%s||0:(e=this._track.duration,this.pause())):e<0&&(r?e=s+(e%s||0):(e=0,this.pause())),this._time=e}this._time!==this._snapshot._time&&this._track.eval(this._time,this._snapshot)}play(){this._playing=!0,this._time=0}stop(){this._playing=!1,this._time=0}pause(){this._playing=!1}resume(){this._playing=!0}reset(){this._time=0}};n(MS,"eventFrame",{start:0,end:0,residual:0});var th=MS;var Am="NONE",NI="PREV_STATE",BI="NEXT_STATE",UI="PREV_STATE_NEXT_STATE",kI="NEXT_STATE_PREV_STATE",zI="GREATER_THAN",GI="LESS_THAN",VI="GREATER_THAN_EQUAL_TO",HI="LESS_THAN_EQUAL_TO",WI="EQUAL_TO",XI="NOT_EQUAL_TO",m0="INTEGER",_0="FLOAT",g0="BOOLEAN",cu="TRIGGER",hB="1D",YI="2D_DIRECTIONAL",KI="2D_CARTESIAN",jI="DIRECT",hu="START",qI="END",fu="ANY",sh=[hu,"END","ANY"],OS="OVERWRITE",$I="ADDITIVE";var Ir=class c{static dot(t,e){let s=t.length,i=0;for(let r=0;r0){e=1/Math.sqrt(e);let s=t.length;for(let i=0;i0&&(r=1/Math.sqrt(r));for(let a=0;a0;)this.removeClip(0)}updateClipTrack(t,e){this._clips.forEach(s=>{s.name.includes(t)&&(s.track=e)}),this.rebind()}findClip(t){let e=this._clips;for(let s=0;s{this.addClip(e)})}assignMask(t){return this._binder.assignMask(t)}update(t,e=!0){let s=this._clips,i=s.map((o,l)=>l);Ir.stableSort(i,(o,l)=>s[o].blendOrder0&&h._update(t),!e)break;let p,m,_;if(d>=1)for(let S=0;S0)for(let S=0;Se.time-s.time)}get events(){return this._events}};var S0=class S0{constructor(t,e,s,i,r,a=new rh([])){this._name=t,this._duration=e,this._inputs=s,this._outputs=i,this._curves=r,this._animEvents=a}get name(){return this._name}get duration(){return this._duration}get inputs(){return this._inputs}get outputs(){return this._outputs}get curves(){return this._curves}set events(t){this._animEvents=t}get events(){return this._animEvents.events}eval(t,e){e._time=t;let s=this._inputs,i=this._outputs,r=this._curves,a=e._cache,o=e._results;for(let l=0;l0&&s.push(i),s}static encode(t,e,s){return`${Array.isArray(t)?t.join("/"):t}/${e}/${Array.isArray(s)?s.join("/"):s}`}resolve(t){return null}unresolve(t){}update(t){}};var ml=class{constructor(t,e,s,i){t.set?(this._set=t.set,this._get=t.get):this._set=t,this._type=e,this._components=s,this._targetPath=i,this._isTransform=this._targetPath.substring(this._targetPath.length-13)==="localRotation"||this._targetPath.substring(this._targetPath.length-13)==="localPosition"||this._targetPath.substring(this._targetPath.length-10)==="localScale",this._isWeight=this._targetPath.indexOf("weight.")!==-1}get set(){return this._set}get get(){return this._get}get type(){return this._type}get components(){return this._components}get targetPath(){return this._targetPath}get isTransform(){return this._isTransform}get isWeight(){return this._isWeight}get usesLayerBlending(){return this._isTransform||this._isWeight}};var ah=class c{constructor(t){n(this,"_isPathInMask",(t,e)=>{let s=this._mask[t];if(s){if(s.children||e&&s.value!==!1)return!0}else return!1;return!1});if(this.graph=t,!t)return;this._mask=null;let e={},s=function(r){e[r.name]=r;for(let a=0;a0){let h={set:f=>{for(let u=0;u[l[0].getWeight(a)]};return c.createAnimTarget(h,"number",1,r,`weight.${a}`)}return null},materialTexture:(r,a)=>{let o=i(r);if(o){let l;for(let h=0;h{let u=this.animComponent.system.app.assets.get(f[0]);u&&u.resource&&u.type==="texture"&&(l.material[a]=u.resource,l.material.update())};return c.createAnimTarget(h,"vector",1,r,"materialTexture","material")}}return null}}}_isPathActive(t){if(!this._mask)return!0;let e=[t.entityPath[0],this.graph.name];for(let s=0;sr instanceof ae?r.id:r);this.loadAnimationAssets(i)}get assets(){return this._assets}set currentTime(e){if(this.skeleton&&(this.skeleton.currentTime=e,this.skeleton.addTime(0),this.skeleton.updateGraph()),this.animEvaluator){let s=this.animEvaluator.clips;for(let i=0;i0)return e[e.length-1].time}return 0}get duration(){return this.currAnim?this.animations[this.currAnim].duration:0}set loop(e){if(this._loop=e,this.skeleton&&(this.skeleton.looping=e),this.animEvaluator)for(let s=0;s0&&!!this.prevAnim,this.blending&&(this.blend=0,this.blendSpeed=1/s),this.skeleton&&(this.blending?(this.fromSkel.animation=i,this.fromSkel.addTime(this.skeleton._time),this.toSkel.animation=r):this.skeleton.animation=r),this.animEvaluator){let a=this.animEvaluator;if(this.blending)for(;a.clips.length>1;)a.removeClip(0);else this.animEvaluator.removeClips();let o=new th(this.animations[this.currAnim],0,1,!0,this.loop);o.name=this.currAnim,o.blendWeight=this.blending?0:1,o.reset(),this.animEvaluator.addClip(o)}}this.playing=!0}}getAnimation(e){return this.animations[e]}setModel(e){e!==this.model&&(this._resetAnimationController(),this.model=e,this.animations&&this.currAnim&&this.animations[this.currAnim]&&this.play(this.currAnim))}onSetAnimations(){let e=this.entity.model;if(e){let s=e.model;s&&s!==this.model&&this.setModel(s)}if(!this.currAnim&&this.activate&&this.enabled&&this.entity.enabled){let s=Object.keys(this._animations);s.length>0&&this.play(s[0])}}_resetAnimationController(){this.skeleton=null,this.fromSkel=null,this.toSkel=null,this.animEvaluator=null}_createAnimationController(){let e=this.model,s=this.animations,i=!1,r=!1;for(let o in s)s.hasOwnProperty(o)&&(s[o].constructor===Qs?r=!0:i=!0);let a=e.getGraph();i?(this.fromSkel=new Hc(a),this.toSkel=new Hc(a),this.skeleton=new Hc(a),this.skeleton.looping=this.loop,this.skeleton.setGraph(a)):r&&(this.animEvaluator=new ih(new ah(this.entity)))}loadAnimationAssets(e){if(!e||!e.length)return;let s=this.system.app.assets,i=a=>{if(a.resources.length>1)for(let o=0;o{a.off("change",this.onAssetChanged,this),a.on("change",this.onAssetChanged,this),a.off("remove",this.onAssetRemoved,this),a.on("remove",this.onAssetRemoved,this),a.resource?i(a):(a.once("load",i,this),this.enabled&&this.entity.enabled&&s.load(a))};for(let a=0,o=e.length;a1){if(r&&r.length>1)for(let o=0;o1)for(let o=0;o1)for(let a=0;a1)for(let s=0;s0&&this.play(i[0])}}onBeforeRemove(){for(let e=0;e=1&&(this.blend=1)),this.playing){let i=this.skeleton;if(i!==null&&this.model!==null){if(this.blending)i.blend(this.fromSkel,this.toSkel,this.blend);else{let r=e*this.speed;i.addTime(r),this.speed>0&&i._time===i.animation.duration&&!this.loop?this.playing=!1:this.speed<0&&i._time===0&&!this.loop&&(this.playing=!1)}this.blending&&this.blend===1&&(i.animation=this.toSkel.animation),i.updateGraph()}}let s=this.animEvaluator;if(s){for(let i=0;i1&&(s.clips[1].blendWeight=this.blend),s.update(e)}this.blending&&this.blend===1&&(this.blending=!1)}};var x0=class{constructor(){n(this,"enabled",!0)}};var ZI=["enabled"],Pm=class extends Fe{constructor(t){super(t),this.id="animation",this.ComponentType=uu,this.DataType=x0,this.schema=ZI,this.on("beforeremove",this.onBeforeRemove,this),this.app.systems.on("update",this.onUpdate,this)}initializeComponentData(t,e,s){s=["activate","enabled","loop","speed","assets"];for(let i of s)e.hasOwnProperty(i)&&(t[i]=e[i]);super.initializeComponentData(t,e,ZI)}cloneComponent(t,e){this.addComponent(e,{}),e.animation.assets=t.animation.assets.slice(),e.animation.speed=t.animation.speed,e.animation.loop=t.animation.loop,e.animation.activate=t.animation.activate,e.animation.enabled=t.animation.enabled;let s={},i=t.animation.animations;for(let o in i)i.hasOwnProperty(o)&&(s[o]=i[o]);e.animation.animations=s;let r={},a=t.animation.animationsIndex;for(let o in a)a.hasOwnProperty(o)&&(r[o]=a[o]);return e.animation.animationsIndex=r,e.animation}onBeforeRemove(t,e){e.onBeforeRemove()}onUpdate(t){let e=this.store;for(let s in e)if(e.hasOwnProperty(s)){let i=e[s];i.data.enabled&&i.entity.enabled&&i.entity.animation.update(t)}}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this)}};le._buildAccessors(uu.prototype,ZI);var Qo=class{constructor(t,e,s,i,r=1){this._state=t,this._parent=e,this._name=s,Array.isArray(i)?(this._point=new B(i[0],i[1]),this._pointLength=this._point.length()):(this._point=i,this._pointLength=i),this._speed=r,this._weightedSpeed=1,this._weight=1,this._animTrack=null}get parent(){return this._parent}get name(){return this._name}get path(){return this._parent?`${this._parent.path}.${this._name}`:this._name}get point(){return this._point}get pointLength(){return this._pointLength}set weight(t){this._weight=t}get weight(){return this._parent?this._parent.weight*this._weight:this._weight}get normalizedWeight(){let t=this._state.totalWeight;return t===0?0:this.weight/t}get speed(){return this._weightedSpeed*this._speed}get absoluteSpeed(){return Math.abs(this._speed)}set weightedSpeed(t){this._weightedSpeed=t}get weightedSpeed(){return this._weightedSpeed}set animTrack(t){this._animTrack=t}get animTrack(){return this._animTrack}};var Jo=class c extends Qo{constructor(t,e,s,i,r,a,o,l,h){super(t,e,s,i),this._parameters=r,this._parameterValues=new Array(r.length),this._children=[],this._findParameter=h,this._syncAnimations=o!==!1,this._pointCache={};for(let f=0;ff.point-u.point),super(t,e,s,i,r,a,o,l,h)}calculateWeights(){if(this.updateParameterValues())return;let t=0;this._children[0].weight=0;for(let e=0;er.path===s);if(i>=0)this._animationList[i].animTrack=e;else{let r=this._getNodeFromPath(t);r.animTrack=e,this._animationList.push(r)}this._updateHasAnimations()}_updateHasAnimations(){this._hasAnimations=this._animationList.length>0&&this._animationList.every(t=>t.animTrack&&t.animTrack!==Qs.EMPTY)}get name(){return this._name}set animations(t){this._animationList=t,this._updateHasAnimations()}get animations(){return this._animationList}get hasAnimations(){return this._hasAnimations}set speed(t){this._speed=t}get speed(){return this._speed}set loop(t){this._loop=t}get loop(){return this._loop}get nodeCount(){return!this._blendTree||this._blendTree.constructor===Qo?1:this._blendTree.getNodeCount()}get playable(){return sh.indexOf(this.name)!==-1||this.animations.length===this.nodeCount}get looping(){if(this.animations.length>0){let t=`${this.name}.${this.animations[0].animTrack.name}`,e=this._controller.animEvaluator.findClip(t);if(e)return e.loop}return!1}get totalWeight(){let t=0;for(let e=0;et&&(t=s.animTrack.duration)}return t}};var oh=class{constructor({from:t,to:e,time:s=0,priority:i=0,conditions:r=[],exitTime:a=null,transitionOffset:o=null,interruptionSource:l=Am}){this._from=t,this._to=e,this._time=s,this._priority=i,this._conditions=r,this._exitTime=a,this._transitionOffset=o,this._interruptionSource=l}get from(){return this._from}set to(t){this._to=t}get to(){return this._to}get time(){return this._time}get priority(){return this._priority}get conditions(){return this._conditions}get exitTime(){return this._exitTime}get transitionOffset(){return this._transitionOffset}get interruptionSource(){return this._interruptionSource}get hasExitTime(){return!!this.exitTime}};var wm=class{constructor(t,e,s,i,r,a,o){n(this,"_states",{});n(this,"_stateNames",[]);n(this,"_findTransitionsFromStateCache",{});n(this,"_findTransitionsBetweenStatesCache",{});n(this,"_previousStateName",null);n(this,"_activeStateName",hu);n(this,"_activeStateDuration",0);n(this,"_activeStateDurationDirty",!0);n(this,"_playing",!1);n(this,"_activate");n(this,"_transitions");n(this,"_currTransitionTime",1);n(this,"_totalTransitionTime",1);n(this,"_isTransitioning",!1);n(this,"_transitionInterruptionSource",Am);n(this,"_transitionPreviousStates",[]);n(this,"_timeInState",0);n(this,"_timeInStateBefore",0);n(this,"findParameter",t=>this._findParameter(t));this._animEvaluator=t,this._eventHandler=r,this._findParameter=a,this._consumeTrigger=o;for(let l=0;lnew oh({...l})),this._activate=i}get animEvaluator(){return this._animEvaluator}set activeState(t){this._activeStateName=t}get activeState(){return this._findState(this._activeStateName)}get activeStateName(){return this._activeStateName}get activeStateAnimations(){return this.activeState.animations}set previousState(t){this._previousStateName=t}get previousState(){return this._findState(this._previousStateName)}get previousStateName(){return this._previousStateName}get playable(){let t=!0;for(let e=0;es.from===t),Uc(e),this._findTransitionsFromStateCache[t]=e),e}_findTransitionsBetweenStates(t,e){let s=this._findTransitionsBetweenStatesCache[`${t}->${e}`];return s||(s=this._transitions.filter(i=>i.from===t&&i.to===e),Uc(s),this._findTransitionsBetweenStatesCache[`${t}->${e}`]=s),s}_transitionHasConditionsMet(t){let e=t.conditions;for(let s=0;si.value))return!1;break;case GI:if(!(r.value=i.value))return!1;break;case HI:if(!(r.value<=i.value))return!1;break;case WI:if(r.value!==i.value)return!1;break;case XI:if(r.value===i.value)return!1;break}}return!0}_findTransition(t,e){let s=[];if(t&&e)s=s.concat(this._findTransitionsBetweenStates(t,e));else if(!this._isTransitioning)s=s.concat(this._findTransitionsFromState(this._activeStateName)),s=s.concat(this._findTransitionsFromState("ANY"));else switch(this._transitionInterruptionSource){case NI:s=s.concat(this._findTransitionsFromState(this._previousStateName)),s=s.concat(this._findTransitionsFromState("ANY"));break;case BI:s=s.concat(this._findTransitionsFromState(this._activeStateName)),s=s.concat(this._findTransitionsFromState("ANY"));break;case UI:s=s.concat(this._findTransitionsFromState(this._previousStateName)),s=s.concat(this._findTransitionsFromState(this._activeStateName)),s=s.concat(this._findTransitionsFromState("ANY"));break;case kI:s=s.concat(this._findTransitionsFromState(this._activeStateName)),s=s.concat(this._findTransitionsFromState(this._previousStateName)),s=s.concat(this._findTransitionsFromState("ANY"));break;case Am:default:}if(s=s.filter(i=>{if(i.to===this.activeStateName)return!1;if(i.hasExitTime){let r=this._getActiveStateProgressForTime(this._timeInStateBefore),a=this._getActiveStateProgressForTime(this._timeInState);if(i.exitTime<1&&this.activeState.loop&&(r-=Math.floor(r),a-=Math.floor(a)),a===r){if(a!==i.exitTime)return null}else if(!(i.exitTime>r&&i.exitTime<=a))return null}return this._transitionHasConditionsMet(i)}),s.length>0){let i=s[0];if(i.to==="END"){let r=this._findTransitionsFromState(hu)[0];i.to=r.to}return i}return null}updateStateFromTransition(t){let e,s,i;this.previousState=t.from?this.activeStateName:null,this.activeState=t.to,this._activeStateDurationDirty=!0;for(let h=0;h0&&t.transitionOffset<1,o=0,l=0;if(a){let h=r.timelineDuration*t.transitionOffset;o=h,l=h}this._timeInState=o,this._timeInStateBefore=l;for(let h=0;h0?i.blendWeight=0:i.blendWeight=r.animations[h].normalizedWeight,i.play(),a)i.time=r.timelineDuration*t.transitionOffset;else{let f=r.speed>=0?0:this.activeStateDuration;i.time=f}}}_transitionToState(t){if(!this._findState(t))return;let e=this._findTransition(this._activeStateName,t);e||(this._animEvaluator.removeClips(),e=new oh({from:null,to:t})),this.updateStateFromTransition(e)}assignAnimation(t,e,s,i){let r=t.split("."),a=this._findState(r[0]);a||(a=new FS(this,r[0],s),this._states[r[0]]=a,this._stateNames.push(r[0])),a.addAnimation(r,e),this._animEvaluator.updateClipTrack(a.name,e),s!==void 0&&(a.speed=s),i!==void 0&&(a.loop=i),!this._playing&&this._activate&&this.playable&&this.play(),this._activeStateDurationDirty=!0}removeNodeAnimations(t){if(sh.indexOf(t)!==-1)return!1;let e=this._findState(t);return e?(e.animations=[],!0):!1}play(t){t&&this._transitionToState(t),this._playing=!0}pause(){this._playing=!1}reset(){this._previousStateName=null,this._activeStateName=hu,this._playing=!1,this._currTransitionTime=1,this._totalTransitionTime=1,this._isTransitioning=!1,this._timeInState=0,this._timeInStateBefore=0,this._animEvaluator.removeClips()}rebind(){this._animEvaluator.rebind()}update(t){if(!this._playing)return;let e,s,i;(this.activeState.loop||this._timeInStatethis.activeStateDuration&&(this._timeInState=this.activeStateDuration,t=this.activeStateDuration-this._timeInStateBefore));let r=this._findTransition(this._activeStateName);if(r&&this.updateStateFromTransition(r),this._isTransitioning)if(this._currTransitionTime+=t,this._currTransitionTime<=this._totalTransitionTime){let a=this._totalTransitionTime!==0?this._currTransitionTime/this._totalTransitionTime:1;for(let o=0;o{f(s(u))},get:()=>h}}let o=i[r];if(typeof o=="object"&&o.hasOwnProperty("copy"))return function(l){o.copy(s(l))};if([B,x,Q,F,$].indexOf(i.constructor)!==-1&&e.length>1){let l=e.length>2?this._resolvePath(t,e.slice(0,-1)):t,h=e[e.length-2];return function(f){i[r]=s(f),l[h]=i}}return function(l){i[r]=s(l)}}_createAnimTargetForProperty(t,e,s){if(this.handlers&&e[0].startsWith("weight."))return this.handlers.weight(t,e[0].replace("weight.",""));if(this.handlers&&e[0]==="material"&&e.length===2){let l=e[1];if(l.endsWith("Map"))return this.handlers.materialTexture(t,l)}let i=this._resolvePath(t,e,!0);if(typeof i>"u")return null;let r,a,o;if(typeof i=="number")r=this._setter(t,e,c._packFloat),a="vector",o=1;else if(typeof i=="boolean")r=this._setter(t,e,c._packBoolean),a="vector",o=1;else if(typeof i=="object")switch(i.constructor){case B:r=this._setter(t,e,c._packVec2),a="vector",o=2;break;case x:r=this._setter(t,e,c._packVec3),a="vector",o=3;break;case Q:r=this._setter(t,e,c._packVec4),a="vector",o=4;break;case F:r=this._setter(t,e,c._packColor),a="vector",o=4;break;case $:r=this._setter(t,e,c._packQuat),a="quaternion",o=4;break;default:return null}return e.indexOf("material")!==-1?new ml(l=>{r(l),t.material.update()},a,o,s):new ml(r,a,o,s)}rebind(){this.targetCache={},this.animComponent.rootBone?this.graph=this.animComponent.rootBone:this.graph=this.animComponent.entity;let t={},e=function(s){t[s.name]=s;for(let i=0;ithis._parameters[e]);n(this,"consumeTrigger",e=>{this._consumedTriggers.add(e)})}set stateGraphAsset(e){if(e===null){this.removeStateGraph();return}this._stateGraphAsset&&this.system.app.assets.get(this._stateGraphAsset).off("change",this._onStateGraphAssetChangeEvent,this);let s,i;e instanceof ae?(s=e.id,i=this.system.app.assets.get(s),i||(this.system.app.assets.add(e),i=this.system.app.assets.get(s))):(s=e,i=this.system.app.assets.get(s)),!(!i||this._stateGraphAsset===s)&&(i.resource?(this._stateGraph=i.resource,this.loadStateGraph(this._stateGraph),i.on("change",this._onStateGraphAssetChangeEvent,this)):(i.once("load",r=>{this._stateGraph=r.resource,this.loadStateGraph(this._stateGraph)}),i.on("change",this._onStateGraphAssetChangeEvent,this),this.system.app.assets.load(i)),this._stateGraphAsset=s)}get stateGraphAsset(){return this._stateGraphAsset}set normalizeWeights(e){this._normalizeWeights=e,this.unbind()}get normalizeWeights(){return this._normalizeWeights}set animationAssets(e){this._animationAssets=e,this.loadAnimationAssets()}get animationAssets(){return this._animationAssets}set speed(e){this._speed=e}get speed(){return this._speed}set activate(e){this._activate=e}get activate(){return this._activate}set playing(e){this._playing=e}get playing(){return this._playing}set rootBone(e){if(typeof e=="string"){let s=this.entity.root.findByGuid(e);this._rootBone=s}else e instanceof Ne?this._rootBone=e:this._rootBone=null;this.rebind()}get rootBone(){return this._rootBone}set stateGraph(e){this._stateGraph=e}get stateGraph(){return this._stateGraph}get layers(){return this._layers}set layerIndices(e){this._layerIndices=e}get layerIndices(){return this._layerIndices}set parameters(e){this._parameters=e}get parameters(){return this._parameters}set targets(e){this._targets=e}get targets(){return this._targets}get playable(){for(let e=0;e0?this._layers[0]:null}_onStateGraphAssetChangeEvent(e){let s=this.animationAssets,i=this.layers.map(r=>r.mask);this.removeStateGraph(),this._stateGraph=new en(e._data),this.loadStateGraph(this._stateGraph),this.animationAssets=s,this.loadAnimationAssets(),this.layers.forEach((r,a)=>{r.mask=i[a]}),this.rebind()}dirtifyTargets(){let e=Object.values(this._targets);for(let s=0;sa.blendTree)&&(s=!0)}s||this.setupAnimationAssets()}setupAnimationAssets(){for(let e=0;e{this._targets[e].unbind()})}rebind(){this._targets={};for(let e=0;e{this.parameters[s].value=!1}),this._consumedTriggers.clear()}resolveDuplicatedEntityReferenceProperties(e,s){e.rootBone&&s[e.rootBone.guid]?this.rootBone=s[e.rootBone.guid]:this.rebind()}};var P0=class{constructor(){n(this,"enabled",!0)}};var JI=["enabled"],Rm=class extends Fe{constructor(t){super(t),this.id="anim",this.ComponentType=du,this.DataType=P0,this.schema=JI,this.on("beforeremove",this.onBeforeRemove,this),this.app.systems.on("animationUpdate",this.onAnimationUpdate,this)}initializeComponentData(t,e,s){super.initializeComponentData(t,e,JI);let i=["animationAssets","stateGraph","layers","masks"];Object.keys(e).forEach(r=>{i.includes(r)||(t[r]=e[r])}),e.stateGraph&&(t.stateGraph=e.stateGraph,t.loadStateGraph(t.stateGraph)),e.layers&&e.layers.forEach((r,a)=>{r._controller.states.forEach(o=>{r._controller._states[o]._animationList.forEach(l=>{if(!l.animTrack||l.animTrack===Qs.EMPTY){let h=this.app.assets.get(r._component._animationAssets[`${r.name}:${l.name}`].asset);h&&!h.loaded&&h.once("load",()=>{t.layers[a].assignAnimation(l.name,h.resource)})}else t.layers[a].assignAnimation(l.name,l.animTrack)})})}),e.animationAssets&&(t.animationAssets=Object.assign(t.animationAssets,e.animationAssets)),e.masks&&Object.keys(e.masks).forEach(r=>{if(t.layers[r]){let a=e.masks[r].mask,o={};Object.keys(a).forEach(l=>{o[decodeURI(l)]=a[l]}),t.layers[r].mask=o}})}onAnimationUpdate(t){let e=this.store;for(let s in e)if(e.hasOwnProperty(s)){let i=e[s].entity.anim;i.data.enabled&&i.entity.enabled&&i.playing&&i.update(t)}}cloneComponent(t,e){let s;(!t.anim.rootBone||t.anim.rootBone===t)&&(s={},t.anim.layers.forEach((r,a)=>{if(r.mask){let o={};Object.keys(r.mask).forEach(l=>{let h=l.split("/");h.shift();let f=[e.name,...h].join("/");o[f]=r.mask[l]}),s[a]={mask:o}}}));let i={enabled:t.anim.enabled,stateGraphAsset:t.anim.stateGraphAsset,animationAssets:t.anim.animationAssets,speed:t.anim.speed,activate:t.anim.activate,playing:t.anim.playing,rootBone:t.anim.rootBone,stateGraph:t.anim.stateGraph,layers:t.anim.layers,layerIndices:t.anim.layerIndices,parameters:t.anim.parameters,normalizeWeights:t.anim.normalizeWeights,masks:s};return this.addComponent(e,i)}onBeforeRemove(t,e){e.onBeforeRemove()}destroy(){super.destroy(),this.app.systems.off("animationUpdate",this.onAnimationUpdate,this)}};le._buildAccessors(du.prototype,JI);var pu=class extends le{setCurrentListener(){if(this.enabled&&this.entity.audiolistener&&this.entity.enabled){this.system.current=this.entity;let t=this.system.current.getPosition();this.system.manager.listener.setPosition(t)}}onEnable(){this.setCurrentListener()}onDisable(){this.system.current===this.entity&&(this.system.current=null)}};var w0=class{constructor(){n(this,"enabled",!0)}};var fB=["enabled"],bm=class extends Fe{constructor(t){super(t),this.id="audiolistener",this.ComponentType=pu,this.DataType=w0,this.schema=fB,this.manager=t.soundManager,this.current=null,this.app.systems.on("update",this.onUpdate,this)}initializeComponentData(t,e,s){s=["enabled"],super.initializeComponentData(t,e,s)}onUpdate(t){if(this.current){let e=this.current.getPosition();this.manager.listener.setPosition(e);let s=this.current.getWorldTransform();this.manager.listener.setOrientation(s)}}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this)}};le._buildAccessors(pu.prototype,fB);var eR=0,uB=1;var mu="group",Dm="image",kS="text",_u="stretch",tR="contain",sR="cover";var us={DEFAULT:"DEFAULT",HOVER:"HOVER",PRESSED:"PRESSED",INACTIVE:"INACTIVE"},zS={};zS[us.DEFAULT]="_defaultTint";zS[us.HOVER]="hoverTint";zS[us.PRESSED]="pressedTint";zS[us.INACTIVE]="inactiveTint";var GS={};GS[us.DEFAULT]="_defaultSpriteAsset";GS[us.HOVER]="hoverSpriteAsset";GS[us.PRESSED]="pressedSpriteAsset";GS[us.INACTIVE]="inactiveSpriteAsset";var VS={};VS[us.DEFAULT]="_defaultSpriteFrame";VS[us.HOVER]="hoverSpriteFrame";VS[us.PRESSED]="pressedSpriteFrame";VS[us.INACTIVE]="inactiveSpriteFrame";var es=class extends le{constructor(e,s){super(e,s);n(this,"_visualState",us.DEFAULT);n(this,"_isHovering",!1);n(this,"_hoveringCounter",0);n(this,"_isPressed",!1);n(this,"_defaultTint",new F(1,1,1,1));n(this,"_defaultSpriteAsset",null);n(this,"_defaultSpriteFrame",0);n(this,"_imageEntity",null);n(this,"_evtElementAdd",null);n(this,"_evtImageEntityElementAdd",null);n(this,"_evtImageEntityElementRemove",null);n(this,"_evtImageEntityElementColor",null);n(this,"_evtImageEntityElementOpacity",null);n(this,"_evtImageEntityElementSpriteAsset",null);n(this,"_evtImageEntityElementSpriteFrame",null);this._toggleLifecycleListeners("on",e)}set enabled(e){this._setValue("enabled",e)}get enabled(){return this.data.enabled}set active(e){this._setValue("active",e)}get active(){return this.data.active}set imageEntity(e){if(this._imageEntity!==e){let s=typeof e=="string";if(this._imageEntity&&s&&this._imageEntity.guid===e)return;this._imageEntity&&this._imageEntityUnsubscribe(),e instanceof Pe?this._imageEntity=e:s?this._imageEntity=this.system.app.getEntityFromIndex(e)||null:this._imageEntity=null,this._imageEntity&&this._imageEntitySubscribe(),this._imageEntity?this.data.imageEntity=this._imageEntity.guid:s&&e&&(this.data.imageEntity=e)}}get imageEntity(){return this._imageEntity}set hitPadding(e){this._setValue("hitPadding",e)}get hitPadding(){return this.data.hitPadding}set transitionMode(e){this._setValue("transitionMode",e)}get transitionMode(){return this.data.transitionMode}set hoverTint(e){this._setValue("hoverTint",e)}get hoverTint(){return this.data.hoverTint}set pressedTint(e){this._setValue("pressedTint",e)}get pressedTint(){return this.data.pressedTint}set inactiveTint(e){this._setValue("inactiveTint",e)}get inactiveTint(){return this.data.inactiveTint}set fadeDuration(e){this._setValue("fadeDuration",e)}get fadeDuration(){return this.data.fadeDuration}set hoverSpriteAsset(e){this._setValue("hoverSpriteAsset",e)}get hoverSpriteAsset(){return this.data.hoverSpriteAsset}set hoverSpriteFrame(e){this._setValue("hoverSpriteFrame",e)}get hoverSpriteFrame(){return this.data.hoverSpriteFrame}set pressedSpriteAsset(e){this._setValue("pressedSpriteAsset",e)}get pressedSpriteAsset(){return this.data.pressedSpriteAsset}set pressedSpriteFrame(e){this._setValue("pressedSpriteFrame",e)}get pressedSpriteFrame(){return this.data.pressedSpriteFrame}set inactiveSpriteAsset(e){this._setValue("inactiveSpriteAsset",e)}get inactiveSpriteAsset(){return this.data.inactiveSpriteAsset}set inactiveSpriteFrame(e){this._setValue("inactiveSpriteFrame",e)}get inactiveSpriteFrame(){return this.data.inactiveSpriteFrame}_setValue(e,s){let i=this.data,r=i[e];i[e]=s,this.fire("set",e,r,s)}_toggleLifecycleListeners(e,s){this[e]("set_active",this._onSetActive,this),this[e]("set_transitionMode",this._onSetTransitionMode,this),this[e]("set_hoverTint",this._onSetTransitionValue,this),this[e]("set_pressedTint",this._onSetTransitionValue,this),this[e]("set_inactiveTint",this._onSetTransitionValue,this),this[e]("set_hoverSpriteAsset",this._onSetTransitionValue,this),this[e]("set_hoverSpriteFrame",this._onSetTransitionValue,this),this[e]("set_pressedSpriteAsset",this._onSetTransitionValue,this),this[e]("set_pressedSpriteFrame",this._onSetTransitionValue,this),this[e]("set_inactiveSpriteAsset",this._onSetTransitionValue,this),this[e]("set_inactiveSpriteFrame",this._onSetTransitionValue,this),e==="on"?this._evtElementAdd=this.entity.on("element:add",this._onElementComponentAdd,this):(this._evtElementAdd?.off(),this._evtElementAdd=null)}_onSetActive(e,s,i){s!==i&&this._updateVisualState()}_onSetTransitionMode(e,s,i){s!==i&&(this._cancelTween(),this._resetToDefaultVisualState(s),this._forceReapplyVisualState())}_onSetTransitionValue(e,s,i){s!==i&&this._forceReapplyVisualState()}_imageEntitySubscribe(){this._evtImageEntityElementAdd=this._imageEntity.on("element:add",this._onImageElementGain,this),this._imageEntity.element&&this._onImageElementGain()}_imageEntityUnsubscribe(){this._evtImageEntityElementAdd?.off(),this._evtImageEntityElementAdd=null,this._imageEntity?.element&&this._onImageElementLose()}_imageEntityElementSubscribe(){let e=this._imageEntity.element;this._evtImageEntityElementRemove=e.once("beforeremove",this._onImageElementLose,this),this._evtImageEntityElementColor=e.on("set:color",this._onSetColor,this),this._evtImageEntityElementOpacity=e.on("set:opacity",this._onSetOpacity,this),this._evtImageEntityElementSpriteAsset=e.on("set:spriteAsset",this._onSetSpriteAsset,this),this._evtImageEntityElementSpriteFrame=e.on("set:spriteFrame",this._onSetSpriteFrame,this)}_imageEntityElementUnsubscribe(){this._evtImageEntityElementRemove?.off(),this._evtImageEntityElementRemove=null,this._evtImageEntityElementColor?.off(),this._evtImageEntityElementColor=null,this._evtImageEntityElementOpacity?.off(),this._evtImageEntityElementOpacity=null,this._evtImageEntityElementSpriteAsset?.off(),this._evtImageEntityElementSpriteAsset=null,this._evtImageEntityElementSpriteFrame?.off(),this._evtImageEntityElementSpriteFrame=null}_onElementComponentRemove(){this._toggleHitElementListeners("off")}_onElementComponentAdd(){this._toggleHitElementListeners("on")}_onImageElementLose(){this._imageEntityElementUnsubscribe(),this._cancelTween(),this._resetToDefaultVisualState(this.transitionMode)}_onImageElementGain(){this._imageEntityElementSubscribe(),this._storeDefaultVisualState(),this._forceReapplyVisualState()}_toggleHitElementListeners(e){if(this.entity.element){let s=e==="on";if(s&&this._hasHitElementListeners)return;this.entity.element[e]("beforeremove",this._onElementComponentRemove,this),this.entity.element[e]("mouseenter",this._onMouseEnter,this),this.entity.element[e]("mouseleave",this._onMouseLeave,this),this.entity.element[e]("mousedown",this._onMouseDown,this),this.entity.element[e]("mouseup",this._onMouseUp,this),this.entity.element[e]("touchstart",this._onTouchStart,this),this.entity.element[e]("touchend",this._onTouchEnd,this),this.entity.element[e]("touchleave",this._onTouchLeave,this),this.entity.element[e]("touchcancel",this._onTouchCancel,this),this.entity.element[e]("selectstart",this._onSelectStart,this),this.entity.element[e]("selectend",this._onSelectEnd,this),this.entity.element[e]("selectenter",this._onSelectEnter,this),this.entity.element[e]("selectleave",this._onSelectLeave,this),this.entity.element[e]("click",this._onClick,this),this._hasHitElementListeners=s}}_storeDefaultVisualState(){let e=this._imageEntity?.element;!e||e.type===mu||(this._storeDefaultColor(e.color),this._storeDefaultOpacity(e.opacity),this._storeDefaultSpriteAsset(e.spriteAsset),this._storeDefaultSpriteFrame(e.spriteFrame))}_storeDefaultColor(e){this._defaultTint.r=e.r,this._defaultTint.g=e.g,this._defaultTint.b=e.b}_storeDefaultOpacity(e){this._defaultTint.a=e}_storeDefaultSpriteAsset(e){this._defaultSpriteAsset=e}_storeDefaultSpriteFrame(e){this._defaultSpriteFrame=e}_onSetColor(e){this._isApplyingTint||(this._storeDefaultColor(e),this._forceReapplyVisualState())}_onSetOpacity(e){this._isApplyingTint||(this._storeDefaultOpacity(e),this._forceReapplyVisualState())}_onSetSpriteAsset(e){this._isApplyingSprite||(this._storeDefaultSpriteAsset(e),this._forceReapplyVisualState())}_onSetSpriteFrame(e){this._isApplyingSprite||(this._storeDefaultSpriteFrame(e),this._forceReapplyVisualState())}_onMouseEnter(e){this._isHovering=!0,this._updateVisualState(),this._fireIfActive("mouseenter",e)}_onMouseLeave(e){this._isHovering=!1,this._isPressed=!1,this._updateVisualState(),this._fireIfActive("mouseleave",e)}_onMouseDown(e){this._isPressed=!0,this._updateVisualState(),this._fireIfActive("mousedown",e)}_onMouseUp(e){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("mouseup",e)}_onTouchStart(e){this._isPressed=!0,this._updateVisualState(),this._fireIfActive("touchstart",e)}_onTouchEnd(e){e.event.preventDefault(),this._isPressed=!1,this._updateVisualState(),this._fireIfActive("touchend",e)}_onTouchLeave(e){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("touchleave",e)}_onTouchCancel(e){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("touchcancel",e)}_onSelectStart(e){this._isPressed=!0,this._updateVisualState(),this._fireIfActive("selectstart",e)}_onSelectEnd(e){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("selectend",e)}_onSelectEnter(e){this._hoveringCounter++,this._hoveringCounter===1&&(this._isHovering=!0,this._updateVisualState()),this._fireIfActive("selectenter",e)}_onSelectLeave(e){this._hoveringCounter--,this._hoveringCounter===0&&(this._isHovering=!1,this._isPressed=!1,this._updateVisualState()),this._fireIfActive("selectleave",e)}_onClick(e){this._fireIfActive("click",e)}_fireIfActive(e,s){this.data.active&&this.fire(e,s)}_updateVisualState(e){let s=this._visualState,i=this._determineVisualState();if((s!==i||e)&&this.enabled)switch(this._visualState=i,s===us.HOVER&&this._fireIfActive("hoverend"),s===us.PRESSED&&this._fireIfActive("pressedend"),i===us.HOVER&&this._fireIfActive("hoverstart"),i===us.PRESSED&&this._fireIfActive("pressedstart"),this.transitionMode){case 0:{let r=zS[this._visualState],a=this[r];this._applyTint(a);break}case 1:{let r=GS[this._visualState],a=VS[this._visualState],o=this[r],l=this[a];this._applySprite(o,l);break}}}_forceReapplyVisualState(){this._updateVisualState(!0)}_resetToDefaultVisualState(e){if(this._imageEntity?.element)switch(e){case 0:this._cancelTween(),this._applyTintImmediately(this._defaultTint);break;case 1:this._applySprite(this._defaultSpriteAsset,this._defaultSpriteFrame);break}}_determineVisualState(){if(this.active){if(this._isPressed)return us.PRESSED;if(this._isHovering)return us.HOVER}else return us.INACTIVE;return us.DEFAULT}_applySprite(e,s){let i=this._imageEntity?.element;i&&(s=s||0,this._isApplyingSprite=!0,i.spriteAsset!==e&&(i.spriteAsset=e),i.spriteFrame!==s&&(i.spriteFrame=s),this._isApplyingSprite=!1)}_applyTint(e){this._cancelTween(),this.fadeDuration===0?this._applyTintImmediately(e):this._applyTintWithTween(e)}_applyTintImmediately(e){let s=this._imageEntity?.element;if(!e||!s||s.type===mu)return;let i=dB(e);this._isApplyingTint=!0,i.equals(s.color)||(s.color=i),s.opacity!==e.a&&(s.opacity=e.a),this._isApplyingTint=!1}_applyTintWithTween(e){let s=this._imageEntity?.element;if(!e||!s||s.type===mu)return;let i=dB(e),r=s.color,a=s.opacity;i.equals(r)&&e.a===a||(this._tweenInfo={startTime:Tt(),from:new F(r.r,r.g,r.b,a),to:e.clone(),lerpColor:new F})}_updateTintTween(){let e=Tt()-this._tweenInfo.startTime,s=this.fadeDuration===0?1:e/this.fadeDuration;if(s=R.clamp(s,0,1),Math.abs(s-1)>1e-5){let i=this._tweenInfo.lerpColor;i.lerp(this._tweenInfo.from,this._tweenInfo.to,s),this._applyTintImmediately(new F(i.r,i.g,i.b,i.a))}else this._applyTintImmediately(this._tweenInfo.to),this._cancelTween()}_cancelTween(){delete this._tweenInfo}onUpdate(){this._tweenInfo&&this._updateTintTween()}onEnable(){this._isHovering=!1,this._hoveringCounter=0,this._isPressed=!1,this._toggleHitElementListeners("on"),this._forceReapplyVisualState()}onDisable(){this._toggleHitElementListeners("off"),this._resetToDefaultVisualState(this.transitionMode)}onRemove(){this._imageEntityUnsubscribe(),this._toggleLifecycleListeners("off",this.system),this.onDisable()}resolveDuplicatedEntityReferenceProperties(e,s){e.imageEntity&&(this.imageEntity=s[e.imageEntity.guid])}};n(es,"EVENT_MOUSEDOWN","mousedown"),n(es,"EVENT_MOUSEUP","mouseup"),n(es,"EVENT_MOUSEENTER","mouseenter"),n(es,"EVENT_MOUSELEAVE","mouseleave"),n(es,"EVENT_CLICK","click"),n(es,"EVENT_TOUCHSTART","touchstart"),n(es,"EVENT_TOUCHEND","touchend"),n(es,"EVENT_TOUCHCANCEL","touchcancel"),n(es,"EVENT_TOUCHLEAVE","touchleave"),n(es,"EVENT_SELECTSTART","selectstart"),n(es,"EVENT_SELECTEND","selectend"),n(es,"EVENT_SELECTENTER","selectenter"),n(es,"EVENT_SELECTLEAVE","selectleave"),n(es,"EVENT_HOVERSTART","hoverstart"),n(es,"EVENT_HOVEREND","hoverend"),n(es,"EVENT_PRESSEDSTART","pressedstart"),n(es,"EVENT_PRESSEDEND","pressedend");function dB(c){return new F(c.r,c.g,c.b)}var I0=class{constructor(){n(this,"enabled",!0);n(this,"active",!0);n(this,"imageEntity",null);n(this,"hitPadding",new Q);n(this,"transitionMode",0);n(this,"hoverTint",new F(.75,.75,.75));n(this,"pressedTint",new F(.5,.5,.5));n(this,"inactiveTint",new F(.25,.25,.25));n(this,"fadeDuration",0);n(this,"hoverSpriteAsset",null);n(this,"hoverSpriteFrame",0);n(this,"pressedSpriteAsset",null);n(this,"pressedSpriteFrame",0);n(this,"inactiveSpriteAsset",null);n(this,"inactiveSpriteFrame",0)}};var pB=["enabled","active",{name:"hitPadding",type:"vec4"},"transitionMode",{name:"hoverTint",type:"rgba"},{name:"pressedTint",type:"rgba"},{name:"inactiveTint",type:"rgba"},"fadeDuration","hoverSpriteAsset","hoverSpriteFrame","pressedSpriteAsset","pressedSpriteFrame","inactiveSpriteAsset","inactiveSpriteFrame"],Lm=class extends Fe{constructor(t){super(t),this.id="button",this.ComponentType=es,this.DataType=I0,this.schema=pB,this.on("beforeremove",this._onRemoveComponent,this),this.app.systems.on("update",this.onUpdate,this)}initializeComponentData(t,e,s){t.imageEntity=e.imageEntity,super.initializeComponentData(t,e,pB)}onUpdate(t){let e=this.store;for(let s in e){let i=e[s].entity,r=i.button;r.enabled&&i.enabled&&r.onUpdate()}}_onRemoveComponent(t,e){e.onRemove()}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this)}};var mB=new x,_B=new $,eo=class extends le{constructor(e,s){super(e,s);n(this,"_compoundParent",null);n(this,"_hasOffset",!1);this.entity.on("insert",this._onInsert,this),this.on("set_type",this.onSetType,this),this.on("set_convexHull",this.onSetModel,this),this.on("set_halfExtents",this.onSetHalfExtents,this),this.on("set_linearOffset",this.onSetOffset,this),this.on("set_angularOffset",this.onSetOffset,this),this.on("set_radius",this.onSetRadius,this),this.on("set_height",this.onSetHeight,this),this.on("set_axis",this.onSetAxis,this),this.on("set_asset",this.onSetAsset,this),this.on("set_renderAsset",this.onSetRenderAsset,this),this.on("set_model",this.onSetModel,this),this.on("set_render",this.onSetRender,this)}set enabled(e){this._setValue("enabled",e)}get enabled(){return this.data.enabled}set type(e){this._setValue("type",e)}get type(){return this.data.type}set halfExtents(e){this._setValue("halfExtents",e)}get halfExtents(){return this.data.halfExtents}set linearOffset(e){this._setValue("linearOffset",e)}get linearOffset(){return this.data.linearOffset}set angularOffset(e){this._setValue("angularOffset",e)}get angularOffset(){return this.data.angularOffset}set radius(e){this._setValue("radius",e)}get radius(){return this.data.radius}set axis(e){this._setValue("axis",e)}get axis(){return this.data.axis}set height(e){this._setValue("height",e)}get height(){return this.data.height}set asset(e){this._setValue("asset",e)}get asset(){return this.data.asset}set renderAsset(e){this._setValue("renderAsset",e)}get renderAsset(){return this.data.renderAsset}set convexHull(e){this._setValue("convexHull",e)}get convexHull(){return this.data.convexHull}set shape(e){this._setValue("shape",e)}get shape(){return this.data.shape}set model(e){this._setValue("model",e)}get model(){return this.data.model}set render(e){this._setValue("render",e)}get render(){return this.data.render}set checkVertexDuplicates(e){this._setValue("checkVertexDuplicates",e)}get checkVertexDuplicates(){return this.data.checkVertexDuplicates}_setValue(e,s){let i=this.data,r=i[e];i[e]=s,this.fire("set",e,r,s)}onSetType(e,s,i){s!==i&&this.system.changeType(this,s,i)}onSetHalfExtents(e,s,i){let r=this.data.type;this.data.initialized&&r==="box"&&this.system.recreatePhysicalShapes(this)}onSetOffset(e,s,i){this._hasOffset=!this.data.linearOffset.equals(x.ZERO)||!this.data.angularOffset.equals($.IDENTITY),this.data.initialized&&this.system.recreatePhysicalShapes(this)}onSetRadius(e,s,i){let r=this.data.type;this.data.initialized&&(r==="sphere"||r==="capsule"||r==="cylinder"||r==="cone")&&this.system.recreatePhysicalShapes(this)}onSetHeight(e,s,i){let r=this.data.type;this.data.initialized&&(r==="capsule"||r==="cylinder"||r==="cone")&&this.system.recreatePhysicalShapes(this)}onSetAxis(e,s,i){let r=this.data.type;this.data.initialized&&(r==="capsule"||r==="cylinder"||r==="cone")&&this.system.recreatePhysicalShapes(this)}onSetAsset(e,s,i){let r=this.system.app.assets;if(s){let a=r.get(s);a&&a.off("remove",this.onAssetRemoved,this)}if(i){i instanceof ae&&(this.data.asset=i.id);let a=r.get(this.data.asset);a&&(a.off("remove",this.onAssetRemoved,this),a.on("remove",this.onAssetRemoved,this))}this.data.initialized&&this.data.type==="mesh"&&(i||(this.data.model=null),this.system.recreatePhysicalShapes(this))}onSetRenderAsset(e,s,i){let r=this.system.app.assets;if(s){let a=r.get(s);a&&a.off("remove",this.onRenderAssetRemoved,this)}if(i){i instanceof ae&&(this.data.renderAsset=i.id);let a=r.get(this.data.renderAsset);a&&(a.off("remove",this.onRenderAssetRemoved,this),a.on("remove",this.onRenderAssetRemoved,this))}this.data.initialized&&this.data.type==="mesh"&&(i||(this.data.render=null),this.system.recreatePhysicalShapes(this))}onSetModel(e,s,i){this.data.initialized&&this.data.type==="mesh"&&this.system.implementations.mesh.doRecreatePhysicalShape(this)}onSetRender(e,s,i){this.onSetModel(e,s,i)}onAssetRemoved(e){e.off("remove",this.onAssetRemoved,this),this.data.asset===e.id&&(this.asset=null)}onRenderAssetRemoved(e){e.off("remove",this.onRenderAssetRemoved,this),this.data.renderAsset===e.id&&(this.renderAsset=null)}getCompoundChildShapeIndex(e){let s=this.data.shape,i=s.getNumChildShapes();for(let r=0;r"u")){if(this._compoundParent)this.system.recreatePhysicalShapes(this);else if(!this.entity.rigidbody){let s=this.entity.parent;for(;s;){if(s.collision&&s.collision.type==="compound"){s.collision.shape.getNumChildShapes()===0?this.system.recreatePhysicalShapes(s.collision):this.system.recreatePhysicalShapes(this);break}s=s.parent}}}}_updateCompound(){let e=this.entity;if(e._dirtyWorld){let s=e._dirtyLocal,i=e;for(;i&&!s&&!(i.collision&&i.collision===this._compoundParent);)i._dirtyLocal&&(s=!0),i=i.parent;if(s){e.forEach(this.system.implementations.compound._updateEachDescendantTransform,e);let r=this._compoundParent.entity.rigidbody;r&&r.activate()}}}getShapePosition(){let e=this.entity.getPosition();if(this._hasOffset){let s=this.entity.getRotation(),i=this.data.linearOffset;return _B.copy(s).transformVector(i,mB),mB.add(e)}return e}getShapeRotation(){let e=this.entity.getRotation();return this._hasOffset?_B.copy(e).mul(this.data.angularOffset):e}onEnable(){if(this.data.type==="mesh"&&(this.data.asset||this.data.renderAsset)&&this.data.initialized){let e=this.system.app.assets.get(this.data.asset||this.data.renderAsset);if(e&&(!e.resource||!this.data.shape)){this.system.recreatePhysicalShapes(this);return}}if(this.entity.rigidbody)this.entity.rigidbody.enabled&&this.entity.rigidbody.enableSimulation();else if(this._compoundParent&&this!==this._compoundParent)if(this._compoundParent.shape.getNumChildShapes()===0)this.system.recreatePhysicalShapes(this._compoundParent);else{let e=this.system._getNodeTransform(this.entity,this._compoundParent.entity);this._compoundParent.shape.addChildShape(e,this.data.shape),Ammo.destroy(e),this._compoundParent.entity.rigidbody&&this._compoundParent.entity.rigidbody.activate()}else this.entity.trigger&&this.entity.trigger.enable()}onDisable(){this.entity.rigidbody?this.entity.rigidbody.disableSimulation():this._compoundParent&&this!==this._compoundParent?this._compoundParent.entity._destroying||(this.system._removeCompoundChild(this._compoundParent,this.data.shape),this._compoundParent.entity.rigidbody&&this._compoundParent.entity.rigidbody.activate()):this.entity.trigger&&this.entity.trigger.disable()}onBeforeRemove(){this.asset&&(this.asset=null),this.renderAsset&&(this.renderAsset=null),this.entity.off("insert",this._onInsert,this),this.off()}};n(eo,"EVENT_CONTACT","contact"),n(eo,"EVENT_COLLISIONSTART","collisionstart"),n(eo,"EVENT_COLLISIONEND","collisionend"),n(eo,"EVENT_TRIGGERENTER","triggerenter"),n(eo,"EVENT_TRIGGERLEAVE","triggerleave");var R0=class{constructor(){n(this,"enabled",!0);n(this,"type","box");n(this,"halfExtents",new x(.5,.5,.5));n(this,"linearOffset",new x);n(this,"angularOffset",new $);n(this,"radius",.5);n(this,"axis",1);n(this,"height",2);n(this,"convexHull",!1);n(this,"asset",null);n(this,"renderAsset",null);n(this,"checkVertexDuplicates",!0);n(this,"shape",null);n(this,"model",null);n(this,"render",null);n(this,"initialized",!1)}};var Sl="static",Ui="dynamic",tn="kinematic",gB=1,b0=2,gu=4,Mm=1,SB=2,xB=3,HS=4,WS=5,fke=0,uke=1,vB=1,iR=2,TB=4,dke=8,yB=16,pke=32,mke=64,_ke=128,gke=256,Ske=512,xke=1024,vke=2048,Tke=4096,yke=8192,Eke=16384,Ake=0,rR=65535,Cke=2,D0=65533,Pke=65529;var to,Su,Om,XS=class{constructor(t,e,s){this.entity=e.entity,this.component=e,this.app=t,typeof Ammo<"u"&&!to&&(to=new Ammo.btVector3,Su=new Ammo.btQuaternion,Om=new Ammo.btTransform),this.initialize(s)}initialize(t){let e=this.entity,s=t.shape;if(s&&typeof Ammo<"u"){e.trigger&&e.trigger.destroy();let i=1,r=this.component;if(r){let o=r.getShapePosition(),l=r.getShapeRotation();to.setValue(o.x,o.y,o.z),Su.setValue(l.x,l.y,l.z,l.w)}else{let o=e.getPosition(),l=e.getRotation();to.setValue(o.x,o.y,o.z),Su.setValue(l.x,l.y,l.z,l.w)}Om.setOrigin(to),Om.setRotation(Su);let a=this.app.systems.rigidbody.createBody(i,s,Om);a.setRestitution(0),a.setFriction(0),a.setDamping(0,0),to.setValue(0,0,0),a.setLinearFactor(to),a.setAngularFactor(to),a.setCollisionFlags(a.getCollisionFlags()|4),a.entity=e,this.body=a,this.component.enabled&&e.enabled&&this.enable()}}destroy(){this.body&&(this.disable(),this.app.systems.rigidbody.destroyBody(this.body),this.body=null)}_getEntityTransform(t){let e=this.component;if(e){let s=e.getShapePosition(),i=e.getShapeRotation();to.setValue(s.x,s.y,s.z),Su.setValue(i.x,i.y,i.z,i.w)}else{let s=this.entity.getPosition(),i=this.entity.getRotation();to.setValue(s.x,s.y,s.z),Su.setValue(i.x,i.y,i.z,i.w)}t.setOrigin(to),t.setRotation(Su)}updateTransform(){this._getEntityTransform(Om);let t=this.body;t.setWorldTransform(Om),t.activate()}enable(){let t=this.body;if(!t)return;let e=this.app.systems.rigidbody;e._triggers.indexOf(this)<0&&(e.addBody(t,16,65517),e._triggers.push(this)),t.forceActivationState(1),this.updateTransform()}disable(){let t=this.body;if(!t)return;let e=this.app.systems.rigidbody,s=e._triggers.indexOf(this);s>-1&&(e.removeBody(t),e._triggers.splice(s,1)),t.forceActivationState(5)}};var L0=new W,L8=new x,M8=new x,xu=new $,EB=new Pe,O8=["enabled","type","halfExtents","linearOffset","angularOffset","radius","axis","height","convexHull","asset","renderAsset","shape","model","render","checkVertexDuplicates"],xl=class{constructor(t){this.system=t}beforeInitialize(t,e){e.shape=null,e.model=new Ei,e.model.graph=new Pe}afterInitialize(t,e){this.recreatePhysicalShapes(t),t.data.initialized=!0}reset(t,e){this.beforeInitialize(t,e),this.afterInitialize(t,e)}recreatePhysicalShapes(t){let e=t.entity,s=t.data;if(typeof Ammo<"u"){e.trigger&&(e.trigger.destroy(),delete e.trigger),s.shape&&(t._compoundParent&&(t!==t._compoundParent&&this.system._removeCompoundChild(t._compoundParent,s.shape),t._compoundParent.entity.rigidbody&&t._compoundParent.entity.rigidbody.activate()),this.destroyShape(s)),s.shape=this.createPhysicalShape(t.entity,s);let i=!t._compoundParent;if(s.type==="compound"&&(!t._compoundParent||t===t._compoundParent))t._compoundParent=t,e.forEach(this._addEachDescendant,t);else if(s.type!=="compound"&&!t.rigidbody){t._compoundParent=null;let r=e.parent;for(;r;){if(r.collision&&r.collision.type==="compound"){t._compoundParent=r.collision;break}r=r.parent}}t._compoundParent&&t!==t._compoundParent&&(i&&t._compoundParent.shape.getNumChildShapes()===0?this.system.recreatePhysicalShapes(t._compoundParent):(this.system.updateCompoundChildTransform(e,!0),t._compoundParent.entity.rigidbody&&t._compoundParent.entity.rigidbody.activate())),e.rigidbody?(e.rigidbody.disableSimulation(),e.rigidbody.createBody(),e.enabled&&e.rigidbody.enabled&&e.rigidbody.enableSimulation()):t._compoundParent||(e.trigger?e.trigger.initialize(s):e.trigger=new XS(this.system.app,t,s))}}createPhysicalShape(t,e){}updateTransform(t,e,s,i){t.entity.trigger&&t.entity.trigger.updateTransform()}destroyShape(t){t.shape&&(Ammo.destroy(t.shape),t.shape=null)}beforeRemove(t,e){e.data.shape&&(e._compoundParent&&!e._compoundParent.entity._destroying&&(this.system._removeCompoundChild(e._compoundParent,e.data.shape),e._compoundParent.entity.rigidbody&&e._compoundParent.entity.rigidbody.activate()),e._compoundParent=null,this.destroyShape(e.data))}remove(t,e){t.rigidbody&&t.rigidbody.body&&t.rigidbody.disableSimulation(),t.trigger&&(t.trigger.destroy(),delete t.trigger)}clone(t,e){let s=this.system.store[t.guid],i={enabled:s.data.enabled,type:s.data.type,halfExtents:[s.data.halfExtents.x,s.data.halfExtents.y,s.data.halfExtents.z],linearOffset:[s.data.linearOffset.x,s.data.linearOffset.y,s.data.linearOffset.z],angularOffset:[s.data.angularOffset.x,s.data.angularOffset.y,s.data.angularOffset.z,s.data.angularOffset.w],radius:s.data.radius,axis:s.data.axis,height:s.data.height,convexHull:s.data.convexHull,asset:s.data.asset,renderAsset:s.data.renderAsset,model:s.data.model,render:s.data.render,checkVertexDuplicates:s.data.checkVertexDuplicates};return this.system.addComponent(e,i)}},aR=class extends xl{createPhysicalShape(t,e){if(typeof Ammo<"u"){let s=e.halfExtents,i=new Ammo.btVector3(s?s.x:.5,s?s.y:.5,s?s.z:.5),r=new Ammo.btBoxShape(i);return Ammo.destroy(i),r}}},oR=class extends xl{createPhysicalShape(t,e){if(typeof Ammo<"u")return new Ammo.btSphereShape(e.radius)}},nR=class extends xl{createPhysicalShape(t,e){let s=e.axis??1,i=e.radius??.5,r=Math.max((e.height??2)-2*i,0),a=null;if(typeof Ammo<"u")switch(s){case 0:a=new Ammo.btCapsuleShapeX(i,r);break;case 1:a=new Ammo.btCapsuleShape(i,r);break;case 2:a=new Ammo.btCapsuleShapeZ(i,r);break}return a}},lR=class extends xl{createPhysicalShape(t,e){let s=e.axis??1,i=e.radius??.5,r=e.height??1,a=null,o=null;if(typeof Ammo<"u")switch(s){case 0:a=new Ammo.btVector3(r*.5,i,i),o=new Ammo.btCylinderShapeX(a);break;case 1:a=new Ammo.btVector3(i,r*.5,i),o=new Ammo.btCylinderShape(a);break;case 2:a=new Ammo.btVector3(i,i,r*.5),o=new Ammo.btCylinderShapeZ(a);break}return a&&Ammo.destroy(a),o}},cR=class extends xl{createPhysicalShape(t,e){let s=e.axis??1,i=e.radius??.5,r=e.height??1,a=null;if(typeof Ammo<"u")switch(s){case 0:a=new Ammo.btConeShapeX(i,r);break;case 1:a=new Ammo.btConeShape(i,r);break;case 2:a=new Ammo.btConeShapeZ(i,r);break}return a}},hR=class extends xl{beforeInitialize(t,e){}createAmmoHull(t,e,s,i){let r=new Ammo.btConvexHullShape,a=new Ammo.btVector3,o=[];t.getPositions(o);for(let h=0;h{let O=p[D*d]*P,G=p[D*d+1]*A,M=p[D*d+2]*w,H;if(r){let U=`${O}:${G}:${M}`;if(H=E.get(U),H!==void 0)return H;S.setValue(O,G,M),H=o.findOrAddVertex(S,!1),E.set(U,H)}else S.setValue(O,G,M),H=o.findOrAddVertex(S,!1);return H};for(let D=0;D<_;D++)g=I(m[v+D*3]),T=I(m[v+D*3+1]),C=I(m[v+D*3+2]),o.addIndex(g),o.addIndex(T),o.addIndex(C);Ammo.destroy(S)}let l=new Ammo.btBvhTriangleMeshShape(o,!0);if(!i){let f=a._getNodeScaling(e);l.setLocalScaling(f),Ammo.destroy(f)}let h=a._getNodeTransform(e);s.addChildShape(h,l),Ammo.destroy(h)}createPhysicalShape(t,e){if(!(typeof Ammo>"u")&&(e.model||e.render)){let s=new Ammo.btCompoundShape,r=t.getWorldTransform().getScale();if(e.render){let a=e.render.meshes;for(let o=0;o{i[s]===a&&(i[s]=f.resource,this.doRecreatePhysicalShape(t))},l=f=>{f.ready(u=>{if(u.data.containerAsset){let d=r.get(u.data.containerAsset);d.loaded?o(u):(d.ready(()=>{o(u)}),r.load(d))}else o(u)}),r.load(f)},h=r.get(e);h?l(h):r.once(`add:${e}`,l)}doRecreatePhysicalShape(t){let e=t.entity,s=t.data;s.model||s.render?(this.destroyShape(s),s.shape=this.createPhysicalShape(e,s),e.rigidbody?(e.rigidbody.disableSimulation(),e.rigidbody.createBody(),e.enabled&&e.rigidbody.enabled&&e.rigidbody.enableSimulation()):e.trigger?e.trigger.initialize(s):e.trigger=new XS(this.system.app,t,s)):(this.beforeRemove(e,t),this.remove(e,s))}updateTransform(t,e,s,i){if(t.shape){let a=t.entity.getWorldTransform().getScale(),o=t.shape.getLocalScaling();(a.x!==o.x()||a.y!==o.y()||a.z!==o.z())&&this.doRecreatePhysicalShape(t)}super.updateTransform(t,e,s,i)}destroyShape(t){if(!t.shape)return;let e=t.shape.getNumChildShapes();for(let s=0;s=0&&this.model.meshInstances.splice(e,1)}this._entity.enabled&&this._element.enabled&&this._element.addModelToLayers(this.model),t||(this.unmaskMeshInstance?.destroy(),this.unmaskMeshInstance=null)}}setMaterial(t){this.meshInstance&&(this.meshInstance.material=t,this.unmaskMeshInstance&&(this.unmaskMeshInstance.material=t))}setParameter(t,e){this.meshInstance&&(this.meshInstance.setParameter(t,e),this.unmaskMeshInstance&&this.unmaskMeshInstance.setParameter(t,e))}deleteParameter(t){this.meshInstance&&(this.meshInstance.deleteParameter(t),this.unmaskMeshInstance&&this.unmaskMeshInstance.deleteParameter(t))}setUnmaskDrawOrder(){if(!this.meshInstance)return;let t=function(e){let s,i=e.children,r=i.length;if(r){for(let o=0;onew Ft(r,[{semantic:ee,components:3,type:ye},{semantic:Ot,components:3,type:ye},{semantic:_t,components:2,type:ye}])),l=new ft(r,o,4,{data:a.buffer}),h=new _e(r);return h.vertexBuffer=l,h.primitive[0].type=Ks,h.primitive[0].base=0,h.primitive[0].count=4,h.primitive[0].indexed=!1,h.aabb.setMinMax(x.ZERO,new x(e,s,0)),this._updateMesh(h),h}_updateMesh(t){let e=this._element,s=e.calculatedWidth,i=e.calculatedHeight;if(e.fitMode!==_u&&this._targetAspectRatio>0){let a=e.calculatedWidth/e.calculatedHeight;e.fitMode===tR&&a>this._targetAspectRatio||e.fitMode===sR&&a0&&(this._targetAspectRatio=s.rect.z/s.rect.w)}this.mesh=t?e:this._defaultMesh,this.refreshMesh()}refreshMesh(){this.mesh&&(this._element._beingInitialized?this._meshDirty=!0:this._updateMesh(this.mesh))}_updateAabb(t){return t.center.set(0,0,0),t.halfExtents.set(this._outerScale.x*.5,this._outerScale.y*.5,.001),t.setFromTransformedAabb(t,this._renderable.node.getWorldTransform()),t}_toggleMask(){this._element._dirtifyMask();let t=this._element._isScreenSpace();this._updateMaterial(t),this._renderable.setMask(!!this._mask)}_onMaterialLoad(t){this.material=t.resource}_onMaterialAdded(t){this._system.app.assets.off(`add:${t.id}`,this._onMaterialAdded,this),this._materialAsset===t.id&&this._bindMaterialAsset(t)}_bindMaterialAsset(t){this._entity.enabled&&(t.on("load",this._onMaterialLoad,this),t.on("change",this._onMaterialChange,this),t.on("remove",this._onMaterialRemove,this),t.resource?this._onMaterialLoad(t):this._system.app.assets.load(t))}_unbindMaterialAsset(t){t.off("load",this._onMaterialLoad,this),t.off("change",this._onMaterialChange,this),t.off("remove",this._onMaterialRemove,this)}_onMaterialChange(){}_onMaterialRemove(){}_onTextureAdded(t){this._system.app.assets.off(`add:${t.id}`,this._onTextureAdded,this),this._textureAsset===t.id&&this._bindTextureAsset(t)}_bindTextureAsset(t){this._entity.enabled&&(t.on("load",this._onTextureLoad,this),t.on("change",this._onTextureChange,this),t.on("remove",this._onTextureRemove,this),t.resource?this._onTextureLoad(t):this._system.app.assets.load(t))}_unbindTextureAsset(t){t.off("load",this._onTextureLoad,this),t.off("change",this._onTextureChange,this),t.off("remove",this._onTextureRemove,this)}_onTextureLoad(t){this.texture=t.resource}_onTextureChange(t){}_onTextureRemove(t){}_onSpriteAssetAdded(t){this._system.app.assets.off(`add:${t.id}`,this._onSpriteAssetAdded,this),this._spriteAsset===t.id&&this._bindSpriteAsset(t)}_bindSpriteAsset(t){this._entity.enabled&&(t.on("load",this._onSpriteAssetLoad,this),t.on("change",this._onSpriteAssetChange,this),t.on("remove",this._onSpriteAssetRemove,this),t.resource?this._onSpriteAssetLoad(t):this._system.app.assets.load(t))}_unbindSpriteAsset(t){t.off("load",this._onSpriteAssetLoad,this),t.off("change",this._onSpriteAssetChange,this),t.off("remove",this._onSpriteAssetRemove,this),t.data.textureAtlasAsset&&this._system.app.assets.off(`load:${t.data.textureAtlasAsset}`,this._onTextureAtlasLoad,this)}_onSpriteAssetLoad(t){if(!t||!t.resource)this.sprite=null;else if(t.resource.atlas)this.sprite=t.resource;else{let e=t.data.textureAtlasAsset;if(e){let s=this._system.app.assets;s.off(`load:${e}`,this._onTextureAtlasLoad,this),s.once(`load:${e}`,this._onTextureAtlasLoad,this)}}}_onSpriteAssetChange(t){this._onSpriteAssetLoad(t)}_onSpriteAssetRemove(t){}_bindSprite(t){this._evtSetMeshes=t.on("set:meshes",this._onSpriteMeshesChange,this),t.on("set:pixelsPerUnit",this._onSpritePpuChange,this),t.on("set:atlas",this._onAtlasTextureChange,this),t.atlas&&t.atlas.on("set:texture",this._onAtlasTextureChange,this)}_unbindSprite(t){this._evtSetMeshes?.off(),this._evtSetMeshes=null,t.off("set:pixelsPerUnit",this._onSpritePpuChange,this),t.off("set:atlas",this._onAtlasTextureChange,this),t.atlas&&t.atlas.off("set:texture",this._onAtlasTextureChange,this)}_onSpriteMeshesChange(){this._sprite&&(this._spriteFrame=R.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1)),this._updateSprite()}_onSpritePpuChange(){this.sprite.renderMode!==Ti&&this._pixelsPerUnit===null&&this._updateSprite()}_onAtlasTextureChange(){this.sprite&&this.sprite.atlas&&this.sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"))}_onTextureAtlasLoad(t){let e=this._spriteAsset;e instanceof ae?this._onSpriteAssetLoad(e):this._onSpriteAssetLoad(this._system.app.assets.get(e))}onEnable(){if(this._materialAsset){let t=this._system.app.assets.get(this._materialAsset);t&&t.resource!==this._material&&this._bindMaterialAsset(t)}if(this._textureAsset){let t=this._system.app.assets.get(this._textureAsset);t&&t.resource!==this._texture&&this._bindTextureAsset(t)}if(this._spriteAsset){let t=this._system.app.assets.get(this._spriteAsset);t&&t.resource!==this._sprite&&this._bindSpriteAsset(t)}this._element.addModelToLayers(this._renderable.model)}onDisable(){this._element.removeModelFromLayers(this._renderable.model)}_setStencil(t){this._renderable.meshInstance.stencilFront=t,this._renderable.meshInstance.stencilBack=t;let e=0;if(this._element.maskedBy&&(e=this._element.maskedBy.element._image._maskRef),this._renderable.unmaskMeshInstance){let s=new Ls({ref:e+1,func:2,zpass:$C});this._renderable.unmaskMeshInstance.stencilFront=s,this._renderable.unmaskMeshInstance.stencilBack=s}}_updateRenderableEmissive(){M0.linear(this._color),this._colorUniform[0]=M0.r,this._colorUniform[1]=M0.g,this._colorUniform[2]=M0.b,this._renderable.setParameter("material_emissive",this._colorUniform)}set color(t){let{r:e,g:s,b:i}=t;(this._color.r!==e||this._color.g!==s||this._color.b!==i)&&(this._color.r=e,this._color.g=s,this._color.b=i,this._updateRenderableEmissive()),this._element&&this._element.fire("set:color",this._color)}get color(){return this._color}set opacity(t){t!==this._color.a&&(this._color.a=t,this._renderable.setParameter("material_opacity",t)),this._element&&this._element.fire("set:opacity",t)}get opacity(){return this._color.a}set rect(t){let e,s,i,r;t instanceof Q?(e=t.x,s=t.y,i=t.z,r=t.w):(e=t[0],s=t[1],i=t[2],r=t[3]),!(e===this._rect.x&&s===this._rect.y&&i===this._rect.z&&r===this._rect.w)&&(this._rect.set(e,s,i,r),this._renderable.mesh&&(this._element._beingInitialized?this._meshDirty=!0:this._updateMesh(this._renderable.mesh)))}get rect(){return this._rect}_removeMaterialAssetEvents(){if(this._materialAsset){let t=this._system.app.assets;t.off(`add:${this._materialAsset}`,this._onMaterialAdded,this);let e=t.get(this._materialAsset);e&&(e.off("load",this._onMaterialLoad,this),e.off("change",this._onMaterialChange,this),e.off("remove",this._onMaterialRemove,this))}}set material(t){if(this._material!==t){if(!t){let e=this._element._isScreenSpace();this.mask?t=e?this._system.defaultScreenSpaceImageMaskMaterial:this._system.defaultImageMaskMaterial:t=e?this._system.defaultScreenSpaceImageMaterial:this._system.defaultImageMaterial}if(this._material=t,this._materialAsset){let e=this._system.app.assets.get(this._materialAsset);(!e||e.resource!==t)&&(this._removeMaterialAssetEvents(),this._materialAsset=null)}t&&(this._renderable.setMaterial(t),this._hasUserMaterial()?(this._renderable.deleteParameter("material_opacity"),this._renderable.deleteParameter("material_emissive")):(this._updateRenderableEmissive(),this._renderable.setParameter("material_opacity",this._color.a)))}}get material(){return this._material}set materialAsset(t){let e=this._system.app.assets,s=t;if(t instanceof ae&&(s=t.id),this._materialAsset!==s)if(this._removeMaterialAssetEvents(),this._materialAsset=s,this._materialAsset){let i=e.get(this._materialAsset);i?this._bindMaterialAsset(i):(this._materialAsset=null,this.material=null,this._materialAsset=s,e.on(`add:${this._materialAsset}`,this._onMaterialAdded,this))}else this._materialAsset=null,this.material=null,this._materialAsset=s}get materialAsset(){return this._materialAsset}set texture(t){if(this._texture!==t){if(this._textureAsset){let e=this._system.app.assets.get(this._textureAsset);e&&e.resource!==t&&(this.textureAsset=null)}if(this._texture=t,t){this._spriteAsset&&(this.spriteAsset=null),this._renderable.setParameter("texture_emissiveMap",this._texture),this._renderable.setParameter("texture_opacityMap",this._texture),this._updateRenderableEmissive(),this._renderable.setParameter("material_opacity",this._color.a);let e=this._texture.width/this._texture.height;e!==this._targetAspectRatio&&(this._targetAspectRatio=e,this._element.fitMode!==_u&&this.refreshMesh())}else this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"),this._targetAspectRatio=-1,this._element.fitMode!==_u&&this.refreshMesh()}}get texture(){return this._texture}set textureAsset(t){let e=this._system.app.assets,s=t;if(t instanceof ae&&(s=t.id),this._textureAsset!==s){if(this._textureAsset){e.off(`add:${this._textureAsset}`,this._onTextureAdded,this);let i=e.get(this._textureAsset);i&&(i.off("load",this._onTextureLoad,this),i.off("change",this._onTextureChange,this),i.off("remove",this._onTextureRemove,this))}if(this._textureAsset=s,this._textureAsset){let i=e.get(this._textureAsset);i?this._bindTextureAsset(i):(this.texture=null,e.on(`add:${this._textureAsset}`,this._onTextureAdded,this))}else this.texture=null}}get textureAsset(){return this._textureAsset}set spriteAsset(t){let e=this._system.app.assets,s=t;if(t instanceof ae&&(s=t.id),this._spriteAsset!==s){if(this._spriteAsset){e.off(`add:${this._spriteAsset}`,this._onSpriteAssetAdded,this);let i=e.get(this._spriteAsset);i&&this._unbindSpriteAsset(i)}if(this._spriteAsset=s,this._spriteAsset){let i=e.get(this._spriteAsset);i?this._bindSpriteAsset(i):(this.sprite=null,e.on(`add:${this._spriteAsset}`,this._onSpriteAssetAdded,this))}else this.sprite=null}this._element&&this._element.fire("set:spriteAsset",s)}get spriteAsset(){return this._spriteAsset}set sprite(t){if(this._sprite!==t){if(this._sprite&&this._unbindSprite(this._sprite),this._spriteAsset){let e=this._system.app.assets.get(this._spriteAsset);e&&e.resource!==t&&(this.spriteAsset=null)}this._sprite=t,this._sprite&&(this._bindSprite(this._sprite),this._textureAsset&&(this.textureAsset=null)),this._sprite&&this._sprite.atlas&&this._sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap")),this._sprite&&(this._spriteFrame=R.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1)),this._updateSprite()}}get sprite(){return this._sprite}set spriteFrame(t){let e=this._spriteFrame;this._sprite?this._spriteFrame=R.clamp(t,0,this._sprite.frameKeys.length-1):this._spriteFrame=t,this._spriteFrame!==e&&this._updateSprite(),this._element&&this._element.fire("set:spriteFrame",t)}get spriteFrame(){return this._spriteFrame}set mesh(t){this._renderable.setMesh(t),this._defaultMesh===t?this._renderable.setAabbFunc(null):this._renderable.setAabbFunc(this._updateAabbFunc)}get mesh(){return this._renderable.mesh}set mask(t){this._mask!==t&&(this._mask=t,this._toggleMask())}get mask(){return this._mask}set pixelsPerUnit(t){this._pixelsPerUnit!==t&&(this._pixelsPerUnit=t,this._sprite&&(this._sprite.renderMode===It||this._sprite.renderMode===Rt)&&this._updateSprite())}get pixelsPerUnit(){return this._pixelsPerUnit}get aabb(){return this._renderable.meshInstance?this._renderable.meshInstance.aabb:null}};var Bm=class extends J{constructor(t){super(),this._app=t,t.i18n.on(fa.EVENT_CHANGE,this._onSetLocale,this),this._autoLoad=!1,this._disableLocalization=!1,this._defaultAsset=null,this._localizedAsset=null}set defaultAsset(t){let e=t instanceof ae?t.id:t;this._defaultAsset!==e&&(this._defaultAsset&&this._unbindDefaultAsset(),this._defaultAsset=e,this._defaultAsset&&this._bindDefaultAsset(),this._onSetLocale(this._app.i18n.locale))}get defaultAsset(){return this._defaultAsset}set localizedAsset(t){let e=t instanceof ae?t.id:t;this._localizedAsset!==e&&(this._localizedAsset&&(this._app.assets.off(`add:${this._localizedAsset}`,this._onLocalizedAssetAdd,this),this._unbindLocalizedAsset()),this._localizedAsset=e,this._localizedAsset&&(this._app.assets.get(this._localizedAsset)?this._bindLocalizedAsset():this._app.assets.once(`add:${this._localizedAsset}`,this._onLocalizedAssetAdd,this)))}get localizedAsset(){return this._localizedAsset}set autoLoad(t){this._autoLoad!==t&&(this._autoLoad=t,this._autoLoad&&this._localizedAsset&&(this._unbindLocalizedAsset(),this._bindLocalizedAsset()))}get autoLoad(){return this._autoLoad}set disableLocalization(t){this._disableLocalization!==t&&(this._disableLocalization=t,this._onSetLocale(this._app.i18n.locale))}get disableLocalization(){return this._disableLocalization}_bindDefaultAsset(){let t=this._app.assets.get(this._defaultAsset);t?this._onDefaultAssetAdd(t):this._app.assets.once(`add:${this._defaultAsset}`,this._onDefaultAssetAdd,this)}_unbindDefaultAsset(){if(!this._defaultAsset)return;this._app.assets.off(`add:${this._defaultAsset}`,this._onDefaultAssetAdd,this);let t=this._app.assets.get(this._defaultAsset);t&&(t.off("add:localized",this._onLocaleAdd,this),t.off("remove:localized",this._onLocaleRemove,this),t.off("remove",this._onDefaultAssetRemove,this))}_onDefaultAssetAdd(t){this._defaultAsset===t.id&&(t.on("add:localized",this._onLocaleAdd,this),t.on("remove:localized",this._onLocaleRemove,this),t.once("remove",this._onDefaultAssetRemove,this))}_onDefaultAssetRemove(t){this._defaultAsset===t.id&&(t.off("add:localized",this._onLocaleAdd,this),t.off("remove:localized",this._onLocaleAdd,this),this._app.assets.once(`add:${this._defaultAsset}`,this._onDefaultAssetAdd,this))}_bindLocalizedAsset(){if(!this._autoLoad)return;let t=this._app.assets.get(this._localizedAsset);t&&(t.on("load",this._onLocalizedAssetLoad,this),t.on("change",this._onLocalizedAssetChange,this),t.on("remove",this._onLocalizedAssetRemove,this),t.resource?this._onLocalizedAssetLoad(t):this._app.assets.load(t))}_unbindLocalizedAsset(){let t=this._app.assets.get(this._localizedAsset);t&&(t.off("load",this._onLocalizedAssetLoad,this),t.off("change",this._onLocalizedAssetChange,this),t.off("remove",this._onLocalizedAssetRemove,this))}_onLocalizedAssetAdd(t){this._localizedAsset===t.id&&this._bindLocalizedAsset()}_onLocalizedAssetLoad(t){this.fire("load",t)}_onLocalizedAssetChange(t,e,s,i){this.fire("change",t,e,s,i)}_onLocalizedAssetRemove(t){this._localizedAsset===t.id&&(this.localizedAsset=this._defaultAsset),this.fire("remove",t)}_onLocaleAdd(t,e){this._app.i18n.locale===t&&this._onSetLocale(t)}_onLocaleRemove(t,e){this._app.i18n.locale===t&&this._onSetLocale(t)}_onSetLocale(t){if(!this._defaultAsset){this.localizedAsset=null;return}let e=this._app.assets.get(this._defaultAsset);if(!e||this._disableLocalization){this.localizedAsset=this._defaultAsset;return}let s=e.getLocalizedAssetId(t);if(!s){this.localizedAsset=this._defaultAsset;return}this.localizedAsset=s}destroy(){this.defaultAsset=null,this._app.i18n.off(fa.EVENT_CHANGE,this._onSetLocale,this),this.off()}};var vu="msdf",dR="bitmap";var N8=` \r\v\f`,B8=/[\w|/]/,pR=class{constructor(t){this._symbols=t,this._index=0,this._last=0,this._cur=this._symbols.length>0?this._symbols[0]:null,this._buf=[],this._mode="text",this._error=null}read(){let t=this._read();for(;t===8;)t=this._read();return t!==0&&t!==1&&(this._last=this._index),t}buf(){return this._buf}last(){return this._last}error(){return this._error}debugPrint(){let t=["EOF","ERROR","TEXT","OPEN_BRACKET","CLOSE_BRACKET","EQUALS","STRING","IDENTIFIER","WHITESPACE"],e=this.read(),s="";for(;s+=`${(s.length>0?` `:"")+t[e]} '${this.buf().join("")}'`,!(e===0||e===1);)e=this.read();return s}_read(){return this._buf=[],this._eof()?0:this._mode==="text"?this._text():this._tag()}_text(){for(;;)switch(this._cur){case null:return this._buf.length>0?2:0;case"[":return this._mode="tag",this._buf.length>0?2:this._tag();case"\\":this._next(),this._cur==="["?this._store():this._output("\\");break;default:this._store();break}}_tag(){switch(this._cur){case null:return this._error="unexpected end of input reading tag",1;case"[":return this._store(),3;case"]":return this._store(),this._mode="text",4;case"=":return this._store(),5;case" ":case" ":case` `:case"\r":case"\v":case"\f":return this._whitespace();case'"':return this._string();default:return this._isIdentifierSymbol(this._cur)?this._identifier():(this._error="unrecognized character",1)}}_whitespace(){for(this._store();N8.indexOf(this._cur)!==-1;)this._store();return 8}_string(){for(this._next();;)switch(this._cur){case null:return this._error="unexpected end of input reading string",1;case'"':return this._next(),6;default:this._store();break}}_identifier(){for(this._store();this._cur!==null&&this._isIdentifierSymbol(this._cur);)this._store();return 7}_isIdentifierSymbol(t){return t.length===1&&t.match(B8)!==null}_eof(){return this._cur===null}_next(){return this._eof()||(this._index++,this._cur=this._index=0;--a)if(i===`/${e[a].name}`&&e[a].end===null)return e[a].end=t.length,s=this._scanner.read(),s!==4?(this._error="expected close bracket",!1):!0;return this._error="failed to find matching tag",!1}let r={name:i,value:null,attributes:{},start:t.length,end:null};if(s=this._scanner.read(),s===5){if(s=this._scanner.read(),s!==6)return this._error="expected string",!1;r.value=this._scanner.buf().join(""),s=this._scanner.read()}for(;;){switch(s){case 4:return e.push(r),!0;case 7:{let a=this._scanner.buf().join("");if(s=this._scanner.read(),s!==5)return this._error="expected equals",!1;if(s=this._scanner.read(),s!==6)return this._error="expected string",!1;let o=this._scanner.buf().join("");r.attributes[a]=o;break}default:return this._error="expected close bracket or identifier",!1}s=this._scanner.read()}}};function AB(c,t){for(let e in t){if(!t.hasOwnProperty(e))continue;let s=t[e];s instanceof Object?(c.hasOwnProperty(e)||(c[e]={}),AB(c[e],t[e])):c[e]=s}}function U8(c){if(c.length===0)return null;let t={};for(let e=0;ef.find(d=>d===u)===void 0)}function r(f){for(let u=0;uf-u),o=[];for(let f=0;fa.end===null))return{symbols:c,tags:null};let r=k8(s,e.length);return{symbols:e,tags:r}}var O0=class{static evaluate(t){return z8(t)}};var _R=class{constructor(){this.count=0,this.quad=0,this.lines={},this.positions=[],this.normals=[],this.uvs=[],this.colors=[],this.indices=[],this.outlines=[],this.shadows=[],this.meshInstance=null}};function G8(c,t){let e=new _e(c);return e.setPositions(t.positions),e.setNormals(t.normals),e.setColors32(t.colors),e.setUvs(0,t.uvs),e.setIndices(t.indices),e.setVertexStream(rc,t.outlines,3,void 0,ye,!1),e.setVertexStream(ac,t.shadows,3,void 0,ye,!1),e.update(),e}var CB=/^[\r\n]$/,V8=/^[ \t]$/,PB=/^[ \t\-]|\u200b$/,H8=/^[a-z0-9]$/i,wB=/^[\u1100-\u11ff]|[\u3000-\u9fff\ua960-\ua97f]|[\uac00-\ud7ff]$/,W8=/^[〕〉》」』】〙〗〟ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻]$/,X8=["\u200B","\u061C","\u200E","\u200F","\u202A","\u202B","\u202C","\u202D","\u202E","\u2066","\u2067","\u2068","\u2069"],Y8={width:0,height:0,xadvance:0,xoffset:0,yoffset:0},IB=new F,K8=new B,Et=new F,Um=class{constructor(t){this._element=t,this._system=t.system,this._entity=t.entity,this._text="",this._symbols=[],this._colorPalette=[],this._outlinePalette=[],this._shadowPalette=[],this._symbolColors=null,this._symbolOutlineParams=null,this._symbolShadowParams=null,this._i18nKey=null,this._fontAsset=new Bm(this._system.app),this._fontAsset.disableLocalization=!0,this._fontAsset.on("load",this._onFontLoad,this),this._fontAsset.on("change",this._onFontChange,this),this._fontAsset.on("remove",this._onFontRemove,this),this._font=null,this._color=new F(1,1,1,1),this._colorUniform=new Float32Array(3),this._spacing=1,this._fontSize=32,this._fontMinY=0,this._fontMaxY=0,this._originalFontSize=32,this._maxFontSize=32,this._minFontSize=8,this._autoFitWidth=!1,this._autoFitHeight=!1,this._maxLines=-1,this._lineHeight=32,this._scaledLineHeight=32,this._wrapLines=!1,this._drawOrder=0,this._alignment=new B(.5,.5),this._autoWidth=!0,this._autoHeight=!0,this.width=0,this.height=0,this._node=new Pe,this._model=new Ei,this._model.graph=this._node,this._entity.addChild(this._node),this._meshInfo=[],this._material=null,this._aabbDirty=!0,this._aabb=new ge,this._noResize=!1,this._currentMaterialType=null,this._maskedMaterialSrc=null,this._rtlReorder=!1,this._unicodeConverter=!1,this._rtl=!1,this._outlineColor=new F(0,0,0,1),this._outlineColorUniform=new Float32Array(4),this._outlineThicknessScale=.2,this._outlineThickness=0,this._shadowColor=new F(0,0,0,1),this._shadowColorUniform=new Float32Array(4),this._shadowOffsetScale=.005,this._shadowOffset=new B(0,0),this._shadowOffsetUniform=new Float32Array(2),this._enableMarkup=!1,this._onScreenChange(this._element.screen),t.on("resize",this._onParentResize,this),t.on("set:screen",this._onScreenChange,this),t.on("screen:set:screenspace",this._onScreenSpaceChange,this),t.on("set:draworder",this._onDrawOrderChange,this),t.on("set:pivot",this._onPivotChange,this),this._system.app.i18n.on(fa.EVENT_CHANGE,this._onLocaleSet,this),this._system.app.i18n.on("data:add",this._onLocalizationData,this),this._system.app.i18n.on("data:remove",this._onLocalizationData,this),this._rangeStart=0,this._rangeEnd=0,!t._beingInitialized&&t.enabled&&t.entity.enabled&&this.onEnable()}destroy(){this._setMaterial(null),this._model&&(this._element.removeModelFromLayers(this._model),this._model.destroy(),this._model=null),this._fontAsset.destroy(),this.font=null,this._element.off("resize",this._onParentResize,this),this._element.off("set:screen",this._onScreenChange,this),this._element.off("screen:set:screenspace",this._onScreenSpaceChange,this),this._element.off("set:draworder",this._onDrawOrderChange,this),this._element.off("set:pivot",this._onPivotChange,this),this._system.app.i18n.off(fa.EVENT_CHANGE,this._onLocaleSet,this),this._system.app.i18n.off("data:add",this._onLocalizationData,this),this._system.app.i18n.off("data:remove",this._onLocalizationData,this)}_onParentResize(t,e){this._noResize||this._font&&this._updateText()}_onScreenChange(t){t?this._updateMaterial(t.screen.screenSpace):this._updateMaterial(!1)}_onScreenSpaceChange(t){this._updateMaterial(t)}_onDrawOrderChange(t){if(this._drawOrder=t,this._model)for(let e=0,s=this._model.meshInstances.length;ee[p]))}}else this._rtl=!1;let s=(u,d)=>`${u.toString(!0).toLowerCase()}:${d.toFixed(2)}`,i=(u,d)=>`${u.toString(!0).toLowerCase()}:${d.x.toFixed(2)}:${d.y.toFixed(2)}`;if(e){let u={},d={},p={};this._colorPalette=[Math.round(this._color.r*255),Math.round(this._color.g*255),Math.round(this._color.b*255)],this._outlinePalette=[Math.round(this._outlineColor.r*255),Math.round(this._outlineColor.g*255),Math.round(this._outlineColor.b*255),Math.round(this._outlineColor.a*255),Math.round(this._outlineThickness*255)],this._shadowPalette=[Math.round(this._shadowColor.r*255),Math.round(this._shadowColor.g*255),Math.round(this._shadowColor.b*255),Math.round(this._shadowColor.a*255),Math.round(this._shadowOffset.x*127),Math.round(this._shadowOffset.y*127)],this._symbolColors=[],this._symbolOutlineParams=[],this._symbolShadowParams=[],u[this._color.toString(!1).toLowerCase()]=0,d[s(this._outlineColor,this._outlineThickness)]=0,p[i(this._shadowColor,this._shadowOffset)]=0;for(let m=0,_=this._symbols.length;m<_;++m){let S=e[m],g=0;if(S&&S.color&&S.color.value){let v=S.color.value;if(v.length===7&&v[0]==="#"){let E=v.substring(1).toLowerCase();u.hasOwnProperty(E)?g=u[E]:/^[0-9a-f]{6}$/.test(E)&&(g=this._colorPalette.length/3,u[E]=g,this._colorPalette.push(parseInt(E.substring(0,2),16)),this._colorPalette.push(parseInt(E.substring(2,4),16)),this._colorPalette.push(parseInt(E.substring(4,6),16)))}}this._symbolColors.push(g);let T=0;if(S&&S.outline&&(S.outline.attributes.color||S.outline.attributes.thickness)){let v=S.outline.attributes.color?IB.fromString(S.outline.attributes.color):this._outlineColor,E=Number(S.outline.attributes.thickness);(Number.isNaN(v.r)||Number.isNaN(v.g)||Number.isNaN(v.b)||Number.isNaN(v.a))&&(v=this._outlineColor),Number.isNaN(E)&&(E=this._outlineThickness);let y=s(v,E);d.hasOwnProperty(y)?T=d[y]:(T=this._outlinePalette.length/5,d[y]=T,this._outlinePalette.push(Math.round(v.r*255),Math.round(v.g*255),Math.round(v.b*255),Math.round(v.a*255),Math.round(E*255)))}this._symbolOutlineParams.push(T);let C=0;if(S&&S.shadow&&(S.shadow.attributes.color||S.shadow.attributes.offset||S.shadow.attributes.offsetX||S.shadow.attributes.offsetY)){let v=S.shadow.attributes.color?IB.fromString(S.shadow.attributes.color):this._shadowColor,E=Number(S.shadow.attributes.offset),y=Number(S.shadow.attributes.offsetX),P=Number(S.shadow.attributes.offsetY);(Number.isNaN(v.r)||Number.isNaN(v.g)||Number.isNaN(v.b)||Number.isNaN(v.a))&&(v=this._shadowColor);let A=K8.set(Number.isNaN(y)?Number.isNaN(E)?this._shadowOffset.x:E:y,Number.isNaN(P)?Number.isNaN(E)?this._shadowOffset.y:E:P),w=i(v,A);p.hasOwnProperty(w)?C=p[w]:(C=this._shadowPalette.length/6,p[w]=C,this._shadowPalette.push(Math.round(v.r*255),Math.round(v.g*255),Math.round(v.b*255),Math.round(v.a*255),Math.round(A.x*127),Math.round(A.y*127)))}this._symbolShadowParams.push(C)}}else this._colorPalette=[],this._symbolColors=null,this._symbolOutlineParams=null,this._symbolShadowParams=null;this._updateMaterialEmissive(),this._updateMaterialOutline(),this._updateMaterialShadow();let r=this._calculateCharsPerTexture(),a=!1,o=this._element,l=o._isScreenSpace(),h=o._isScreenCulled(),f=function(u){return o.isVisibleForCamera(u)};for(let u=0,d=this._meshInfo.length;u=1e-4,v=this._element.calculatedWidth;(this.autoWidth&&!C||!this._wrapLines)&&(v=Number.POSITIVE_INFINITY);let E=0,y=0,P,A,w,I;function D(L,b,N){e._lineWidths.push(Math.abs(N));let k=_>b?b+1:_,z=_>b?_+1:b,V=L.slice(k,z);if(T){let q=V.length;for(;q--&&T>0;)CB.test(V[q])&&(V.splice(q,1),T--)}e._lineContents.push(V.join("")),l=0,h-=e._scaledLineHeight,d++,S=0,g=0,T=0,p=0,_=b}let O=!0;for(;O;){O=!1,r?this._scaledLineHeight=this._lineHeight*this._fontSize/(this._maxFontSize||1e-4):this._scaledLineHeight=this._lineHeight,this.width=0,this.height=0,this._lineWidths=[],this._lineContents=[],l=0,h=0,f=0,u=0,d=1,p=0,m=0,_=0,S=0,g=0,T=0;let L=this._fontSize/a;E=this._fontMinY*L,y=this._fontMaxY*L;for(let oe=0;oe=o?null:this._symbols[oe+1],CB.test(P)){T++,(!this._wrapLines||this._maxLines<0||d0){let Px=this._font.data.kerning;if(Px){let wx=Px[Nr.getCodePoint(this._symbols[oe-1])||0];wx&&(mt=wx[Nr.getCodePoint(this._symbols[oe])||0]||0)}}Vs=A.scale||1,ds=(A.width+A.height)/2,Lt=L*ds/Vs,Ve=(A.xadvance+mt)*L,qe=(A.xoffset-mt)*L,ot=A.yoffset*L}let Cs=V8.test(P),di=A&&A.map||0,Qu=-this._font.data.info.maps[di].width/this._font.data.info.maps[di].height,de=this._meshInfo[di],Qb=l+this._spacing*Ve;if(Qb>v&&g>0&&!Cs&&(this._maxLines<0||dthis._element.calculatedWidth&&(Vl=Math.floor(this._element.fontSize*this._element.calculatedWidth/(this.width||1e-4)),Vl=R.clamp(Vl,s,i),Vl!==this._element.fontSize)){this._fontSize=Vl,O=!0;break}if(this.height=Math.max(this.height,y-(h+E)),this._shouldAutoFitHeight()&&this.height>this._element.calculatedHeight&&(Vl=R.clamp(this._fontSize-1,s,i),Vl!==this._element.fontSize)){this._fontSize=Vl,O=!0;break}l+=this._spacing*Ve,Cs||(u=l),(this._isWordBoundary(P)||this._isValidNextChar(I)&&(this._isNextCJKBoundary(P,I)||this._isNextCJKWholeWord(I)))&&(S++,p=u,m=oe+1),g++;let Hl=this._getUv(P);if(de.uvs[w*4*2+0]=Hl[0],de.uvs[w*4*2+1]=1-Hl[1],de.uvs[w*4*2+2]=Hl[2],de.uvs[w*4*2+3]=1-Hl[1],de.uvs[w*4*2+4]=Hl[2],de.uvs[w*4*2+5]=1-Hl[3],de.uvs[w*4*2+6]=Hl[0],de.uvs[w*4*2+7]=1-Hl[3],this._symbolColors){let mt=this._symbolColors[oe]*3;b=this._colorPalette[mt],N=this._colorPalette[mt+1],k=this._colorPalette[mt+2]}if(de.colors[w*4*4+0]=b,de.colors[w*4*4+1]=N,de.colors[w*4*4+2]=k,de.colors[w*4*4+3]=255,de.colors[w*4*4+4]=b,de.colors[w*4*4+5]=N,de.colors[w*4*4+6]=k,de.colors[w*4*4+7]=255,de.colors[w*4*4+8]=b,de.colors[w*4*4+9]=N,de.colors[w*4*4+10]=k,de.colors[w*4*4+11]=255,de.colors[w*4*4+12]=b,de.colors[w*4*4+13]=N,de.colors[w*4*4+14]=k,de.colors[w*4*4+15]=255,this._symbolOutlineParams){let mt=this._symbolOutlineParams[oe]*5;z=this._outlinePalette[mt]+this._outlinePalette[mt+1]*256,V=this._outlinePalette[mt+2]+this._outlinePalette[mt+3]*256,q=this._outlinePalette[mt+4]}if(de.outlines[w*4*3+0]=z,de.outlines[w*4*3+1]=V,de.outlines[w*4*3+2]=q,de.outlines[w*4*3+3]=z,de.outlines[w*4*3+4]=V,de.outlines[w*4*3+5]=q,de.outlines[w*4*3+6]=z,de.outlines[w*4*3+7]=V,de.outlines[w*4*3+8]=q,de.outlines[w*4*3+9]=z,de.outlines[w*4*3+10]=V,de.outlines[w*4*3+11]=q,this._symbolShadowParams){let mt=this._symbolShadowParams[oe]*6;re=this._shadowPalette[mt]+this._shadowPalette[mt+1]*256,te=this._shadowPalette[mt+2]+this._shadowPalette[mt+3]*256,j=this._shadowPalette[mt+4]+127+Math.round(Qu*this._shadowPalette[mt+5]+127)*256}de.shadows[w*4*3+0]=re,de.shadows[w*4*3+1]=te,de.shadows[w*4*3+2]=j,de.shadows[w*4*3+3]=re,de.shadows[w*4*3+4]=te,de.shadows[w*4*3+5]=j,de.shadows[w*4*3+6]=re,de.shadows[w*4*3+7]=te,de.shadows[w*4*3+8]=j,de.shadows[w*4*3+9]=re,de.shadows[w*4*3+10]=te,de.shadows[w*4*3+11]=j,de.quad++}O||_=k?(z.element[ee].set(0,0,0),z.element[_t].set(0,0),z.element[Ct].set(0,0,0,0),z.element[rc].set(0,0,0,0),z.element[ac].set(0,0,0,0)):(z.element[ee].set(this._meshInfo[L].positions[V*3+0],this._meshInfo[L].positions[V*3+1],this._meshInfo[L].positions[V*3+2]),z.element[_t].set(this._meshInfo[L].uvs[V*2+0],this._meshInfo[L].uvs[V*2+1]),z.element[Ct].set(this._meshInfo[L].colors[V*4+0],this._meshInfo[L].colors[V*4+1],this._meshInfo[L].colors[V*4+2],this._meshInfo[L].colors[V*4+3]),z.element[rc].set(this._meshInfo[L].outlines[V*3+0],this._meshInfo[L].outlines[V*3+1],this._meshInfo[L].outlines[V*3+2]),z.element[ac].set(this._meshInfo[L].shadows[V*3+0],this._meshInfo[L].shadows[V*3+1],this._meshInfo[L].shadows[V*3+2])),z.next();z.end(),this._meshInfo[L].meshInstance.mesh.aabb.compute(this._meshInfo[L].positions),this._meshInfo[L].meshInstance._aabbVer=-1}this._aabbDirty=!0}_onFontRender(){this.font=this._font}_onFontLoad(t){this.font!==t.resource&&(this.font=t.resource)}_onFontChange(t,e,s,i){if(e==="data"){this._font.data=s;let r=this._font.data.info.maps.length;for(let a=0;athis._font.textures.length&&(this._meshInfo.length=this._font.textures.length),this._updateText()}get font(){return this._font}set alignment(t){t instanceof B?this._alignment.set(t.x,t.y):this._alignment.set(t[0],t[1]),this._font&&this._updateText()}get alignment(){return this._alignment}set autoWidth(t){let e=this._autoWidth;if(this._autoWidth=t,t&&Math.abs(this._element.anchor.x-this._element.anchor.z)<1e-4&&(this._element.width=this.width),e!==t){let s=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize;s!==this._fontSize&&(this._fontSize=s,this._font&&this._updateText())}}get autoWidth(){return this._autoWidth}set autoHeight(t){let e=this._autoHeight;if(this._autoHeight=t,t&&Math.abs(this._element.anchor.y-this._element.anchor.w)<1e-4&&(this._element.height=this.height),e!==t){let s=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize;s!==this._fontSize&&(this._fontSize=s,this._font&&this._updateText())}}get autoHeight(){return this._autoHeight}set rtlReorder(t){this._rtlReorder!==t&&(this._rtlReorder=t,this._font&&this._updateText())}get rtlReorder(){return this._rtlReorder}set unicodeConverter(t){this._unicodeConverter!==t&&(this._unicodeConverter=t,this._setText(this._text))}get unicodeConverter(){return this._unicodeConverter}get aabb(){if(this._aabbDirty){let t=!1;for(let e=0;e.001}get _hasSplitAnchorsY(){return Math.abs(this._anchor.y-this._anchor.w)>.001}get aabb(){return this._image?this._image.aabb:this._text?this._text.aabb:null}set anchor(e){e instanceof Q?this._anchor.copy(e):this._anchor.set(...e),!this.entity._parent&&!this.screen?this._calculateLocalAnchors():this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY),this._anchorDirty=!0,this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:anchor",this._anchor)}get anchor(){return this._anchor}set batchGroupId(e){this._batchGroupId!==e&&(this.entity.enabled&&this._batchGroupId>=0&&this.system.app.batcher?.remove(pt.ELEMENT,this.batchGroupId,this.entity),this.entity.enabled&&e>=0&&this.system.app.batcher?.insert(pt.ELEMENT,e,this.entity),e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&(this._image&&this._image._renderable.model?this.addModelToLayers(this._image._renderable.model):this._text&&this._text._model&&this.addModelToLayers(this._text._model)),this._batchGroupId=e)}get batchGroupId(){return this._batchGroupId}set bottom(e){this._margin.y=e;let s=this.entity.getLocalPosition(),i=this._absTop,r=this._localAnchor.y+e;this._setHeight(i-r),s.y=e+this._calculatedHeight*this._pivot.y,this.entity.setLocalPosition(s)}get bottom(){return this._margin.y}set calculatedWidth(e){this._setCalculatedWidth(e,!0)}get calculatedWidth(){return this._calculatedWidth}set calculatedHeight(e){this._setCalculatedHeight(e,!0)}get calculatedHeight(){return this._calculatedHeight}get canvasCorners(){if(!this._canvasCornersDirty||!this.screen||!this.screen.screen.screenSpace)return this._canvasCorners;let e=this.system.app.graphicsDevice,s=this.screenCorners,i=e.canvas.clientWidth/e.width,r=e.canvas.clientHeight/e.height;for(let a=0;a<4;a++)this._canvasCorners[a].set(s[a].x*i,(e.height-s[a].y)*r);return this._canvasCornersDirty=!1,this._canvasCorners}set drawOrder(e){let s=0;this.screen&&(s=this.screen.screen.priority),e>16777215&&(e=16777215),this._drawOrder=(s<<24)+e,this.fire("set:draworder",this._drawOrder)}get drawOrder(){return this._drawOrder}set height(e){this._height=e,this._hasSplitAnchorsY||this._setCalculatedHeight(e,!0),this.fire("set:height",this._height)}get height(){return this._height}set layers(e){if(this._addedModels.length)for(let s=0;s=0&&this.system._prerender.splice(i,1),this.system._prerender.indexOf(e)<0&&this.system._prerender.push(e)}e=s}}_onPrerender(){for(let e=0;e=0&&this.system.app.batcher?.insert(pt.ELEMENT,this.batchGroupId,this.entity),this.fire("enableelement")}onDisable(){let s=this.system.app.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,s&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this._image&&this._image.onDisable(),this._text&&this._text.onDisable(),this._group&&this._group.onDisable(),this.system.app.elementInput&&this.useInput&&this.system.app.elementInput.removeElement(this),this._batchGroupId>=0&&this.system.app.batcher?.remove(pt.ELEMENT,this.batchGroupId,this.entity),this.fire("disableelement")}onRemove(){this.entity.off("insert",this._onInsert,this),this._unpatch(),this._image&&this._image.destroy(),this._text&&this._text.destroy(),this.system.app.elementInput&&this.useInput&&this.system.app.elementInput.removeElement(this),this.screen&&this.screen.screen&&(this._unbindScreen(this.screen.screen),this.screen.screen.syncDrawOrder()),this.off()}_calculateSize(e,s){if(!this.entity._parent&&!this.screen)return;this._calculateLocalAnchors();let i=this._absRight-this._absLeft,r=this._absTop-this._absBottom;e?this._setWidth(i):this._setCalculatedWidth(i,!1),s?this._setHeight(r):this._setCalculatedHeight(r,!1);let a=this.entity.getLocalPosition();a.x=this._margin.x+this._calculatedWidth*this._pivot.x,a.y=this._margin.y+this._calculatedHeight*this._pivot.y,this.entity.setLocalPosition(a),this._sizeDirty=!1}_setWidth(e){this._width=e,this._setCalculatedWidth(e,!1),this.fire("set:width",this._width)}_setHeight(e){this._height=e,this._setCalculatedHeight(e,!1),this.fire("set:height",this._height)}_setCalculatedWidth(e,s){if(!(Math.abs(e-this._calculatedWidth)<=1e-4)){if(this._calculatedWidth=e,this.entity._dirtifyLocal(),s){let i=this.entity.getLocalPosition(),r=this._pivot;this._margin.x=i.x-this._calculatedWidth*r.x,this._margin.z=this._localAnchor.z-this._localAnchor.x-this._calculatedWidth-this._margin.x}this._flagChildrenAsDirty(),this.fire("set:calculatedWidth",this._calculatedWidth),this.fire("resize",this._calculatedWidth,this._calculatedHeight)}}_setCalculatedHeight(e,s){if(!(Math.abs(e-this._calculatedHeight)<=1e-4)){if(this._calculatedHeight=e,this.entity._dirtifyLocal(),s){let i=this.entity.getLocalPosition(),r=this._pivot;this._margin.y=i.y-this._calculatedHeight*r.y,this._margin.w=this._localAnchor.w-this._localAnchor.y-this._calculatedHeight-this._margin.y}this._flagChildrenAsDirty(),this.fire("set:calculatedHeight",this._calculatedHeight),this.fire("resize",this._calculatedWidth,this._calculatedHeight)}}_flagChildrenAsDirty(){let e=this.entity._children;for(let s=0,i=e.length;s=0&&this._addedModels.splice(s,1);for(let i=0;ii||f>r||u.001,r=Math.abs(t.anchor.y-t.anchor.w)>.001,a=!1,o;e.margin!==void 0&&(e.margin instanceof Q?t.margin.copy(e.margin):t._margin.set(e.margin[0],e.margin[1],e.margin[2],e.margin[3]),a=!0),e.left!==void 0&&(t._margin.x=e.left,a=!0),e.bottom!==void 0&&(t._margin.y=e.bottom,a=!0),e.right!==void 0&&(t._margin.z=e.right,a=!0),e.top!==void 0&&(t._margin.w=e.top,a=!0),a&&(t.margin=t._margin);let l=!1;e.width!==void 0&&!i?t.width=e.width:i&&(l=!0),e.height!==void 0&&!r?t.height=e.height:r&&(l=!0),l&&(t.anchor=t.anchor),e.enabled!==void 0&&(t.enabled=e.enabled),e.useInput!==void 0&&(t.useInput=e.useInput),e.fitMode!==void 0&&(t.fitMode=e.fitMode),t.batchGroupId=e.batchGroupId===void 0||e.batchGroupId===null?-1:e.batchGroupId,e.layers&&Array.isArray(e.layers)&&(t.layers=e.layers.slice(0)),e.type!==void 0&&(t.type=e.type),t.type===Dm?(e.rect!==void 0&&(t.rect=e.rect),e.color!==void 0&&(o=e.color,o instanceof F||(o=new F(e.color[0],e.color[1],e.color[2])),t.color=o),e.opacity!==void 0&&(t.opacity=e.opacity),e.textureAsset!==void 0&&(t.textureAsset=e.textureAsset),e.texture&&(t.texture=e.texture),e.spriteAsset!==void 0&&(t.spriteAsset=e.spriteAsset),e.sprite&&(t.sprite=e.sprite),e.spriteFrame!==void 0&&(t.spriteFrame=e.spriteFrame),e.pixelsPerUnit!==void 0&&e.pixelsPerUnit!==null&&(t.pixelsPerUnit=e.pixelsPerUnit),e.materialAsset!==void 0&&(t.materialAsset=e.materialAsset),e.material&&(t.material=e.material),e.mask!==void 0&&(t.mask=e.mask)):t.type===kS&&(e.autoWidth!==void 0&&(t.autoWidth=e.autoWidth),e.autoHeight!==void 0&&(t.autoHeight=e.autoHeight),e.rtlReorder!==void 0&&(t.rtlReorder=e.rtlReorder),e.unicodeConverter!==void 0&&(t.unicodeConverter=e.unicodeConverter),e.text!==null&&e.text!==void 0?t.text=e.text:e.key!==null&&e.key!==void 0&&(t.key=e.key),e.color!==void 0&&(o=e.color,o instanceof F||(o=new F(o[0],o[1],o[2])),t.color=o),e.opacity!==void 0&&(t.opacity=e.opacity),e.spacing!==void 0&&(t.spacing=e.spacing),e.fontSize!==void 0&&(t.fontSize=e.fontSize,e.lineHeight||(t.lineHeight=e.fontSize)),e.lineHeight!==void 0&&(t.lineHeight=e.lineHeight),e.maxLines!==void 0&&(t.maxLines=e.maxLines),e.wrapLines!==void 0&&(t.wrapLines=e.wrapLines),e.minFontSize!==void 0&&(t.minFontSize=e.minFontSize),e.maxFontSize!==void 0&&(t.maxFontSize=e.maxFontSize),e.autoFitWidth&&(t.autoFitWidth=e.autoFitWidth),e.autoFitHeight&&(t.autoFitHeight=e.autoFitHeight),e.fontAsset!==void 0&&(t.fontAsset=e.fontAsset),e.font!==void 0&&(t.font=e.font),e.alignment!==void 0&&(t.alignment=e.alignment),e.outlineColor!==void 0&&(t.outlineColor=e.outlineColor),e.outlineThickness!==void 0&&(t.outlineThickness=e.outlineThickness),e.shadowColor!==void 0&&(t.shadowColor=e.shadowColor),e.shadowOffset!==void 0&&(t.shadowOffset=e.shadowOffset),e.enableMarkup!==void 0&&(t.enableMarkup=e.enableMarkup));let h=t._parseUpToScreen();h.screen&&t._updateScreen(h.screen),super.initializeComponentData(t,e,s),t._beingInitialized=!1,t.type===Dm&&t._image._meshDirty&&t._image._updateMesh(t._image.mesh)}onAddComponent(t,e){t.fire("element:add")}onRemoveComponent(t,e){e.onRemove()}cloneComponent(t,e){let s=t.element,i={enabled:s.enabled,width:s.width,height:s.height,anchor:s.anchor.clone(),pivot:s.pivot.clone(),margin:s.margin.clone(),alignment:s.alignment&&s.alignment.clone()||s.alignment,autoWidth:s.autoWidth,autoHeight:s.autoHeight,type:s.type,rect:s.rect&&s.rect.clone()||s.rect,rtlReorder:s.rtlReorder,unicodeConverter:s.unicodeConverter,materialAsset:s.materialAsset,material:s.material,color:s.color&&s.color.clone()||s.color,opacity:s.opacity,textureAsset:s.textureAsset,texture:s.texture,spriteAsset:s.spriteAsset,sprite:s.sprite,spriteFrame:s.spriteFrame,pixelsPerUnit:s.pixelsPerUnit,spacing:s.spacing,lineHeight:s.lineHeight,wrapLines:s.wrapLines,layers:s.layers,fontSize:s.fontSize,minFontSize:s.minFontSize,maxFontSize:s.maxFontSize,autoFitWidth:s.autoFitWidth,autoFitHeight:s.autoFitHeight,maxLines:s.maxLines,fontAsset:s.fontAsset,font:s.font,useInput:s.useInput,fitMode:s.fitMode,batchGroupId:s.batchGroupId,mask:s.mask,outlineColor:s.outlineColor&&s.outlineColor.clone()||s.outlineColor,outlineThickness:s.outlineThickness,shadowColor:s.shadowColor&&s.shadowColor.clone()||s.shadowColor,shadowOffset:s.shadowOffset&&s.shadowOffset.clone()||s.shadowOffset,enableMarkup:s.enableMarkup};return s.key!==void 0&&s.key!==null?i.key=s.key:i.text=s.text,this.addComponent(e,i)}getTextElementMaterial(t,e,s){let i=(t&&1)|(e&&2)|(s&&4),r=this._defaultTextMaterials[i];if(r)return r;let a="TextMaterial";return r=new it,e?(r.msdfMap=this._defaultTexture,r.msdfTextAttribute=s,r.emissive.set(1,1,1)):(a=`Bitmap${a}`,r.emissive.set(1,1,1),r.emissiveMap=this._defaultTexture,r.opacityMap=this._defaultTexture,r.opacityMapChannel="a"),t&&(a=`ScreenSpace${a}`,r.depthTest=!1),r.name=`default${a}`,r.useLighting=!1,r.useTonemap=!1,r.useFog=!1,r.useSkybox=!1,r.diffuse.set(0,0,0),r.opacity=.5,r.blendType=Ms,r.depthWrite=!1,r.emissiveVertexColor=!0,r.update(),this._defaultTextMaterials[i]=r,r}_createBaseImageMaterial(){let t=new it;return t.diffuse.set(0,0,0),t.emissive.set(1,1,1),t.emissiveMap=this._defaultTexture,t.opacityMap=this._defaultTexture,t.opacityMapChannel="a",t.useLighting=!1,t.useTonemap=!1,t.useFog=!1,t.useSkybox=!1,t.blendType=Ms,t.depthWrite=!1,t}getImageElementMaterial(t,e,s,i){return t?e?s?(this.defaultScreenSpaceImageMask9SlicedMaterial||(this.defaultScreenSpaceImageMask9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMask9SlicedMaterial.name="defaultScreenSpaceImageMask9SlicedMaterial",this.defaultScreenSpaceImageMask9SlicedMaterial.nineSlicedMode=It,this.defaultScreenSpaceImageMask9SlicedMaterial.depthTest=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.alphaTest=1,this.defaultScreenSpaceImageMask9SlicedMaterial.redWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.greenWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.blueWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.alphaWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMask9SlicedMaterial)),this.defaultScreenSpaceImageMask9SlicedMaterial):i?(this.defaultScreenSpaceImageMask9TiledMaterial||(this.defaultScreenSpaceImageMask9TiledMaterial=this.defaultScreenSpaceImage9TiledMaterial.clone(),this.defaultScreenSpaceImageMask9TiledMaterial.name="defaultScreenSpaceImageMask9TiledMaterial",this.defaultScreenSpaceImageMask9TiledMaterial.nineSlicedMode=Rt,this.defaultScreenSpaceImageMask9TiledMaterial.depthTest=!1,this.defaultScreenSpaceImageMask9TiledMaterial.alphaTest=1,this.defaultScreenSpaceImageMask9TiledMaterial.redWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.greenWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.blueWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.alphaWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMask9TiledMaterial)),this.defaultScreenSpaceImageMask9TiledMaterial):(this.defaultScreenSpaceImageMaskMaterial||(this.defaultScreenSpaceImageMaskMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMaskMaterial.name="defaultScreenSpaceImageMaskMaterial",this.defaultScreenSpaceImageMaskMaterial.depthTest=!1,this.defaultScreenSpaceImageMaskMaterial.alphaTest=1,this.defaultScreenSpaceImageMaskMaterial.redWrite=!1,this.defaultScreenSpaceImageMaskMaterial.greenWrite=!1,this.defaultScreenSpaceImageMaskMaterial.blueWrite=!1,this.defaultScreenSpaceImageMaskMaterial.alphaWrite=!1,this.defaultScreenSpaceImageMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMaskMaterial)),this.defaultScreenSpaceImageMaskMaterial):s?(this.defaultScreenSpaceImage9SlicedMaterial||(this.defaultScreenSpaceImage9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9SlicedMaterial.name="defaultScreenSpaceImage9SlicedMaterial",this.defaultScreenSpaceImage9SlicedMaterial.nineSlicedMode=It,this.defaultScreenSpaceImage9SlicedMaterial.depthTest=!1,this.defaultScreenSpaceImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImage9SlicedMaterial)),this.defaultScreenSpaceImage9SlicedMaterial):i?(this.defaultScreenSpaceImage9TiledMaterial||(this.defaultScreenSpaceImage9TiledMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9TiledMaterial.name="defaultScreenSpaceImage9TiledMaterial",this.defaultScreenSpaceImage9TiledMaterial.nineSlicedMode=Rt,this.defaultScreenSpaceImage9TiledMaterial.depthTest=!1,this.defaultScreenSpaceImage9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImage9TiledMaterial)),this.defaultScreenSpaceImage9TiledMaterial):(this.defaultScreenSpaceImageMaterial||(this.defaultScreenSpaceImageMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMaterial.name="defaultScreenSpaceImageMaterial",this.defaultScreenSpaceImageMaterial.depthTest=!1,this.defaultScreenSpaceImageMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMaterial)),this.defaultScreenSpaceImageMaterial):e?s?(this.defaultImage9SlicedMaskMaterial||(this.defaultImage9SlicedMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9SlicedMaskMaterial.name="defaultImage9SlicedMaskMaterial",this.defaultImage9SlicedMaskMaterial.nineSlicedMode=It,this.defaultImage9SlicedMaskMaterial.alphaTest=1,this.defaultImage9SlicedMaskMaterial.redWrite=!1,this.defaultImage9SlicedMaskMaterial.greenWrite=!1,this.defaultImage9SlicedMaskMaterial.blueWrite=!1,this.defaultImage9SlicedMaskMaterial.alphaWrite=!1,this.defaultImage9SlicedMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9SlicedMaskMaterial)),this.defaultImage9SlicedMaskMaterial):i?(this.defaultImage9TiledMaskMaterial||(this.defaultImage9TiledMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9TiledMaskMaterial.name="defaultImage9TiledMaskMaterial",this.defaultImage9TiledMaskMaterial.nineSlicedMode=Rt,this.defaultImage9TiledMaskMaterial.alphaTest=1,this.defaultImage9TiledMaskMaterial.redWrite=!1,this.defaultImage9TiledMaskMaterial.greenWrite=!1,this.defaultImage9TiledMaskMaterial.blueWrite=!1,this.defaultImage9TiledMaskMaterial.alphaWrite=!1,this.defaultImage9TiledMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9TiledMaskMaterial)),this.defaultImage9TiledMaskMaterial):(this.defaultImageMaskMaterial||(this.defaultImageMaskMaterial=this._createBaseImageMaterial(),this.defaultImageMaskMaterial.name="defaultImageMaskMaterial",this.defaultImageMaskMaterial.alphaTest=1,this.defaultImageMaskMaterial.redWrite=!1,this.defaultImageMaskMaterial.greenWrite=!1,this.defaultImageMaskMaterial.blueWrite=!1,this.defaultImageMaskMaterial.alphaWrite=!1,this.defaultImageMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImageMaskMaterial)),this.defaultImageMaskMaterial):s?(this.defaultImage9SlicedMaterial||(this.defaultImage9SlicedMaterial=this._createBaseImageMaterial(),this.defaultImage9SlicedMaterial.name="defaultImage9SlicedMaterial",this.defaultImage9SlicedMaterial.nineSlicedMode=It,this.defaultImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9SlicedMaterial)),this.defaultImage9SlicedMaterial):i?(this.defaultImage9TiledMaterial||(this.defaultImage9TiledMaterial=this._createBaseImageMaterial(),this.defaultImage9TiledMaterial.name="defaultImage9TiledMaterial",this.defaultImage9TiledMaterial.nineSlicedMode=Rt,this.defaultImage9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9TiledMaterial)),this.defaultImage9TiledMaterial):(this.defaultImageMaterial||(this.defaultImageMaterial=this._createBaseImageMaterial(),this.defaultImageMaterial.name="defaultImageMaterial",this.defaultImageMaterial.update(),this.defaultImageMaterials.push(this.defaultImageMaterial)),this.defaultImageMaterial)}registerUnicodeConverter(t){this._unicodeConverter=t}registerRtlReorder(t){this._rtlReorder=t}getUnicodeConverter(){return this._unicodeConverter}getRtlReorder(){return this._rtlReorder}};var nh="free",lh="limited",ch="locked";var $8=["angularDampingX","angularDampingY","angularDampingZ","angularEquilibriumX","angularEquilibriumY","angularEquilibriumZ","angularLimitsX","angularLimitsY","angularLimitsZ","angularMotionX","angularMotionY","angularMotionZ","angularSpringX","angularSpringY","angularSpringZ","angularStiffnessX","angularStiffnessY","angularStiffnessZ","breakForce","enableCollision","enabled","entityA","entityB","linearDampingX","linearDampingY","linearDampingZ","linearEquilibriumX","linearEquilibriumY","linearEquilibriumZ","linearLimitsX","linearLimitsY","linearLimitsZ","linearMotionX","linearMotionY","linearMotionZ","linearSpringX","linearSpringY","linearSpringZ","linearStiffnessX","linearStiffnessY","linearStiffnessZ"],hh=class extends le{constructor(t,e){super(t,e),this._constraint=null,this._entityA=null,this._entityB=null,this._breakForce=34e37,this._enableCollision=!0,this._linearMotionX=ch,this._linearLimitsX=new B(0,0),this._linearSpringX=!1,this._linearStiffnessX=0,this._linearDampingX=1,this._linearEquilibriumX=0,this._linearMotionY=ch,this._linearLimitsY=new B(0,0),this._linearSpringY=!1,this._linearStiffnessY=0,this._linearDampingY=1,this._linearEquilibriumY=0,this._linearMotionZ=ch,this._linearLimitsZ=new B(0,0),this._linearSpringZ=!1,this._linearStiffnessZ=0,this._linearDampingZ=1,this._linearEquilibriumZ=0,this._angularMotionX=ch,this._angularLimitsX=new B(0,0),this._angularSpringX=!1,this._angularStiffnessX=0,this._angularDampingX=1,this._angularEquilibriumX=0,this._angularMotionY=ch,this._angularLimitsY=new B(0,0),this._angularSpringY=!1,this._angularStiffnessY=0,this._angularDampingY=1,this._angularEquilibriumY=0,this._angularMotionZ=ch,this._angularLimitsZ=new B(0,0),this._angularSpringZ=!1,this._angularEquilibriumZ=0,this._angularDampingZ=1,this._angularStiffnessZ=0,this.on("set_enabled",this._onSetEnabled,this)}set entityA(t){this._destroyConstraint(),this._entityA=t,this._createConstraint()}get entityA(){return this._entityA}set entityB(t){this._destroyConstraint(),this._entityB=t,this._createConstraint()}get entityB(){return this._entityB}set breakForce(t){this._constraint&&this._breakForce!==t&&(this._constraint.setBreakingImpulseThreshold(t),this._breakForce=t)}get breakForce(){return this._breakForce}set enableCollision(t){this._destroyConstraint(),this._enableCollision=t,this._createConstraint()}get enableCollision(){return this._enableCollision}set angularLimitsX(t){this._angularLimitsX.equals(t)||(this._angularLimitsX.copy(t),this._updateAngularLimits())}get angularLimitsX(){return this._angularLimitsX}set angularMotionX(t){this._angularMotionX!==t&&(this._angularMotionX=t,this._updateAngularLimits())}get angularMotionX(){return this._angularMotionX}set angularLimitsY(t){this._angularLimitsY.equals(t)||(this._angularLimitsY.copy(t),this._updateAngularLimits())}get angularLimitsY(){return this._angularLimitsY}set angularMotionY(t){this._angularMotionY!==t&&(this._angularMotionY=t,this._updateAngularLimits())}get angularMotionY(){return this._angularMotionY}set angularLimitsZ(t){this._angularLimitsZ.equals(t)||(this._angularLimitsZ.copy(t),this._updateAngularLimits())}get angularLimitsZ(){return this._angularLimitsZ}set angularMotionZ(t){this._angularMotionZ!==t&&(this._angularMotionZ=t,this._updateAngularLimits())}get angularMotionZ(){return this._angularMotionZ}set linearLimitsX(t){this._linearLimitsX.equals(t)||(this._linearLimitsX.copy(t),this._updateLinearLimits())}get linearLimitsX(){return this._linearLimitsX}set linearMotionX(t){this._linearMotionX!==t&&(this._linearMotionX=t,this._updateLinearLimits())}get linearMotionX(){return this._linearMotionX}set linearLimitsY(t){this._linearLimitsY.equals(t)||(this._linearLimitsY.copy(t),this._updateLinearLimits())}get linearLimitsY(){return this._linearLimitsY}set linearMotionY(t){this._linearMotionY!==t&&(this._linearMotionY=t,this._updateLinearLimits())}get linearMotionY(){return this._linearMotionY}set linearLimitsZ(t){this._linearLimitsZ.equals(t)||(this._linearLimitsZ.copy(t),this._updateLinearLimits())}get linearLimitsZ(){return this._linearLimitsZ}set linearMotionZ(t){this._linearMotionZ!==t&&(this._linearMotionZ=t,this._updateLinearLimits())}get linearMotionZ(){return this._linearMotionZ}_convertTransform(t,e){let s=t.getTranslation(),i=new $;i.setFromMat4(t);let r=new Ammo.btVector3(s.x,s.y,s.z),a=new Ammo.btQuaternion(i.x,i.y,i.z,i.w);e.setOrigin(r),e.setRotation(a),Ammo.destroy(r),Ammo.destroy(a)}_updateAngularLimits(){let t=this._constraint;if(t){let e,s,i,r,a,o;this._angularMotionX===lh?(e=this._angularLimitsX.x*R.DEG_TO_RAD,r=this._angularLimitsX.y*R.DEG_TO_RAD):this._angularMotionX===nh?(e=1,r=0):e=r=0,this._angularMotionY===lh?(s=this._angularLimitsY.x*R.DEG_TO_RAD,a=this._angularLimitsY.y*R.DEG_TO_RAD):this._angularMotionY===nh?(s=1,a=0):s=a=0,this._angularMotionZ===lh?(i=this._angularLimitsZ.x*R.DEG_TO_RAD,o=this._angularLimitsZ.y*R.DEG_TO_RAD):this._angularMotionZ===nh?(i=1,o=0):i=o=0;let l=new Ammo.btVector3(e,s,i);t.setAngularLowerLimit(l),l.setValue(r,a,o),t.setAngularUpperLimit(l),Ammo.destroy(l)}}_updateLinearLimits(){let t=this._constraint;if(t){let e,s,i,r,a,o;this._linearMotionX===lh?(e=this._linearLimitsX.x,r=this._linearLimitsX.y):this._linearMotionX===nh?(e=1,r=0):e=r=0,this._linearMotionY===lh?(s=this._linearLimitsY.x,a=this._linearLimitsY.y):this._linearMotionY===nh?(s=1,a=0):s=a=0,this._linearMotionZ===lh?(i=this._linearLimitsZ.x,o=this._linearLimitsZ.y):this._linearMotionZ===nh?(i=1,o=0):i=o=0;let l=new Ammo.btVector3(e,s,i);t.setLinearLowerLimit(l),l.setValue(r,a,o),t.setLinearUpperLimit(l),Ammo.destroy(l)}}_createConstraint(){if(this._entityA&&this._entityA.rigidbody){this._destroyConstraint();let t=new W,e=this._entityA.rigidbody.body;e.activate();let s=this.entity.getWorldTransform(),r=this._entityA.getWorldTransform().clone().invert();t.mul2(r,s);let a=new Ammo.btTransform;if(this._convertTransform(t,a),this._entityB&&this._entityB.rigidbody){let f=this._entityB.rigidbody.body;f.activate();let d=this._entityB.getWorldTransform().clone().invert();t.mul2(d,s);let p=new Ammo.btTransform;this._convertTransform(t,p),this._constraint=new Ammo.btGeneric6DofSpringConstraint(e,f,a,p,!this._enableCollision),Ammo.destroy(p)}else this._constraint=new Ammo.btGeneric6DofSpringConstraint(e,a,!this._enableCollision);Ammo.destroy(a);let o=["X","Y","Z","X","Y","Z"];for(let f=0;f<6;f++){let u=f<3?"_linear":"_angular";this._constraint.enableSpring(f,this[`${u}Spring${o[f]}`]),this._constraint.setDamping(f,this[`${u}Damping${o[f]}`]),this._constraint.setEquilibriumPoint(f,this[`${u}Equilibrium${o[f]}`]),this._constraint.setStiffness(f,this[`${u}Stiffness${o[f]}`])}this._constraint.setBreakingImpulseThreshold(this._breakForce),this._updateLinearLimits(),this._updateAngularLimits(),this.system.app.systems.rigidbody.dynamicsWorld.addConstraint(this._constraint,!this._enableCollision)}}_destroyConstraint(){this._constraint&&(this.system.app.systems.rigidbody.dynamicsWorld.removeConstraint(this._constraint),Ammo.destroy(this._constraint),this._constraint=null)}initFromData(t){for(let e of $8)t.hasOwnProperty(e)&&(t[e]instanceof B?this[`_${e}`].copy(t[e]):this[`_${e}`]=t[e]);this._createConstraint()}onEnable(){this._createConstraint()}onDisable(){this._destroyConstraint()}_onSetEnabled(t,e,s){}_onBeforeRemove(){this.fire("remove")}},Z8={Damping:"setDamping",Equilibrium:"setEquilibriumPoint",Spring:"enableSpring",Stiffness:"setStiffness"};["linear","angular"].forEach(c=>{["Damping","Equilibrium","Spring","Stiffness"].forEach(t=>{["X","Y","Z"].forEach(e=>{let s=c+t+e,i=`_${s}`,r=c==="linear"?0:3;e==="Y"&&(r+=1),e==="Z"&&(r+=2),Object.defineProperty(hh.prototype,s,{get:function(){return this[i]},set:function(a){this[i]!==a&&(this[i]=a,this._constraint[Z8[t]](r,a))}})})})});var U0=class{constructor(){n(this,"enabled",!0)}};var SR=["enabled"],Gm=class extends Fe{constructor(t){super(t),this.id="joint",this.app=t,this.ComponentType=hh,this.DataType=U0,this.schema=SR}initializeComponentData(t,e,s){t.initFromData(e),super.initializeComponentData(t,e,SR)}};le._buildAccessors(hh.prototype,SR);var Tu=class extends le{constructor(){super(...arguments);n(this,"_minWidth",0);n(this,"_minHeight",0);n(this,"_maxWidth",null);n(this,"_maxHeight",null);n(this,"_fitWidthProportion",0);n(this,"_fitHeightProportion",0);n(this,"_excludeFromLayout",!1)}set minWidth(e){e!==this._minWidth&&(this._minWidth=e,this.fire("resize"))}get minWidth(){return this._minWidth}set minHeight(e){e!==this._minHeight&&(this._minHeight=e,this.fire("resize"))}get minHeight(){return this._minHeight}set maxWidth(e){e!==this._maxWidth&&(this._maxWidth=e,this.fire("resize"))}get maxWidth(){return this._maxWidth}set maxHeight(e){e!==this._maxHeight&&(this._maxHeight=e,this.fire("resize"))}get maxHeight(){return this._maxHeight}set fitWidthProportion(e){e!==this._fitWidthProportion&&(this._fitWidthProportion=e,this.fire("resize"))}get fitWidthProportion(){return this._fitWidthProportion}set fitHeightProportion(e){e!==this._fitHeightProportion&&(this._fitHeightProportion=e,this.fire("resize"))}get fitHeightProportion(){return this._fitHeightProportion}set excludeFromLayout(e){e!==this._excludeFromLayout&&(this._excludeFromLayout=e,this.fire("resize"))}get excludeFromLayout(){return this._excludeFromLayout}};var k0=class{constructor(){n(this,"enabled",!0)}};var bB=["enabled"],Vm=class extends Fe{constructor(t){super(t),this.id="layoutchild",this.ComponentType=Tu,this.DataType=k0,this.schema=bB}initializeComponentData(t,e,s){e.enabled!==void 0&&(t.enabled=e.enabled),e.minWidth!==void 0&&(t.minWidth=e.minWidth),e.minHeight!==void 0&&(t.minHeight=e.minHeight),e.maxWidth!==void 0&&(t.maxWidth=e.maxWidth),e.maxHeight!==void 0&&(t.maxHeight=e.maxHeight),e.fitWidthProportion!==void 0&&(t.fitWidthProportion=e.fitWidthProportion),e.fitHeightProportion!==void 0&&(t.fitHeightProportion=e.fitHeightProportion),e.excludeFromLayout!==void 0&&(t.excludeFromLayout=e.excludeFromLayout),super.initializeComponentData(t,e,s)}cloneComponent(t,e){let s=t.layoutchild;return this.addComponent(e,{enabled:s.enabled,minWidth:s.minWidth,minHeight:s.minHeight,maxWidth:s.maxWidth,maxHeight:s.maxHeight,fitWidthProportion:s.fitWidthProportion,fitHeightProportion:s.fitHeightProportion,excludeFromLayout:s.excludeFromLayout})}};le._buildAccessors(Tu.prototype,bB);var xR=0,Q8=1,DB=2,J8=3;var z0={};z0[Ge]={axis:"x",size:"width",calculatedSize:"calculatedWidth",minSize:"minWidth",maxSize:"maxWidth",fitting:"widthFitting",fittingProportion:"fitWidthProportion"};z0[dt]={axis:"y",size:"height",calculatedSize:"calculatedHeight",minSize:"minHeight",maxSize:"maxHeight",fitting:"heightFitting",fittingProportion:"fitHeightProportion"};var vR={};vR[Ge]=dt;vR[dt]=Ge;var eK={minWidth:0,minHeight:0,maxWidth:Number.POSITIVE_INFINITY,maxHeight:Number.POSITIVE_INFINITY,width:null,height:null,fitWidthProportion:0,fitHeightProportion:0},Rr={NONE:"NONE",APPLY_STRETCHING:"APPLY_STRETCHING",APPLY_SHRINKING:"APPLY_SHRINKING"},br=new B;function LB(c){let t,e=z0[c],s=z0[vR[c]];function i(b,N){return-N[e.size]*b.pivot[e.axis]}function r(b,N){return-N[s.size]*b.pivot[s.axis]}function a(b,N){return N[e.size]*(1-b.pivot[e.axis])}function o(b,N){return N[s.size]*(1-b.pivot[s.axis])}function l(b,N){b=b.filter(h),t=N,br.x=t.containerSize.x-t.padding.x-t.padding.z,br.y=t.containerSize.y-t.padding.y-t.padding.w,f(b);let k=d(u(b)),z=m(k,p(k)),V=v(k,z);return E(k,z,V),y(k,z,V),P(k)}function h(b){let N=b.entity.layoutchild;return!N||!N.enabled||!N.excludeFromLayout}function f(b){for(let N=0;N0&&(z+=t.spacing[e.axis]);let re=k[q][e.size];z+=re,!V&&z>br[e.axis]&&N[N.length-1].length!==0&&(z=re,N.push([])),N[N.length-1].push(b[q]),V&&z>br[e.axis]&&q!==b.length-1&&(z=0,N.push([]))}return N}function d(b){let N=t.orientation===Ge&&t.reverseX||t.orientation===dt&&t.reverseY,k=t.orientation===Ge&&t.reverseY||t.orientation===dt&&t.reverseX;if(N)for(let z=0;zte.largestSize[s.size]&&(te.largestElement=te[j],te.largestSize=oe)}k.push(te.largestElement),z.push(te.largestSize)}let V=S(z,s),q=_(t[s.fitting],V,br[s.axis]);q===Rr.APPLY_STRETCHING?g(z,V,s):q===Rr.APPLY_SHRINKING&&T(z,V,s);for(let re=0;re=k?Rr.APPLY_SHRINKING:Rr.NONE;case 3:return Nk+z[N],0)}function O(b,N){let k=D(b,N),z=[],V=b.length;if(k===0)for(let q=0;qk?V[N]-z[N]:z[N]-V[N]).map(U)}function H(b,N){b.index=N}function U(b){return b.index}function L(b,N){let k=[];k[N[b.length-1]]=b[N[b.length-1]];for(let z=b.length-2;z>=0;--z)k[N[z]]=k[N[z+1]]+b[N[z]];return k}return l}var TR={};TR[Ge]=LB(Ge);TR[dt]=LB(dt);var Hm=class{calculateLayout(t,e){let s=TR[e.orientation];if(s)return s(t,e);throw new Error(`Unrecognized orientation value: ${e.orientation}`)}};function MB(c){return c.element}function tK(c){return c.enabled&&c.element&&c.element.enabled}var yu=class extends le{constructor(e,s){super(e,s);n(this,"_orientation",Ge);n(this,"_reverseX",!1);n(this,"_reverseY",!0);n(this,"_alignment",new B(0,1));n(this,"_padding",new Q);n(this,"_spacing",new B);n(this,"_widthFitting",0);n(this,"_heightFitting",0);n(this,"_wrap",!1);n(this,"_layoutCalculator",new Hm);this._listenForReflowEvents(this.entity,"on"),this.entity.children.forEach(i=>{this._listenForReflowEvents(i,"on")}),this.entity.on("childinsert",this._onChildInsert,this),this.entity.on("childremove",this._onChildRemove,this),e.app.systems.element.on("add",this._onElementOrLayoutComponentAdd,this),e.app.systems.element.on("beforeremove",this._onElementOrLayoutComponentRemove,this),e.app.systems.layoutchild.on("add",this._onElementOrLayoutComponentAdd,this),e.app.systems.layoutchild.on("beforeremove",this._onElementOrLayoutComponentRemove,this)}set orientation(e){e!==this._orientation&&(this._orientation=e,this._scheduleReflow())}get orientation(){return this._orientation}set reverseX(e){e!==this._reverseX&&(this._reverseX=e,this._scheduleReflow())}get reverseX(){return this._reverseX}set reverseY(e){e!==this._reverseY&&(this._reverseY=e,this._scheduleReflow())}get reverseY(){return this._reverseY}set alignment(e){e.equals(this._alignment)||(this._alignment.copy(e),this._scheduleReflow())}get alignment(){return this._alignment}set padding(e){e.equals(this._padding)||(this._padding.copy(e),this._scheduleReflow())}get padding(){return this._padding}set spacing(e){e.equals(this._spacing)||(this._spacing.copy(e),this._scheduleReflow())}get spacing(){return this._spacing}set widthFitting(e){e!==this._widthFitting&&(this._widthFitting=e,this._scheduleReflow())}get widthFitting(){return this._widthFitting}set heightFitting(e){e!==this._heightFitting&&(this._heightFitting=e,this._scheduleReflow())}get heightFitting(){return this._heightFitting}set wrap(e){e!==this._wrap&&(this._wrap=e,this._scheduleReflow())}get wrap(){return this._wrap}_isSelfOrChild(e){return e===this.entity||this.entity.children.indexOf(e)!==-1}_listenForReflowEvents(e,s){e.element&&(e.element[s]("enableelement",this._scheduleReflow,this),e.element[s]("disableelement",this._scheduleReflow,this),e.element[s]("resize",this._scheduleReflow,this),e.element[s]("set:pivot",this._scheduleReflow,this)),e.layoutchild&&(e.layoutchild[s]("set_enabled",this._scheduleReflow,this),e.layoutchild[s]("resize",this._scheduleReflow,this))}_onElementOrLayoutComponentAdd(e){this._isSelfOrChild(e)&&(this._listenForReflowEvents(e,"on"),this._scheduleReflow())}_onElementOrLayoutComponentRemove(e){this._isSelfOrChild(e)&&(this._listenForReflowEvents(e,"off"),this._scheduleReflow())}_onChildInsert(e){this._listenForReflowEvents(e,"on"),this._scheduleReflow()}_onChildRemove(e){this._listenForReflowEvents(e,"off"),this._scheduleReflow()}_scheduleReflow(){this.enabled&&this.entity&&this.entity.enabled&&!this._isPerformingReflow&&this.system.scheduleReflow(this)}reflow(){let e=MB(this.entity),s=this.entity.children.filter(tK).map(MB);if(!e||s.length===0)return;let i=Math.max(e.calculatedWidth,0),r=Math.max(e.calculatedHeight,0),a={orientation:this._orientation,reverseX:this._reverseX,reverseY:this._reverseY,alignment:this._alignment,padding:this._padding,spacing:this._spacing,widthFitting:this._widthFitting,heightFitting:this._heightFitting,wrap:this._wrap,containerSize:new B(i,r)};this._isPerformingReflow=!0;let o=this._layoutCalculator.calculateLayout(s,a);this._isPerformingReflow=!1,this.fire("reflow",o)}onEnable(){this._scheduleReflow()}onRemove(){this.entity.off("childinsert",this._onChildInsert,this),this.entity.off("childremove",this._onChildRemove,this),this._listenForReflowEvents(this.entity,"off"),this.entity.children.forEach(e=>{this._listenForReflowEvents(e,"off")}),this.system.app.systems.element.off("add",this._onElementOrLayoutComponentAdd,this),this.system.app.systems.element.off("beforeremove",this._onElementOrLayoutComponentRemove,this),this.system.app.systems.layoutchild.off("add",this._onElementOrLayoutComponentAdd,this),this.system.app.systems.layoutchild.off("beforeremove",this._onElementOrLayoutComponentRemove,this)}};var G0=class{constructor(){n(this,"enabled",!0)}};var OB=["enabled"],sK=100,Wm=class extends Fe{constructor(t){super(t),this.id="layoutgroup",this.ComponentType=yu,this.DataType=G0,this.schema=OB,this._reflowQueue=[],this.on("beforeremove",this._onRemoveComponent,this),this.app.systems.on("postUpdate",this._onPostUpdate,this)}initializeComponentData(t,e,s){e.enabled!==void 0&&(t.enabled=e.enabled),e.orientation!==void 0&&(t.orientation=e.orientation),e.reverseX!==void 0&&(t.reverseX=e.reverseX),e.reverseY!==void 0&&(t.reverseY=e.reverseY),e.alignment!==void 0&&(t.alignment=Array.isArray(e.alignment)?new B(e.alignment):e.alignment),e.padding!==void 0&&(t.padding=Array.isArray(e.padding)?new Q(e.padding):e.padding),e.spacing!==void 0&&(t.spacing=Array.isArray(e.spacing)?new B(e.spacing):e.spacing),e.widthFitting!==void 0&&(t.widthFitting=e.widthFitting),e.heightFitting!==void 0&&(t.heightFitting=e.heightFitting),e.wrap!==void 0&&(t.wrap=e.wrap),super.initializeComponentData(t,e,s)}cloneComponent(t,e){let s=t.layoutgroup;return this.addComponent(e,{enabled:s.enabled,orientation:s.orientation,reverseX:s.reverseX,reverseY:s.reverseY,alignment:s.alignment,padding:s.padding,spacing:s.spacing,widthFitting:s.widthFitting,heightFitting:s.heightFitting,wrap:s.wrap})}scheduleReflow(t){this._reflowQueue.indexOf(t)===-1&&this._reflowQueue.push(t)}_onPostUpdate(){this._processReflowQueue()}_processReflowQueue(){if(this._reflowQueue.length===0)return;let t=0;for(;this._reflowQueue.length>0;){let e=this._reflowQueue.slice();this._reflowQueue.length=0,e.sort((s,i)=>s.entity.graphDepth-i.entity.graphDepth);for(let s=0;s=sK)break}}_onRemoveComponent(t,e){e.onRemove()}destroy(){super.destroy(),this.app.systems.off("postUpdate",this._onPostUpdate,this)}};le._buildAccessors(yu.prototype,OB);var yR=class{constructor(){n(this,"map",new Map)}destroy(t){this.map.forEach(e=>e.mesh.destroy())}},iK=new et,V0=(c,t)=>{let e=iK.get(c,()=>new yR),s=e.map.get(t);if(!s){let i,r;switch(t){case"box":i=_e.fromGeometry(c,new ci),r={x:2,y:2,z:2,uv:2/3};break;case"capsule":i=_e.fromGeometry(c,new Yc({radius:.5,height:2})),r={x:Math.PI*2,y:Math.PI,z:Math.PI*2,uv:1/3+1/3/3*2};break;case"cone":i=_e.fromGeometry(c,new qa({baseRadius:.5,peakRadius:0,height:1})),r={x:2.54,y:2.54,z:2.54,uv:1/3+1/3/3};break;case"cylinder":i=_e.fromGeometry(c,new Ci({radius:.5,height:1})),r={x:Math.PI,y:.79*2,z:Math.PI,uv:1/3+1/3/3*2};break;case"plane":i=_e.fromGeometry(c,new $a({halfExtents:new B(.5,.5),widthSegments:1,lengthSegments:1})),r={x:0,y:1,z:0,uv:1};break;case"sphere":i=_e.fromGeometry(c,new wr({radius:.5})),r={x:Math.PI,y:Math.PI,z:Math.PI,uv:1};break;case"torus":i=_e.fromGeometry(c,new Za({tubeRadius:.2,ringRadius:.3})),r={x:Math.PI*.5*.5-Math.PI*.1*.1,y:.4,z:.4,uv:1};break;default:throw new Error(`Invalid primitive type: ${t}`)}i.incRefCount(),s={mesh:i,area:r},e.map.set(t,s)}return s};var Tl=class extends le{constructor(e,s){super(e,s);n(this,"_type","asset");n(this,"_asset",null);n(this,"_model",null);n(this,"_mapping",{});n(this,"_castShadows",!0);n(this,"_receiveShadows",!0);n(this,"_materialAsset",null);n(this,"_material");n(this,"_castShadowsLightmap",!0);n(this,"_lightmapped",!1);n(this,"_lightmapSizeMultiplier",1);n(this,"isStatic",!1);n(this,"_layers",[Os]);n(this,"_batchGroupId",-1);n(this,"_customAabb",null);n(this,"_area",null);n(this,"_materialEvents",null);n(this,"_clonedModel",!1);n(this,"_evtLayersChanged",null);n(this,"_evtLayerAdded",null);n(this,"_evtLayerRemoved",null);this._material=e.defaultMaterial,s.on("remove",this.onRemoveChild,this),s.on("removehierarchy",this.onRemoveChild,this),s.on("insert",this.onInsertChild,this),s.on("inserthierarchy",this.onInsertChild,this)}set meshInstances(e){this._model&&(this._model.meshInstances=e)}get meshInstances(){return this._model?this._model.meshInstances:null}set customAabb(e){if(this._customAabb=e,this._model){let s=this._model.meshInstances;if(s)for(let i=0;i=0&&this.system.app.batcher?.remove(pt.MODEL,this.batchGroupId,this.entity),this.entity.enabled&&e>=0&&this.system.app.batcher?.insert(pt.MODEL,e,this.entity),e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&this.addModelToLayers(),this._batchGroupId=e)}get batchGroupId(){return this._batchGroupId}set materialAsset(e){let s=e;e instanceof ae&&(s=e.id);let i=this.system.app.assets;if(s!==this._materialAsset){if(this._materialAsset){i.off(`add:${this._materialAsset}`,this._onMaterialAssetAdd,this);let r=i.get(this._materialAsset);r&&this._unbindMaterialAsset(r)}if(this._materialAsset=s,this._materialAsset){let r=i.get(this._materialAsset);r?this._bindMaterialAsset(r):(this._setMaterial(this.system.defaultMaterial),i.on(`add:${this._materialAsset}`,this._onMaterialAssetAdd,this))}else this._setMaterial(this.system.defaultMaterial)}}get materialAsset(){return this._materialAsset}set material(e){this._material!==e&&(this.materialAsset=null,this._setMaterial(e))}get material(){return this._material}set mapping(e){if(this._type!=="asset"||(this._unsetMaterialEvents(),e||(e={}),this._mapping=e,!this._model))return;let s=this._model.meshInstances,i=this.asset?this.system.app.assets.get(this.asset):null,r=i?i.data.mapping:null,a=null;for(let o=0,l=s.length;o=0&&e.batcher?.insert(pt.MODEL,this.batchGroupId,this.entity)}onDisable(){let e=this.system.app,i=e.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,i&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this._batchGroupId>=0&&e.batcher?.remove(pt.MODEL,this.batchGroupId,this.entity),this._model&&this.removeModelFromLayers()}hide(){if(this._model){let e=this._model.meshInstances;for(let s=0,i=e.length;s{this.on(`set_${i}`,this.onSetSimpleProperty,this)}),aK.forEach(i=>{this.on(`set_${i}`,this.onSetComplexProperty,this)}),oK.forEach(i=>{this.on(`set_${i}`,this.onSetGraphProperty,this)})}set enabled(e){this._setValue("enabled",e)}get enabled(){return this.data.enabled}set autoPlay(e){this._setValue("autoPlay",e)}get autoPlay(){return this.data.autoPlay}set numParticles(e){this._setValue("numParticles",e)}get numParticles(){return this.data.numParticles}set lifetime(e){this._setValue("lifetime",e)}get lifetime(){return this.data.lifetime}set rate(e){this._setValue("rate",e)}get rate(){return this.data.rate}set rate2(e){this._setValue("rate2",e)}get rate2(){return this.data.rate2}set startAngle(e){this._setValue("startAngle",e)}get startAngle(){return this.data.startAngle}set startAngle2(e){this._setValue("startAngle2",e)}get startAngle2(){return this.data.startAngle2}set loop(e){this._setValue("loop",e)}get loop(){return this.data.loop}set preWarm(e){this._setValue("preWarm",e)}get preWarm(){return this.data.preWarm}set lighting(e){this._setValue("lighting",e)}get lighting(){return this.data.lighting}set halfLambert(e){this._setValue("halfLambert",e)}get halfLambert(){return this.data.halfLambert}set intensity(e){this._setValue("intensity",e)}get intensity(){return this.data.intensity}set depthWrite(e){this._setValue("depthWrite",e)}get depthWrite(){return this.data.depthWrite}set noFog(e){this._setValue("noFog",e)}get noFog(){return this.data.noFog}set depthSoftening(e){this._setValue("depthSoftening",e)}get depthSoftening(){return this.data.depthSoftening}set sort(e){this._setValue("sort",e)}get sort(){return this.data.sort}set blendType(e){this._setValue("blendType",e)}get blendType(){return this.data.blendType}set stretch(e){this._setValue("stretch",e)}get stretch(){return this.data.stretch}set alignToMotion(e){this._setValue("alignToMotion",e)}get alignToMotion(){return this.data.alignToMotion}set emitterShape(e){this._setValue("emitterShape",e)}get emitterShape(){return this.data.emitterShape}set emitterExtents(e){this._setValue("emitterExtents",e)}get emitterExtents(){return this.data.emitterExtents}set emitterExtentsInner(e){this._setValue("emitterExtentsInner",e)}get emitterExtentsInner(){return this.data.emitterExtentsInner}set emitterRadius(e){this._setValue("emitterRadius",e)}get emitterRadius(){return this.data.emitterRadius}set emitterRadiusInner(e){this._setValue("emitterRadiusInner",e)}get emitterRadiusInner(){return this.data.emitterRadiusInner}set initialVelocity(e){this._setValue("initialVelocity",e)}get initialVelocity(){return this.data.initialVelocity}set wrap(e){this._setValue("wrap",e)}get wrap(){return this.data.wrap}set wrapBounds(e){this._setValue("wrapBounds",e)}get wrapBounds(){return this.data.wrapBounds}set localSpace(e){this._setValue("localSpace",e)}get localSpace(){return this.data.localSpace}set screenSpace(e){this._setValue("screenSpace",e)}get screenSpace(){return this.data.screenSpace}set colorMapAsset(e){this._setValue("colorMapAsset",e)}get colorMapAsset(){return this.data.colorMapAsset}set normalMapAsset(e){this._setValue("normalMapAsset",e)}get normalMapAsset(){return this.data.normalMapAsset}set mesh(e){this._setValue("mesh",e)}get mesh(){return this.data.mesh}set meshAsset(e){this._setValue("meshAsset",e)}get meshAsset(){return this.data.meshAsset}set renderAsset(e){this._setValue("renderAsset",e)}get renderAsset(){return this.data.renderAsset}set orientation(e){this._setValue("orientation",e)}get orientation(){return this.data.orientation}set particleNormal(e){this._setValue("particleNormal",e)}get particleNormal(){return this.data.particleNormal}set localVelocityGraph(e){this._setValue("localVelocityGraph",e)}get localVelocityGraph(){return this.data.localVelocityGraph}set localVelocityGraph2(e){this._setValue("localVelocityGraph2",e)}get localVelocityGraph2(){return this.data.localVelocityGraph2}set velocityGraph(e){this._setValue("velocityGraph",e)}get velocityGraph(){return this.data.velocityGraph}set velocityGraph2(e){this._setValue("velocityGraph2",e)}get velocityGraph2(){return this.data.velocityGraph2}set rotationSpeedGraph(e){this._setValue("rotationSpeedGraph",e)}get rotationSpeedGraph(){return this.data.rotationSpeedGraph}set rotationSpeedGraph2(e){this._setValue("rotationSpeedGraph2",e)}get rotationSpeedGraph2(){return this.data.rotationSpeedGraph2}set radialSpeedGraph(e){this._setValue("radialSpeedGraph",e)}get radialSpeedGraph(){return this.data.radialSpeedGraph}set radialSpeedGraph2(e){this._setValue("radialSpeedGraph2",e)}get radialSpeedGraph2(){return this.data.radialSpeedGraph2}set scaleGraph(e){this._setValue("scaleGraph",e)}get scaleGraph(){return this.data.scaleGraph}set scaleGraph2(e){this._setValue("scaleGraph2",e)}get scaleGraph2(){return this.data.scaleGraph2}set colorGraph(e){this._setValue("colorGraph",e)}get colorGraph(){return this.data.colorGraph}set colorGraph2(e){this._setValue("colorGraph2",e)}get colorGraph2(){return this.data.colorGraph2}set alphaGraph(e){this._setValue("alphaGraph",e)}get alphaGraph(){return this.data.alphaGraph}set alphaGraph2(e){this._setValue("alphaGraph2",e)}get alphaGraph2(){return this.data.alphaGraph2}set colorMap(e){this._setValue("colorMap",e)}get colorMap(){return this.data.colorMap}set normalMap(e){this._setValue("normalMap",e)}get normalMap(){return this.data.normalMap}set animTilesX(e){this._setValue("animTilesX",e)}get animTilesX(){return this.data.animTilesX}set animTilesY(e){this._setValue("animTilesY",e)}get animTilesY(){return this.data.animTilesY}set animStartFrame(e){this._setValue("animStartFrame",e)}get animStartFrame(){return this.data.animStartFrame}set animNumFrames(e){this._setValue("animNumFrames",e)}get animNumFrames(){return this.data.animNumFrames}set animNumAnimations(e){this._setValue("animNumAnimations",e)}get animNumAnimations(){return this.data.animNumAnimations}set animIndex(e){this._setValue("animIndex",e)}get animIndex(){return this.data.animIndex}set randomizeAnimIndex(e){this._setValue("randomizeAnimIndex",e)}get randomizeAnimIndex(){return this.data.randomizeAnimIndex}set animSpeed(e){this._setValue("animSpeed",e)}get animSpeed(){return this.data.animSpeed}set animLoop(e){this._setValue("animLoop",e)}get animLoop(){return this.data.animLoop}set layers(e){this._setValue("layers",e)}get layers(){return this.data.layers}set drawOrder(e){this._drawOrder=e,this.emitter&&(this.emitter.drawOrder=e)}get drawOrder(){return this._drawOrder}_setValue(e,s){let i=this.data,r=i[e];i[e]=s,this.fire("set",e,r,s)}addMeshInstanceToLayers(){if(this.emitter)for(let e=0;e{this._bindColorMapAsset(o)})}else this.colorMap=null}_bindNormalMapAsset(e){if(e.on("load",this._onNormalMapAssetLoad,this),e.on("unload",this._onNormalMapAssetUnload,this),e.on("remove",this._onNormalMapAssetRemove,this),e.on("change",this._onNormalMapAssetChange,this),e.resource)this._onNormalMapAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}}_unbindNormalMapAsset(e){e.off("load",this._onNormalMapAssetLoad,this),e.off("unload",this._onNormalMapAssetUnload,this),e.off("remove",this._onNormalMapAssetRemove,this),e.off("change",this._onNormalMapAssetChange,this)}_onNormalMapAssetLoad(e){this.normalMap=e.resource}_onNormalMapAssetUnload(e){this.normalMap=null}_onNormalMapAssetRemove(e){this._onNormalMapAssetUnload(e)}_onNormalMapAssetChange(e){}onSetNormalMapAsset(e,s,i){let r=this.system.app.assets;if(s){let a=r.get(s);a&&this._unbindNormalMapAsset(a)}if(i){i instanceof ae&&(this.data.normalMapAsset=i.id,i=i.id);let a=r.get(i);a?this._bindNormalMapAsset(a):r.once(`add:${i}`,o=>{this._bindNormalMapAsset(o)})}else this.normalMap=null}_bindMeshAsset(e){if(e.on("load",this._onMeshAssetLoad,this),e.on("unload",this._onMeshAssetUnload,this),e.on("remove",this._onMeshAssetRemove,this),e.on("change",this._onMeshAssetChange,this),e.resource)this._onMeshAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}}_unbindMeshAsset(e){e.off("load",this._onMeshAssetLoad,this),e.off("unload",this._onMeshAssetUnload,this),e.off("remove",this._onMeshAssetRemove,this),e.off("change",this._onMeshAssetChange,this)}_onMeshAssetLoad(e){this._onMeshChanged(e.resource)}_onMeshAssetUnload(e){this.mesh=null}_onMeshAssetRemove(e){this._onMeshAssetUnload(e)}_onMeshAssetChange(e){}onSetMeshAsset(e,s,i){let r=this.system.app.assets;if(s){let a=r.get(s);a&&this._unbindMeshAsset(a)}if(i){i instanceof ae&&(this.data.meshAsset=i.id,i=i.id);let a=r.get(i);a&&this._bindMeshAsset(a)}else this._onMeshChanged(null)}onSetMesh(e,s,i){!i||i instanceof ae||typeof i=="number"?this.meshAsset=i:this._onMeshChanged(i)}_onMeshChanged(e){e&&!(e instanceof _e)&&(e.meshInstances[0]?e=e.meshInstances[0].mesh:e=null),this.data.mesh=e,this.emitter&&(this.emitter.mesh=e,this.emitter.resetMaterial(),this.rebuild())}onSetRenderAsset(e,s,i){let r=this.system.app.assets;if(s){let a=r.get(s);a&&this._unbindRenderAsset(a)}if(i){i instanceof ae&&(this.data.renderAsset=i.id,i=i.id);let a=r.get(i);a&&this._bindRenderAsset(a)}else this._onRenderChanged(null)}_bindRenderAsset(e){if(e.on("load",this._onRenderAssetLoad,this),e.on("unload",this._onRenderAssetUnload,this),e.on("remove",this._onRenderAssetRemove,this),e.resource)this._onRenderAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}}_unbindRenderAsset(e){e.off("load",this._onRenderAssetLoad,this),e.off("unload",this._onRenderAssetUnload,this),e.off("remove",this._onRenderAssetRemove,this),this._evtSetMeshes?.off(),this._evtSetMeshes=null}_onRenderAssetLoad(e){this._onRenderChanged(e.resource)}_onRenderAssetUnload(e){this._onRenderChanged(null)}_onRenderAssetRemove(e){this._onRenderAssetUnload(e)}_onRenderChanged(e){if(!e){this._onMeshChanged(null);return}this._evtSetMeshes?.off(),this._evtSetMeshes=e.on("set:meshes",this._onRenderSetMeshes,this),e.meshes&&this._onRenderSetMeshes(e.meshes)}_onRenderSetMeshes(e){this._onMeshChanged(e&&e[0])}onSetLoop(e,s,i){this.emitter&&(this.emitter[e]=i,this.emitter.resetTime())}onSetBlendType(e,s,i){this.emitter&&(this.emitter[e]=i,this.emitter.material.blendType=i,this.emitter.resetMaterial(),this.rebuild())}_requestDepth(){this._requestedDepth||(Ym||(Ym=this.system.app.scene.layers.getLayerById(Zt)),Ym&&(Ym.incrementCounter(),this._requestedDepth=!0))}_releaseDepth(){this._requestedDepth&&Ym&&(Ym.decrementCounter(),this._requestedDepth=!1)}onSetDepthSoftening(e,s,i){s!==i&&(i?(this.enabled&&this.entity.enabled&&this._requestDepth(),this.emitter&&(this.emitter[e]=i)):(this.enabled&&this.entity.enabled&&this._releaseDepth(),this.emitter&&(this.emitter[e]=i)),this.emitter&&(this.reset(),this.emitter.resetMaterial(),this.rebuild()))}onSetSimpleProperty(e,s,i){this.emitter&&(this.emitter[e]=i,this.emitter.resetMaterial())}onSetComplexProperty(e,s,i){this.emitter&&(this.emitter[e]=i,this.emitter.resetMaterial(),this.rebuild(),this.reset())}onSetGraphProperty(e,s,i){this.emitter&&(this.emitter[e]=i,this.emitter.rebuildGraphs(),this.emitter.resetMaterial())}onEnable(){let e=this.system.app.scene,s=e.layers,i=this.data;for(let r=0,a=W0.length;r=0)o=this.system.app.assets.get(o);else continue;o&&!o.resource&&this.system.app.assets.load(o)}}if(!this.system.app.graphicsDevice.disableParticleSystem){if(!this.emitter){let r=i.mesh;r instanceof _e||(r=null),this.emitter=new Xp(this.system.app.graphicsDevice,{numParticles:i.numParticles,emitterExtents:i.emitterExtents,emitterExtentsInner:i.emitterExtentsInner,emitterRadius:i.emitterRadius,emitterRadiusInner:i.emitterRadiusInner,emitterShape:i.emitterShape,initialVelocity:i.initialVelocity,wrap:i.wrap,localSpace:i.localSpace,screenSpace:i.screenSpace,wrapBounds:i.wrapBounds,lifetime:i.lifetime,rate:i.rate,rate2:i.rate2,orientation:i.orientation,particleNormal:i.particleNormal,animTilesX:i.animTilesX,animTilesY:i.animTilesY,animStartFrame:i.animStartFrame,animNumFrames:i.animNumFrames,animNumAnimations:i.animNumAnimations,animIndex:i.animIndex,randomizeAnimIndex:i.randomizeAnimIndex,animSpeed:i.animSpeed,animLoop:i.animLoop,startAngle:i.startAngle,startAngle2:i.startAngle2,scaleGraph:i.scaleGraph,scaleGraph2:i.scaleGraph2,colorGraph:i.colorGraph,colorGraph2:i.colorGraph2,alphaGraph:i.alphaGraph,alphaGraph2:i.alphaGraph2,localVelocityGraph:i.localVelocityGraph,localVelocityGraph2:i.localVelocityGraph2,velocityGraph:i.velocityGraph,velocityGraph2:i.velocityGraph2,rotationSpeedGraph:i.rotationSpeedGraph,rotationSpeedGraph2:i.rotationSpeedGraph2,radialSpeedGraph:i.radialSpeedGraph,radialSpeedGraph2:i.radialSpeedGraph2,colorMap:i.colorMap,normalMap:i.normalMap,loop:i.loop,preWarm:i.preWarm,sort:i.sort,stretch:i.stretch,alignToMotion:i.alignToMotion,lighting:i.lighting,halfLambert:i.halfLambert,intensity:i.intensity,depthSoftening:i.depthSoftening,scene:this.system.app.scene,mesh:r,depthWrite:i.depthWrite,noFog:i.noFog,node:this.entity,blendType:i.blendType}),this.emitter.meshInstance.node=this.entity,this.emitter.drawOrder=this.drawOrder,i.autoPlay||(this.pause(),this.emitter.meshInstance.visible=!1)}this.emitter.colorMap&&this.addMeshInstanceToLayers(),this._evtLayersChanged=e.on("set:layers",this.onLayersChanged,this),s&&(this._evtLayerAdded=s.on("add",this.onLayerAdded,this),this._evtLayerRemoved=s.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&i.depthSoftening&&this._requestDepth()}}onDisable(){let s=this.system.app.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,s&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this.emitter&&(this.removeMeshInstanceFromLayers(),this.data.depthSoftening&&this._releaseDepth(),this.emitter.camera=null)}onBeforeRemove(){this.enabled&&(this.enabled=!1),this.emitter&&(this.emitter.destroy(),this.emitter=null);for(let e=0;e 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; var colorMapSampler: sampler; var colorParam: texture_2d; 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, 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, 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, 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; var internalTex0: texture_2d; var internalTex1: texture_2d; var internalTex2: texture_2d; var internalTex3: texture_2d; 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 inPos: vec3f; var inVel: vec3f; var inAngle: f32; var inShow: bool; var inLife: f32; var visMode: f32; var outPos: vec3f; var outVel: vec3f; var outAngle: f32; var outShow: bool; var 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, 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, 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; var internalTex1: texture_2d; var internalTex2: texture_2d; #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 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; var particleTexIN: texture_2d; #ifdef PARTICLE_GPU var internalTex0: texture_2d; var internalTex1: texture_2d; var internalTex2: texture_2d; #endif #ifndef CAMERAPLANES #define CAMERAPLANES uniform camera_params: vec4f; #endif varying texCoordsAlphaLife: vec4f; var inPos: vec3f; var inVel: vec3f; var inAngle: f32; var inShow: bool; var 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(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; #endif #ifdef SOFT varying vDepth: f32; #include "screenDepthPS" #endif #include "gammaPS" #include "tonemappingPS" #include "fogPS" #if NORMAL == MAP var normalMap: texture_2d; 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=h.fixedTimeStep&&(f=Math.floor(h.simTime/h.fixedTimeStep),h.simTime-=f*h.fixedTimeStep),f){f=Math.min(f,h.maxSubSteps);for(let u=0;ua.skin===t);r&&(r.incRefCount(),s=r.skinInstance)}return s}static addCachedSkinInstance(t,e,s){let i=sn._skinInstanceCache.get(e);i||(i=[],sn._skinInstanceCache.set(e,i));let r=i.find(a=>a.skin===t);r||(r=new ER(t,s),i.push(r)),r.incRefCount()}static removeCachedSkinInstance(t){if(t){let e=t.rootBone;if(e){let s=sn._skinInstanceCache.get(e);if(s){let i=s.findIndex(r=>r.skinInstance===t);if(i>=0){let r=s[i];r.decRefCount(),r.refCount===0&&(s.splice(i,1),s.length||sn._skinInstanceCache.delete(e),t&&(t.destroy(),r.skinInstance=null))}}}}}};n(sn,"_skinInstanceCache",new Map);var Eu=sn;var pa=class{constructor(t,e,s,i,r){n(this,"_evtLoadById",null);n(this,"_evtUnloadById",null);n(this,"_evtAddById",null);n(this,"_evtRemoveById",null);n(this,"_evtLoadByUrl",null);n(this,"_evtAddByUrl",null);n(this,"_evtRemoveByUrl",null);this.propertyName=t,this.parent=e,this._scope=r,this._registry=s,this.id=null,this.url=null,this.asset=null,this._onAssetLoad=i.load,this._onAssetAdd=i.add,this._onAssetRemove=i.remove,this._onAssetUnload=i.unload}set id(t){if(this.url)throw Error("Can't set id and url");this._unbind(),this._id=t,this.asset=this._registry.get(this._id),this._bind()}get id(){return this._id}set url(t){if(this.id)throw Error("Can't set id and url");this._unbind(),this._url=t,this.asset=this._registry.getByUrl(this._url),this._bind()}get url(){return this._url}_bind(){this.id&&(this._onAssetLoad&&(this._evtLoadById=this._registry.on(`load:${this.id}`,this._onLoad,this)),this._onAssetAdd&&(this._evtAddById=this._registry.once(`add:${this.id}`,this._onAdd,this)),this._onAssetRemove&&(this._evtRemoveById=this._registry.on(`remove:${this.id}`,this._onRemove,this)),this._onAssetUnload&&(this._evtUnloadById=this._registry.on(`unload:${this.id}`,this._onUnload,this))),this.url&&(this._onAssetLoad&&(this._evtLoadByUrl=this._registry.on(`load:url:${this.url}`,this._onLoad,this)),this._onAssetAdd&&(this._evtAddByUrl=this._registry.once(`add:url:${this.url}`,this._onAdd,this)),this._onAssetRemove&&(this._evtRemoveByUrl=this._registry.on(`remove:url:${this.url}`,this._onRemove,this)))}_unbind(){this.id&&(this._evtLoadById?.off(),this._evtLoadById=null,this._evtAddById?.off(),this._evtAddById=null,this._evtRemoveById?.off(),this._evtRemoveById=null,this._evtUnloadById?.off(),this._evtUnloadById=null),this.url&&(this._evtLoadByUrl?.off(),this._evtLoadByUrl=null,this._evtAddByUrl?.off(),this._evtAddByUrl=null,this._evtRemoveByUrl?.off(),this._evtRemoveByUrl=null)}_onLoad(t){this._onAssetLoad.call(this._scope,this.propertyName,this.parent,t)}_onAdd(t){this.asset=t,this._onAssetAdd.call(this._scope,this.propertyName,this.parent,t)}_onRemove(t){this._onAssetRemove.call(this._scope,this.propertyName,this.parent,t),this.asset=null}_onUnload(t){this._onAssetUnload.call(this._scope,this.propertyName,this.parent,t)}};var Au=class extends le{constructor(e,s){super(e,s);n(this,"_type","asset");n(this,"_castShadows",!0);n(this,"_receiveShadows",!0);n(this,"_castShadowsLightmap",!0);n(this,"_lightmapped",!1);n(this,"_lightmapSizeMultiplier",1);n(this,"isStatic",!1);n(this,"_batchGroupId",-1);n(this,"_layers",[Os]);n(this,"_renderStyle",Oo);n(this,"_meshInstances",[]);n(this,"_customAabb",null);n(this,"_area",null);n(this,"_assetReference");n(this,"_materialReferences",[]);n(this,"_material");n(this,"_rootBone",null);n(this,"_evtLayersChanged",null);n(this,"_evtLayerAdded",null);n(this,"_evtLayerRemoved",null);n(this,"_evtSetMeshes",null);this._assetReference=new pa("asset",this,e.app.assets,{add:this._onRenderAssetAdded,load:this._onRenderAssetLoad,remove:this._onRenderAssetRemove,unload:this._onRenderAssetUnload},this),this._material=e.defaultMaterial,s.on("remove",this.onRemoveChild,this),s.on("removehierarchy",this.onRemoveChild,this),s.on("insert",this.onInsertChild,this),s.on("inserthierarchy",this.onInsertChild,this)}set renderStyle(e){this._renderStyle!==e&&(this._renderStyle=e,we._prepareRenderStyleForArray(this._meshInstances,e))}get renderStyle(){return this._renderStyle}set customAabb(e){this._customAabb=e;let s=this._meshInstances;if(s)for(let i=0;i=0&&this.system.app.batcher?.remove(pt.RENDER,this.batchGroupId,this.entity),this.entity.enabled&&e>=0&&this.system.app.batcher?.insert(pt.RENDER,e,this.entity),e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&this.addToLayers(),this._batchGroupId=e)}get batchGroupId(){return this._batchGroupId}set material(e){if(this._material!==e&&(this._material=e,this._meshInstances&&this._type!=="asset"))for(let s=0;se.length){for(let s=e.length;se.id)}set asset(e){let s=e instanceof ae?e.id:e;this._assetReference.id!==s&&(this._assetReference.asset&&this._assetReference.asset.resource&&this._onRenderAssetRemove(),this._assetReference.id=s,this._assetReference.asset&&this._onRenderAssetAdded())}get asset(){return this._assetReference.id}assignAsset(e){let s=e instanceof ae?e.id:e;this._assetReference.id=s}set rootBone(e){if(this._rootBone!==e){let s=typeof e=="string";if(this._rootBone&&s&&this._rootBone.guid===e)return;this._rootBone&&this._clearSkinInstances(),e instanceof Pe?this._rootBone=e:s?(this._rootBone=this.system.app.getEntityFromIndex(e)||null,this._rootBone):this._rootBone=null,this._rootBone&&this._cloneSkinInstances()}}get rootBone(){return this._rootBone}destroyMeshInstances(){let e=this._meshInstances;if(e){this.removeFromLayers(),this._clearSkinInstances();for(let s=0;s=0&&e.batcher?.insert(pt.RENDER,this.batchGroupId,this.entity)}onDisable(){let e=this.system.app,i=e.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,this._rootBone&&this._clearSkinInstances(),i&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this._batchGroupId>=0&&e.batcher?.remove(pt.RENDER,this.batchGroupId,this.entity),this.removeFromLayers()}hide(){if(this._meshInstances)for(let e=0;eo.mesh);i._onSetMeshes(a);for(let o=0;othis._pool.length)for(let e=this._pool.length;e=this._pool.length&&this._resize(this._pool.length*2),this._pool[this._count++]}freeAll(){this._count=0}};var Dr,at,so,Zm,lK=new $,cK=new $,K0=new x,Js=class extends le{constructor(){super(...arguments);n(this,"_angularDamping",0);n(this,"_angularFactor",new x(1,1,1));n(this,"_angularVelocity",new x);n(this,"_body",null);n(this,"_friction",.5);n(this,"_group",2);n(this,"_linearDamping",0);n(this,"_linearFactor",new x(1,1,1));n(this,"_linearVelocity",new x);n(this,"_mask",65533);n(this,"_mass",1);n(this,"_restitution",0);n(this,"_rollingFriction",0);n(this,"_simulationEnabled",!1);n(this,"_type",Sl)}static onLibraryLoaded(){typeof Ammo<"u"&&(Dr=new Ammo.btTransform,at=new Ammo.btVector3,so=new Ammo.btVector3,Zm=new Ammo.btQuaternion)}static onAppDestroy(){Ammo.destroy(Dr),Ammo.destroy(at),Ammo.destroy(so),Ammo.destroy(Zm),Dr=null,at=null,so=null,Zm=null}set angularDamping(e){this._angularDamping!==e&&(this._angularDamping=e,this._body&&this._body.setDamping(this._linearDamping,e))}get angularDamping(){return this._angularDamping}set angularFactor(e){this._angularFactor.equals(e)||(this._angularFactor.copy(e),this._body&&this._type===Ui&&(at.setValue(e.x,e.y,e.z),this._body.setAngularFactor(at)))}get angularFactor(){return this._angularFactor}set angularVelocity(e){this._body&&this._type===Ui&&(this._body.activate(),at.setValue(e.x,e.y,e.z),this._body.setAngularVelocity(at),this._angularVelocity.copy(e))}get angularVelocity(){if(this._body&&this._type===Ui){let e=this._body.getAngularVelocity();this._angularVelocity.set(e.x(),e.y(),e.z())}return this._angularVelocity}set body(e){this._body!==e&&(this._body=e,e&&this._simulationEnabled&&e.activate())}get body(){return this._body}set friction(e){this._friction!==e&&(this._friction=e,this._body&&this._body.setFriction(e))}get friction(){return this._friction}set group(e){this._group!==e&&(this._group=e,this.enabled&&this.entity.enabled&&(this.disableSimulation(),this.enableSimulation()))}get group(){return this._group}set linearDamping(e){this._linearDamping!==e&&(this._linearDamping=e,this._body&&this._body.setDamping(e,this._angularDamping))}get linearDamping(){return this._linearDamping}set linearFactor(e){this._linearFactor.equals(e)||(this._linearFactor.copy(e),this._body&&this._type===Ui&&(at.setValue(e.x,e.y,e.z),this._body.setLinearFactor(at)))}get linearFactor(){return this._linearFactor}set linearVelocity(e){this._body&&this._type===Ui&&(this._body.activate(),at.setValue(e.x,e.y,e.z),this._body.setLinearVelocity(at),this._linearVelocity.copy(e))}get linearVelocity(){if(this._body&&this._type===Ui){let e=this._body.getLinearVelocity();this._linearVelocity.set(e.x(),e.y(),e.z())}return this._linearVelocity}set mask(e){this._mask!==e&&(this._mask=e,this.enabled&&this.entity.enabled&&(this.disableSimulation(),this.enableSimulation()))}get mask(){return this._mask}set mass(e){if(this._mass!==e&&(this._mass=e,this._body&&this._type===Ui)){let s=this.enabled&&this.entity.enabled;s&&this.disableSimulation(),this._body.getCollisionShape().calculateLocalInertia(e,at),this._body.setMassProps(e,at),this._body.updateInertiaTensor(),s&&this.enableSimulation()}}get mass(){return this._mass}set restitution(e){this._restitution!==e&&(this._restitution=e,this._body&&this._body.setRestitution(e))}get restitution(){return this._restitution}set rollingFriction(e){this._rollingFriction!==e&&(this._rollingFriction=e,this._body&&this._body.setRollingFriction(e))}get rollingFriction(){return this._rollingFriction}set type(e){if(this._type!==e){switch(this._type=e,this.disableSimulation(),e){case Ui:this._group=1,this._mask=65535;break;case tn:this._group=4,this._mask=65535;break;case Sl:default:this._group=2,this._mask=65533;break}this.createBody()}}get type(){return this._type}createBody(){let e=this.entity,s;if(e.collision&&(s=e.collision.shape,e.trigger&&(e.trigger.destroy(),delete e.trigger)),s){this._body&&(this.system.removeBody(this._body),this.system.destroyBody(this._body),this._body=null);let i=this._type===Ui?this._mass:0;this._getEntityTransform(Dr);let r=this.system.createBody(i,s,Dr);if(r.setRestitution(this._restitution),r.setFriction(this._friction),r.setRollingFriction(this._rollingFriction),r.setDamping(this._linearDamping,this._angularDamping),this._type===Ui){let a=this._linearFactor;at.setValue(a.x,a.y,a.z),r.setLinearFactor(at);let o=this._angularFactor;at.setValue(o.x,o.y,o.z),r.setAngularFactor(at)}else this._type===tn&&(r.setCollisionFlags(r.getCollisionFlags()|2),r.setActivationState(4));r.entity=e,this.body=r,this.enabled&&e.enabled&&this.enableSimulation()}}isActive(){return this._body?this._body.isActive():!1}activate(){this._body&&this._body.activate()}enableSimulation(){let e=this.entity;if(e.collision&&e.collision.enabled&&!this._simulationEnabled){let s=this._body;if(s){switch(this.system.addBody(s,this._group,this._mask),this._type){case Ui:this.system._dynamic.push(this),s.forceActivationState(1),this.syncEntityToBody();break;case tn:this.system._kinematic.push(this),s.forceActivationState(4);break;case Sl:s.forceActivationState(1),this.syncEntityToBody();break}e.collision.type==="compound"&&this.system._compounds.push(e.collision),s.activate(),this._simulationEnabled=!0}}}disableSimulation(){let e=this._body;if(e&&this._simulationEnabled){let s=this.system,i=s._compounds.indexOf(this.entity.collision);i>-1&&s._compounds.splice(i,1),i=s._dynamic.indexOf(this),i>-1&&s._dynamic.splice(i,1),i=s._kinematic.indexOf(this),i>-1&&s._kinematic.splice(i,1),s.removeBody(e),e.forceActivationState(5),this._simulationEnabled=!1}}applyForce(e,s,i,r,a,o){let l=this._body;l&&(l.activate(),e instanceof x?at.setValue(e.x,e.y,e.z):at.setValue(e,s,i),s instanceof x?so.setValue(s.x,s.y,s.z):r!==void 0?so.setValue(r,a,o):so.setValue(0,0,0),l.applyForce(at,so))}applyTorque(e,s,i){let r=this._body;r&&(r.activate(),e instanceof x?at.setValue(e.x,e.y,e.z):at.setValue(e,s,i),r.applyTorque(at))}applyImpulse(e,s,i,r,a,o){let l=this._body;l&&(l.activate(),e instanceof x?at.setValue(e.x,e.y,e.z):at.setValue(e,s,i),s instanceof x?so.setValue(s.x,s.y,s.z):r!==void 0?so.setValue(r,a,o):so.setValue(0,0,0),l.applyImpulse(at,so))}applyTorqueImpulse(e,s,i){let r=this._body;r&&(r.activate(),e instanceof x?at.setValue(e.x,e.y,e.z):at.setValue(e,s,i),r.applyTorqueImpulse(at))}isStatic(){return this._type===Sl}isStaticOrKinematic(){return this._type===Sl||this._type===tn}isKinematic(){return this._type===tn}_getEntityTransform(e){let s=this.entity,i=s.collision;if(i){let r=i.getShapePosition(),a=i.getShapeRotation();at.setValue(r.x,r.y,r.z),Zm.setValue(a.x,a.y,a.z,a.w)}else{let r=s.getPosition(),a=s.getRotation();at.setValue(r.x,r.y,r.z),Zm.setValue(a.x,a.y,a.z,a.w)}e.setOrigin(at),e.setRotation(Zm)}syncEntityToBody(){let e=this._body;if(e){if(this._getEntityTransform(Dr),e.setWorldTransform(Dr),this._type===tn){let s=e.getMotionState();s&&s.setWorldTransform(Dr)}e.activate()}}_updateDynamic(){let e=this._body;if(e.isActive()){let s=e.getMotionState();if(s){let i=this.entity;s.getWorldTransform(Dr);let r=Dr.getOrigin(),a=Dr.getRotation(),o=i.collision;if(o&&o._hasOffset){let l=o.data.linearOffset,h=o.data.angularOffset,f=cK.copy(h).invert(),u=lK.set(a.x(),a.y(),a.z(),a.w()).mul(f);u.transformVector(l,K0),i.setPosition(r.x()-K0.x,r.y()-K0.y,r.z()-K0.z),i.setRotation(u)}else i.setPosition(r.x(),r.y(),r.z()),i.setRotation(a.x(),a.y(),a.z(),a.w())}}}_updateKinematic(){let e=this._body.getMotionState();e&&(this._getEntityTransform(Dr),e.setWorldTransform(Dr))}teleport(e,s,i,r,a,o){e instanceof x?this.entity.setPosition(e):this.entity.setPosition(e,s,i),s instanceof $?this.entity.setRotation(s):s instanceof x?this.entity.setEulerAngles(s):r!==void 0&&this.entity.setEulerAngles(r,a,o),this.syncEntityToBody()}onEnable(){this._body||this.createBody(),this.enableSimulation()}onDisable(){this.disableSimulation()}};n(Js,"EVENT_CONTACT","contact"),n(Js,"EVENT_COLLISIONSTART","collisionstart"),n(Js,"EVENT_COLLISIONEND","collisionend"),n(Js,"EVENT_TRIGGERENTER","triggerenter"),n(Js,"EVENT_TRIGGERLEAVE","triggerleave"),n(Js,"order",-1);var j0=class{constructor(){n(this,"enabled",!0)}};var yl,El,Qm=class{constructor(t,e,s,i){n(this,"entity");n(this,"point");n(this,"normal");n(this,"hitFraction");this.entity=t,this.point=e,this.normal=s,this.hitFraction=i}},YS=class{constructor(t,e,s){n(this,"a");n(this,"b");n(this,"impulse");n(this,"localPointA");n(this,"localPointB");n(this,"pointA");n(this,"pointB");n(this,"normal");arguments.length!==0?(this.a=t,this.b=e,this.impulse=s.impulse,this.localPointA=s.localPoint,this.localPointB=s.localPointOther,this.pointA=s.point,this.pointB=s.pointOther,this.normal=s.normal):(this.a=null,this.b=null,this.impulse=0,this.localPointA=new x,this.localPointB=new x,this.pointA=new x,this.pointB=new x,this.normal=new x)}},KS=class{constructor(t=new x,e=new x,s=new x,i=new x,r=new x,a=0){n(this,"localPoint");n(this,"localPointOther");n(this,"point");n(this,"pointOther");n(this,"normal");n(this,"impulse");this.localPoint=t,this.localPointOther=e,this.point=s,this.pointOther=i,this.normal=r,this.impulse=a}},jS=class{constructor(t,e){n(this,"other");n(this,"contacts");this.other=t,this.contacts=e}},_k=["enabled"],Al=class extends Fe{constructor(e){super(e);n(this,"maxSubSteps",10);n(this,"fixedTimeStep",1/60);n(this,"gravity",new x(0,-9.81,0));n(this,"_gravityFloat32",new Float32Array(3));n(this,"_dynamic",[]);n(this,"_kinematic",[]);n(this,"_triggers",[]);n(this,"_compounds",[]);this.id="rigidbody",this._stats=e.stats.frame,this.ComponentType=Js,this.DataType=j0,this.contactPointPool=null,this.contactResultPool=null,this.singleContactResultPool=null,this.schema=_k,this.collisions={},this.frameCollisions={},this.on("beforeremove",this.onBeforeRemove,this)}onLibraryLoaded(){if(typeof Ammo<"u"){if(this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.overlappingPairCache=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.dynamicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.overlappingPairCache,this.solver,this.collisionConfiguration),this.dynamicsWorld.setInternalTickCallback){let e=Ammo.addFunction(this._checkForCollisions.bind(this),"vif");this.dynamicsWorld.setInternalTickCallback(e)}yl=new Ammo.btVector3,El=new Ammo.btVector3,Js.onLibraryLoaded(),this.contactPointPool=new $m(KS,1),this.contactResultPool=new $m(jS,1),this.singleContactResultPool=new $m(YS,1),this.app.systems.on("update",this.onUpdate,this)}else this.app.systems.off("update",this.onUpdate,this)}initializeComponentData(e,s,i){let r=["mass","linearDamping","angularDamping","linearFactor","angularFactor","friction","rollingFriction","restitution","type","group","mask"];for(let a of r)if(s.hasOwnProperty(a)){let o=s[a];Array.isArray(o)?e[a]=new x(o[0],o[1],o[2]):e[a]=o}super.initializeComponentData(e,s,["enabled"])}cloneComponent(e,s){let i=e.rigidbody,r={enabled:i.enabled,mass:i.mass,linearDamping:i.linearDamping,angularDamping:i.angularDamping,linearFactor:[i.linearFactor.x,i.linearFactor.y,i.linearFactor.z],angularFactor:[i.angularFactor.x,i.angularFactor.y,i.angularFactor.z],friction:i.friction,rollingFriction:i.rollingFriction,restitution:i.restitution,type:i.type,group:i.group,mask:i.mask};return this.addComponent(s,r)}onBeforeRemove(e,s){s.enabled&&(s.enabled=!1),s.body&&(this.destroyBody(s.body),s.body=null)}addBody(e,s,i){s!==void 0&&i!==void 0?this.dynamicsWorld.addRigidBody(e,s,i):this.dynamicsWorld.addRigidBody(e)}removeBody(e){this.dynamicsWorld.removeRigidBody(e)}createBody(e,s,i){let r=new Ammo.btVector3(0,0,0);e!==0&&s.calculateLocalInertia(e,r);let a=new Ammo.btDefaultMotionState(i),o=new Ammo.btRigidBodyConstructionInfo(e,a,s,r),l=new Ammo.btRigidBody(o);return Ammo.destroy(o),Ammo.destroy(r),l}destroyBody(e){let s=e.getMotionState();s&&Ammo.destroy(s),Ammo.destroy(e)}raycastFirst(e,s,i={}){if(i.filterTags||i.filterCallback)return i.sort=!0,this.raycastAll(e,s,i)[0]||null;let r=null;yl.setValue(e.x,e.y,e.z),El.setValue(s.x,s.y,s.z);let a=new Ammo.ClosestRayResultCallback(yl,El);if(typeof i.filterCollisionGroup=="number"&&a.set_m_collisionFilterGroup(i.filterCollisionGroup),typeof i.filterCollisionMask=="number"&&a.set_m_collisionFilterMask(i.filterCollisionMask),this.dynamicsWorld.rayTest(yl,El,a),a.hasHit()){let o=a.get_m_collisionObject(),l=Ammo.castObject(o,Ammo.btRigidBody);if(l){let h=a.get_m_hitPointWorld(),f=a.get_m_hitNormalWorld();r=new Qm(l.entity,new x(h.x(),h.y(),h.z()),new x(f.x(),f.y(),f.z()),a.get_m_closestHitFraction())}}return Ammo.destroy(a),r}raycastAll(e,s,i={}){let r=[];yl.setValue(e.x,e.y,e.z),El.setValue(s.x,s.y,s.z);let a=new Ammo.AllHitsRayResultCallback(yl,El);if(typeof i.filterCollisionGroup=="number"&&a.set_m_collisionFilterGroup(i.filterCollisionGroup),typeof i.filterCollisionMask=="number"&&a.set_m_collisionFilterMask(i.filterCollisionMask),this.dynamicsWorld.rayTest(yl,El,a),a.hasHit()){let o=a.get_m_collisionObjects(),l=a.get_m_hitPointWorld(),h=a.get_m_hitNormalWorld(),f=a.get_m_hitFractions(),u=o.size();for(let d=0;dd.hitFraction-p.hitFraction)}return Ammo.destroy(a),r}_storeCollision(e,s){let i=!1,r=e.guid;return this.collisions[r]=this.collisions[r]||{others:[],entity:e},this.collisions[r].others.indexOf(s)<0&&(this.collisions[r].others.push(s),i=!0),this.frameCollisions[r]=this.frameCollisions[r]||{others:[],entity:e},this.frameCollisions[r].others.push(s),i}_createContactPointFromAmmo(e){let s=e.get_m_localPointA(),i=e.get_m_localPointB(),r=e.getPositionWorldOnA(),a=e.getPositionWorldOnB(),o=e.get_m_normalWorldOnB(),l=this.contactPointPool.allocate();return l.localPoint.set(s.x(),s.y(),s.z()),l.localPointOther.set(i.x(),i.y(),i.z()),l.point.set(r.x(),r.y(),r.z()),l.pointOther.set(a.x(),a.y(),a.z()),l.normal.set(o.x(),o.y(),o.z()),l.impulse=e.getAppliedImpulse(),l}_createReverseContactPointFromAmmo(e){let s=e.get_m_localPointA(),i=e.get_m_localPointB(),r=e.getPositionWorldOnA(),a=e.getPositionWorldOnB(),o=e.get_m_normalWorldOnB(),l=this.contactPointPool.allocate();return l.localPointOther.set(s.x(),s.y(),s.z()),l.localPoint.set(i.x(),i.y(),i.z()),l.pointOther.set(r.x(),r.y(),r.z()),l.point.set(a.x(),a.y(),a.z()),l.normal.set(o.x(),o.y(),o.z()),l.impulse=e.getAppliedImpulse(),l}_createSingleContactResult(e,s,i){let r=this.singleContactResultPool.allocate();return r.a=e,r.b=s,r.localPointA=i.localPoint,r.localPointB=i.localPointOther,r.pointA=i.point,r.pointB=i.pointOther,r.normal=i.normal,r.impulse=i.impulse,r}_createContactResult(e,s){let i=this.contactResultPool.allocate();return i.other=e,i.contacts=s,i}_cleanOldCollisions(){for(let e in this.collisions)if(this.collisions.hasOwnProperty(e)){let s=this.frameCollisions[e],i=this.collisions[e],r=i.entity,a=r.collision,o=r.rigidbody,l=i.others,f=l.length;for(;f--;){let u=l[f];(!s||s.others.indexOf(u)<0)&&(l.splice(f,1),r.trigger?(a&&a.fire("triggerleave",u),u.rigidbody&&u.rigidbody.fire("triggerleave",r)):u.trigger||(o&&o.fire("collisionend",u),a&&a.fire("collisionend",u)))}l.length===0&&delete this.collisions[e]}}_hasContactEvent(e){let s=e.collision;if(s&&(s.hasEvent("collisionstart")||s.hasEvent("collisionend")||s.hasEvent("contact")))return!0;let i=e.rigidbody;return i&&(i.hasEvent("collisionstart")||i.hasEvent("collisionend")||i.hasEvent("contact"))}_checkForCollisions(e,s){let r=Ammo.wrapPointer(e,Ammo.btDynamicsWorld).getDispatcher(),a=r.getNumManifolds();this.frameCollisions={};for(let o=0;o0)if(_&4||S&4){let E=p.collision&&(p.collision.hasEvent("triggerenter")||p.collision.hasEvent("triggerleave")),y=m.collision&&(m.collision.hasEvent("triggerenter")||m.collision.hasEvent("triggerleave")),P=p.rigidbody&&(p.rigidbody.hasEvent("triggerenter")||p.rigidbody.hasEvent("triggerleave")),A=m.rigidbody&&(m.rigidbody.hasEvent("triggerenter")||m.rigidbody.hasEvent("triggerleave"));E&&(v=this._storeCollision(p,m),v&&!(S&4)&&p.collision.fire("triggerenter",m)),y&&(v=this._storeCollision(m,p),v&&!(_&4)&&m.collision.fire("triggerenter",p)),P&&(v||(v=this._storeCollision(m,p)),v&&p.rigidbody.fire("triggerenter",m)),A&&(v||(v=this._storeCollision(p,m)),v&&m.rigidbody.fire("triggerenter",p))}else{let E=this._hasContactEvent(p),y=this._hasContactEvent(m),P=this.hasEvent("contact");if(P||E||y){for(let A=0;A=0&&r!==e.element.drawOrder&&this.system.app.batcher?.markGroupDirty(e.element._batchGroupId)}e.particlesystem&&(e.particlesystem.drawOrder=s++);let i=e.children;for(let r=0;re._onScreenRemove()),this._elements.clear(),this.off()}set resolution(e){this._screenSpace?this._resolution.set(this.system.app.graphicsDevice.width,this.system.app.graphicsDevice.height):this._resolution.set(e.x,e.y),this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:resolution",this._resolution),this._elements.forEach(s=>s._onScreenResize(this._resolution))}get resolution(){return this._resolution}set referenceResolution(e){this._referenceResolution.set(e.x,e.y),this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:referenceresolution",this._resolution),this._elements.forEach(s=>s._onScreenResize(this._resolution))}get referenceResolution(){return this._scaleMode===fh?this._resolution:this._referenceResolution}set screenSpace(e){this._screenSpace=e,this._screenSpace&&this._resolution.set(this.system.app.graphicsDevice.width,this.system.app.graphicsDevice.height),this.resolution=this._resolution,this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:screenspace",this._screenSpace),this._elements.forEach(s=>s._onScreenSpaceChange())}get screenSpace(){return this._screenSpace}set scaleMode(e){e!==fh&&e!==CR&&(e=fh),!this._screenSpace&&e!==fh&&(e=fh),this._scaleMode=e,this.resolution=this._resolution,this.fire("set:scalemode",this._scaleMode)}get scaleMode(){return this._scaleMode}set scaleBlend(e){this._scaleBlend=e,this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:scaleblend",this._scaleBlend),this._elements.forEach(s=>s._onScreenResize(this._resolution))}get scaleBlend(){return this._scaleBlend}set priority(e){e=R.clamp(e,0,127),this._priority!==e&&(this._priority=e,this.syncDrawOrder())}get priority(){return this._priority}};var q0=class{constructor(){n(this,"enabled",!0)}};var PR=["enabled"],Jm=class extends Fe{constructor(t){super(t),this.id="screen",this.ComponentType=Pu,this.DataType=q0,this.schema=PR,this.windowResolution=new B,this._drawOrderSyncQueue=new sd,this.app.graphicsDevice.on("resizecanvas",this._onResize,this),this.app.systems.on("update",this._onUpdate,this),this.on("beforeremove",this.onRemoveComponent,this)}initializeComponentData(t,e,s){e.priority!==void 0&&(t.priority=e.priority),e.screenSpace!==void 0&&(t.screenSpace=e.screenSpace),t.cull=t.screenSpace,e.scaleMode!==void 0&&(t.scaleMode=e.scaleMode),e.scaleBlend!==void 0&&(t.scaleBlend=e.scaleBlend),e.resolution!==void 0&&(e.resolution instanceof B?t._resolution.copy(e.resolution):t._resolution.set(e.resolution[0],e.resolution[1]),t.resolution=t._resolution),e.referenceResolution!==void 0&&(e.referenceResolution instanceof B?t._referenceResolution.copy(e.referenceResolution):t._referenceResolution.set(e.referenceResolution[0],e.referenceResolution[1]),t.referenceResolution=t._referenceResolution),this._updateDescendantElements(t.entity,t.entity),t.syncDrawOrder(),super.initializeComponentData(t,e,PR)}_updateDescendantElements(t,e){let s=t.children;for(let i=0;ithis.dragThreshold||Math.abs(i)>this.dragThreshold)&&this._disableContentInput()}}_horizontalScrollbarEntitySubscribe(){this._evtHorizontalScrollbarAdd=this._horizontalScrollbarEntity.on("scrollbar:add",this._onHorizontalScrollbarGain,this),this._horizontalScrollbarEntity.scrollbar&&this._onHorizontalScrollbarGain()}_verticalScrollbarEntitySubscribe(){this._evtVerticalScrollbarAdd=this._verticalScrollbarEntity.on("scrollbar:add",this._onVerticalScrollbarGain,this),this._verticalScrollbarEntity.scrollbar&&this._onVerticalScrollbarGain()}_horizontalScrollbarEntityUnsubscribe(){this._evtHorizontalScrollbarAdd?.off(),this._evtHorizontalScrollbarAdd=null,this._horizontalScrollbarEntity.scrollbar&&this._onHorizontalScrollbarLose()}_verticalScrollbarEntityUnsubscribe(){this._evtVerticalScrollbarAdd?.off(),this._evtVerticalScrollbarAdd=null,this._verticalScrollbarEntity.scrollbar&&this._onVerticalScrollbarLose()}_onSetHorizontalScrollbarValue(e){!this._scrollbarUpdateFlags[Ge]&&this.enabled&&this.entity.enabled&&this._onSetScroll(e,null)}_onSetVerticalScrollbarValue(e){!this._scrollbarUpdateFlags[dt]&&this.enabled&&this.entity.enabled&&this._onSetScroll(null,e)}_onHorizontalScrollbarGain(){let e=this._horizontalScrollbarEntity?.scrollbar;this._evtHorizontalScrollbarRemove=e.on("beforeremove",this._onHorizontalScrollbarLose,this),this._evtHorizontalScrollbarValue=e.on("set:value",this._onSetHorizontalScrollbarValue,this),this._syncScrollbarEnabledState(Ge),this._syncScrollbarPosition(Ge)}_onVerticalScrollbarGain(){let e=this._verticalScrollbarEntity?.scrollbar;this._evtVerticalScrollbarRemove=e.on("beforeremove",this._onVerticalScrollbarLose,this),this._evtVerticalScrollbarValue=e.on("set:value",this._onSetVerticalScrollbarValue,this),this._syncScrollbarEnabledState(dt),this._syncScrollbarPosition(dt)}_onHorizontalScrollbarLose(){this._evtHorizontalScrollbarRemove?.off(),this._evtHorizontalScrollbarRemove=null,this._evtHorizontalScrollbarValue?.off(),this._evtHorizontalScrollbarValue=null}_onVerticalScrollbarLose(){this._evtVerticalScrollbarRemove?.off(),this._evtVerticalScrollbarRemove=null,this._evtVerticalScrollbarValue?.off(),this._evtVerticalScrollbarValue=null}_onSetScroll(e,s,i){i!==!1&&this._velocity.set(0,0,0);let r=this._updateAxis(e,"x",Ge),a=this._updateAxis(s,"y",dt);(r||a)&&this.fire("set:scroll",this._scroll)}_updateAxis(e,s,i){let r=e!==null&&Math.abs(e-this._scroll[s])>1e-5;return(r||this._isDragging()||e===0)&&(this._scroll[s]=this._determineNewScrollValue(e,s,i),this._syncContentPosition(i),this._syncScrollbarPosition(i)),r}_determineNewScrollValue(e,s,i){if(!this._getScrollingEnabled(i))return this._scroll[s];switch(this.scrollMode){case 0:return R.clamp(e,0,this._getMaxScrollValue(i));case 1:return this._setVelocityFromOvershoot(e,s,i),e;case 2:return e;default:return e}}_syncAll(){this._syncContentPosition(Ge),this._syncContentPosition(dt),this._syncScrollbarPosition(Ge),this._syncScrollbarPosition(dt),this._syncScrollbarEnabledState(Ge),this._syncScrollbarEnabledState(dt)}_syncContentPosition(e){if(!this._contentEntity)return;let s=this._getAxis(e),i=this._getSign(e),r=this._prevContentSizes[e],a=this._getContentSize(e);if(r!==null&&Math.abs(r-a)>1e-4){let h=this._getMaxOffset(e,r),f=this._getMaxOffset(e,a);f===0?this._scroll[s]=1:this._scroll[s]=R.clamp(this._scroll[s]*h/f,0,1)}let o=this._scroll[s]*this._getMaxOffset(e),l=this._contentEntity.getLocalPosition();l[s]=o*i,this._contentEntity.setLocalPosition(l),this._prevContentSizes[e]=a}_syncScrollbarPosition(e){let s=this._scrollbarEntities[e];if(!s?.scrollbar)return;let i=this._getAxis(e);this._scrollbarUpdateFlags[e]=!0,s.scrollbar.value=this._scroll[i],s.scrollbar.handleSize=this._getScrollbarHandleSize(i,e),this._scrollbarUpdateFlags[e]=!1}_syncScrollbarEnabledState(e){let s=this._scrollbarEntities[e];if(!s)return;let i=this._getScrollingEnabled(e);switch(this._getScrollbarVisibility(e)){case 0:s.enabled=i;return;case 1:s.enabled=i&&this._contentIsLargerThanViewport(e);return;default:s.enabled=i}}_contentIsLargerThanViewport(e){return this._getContentSize(e)>this._getViewportSize(e)}_contentPositionToScrollValue(e){let s=this._getMaxOffset(Ge),i=this._getMaxOffset(dt);return s===0?$S.x=0:$S.x=e.x/s,i===0?$S.y=0:$S.y=e.y/-i,$S}_getMaxOffset(e,s){s=s===void 0?this._getContentSize(e):s;let i=this._getViewportSize(e);return s1e-4||Math.abs(this._velocity.y)>1e-4){let e=this._contentEntity.getLocalPosition();e.x+=this._velocity.x,e.y+=this._velocity.y,this._contentEntity.setLocalPosition(e),this._setScrollFromContentPosition(e)}this._velocity.x*=1-this.friction,this._velocity.y*=1-this.friction}}_hasOvershoot(e,s){return Math.abs(this._toOvershoot(this.scroll[e],s))>.001}_toOvershoot(e,s){let i=this._getMaxScrollValue(s);return e<0?e:e>i?e-i:0}_setVelocityFromOvershoot(e,s,i){let a=this._toOvershoot(e,i)*this._getMaxOffset(i)*this._getSign(i);Math.abs(a)>0&&(this._velocity[s]=-a/(this.bounceAmount*50+1))}_setVelocityFromContentPositionDelta(e){this._prevContentDragPosition?(this._velocity.sub2(e,this._prevContentDragPosition),this._prevContentDragPosition.copy(e)):(this._velocity.set(0,0,0),this._prevContentDragPosition=e.clone())}_setScrollFromContentPosition(e){let s=this._contentPositionToScrollValue(e);this._isDragging()&&(s=this._applyScrollValueTension(s)),this._onSetScroll(s.x,s.y,!1)}_applyScrollValueTension(e){let i=this._getMaxScrollValue(Ge),r=this._toOvershoot(e.x,Ge);return r>0?e.x=i+1*Math.log10(1+r):r<0&&(e.x=-1*Math.log10(1-r)),i=this._getMaxScrollValue(dt),r=this._toOvershoot(e.y,dt),r>0?e.y=i+1*Math.log10(1+r):r<0&&(e.y=-1*Math.log10(1-r)),e}_isDragging(){return this._contentDragHelper&&this._contentDragHelper.isDragging}_setScrollbarComponentsEnabled(e){this._horizontalScrollbarEntity?.scrollbar&&(this._horizontalScrollbarEntity.scrollbar.enabled=e),this._verticalScrollbarEntity?.scrollbar&&(this._verticalScrollbarEntity.scrollbar.enabled=e)}_setContentDraggingEnabled(e){this._contentDragHelper&&(this._contentDragHelper.enabled=e)}_onMouseWheel(e){if(!this.useMouseWheel||!this._contentEntity?.element)return;let s=e.event,i=s.deltaX/this._contentEntity.element.calculatedWidth*this.mouseWheelSensitivity.x,r=s.deltaY/this._contentEntity.element.calculatedHeight*this.mouseWheelSensitivity.y,a=R.clamp(this._scroll.x+i,0,this._getMaxScrollValue(Ge)),o=R.clamp(this._scroll.y+r,0,this._getMaxScrollValue(dt));this.scroll=new B(a,o)}_enableContentInput(){for(;this._disabledContentInputEntities.length;){let e=this._disabledContentInputEntities.pop();e.element&&(e.element.useInput=!0)}this._disabledContentInput=!1}_disableContentInput(){let e=s=>{s.element&&s.element.useInput&&(this._disabledContentInputEntities.push(s),s.element.useInput=!1);let i=s.children;for(let r=0,a=i.length;r1e-5&&(this._value=R.clamp(e,0,1),this._updateHandlePositionAndSize(),this.fire("set:value",this._value))}get value(){return this._value}set handleSize(e){Math.abs(e-this._handleSize)>1e-5&&(this._handleSize=R.clamp(e,0,1),this._updateHandlePositionAndSize())}get handleSize(){return this._handleSize}set handleEntity(e){let s;e instanceof Pe?s=e:typeof e=="string"?s=this.system.app.getEntityFromIndex(e)??null:s=null,this._handleEntity!==s&&(this._handleEntity&&this._handleEntityUnsubscribe(),this._handleEntity=s,s&&this._handleEntitySubscribe())}get handleEntity(){return this._handleEntity}_handleEntitySubscribe(){this._evtHandleEntityElementAdd=this._handleEntity.on("element:add",this._onHandleElementGain,this),this._handleEntity.element&&this._onHandleElementGain()}_handleEntityUnsubscribe(){this._evtHandleEntityElementAdd?.off(),this._evtHandleEntityElementAdd=null,this._handleEntity?.element&&this._onHandleElementLose()}_handleEntityElementSubscribe(){let e=this._handleEntity.element,s=this._evtHandleEntityChanges;s.push(e.once("beforeremove",this._onHandleElementLose,this)),s.push(e.on("set:anchor",this._updateHandlePositionAndSize,this)),s.push(e.on("set:margin",this._updateHandlePositionAndSize,this)),s.push(e.on("set:pivot",this._updateHandlePositionAndSize,this))}_handleEntityElementUnsubscribe(){for(let e=0;e0?i.duration:null,this._startTime=Math.max(0,Number(i.startTime)||0),this._overlap=!!i.overlap,this._autoPlay=!!i.autoPlay,this._firstNode=null,this._lastNode=null,this._asset=i.asset,this._asset instanceof ae&&(this._asset=this._asset.id),this._onInstancePlayHandler=this._onInstancePlay.bind(this),this._onInstancePauseHandler=this._onInstancePause.bind(this),this._onInstanceResumeHandler=this._onInstanceResume.bind(this),this._onInstanceStopHandler=this._onInstanceStop.bind(this),this._onInstanceEndHandler=this._onInstanceEnd.bind(this)}play(){if(this.overlap||this.stop(),!this.isLoaded&&!this._hasAsset())return;let e=this._createInstance();if(this.instances.push(e),this.isLoaded)e.play();else{let s=function(i){let r=e._playWhenLoaded;e.sound=i,r&&e.play()};this.off("load",s),this.once("load",s),this.load()}return e}pause(){let e=!1,s=this.instances;for(let i=0,r=s.length;i=0;l--){let h=a[l].isPlaying||a[l].isSuspended,f=a[l].currentTime;h&&a[l].stop();let u=r._createInstance();h&&(u.play(),u.currentTime=f),a.push(u)}}}}get positional(){return this._positional}set slots(e){let s=this._slots;if(s)for(let r in s)s[r].stop();let i={};for(let r in e)e[r]instanceof ir?i[e[r].name]=e[r]:e[r].name&&(i[e[r].name]=new ir(this,e[r].name,e[r]));this._slots=i,this.enabled&&this.entity.enabled&&this.onEnable()}get slots(){return this._slots}onEnable(){if(this.system._inTools)return;let e=this._slots,s=this._playingBeforeDisable;for(let i in e){let r=e[i];r.autoPlay&&r.isStopped?r.play():s[i]?r.resume():r.isLoaded||r.load()}}onDisable(){let e=this._slots,s={};for(let i in e)e[i].overlap||e[i].isPlaying&&(e[i].pause(),s[i]=!0);this._playingBeforeDisable=s}onRemove(){this.off()}addSlot(e,s){let i=this._slots;if(i[e])return null;let r=new ir(this,e,s);return i[e]=r,r.autoPlay&&this.enabled&&this.entity.enabled&&r.play(),r}removeSlot(e){let s=this._slots;s[e]&&(s[e].stop(),delete s[e])}slot(e){return this._slots[e]}_getSlotProperty(e,s){if(!this.enabled||!this.entity.enabled)return;let i=this._slots[e];if(i)return i[s]}isPlaying(e){return this._getSlotProperty(e,"isPlaying")||!1}isLoaded(e){return this._getSlotProperty(e,"isLoaded")||!1}isPaused(e){return this._getSlotProperty(e,"isPaused")||!1}isStopped(e){return this._getSlotProperty(e,"isStopped")||!1}play(e){if(!this.enabled||!this.entity.enabled)return null;let s=this._slots[e];return s?s.play():null}pause(e){let s=this._slots;if(e){let i=s[e];if(!i)return;i.pause()}else for(let i in s)s[i].pause()}resume(e){let s=this._slots;if(e){let i=s[e];if(!i)return;i.isPaused&&i.resume()}else for(let i in s)s[i].resume()}stop(e){let s=this._slots;if(e){let i=s[e];if(!i)return;i.stop()}else for(let i in s)s[i].stop()}};n(ma,"EVENT_PLAY","play"),n(ma,"EVENT_PAUSE","pause"),n(ma,"EVENT_RESUME","resume"),n(ma,"EVENT_STOP","stop"),n(ma,"EVENT_END","end");var Q0=class{constructor(){n(this,"enabled",!0)}};var Ak=["enabled"],s_=class extends Fe{constructor(t){super(t),this.id="sound",this.ComponentType=ma,this.DataType=Q0,this.schema=Ak,this.manager=t.soundManager,this.app.systems.on("update",this.onUpdate,this),this.on("beforeremove",this.onBeforeRemove,this)}set volume(t){this.manager.volume=t}get volume(){return this.manager.volume}get context(){return this.manager.context}initializeComponentData(t,e,s){s=["volume","pitch","positional","refDistance","maxDistance","rollOffFactor","distanceModel","slots"];for(let i=0;ir||i<0;this._setTime(i);let o=this.frame;this._sprite?o=Math.floor(this._sprite.frameKeys.length*this._time/r):o=0,o!==this._frame&&this._setFrame(o),a&&(this.loop?(this.fire("loop"),this._component.fire("loop",this)):(this._playing=!1,this._paused=!1,this.fire("end"),this._component.fire("end",this)))}_setTime(e){this._time=e;let s=this.duration;this._time<0?this.loop?this._time=this._time%s+s:this._time=0:this._time>s&&(this.loop?this._time%=s:this._time=s)}_setFrame(e){this._sprite?this._frame=R.clamp(e,0,this._sprite.frameKeys.length-1):this._frame=e,this._component.currentClip===this&&this._component._showFrame(this._frame)}_destroy(){if(this._spriteAsset){let e=this._component.system.app.assets;this._unbindSpriteAsset(e.get(this._spriteAsset))}this._sprite&&(this.sprite=null),this._spriteAsset&&(this.spriteAsset=null)}play(){this._playing||(this._playing=!0,this._paused=!1,this.frame=0,this.fire("play"),this._component.fire("play",this))}pause(){!this._playing||this._paused||(this._paused=!0,this.fire("pause"),this._component.fire("pause",this))}resume(){this._paused&&(this._paused=!1,this.fire("resume"),this._component.fire("resume",this))}stop(){this._playing&&(this._playing=!1,this._paused=!1,this._time=0,this.frame=0,this.fire("stop"),this._component.fire("stop",this))}};n(rr,"EVENT_PLAY","play"),n(rr,"EVENT_PAUSE","pause"),n(rr,"EVENT_RESUME","resume"),n(rr,"EVENT_STOP","stop"),n(rr,"EVENT_END","end"),n(rr,"EVENT_LOOP","loop");var Ck="texture_emissiveMap",Pk="texture_opacityMap",wk="material_emissive",Ik="material_opacity",gK="innerOffset",SK="outerScale",xK="atlasRect",Lr=class extends le{constructor(e,s){super(e,s);n(this,"_evtLayersChanged",null);n(this,"_evtLayerAdded",null);n(this,"_evtLayerRemoved",null);n(this,"_type",J0);n(this,"_material",null);n(this,"_color",new F(1,1,1,1));n(this,"_colorUniform",new Float32Array(3));n(this,"_speed",1);n(this,"_flipX",!1);n(this,"_flipY",!1);n(this,"_width",1);n(this,"_height",1);n(this,"_drawOrder",0);n(this,"_layers",[Os]);n(this,"_outerScale",new B(1,1));n(this,"_outerScaleUniform",new Float32Array(2));n(this,"_innerOffset",new Q);n(this,"_innerOffsetUniform",new Float32Array(4));n(this,"_atlasRect",new Q);n(this,"_atlasRectUniform",new Float32Array(4));n(this,"_batchGroupId",-1);n(this,"_node",new Pe);n(this,"_meshInstance",null);n(this,"_updateAabbFunc",null);n(this,"_inLayers",!1);n(this,"_autoPlayClip",null);n(this,"_clips",{});n(this,"_defaultClip",null);n(this,"_currentClip",null);this._material=e.defaultMaterial,s.addChild(this._node),this._updateAabbFunc=this._updateAabb.bind(this),this._defaultClip=new rr(this,{name:this.entity.name,fps:0,loop:!1,spriteAsset:null}),this._currentClip=this._defaultClip}set type(e){this._type!==e&&(this._type=e,this._type===J0?(this.stop(),this._currentClip=this._defaultClip,this.enabled&&this.entity.enabled&&(this._currentClip.frame=this.frame,this._currentClip.sprite?this.addToLayers():this.removeFromLayers())):this._type===eE&&(this.stop(),this._autoPlayClip&&this._tryAutoPlay(),this._currentClip&&this._currentClip.isPlaying&&this.enabled&&this.entity.enabled?this.addToLayers():this.removeFromLayers()))}get type(){return this._type}set frame(e){this._currentClip.frame=e}get frame(){return this._currentClip.frame}set spriteAsset(e){this._defaultClip.spriteAsset=e}get spriteAsset(){return this._defaultClip._spriteAsset}set sprite(e){this._currentClip.sprite=e}get sprite(){return this._currentClip.sprite}set material(e){this._material=e,this._meshInstance&&(this._meshInstance.material=e)}get material(){return this._material}set color(e){this._color.r=e.r,this._color.g=e.g,this._color.b=e.b,this._meshInstance&&(this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._meshInstance.setParameter(wk,this._colorUniform))}get color(){return this._color}set opacity(e){this._color.a=e,this._meshInstance&&this._meshInstance.setParameter(Ik,e)}get opacity(){return this._color.a}set clips(e){if(!e){for(let s in this._clips)this.removeClip(s);return}for(let s in this._clips){let i=!1;for(let r in e)if(e[r].name===s){i=!0,this._clips[s].fps=e[r].fps,this._clips[s].loop=e[r].loop,e[r].hasOwnProperty("sprite")?this._clips[s].sprite=e[r].sprite:e[r].hasOwnProperty("spriteAsset")&&(this._clips[s].spriteAsset=e[r].spriteAsset);break}i||this.removeClip(s)}for(let s in e)this._clips[e[s].name]||this.addClip(e[s]);this._autoPlayClip&&this._tryAutoPlay(),(!this._currentClip||!this._currentClip.sprite)&&this.removeFromLayers()}get clips(){return this._clips}get currentClip(){return this._currentClip}set speed(e){this._speed=e}get speed(){return this._speed}set flipX(e){this._flipX!==e&&(this._flipX=e,this._updateTransform())}get flipX(){return this._flipX}set flipY(e){this._flipY!==e&&(this._flipY=e,this._updateTransform())}get flipY(){return this._flipY}set width(e){e!==this._width&&(this._width=e,this._outerScale.x=this._width,this.sprite&&(this.sprite.renderMode===Rt||this.sprite.renderMode===It)&&this._updateTransform())}get width(){return this._width}set height(e){e!==this._height&&(this._height=e,this._outerScale.y=this.height,this.sprite&&(this.sprite.renderMode===Rt||this.sprite.renderMode===It)&&this._updateTransform())}get height(){return this._height}set batchGroupId(e){if(this._batchGroupId===e)return;let s=this._batchGroupId;this._batchGroupId=e,this.entity.enabled&&s>=0&&this.system.app.batcher?.remove(pt.SPRITE,s,this.entity),this.entity.enabled&&e>=0?this.system.app.batcher?.insert(pt.SPRITE,e,this.entity):s>=0&&this._currentClip&&this._currentClip.sprite&&this.enabled&&this.entity.enabled&&this.addToLayers()}get batchGroupId(){return this._batchGroupId}set autoPlayClip(e){this._autoPlayClip=e instanceof rr?e.name:e,this._tryAutoPlay()}get autoPlayClip(){return this._autoPlayClip}set drawOrder(e){this._drawOrder=e,this._meshInstance&&(this._meshInstance.drawOrder=e)}get drawOrder(){return this._drawOrder}set layers(e){this._inLayers&&this.removeFromLayers(),this._layers=e,this._meshInstance&&this.enabled&&this.entity.enabled&&this.addToLayers()}get layers(){return this._layers}get aabb(){return this._meshInstance?this._meshInstance.aabb:null}onEnable(){let e=this.system.app,s=e.scene,i=s.layers;this._evtLayersChanged=s.on("set:layers",this._onLayersChanged,this),i&&(this._evtLayerAdded=i.on("add",this._onLayerAdded,this),this._evtLayerRemoved=i.on("remove",this._onLayerRemoved,this)),this.addToLayers(),this._autoPlayClip&&this._tryAutoPlay(),this._batchGroupId>=0&&e.batcher?.insert(pt.SPRITE,this._batchGroupId,this.entity)}onDisable(){let e=this.system.app,i=e.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,i&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this.stop(),this.removeFromLayers(),this._batchGroupId>=0&&e.batcher?.remove(pt.SPRITE,this._batchGroupId,this.entity)}onDestroy(){this._currentClip=null,this._defaultClip&&(this._defaultClip._destroy(),this._defaultClip=null);for(let e in this._clips)this._clips[e]._destroy();this._clips=null,this.removeFromLayers(),this._node?.remove(),this._node=null,this._meshInstance&&(this._meshInstance.material=null,this._meshInstance.mesh=null,this._meshInstance=null)}addToLayers(){if(this._inLayers||!this._meshInstance)return;let e=[this._meshInstance];for(let s=0,i=this._layers.length;s=3&&this.size.set(e[0],e[1],e[2])}get size(){return this._size}onEnable(){this._checkState()}onDisable(){this._checkState()}_onSetEnabled(e,s,i){this._checkState()}_checkState(){let e=this.enabled&&this.entity.enabled;e!==this._oldState&&(this._oldState=e,this.fire("enable"),this.fire("state",this.enabled))}_onBeforeRemove(){this.fire("remove")}};n(ro,"EVENT_ENABLE","enable"),n(ro,"EVENT_DISABLE","disable"),n(ro,"EVENT_STATE","state"),n(ro,"EVENT_REMOVE","remove");var sE=class{constructor(){n(this,"enabled",!0)}};var bk=["enabled"],r_=class extends Fe{constructor(t){super(t),this.id="zone",this.ComponentType=ro,this.DataType=sE,this.schema=bk,this.on("beforeremove",this._onBeforeRemove,this)}initializeComponentData(t,e,s){t.enabled=e.hasOwnProperty("enabled")?!!e.enabled:!0,e.size&&(e.size instanceof x?t.size.copy(e.size):e.size instanceof Array&&e.size.length>=3&&t.size.set(e.size[0],e.size[1],e.size[2]))}cloneComponent(t,e){let s={enabled:t.zone.enabled,size:t.zone.size};return this.addComponent(e,s)}_onBeforeRemove(t,e){e._onBeforeRemove()}};le._buildAccessors(ro.prototype,bk);var RR=class{constructor(t,e){this.effect=t,this.inputTarget=e,this.outputTarget=null,this.name=t.constructor.name}},a_=class{constructor(t,e){this.app=t,this.camera=e,this.destinationRenderTarget=null,this.effects=[],this.enabled=!1,this.depthTarget=null,e.on("set:rect",this.onCameraRectChanged,this)}_allocateColorBuffer(t,e){let s=this.camera.rect,i=this.destinationRenderTarget,r=this.app.graphicsDevice,a=Math.floor(s.z*(i?.width??r.width)),o=Math.floor(s.w*(i?.height??r.height));return Z.createDataTexture2D(r,e,a,o,t)}_createOffscreenTarget(t,e){let s=this.app.graphicsDevice,r=(this.destinationRenderTarget??s.backBuffer).isColorBufferSrgb(0),a=(e&&s.getRenderableHdrFormat([Me,ke],!0))??(r?st:ce),o=`${this.camera.entity.name}-posteffect-${this.effects.length}`,l=this._allocateColorBuffer(a,o);return new me({colorBuffer:l,depth:t,stencil:t&&this.app.graphicsDevice.supportsStencil,samples:t?s.samples:1})}_resizeOffscreenTarget(t){let e=t.colorBuffer.format,s=t.colorBuffer.name;t.destroyFrameBuffers(),t.destroyTextureBuffers(),t._colorBuffer=this._allocateColorBuffer(e,s),t._colorBuffers=[t._colorBuffer],t.evaluateDimensions()}_destroyOffscreenTarget(t){t.destroyTextureBuffers(),t.destroy()}addEffect(t){let e=this.effects,s=e.length===0,i=this._createOffscreenTarget(s,t.hdr),r=new RR(t,i);e.push(r),this._sourceTarget=r.inputTarget,e.length>1&&(e[e.length-2].outputTarget=r.inputTarget),this._newPostEffect=t,t.needsDepthBuffer&&this._requestDepthMap(),this.enable(),this._newPostEffect=void 0}removeEffect(t){let e=-1;for(let s=0,i=this.effects.length;s=0&&(e>0?this.effects[e-1].outputTarget=e+11&&(this.effects[1].inputTarget._depth||(this._destroyOffscreenTarget(this.effects[1].inputTarget),this.effects[1].inputTarget=this._createOffscreenTarget(!0,this.effects[1].hdr),this._sourceTarget=this.effects[1].inputTarget),this.camera.renderTarget=this.effects[1].inputTarget),this._destroyOffscreenTarget(this.effects[e].inputTarget),this.effects.splice(e,1)),this.enabled&&t.needsDepthBuffer&&this._releaseDepthMap(),this.effects.length===0&&this.disable()}_requestDepthMaps(){for(let t=0,e=this.effects.length;t{if(this.enabled){let t=null,e=this.effects.length;if(e)for(let s=0;s{i.layers.getLayerById(r)?.removeCamera(this)}),this._camera.layers=e,this.enabled&&this.entity.enabled&&e.forEach(r=>{i.layers.getLayerById(r)?.addCamera(this)}),this.fire("set:layers")}get layers(){return this._camera.layers}get layersSet(){return this._camera.layersSet}set jitter(e){this._camera.jitter=e}get jitter(){return this._camera.jitter}set nearClip(e){this._camera.nearClip=e}get nearClip(){return this._camera.nearClip}set orthoHeight(e){this._camera.orthoHeight=e}get orthoHeight(){return this._camera.orthoHeight}get postEffects(){return this._postEffects}get postEffectsEnabled(){return this._postEffects.enabled}set priority(e){this._priority=e,this.dirtyLayerCompositionCameras()}get priority(){return this._priority}set projection(e){this._camera.projection=e}get projection(){return this._camera.projection}get projectionMatrix(){return this._camera.projectionMatrix}set rect(e){this._camera.rect=e,this.fire("set:rect",this._camera.rect)}get rect(){return this._camera.rect}set renderSceneColorMap(e){e&&!this._sceneColorMapRequested?(this.requestSceneColorMap(!0),this._sceneColorMapRequested=!0):!e&&this._sceneColorMapRequested&&(this.requestSceneColorMap(!1),this._sceneColorMapRequested=!1)}get renderSceneColorMap(){return this._renderSceneColorMap>0}set renderSceneDepthMap(e){e&&!this._sceneDepthMapRequested?(this.requestSceneDepthMap(!0),this._sceneDepthMapRequested=!0):!e&&this._sceneDepthMapRequested&&(this.requestSceneDepthMap(!1),this._sceneDepthMapRequested=!1)}get renderSceneDepthMap(){return this._renderSceneDepthMap>0}set renderTarget(e){this._camera.renderTarget=e,this.dirtyLayerCompositionCameras()}get renderTarget(){return this._camera.renderTarget}set scissorRect(e){this._camera.scissorRect=e}get scissorRect(){return this._camera.scissorRect}set sensitivity(e){this._camera.sensitivity=e}get sensitivity(){return this._camera.sensitivity}set shutter(e){this._camera.shutter=e}get shutter(){return this._camera.shutter}get viewMatrix(){return this._camera.viewMatrix}_enableDepthLayer(e){if(this.layers.find(i=>i===Zt)){let i=this.system.app.scene.layers.getLayerById(Zt);e?i?.incrementCounter():i?.decrementCounter()}else if(e)return!1;return!0}requestSceneColorMap(e){this._renderSceneColorMap+=e?1:-1;let s=this._enableDepthLayer(e);this.camera._enableRenderPassColorGrab(this.system.app.graphicsDevice,this.renderSceneColorMap),this.system.app.scene.layers.markDirty()}requestSceneDepthMap(e){this._renderSceneDepthMap+=e?1:-1;let s=this._enableDepthLayer(e);this.camera._enableRenderPassDepthGrab(this.system.app.graphicsDevice,this.system.app.renderer,this.renderSceneDepthMap),this.system.app.scene.layers.markDirty()}dirtyLayerCompositionCameras(){let e=this.system.app.scene.layers;e._dirty=!0}screenToWorld(e,s,i,r){let a=this.system.app.graphicsDevice,{width:o,height:l}=a.clientRect;return this._camera.screenToWorld(e,s,i,o,l,r)}worldToScreen(e,s){let i=this.system.app.graphicsDevice,{width:r,height:a}=i.clientRect;return this._camera.worldToScreen(e,r,a,s)}onAppPrerender(){this._camera._viewMatDirty=!0,this._camera._viewProjMatDirty=!0}addCameraToLayers(){let e=this.layers;for(let s=0;s=0&&(this.cameras.splice(s,1),Uc(this.cameras))}destroy(){this.app.off("prerender",this.onAppPrerender,this),super.destroy()}};le._buildAccessors(ar.prototype,Dk);var Iu=["type","color","intensity","luminance","shape","affectSpecularity","castShadows","shadowDistance","shadowIntensity","shadowResolution","shadowBias","numCascades","cascadeBlend","bakeNumSamples","bakeArea","cascadeDistribution","normalOffsetBias","range","innerConeAngle","outerConeAngle","falloffMode","shadowType","vsmBlurSize","vsmBlurMode","vsmBias","cookieAsset","cookie","cookieIntensity","cookieFalloff","cookieChannel","cookieAngle","cookieScale","cookieOffset","shadowUpdateMode","mask","affectDynamic","affectLightmapped","bake","bakeDir","isStatic","layers","penumbraSize","penumbraFalloff","shadowSamples","shadowBlockerSamples"],Ru=class extends le{constructor(e,s){super(e,s);n(this,"_light");n(this,"_evtLayersChanged",null);n(this,"_evtLayerAdded",null);n(this,"_evtLayerRemoved",null);n(this,"_cookieAsset",null);n(this,"_cookieAssetId",null);n(this,"_cookieAssetAdd",!1);n(this,"_cookieMatrix",null);n(this,"_shadowBias",.05);n(this,"_cookieAngle",0);n(this,"_cookieScale",null);n(this,"_castShadows",!1);n(this,"_affectSpecularity",!0);n(this,"_affectDynamic",!0);n(this,"_affectLightmapped",!1);n(this,"_bake",!1);n(this,"_layers",[Os]);n(this,"_type","directional");this._light=new kc(e.app.graphicsDevice,e.app.scene.clusteredLightingEnabled),this._light._node=s,this._light.setColor(1,1,1)}get light(){return this._light}set type(e){this._type!==e&&(this.removeLightFromLayers(),this._type=e,this._light.type=ly[e],this.refreshProperties())}get type(){return this._type}set color(e){this._light.setColor(e)}get color(){return this._light.getColor()}set intensity(e){this._light.intensity=e}get intensity(){return this._light.intensity}set luminance(e){this._light.luminance=e}get luminance(){return this._light.luminance}set shape(e){this._light.shape=e}get shape(){return this._light.shape}set affectSpecularity(e){this._affectSpecularity=e,this._light.affectSpecularity=e}get affectSpecularity(){return this._affectSpecularity}set castShadows(e){this._castShadows=e,this._light.castShadows=e}get castShadows(){return this._castShadows}set shadowDistance(e){this._light.shadowDistance=e}get shadowDistance(){return this._light.shadowDistance}set shadowIntensity(e){this._light.shadowIntensity=e}get shadowIntensity(){return this._light.shadowIntensity}set shadowResolution(e){this._light.shadowResolution=e}get shadowResolution(){return this._light.shadowResolution}set shadowBias(e){this._shadowBias=e,this._light.shadowBias=-.01*R.clamp(e,0,1)}get shadowBias(){return this._shadowBias}set numCascades(e){this._light.numCascades=R.clamp(Math.floor(e),1,4)}get numCascades(){return this._light.numCascades}set cascadeBlend(e){this._light.cascadeBlend=R.clamp(e,0,1)}get cascadeBlend(){return this._light.cascadeBlend}set bakeNumSamples(e){this._light.bakeNumSamples=R.clamp(Math.floor(e),1,255)}get bakeNumSamples(){return this._light.bakeNumSamples}set bakeArea(e){this._light.bakeArea=R.clamp(e,0,180)}get bakeArea(){return this._light.bakeArea}set cascadeDistribution(e){this._light.cascadeDistribution=R.clamp(e,0,1)}get cascadeDistribution(){return this._light.cascadeDistribution}set normalOffsetBias(e){this._light.normalOffsetBias=R.clamp(e,0,1)}get normalOffsetBias(){return this._light.normalOffsetBias}set range(e){this._light.attenuationEnd=e}get range(){return this._light.attenuationEnd}set innerConeAngle(e){this._light.innerConeAngle=e}get innerConeAngle(){return this._light.innerConeAngle}set outerConeAngle(e){this._light.outerConeAngle=e}get outerConeAngle(){return this._light.outerConeAngle}set falloffMode(e){this._light.falloffMode=e}get falloffMode(){return this._light.falloffMode}set shadowType(e){this._light.shadowType=e}get shadowType(){return this._light.shadowType}set vsmBlurSize(e){this._light.vsmBlurSize=e}get vsmBlurSize(){return this._light.vsmBlurSize}set vsmBlurMode(e){this._light.vsmBlurMode=e}get vsmBlurMode(){return this._light.vsmBlurMode}set vsmBias(e){this._light.vsmBias=R.clamp(e,0,1)}get vsmBias(){return this._light.vsmBias}set cookieAsset(e){if(!(this._cookieAssetId&&(e instanceof ae&&e.id===this._cookieAssetId||e===this._cookieAssetId))){if(this.onCookieAssetRemove(),this._cookieAssetId=null,e instanceof ae)this._cookieAssetId=e.id,this.onCookieAssetAdd(e);else if(typeof e=="number"){this._cookieAssetId=e;let s=this.system.app.assets.get(e);s?this.onCookieAssetAdd(s):(this._cookieAssetAdd=!0,this.system.app.assets.on(`add:${this._cookieAssetId}`,this.onCookieAssetAdd,this))}}}get cookieAsset(){return this._cookieAssetId}set cookie(e){this._light.cookie=e}get cookie(){return this._light.cookie}set cookieIntensity(e){this._light.cookieIntensity=R.clamp(e,0,1)}get cookieIntensity(){return this._light.cookieIntensity}set cookieFalloff(e){this._light.cookieFalloff=e}get cookieFalloff(){return this._light.cookieFalloff}set cookieChannel(e){this._light.cookieChannel=e}get cookieChannel(){return this._light.cookieChannel}set cookieAngle(e){if(this._cookieAngle!==e)if(this._cookieAngle=e,e!==0||this._cookieScale!==null){this._cookieMatrix||(this._cookieMatrix=new Q);let s=1,i=1;this._cookieScale&&(s=this._cookieScale.x,i=this._cookieScale.y);let r=Math.cos(e*R.DEG_TO_RAD),a=Math.sin(e*R.DEG_TO_RAD);this._cookieMatrix.set(r/s,-a/s,a/i,r/i),this._light.cookieTransform=this._cookieMatrix}else this._light.cookieTransform=null}get cookieAngle(){return this._cookieAngle}set cookieScale(e){if(this._cookieScale=e,e!==null||this._cookieAngle!==0){this._cookieMatrix||(this._cookieMatrix=new Q);let s=e?e.x:1,i=e?e.y:1,r=Math.cos(this._cookieAngle*R.DEG_TO_RAD),a=Math.sin(this._cookieAngle*R.DEG_TO_RAD);this._cookieMatrix.set(r/s,-a/s,a/i,r/i),this._light.cookieTransform=this._cookieMatrix}else this._light.cookieTransform=null}get cookieScale(){return this._cookieScale}set cookieOffset(e){this._light.cookieOffset=e}get cookieOffset(){return this._light.cookieOffset}set shadowUpdateMode(e){this._light.shadowUpdateMode=e}get shadowUpdateMode(){return this._light.shadowUpdateMode}set mask(e){this._light.mask=e}get mask(){return this._light.mask}set affectDynamic(e){this._affectDynamic!==e&&(this._affectDynamic=e,e?this._light.mask|=cs:this._light.mask&=~cs,this._light.layersDirty())}get affectDynamic(){return this._affectDynamic}set affectLightmapped(e){this._affectLightmapped!==e&&(this._affectLightmapped=e,e?(this._light.mask|=xi,this._bake&&(this._light.mask&=~vi)):(this._light.mask&=~xi,this._bake&&(this._light.mask|=vi)))}get affectLightmapped(){return this._affectLightmapped}set bake(e){this._bake!==e&&(this._bake=e,e?(this._light.mask|=vi,this._affectLightmapped&&(this._light.mask&=~xi)):(this._light.mask&=~vi,this._affectLightmapped&&(this._light.mask|=xi)),this._light.layersDirty())}get bake(){return this._bake}set bakeDir(e){this._light.bakeDir=e}get bakeDir(){return this._light.bakeDir}set isStatic(e){this._light.isStatic=e}get isStatic(){return this._light.isStatic}set layers(e){let s=this._layers;for(let i=0;i=0&&this.enabled&&this.entity.enabled&&(e.addLight(this),this._light.addLayer(e))}onLayerRemoved(e){this._layers.indexOf(e.id)>=0&&(e.removeLight(this),this._light.removeLayer(e))}refreshProperties(){for(let e=0;e=3&&e.length<=4){for(let i=0;ic_(c,t,i,s?s[r]:null)):c_(c,t,e,s)}function bR(c,t,e,s){if(e)for(let i in t){let r=t[i],a=e[i];a!==void 0&&(s[i]=Mk(c,r,a,s[i]))}}var l_=class l_{constructor(t){this.scriptType=t,this.index={}}add(t,e){e&&e.type&&(this.index[t]||l_.reservedNames.has(t)||(this.index[t]=e,Object.defineProperty(this.scriptType.prototype,t,{get:function(){return this.__attributes[t]},set:function(s){let i="attr",r=`attr:${t}`,a=this.__attributes[t],o=a;if(a&&e.type!=="json"&&e.type!=="entity"&&a.clone&&(this.hasEvent(i)||this.hasEvent(r))&&(o=a.clone()),e.array){if(this.__attributes[t]=[],s)for(let l=0,h=s.length;l{this.initializeAttributes(i)}),i.enabled=!!e[s].enabled),typeof e[s].attributes=="object")){for(let r in e[s].attributes)if(!ao.reservedNames.has(r)){if(!i.__attributes.hasOwnProperty(r)){let a=this.system.app.scripts.get(s);a&&a.attributes.add(r,{})}i[r]=e[s].attributes[r]}}}}get scripts(){return this._scripts}set enabled(e){let s=this._enabled;this._enabled=e,this.fire("set","enabled",s,e)}get enabled(){return this._enabled}onEnable(){this._beingEnabled=!0,this._checkState(),this.entity._beingEnabled||this.onPostStateChange(),this._beingEnabled=!1}onDisable(){this._checkState()}onPostStateChange(){let e=this._beginLooping();for(let s=0,i=this.scripts.length;s{this.initializeAttributes(a)}),a.enabled=a._enabled}this._endLooping(s)}_onBeforeRemove(){this.fire("remove");let e=this._beginLooping();for(let s=0;ss.ind&&(h=s.ind),this._insertScriptInstance(o,h,l),this._scriptsIndex[a]={instance:o,onSwap:function(){i.swap(a)}},this[a]=o,s.preloading||this.initializeAttributes(o),this.fire("create",a,o),this.fire(`create:${a}`,o),this.system.app.scripts.on(`swap:${a}`,this._scriptsIndex[a].onSwap),s.preloading||(o.enabled&&!o._initialized&&(o._initialized=!0,o.initialize&&this._scriptMethod(o,IS)),o.enabled&&!o._postInitialized&&(o._postInitialized=!0,o.postInitialize&&this._scriptMethod(o,RS))),o}}else this._scriptsIndex[a]={awaiting:!0,ind:this._scripts.length};return null}destroy(e){let s=e,i=e;typeof i=="string"?i=this.system.app.scripts.get(i):i&&(s=i.__name);let r=this._scriptsIndex[s];if(delete this._scriptsIndex[s],!r)return!1;this._attributeDataMap.delete(s);let a=r.instance;if(a&&!a._destroyed)if(a.enabled=!1,a._destroyed=!0,this._isLoopingThroughScripts)this._destroyedScripts.push(a);else{let o=this._removeScriptInstance(a);o>=0&&this._resetExecutionOrder(o,this._scripts.length)}return this.system.app.scripts.off(`swap:${s}`,r.onSwap),delete this[s],this.fire("destroy",s,a||null),this.fire(`destroy:${s}`,a||null),a&&a.fire("destroy"),!0}swap(e){let s=e,i=e;typeof i=="string"?i=this.system.app.scripts.get(i):i&&(s=i.__name);let r=this._scriptsIndex[s];if(!r||!r.instance)return!1;let a=r.instance,o=this._scripts.indexOf(a),l=new i({app:this.system.app,entity:this.entity,enabled:a.enabled,attributes:a.__attributes});return l.swap?(this.initializeAttributes(l),this._scripts[o]=l,this._scriptsIndex[s].instance=l,this[s]=l,l.__executionOrder=o,a.update&&this._updateList.remove(a),a.postUpdate&&this._postUpdateList.remove(a),l.update&&this._updateList.insert(l),l.postUpdate&&this._postUpdateList.insert(l),this._scriptMethod(l,w2,a),this.fire("swap",s,l),this.fire(`swap:${s}`,l),!0):!1}resolveDuplicatedEntityReferenceProperties(e,s){let i=this.entity.script;for(let r in e._scriptsIndex){let a=this.system.app.scripts.get(r);if(!a)continue;let o=e._scriptsIndex[r];if(!o||!o.instance)continue;let l=i[r].__attributesRaw??i._attributeDataMap.get(r),h=i[r].__attributes;if(!l&&!h)continue;let f=!!l,u=o.instance.__attributes??i._attributeDataMap.get(r);for(let d in u){if(!u[d])continue;let p=a.attributes?.get(d)??this.system.app.scripts.getSchema(r)?.attributes?.[d];if(p){if(p.type==="entity")this._resolveEntityScriptAttribute(p,d,u[d],f,l||h,s);else if(p.type==="json"&&Array.isArray(p.schema)){let m=u[d],_=l?l[d]:h[d];for(let S=0;S=i||s<0)return!1;let r=e,a=e;typeof a!="string"?a=e.__name:r=null;let o=this._scriptsIndex[a];if(!o||!o.instance)return!1;let l=o.instance;if(r&&!(l instanceof r))return!1;let h=this._scripts.indexOf(l);return h===-1||h===s?!1:(this._scripts.splice(s,0,this._scripts.splice(h,1)[0]),this._resetExecutionOrder(0,i),this._updateList.sort(),this._postUpdateList.sort(),this.fire("move",a,l,s,h),this.fire(`move:${a}`,l,s,h),!0)}};n(or,"EVENT_CREATE","create"),n(or,"EVENT_DESTROY","destroy"),n(or,"EVENT_ENABLE","enable"),n(or,"EVENT_DISABLE","disable"),n(or,"EVENT_REMOVE","remove"),n(or,"EVENT_STATE","state"),n(or,"EVENT_MOVE","move"),n(or,"EVENT_ERROR","error");var aE=class{constructor(){n(this,"enabled",!0)}};var yK="_onInitializeAttributes",EK="_onInitialize",AK="_onPostInitialize",CK="_onUpdate",PK="_onPostUpdate",oE=0,h_=class extends Fe{constructor(t){super(t),this.id="script",this.ComponentType=or,this.DataType=aE,this._components=new po({sortBy:"_executionOrder"}),this._enabledComponents=new po({sortBy:"_executionOrder"}),this.preloading=!0,this.on("beforeremove",this._onBeforeRemove,this),this.app.systems.on("initialize",this._onInitialize,this),this.app.systems.on("postInitialize",this._onPostInitialize,this),this.app.systems.on("update",this._onUpdate,this),this.app.systems.on("postUpdate",this._onPostUpdate,this)}initializeComponentData(t,e){if(t._executionOrder=oE++,this._components.append(t),oE>Number.MAX_SAFE_INTEGER&&this._resetExecutionOrder(),t.enabled=e.hasOwnProperty("enabled")?!!e.enabled:!0,t.enabled&&t.entity.enabled&&this._enabledComponents.append(t),e.hasOwnProperty("order")&&e.hasOwnProperty("scripts")){t._scriptsData=e.scripts;for(let s=0;s=0&&e._onBeforeRemove(),this._removeComponentFromEnabled(e),this._components.remove(e)}destroy(){super.destroy(),this.app.systems.off("initialize",this._onInitialize,this),this.app.systems.off("postInitialize",this._onPostInitialize,this),this.app.systems.off("update",this._onUpdate,this),this.app.systems.off("postUpdate",this._onPostUpdate,this)}};var wK=new B,DR=new Uint32Array(0),LR=[0,0],ZS=class{constructor(t,e,s,i=null,r=null,a=null){n(this,"device");n(this,"resource");n(this,"node");n(this,"lodIndex");n(this,"placementId");n(this,"allocId");n(this,"parentPlacementId");n(this,"numSplats");n(this,"activeSplats",0);n(this,"intervals",[]);n(this,"intervalOffsets",[]);n(this,"intervalAllocIds",[]);n(this,"intervalNodeIndices",[]);n(this,"previousWorldTransform",new W);n(this,"aabb",new ge);n(this,"subDrawTexture",null);n(this,"subDrawCount",0);n(this,"numBoundsEntries",0);n(this,"boundsBaseIndex",0);n(this,"octreeNodes",null);n(this,"nodeInfos",null);n(this,"colorAccumulatedTranslation",0);n(this,"parameters",null);n(this,"getWorkBufferModifier",null);n(this,"getInstanceStreams",null);n(this,"_consumeRenderDirty",null);this.device=t,this.resource=e,this.node=s.node,this.lodIndex=s.lodIndex,this.placementId=s.id,this.allocId=s.allocId,this.parentPlacementId=r&&s.parentPlacement?s.parentPlacement.allocId:s.allocId,this.numSplats=e.numSplats,this.aabb.copy(s.aabb),this.parameters=s.parameters,this.getWorkBufferModifier=()=>s.workBufferModifier,this.getInstanceStreams=()=>s.streams,this._consumeRenderDirty=i,this.octreeNodes=r,this.nodeInfos=a,this.updateIntervals(s.intervals)}destroy(){this.intervals.length=0,this.intervalOffsets.length=0,this.intervalAllocIds.length=0,this.intervalNodeIndices.length=0,this.subDrawTexture?.destroy(),this.subDrawTexture=null,this.subDrawCount=0}setLayout(t){this.intervalOffsets=t,this.subDrawTexture?.destroy(),this.subDrawTexture=null,this.subDrawCount=0}ensureSubDrawTexture(t){!this.subDrawTexture&&t>0&&this.updateSubDraws(t)}updateIntervals(t){let e=this.resource;if(this.intervals.length=0,this.intervalAllocIds.length=0,this.intervalNodeIndices.length=0,this.activeSplats=e.numSplats,t.size>0){let s=0,i=0;this.intervals.length=t.size*2;for(let[r,a]of t)this.intervals[i++]=a.x,this.intervals[i++]=a.y+1,s+=a.y-a.x+1,this.nodeInfos&&(this.intervalAllocIds.push(this.nodeInfos[r].allocId),this.intervalNodeIndices.push(r));this.octreeNodes?(this.activeSplats=s,this.numBoundsEntries=this.octreeNodes.length):s===this.numSplats?this.intervals.length=0:this.activeSplats=s}else{this.numBoundsEntries=1,this.intervalAllocIds.push(this.allocId);let s=e.maxSplats;s&&this.activeSplats0){let u=Math.min(o,a-h),d=e*4;t[d]=l|65536,t[d+1]=h,t[d+2]=h+u,t[d+3]=s,e++,s+=u,o-=u,l++}let f=o/a|0;if(f>0){let u=e*4;t[u]=l|f<<16,t[u+1]=0,t[u+2]=a,t[u+3]=s,e++,s+=f*a,o-=f*a,l+=f}if(o>0){let u=e*4;t[u]=l|65536,t[u+1]=0,t[u+2]=o,t[u+3]=s,e++}return e}updateSubDraws(t){let e=this.intervals,s=e.length/2;s===0&&(LR[0]=0,LR[1]=this.activeSplats,e=LR,s=1);let r=s*3*4;DR.length0}};function Ok(){let c=typeof self<"u"&&self||EC("node:worker_threads").parentPort,t=new Map,e,s,i,r,a=!1,o=!1,l=32,h=new Float32Array(l+1),f=new Float32Array(l+1),u=new GSplatSortBinWeights,d=E=>{for(let y=0;y{let{ids:O,intervals:G}=I,M=l/P,H=0;for(let U=0;U0?G[U]:[0,N.length/3];for(let z=0;z{p(E,y,P,A,w,I,(D,O,G,M,H,U,L,b,N,k)=>{let{transformedDirection:z,offset:V,scale:q}=O,re=z.x,te=z.y,j=z.z,oe=re*q,be=te*q,qe=j*q,ot=V-L;for(let Ve=G;Ve>>0,de=h[Qu]+f[Qu]*(di-Qu)>>>0;N[H++]=de,k[de]++}return H})},_=(E,y,P,A,w,I)=>{p(E,y,P,A,w,I,(D,O,G,M,H,U,L,b,N,k)=>{let{transformedPosition:z,scale:V}=O,q=z.x,re=z.y,te=z.z;for(let j=G;j>>0,Cs=h[ds]+f[ds]*(Vs-ds)>>>0;N[H++]=Cs,k[Cs]++}return H})},S=(E,y,P,A,w)=>{for(let D=1;D{let y=1/0,P=-1/0;for(let A=0;A=0?G[0]:M[0],N=U>=0?G[1]:M[1],k=L>=0?G[2]:M[2],z=H>=0?M[0]:G[0],V=U>=0?M[1]:G[1],q=L>=0?M[2]:G[2],re=b*H+N*U+k*L,te=z*H+V*U+q*L,j=re*O+D,oe=te*O+D,be=Math.min(j,oe),qe=Math.max(j,oe);beP&&(P=qe)}return y===1/0&&(y=0,P=0),{minDist:y,maxDist:P}},T=E=>{let y=-1/0;for(let A=0;Ay&&(y=te)}}let P=0;return y<0&&(y=0),{minDist:P,maxDist:y}},C=(E,y,P)=>{let A=performance.now(),{minDist:w,maxDist:I}=a?T(E):g(E),D=P.totalActiveSplats,G=2**Math.max(10,Math.min(20,Math.round(Math.log2(D/4))))+1;s?.length!==D&&(s=new Uint32Array(D)),!i||i.length!==G?i=new Uint32Array(G):i.fill(0);let M=I-w,H=GSplatSortBinWeights.computeCameraBin(a,w,M),U=u.compute(H,G);d(U),a?_(E,w,M,s,i,P):m(E,w,M,s,i,P),S(G,i,D,s,y);let L=D,b=performance.now()-A,N=[y.buffer],k={order:y.buffer,count:L,version:P.version,sortTime:b};c.postMessage(k,N)},v=E=>{let{ids:y,pixelOffsets:P,intervals:A,totalActiveSplats:w}=E;(!r||r.length0?A[D]:[0,O.length/3];for(let H=0;H{let y=E.data??E;switch(y.command){case"addCenters":{t.set(y.id,new Float32Array(y.centers));break}case"removeCenters":{t.delete(y.id);break}case"sort":{a=y.radialSorting||!1;let P=new Uint32Array(y.order);C(y.sortParams,P,e);break}case"intervals":{e=y,v(e);break}}})}var Cl=class c{static get NUM_BINS(){return 32}static get WEIGHT_TIERS(){return[{maxDistance:0,weight:40},{maxDistance:2,weight:20},{maxDistance:5,weight:8},{maxDistance:10,weight:3},{maxDistance:1/0,weight:1}]}constructor(){let t=c.NUM_BINS,e=c.WEIGHT_TIERS;this.binWeights=new Float32Array(t*2),this.bitsPerBin=new Float32Array(t),this.weightByDistance=new Float32Array(t);for(let s=0;se){let o=a-e,l=(s-1)*2+1;this.binWeights[l]=Math.max(1,this.binWeights[l]-o)}return this.binWeights}};var MR=new Set,nE=class extends J{constructor(e){super();n(this,"worker");n(this,"bufferLength",0);n(this,"availableOrderData",[]);n(this,"jobsInFlight",0);n(this,"hasNewVersion",!1);n(this,"pendingSorted",null);n(this,"centersSet",new Set);n(this,"_destroyed",!1);n(this,"scene",null);this.scene=e??null;let s=` const GSplatSortBinWeights = ${Cl.toString()}; (${Ok.toString()})() `;ue.environment==="node"?(this.worker=new Worker(s,{eval:!0}),this.worker.on("message",this.onSorted.bind(this))):(this.worker=new Worker(URL.createObjectURL(new Blob([s],{type:"application/javascript"}))),this.worker.addEventListener("message",this.onSorted.bind(this)))}onSorted(e){if(this._destroyed)return;let s=e.data??e;this.scene&&s.sortTime!==void 0&&this.scene.fire("gsplat:sorted",s.sortTime);let i=new Uint32Array(s.order);this.jobsInFlight--,this.pendingSorted&&this.releaseOrderData(this.pendingSorted.orderData),this.pendingSorted={count:s.count,version:s.version,orderData:i}}applyPendingSorted(){if(this.pendingSorted){let{count:e,version:s,orderData:i}=this.pendingSorted;this.pendingSorted=null,this.fire("sorted",e,s,i),this.releaseOrderData(i)}}releaseOrderData(e){e.length===this.bufferLength&&this.availableOrderData.push(e)}destroy(){this._destroyed=!0,this.pendingSorted=null,this.worker.terminate(),this.worker=null}setCenters(e,s){if(s){if(!this.centersSet.has(e)){this.centersSet.add(e);let i=s.buffer.slice();this.worker.postMessage({command:"addCenters",id:e,centers:i},[i])}}else this.centersSet.has(e)&&(this.centersSet.delete(e),this.worker.postMessage({command:"removeCenters",id:e}))}updateCentersForSplats(e){for(let s of e){let i=s.resource.id;MR.add(i),this.centersSet.has(i)||this.setCenters(i,s.resource.centers)}for(let s of this.centersSet)MR.has(s)||this.setCenters(s,null);MR.clear()}setSortParameters(e){this.hasNewVersion=!0;let{textureSize:s}=e,i=s*s;i!==this.bufferLength&&(this.bufferLength=i,this.availableOrderData.length=0),this.worker.postMessage(e)}setSortParams(e,s){if(this.hasNewVersion||this.jobsInFlight===0){let i=this.availableOrderData.pop();i||(i=new Uint32Array(this.bufferLength)),this.jobsInFlight++,this.hasNewVersion=!1,this.worker.postMessage({command:"sort",sortParams:e,radialSorting:s,order:i.buffer},[i.buffer])}}};var lE=` #include "tonemappingPS" #include "decodePS" #include "gammaPS" #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 sortElementCount: array; @group(0) @binding(1) var dispatchArgs: array; @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 countersBuffer: array; @group(0) @binding(1) var dispatchArgs: array; @group(0) @binding(2) var largeSplatIds: array; @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 compactedSplatIds: array; @group(0) @binding(1) var sortElementCount: array; @group(0) @binding(2) var projCache: array; @group(0) @binding(3) var tileSplatCounts: array>; 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 uniforms: Uniforms; @group(0) @binding(5) var pairBuffer: array; @group(0) @binding(6) var countersBuffer: array>; @group(0) @binding(7) var splatPairStart: array; @group(0) @binding(8) var splatPairCount: array; @group(0) @binding(9) var largeSplatIds: array; @group(0) @binding(10) var depthBuffer: array; #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(proj.screen.x); projCache[base + 1u] = bitcast(proj.screen.y); projCache[base + 2u] = bitcast(cx); projCache[base + 3u] = bitcast(cy); projCache[base + 4u] = bitcast(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(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(-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 projCache: array; @group(0) @binding(1) var tileSplatCounts: array>; @group(0) @binding(2) var pairBuffer: array; @group(0) @binding(3) var countersBuffer: array>; @group(0) @binding(4) var splatPairStart: array; @group(0) @binding(5) var splatPairCount: array; @group(0) @binding(6) var largeSplatIds: array; struct Uniforms { numTilesX: u32, numTilesY: u32, viewportWidth: f32, viewportHeight: f32, alphaClip: f32, } @group(0) @binding(7) var uniforms: Uniforms; var wgPairCounts: array; var wgPairOffsets: array; var 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(projCache[cacheBase + 0u]), bitcast(projCache[cacheBase + 1u])); cx = bitcast(projCache[cacheBase + 2u]); cy = bitcast(projCache[cacheBase + 3u]); cz = bitcast(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 pairBuffer: array; @group(0) @binding(1) var splatPairStart: array; @group(0) @binding(2) var splatPairCount: array; @group(0) @binding(3) var tileSplatCounts: array; @group(0) @binding(4) var tileEntries: array; @group(0) @binding(5) var sortElementCount: array; @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 pairBuffer: array; @group(0) @binding(1) var splatPairStart: array; @group(0) @binding(2) var splatPairCount: array; @group(0) @binding(3) var tileSplatCounts: array; @group(0) @binding(4) var tileEntries: array; @group(0) @binding(5) var largeSplatIds: array; @group(0) @binding(6) var countersBuffer: array; @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 tileEntries: array; @group(0) @binding(1) var tileSplatCounts: array; @group(0) @binding(2) var depthBuffer: array; @group(0) @binding(3) var smallTileList: array; @group(0) @binding(4) var tileListCounts: array; @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 tileSplatCounts: array; @group(0) @binding(1) var smallTileList: array; @group(0) @binding(2) var largeTileList: array; @group(0) @binding(3) var rasterizeTileList: array; @group(0) @binding(4) var tileListCounts: array>; @group(0) @binding(5) var indirectDispatchArgs: array; @group(0) @binding(6) var largeTileOverflowBases: array; @group(0) @binding(8) var indirectDrawArgs: array; struct Uniforms { numTiles: u32, dispatchSlotOffset: u32, bufferCapacity: u32, maxWorkgroupsPerDim: u32, drawSlot: u32, } @group(0) @binding(7) var 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 tileEntries: array; @group(0) @binding(1) var largeTileOverflowBases: array; @group(0) @binding(2) var tileSplatCounts: array; @group(0) @binding(3) var depthBuffer: array; @group(0) @binding(4) var largeTileList: array; @group(0) @binding(5) var chunkRanges: array; @group(0) @binding(6) var totalChunks: array>; @group(0) @binding(7) var tileListCounts: array; struct Uniforms { bufferCapacity: u32, maxChunks: u32, } @group(0) @binding(8) var uniforms: Uniforms; var sDepthMin: atomic; var sDepthMax: atomic; var sBucketCounts: array, NUM_BUCKETS>; var sBucketOffsets: array; var sBucketCursors: array, 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(depthMinU); let depthMax = bitcast(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(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(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 tileEntries: array; @group(0) @binding(1) var depthBuffer: array; @group(0) @binding(2) var chunkRanges: array; @group(0) @binding(3) var totalChunks: array; struct Uniforms { maxChunks: u32, } @group(0) @binding(4) var 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 totalChunks: array; @group(0) @binding(1) var chunkSortIndirect: array; struct Uniforms { maxChunks: u32, maxWorkgroupsPerDim: u32, } @group(0) @binding(2) var 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 sData: array; var sDepthMin: atomic; var sDepthMax: atomic; 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(depthMinU); let depthMax = bitcast(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(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 uniforms: Uniforms; @group(0) @binding(1) var tileEntries: array; @group(0) @binding(2) var tileSplatCounts: array; @group(0) @binding(3) var projCache: array; @group(0) @binding(4) var rasterizeTileList: array; @group(0) @binding(5) var tileListCounts: array; @group(0) @binding(6) var depthBuffer: array; #ifdef PICK_MODE @group(0) @binding(7) var pickIdTexture: texture_storage_2d; @group(0) @binding(8) var pickDepthTexture: texture_storage_2d; #else @group(0) @binding(7) var outputTexture: texture_storage_2d; #ifdef DEPTH_TEST @group(0) @binding(8) var sceneDepthMap: texture_2d; #endif #endif var sharedCenterScreen: array; var sharedCoeffs: array; var sharedPowerCutoff: array; #ifdef HEATMAP_MODE var sharedHeatCount: atomic; #endif #ifdef PICK_MODE var sharedOpacity: array; var sharedPickId: array; var sharedViewDepth: array; #else var sharedColor: array; #ifdef DEPTH_TEST var sharedViewDepth: array; #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, depthAccum: ptr, weightAccum: ptr, T: ptr) { 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(projCache[base + 0u]), bitcast(projCache[base + 1u]) ); let cx = bitcast(projCache[base + 2u]); let cy = bitcast(projCache[base + 3u]); let cz = bitcast(projCache[base + 4u]); sharedCoeffs[localIdx] = vec3f(cx * -0.5, cz * -0.5, -cy); sharedPowerCutoff[localIdx] = bitcast(projCache[base + 7u]); #ifdef PICK_MODE sharedPickId[localIdx] = projCache[base + 5u]; sharedOpacity[localIdx] = half(unpack2x16float(projCache[base + 6u]).y); sharedViewDepth[localIdx] = bitcast(depthBuffer[cacheIdx]); #else let rg = unpack2x16float(projCache[base + 5u]); let ba = unpack2x16float(projCache[base + 6u]); #if FOG != NONE let viewDepth = bitcast(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(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(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 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=bK&&e>0){let f=Math.max(FR,r/e*qk);this._tileEntryMultiplier=Math.max(f,this._tileEntryMultiplier*.9),this._shrinkFrameCount=0}}if(!i)return;e>this._allocatedSplatCapacity&&(this._projCacheBuffer?.destroy(),this._depthBuffer?.destroy(),this._splatPairStartBuffer?.destroy(),this._splatPairCountBuffer?.destroy(),this._allocatedSplatCapacity=e,this._projCacheBuffer=new Ee(s,e*u_*4),this._depthBuffer=new Ee(s,e*4),this._splatPairStartBuffer=new Ee(s,e*4),this._splatPairCountBuffer=new Ee(s,e*4)),this._countersBuffer||(this._countersBuffer=new Ee(s,8,12)),this._largeSplatIdsCapacity>this._allocatedLargeSplatCapacity&&(this._largeSplatIdsBuffer?.destroy(),this._allocatedLargeSplatCapacity=this._largeSplatIdsCapacity,this._largeSplatIdsBuffer=new Ee(s,this._largeSplatIdsCapacity*4));let a=Math.ceil(e*this._tileEntryMultiplier),o=a>this._allocatedEntryCapacity,l=this._allocatedEntryCapacity>0&&a*2Zk){let U=Math.sqrt(Zk/(l*h));l=Math.max(1,Math.floor(l*U)),h=Math.max(1,Math.floor(h*U))}let f=l*h;this._ensureSharedBuffers(a),e.ensureTileBuffers(f);let u=this._allocatedEntryCapacity,d=this._dataSource,p=this.cameraNode.camera,m=p.camera,_=m.viewMatrix,S=!!p.renderTarget?.flipY,g=o.isWebGPU;Qk.mul2(Bs.applyShaderProjectionTransform(m.projectionMatrix,tz,S,g),_),Jk.set(Qk.data),ez.set(_.data);let T=s*tz.data[0],C=r?this._alphaClip:Math.max(f_,this._alphaClipForward);this.fisheyeProj.update(this._fisheye,p.fov,m.projectionMatrix);let v=this.fisheyeProj.enabled,E=(U,L)=>this._createCountShaderAndFormat(U,L),y=e.getCountCompute(v,E);this._placeEntryPrepCompute.setParameter("sortElementCount",this._sortElementCountBuffer),this._placeEntryPrepCompute.setParameter("dispatchArgs",this._placeEntryPrepDispatchBuffer),this._placeEntryPrepCompute.setupDispatch(1,1,1),o.computeDispatch([this._placeEntryPrepCompute],"GSplatLocalDispatchPrep"),e._tileSplatCountsBuffer.clear(),this._countersBuffer.clear(),y.setParameter("compactedSplatIds",this._compactedSplatIds),y.setParameter("sortElementCount",this._sortElementCountBuffer),y.setParameter("projCache",this._projCacheBuffer),y.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),y.setParameter("pairBuffer",this._pairBuffer),y.setParameter("countersBuffer",this._countersBuffer),y.setParameter("splatPairStart",this._splatPairStartBuffer),y.setParameter("splatPairCount",this._splatPairCountBuffer),y.setParameter("largeSplatIds",this._largeSplatIdsBuffer),y.setParameter("depthBuffer",this._depthBuffer);for(let U of d.format.streams)y.setParameter(U.name,d.getTexture(U.name));for(let U of d.format.extraStreams)y.setParameter(U.name,d.getTexture(U.name));if(y.setParameter("splatTextureSize",this._textureSize),y.setParameter("numTilesX",l),y.setParameter("numTilesY",h),y.setParameter("viewProj",Jk),y.setParameter("viewMatrix",ez),y.setParameter("focal",T),y.setParameter("viewportWidth",s),y.setParameter("viewportHeight",i),y.setParameter("nearClip",m.nearClip),y.setParameter("farClip",m.farClip),y.setParameter("minPixelSize",this._minPixelSize*.5),y.setParameter("isOrtho",m.projection===ni?1:0),y.setParameter("exposure",this._exposure),y.setParameter("alphaClip",C),y.setParameter("minContribution",this._minContribution),v){let U=this.fisheyeProj;y.setParameter("fisheye_k",U.k),y.setParameter("fisheye_inv_k",U.invK),y.setParameter("fisheye_projMat00",U.projMat00),y.setParameter("fisheye_projMat11",U.projMat11)}y.setupIndirectDispatch(0,this._placeEntryPrepDispatchBuffer),o.computeDispatch([y],r?"GSplatPickTileCount":"GSplatLocalTileCount"),this._largeSplatPrepCompute.setParameter("countersBuffer",this._countersBuffer),this._largeSplatPrepCompute.setParameter("dispatchArgs",this._largeSplatDispatchBuffer),this._largeSplatPrepCompute.setParameter("largeSplatIds",this._largeSplatIdsBuffer),this._largeSplatPrepCompute.setupDispatch(1,1,1),o.computeDispatch([this._largeSplatPrepCompute],r?"GSplatPickLargeSplatPrep":"GSplatLocalLargeSplatPrep"),e.largeSplatCompute.setParameter("projCache",this._projCacheBuffer),e.largeSplatCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.largeSplatCompute.setParameter("pairBuffer",this._pairBuffer),e.largeSplatCompute.setParameter("countersBuffer",this._countersBuffer),e.largeSplatCompute.setParameter("splatPairStart",this._splatPairStartBuffer),e.largeSplatCompute.setParameter("splatPairCount",this._splatPairCountBuffer),e.largeSplatCompute.setParameter("largeSplatIds",this._largeSplatIdsBuffer),e.largeSplatCompute.setParameter("numTilesX",l),e.largeSplatCompute.setParameter("numTilesY",h),e.largeSplatCompute.setParameter("viewportWidth",s),e.largeSplatCompute.setParameter("viewportHeight",i),e.largeSplatCompute.setParameter("alphaClip",C),e.largeSplatCompute.setupIndirectDispatch(0,this._largeSplatDispatchBuffer),o.computeDispatch([e.largeSplatCompute],r?"GSplatPickLargeTileCount":"GSplatLocalLargeTileCount"),e.prefixSumKernel.resize(e._tileSplatCountsBuffer,f+1),e.prefixSumKernel.dispatch(o),e.placeEntriesCompute.setParameter("pairBuffer",this._pairBuffer),e.placeEntriesCompute.setParameter("splatPairStart",this._splatPairStartBuffer),e.placeEntriesCompute.setParameter("splatPairCount",this._splatPairCountBuffer),e.placeEntriesCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.placeEntriesCompute.setParameter("tileEntries",this._tileEntriesBuffer),e.placeEntriesCompute.setParameter("sortElementCount",this._sortElementCountBuffer),e.placeEntriesCompute.setupIndirectDispatch(1,this._placeEntryPrepDispatchBuffer),o.computeDispatch([e.placeEntriesCompute],r?"GSplatPickPlaceEntries":"GSplatLocalPlaceEntries"),e.largePlaceEntriesCompute.setParameter("pairBuffer",this._pairBuffer),e.largePlaceEntriesCompute.setParameter("splatPairStart",this._splatPairStartBuffer),e.largePlaceEntriesCompute.setParameter("splatPairCount",this._splatPairCountBuffer),e.largePlaceEntriesCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.largePlaceEntriesCompute.setParameter("tileEntries",this._tileEntriesBuffer),e.largePlaceEntriesCompute.setParameter("largeSplatIds",this._largeSplatIdsBuffer),e.largePlaceEntriesCompute.setParameter("countersBuffer",this._countersBuffer),e.largePlaceEntriesCompute.setupIndirectDispatch(0,this._largeSplatDispatchBuffer),o.computeDispatch([e.largePlaceEntriesCompute],r?"GSplatPickLargePlaceEntries":"GSplatLocalLargePlaceEntries"),e._tileListCountsBuffer.clear(),e._totalChunksBuffer.clear(),e._chunkSortIndirectBuffer.clear();let P=o.getIndirectDispatchSlot(3),A=o.getIndirectDrawSlot(1);e.classifyCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.classifyCompute.setParameter("smallTileList",e._smallTileListBuffer),e.classifyCompute.setParameter("largeTileList",e._largeTileListBuffer),e.classifyCompute.setParameter("rasterizeTileList",e._rasterizeTileListBuffer),e.classifyCompute.setParameter("tileListCounts",e._tileListCountsBuffer),e.classifyCompute.setParameter("indirectDispatchArgs",o.indirectDispatchBuffer),e.classifyCompute.setParameter("largeTileOverflowBases",e._largeTileOverflowBasesBuffer),e.classifyCompute.setParameter("indirectDrawArgs",o.indirectDrawBuffer),e.classifyCompute.setParameter("numTiles",f),e.classifyCompute.setParameter("dispatchSlotOffset",P*3),e.classifyCompute.setParameter("bufferCapacity",u),e.classifyCompute.setParameter("maxWorkgroupsPerDim",o.limits.maxComputeWorkgroupsPerDimension||65535),e.classifyCompute.setParameter("drawSlot",A),e.classifyCompute.setupDispatch(1,1,1),o.computeDispatch([e.classifyCompute],r?"GSplatPickClassify":"GSplatLocalClassify"),e.bucketSortCompute.setParameter("tileEntries",this._tileEntriesBuffer),e.bucketSortCompute.setParameter("largeTileOverflowBases",e._largeTileOverflowBasesBuffer),e.bucketSortCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.bucketSortCompute.setParameter("depthBuffer",this._depthBuffer),e.bucketSortCompute.setParameter("largeTileList",e._largeTileListBuffer),e.bucketSortCompute.setParameter("chunkRanges",e._chunkRangesBuffer),e.bucketSortCompute.setParameter("totalChunks",e._totalChunksBuffer),e.bucketSortCompute.setParameter("tileListCounts",e._tileListCountsBuffer),e.bucketSortCompute.setParameter("bufferCapacity",u),e.bucketSortCompute.setParameter("maxChunks",f*NR),e.bucketSortCompute.setupIndirectDispatch(P+1),o.computeDispatch([e.bucketSortCompute],r?"GSplatPickBucketSort":"GSplatLocalBucketSort"),e.copyCompute.setParameter("totalChunks",e._totalChunksBuffer),e.copyCompute.setParameter("chunkSortIndirect",e._chunkSortIndirectBuffer),e.copyCompute.setParameter("maxChunks",f*NR),e.copyCompute.setParameter("maxWorkgroupsPerDim",o.limits.maxComputeWorkgroupsPerDimension||65535),e.copyCompute.setupDispatch(1,1,1),o.computeDispatch([e.copyCompute],r?"GSplatPickCopy":"GSplatLocalCopy"),e.sortCompute.setParameter("tileEntries",this._tileEntriesBuffer),e.sortCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.sortCompute.setParameter("depthBuffer",this._depthBuffer),e.sortCompute.setParameter("smallTileList",e._smallTileListBuffer),e.sortCompute.setParameter("tileListCounts",e._tileListCountsBuffer),e.sortCompute.setupIndirectDispatch(P),o.computeDispatch([e.sortCompute],r?"GSplatPickTileSort":"GSplatLocalTileSort"),e.chunkSortCompute.setParameter("tileEntries",this._tileEntriesBuffer),e.chunkSortCompute.setParameter("depthBuffer",this._depthBuffer),e.chunkSortCompute.setParameter("chunkRanges",e._chunkRangesBuffer),e.chunkSortCompute.setParameter("totalChunks",e._totalChunksBuffer),e.chunkSortCompute.setParameter("maxChunks",f*NR),e.chunkSortCompute.setupIndirectDispatch(0,e._chunkSortIndirectBuffer),o.computeDispatch([e.chunkSortCompute],r?"GSplatPickChunkSort":"GSplatLocalChunkSort");let I=m.shaderParams.sceneDepthMapLinear?o.scope.resolve("uSceneDepthMap").value:null,D=!r&&I,O=this._fogParams,G=O&&O.type!==Mi?O.type:"none",M=!r&&this._debugMode===Ep,H=e.getRasterizeCompute(r,D,G,M);H.setParameter("screenWidth",s),H.setParameter("screenHeight",i),H.setParameter("numTilesX",l),H.setParameter("nearClip",m.nearClip),H.setParameter("farClip",m.farClip),H.setParameter("alphaClip",C),G!=="none"&&(SE.linear(O.color),xE[0]=SE.r,xE[1]=SE.g,xE[2]=SE.b,H.setParameter("fog_color",xE),H.setParameter("fog_start",O.start),H.setParameter("fog_end",O.end),H.setParameter("fog_density",O.density)),H.setParameter("tileEntries",this._tileEntriesBuffer),H.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),H.setParameter("projCache",this._projCacheBuffer),H.setParameter("rasterizeTileList",e._rasterizeTileListBuffer),H.setParameter("tileListCounts",e._tileListCountsBuffer),H.setParameter("depthBuffer",this._depthBuffer),r?(H.setParameter("pickIdTexture",e.pickIdTexture),H.setParameter("pickDepthTexture",e.pickDepthTexture)):(H.setParameter("outputTexture",e.outputTexture),D&&H.setParameter("sceneDepthMap",I)),H.setupIndirectDispatch(P+2),o.computeDispatch([H],r?"GSplatPickRasterize":"GSplatLocalRasterize"),this._lastDrawSlot=A,this._lastNumTilesX=l,this._scheduleReadback(a,f,e)}_scheduleReadback(e,s,i){if(e===0)return;let r=e,a=i._tileSplatCountsBuffer.read(s*4,4),o=i._tileListCountsBuffer.read(12,4),l=this._countersBuffer.read(4,4);Promise.all([a,o,l]).then(([h,f,u])=>{let d=new Uint32Array(h.buffer,h.byteOffset,1)[0],p=new Uint32Array(f.buffer,f.byteOffset,1)[0],m=d+p;r>0&&(this._tileEntryMultiplier=Math.max(this._tileEntryMultiplier,m/r*qk),this._tileEntryMultiplier=Math.max(this._tileEntryMultiplier,FR)),this._lastReadbackEntryCount=m;let _=new Uint32Array(u.buffer,u.byteOffset,1)[0];_>this._largeSplatIdsCapacity&&(this._largeSplatIdsCapacity=Math.ceil(_*1.2))}).catch(()=>{})}_invalidateCountCompute(){this._mainSet.destroyCountResources(),this._pickSet?.destroyCountResources()}_createCommonIncludes(){let e=new Map;return e.set("gsplatCommonCS",dE),e.set("gsplatTileIntersectCS",pE),e}_createBitonicIncludes(){let e=new Map;return e.set("gsplatLocalBitonicCS",Kk),e}_createSharedShaders(){let e=this.device;this._placeEntriesBindGroupFormat=new Ue(e,[new K("pairBuffer",X,!0),new K("splatPairStart",X,!0),new K("splatPairCount",X,!0),new K("tileSplatCounts",X,!0),new K("tileEntries",X),new K("sortElementCount",X,!0)]),this._placeEntriesShader=new Be(e,{name:"GSplatLocalPlaceEntries",shaderLanguage:se,cshader:zk,computeBindGroupFormat:this._placeEntriesBindGroupFormat});{let s=e.limits.maxComputeWorkgroupsPerDimension||65535,i=new Map;i.set("{MAX_DIM}",s.toString()),i.set("{SPLATS_PER_WG}","256"),i.set("{SPLATS_PER_WG_MINUS_1}","255"),this._placeEntryPrepBindGroupFormat=new Ue(e,[new K("sortElementCount",X,!0),new K("dispatchArgs",X)]),this._placeEntryPrepShader=new Be(e,{name:"GSplatLocalPlaceEntryPrep",shaderLanguage:se,cshader:Nk,cdefines:i,computeBindGroupFormat:this._placeEntryPrepBindGroupFormat}),this._placeEntryPrepDispatchBuffer=new Ee(e,24,256),this._placeEntryPrepCompute=new Ye(e,this._placeEntryPrepShader)}{let s=this._createCommonIncludes(),i=new Xe(e,[new Y("numTilesX",pe),new Y("numTilesY",pe),new Y("viewportWidth",Te),new Y("viewportHeight",Te),new Y("alphaClip",Te)]);this._largeSplatBindGroupFormat=new Ue(e,[new K("projCache",X,!0),new K("tileSplatCounts",X),new K("pairBuffer",X),new K("countersBuffer",X),new K("splatPairStart",X),new K("splatPairCount",X),new K("largeSplatIds",X,!0),new Qe("uniforms",X)]);let r=new Map;r.set("{CACHE_STRIDE}",u_.toString()),this._largeSplatShader=new Be(e,{name:"GSplatLocalTileCountLarge",shaderLanguage:se,cshader:kk,cincludes:s,cdefines:r,computeBindGroupFormat:this._largeSplatBindGroupFormat,computeUniformBufferFormats:{uniforms:i}})}{let s=e.limits.maxComputeWorkgroupsPerDimension||65535,i=new Map;i.set("{MAX_DIM}",s.toString()),this._largeSplatPrepBindGroupFormat=new Ue(e,[new K("countersBuffer",X,!0),new K("dispatchArgs",X),new K("largeSplatIds",X,!0)]),this._largeSplatPrepShader=new Be(e,{name:"GSplatLocalLargeSplatPrep",shaderLanguage:se,cshader:Bk,cdefines:i,computeBindGroupFormat:this._largeSplatPrepBindGroupFormat}),this._largeSplatDispatchBuffer=new Ee(e,12,256),this._largeSplatPrepCompute=new Ye(e,this._largeSplatPrepShader)}this._largePlaceEntriesBindGroupFormat=new Ue(e,[new K("pairBuffer",X,!0),new K("splatPairStart",X,!0),new K("splatPairCount",X,!0),new K("tileSplatCounts",X,!0),new K("tileEntries",X),new K("largeSplatIds",X,!0),new K("countersBuffer",X,!0)]),this._largePlaceEntriesShader=new Be(e,{name:"GSplatLocalPlaceEntriesLarge",shaderLanguage:se,cshader:Gk,computeBindGroupFormat:this._largePlaceEntriesBindGroupFormat});{let s=new Xe(e,[new Y("numTiles",pe),new Y("dispatchSlotOffset",pe),new Y("bufferCapacity",pe),new Y("maxWorkgroupsPerDim",pe),new Y("drawSlot",pe)]);this._classifyBindGroupFormat=new Ue(e,[new K("tileSplatCounts",X,!0),new K("smallTileList",X),new K("largeTileList",X),new K("rasterizeTileList",X),new K("tileListCounts",X),new K("indirectDispatchArgs",X),new K("largeTileOverflowBases",X),new Qe("uniforms",X),new K("indirectDrawArgs",X)]),this._classifyShader=new Be(e,{name:"GSplatLocalClassify",shaderLanguage:se,cshader:Hk,computeBindGroupFormat:this._classifyBindGroupFormat,computeUniformBufferFormats:{uniforms:s}})}this._sortBindGroupFormat=new Ue(e,[new K("tileEntries",X),new K("tileSplatCounts",X,!0),new K("depthBuffer",X,!0),new K("smallTileList",X,!0),new K("tileListCounts",X,!0)]),this._sortShader=new Be(e,{name:"GSplatLocalTileSort",shaderLanguage:se,cshader:Vk,cincludes:this._createBitonicIncludes(),computeBindGroupFormat:this._sortBindGroupFormat});{let s=new Xe(e,[new Y("bufferCapacity",pe),new Y("maxChunks",pe)]);this._bucketSortBindGroupFormat=new Ue(e,[new K("tileEntries",X),new K("largeTileOverflowBases",X,!0),new K("tileSplatCounts",X,!0),new K("depthBuffer",X,!0),new K("largeTileList",X,!0),new K("chunkRanges",X),new K("totalChunks",X),new K("tileListCounts",X,!0),new Qe("uniforms",X)]),this._bucketSortShader=new Be(e,{name:"GSplatLocalBucketSort",shaderLanguage:se,cshader:Wk,computeBindGroupFormat:this._bucketSortBindGroupFormat,computeUniformBufferFormats:{uniforms:s}})}{let s=new Xe(e,[new Y("maxChunks",pe),new Y("maxWorkgroupsPerDim",pe)]);this._copyBindGroupFormat=new Ue(e,[new K("totalChunks",X,!0),new K("chunkSortIndirect",X),new Qe("uniforms",X)]),this._copyShader=new Be(e,{name:"GSplatLocalCopy",shaderLanguage:se,cshader:Yk,computeBindGroupFormat:this._copyBindGroupFormat,computeUniformBufferFormats:{uniforms:s}})}{let s=new Xe(e,[new Y("maxChunks",pe)]);this._chunkSortBindGroupFormat=new Ue(e,[new K("tileEntries",X),new K("depthBuffer",X,!0),new K("chunkRanges",X,!0),new K("totalChunks",X,!0),new Qe("uniforms",X)]),this._chunkSortShader=new Be(e,{name:"GSplatLocalChunkSort",shaderLanguage:se,cshader:Xk,cincludes:this._createBitonicIncludes(),computeBindGroupFormat:this._chunkSortBindGroupFormat,computeUniformBufferFormats:{uniforms:s}})}}_createCountShaderAndFormat(e,s){let i=this.device,r=[new Y("splatTextureSize",pe),new Y("numTilesX",pe),new Y("numTilesY",pe),new Y("viewProj",as),new Y("viewMatrix",as),new Y("focal",Te),new Y("viewportWidth",Te),new Y("viewportHeight",Te),new Y("nearClip",Te),new Y("farClip",Te),new Y("minPixelSize",Te),new Y("isOrtho",pe),new Y("exposure",Te),new Y("alphaClip",Te),new Y("minContribution",Te)];s&&r.push(new Y("fisheye_k",Te),new Y("fisheye_inv_k",Te),new Y("fisheye_projMat00",Te),new Y("fisheye_projMat11",Te));let a=new Xe(i,r),o=this._dataSource.format,l=[new K("compactedSplatIds",X,!0),new K("sortElementCount",X,!0),new K("projCache",X),new K("tileSplatCounts",X),new Qe("uniforms",X),new K("pairBuffer",X),new K("countersBuffer",X),new K("splatPairStart",X),new K("splatPairCount",X),new K("largeSplatIds",X),new K("depthBuffer",X)],h=new Ue(i,[...l,...o.getComputeBindFormats()]),f=this._createCommonIncludes();f.set("gsplatComputeSplatCS",gE),f.set("gsplatFormatDeclCS",o.getComputeInputDeclarations(l.length)),f.set("gsplatFormatReadCS",o.getReadCode()),f.set("gsplatProjectCommonCS",uE);let u=new Map;u.set("{CACHE_STRIDE}",u_.toString()),s&&u.set("GSPLAT_FISHEYE",""),e&&u.set("PICK_MODE","");let d=o.getStream("dataColor");d&&d.format!==Rs&&u.set("GSPLAT_COLOR_FLOAT","");let p=s?"Fisheye":"";return{shader:new Be(i,{name:e?`GSplatLocalTileCountPick${p}`:`GSplatLocalTileCount${p}`,shaderLanguage:se,cshader:Uk,cincludes:f,cdefines:u,computeBindGroupFormat:h,computeUniformBufferFormats:{uniforms:a}}),bindGroupFormat:h}}_createDispatchSet(e){let s=this.device,i=new _E(s,e);return i.placeEntriesCompute=new Ye(s,this._placeEntriesShader,e?"GSplatPickPlaceEntries":"GSplatLocalPlaceEntries"),i.largeSplatCompute=new Ye(s,this._largeSplatShader,e?"GSplatPickLargeTileCount":"GSplatLocalLargeTileCount"),i.largePlaceEntriesCompute=new Ye(s,this._largePlaceEntriesShader,e?"GSplatPickLargePlaceEntries":"GSplatLocalLargePlaceEntries"),i.classifyCompute=new Ye(s,this._classifyShader,e?"GSplatPickClassify":"GSplatLocalClassify"),i.sortCompute=new Ye(s,this._sortShader,e?"GSplatPickTileSort":"GSplatLocalTileSort"),i.bucketSortCompute=new Ye(s,this._bucketSortShader,e?"GSplatPickBucketSort":"GSplatLocalBucketSort"),i.copyCompute=new Ye(s,this._copyShader,e?"GSplatPickCopy":"GSplatLocalCopy"),i.chunkSortCompute=new Ye(s,this._chunkSortShader,e?"GSplatPickChunkSort":"GSplatLocalChunkSort"),i}};var sz=` #include "gsplatCommonCS" #include "gsplatTileIntersectCS" @group(0) @binding(0) var compactedSplatIds: array; @group(0) @binding(1) var sortElementCount: array; @group(0) @binding(2) var projCache: array; @group(0) @binding(3) var sortKeys: array; @group(0) @binding(4) var renderCounter: array>; struct BinWeight { base: f32, divider: f32 } @group(0) @binding(5) var binWeights: array; struct ProjectorUniforms { splatTextureSize: u32, numBins: u32, isOrtho: u32, pad0: u32, viewProj: mat4x4f, viewMatrix: mat4x4f, cameraPosition: vec3f, minPixelSize: f32, cameraDirection: vec3f, focal: f32, viewportWidth: f32, viewportHeight: f32, nearClip: f32, farClip: f32, alphaClip: f32, minContribution: f32, minDist: f32, invRange: f32, #ifdef GSPLAT_FISHEYE fisheye_k: f32, fisheye_inv_k: f32, fisheye_projMat00: f32, fisheye_projMat11: f32, #endif } @group(0) @binding(6) var uniforms: ProjectorUniforms; #include "gsplatComputeSplatCS" #include "gsplatFormatDeclCS" #include "gsplatFormatReadCS" #include "gsplatProjectCommonCS" var wgCount: atomic; var wgBase: u32; @compute @workgroup_size(256) fn main( @builtin(global_invocation_id) gid: vec3u, @builtin(num_workgroups) numWorkgroups: vec3u, @builtin(local_invocation_index) localIdx: u32 ) { if (localIdx == 0u) { atomicStore(&wgCount, 0u); } workgroupBarrier(); let threadIdx = gid.y * (numWorkgroups.x * 256u) + gid.x; let numVisible = sortElementCount[0]; var valid = false; var clipPos: vec4f = vec4f(0.0); var v1: vec2f = vec2f(0.0); var v2: vec2f = vec2f(0.0); var rgb: vec3f = vec3f(0.0); var alpha: f32 = 0.0; var pcId: u32 = 0u; var sortKey: u32 = 0u; let projected = projectSplatCommon( threadIdx, numVisible, uniforms.alphaClip, uniforms.minPixelSize, uniforms.minContribution, uniforms.viewMatrix, uniforms.viewProj, uniforms.focal, uniforms.viewportWidth, uniforms.viewportHeight, uniforms.nearClip, uniforms.farClip, uniforms.isOrtho, #ifdef GSPLAT_FISHEYE uniforms.fisheye_k, uniforms.fisheye_inv_k, uniforms.fisheye_projMat00, uniforms.fisheye_projMat11, #endif ); if (projected.valid) { let center = projected.center; let opacity = projected.opacity; let proj = projected.proj; let mid = 0.5 * (proj.a + proj.c); let radius = length(vec2f(0.5 * (proj.a - proj.c), proj.b)); let lambda1 = mid + radius; let lambda2 = max(mid - radius, 0.1); let vmin = min(1024.0, min(uniforms.viewportWidth, uniforms.viewportHeight)); let l1 = 2.0 * min(sqrt(2.0 * lambda1), vmin); let l2 = 2.0 * min(sqrt(2.0 * lambda2), vmin); let dir = normalize(vec2f(proj.b, lambda1 - proj.a)); v1 = l1 * dir; v2 = l2 * vec2f(dir.y, -dir.x); #ifdef GSPLAT_FISHEYE let viewCenter = uniforms.viewMatrix * vec4f(center, 1.0); let neg_z = -viewCenter.z; let ndcX = proj.screen.x / uniforms.viewportWidth * 2.0 - 1.0; let ndcY = proj.screen.y / uniforms.viewportHeight * 2.0 - 1.0; let depthNdc = clamp( (neg_z - uniforms.nearClip) / (uniforms.farClip - uniforms.nearClip), 0.0, 1.0 ); clipPos = vec4f(ndcX, ndcY, depthNdc, 1.0); #else clipPos = uniforms.viewProj * vec4f(center, 1.0); clipPos.z = clamp(clipPos.z, 0.0, abs(clipPos.w)); #endif #ifdef RADIAL_SORT let delta = center - uniforms.cameraPosition; let radialDist = length(delta); let dist = (1.0 / uniforms.invRange) - radialDist - uniforms.minDist; #else let toSplat = center - uniforms.cameraPosition; let dist = dot(toSplat, uniforms.cameraDirection) - uniforms.minDist; #endif let d = dist * uniforms.invRange * f32(uniforms.numBins); let binFloat = clamp(d, 0.0, f32(uniforms.numBins) - 0.001); let bin = u32(binFloat); let binFrac = binFloat - f32(bin); sortKey = u32(binWeights[bin].base + binWeights[bin].divider * binFrac); #ifdef PICK_MODE pcId = loadPcId().r; alpha = opacity; #else let color = getColor(); rgb = max(color, vec3f(0.0)); #if GSPLAT_AA alpha = opacity * proj.aaFactor; #else alpha = opacity; #endif #endif valid = true; } var localDst: u32 = 0u; if (valid) { localDst = atomicAdd(&wgCount, 1u); } workgroupBarrier(); if (localIdx == 0u) { let total = atomicLoad(&wgCount); wgBase = atomicAdd(&renderCounter[0], total); } workgroupBarrier(); if (valid) { let dst = wgBase + localDst; let base = dst * {CACHE_STRIDE}u; projCache[base + 0u] = bitcast(clipPos.x); projCache[base + 1u] = bitcast(clipPos.y); projCache[base + 2u] = bitcast(clipPos.z); projCache[base + 3u] = bitcast(clipPos.w); projCache[base + 4u] = pack2x16float(v1); projCache[base + 5u] = pack2x16float(v2); #ifdef PICK_MODE projCache[base + 6u] = pcId; projCache[base + 7u] = pack2x16float(vec2f(0.0, alpha)); #else projCache[base + 6u] = pack2x16float(vec2f(rgb.x, rgb.y)); projCache[base + 7u] = pack2x16float(vec2f(rgb.z, alpha)); #endif sortKeys[dst] = sortKey; } } `;var iz=` ${Jc} ${_h} ${vm} @group(0) @binding(0) var renderCounter: array; @group(0) @binding(1) var indirectDrawArgs: array; @group(0) @binding(2) var numSplatsBuf: array; @group(0) @binding(3) var indirectDispatchArgs: array; @group(0) @binding(4) var sortElementCountBuf: array; struct WriteArgsUniforms { drawSlot: u32, indexCount: u32, sortSlotBase: u32, pad0: u32, sortIndirectInfo: vec4 }; @group(0) @binding(5) var uniforms: WriteArgsUniforms; @compute @workgroup_size(1) fn main() { let count = renderCounter[0]; let instanceCount = (count + {INSTANCE_SIZE}u - 1u) / {INSTANCE_SIZE}u; indirectDrawArgs[uniforms.drawSlot] = DrawIndexedIndirectArgs( uniforms.indexCount, instanceCount, 0u, 0, 0u ); numSplatsBuf[0] = count; sortElementCountBuf[0] = count; writeSortIndirectArgs(uniforms.sortSlotBase, count, uniforms.sortIndirectInfo); } `;var LK=6*rt.instanceSize,MK=256,OK=new x,BR=new B,rz=new W,az=new Float32Array(16),oz=new Float32Array(16),nz=new W,TE=class{constructor(t){n(this,"device");n(this,"projCache",null);n(this,"sortKeys",null);n(this,"renderCounter",null);n(this,"binWeightsBuffer",null);n(this,"binWeightsUtil");n(this,"_projectorComputes",new Map);n(this,"_projectorBindGroupFormat",null);n(this,"_projectorUniformBufferFormat",null);n(this,"_projectorUniformBufferFormatFisheye",null);n(this,"_writeIndirectArgsCompute",null);n(this,"_writeArgsBindGroupFormat",null);n(this,"_writeArgsUniformBufferFormat",null);n(this,"_formatVersion",-1);n(this,"_allocatedCacheCount",0);n(this,"cameraPositionData",new Float32Array(3));n(this,"cameraDirectionData",new Float32Array(3));this.device=t,this.binWeightsUtil=new Cl,this.binWeightsBuffer=new Ee(t,Cl.NUM_BINS*2*4,12),this.renderCounter=new Ee(t,4,12),this._createUniformBufferFormats(),this._createWriteIndirectArgsCompute()}destroy(){this.projCache?.destroy(),this.sortKeys?.destroy(),this.renderCounter?.destroy(),this.binWeightsBuffer?.destroy();for(let t of this._projectorComputes.values())t.shader?.destroy();this._projectorComputes.clear(),this._projectorBindGroupFormat?.destroy(),this._writeIndirectArgsCompute?.shader?.destroy(),this._writeArgsBindGroupFormat?.destroy(),this.projCache=null,this.sortKeys=null,this.renderCounter=null,this.binWeightsBuffer=null,this._projectorBindGroupFormat=null,this._projectorUniformBufferFormat=null,this._projectorUniformBufferFormatFisheye=null,this._writeIndirectArgsCompute=null,this._writeArgsBindGroupFormat=null,this._writeArgsUniformBufferFormat=null}_createUniformBufferFormats(){let t=this.device,e=[new Y("splatTextureSize",pe),new Y("numBins",pe),new Y("isOrtho",pe),new Y("pad0",pe),new Y("viewProj",as),new Y("viewMatrix",as),new Y("cameraPosition",Kt),new Y("minPixelSize",Te),new Y("cameraDirection",Kt),new Y("focal",Te),new Y("viewportWidth",Te),new Y("viewportHeight",Te),new Y("nearClip",Te),new Y("farClip",Te),new Y("alphaClip",Te),new Y("minContribution",Te),new Y("minDist",Te),new Y("invRange",Te)];this._projectorUniformBufferFormat=new Xe(t,e),this._projectorUniformBufferFormatFisheye=new Xe(t,[...e.map(s=>new Y(s.name,s.type)),new Y("fisheye_k",Te),new Y("fisheye_inv_k",Te),new Y("fisheye_projMat00",Te),new Y("fisheye_projMat11",Te)]),this._writeArgsUniformBufferFormat=new Xe(t,[new Y("drawSlot",pe),new Y("indexCount",pe),new Y("sortSlotBase",pe),new Y("pad0",pe),new Y("sortIndirectInfo",Li)])}_createWriteIndirectArgsCompute(){let t=this.device;this._writeArgsBindGroupFormat=new Ue(t,[new K("renderCounter",X,!0),new K("indirectDrawArgs",X,!1),new K("numSplatsBuf",X,!1),new K("indirectDispatchArgs",X,!1),new K("sortElementCountBuf",X,!1),new Qe("uniforms",X)]);let e=new Map([["{INSTANCE_SIZE}",rt.instanceSize.toString()]]),s=new Be(t,{name:"GSplatProjectorWriteIndirectArgs",shaderLanguage:se,cshader:iz,cdefines:e,computeBindGroupFormat:this._writeArgsBindGroupFormat,computeUniformBufferFormats:{uniforms:this._writeArgsUniformBufferFormat}});this._writeIndirectArgsCompute=new Ye(t,s,"GSplatProjectorWriteIndirectArgs")}_destroyProjectorComputes(){for(let t of this._projectorComputes.values())t.shader?.destroy();this._projectorComputes.clear(),this._projectorBindGroupFormat?.destroy(),this._projectorBindGroupFormat=null}_projectorKey(t,e,s,i){return`${t?"r":"l"}${e?"p":""}${s?"f":""}${i?"a":""}`}_createProjectorCompute(t,e,s,i,r){let a=this.device,o=t.format,l=[new K("compactedSplatIds",X,!0),new K("sortElementCount",X,!0),new K("projCache",X),new K("sortKeys",X),new K("renderCounter",X),new K("binWeights",X,!0),new Qe("uniforms",X)];this._projectorBindGroupFormat||(this._projectorBindGroupFormat=new Ue(a,[...l,...o.getComputeBindFormats()]));let h=new Map;h.set("gsplatCommonCS",dE),h.set("gsplatTileIntersectCS",pE),h.set("gsplatComputeSplatCS",gE),h.set("gsplatFormatDeclCS",o.getComputeInputDeclarations(l.length)),h.set("gsplatFormatReadCS",o.getReadCode()),h.set("gsplatProjectCommonCS",uE);let f=new Map;f.set("{CACHE_STRIDE}",8 .toString()),e&&f.set("RADIAL_SORT",""),s&&f.set("PICK_MODE",""),i&&f.set("GSPLAT_FISHEYE",""),r&&f.set("GSPLAT_AA","");let u=o.getStream("dataColor");u&&u.format!==Rs&&f.set("GSPLAT_COLOR_FLOAT","");let d=`GSplatProjector${e?"Radial":"Linear"}${s?"Pick":""}${i?"Fisheye":""}${r?"Aa":""}`,p=i?this._projectorUniformBufferFormatFisheye:this._projectorUniformBufferFormat,m=new Be(a,{name:d,shaderLanguage:se,cshader:sz,cincludes:h,cdefines:f,computeBindGroupFormat:this._projectorBindGroupFormat,computeUniformBufferFormats:{uniforms:p}});return new Ye(a,m,d)}_getProjectorCompute(t,e,s=!1,i=!1,r=!1){let a=t.format;this._formatVersion!==a.extraStreamsVersion&&(this._destroyProjectorComputes(),this._formatVersion=a.extraStreamsVersion);let o=this._projectorKey(e,s,i,r),l=this._projectorComputes.get(o);return l||(l=this._createProjectorCompute(t,e,s,i,r),this._projectorComputes.set(o,l)),l}_ensureCapacity(t){t>this._allocatedCacheCount&&(this.projCache?.destroy(),this.sortKeys?.destroy(),this._allocatedCacheCount=t,this.projCache=new Ee(this.device,t*8*4),this.sortKeys=new Ee(this.device,t*4,4))}dispatch(t){let{workBuffer:e,cameraNode:s,compactedSplatIds:i,sortElementCountBuffer:r,totalCapacity:a,radialSort:o,numBits:l,minDist:h,maxDist:f,alphaClip:u,minPixelSize:d,minContribution:p,viewportWidth:m,viewportHeight:_,flipY:S,pickMode:g=!1,fisheyeProj:T,antiAlias:C=!1}=t,v=!!T?.enabled,E=C&&!g;this._ensureCapacity(a),this.renderCounter.clear();let y=this._getProjectorCompute(e,o,g,v,E),P=s.getPosition(),w=s.getWorldTransform().getZ(OK).normalize(),I=f-h,D=I>0?1/I:1,O=1<0&&(this._streams=new dl(e,!0),this._streams.textureDimensions.copy(s.streams.textureDimensions),this._streams.syncWithFormat(s.format)),this._streams?.getTexture(t)}get streams(){return this.parentPlacement?.streams??this._streams}ensureInstanceStreams(t){let e=this.resource;e?.format&&!this._streams&&e.format.instanceStreams.length>0&&(this._streams=new dl(t,!0),this._streams.textureDimensions.copy(e.streams.textureDimensions),this._streams.syncWithFormat(e.format))}};var UR=new W,FK=new x,NK=new x,gh=[],Lqe=new ge,BK=Math.tan(22.5*R.DEG_TO_RAD),Mqe=[new F(1,0,0),new F(0,1,0),new F(0,0,1),new F(1,1,0),new F(1,0,1)],kR=class{constructor(){n(this,"currentLod",-1);n(this,"optimalLod",-1);n(this,"worldDistance",0);n(this,"colorAccumulatedTranslation",0);n(this,"inst",null);n(this,"lods",null);n(this,"budgetBucket",0);n(this,"allocId",yE.get())}resetLod(){this.currentLod=-1,this.optimalLod=-1}},EE=class{constructor(t,e,s){n(this,"octree");n(this,"placement");n(this,"activePlacements",new Set);n(this,"dirtyModifiedPlacements",!1);n(this,"dirtyPlacementSetChanged",!1);n(this,"device");n(this,"nodeInfos");n(this,"filePlacements");n(this,"pending",new Set);n(this,"pendingDecrements",new Map);n(this,"removedCandidates",new Set);n(this,"rangeMin",0);n(this,"rangeMax",0);n(this,"previousPosition",new x);n(this,"needsLodUpdate",!1);n(this,"prefetchPending",new Set);n(this,"pendingVisibleAdds",new Map);n(this,"environmentPlacement",null);n(this,"_deviceLostEvent",null);n(this,"_lodMinDistThresholds",null);this.device=t,this.octree=e,this.placement=s,this.nodeInfos=new Array(e.nodes.length);for(let r=0;r0){let r=Math.min(s,e+i);for(let a=e;a<=r;a++){let o=t.lods[a].fileIndex;if(o!==-1&&this.octree.getFileResource(o))return a}for(let a=r;a>=e;a--)if(t.lods[a].fileIndex!==-1)return a}return e}prefetchNextLod(t,e,s){if(e===-1||s===-1)return;if(e===s){let r=t.lods[s].fileIndex;r!==-1&&(this.octree.ensureFileResource(r),this.octree.getFileResource(r)||this.prefetchPending.add(r));return}let i=Math.max(s,e-1);for(let r=i;r>=s;r--){let a=t.lods[r].fileIndex;if(a!==-1){this.octree.ensureFileResource(a),this.octree.getFileResource(a)||this.prefetchPending.add(a);break}}}updateLod(t,e){let s=this.octree.lodLevels-1,{lodBaseDistance:i,lodMultiplier:r}=this.placement,{lodRangeMin:a,lodRangeMax:o}=e,l=Math.max(0,Math.min(a??0,s)),h=Math.max(l,Math.min(o??s,s)),f=this.placement.node.getWorldTransform().getScale().x;this.evaluateNodeLods(t,s,i,r,l,h,e,f,!1),this.applyLodChanges(s,e)}_ensureLodMinDistThresholds(t,e,s){let i=t+1,r=this._lodMinDistThresholds;(!r||r.length=1&&(H=this._ensureLodMinDistThresholds(e,s,i));let U=f>0?rn/Math.sqrt(f):0;for(let L=0;LV&&(k=V);let q=w,re=P[N+1],te=P[N+4];qte&&(q=te);let j=I,oe=P[N+2],be=P[N+5];jbe&&(j=be);let qe=k-A,ot=q-w,Ve=j-I,Lt=Math.sqrt(qe*qe+ot*ot+Ve*Ve),Vs=Lt;if(u>1&&Lt>.01){let di=(D*qe+O*ot+G*Ve)/Lt;if(di<0){let de=1+-di*(u-1);Vs=Lt*de}}let ds=Vs*_,Cs;if(e===0||ds1&&dsa&&(Cs=a),b.optimalLod=Cs,b.worldDistance=ds*l,U>0&&Cs>=0){let di=Math.sqrt(b.worldDistance)*U>>>0;b.budgetBucket=di=0?a.lods[h].fileIndex:-1,d=f>=0?a.lods[f].fileIndex:-1,p=u!==-1,m=d!==-1,_=this.pendingDecrements.get(r);if(_&&_.newFileIndex!==d&&(this.filePlacements[_.newFileIndex]&&this.decrementFileRef(_.newFileIndex,r),p&&m?this.pendingDecrements.set(r,{oldFileIndex:_.oldFileIndex,newFileIndex:d}):this.pendingDecrements.delete(r)),!p&&m){let S=this.pendingVisibleAdds.get(r);S!==void 0&&S!==d&&(this.decrementFileRef(S,r),this.pendingVisibleAdds.delete(r)),this.incrementFileRef(d,r,f),this.filePlacements[d]?.resource?(o.currentLod=f,this.pendingVisibleAdds.delete(r)):this.pendingVisibleAdds.set(r,d)}else if(p&&!m){let S=this.pendingDecrements.get(r);S&&(this.decrementFileRef(S.newFileIndex,r),this.pendingDecrements.delete(r)),this.decrementFileRef(u,r),o.currentLod=-1,this.pendingVisibleAdds.delete(r)}else p&&m&&(this.incrementFileRef(d,r,f),this.filePlacements[d]?.resource?(this.decrementFileRef(u,r),this.pendingDecrements.delete(r),o.currentLod=f,this.pendingVisibleAdds.delete(r)):(this.pendingDecrements.set(r,{oldFileIndex:u,newFileIndex:d}),this.pendingVisibleAdds.delete(r)))}this.prefetchNextLod(a,f,l)}}incrementFileRef(t,e,s){if(t===-1)return;let i=this.filePlacements[t];i||(i=new bu(null,this.placement.node,s,null,this.placement),this.filePlacements[t]=i,this.removedCandidates.delete(t)||this.octree.incRefCount(t),this.addFilePlacement(t)||(this.octree.ensureFileResource(t),this.pending.add(t)));let o=this.octree.nodes[e].lods[s],l=new B(o.offset,o.offset+o.count-1);i.intervals.set(e,l),this.dirtyModifiedPlacements=!0}decrementFileRef(t,e){if(t===-1)return;let s=this.filePlacements[t];s&&s&&(s.intervals.delete(e),this.dirtyModifiedPlacements=!0,s.intervals.size===0&&(s.resource&&(this.activePlacements.delete(s),this.activePlacements.size===0&&(this.dirtyPlacementSetChanged=!0)),this.removedCandidates.add(t),this.filePlacements[t]=null,this.pending.delete(t)))}addFilePlacement(t){let e=this.octree.getFileResource(t);if(e){let s=this.filePlacements[t];if(s)return s.resource=e,this.activePlacements.size===0&&(this.dirtyPlacementSetChanged=!0),this.activePlacements.add(s),this.dirtyModifiedPlacements=!0,this.removedCandidates.delete(t),!0}return!1}testMoved(t){return this.placement.node.getPosition().distance(this.previousPosition)>t}updateMoved(){this.previousPosition.copy(this.placement.node.getPosition())}update(){if(this.placement.lodDirty&&(this.placement.lodDirty=!1,this.needsLodUpdate=!0),this.pending.size){for(let e of this.pending)if(this.octree.ensureFileResource(e),this.addFilePlacement(e)){gh.push(e);for(let[s,{oldFileIndex:i,newFileIndex:r}]of this.pendingDecrements)if(r===e){this.decrementFileRef(i,s),this.pendingDecrements.delete(s);let a=0,o=this.octree.nodes[s].lods;for(let l=0;l0&&(this.needsLodUpdate=!0);for(let e of gh)this.pending.delete(e);gh.length=0}if(this.pollPrefetchCompletions(),this.octree.environmentUrl&&!this.environmentPlacement){this.octree.ensureEnvironmentResource();let e=this.octree.environmentResource;e&&(this.environmentPlacement=new bu(e,this.placement.node,0,null,this.placement),this.environmentPlacement.aabb.copy(e.aabb),this.activePlacements.add(this.environmentPlacement),this.dirtyModifiedPlacements=!0,this.dirtyPlacementSetChanged=!0,e.releaseTextureSources?.())}let t=this.dirtyModifiedPlacements;return this.dirtyModifiedPlacements=!1,t}consumePlacementSetChanged(){let t=this.dirtyPlacementSetChanged;return this.dirtyPlacementSetChanged=!1,t}debugRender(t){}consumeNeedsLodUpdate(){let t=this.needsLodUpdate;return this.needsLodUpdate=!1,t}pollPrefetchCompletions(){if(this.prefetchPending.size){for(let t of this.prefetchPending)this.octree.ensureFileResource(t),this.octree.getFileResource(t)&&gh.push(t);gh.length>0&&(this.needsLodUpdate=!0);for(let t of gh)this.prefetchPending.delete(t);gh.length=0}}};var lz=new x,cz=new x,AE=class{constructor(t,e){n(this,"lods");n(this,"bounds",new ge);n(this,"boundingSphere",new Q);this.lods=t,lz.set(e.min[0],e.min[1],e.min[2]),cz.set(e.max[0],e.max[1],e.max[2]),this.bounds.setMinMax(lz,cz);let s=this.bounds.center,i=this.bounds.halfExtents,r=Math.sqrt(i.x*i.x+i.y*i.y+i.z*i.z);this.boundingSphere.set(s.x,s.y,s.z,r)}};var zR=[],CE=class{constructor(t,e){n(this,"nodes");n(this,"nodeBoundsMinMax");n(this,"files");n(this,"lodLevels");n(this,"assetFileUrl");n(this,"fileResources",new Map);n(this,"fileRefCounts");n(this,"cooldowns",new Map);n(this,"environmentUrl",null);n(this,"environmentResource",null);n(this,"environmentRefCount",0);n(this,"assetLoader",null);n(this,"destroyed",!1);n(this,"cooldownTicks",100);this.lodLevels=e.lodLevels,this.assetFileUrl=t;let s=xe.getDirectory(t);this.files=e.filenames.map(o=>({url:xe.isRelativePath(o)?xe.join(s,o):o,lodLevel:-1})),this.fileRefCounts=new Int32Array(this.files.length),e.environment&&(this.environmentUrl=xe.isRelativePath(e.environment)?xe.join(s,e.environment):e.environment);let i=[];this._extractLeafNodes(e.tree,i),this.nodes=i.map(o=>{let l=[];for(let h=0;h0&&(this.cooldowns.forEach((e,s)=>{e<=1?(this.fileRefCounts[s]===0&&this.unloadResource(s),zR.push(s)):this.cooldowns.set(s,e-1)}),zR.forEach(e=>this.cooldowns.delete(e)),zR.length=0)}ensureFileResource(t){if(this.fileResources.has(t))return;let e=this.files[t].url,s=this.assetLoader?.getResource(e);if(s){this.fileResources.set(t,s),s.releaseTextureSources?.(),this.fileRefCounts[t]===0&&this.cooldowns.set(t,this.cooldownTicks),this._traceLodCounts();return}this.assetLoader?.load(e)}incEnvironmentRefCount(){this.environmentRefCount++}decEnvironmentRefCount(){this.environmentRefCount--,this.environmentRefCount===0&&this.unloadEnvironmentResource()}ensureEnvironmentResource(){if(!this.assetLoader||!this.environmentUrl||this.environmentResource)return;let t=this.assetLoader.getResource(this.environmentUrl);if(t){this.environmentResource=t,this.environmentRefCount===0&&this.unloadEnvironmentResource();return}this.assetLoader.load(this.environmentUrl)}unloadEnvironmentResource(){this.assetLoader&&this.environmentResource&&this.environmentUrl&&(this.assetLoader.unload(this.environmentUrl),this.environmentResource=null)}};var d_=class{constructor(t,e,s){n(this,"aabb",new ge);n(this,"centersVersion",0);n(this,"octree");n(this,"data");this.octree=new CE(t,e),this.octree.assetLoader=s,this.aabb.setMinMax(new x(e.tree.bound.min),new x(e.tree.bound.max)),this.data=e,this.data.tree=null}destroy(){this.octree?.destroy(),this.octree=null}};var GR=new Set,Pl=[],p_=[],m_=[],PE=class{constructor(t,e,s,i,r){n(this,"version",0);n(this,"sortParametersSet",!1);n(this,"sortedBefore",!1);n(this,"splats",[]);n(this,"textureSize",0);n(this,"totalActiveSplats",0);n(this,"totalIntervals",0);n(this,"boundsGroups",[]);n(this,"pendingReleases",[]);n(this,"needsUpload",[]);n(this,"needsUploadIds",new Set);n(this,"allocIdToSplat",new Map);n(this,"fullRebuild",!1);if(this.version=e,this.splats=s,s.length===0){for(let[,l]of r)i.free(l);r.clear(),this.totalActiveSplats=0,this.totalIntervals=0,this.textureSize=1;return}this.computeAllocationDiff(s,r);let{fullRebuild:a,changedAllocIds:o}=this.applyAllocations(t,i,r);this.assignSplatOffsets(s,r,a,o),this.buildBoundsGroups(s)}destroy(){this.splats.forEach(t=>t.destroy()),this.splats.length=0,this.needsUpload.length=0,this.needsUploadIds.clear(),this.allocIdToSplat.clear(),this.boundsGroups.length=0}computeAllocationDiff(t,e){for(let s=0;s0&&r.length===o)for(let l=0;l0&&(Pl.push(t),p_.push(e))):e>0&&(Pl.push(t),p_.push(e))}applyAllocations(t,e,s){let i=!1;if(m_.length>0||p_.length>0){i=e.updateAllocation(m_,p_);for(let h=0;h.3){let h=e.defrag(a);if(h.size>0)for(let[f,u]of s)h.has(u)&&Pl.push(f)}let o=e.capacity;this.textureSize=o>0?Math.ceil(Math.sqrt(o)):1;let l=Pl.length>0?new Set(Pl):null;return GR.clear(),Pl.length=0,p_.length=0,m_.length=0,{fullRebuild:i,changedAllocIds:l}}assignSplatOffsets(t,e,s,i){let r=0,a=0;for(let o=0;o0?u:1;let d=s,p=[];if(u>0&&h.length===u)for(let m=0;m0&&(l.setLayout(p),d&&(this.needsUpload.push(l),s)))for(let m=0;m, numIntervals: u32 #endif }; @group(0) @binding(0) var uniforms: CullUniforms; @group(0) @binding(1) var intervals: array; @group(0) @binding(2) var countBuffer: array; @group(0) @binding(3) var boundsBuffer: array; @group(0) @binding(4) var transformsBuffer: array; @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 uniforms: ScatterUniforms; @group(0) @binding(1) var intervals: array; @group(0) @binding(2) var prefixSumBuffer: array; @group(0) @binding(3) var compactedOutput: array; @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 prefixSumBuffer: array; @group(0) @binding(1) var indirectDrawArgs: array; @group(0) @binding(2) var numSplatsBuf: array; @group(0) @binding(3) var indirectDispatchArgs: array; @group(0) @binding(4) var sortElementCountBuf: array; struct WriteArgsUniforms { drawSlot: u32, indexCount: u32, dispatchSlotBase: u32, totalSplats: u32, sortIndirectInfo: vec4 }; @group(0) @binding(5) var 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;a0){let l=o.intervalNodeIndices;for(let h=0;h0?l[h/2]:0),i[r++]=0}}else i[r++]=o.intervalOffsets[0],i[r++]=o.activeSplats,i[r++]=o.boundsBaseIndex,i[r++]=0}this.intervalsBuffer.write(0,i,0,s*HR)}dispatchCompact(t,e,s,i){if(e===0)return;this._ensureCapacity(e,s);let r=this._getCullCompute(i);r.setParameter("intervals",this.intervalsBuffer),r.setParameter("countBuffer",this.countBuffer),r.setParameter("boundsBuffer",t.boundsBuffer),r.setParameter("transformsBuffer",t.transformsBuffer),i?(r.setParameter("cameraWorldPos",t.fisheyeCameraPos),r.setParameter("maxTheta",t.fisheyeMaxTheta),r.setParameter("cameraForward",t.fisheyeCameraForward)):r.setParameter("frustumPlanes[0]",t.frustumPlanes),r.setParameter("numIntervals",e);let a=Math.ceil(e/VR);r.setupDispatch(a),this.device.computeDispatch([r],"GSplatIntervalCull");let o=e+1;this.prefixSumKernel.resize(this.countBuffer,o),this.prefixSumKernel.dispatch(this.device);let l=this._scatterCompute;l.setParameter("intervals",this.intervalsBuffer),l.setParameter("prefixSumBuffer",this.countBuffer),l.setParameter("compactedOutput",this.compactedSplatIds),l.setParameter("numIntervals",e),l.setParameter("pad0",0),l.setParameter("pad1",0),l.setParameter("pad2",0),l.setupDispatch(e),this.device.computeDispatch([l],"GSplatIntervalScatter")}writeIndirectArgs(t,e,s,i){let r=this._writeIndirectArgsCompute;r.setParameter("prefixSumBuffer",this.countBuffer),r.setParameter("indirectDrawArgs",this.device.indirectDrawBuffer),r.setParameter("numSplatsBuf",this.numSplatsBuffer),r.setParameter("indirectDispatchArgs",this.device.indirectDispatchBuffer),r.setParameter("sortElementCountBuf",this.sortElementCountBuffer),r.setParameter("drawSlot",t),r.setParameter("indexCount",UK),r.setParameter("dispatchSlotBase",e),r.setParameter("totalSplats",s),r.setParameter("sortIndirectInfo",i),r.setupDispatch(1),this.device.computeDispatch([r],"GSplatIntervalWriteIndirectArgs")}};var IE=class{constructor(){n(this,"_buckets",null)}_initBuckets(){if(!this._buckets){this._buckets=new Array(rn);for(let t=0;te,a=!1;for(;!a&&(r?i>e:i=0&&!a;l--){let h=this._buckets[l];for(let f=0,u=h.length;fd.inst.rangeMin){let p=d.lods,m=d.optimalLod,_=p[m-1].count-p[m].count;if(i+_<=e){if(d.optimalLod=m-1,i+=_,o=!0,i>=e){a=!0;break}}else{a=!0;break}}}}if(!o)break}}};var WR=class{constructor(){n(this,"_offset",0);n(this,"_size",0);n(this,"_free",!0);n(this,"_prev",null);n(this,"_next",null);n(this,"_prevFree",null);n(this,"_nextFree",null);n(this,"_bucket",-1)}get offset(){return this._offset}get size(){return this._size}},RE=class{constructor(t=0,e=1.1){n(this,"_headAll",null);n(this,"_tailAll",null);n(this,"_freeBucketHeads",[]);n(this,"_pool",[]);n(this,"_capacity",0);n(this,"_usedSize",0);n(this,"_freeSize",0);n(this,"_freeRegionCount",0);n(this,"_growMultiplier");if(this._growMultiplier=e,t>0){this._capacity=t,this._freeSize=t;let s=this._obtain(0,t,!0);this._headAll=s,this._tailAll=s,this._addToBucket(s)}}get capacity(){return this._capacity}get usedSize(){return this._usedSize}get freeSize(){return this._freeSize}get fragmentation(){return this._freeSize>0?1-1/this._freeRegionCount:0}_bucketFor(t){return 31-Math.clz32(t)}_addToBucket(t){let e=this._bucketFor(t._size);for(t._bucket=e;e>=this._freeBucketHeads.length;)this._freeBucketHeads.push(null);t._prevFree=null,t._nextFree=this._freeBucketHeads[e],this._freeBucketHeads[e]&&(this._freeBucketHeads[e]._prevFree=t),this._freeBucketHeads[e]=t,this._freeRegionCount++}_removeFromBucket(t){let e=t._bucket;t._prevFree?t._prevFree._nextFree=t._nextFree:this._freeBucketHeads[e]=t._nextFree,t._nextFree&&(t._nextFree._prevFree=t._prevFree),t._prevFree=null,t._nextFree=null,t._bucket=-1,this._freeRegionCount--}_rebucket(t){this._bucketFor(t._size)!==t._bucket&&(this._removeFromBucket(t),this._addToBucket(t))}_obtain(t,e,s){let i;return this._pool.length>0?i=this._pool.pop():i=new WR,i._offset=t,i._size=e,i._free=s,i._prev=null,i._next=null,i._prevFree=null,i._nextFree=null,i._bucket=-1,i}_release(t){t._prev=null,t._next=null,t._prevFree=null,t._nextFree=null,t._bucket=-1,this._pool.push(t)}_insertAfterInMainList(t,e){e===null?(t._prev=null,t._next=this._headAll,this._headAll&&(this._headAll._prev=t),this._headAll=t,this._tailAll||(this._tailAll=t)):(t._prev=e,t._next=e._next,e._next&&(e._next._prev=t),e._next=t,this._tailAll===e&&(this._tailAll=t))}_removeFromMainList(t){t._prev?t._prev._next=t._next:this._headAll=t._next,t._next?t._next._prev=t._prev:this._tailAll=t._prev,t._prev=null,t._next=null}_findFreeBlock(t){let e=this._bucketFor(t),s=this._freeBucketHeads.length;if(e=t&&(!i||r._size0){let r=this._obtain(e,i,!0);this._insertAfterInMainList(r,this._tailAll),this._addToBucket(r)}}_defragIncremental(t,e){let s=Math.ceil(t/2),i=t-s;for(let a=0;a=o._offset)break;this._moveBlock(o,l),e.add(o)}let r=this._headAll;for(let a=0;athis._capacity&&this.grow(l),this.defrag(0);for(let h=s;h0?Math.ceil(a*r):0,r),this.workBuffer=new AS(t,this.scene.gsplat.format),this.layer=s,this._createRenderer(this.scene.gsplat.currentRenderer),this._workBufferFormatVersion=this.workBuffer.format.extraStreamsVersion}destroy(){this._destroyed=!0;for(let[,t]of this.worldStates){for(let e of t.splats)e.resource.decRefCount();t.destroy()}this.worldStates.clear();for(let[,t]of this.octreeInstances)t.destroy();this.octreeInstances.clear();for(let t of this.octreeInstancesToDestroy)t.destroy();this.octreeInstancesToDestroy.length=0,this.destroyGpuSorting(),this.destroyCpuSorting(),this.workBuffer.destroy(),this.renderer.destroy()}destroyGpuSorting(){this.gpuSorter?.destroy(),this.gpuSorter=null,this.projector?.destroy(),this.projector=null;let t=!1;this.renderer.setCpuSortedRendering(),this.destroyIntervalCompaction(t)}destroyIntervalCompaction(t=!0){this.intervalCompaction&&(t&&this.renderer.setCpuSortedRendering(),this.intervalCompaction.destroy(),this.intervalCompaction=null)}destroyCpuSorting(){this.cpuSorter?.destroy(),this.cpuSorter=null}initHybridSorting(){this.gpuSorter||(this.gpuSorter=new tm(this.device,{indirect:!0})),this.projector||(this.projector=new TE(this.device))}initCpuSorting(){this.cpuSorter||(this.cpuSorter=this.createSorter());let t=this.worldStates.get(this.sortedVersion);t&&(t.sortParametersSet=!1,t.sortedBefore=!1,this.cpuSorter.updateCentersForSplats(t.splats)),this.renderer.setCpuSortedRendering()}get material(){return this.renderer.material}prepareForPicking(t,e,s){if(this.activeRenderer===Cc){let r=this.worldStates.get(this.sortedVersion);if(!r?.sortedBefore||!t.node)return null;let a=this.sortGpuHybridForCamera(r,t.node,e,s,Math.max(f_,this.scene.gsplat.alphaClip),!!this.workBuffer.format.getStream("pcId"));if(!a)return null;let o=this.projector,l=this.intervalCompaction;return this.renderer.prepareForPicking(this.indirectDrawSlot,a,o.projCache,l.numSplatsBuffer,this.scene.gsplat.alphaClip,this.scene.gsplat.alphaClipForward,t.node)}return this.activeRenderer!==Hf?null:this.renderer.dispatchPick(t,e,s)}createSorter(){let t=new nE(this.scene);return t.on("sorted",(e,s,i)=>{this.onSorted(e,s,i)}),t}setRenderMode(t){this.renderMode=t,this.renderer.setRenderMode(t)}get canCull(){return this.activeRenderer!==tl&&this.workBuffer.frustumCuller.totalBoundsEntries>0}_createRenderer(t){t===Hf?this.renderer=new vE(this.device,this.node,this.cameraNode,this.layer,this.workBuffer):t===Cc?(this.renderer=new hE(this.device,this.node,this.cameraNode,this.layer,this.workBuffer),this.initHybridSorting()):(this.renderer=new cE(this.device,this.node,this.cameraNode,this.layer,this.workBuffer),this.initCpuSorting()),this.activeRenderer=t}prepareRendererMode(){let t=this.scene.gsplat.currentRenderer;t!==this.activeRenderer&&(this._worldStateDirty=!0,this.destroyGpuSorting(),this.destroyCpuSorting(),this.renderer.destroy(),this._createRenderer(t),this.renderer.setRenderMode(this.renderMode),this._workBufferRebuildRequired=!0,this.sortNeeded=!0)}reconcile(t){__.clear();for(let e of t)e.resource instanceof d_?(this.octreeInstances.has(e)||(this.octreeInstances.set(e,new EE(this.device,e.resource.octree,e)),this.hasNewOctreeInstances=!0),XR.add(e)):__.add(e);for(let[e,s]of this.octreeInstances)XR.has(e)||(this.octreeInstances.delete(e),this.layerPlacementsDirty=!0,this._placementSetChanged=!0,this.octreeInstancesToDestroy.push(s));if(this.layerPlacementsDirty||(this.layerPlacementsDirty=this.layerPlacements.length!==__.size),!this.layerPlacementsDirty)for(let e=0;e{if(o.resource){let l=o.resource;if(this.cpuSorter&&!l.hasCenters)return;o.ensureInstanceStreams(this.device);let h=o.intervals.size>0?a.octree.nodes:null,f=h?a.nodeInfos:null,u=new ZS(this.device,o.resource,o,o.consumeRenderDirty.bind(o),h,f);i.push(u)}});if(this.cpuSorter)for(let a of i){let o=a.resource;this._centersVersions.get(o.id)!==o.centersVersion&&(this._centersVersions.set(o.id,o.centersVersion),this.cpuSorter.setCenters(o.id,null),this.cpuSorter.setCenters(o.id,o.centers))}this.cpuSorter?.updateCentersForSplats(i);let r=new PE(this.device,this.lastWorldStateVersion,i,this._allocator,this._allocationMap);for(let a of r.splats)a.resource.incRefCount();for(let[,a]of this.octreeInstances)if(a.removedCandidates&&a.removedCandidates.size){for(let o of a.removedCandidates)r.pendingReleases.push([a.octree,o]);a.removedCandidates.clear()}if(this.octreeInstancesToDestroy.length){for(let a of this.octreeInstancesToDestroy){if(a.removedCandidates&&a.removedCandidates.size){for(let l of a.removedCandidates)r.pendingReleases.push([a.octree,l]);a.removedCandidates.clear()}let o=a.getFileDecrements();for(let l of o)r.pendingReleases.push([a.octree,l]);a.destroy(!0)}this.octreeInstancesToDestroy.length=0}this._placementSetChanged&&(r.fullRebuild=!0),this.worldStates.set(this.lastWorldStateVersion,r),this.layerPlacementsDirty=!1,this._placementSetChanged=!1,this._worldStateDirty=!1,this.sortNeeded=!0}}onSorted(t,e,s){this.cleanupOldWorldStates(e),this.sortedVersion=e;let i=this.worldStates.get(e);i&&(i.sortedBefore||(i.sortedBefore=!0,this.rebuildWorkBuffer(i,t)),this.workBuffer.setOrderData(s),this.renderer.setOrderData())}rebuildWorkBuffer(t,e,s=!1){let i=t.textureSize;i!==this.workBuffer.textureSize&&this.workBuffer.resize(i),this.activeRenderer!==tl&&(this.workBuffer.frustumCuller.updateBoundsData(t.boundsGroups),this.workBuffer.frustumCuller.updateTransformsData(t.boundsGroups));let r=s||t.fullRebuild,a=r?t.splats:t.needsUpload,o=r?null:t.needsUploadIds;if(a.length>0){let l=this._allocationMap.size,h=r?l:t.needsUploadIds.size;this.bufferCopyUploaded+=h,this.bufferCopyTotal=l,this.workBuffer.render(a,this.cameraNode,this.getDebugColors(),o)}for(let l=0;l0,o=0;t.splats.forEach(l=>{if(l.update()){if(bE.push(l),o+=l.intervalAllocIds.length,l.nodeInfos)for(let h of l.intervalNodeIndices)l.nodeInfos[h].colorAccumulatedTranslation=0;else l.colorAccumulatedTranslation=0;this.sortNeeded=!0}else if(a&&l.hasSphericalHarmonics)if(YR.push(l),l.nodeInfos){let h=l.intervalNodeIndices;for(let f=0;f=d&&(tx.add(l.intervalAllocIds[f]),u.colorAccumulatedTranslation=0,o++)}}else{l.colorAccumulatedTranslation+=r,ex.copy(l.node.getWorldTransform()).invert(),ex.transformPoint(i,jR),l.aabb.closestPoint(jR,pz);let h=jR.distance(pz)*l.node.getWorldTransform().getScale().x,f=s*Math.max(1,h);l.colorAccumulatedTranslation>=f&&(tx.add(l.allocId),o+=l.intervalAllocIds.length,l.colorAccumulatedTranslation=0)}}),this.bufferCopyUploaded+=o,this.bufferCopyTotal=this._allocationMap.size,bE.length>0&&(this.workBuffer.render(bE,this.cameraNode,this.getDebugColors()),bE.length=0),tx.size>0&&(this.workBuffer.renderColor(YR,this.cameraNode,this.getDebugColors(),tx),tx.clear()),YR.length=0}testCameraMovedForLod(){let t=this.scene.gsplat.lodUpdateDistance,e=this.cameraNode.getPosition(),s=this.lastLodCameraPos.distance(e)>t;if(s)return!0;let i=!1,r=this.scene.gsplat.lodUpdateAngle;if(r>0)if(Number.isFinite(this.lastLodCameraFwd.x)){let l=this.cameraNode.forward,h=Math.min(1,Math.max(-1,this.lastLodCameraFwd.dot(l))),f=Math.acos(h),u=r*R.DEG_TO_RAD;i=f>u}else i=!0;let a=this.cameraNode.camera.fov,o=this.lastLodCameraFov<0||Math.abs(a-this.lastLodCameraFov)>this.lastLodCameraFov*.02;return s||i||o}testCameraMovedForSort(){if(this.scene.gsplat.radialSorting){let e=this.cameraNode.getPosition();return this.lastSortCameraPos.distance(e)>.001}if(Number.isFinite(this.lastSortCameraFwd.x)){let e=this.cameraNode.forward,s=Math.min(1,Math.max(-1,this.lastSortCameraFwd.dot(e)));return Math.acos(s)>.001}return!0}testFrustumChanged(){if(!this.lastCullingProjMat.equals(this.cameraNode.camera.projectionMatrix))return!0;let e=this.cameraNode.forward,s=Math.min(1,Math.max(-1,this.lastCullingCameraFwd.dot(e)));return Math.acos(s)>.001}updateColorCameraTracking(){this.lastColorUpdateCameraPos.copy(this.cameraNode.getPosition())}getDebugColors(){let t=this.scene.gsplat.debug;if(t===yp){xh??(xh=[]);let e=Math.random(),s=Math.random(),i=Math.random();for(let r=0;rt&&(t=a)}return Math.max(t,1)}_enforceBudget(t){let e=this.workBuffer.textureSize,s=0,i=0;for(let h of this.layerPlacements){let f=h.resource;if(f){let u=f.numSplats??0;s+=u,i+=(e-u%e)%e}}let r=Math.max(1,t-s),a=this.computeGlobalMaxDistance(),o=0;for(let[,h]of this.octreeInstances){o+=h.evaluateOptimalLods(this.cameraNode,this.scene.gsplat,this._budgetScale,a);for(let f of h.activePlacements){let d=f.resource?.numSplats??0;i+=(e-d%e)%e}}let l=Math.max(1,r-i);if(o>0){let h=o/l,f=.4,u=.3;if(h>1+f||h<1-f){let d=1/Math.sqrt(h);this._budgetScale*=1+(d-1)*u,this._budgetScale=Math.max(.01,Math.min(this._budgetScale,100))}}this._budgetBalancer.balance(this.octreeInstances,l);for(let[,h]of this.octreeInstances){let f=h.octree.lodLevels-1;h.applyLodChanges(f,this.scene.gsplat)}}handleFormatChange(){let t=this.scene.gsplat.format;this.workBuffer.format!==t&&(this.workBuffer.destroy(),this.workBuffer=new AS(this.device,t),this.renderer.setDataSource(this.workBuffer),this._workBufferFormatVersion=this.workBuffer.format.extraStreamsVersion,this._workBufferRebuildRequired=!0,this.sortNeeded=!0)}update(){this.bufferCopyUploaded=0,this.bufferCopyTotal=0,this.handleFormatChange();let t=this.workBuffer.format.extraStreamsVersion;this._workBufferFormatVersion!==t&&(this._workBufferFormatVersion=t,this.workBuffer.syncWithFormat(),this._workBufferRebuildRequired=!0,this.sortNeeded=!0),this.prepareRendererMode(),this.cpuSorter&&this.cpuSorter.applyPendingSorted();let e=this.activeRenderer!==tl||this.cpuSorter&&this.cpuSorter.jobsInFlight<3,s=!1;this.framesTillFullUpdate--,this.framesTillFullUpdate<=0&&(this.framesTillFullUpdate=10,e&&(s=!0));let i=this.hasNewOctreeInstances&&e;i&&(this.hasNewOctreeInstances=!1);let r=!1,a=!1,o=!1;if(s){for(let[,p]of this.octreeInstances){let m=p.update();this.layerPlacementsDirty||(this.layerPlacementsDirty=m),this._placementSetChanged||(this._placementSetChanged=p.consumePlacementSetChanged());let _=p.consumeNeedsLodUpdate();r||(r=_)}let d=this.scene.gsplat.lodUpdateDistance;for(let[,p]of this.octreeInstances){let m=p.testMoved(d);a||(a=m)}o=this.testCameraMovedForLod(),this._awaitingLodUpdate=!1}if(this.testCameraMovedForSort()&&(this.sortNeeded=!0),this.intervalCompaction&&!this.sortNeeded&&this.testFrustumChanged()&&(this.lastCullingCameraFwd.copy(this.cameraNode.forward),this.lastCullingProjMat.copy(this.cameraNode.camera.projectionMatrix),this.sortNeeded=!0),this.scene.gsplat.dirty&&(this.layerPlacementsDirty=!0,this.renderer.updateOverdrawMode(this.scene.gsplat),this._workBufferRebuildRequired=!0,this.sortNeeded=!0,this.octreeInstances.size>0&&(this._awaitingLodUpdate=!0)),o||a||this.scene.gsplat.dirty||r||i){for(let[,m]of this.octreeInstances)m.updateMoved();let d=this.cameraNode;this.lastLodCameraPos.copy(d.getPosition()),this.lastLodCameraFwd.copy(d.forward),this.lastLodCameraFov=d.camera.fov;let p=this.scene.gsplat.splatBudget;if(p>0)this._enforceBudget(p);else{this._budgetScale=1;for(let[,m]of this.octreeInstances)m.updateLod(this.cameraNode,this.scene.gsplat)}}this.updateWorldState();let l=this.worldStates.get(this.lastWorldStateVersion);if(l&&this.cpuSorter&&!l.sortParametersSet){l.sortParametersSet=!0;let d=this.prepareSortParameters(l);this.cpuSorter.setSortParameters(d)}let h=this.worldStates.get(this.sortedVersion);if(h?.sortedBefore)if(this._workBufferRebuildRequired){let d=h.totalActiveSplats;this.rebuildWorkBuffer(h,d,!0),this._workBufferRebuildRequired=!1,this.renderer.setOrderData(),this.intervalCompaction&&(this.intervalCompaction._uploadedVersion=-1)}else this.applyWorkBufferUpdates(h);let f=!1;if(this.sortNeeded&&l&&(this.activeRenderer===Hf?(this.compactGpu(l),f=!0):this.activeRenderer===Cc?(this.sortGpuHybrid(l),f=!0):this.sortCpu(l),this.sortNeeded=!1,this.lastSortCameraPos.copy(this.cameraNode.getPosition()),this.lastSortCameraFwd.copy(this.cameraNode.forward),this.lastCullingCameraFwd.copy(this.cameraNode.forward),this.lastCullingProjMat.copy(this.cameraNode.camera.projectionMatrix)),this.activeRenderer===Cc&&l&&!f&&(this.sortGpuHybrid(l),f=!0),h?.sortedBefore&&this.updateColorCameraTracking(),this.octreeInstances.size){let d=this.scene.gsplat.cooldownTicks;for(let[,p]of this.octreeInstances){let m=p.octree;qR.has(m)||(qR.add(m),m.updateCooldownTick(d))}qR.clear()}if(this.fireFrameReadyEvent(),this.scene.gsplat.dirty)for(let[,d]of this.octreeInstances)d.needsLodUpdate=!0;let u=this.scene.gsplat.useFog?this.cameraNode.camera.fogParams??this.scene.fog:null;return this.renderer.frameUpdate(this.scene.gsplat,this.scene.exposure,u),h?h.totalActiveSplats:0}sortGpuHybrid(t){let e=this.cameraNode.camera,s=e.camera,i=e.renderTarget,r=e.rect,a=s.xr?.session?s.xr.views.list[0]:null,o=Math.floor((a?a.viewport.z:i?i.width:this.device.width)*r.z),l=Math.floor((a?a.viewport.w:i?i.height:this.device.height)*r.w),h=this.sortGpuHybridForCamera(t,this.cameraNode,o,l,Math.max(f_,this.scene.gsplat.alphaClipForward),!1);h&&this.applyGpuSortResults(h)}sortGpuHybridForCamera(t,e,s,i,r,a){let o=this.gpuSorter,l=this.projector;if(!o||!l)return null;let h=t.totalActiveSplats;if(h===0)return null;if(this.intervalCompaction||(this.intervalCompaction=new QS(this.device)),t.sortedBefore||(t.sortedBefore=!0,this.cleanupOldWorldStates(t.version),this.sortedVersion=t.version,this.rebuildWorkBuffer(t,h)),this.intervalCompaction.uploadIntervals(t),this.canCull){let y=this.worldStates.get(this.sortedVersion);y&&this._runFrustumCulling(y,e)}let f=this.renderer.fisheyeProj,u=t.totalIntervals,d=t.totalActiveSplats;this.intervalCompaction.dispatchCompact(this.workBuffer.frustumCuller,u,d,f.enabled),this.allocateAndWriteIntervalIndirectArgs(u);let p=this.intervalCompaction,m=p.compactedSplatIds,_=this.scene.gsplat,S=Math.max(10,Math.min(20,Math.round(Math.log2(h/4)))),g=o.radixBits,T=Math.ceil(S/g)*g,{minDist:C,maxDist:v}=this.computeDistanceRange(t,e),E=o.prepareIndirect();return l.dispatch({workBuffer:this.workBuffer,cameraNode:e,compactedSplatIds:m,sortElementCountBuffer:p.sortElementCountBuffer,totalCapacity:h,radialSort:_.radialSorting,numBits:T,minDist:C,maxDist:v,alphaClip:r,minPixelSize:_.minPixelSize*.5,minContribution:_.minContribution,viewportWidth:s,viewportHeight:i,flipY:!!e.camera.renderTarget?.flipY,pickMode:a,fisheyeProj:f,antiAlias:_.antiAlias}),l.writeIndirectArgs(this.indirectDrawSlot,this.indirectDispatchSlot+1,p.numSplatsBuffer,p.sortElementCountBuffer,E),o.sortIndirect(l.sortKeys,h,T,this.indirectDispatchSlot+1,p.sortElementCountBuffer,void 0,!1,!0)}compactGpu(t){this.intervalCompaction||(this.intervalCompaction=new QS(this.device));let e=t.totalActiveSplats;if(e===0)return;if(t.sortedBefore||(t.sortedBefore=!0,this.cleanupOldWorldStates(t.version),this.sortedVersion=t.version,this.rebuildWorkBuffer(t,e)),this.intervalCompaction.uploadIntervals(t),this.canCull){let o=this.worldStates.get(this.sortedVersion);o&&this._runFrustumCulling(o)}let s=t.totalIntervals,i=t.totalActiveSplats;this.intervalCompaction.dispatchCompact(this.workBuffer.frustumCuller,s,i,this.renderer.fisheyeProj.enabled),this.allocateAndWriteIntervalIndirectArgs(s);let r=this.intervalCompaction;this.renderer.setCompactedData(r.compactedSplatIds,r.sortElementCountBuffer,t.textureSize,i)}allocateAndWriteIntervalIndirectArgs(t){let e=this.gpuSorter,s=e?e.prepareIndirect():kK,i=s[0];this.indirectDrawSlot=this.device.getIndirectDrawSlot(1),this.indirectDispatchSlot=this.device.getIndirectDispatchSlot(1+i),this.intervalCompaction.writeIndirectArgs(this.indirectDrawSlot,this.indirectDispatchSlot,t,s),this.lastCompactedNumIntervals=t}applyGpuSortResults(t){let e=this.projector,s=this.intervalCompaction;this.renderer.setHybridSortedRendering(this.indirectDrawSlot,t,e.projCache,s.numSplatsBuffer)}_runFrustumCulling(t,e=this.cameraNode){this.workBuffer.frustumCuller.updateTransformsData(t.boundsGroups);let s=e.camera;this.workBuffer.frustumCuller.computeFrustumPlanes(s.projectionMatrix,s.viewMatrix);let i=this.scene.gsplat,r=this.renderer.fisheyeProj;r.update(i.fisheye,s.fov,s.projectionMatrix),r.enabled&&this.workBuffer.frustumCuller.setFisheyeData(e.getPosition(),e.forward,r.maxTheta)}computeDistanceRange(t,e=this.cameraNode){let s=e.getWorldTransform();s.getTranslation(Sh),s.getZ(JS).normalize();let i=this.scene.gsplat.radialSorting,r=i?0:1/0,a=i?0:-1/0;for(let o of t.splats){let l=o.node.getWorldTransform(),h=o.aabb.getMin(),f=o.aabb.getMax();for(let u=0;u<8;u++)if(wl.x=u&1?f.x:h.x,wl.y=u&2?f.y:h.y,wl.z=u&4?f.z:h.z,l.transformPoint(wl,wl),i){let d=wl.distance(Sh);d>a&&(a=d)}else{let d=wl.sub(Sh).dot(JS);da&&(a=d)}}return a===0||a===-1/0?{minDist:0,maxDist:1}:{minDist:r,maxDist:a}}sortCpu(t){if(!this.cpuSorter)return;let s=this.cameraNode.getWorldTransform();s.getTranslation(Sh),s.getZ(JS).normalize();let i=[];t.splats.forEach(r=>{let a=r.node.getWorldTransform();ex.copy(a).invert();let o=a.getScale().x,l=ex.transformVector(JS).normalize(),h=ex.transformPoint(Sh);a.getTranslation(dz);let f=dz.sub(Sh).dot(JS),u=r.aabb.getMin(),d=r.aabb.getMax();i.push({transformedDirection:l,transformedPosition:h,offset:f,scale:o,modelMat:a.data.slice(),aabbMin:[u.x,u.y,u.z],aabbMax:[d.x,d.y,d.z]})}),this.cpuSorter.setSortParams(i,this.scene.gsplat.radialSorting)}prepareSortParameters(t){return{command:"intervals",textureSize:t.textureSize,totalActiveSplats:t.totalActiveSplats,version:t.version,ids:t.splats.map(e=>e.resource.id),pixelOffsets:t.splats.map(e=>e.intervalOffsets),intervals:t.splats.map(e=>e.intervals)}}};var LE=class{static equals(t,e){if(t.size!==e.size)return!1;for(let s of t)if(!e.has(s))return!1;return!0}};var ME=[],ZR=class{constructor(t,e,s,i){n(this,"gsplatManager",null);n(this,"gsplatManagerShadow",null);this.updateConfiguration(t,e,s,i)}createManager(t,e,s,i,r,a){let o=new DE(t,e,s,i);return o.setRenderMode(a),e.eventHandler&&e.eventHandler.fire("material:created",o.material,r,s),o}updateConfiguration(t,e,s,i){let r=i.node,a=s.gsplatPlacements.length>0,o=s.gsplatShadowCasters.length>0,h=LE.equals(s.gsplatPlacementsSet,s.gsplatShadowCastersSet)&&a,f=h?Fs|el:a?Fs:0,u=h?0:o?el:0;f?this.gsplatManager?this.gsplatManager.setRenderMode(f):this.gsplatManager=this.createManager(t,e,s,r,i,f):this.gsplatManager&&(this.gsplatManager.destroy(),this.gsplatManager=null),u?this.gsplatManagerShadow?this.gsplatManagerShadow.setRenderMode(u):this.gsplatManagerShadow=this.createManager(t,e,s,r,i,u):this.gsplatManagerShadow&&(this.gsplatManagerShadow.destroy(),this.gsplatManagerShadow=null)}destroy(){this.gsplatManager?.destroy(),this.gsplatManager=null,this.gsplatManagerShadow?.destroy(),this.gsplatManagerShadow=null}},QR=class{constructor(){n(this,"layersMap",new Map)}destroy(){this.layersMap.forEach(t=>t.destroy()),this.layersMap.clear()}removeLayerData(t){let e=this.layersMap.get(t);e&&(e.destroy(),this.layersMap.delete(t))}getLayerData(t,e,s,i){let r=this.layersMap.get(s);return r||(r=new ZR(t,e,s,i),this.layersMap.set(s,r)),r}},OE=class{constructor(t,e,s,i){n(this,"device");n(this,"camerasMap",new Map);n(this,"scene");n(this,"eventHandler");this.device=t,this.renderer=e,this.scene=s,this.eventHandler=i}destroy(){this.camerasMap.forEach(t=>t.destroy()),this.camerasMap.clear()}getCameraData(t){let e=this.camerasMap.get(t);return e||(e=new QR,this.camerasMap.set(t,e)),e}prepareForPicking(t,e,s,i){let r=this.camerasMap.get(t);if(!r)return null;let a=r.layersMap.get(i);return a?.gsplatManager?a.gsplatManager.prepareForPicking(t,e,s):null}update(t){am.process(this.device),this.camerasMap.forEach((a,o)=>{if(!t.camerasSet.has(o))a.destroy(),this.camerasMap.delete(o);else{a.layersMap.forEach((l,h)=>{(!o.layersSet.has(h.id)||!h.enabled)&&ME.push(h)});for(let l=0;l0,p=u.gsplatShadowCasters.length>0;if(!d&&!p)l&&l.removeLayerData(u);else{l??(l=this.getCameraData(o));let m=l.getLayerData(this.device,this,u,o);m.updateConfiguration(this.device,this,u,o),m.gsplatManager&&m.gsplatManager.reconcile(u.gsplatPlacements),m.gsplatManagerShadow&&m.gsplatManagerShadow.reconcile(u.gsplatShadowCasters)}}}if(l)for(let f of l.layersMap.values())f.gsplatManager&&(e+=f.gsplatManager.update(),s+=f.gsplatManager.bufferCopyUploaded,i+=f.gsplatManager.bufferCopyTotal),f.gsplatManagerShadow&&(e+=f.gsplatManagerShadow.update(),s+=f.gsplatManagerShadow.bufferCopyUploaded,i+=f.gsplatManagerShadow.bufferCopyTotal)}this.renderer._gsplatCount=e,this.renderer._gsplatBufferCopy=i>0?s/i*100:0,this.scene.gsplat.frameEnd();for(let a=0;a0&&(this.lodBaseDistance=e[0],this.lodMultiplier=3)}get lodDistances(){return[]}set splatBudget(e){}get splatBudget(){return 0}set unified(e){this._unified!==e&&(this._unified=e,this._onGSplatAssetAdded())}get unified(){return this._unified}get id(){return this._id}set workBufferUpdate(e){this._workBufferUpdate=e,this._placement&&(this._placement.workBufferUpdate=e)}get workBufferUpdate(){return this._workBufferUpdate}setWorkBufferModifier(e){if(e){let i=(this.system.app.graphicsDevice.isWebGPU?e.wgsl:e.glsl)??null;this._workBufferModifier=i?{code:i,hash:xt(i)}:null}else this._workBufferModifier=null;this._placement&&(this._placement.workBufferModifier=this._workBufferModifier)}set layers(e){this.removeFromLayers(),this._layers.length=0;for(let s=0;s 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) -> 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, alpha: half) { #if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS) let alphaClipValue = half(uniform.alphaClip); #else let alphaClipValue = half(uniform.alphaClipForward); #endif let clip = min(half(1.0), sqrt(max(half(0.0), log(alpha / alphaClipValue))) * half(0.5)); corner.offset = corner.offset * f32(clip); corner.uv = corner.uv * clip; } `;var Vz=` struct Splat { index: u32, uv: vec2i } var splat: Splat; fn setSplat(idx: u32) { splat.index = idx; splat.uv = vec2i(i32(idx % uniform.splatTextureSize), i32(idx / uniform.splatTextureSize)); } `;var Hz=` #if SH_BANDS == 1 const SH_COEFFS: i32 = 3; #elif SH_BANDS == 2 const SH_COEFFS: i32 = 8; #elif SH_BANDS == 3 const SH_COEFFS: i32 = 15; #else const SH_COEFFS: i32 = 0; #endif #if SH_BANDS > 0 const SH_C1: half = half(0.4886025119029199); #if SH_BANDS > 1 const SH_C2_0: half = half(1.0925484305920792); const SH_C2_1: half = half(-1.0925484305920792); const SH_C2_2: half = half(0.31539156525252005); const SH_C2_3: half = half(-1.0925484305920792); const SH_C2_4: half = half(0.5462742152960396); #endif #if SH_BANDS > 2 const SH_C3_0: half = half(-0.5900435899266435); const SH_C3_1: half = half(2.890611442640554); const SH_C3_2: half = half(-0.4570457994644658); const SH_C3_3: half = half(0.3731763325901154); const SH_C3_4: half = half(-0.4570457994644658); const SH_C3_5: half = half(1.445305721320277); const SH_C3_6: half = half(-0.5900435899266435); #endif fn evalSH(sh: ptr>, dir: vec3f) -> half3 { let d: half3 = half3(dir); var result: half3 = SH_C1 * (-sh[0] * d.y + sh[1] * d.z - sh[2] * d.x); #if SH_BANDS > 1 let xx: half = d.x * d.x; let yy: half = d.y * d.y; let zz: half = d.z * d.z; let xy: half = d.x * d.y; let yz: half = d.y * d.z; let xz: half = d.x * d.z; result = result + ( sh[3] * (SH_C2_0 * xy) + sh[4] * (SH_C2_1 * yz) + sh[5] * (SH_C2_2 * (half(2.0) * zz - xx - yy)) + sh[6] * (SH_C2_3 * xz) + sh[7] * (SH_C2_4 * (xx - yy)) ); #endif #if SH_BANDS > 2 result = result + ( sh[8] * (SH_C3_0 * d.y * (half(3.0) * xx - yy)) + sh[9] * (SH_C3_1 * xy * d.z) + sh[10] * (SH_C3_2 * d.y * (half(4.0) * zz - xx - yy)) + sh[11] * (SH_C3_3 * d.z * (half(2.0) * zz - half(3.0) * xx - half(3.0) * yy)) + sh[12] * (SH_C3_4 * d.x * (half(4.0) * zz - xx - yy)) + sh[13] * (SH_C3_5 * d.z * (xx - yy)) + sh[14] * (SH_C3_6 * d.x * (xx - half(3.0) * yy)) ); #endif return result; } #endif `;var Wz=` fn gsplatMakeSpherical(scale: ptr, size: f32) { *scale = vec3f(size); } fn gsplatGetSizeFromScale(scale: vec3f) -> f32 { return sqrt((scale.x * scale.x + scale.y * scale.y + scale.z * scale.z) / 3.0); } `;var Xz=` fn modifySplatCenter(center: ptr) { } fn modifySplatRotationScale(originalCenter: vec3f, modifiedCenter: vec3f, rotation: ptr, scale: ptr) { } fn modifySplatColor(center: vec3f, color: ptr) { } `;var Yz=` fn quatToMat3(r: half4) -> half3x3 { let r2: half4 = r + r; let x: half = r2.x * r.w; let y: half4 = r2.y * r; let z: half4 = r2.z * r; let w: half = r2.w * r.w; return half3x3( half(1.0) - z.z - w, y.z + x, y.w - z.x, y.z - x, half(1.0) - y.y - w, z.w + y.x, y.w + z.x, z.w - y.x, half(1.0) - y.y - z.z ); } fn quatMul(a: half4, b: half4) -> half4 { return half4( a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x, a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w, a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z ); } `;var Kz=` #include "gsplatSplatVS" struct SplatSource { order: u32, cornerUV: half2 } struct SplatCenter { view: vec3f, proj: vec4f, modelView: mat4x4f, projMat00: f32, modelCenterOriginal: vec3f, modelCenterModified: vec3f, #ifdef GSPLAT_FISHEYE fisheyeSinTK: f32, fisheyeCosTK: f32, fisheyeRxy: f32, #endif } struct SplatCorner { offset: vec3f, uv: half2, #if GSPLAT_AA aaFactor: half, #endif } `;var jz=` uniform viewport_size: vec4f; uniform minPixelSize: f32; fn computeCovariance(rotation: half4, scale: half3, covA_ptr: ptr, covB_ptr: ptr) { 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, center: ptr, corner: ptr, 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, rotation: vec4f, scale: vec3f, corner: ptr) { 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, center: ptr, corner: ptr) -> 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 rasterizeTileList: array; 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(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; var pickDepthTexture: texture_2d; #else #include "tonemappingPS" #include "gammaPS" var source: texture_2d; #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 numSplatsStorage: array; var compactedSplatIds: array; #else uniform numSplats: u32; var splatOrder: array; #endif fn initSource(source: ptr) -> 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; 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, ¢er)) { output.position = discardVec; return output; } var corner: SplatCorner; if (!initCorner(&source, ¢er, &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; 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 sortedIndices: array; var projCache: array; var numSplatsStorage: array; varying gaussianUV: half2; varying gaussianColor: half4; #ifndef DITHER_NONE varying id: f32; #endif #ifdef PREPASS_PASS varying vLinearDepth: f32; #endif #if defined(GSPLAT_UNIFIED_ID) && defined(PICK_PASS) varying @interpolate(flat) vPickId: u32; #endif #ifdef GSPLAT_OVERDRAW uniform colorRampIntensity: f32; var colorRamp: texture_2d; var colorRampSampler: sampler; #endif const discardVec: vec4f = vec4f(0.0, 0.0, 2.0, 1.0); @vertex fn vertexMain(input: VertexInput) -> VertexOutput { var output: VertexOutput; let order = pcInstanceIndex * {GSPLAT_INSTANCE_SIZE}u + u32(vertex_position.z); let numSplats = numSplatsStorage[0]; if (order >= numSplats) { output.position = discardVec; return output; } let cacheIdx = sortedIndices[order]; let base = cacheIdx * {CACHE_STRIDE}u; let proj = vec4f( bitcast(projCache[base + 0u]), bitcast(projCache[base + 1u]), bitcast(projCache[base + 2u]), bitcast(projCache[base + 3u]) ); let v1 = unpack2x16float(projCache[base + 4u]); let v2 = unpack2x16float(projCache[base + 5u]); let ba = unpack2x16float(projCache[base + 7u]); let alpha = half(ba.y); #if defined(GSPLAT_UNIFIED_ID) && defined(PICK_PASS) let pickId = projCache[base + 6u]; #endif #ifdef PICK_PASS var clr: half4 = half4(half(0.0), half(0.0), half(0.0), alpha); #else let rg = unpack2x16float(projCache[base + 6u]); var clr: half4 = half4(half(rg.x), half(rg.y), half(ba.x), alpha); #endif let cornerUV = vec2f(vertex_position.xy); #if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS) let alphaClipValue = half(uniform.alphaClip); #else let alphaClipValue = half(uniform.alphaClipForward); #endif let clip = min(half(1.0), sqrt(max(half(0.0), log(alpha / alphaClipValue))) * half(0.5)); let cornerClipped = cornerUV * f32(clip); let c = vec2f(proj.w) * uniform.viewport_size.zw; let pixelOffset = cornerClipped.x * v1 + cornerClipped.y * v2; let clipOffset = pixelOffset * c; output.position = proj + vec4f(clipOffset, 0.0, 0.0); output.gaussianUV = half2(cornerClipped); let viewDepth = dot(uniform.clipToViewZ, proj); #ifdef GSPLAT_OVERDRAW let t: f32 = clamp(viewDepth / 20.0, 0.0, 1.0); let rampColor: vec3f = textureSampleLevel(colorRamp, colorRampSampler, vec2f(t, 0.5), 0.0).rgb; let outAlpha = alpha * half(1.0 / 32.0) * half(uniform.colorRampIntensity); output.gaussianColor = half4(half3(rampColor), outAlpha); #else output.gaussianColor = half4( half3(prepareOutputFromGamma(max(vec3f(clr.xyz), vec3f(0.0)), viewDepth)), alpha ); #endif #ifndef DITHER_NONE output.id = f32(cacheIdx); #endif #ifdef PREPASS_PASS output.vLinearDepth = viewDepth; #endif #if defined(GSPLAT_UNIFIED_ID) && defined(PICK_PASS) output.vPickId = pickId; #endif return output; } `;var tG=` fn pack8888(v: vec4f) -> u32 { let t = vec4u(v * 255.0) << vec4u(24u, 16u, 8u, 0u); return t.x | t.y | t.z | t.w; } 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 tAw: u32; var 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 = loadTransformA(); tAw = tA.w; tBcached = loadTransformB(); return bitcast(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(bits) >> vec3(21u, 11u, 0u)) & vec3(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) -> ScaleAndSH { var result: ScaleAndSH; result.scale = bitcast(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) -> 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>, scale: ptr) { 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>, scale: ptr) { 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>, scale: ptr) { 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; var chunkDataA: vec4f; var chunkDataB: vec4f; var chunkDataC: vec4f; var chunkDataD: vec4f; var chunkDataE: vec4f; var packedData: vec4u; fn unpack111011(bits: u32) -> vec3f { return (vec3f((vec3(bits) >> vec3(21u, 11u, 0u)) & vec3(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 = vec2(i32((chunkId % w) * 5u), i32(chunkId / w)); chunkDataA = textureLoad(chunkTexture, chunkUV + vec2(0, 0), 0); chunkDataB = textureLoad(chunkTexture, chunkUV + vec2(1, 0), 0); chunkDataC = textureLoad(chunkTexture, chunkUV + vec2(2, 0), 0); chunkDataD = textureLoad(chunkTexture, chunkUV + vec2(3, 0), 0); chunkDataE = textureLoad(chunkTexture, chunkUV + vec2(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(bits) >> vec4(0u, 8u, 16u, 24u)) & vec4(0xffu); return half4(vec4f(unpacked_u) * (8.0 / 255.0) - 4.0); } fn readSHData(sh: ptr>, scale: ptr) { let shData0: vec4 = loadShTexture0(); let shData1: vec4 = loadShTexture1(); let shData2: vec4 = 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>, scale: ptr) { let labels = textureLoad(sh_labels, splat.uv, 0); let n = i32(labels.x * 255.0 + 0.5) + i32(labels.y * 255.0 + 0.5) * 256; let u = (n % 64) * SH_COEFFS; let v = n / 64; sh[0] = readSHTexel(u, v); sh[1] = readSHTexel(u + 1, v); sh[2] = readSHTexel(u + 2, v); #if SH_BANDS > 1 sh[3] = readSHTexel(u + 3, v); sh[4] = readSHTexel(u + 4, v); sh[5] = readSHTexel(u + 5, v); sh[6] = readSHTexel(u + 6, v); sh[7] = readSHTexel(u + 7, v); #endif #if SH_BANDS > 2 sh[8] = readSHTexel(u + 8, v); sh[9] = readSHTexel(u + 9, v); sh[10] = readSHTexel(u + 10, v); sh[11] = readSHTexel(u + 11, v); sh[12] = readSHTexel(u + 12, v); sh[13] = readSHTexel(u + 13, v); sh[14] = readSHTexel(u + 14, v); #endif *scale = 1.0; } #endif `;var cG=` #include "gsplatContainerDeclarationsVS" var splatCenter: vec3f; var splatColor: vec4f; var splatScale: vec3f; var 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{if(a==="material"){if(!s.unified){let o=s[a];o&&(i[a]=o.clone())}}else i[a]=s[a]}),i.enabled=s.enabled;let r=this.addComponent(e,i);return r.customAabb=s.customAabb?.clone()??null,r}onRemove(t,e){e.onRemove()}getMaterial(t,e){let s=this.app.renderer.gsplatDirector;if(!s)return null;let i=s.camerasMap.get(t);return i?i.layersMap.get(e)?.gsplatManager?.material??null:null}getGSplatMaterial(t,e){return this.getMaterial(t,e)}};n(vh,"EVENT_MATERIALCREATED","material:created"),n(vh,"EVENT_FRAMEREADY","frame:ready");le._buildAccessors(Du.prototype,JR);var Lu=class extends J{constructor(){super(...arguments);n(this,"_meshes",null)}set meshes(e){this.decRefMeshes(),this._meshes=e,this.incRefMeshes(),this.fire("set:meshes",e)}get meshes(){return this._meshes}destroy(){this.meshes=null}decRefMeshes(){this._meshes?.forEach((e,s)=>{e&&(e.decRefCount(),e.refCount<1&&(e.destroy(),this._meshes[s]=null))})}incRefMeshes(){this._meshes?.forEach(e=>{e?.incRefCount()})}};n(Lu,"EVENT_SETMESHES","set:meshes");function NE(c){let t=this;if(!t.resource)return;let e=c.resource,s=e.renders&&e.renders[t.data.renderIndex];s&&(t.resource.meshes=s.resource.meshes)}function uG(c){let t=this;t.registry.off(`load:${c.id}`,NE,t),t.registry.on(`load:${c.id}`,NE,t),t.registry.off(`remove:${c.id}`,dG,t),t.registry.once(`remove:${c.id}`,dG,t),c.resource?NE.call(t,c):t.registry.load(c)}function dG(c){let t=this;t.registry.off(`load:${c.id}`,NE,t),t.resource&&t.resource.destroy()}var g_=class extends Re{constructor(t){super(t,"render"),this._registry=t.assets}open(t,e){return new Lu}patch(t,e){if(!t.data.containerAsset)return;let s=e.get(t.data.containerAsset);if(!s){e.once(`add:${t.data.containerAsset}`,uG,t);return}uG.call(t,s)}};var Th=class{constructor(t,e,s,i){this._paths=t,this._input=e,this._output=s,this._interpolation=i}get paths(){return this._paths}get input(){return this._input}get output(){return this._output}get interpolation(){return this._interpolation}};var an=class{constructor(t,e){this._components=t,this._data=e}get components(){return this._components}get data(){return this._data}};function pG(c,t){let e,r=(m,_)=>{switch(_){case e.DT_INT8:return new Int8Array(m.buffer,m.byteOffset,m.byteLength);case e.DT_INT16:return new Int16Array(m.buffer,m.byteOffset,m.byteLength/2);case e.DT_INT32:return new Int32Array(m.buffer,m.byteOffset,m.byteLength/4);case e.DT_UINT8:return new Uint8Array(m.buffer,m.byteOffset,m.byteLength);case e.DT_UINT16:return new Uint16Array(m.buffer,m.byteOffset,m.byteLength/2);case e.DT_UINT32:return new Uint32Array(m.buffer,m.byteOffset,m.byteLength/4);case e.DT_FLOAT32:return new Float32Array(m.buffer,m.byteOffset,m.byteLength/4)}return null},a=m=>{switch(m){case e.DT_INT8:return 1;case e.DT_INT16:return 2;case e.DT_INT32:return 4;case e.DT_UINT8:return 1;case e.DT_UINT16:return 2;case e.DT_UINT32:return 4;case e.DT_FLOAT32:return 4}return 1},o=m=>{switch(m){case e.DT_INT8:return 0;case e.DT_UINT8:return 1;case e.DT_INT16:return 2;case e.DT_UINT16:return 3;case e.DT_INT32:return 4;case e.DT_UINT32:return 5;case e.DT_FLOAT32:return 6;default:return 6}},l=m=>m.num_components()*a(m.data_type()),h={0:0,1:1,5:2,2:3,7:4,8:5,4:6,3:7},f=(m,_)=>{let S=(G,M,H)=>{G[0]=M[0]-H[0],G[1]=M[1]-H[1],G[2]=M[2]-H[2]},g=(G,M,H)=>{G[0]=M[1]*H[2]-H[1]*M[2],G[1]=M[2]*H[0]-H[2]*M[0],G[2]=M[0]*H[1]-H[0]*M[1]},T=(G,M)=>{let H=G[M+0],U=G[M+1],L=G[M+2],b=1/Math.sqrt(H*H+U*U+L*L);G[M+0]*=b,G[M+1]*=b,G[M+2]*=b},C=(G,M,H)=>{for(let U=0;U<3;++U)G[U]=M[H+U]},v=_.length/3,E=m.length/3,y=new Float32Array(m.length),P=[0,0,0],A=[0,0,0],w=[0,0,0],I=[0,0,0],D=[0,0,0],O=[0,0,0];for(let G=0;G{let _={},S=new e.DecoderBuffer;S.Init(m,m.length);let g=new e.Decoder;if(g.GetEncodedGeometryType(S)!==e.TRIANGULAR_MESH)return _.error="Failed to decode draco mesh: not a mesh",_;let T=new e.Mesh,C=g.DecodeBufferToMesh(S,T);if(!C||!C.ok()||e.getPointer(T)===0)return _.error="Failed to decode draco asset",_;let v=T.num_faces()*3,E=T.num_points()<=65535,y=v*(E?2:4),P=e._malloc(y);E?(g.GetTrianglesUInt16Array(T,y,P),_.indices=new Uint16Array(e.HEAPU16.buffer,P,v).slice().buffer):(g.GetTrianglesUInt32Array(T,y,P),_.indices=new Uint32Array(e.HEAPU32.buffer,P,v).slice().buffer),e._free(P);let A=[];for(let M=0;M(h[M.attribute_type()]??h.length)-(h[H.attribute_type()]??h.length));let w=0,I=A.map(M=>{let H=w;return w+=Math.ceil(l(M)/4)*4,H}),D=A.some(M=>M.attribute_type()===1),O=I[1]??0;if(!D){O=I[0]+Math.ceil(l(A[0])/4)*4;for(let M=1;M({id:M.unique_id(),dataType:o(M.data_type()),numComponents:M.num_components(),offset:I[H]})),D||_.attributes.splice(1,0,{id:-1,dataType:6,numComponents:3,offset:O}),_.stride=w,_.vertices=new ArrayBuffer(T.num_points()*w);let G=new Uint8Array(_.vertices);for(let M=0;M{let _=u(new Uint8Array(m.buffer));self.postMessage({jobId:m.jobId,error:_.error,indices:_.indices,vertices:_.vertices,attributes:_.attributes,stride:_.stride},[_.indices,_.vertices].filter(S=>S!=null))},p=[];self.onmessage=m=>{let _=m.data;switch(_.type){case"init":self.DracoDecoderModule({instantiateWasm:(S,g)=>(WebAssembly.instantiate(_.module,S).then(T=>g(T)).catch(T=>{}),{})}).then(S=>{e=S,p.forEach(g=>d(g))});break;case"decodeMesh":e?d(_):p.push(_);break}}}var mG=3,eb=class{constructor(){this.workers=[[],[],[]],this.jobId=0,this.jobQueue=[],this.jobCallbacks=new Map,this.run=(t,e)=>{t.postMessage({type:"decodeMesh",jobId:e.jobId,buffer:e.buffer},[e.buffer])}}init(t){for(t.forEach(e=>{e.addEventListener("message",s=>{let i=s.data,r=this.jobCallbacks.get(i.jobId);if(r&&r(i.error,{indices:i.indices,vertices:i.vertices,attributes:i.attributes,stride:i.stride}),this.jobCallbacks.delete(i.jobId),this.jobQueue.length>0){let a=this.jobQueue.shift();this.run(e,a)}else{let a=this.workers[2].indexOf(e);if(a!==-1)this.workers[2].splice(a,1),this.workers[1].push(e);else{let o=this.workers[1].indexOf(e);o!==-1&&(this.workers[1].splice(o,1),this.workers[0].push(e))}}})}),this.workers[0]=t;this.jobQueue.length&&(this.workers[0].length||this.workers[1].length);){let e=this.jobQueue.shift();if(this.workers[0].length>0){let s=this.workers[0].shift();this.workers[1].push(s),this.run(s,e)}else{let s=this.workers[1].shift();this.workers[2].push(s),this.run(s,e)}}}enqueueJob(t,e){let s={jobId:this.jobId++,buffer:t};if(this.jobCallbacks.set(s.jobId,e),this.workers[0].length>0){let i=this.workers[0].shift();this.workers[1].push(i),this.run(i,s)}else if(this.workers[1].length>0){let i=this.workers[1].shift();this.workers[2].push(i),this.run(i,s)}else this.jobQueue.push(s)}},zK=c=>new Promise((t,e)=>{let s={cache:!0,responseType:"text",retry:mG>0,maxRetries:mG};Le.get(c,s,(i,r)=>{i?e(i):t(r)})}),GK=c=>{let t=()=>fetch(c).then(s=>s.arrayBuffer()).then(s=>WebAssembly.compile(s)),e=()=>WebAssembly.compileStreaming(fetch(c)).catch(s=>t());return WebAssembly.compileStreaming?e():t()},_G=1,BE,tb,gG=c=>{if(BE)return!0;if(!c)if(tb)c=tb;else{let t=Yl.getConfig("DracoDecoderModule");t?c={jsUrl:t.glueUrl,wasmUrl:t.wasmUrl,numWorkers:t.numWorkers}:c={jsUrl:"draco.wasm.js",wasmUrl:"draco.wasm.wasm",numWorkers:_G}}return!c.jsUrl||!c.wasmUrl?!1:(BE=new eb,Promise.all([zK(c.jsUrl),GK(c.wasmUrl)]).then(([t,e])=>{let s=["/* draco */",t,"/* worker */",`( ${pG.toString()} )() `].join(` `),i=new Blob([s],{type:"application/javascript"}),r=URL.createObjectURL(i),a=Math.max(1,Math.min(16,c.numWorkers||_G)),o=[];for(let l=0;l{c?.lazyInit?tb=c:gG(c)},UE=(c,t)=>gG()?(BE.enqueueJob(c,t),!0):!1;var sb=class{constructor(){n(this,"gltf");n(this,"nodes");n(this,"scenes");n(this,"animations");n(this,"textures");n(this,"materials");n(this,"variants");n(this,"meshVariants");n(this,"meshDefaultMaterials");n(this,"renders");n(this,"skins");n(this,"lights");n(this,"cameras");n(this,"nodeInstancingMap")}destroy(){this.renders&&this.renders.forEach(t=>{t.meshes=null})}},TG=c=>/^data:[^\n\r,\u2028\u2029]*,.*$/i.test(c),VK=c=>c.substring(c.indexOf(":")+1,c.indexOf(";")),kE=c=>{switch(c){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":return 4;case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16;default:return 3}},ob=c=>{switch(c){case 5120:return js;case 5121:return ai;case 5122:return qs;case 5123:return Ri;case 5124:return He;case 5125:return kt;case 5126:return ye;default:return 0}},HK=c=>{switch(c){case 5120:return 1;case 5121:return 1;case 5122:return 2;case 5123:return 2;case 5124:return 4;case 5125:return 4;case 5126:return 4;default:return 0}},WK=c=>{switch(c){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5124:return Int32Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:return null}},ib={POSITION:ee,NORMAL:Ot,TANGENT:vs,COLOR_0:Ct,JOINTS_0:$t,WEIGHTS_0:bs,TEXCOORD_0:_t,TEXCOORD_1:ri,TEXCOORD_2:Ca,TEXCOORD_3:Pa,TEXCOORD_4:wa,TEXCOORD_5:Ia,TEXCOORD_6:Ra,TEXCOORD_7:ba},xG={[ee]:0,[Ot]:1,[vs]:2,[Ct]:3,[$t]:4,[bs]:5,[_t]:6,[ri]:7,[Ca]:8,[Pa]:9,[wa]:10,[Ia]:11,[Ra]:12,[ba]:13},XK=c=>{switch(c){case js:return t=>Math.max(t/127,-1);case ai:return t=>t/255;case qs:return t=>Math.max(t/32767,-1);case Ri:return t=>t/65535;default:return t=>t}},rb=(c,t,e)=>{let s=XK(e),i=t.length;for(let r=0;r{let s=kE(c.type),i=WK(c.componentType);if(!i)return null;let r;if(c.sparse){let a=c.sparse,o={count:a.count,type:"SCALAR"},l=Mu(Object.assign(o,a.indices),t,!0),h={count:a.count,type:c.type,componentType:c.componentType},f=Mu(Object.assign(h,a.values),t,!0);if(c.hasOwnProperty("bufferView")){let u={bufferView:c.bufferView,byteOffset:c.byteOffset,componentType:c.componentType,count:c.count,type:c.type};r=Mu(u,t,!0).slice()}else r=new i(c.count*s);for(let u=0;u{let e=Mu(c,t,!0);if(e instanceof Float32Array||!c.normalized)return e;let s=new Float32Array(e.length);return rb(s,e,ob(c.componentType)),s},ab=c=>{let t=c.min,e=c.max;if(!t||!e)return null;if(c.normalized){let s=ob(c.componentType);t=rb([],t,s),e=rb([],e,s)}return new ge(new x((e[0]+t[0])*.5,(e[1]+t[1])*.5,(e[2]+t[2])*.5),new x((e[0]-t[0])*.5,(e[1]-t[1])*.5,(e[2]-t[2])*.5))},yG=c=>{if(!c.hasOwnProperty("mode"))return Yt;switch(c.mode){case 0:return Aa;case 1:return Pn;case 2:return Eg;case 3:return mf;case 4:return Yt;case 5:return Ks;case 6:return dr;default:return Yt}},YK=c=>{let t=new Uint16Array(c);for(let e=0;e{let e=c[ee];if(!e||e.components!==3)return;let s;if(e.size!==e.stride){let o=e.stride/Wn[e.type],l=new Ro[e.type](e.buffer,e.offset,e.count*o);s=new Ro[e.type](e.count*3);for(let h=0;h{let t=s=>{let i=[];for(let r=0;r{let t=new ae(`${c.name}_clone`,c.type,c.file,c.data,c.options);return t.loaded=!0,t.resource=jK(c.resource),c.registry.add(t),t},$K=(c,t)=>{let e=t[ee];if(!e)return null;let s=e.count,i=[];for(let g in t)if(t.hasOwnProperty(g)){let T={semantic:g,components:t[g].components,type:t[g].type,normalize:!!t[g].normalize};Ft.isElementValid(c,T)||T.components++,i.push(T)}i.sort((g,T)=>xG[g.semantic]-xG[T.semantic]);let r,a,o,l,h,f,u=new Ft(c,i),d=!0;for(r=0;r{let a={},o=[];for(let f in t)t.hasOwnProperty(f)&&ib.hasOwnProperty(f)&&(a[f]=t[f],o.push(`${f}:${t[f]}`));o.sort();let l=o.join(),h=r[l];if(!h){let f={};for(let u in a){let d=s[t[u]],p=Mu(d,i),m=i[d.bufferView],_=ib[u],S=kE(d.type)*HK(d.componentType),g=m&&m.hasOwnProperty("byteStride")?m.byteStride:S;f[_]={buffer:p.buffer,size:S,offset:p.byteOffset,stride:g,count:d.count,components:kE(d.type),type:ob(d.componentType),normalize:d.normalized}}f.hasOwnProperty(Ot)||KK(f,e),h=$K(c,f),r[l]=h}return h},QK=(c,t,e,s,i,r)=>{let a,o,l,h=t.joints,f=h.length,u=[];if(t.hasOwnProperty("inverseBindMatrices")){let _=t.inverseBindMatrices,S=Mu(e[_],s,!0),g=[];for(a=0;a{let o=new _e(c);if(o.aabb=ab(e[t.attributes.POSITION]),a.push(new Promise((l,h)=>{let f=t.extensions.KHR_draco_mesh_compression;UE(s[f.bufferView].slice().buffer,(u,d)=>{if(u)h(u);else{let p={};for(let[E,y]of Object.entries(f.attributes))p[y]=ib[E];p[-1]=Ot;let m=[];for(let E of d.attributes){let y=p[E.id];if(y!==void 0){let P=!1;if(E.id!==-1){for(let[A,w]of Object.entries(f.attributes))if(w===E.id&&t.attributes[A]!==void 0){P=e[t.attributes[A]].normalized??(y===Ct&&(E.dataType===ai||E.dataType===Ri));break}}m.push({semantic:y,components:E.numComponents,type:E.dataType,normalize:P,offset:E.offset,stride:d.stride})}}let _=new Ft(c,m),S=d.vertices.byteLength/d.stride,g=S<=65535?1:2,T=d.indices.byteLength/(S<=65535?2:4),C=new ft(c,_,S,{data:d.vertices}),v=new os(c,g,T,0,d.indices);o.vertexBuffer=C,o.indexBuffer[0]=v,o.primitive[0].type=yG(t),o.primitive[0].base=0,o.primitive[0].count=v?T:S,o.primitive[0].indexed=!!v,l()}})})),t?.extensions?.KHR_materials_variants){let l=t.extensions.KHR_materials_variants,h={};l.mappings.forEach(f=>{f.variants.forEach(u=>{h[u]=f.material})}),i[o.id]=h}return r[o.id]=t.material,o},ej=(c,t,e,s,i,r,a,o,l)=>{let h=[];return t.primitives.forEach(f=>{if(f.extensions?.KHR_draco_mesh_compression)h.push(JK(c,f,e,s,r,a,l));else{let u=f.hasOwnProperty("indices")?Mu(e[f.indices],s,!0):null,d=ZK(c,f.attributes,u,e,s,i),p=yG(f),m=new _e(c);if(m.vertexBuffer=d,m.primitive[0].type=p,m.primitive[0].base=0,m.primitive[0].indexed=u!==null,u!==null){let S;u instanceof Uint8Array?S=0:u instanceof Uint16Array?S=1:S=2,S===0&&c.isWebGPU&&(S=1,u=new Uint16Array(u));let g=new os(c,S,u.length,0,u);m.indexBuffer[0]=g,m.primitive[0].count=u.length}else m.primitive[0].count=d.numVertices;if(f.hasOwnProperty("extensions")&&f.extensions.hasOwnProperty("KHR_materials_variants")){let S=f.extensions.KHR_materials_variants,g={};S.mappings.forEach(T=>{T.variants.forEach(C=>{g[C]=T.material})}),r[m.id]=g}a[m.id]=f.material;let _=e[f.attributes.POSITION];if(m.aabb=ab(_),f.hasOwnProperty("targets")){let S=[];f.targets.forEach((g,T)=>{let C={};g.hasOwnProperty("POSITION")&&(_=e[g.POSITION],C.deltaPositions=x_(_,s),C.aabb=ab(_)),g.hasOwnProperty("NORMAL")&&(_=e[g.NORMAL],C.deltaNormals=x_(_,s)),t.hasOwnProperty("extras")&&t.extras.hasOwnProperty("targetNames")?C.name=t.extras.targetNames[T]:C.name=T.toString(10),t.hasOwnProperty("weights")&&(C.defaultWeight=t.weights[T]),C.preserveData=o.morphPreserveData,S.push(new Gc(C))}),m.morph=new Ko(S,c,{preferHighPrecision:o.morphPreferHighPrecision})}h.push(m)}}),h},Gs=(c,t,e)=>{let s,i=c.texCoord;if(i)for(s=0;s{let s;if(c.hasOwnProperty("diffuseFactor")){let[i,r,a,o]=c.diffuseFactor;t.diffuse.set(i,r,a).gamma(),t.opacity=o}else t.diffuse.set(1,1,1),t.opacity=1;if(c.hasOwnProperty("diffuseTexture")){let i=c.diffuseTexture;s=e[i.index],t.diffuseMap=s,t.diffuseMapChannel="rgb",t.opacityMap=s,t.opacityMapChannel="a",Gs(i,t,["diffuse","opacity"])}if(t.useMetalness=!1,c.hasOwnProperty("specularFactor")){let[i,r,a]=c.specularFactor;t.specular.set(i,r,a).gamma()}else t.specular.set(1,1,1);if(c.hasOwnProperty("glossinessFactor")?t.gloss=c.glossinessFactor:t.gloss=1,c.hasOwnProperty("specularGlossinessTexture")){let i=c.specularGlossinessTexture;t.specularMap=t.glossMap=e[i.index],t.specularMapChannel="rgb",t.glossMapChannel="a",Gs(i,t,["gloss","metalness"])}},sj=(c,t,e)=>{if(c.hasOwnProperty("clearcoatFactor")?t.clearCoat=c.clearcoatFactor*.25:t.clearCoat=0,c.hasOwnProperty("clearcoatTexture")){let s=c.clearcoatTexture;t.clearCoatMap=e[s.index],t.clearCoatMapChannel="r",Gs(s,t,["clearCoat"])}if(c.hasOwnProperty("clearcoatRoughnessFactor")?t.clearCoatGloss=c.clearcoatRoughnessFactor:t.clearCoatGloss=0,c.hasOwnProperty("clearcoatRoughnessTexture")){let s=c.clearcoatRoughnessTexture;t.clearCoatGlossMap=e[s.index],t.clearCoatGlossMapChannel="g",Gs(s,t,["clearCoatGloss"])}if(c.hasOwnProperty("clearcoatNormalTexture")){let s=c.clearcoatNormalTexture;t.clearCoatNormalMap=e[s.index],Gs(s,t,["clearCoatNormal"]),s.hasOwnProperty("scale")?t.clearCoatBumpiness=s.scale:t.clearCoatBumpiness=1}t.clearCoatGlossInvert=!0},ij=(c,t,e)=>{t.useLighting=!1,t.emissive.copy(t.diffuse),t.emissiveMap=t.diffuseMap,t.emissiveMapUv=t.diffuseMapUv,t.emissiveMapTiling.copy(t.diffuseMapTiling),t.emissiveMapOffset.copy(t.diffuseMapOffset),t.emissiveMapRotation=t.diffuseMapRotation,t.emissiveMapChannel=t.diffuseMapChannel,t.emissiveVertexColor=t.diffuseVertexColor,t.emissiveVertexColorChannel=t.diffuseVertexColorChannel,t.useLighting=!1,t.useSkybox=!1,t.diffuse.set(1,1,1),t.diffuseMap=null,t.diffuseVertexColor=!1},rj=(c,t,e)=>{if(t.useMetalnessSpecularColor=!0,c.hasOwnProperty("specularColorTexture")&&(t.specularMap=e[c.specularColorTexture.index],t.specularMapChannel="rgb",Gs(c.specularColorTexture,t,["specular"])),c.hasOwnProperty("specularColorFactor")){let[s,i,r]=c.specularColorFactor;t.specular.set(s,i,r).gamma()}else t.specular.set(1,1,1);c.hasOwnProperty("specularFactor")?t.specularityFactor=c.specularFactor:t.specularityFactor=1,c.hasOwnProperty("specularTexture")&&(t.specularityFactorMapChannel="a",t.specularityFactorMap=e[c.specularTexture.index],Gs(c.specularTexture,t,["specularityFactor"]))},aj=(c,t,e)=>{c.hasOwnProperty("ior")&&(t.refractionIndex=1/c.ior)},oj=(c,t,e)=>{c.hasOwnProperty("dispersion")&&(t.dispersion=c.dispersion)},nj=(c,t,e)=>{t.blendType=ls,t.useDynamicRefraction=!0,c.hasOwnProperty("transmissionFactor")&&(t.refraction=c.transmissionFactor),c.hasOwnProperty("transmissionTexture")&&(t.refractionMapChannel="r",t.refractionMap=e[c.transmissionTexture.index],Gs(c.transmissionTexture,t,["refraction"]))},lj=(c,t,e)=>{if(t.useSheen=!0,c.hasOwnProperty("sheenColorFactor")){let[s,i,r]=c.sheenColorFactor;t.sheen.set(s,i,r).gamma()}else t.sheen.set(1,1,1);c.hasOwnProperty("sheenColorTexture")&&(t.sheenMap=e[c.sheenColorTexture.index],Gs(c.sheenColorTexture,t,["sheen"])),t.sheenGloss=c.hasOwnProperty("sheenRoughnessFactor")?c.sheenRoughnessFactor:0,c.hasOwnProperty("sheenRoughnessTexture")&&(t.sheenGlossMap=e[c.sheenRoughnessTexture.index],t.sheenGlossMapChannel="a",Gs(c.sheenRoughnessTexture,t,["sheenGloss"])),t.sheenGlossInvert=!0},cj=(c,t,e)=>{if(t.blendType=ls,t.useDynamicRefraction=!0,c.hasOwnProperty("thicknessFactor")&&(t.thickness=c.thicknessFactor),c.hasOwnProperty("thicknessTexture")&&(t.thicknessMap=e[c.thicknessTexture.index],t.thicknessMapChannel="g",Gs(c.thicknessTexture,t,["thickness"])),c.hasOwnProperty("attenuationDistance")&&(t.attenuationDistance=c.attenuationDistance),c.hasOwnProperty("attenuationColor")){let[s,i,r]=c.attenuationColor;t.attenuation.set(s,i,r).gamma()}},hj=(c,t,e)=>{c.hasOwnProperty("emissiveStrength")&&(t.emissiveIntensity=c.emissiveStrength)},fj=(c,t,e)=>{t.useIridescence=!0,c.hasOwnProperty("iridescenceFactor")&&(t.iridescence=c.iridescenceFactor),c.hasOwnProperty("iridescenceTexture")&&(t.iridescenceMapChannel="r",t.iridescenceMap=e[c.iridescenceTexture.index],Gs(c.iridescenceTexture,t,["iridescence"])),c.hasOwnProperty("iridescenceIor")&&(t.iridescenceRefractionIndex=c.iridescenceIor),c.hasOwnProperty("iridescenceThicknessMinimum")&&(t.iridescenceThicknessMin=c.iridescenceThicknessMinimum),c.hasOwnProperty("iridescenceThicknessMaximum")&&(t.iridescenceThicknessMax=c.iridescenceThicknessMaximum),c.hasOwnProperty("iridescenceThicknessTexture")&&(t.iridescenceThicknessMapChannel="g",t.iridescenceThicknessMap=e[c.iridescenceThicknessTexture.index],Gs(c.iridescenceThicknessTexture,t,["iridescenceThickness"]))},uj=(c,t,e)=>{if(t.enableGGXSpecular=!0,c.hasOwnProperty("anisotropyStrength")?t.anisotropyIntensity=c.anisotropyStrength:t.anisotropyIntensity=0,c.hasOwnProperty("anisotropyTexture")){let s=c.anisotropyTexture;t.anisotropyMap=e[s.index],Gs(s,t,["anisotropy"])}c.hasOwnProperty("anisotropyRotation")?t.anisotropyRotation=c.anisotropyRotation*R.RAD_TO_DEG:t.anisotropyRotation=0},EG=(c,t)=>{let e=new it;c.hasOwnProperty("name")&&(e.name=c.name),e.occludeSpecular=Bo,e.diffuseVertexColor=!0,e.specularTint=!0,e.specularVertexColor=!0,e.specular.set(1,1,1),e.gloss=1,e.glossInvert=!0,e.useMetalness=!0;let s;if(c.hasOwnProperty("pbrMetallicRoughness")){let r=c.pbrMetallicRoughness;if(r.hasOwnProperty("baseColorFactor")){let[a,o,l,h]=r.baseColorFactor;e.diffuse.set(a,o,l).gamma(),e.opacity=h}if(r.hasOwnProperty("baseColorTexture")){let a=r.baseColorTexture;s=t[a.index],e.diffuseMap=s,e.diffuseMapChannel="rgb",e.opacityMap=s,e.opacityMapChannel="a",Gs(a,e,["diffuse","opacity"])}if(r.hasOwnProperty("metallicFactor")&&(e.metalness=r.metallicFactor),r.hasOwnProperty("roughnessFactor")&&(e.gloss=r.roughnessFactor),r.hasOwnProperty("metallicRoughnessTexture")){let a=r.metallicRoughnessTexture;e.metalnessMap=e.glossMap=t[a.index],e.metalnessMapChannel="b",e.glossMapChannel="g",Gs(a,e,["gloss","metalness"])}}if(c.hasOwnProperty("normalTexture")){let r=c.normalTexture;e.normalMap=t[r.index],Gs(r,e,["normal"]),r.hasOwnProperty("scale")&&(e.bumpiness=r.scale)}if(c.hasOwnProperty("occlusionTexture")){let r=c.occlusionTexture;e.aoMap=t[r.index],e.aoMapChannel="r",Gs(r,e,["ao"])}if(c.hasOwnProperty("emissiveFactor")){let[r,a,o]=c.emissiveFactor;e.emissive.set(r,a,o).gamma()}if(c.hasOwnProperty("emissiveTexture")){let r=c.emissiveTexture;e.emissiveMap=t[r.index],Gs(r,e,["emissive"])}if(c.hasOwnProperty("alphaMode"))switch(c.alphaMode){case"MASK":e.blendType=wt,c.hasOwnProperty("alphaCutoff")?e.alphaTest=c.alphaCutoff:e.alphaTest=.5;break;case"BLEND":e.blendType=ls,e.depthWrite=!1;break;default:case"OPAQUE":e.blendType=wt;break}else e.blendType=wt;c.hasOwnProperty("doubleSided")?(e.twoSidedLighting=c.doubleSided,e.cull=c.doubleSided?0:1):(e.twoSidedLighting=!1,e.cull=1);let i={KHR_materials_clearcoat:sj,KHR_materials_emissive_strength:hj,KHR_materials_ior:aj,KHR_materials_dispersion:oj,KHR_materials_iridescence:fj,KHR_materials_pbrSpecularGlossiness:tj,KHR_materials_sheen:lj,KHR_materials_specular:rj,KHR_materials_transmission:nj,KHR_materials_unlit:ij,KHR_materials_volume:cj,KHR_materials_anisotropy:uj};if(c.hasOwnProperty("extensions"))for(let r in c.extensions){let a=i[r];a!==void 0&&a(c.extensions[r],e,t)}return e.update(),e},dj=(c,t,e,s,i,r,a)=>{let o=A=>new an(kE(A.type),x_(A,s)),l={STEP:0,LINEAR:1,CUBICSPLINE:2},h={},f={},u={},d=1,p;for(p=0;p{let w=[];for(;A;)w.unshift(A.name),A=A.parent;return w},g=(A,w,I)=>{let D=f[A.output];if(!D)return;let O;if(r&&r[w.mesh]){let b=r[w.mesh];b.hasOwnProperty("extras")&&b.extras.hasOwnProperty("targetNames")&&(O=b.extras.targetNames)}let G=D.data,M=G.length/h[A.input].data.length,H=G.length/M,U=H*4,L=new ArrayBuffer(U*M);for(let b=0;b0&&w.paths[0].propertyPath[0]==="localRotation"&&w.interpolation!==2&&m.push(v[v.length-1].output))}m.sort();let E=null,y;for(p=0;p{let s=new Pe;if(c.hasOwnProperty("name")&&c.name.length>0?s.name=c.name:s.name=`node_${t}`,c.hasOwnProperty("matrix")&&(ix.data.set(c.matrix),ix.getTranslation(rx),s.setLocalPosition(rx),vG.setFromMat4(ix),s.setLocalRotation(vG),ix.getScale(rx),rx.x*=ix.scaleSign,s.setLocalScale(rx)),c.hasOwnProperty("rotation")){let i=c.rotation;s.setLocalRotation(i[0],i[1],i[2],i[3])}if(c.hasOwnProperty("translation")){let i=c.translation;s.setLocalPosition(i[0],i[1],i[2])}if(c.hasOwnProperty("scale")){let i=c.scale;s.setLocalScale(i[0],i[1],i[2])}return c.hasOwnProperty("extensions")&&c.extensions.EXT_mesh_gpu_instancing&&e.set(c,{ext:c.extensions.EXT_mesh_gpu_instancing}),s},mj=(c,t)=>{let e=c.type==="orthographic",s=e?c.orthographic:c.perspective,i={enabled:!1,projection:e?ni:ts,nearClip:s.znear,aspectRatioMode:Ac};s.zfar&&(i.farClip=s.zfar),e?(i.orthoHeight=s.ymag,s.xmag&&s.ymag&&(i.aspectRatioMode=vp,i.aspectRatio=s.xmag/s.ymag)):(i.fov=s.yfov*R.RAD_TO_DEG,s.aspectRatio&&(i.aspectRatioMode=vp,i.aspectRatio=s.aspectRatio));let r=new Ne(c.name);return r.addComponent("camera",i),r},_j=(c,t)=>{let e={enabled:!1,type:c.type==="point"?"omni":c.type,color:c.hasOwnProperty("color")?new F(c.color):F.WHITE,range:c.hasOwnProperty("range")?c.range:9999,falloffMode:dT,intensity:c.hasOwnProperty("intensity")?R.clamp(c.intensity,0,2):1};if(c.hasOwnProperty("spot")&&(e.innerConeAngle=c.spot.hasOwnProperty("innerConeAngle")?c.spot.innerConeAngle*R.RAD_TO_DEG:0,e.outerConeAngle=c.spot.hasOwnProperty("outerConeAngle")?c.spot.outerConeAngle*R.RAD_TO_DEG:45),c.hasOwnProperty("intensity")){let i=c.spot?.outerConeAngle??Math.PI/4,r=c.spot?.innerConeAngle??0;e.luminance=c.intensity*kc.getLightUnitConversion(ly[e.type],i,r)}let s=new Ne(t.name);return s.rotateLocal(90,0,0),s.addComponent("light",e),s},gj=(c,t,e,s)=>{if(!t.hasOwnProperty("skins")||t.skins.length===0)return[];let i=new Map;return t.skins.map(r=>QK(c,r,t.accessors,s,e,i))},Sj=(c,t,e,s)=>{let i={},r={},a={},o=[];return{meshes:!s.skipMeshes&&t?.meshes?.length&&t?.accessors?.length&&t?.bufferViews?.length?t.meshes.map(f=>ej(c,f,t.accessors,e,i,r,a,s,o)):[],meshVariants:r,meshDefaultMaterials:a,promises:o}},xj=(c,t,e)=>{if(!c.hasOwnProperty("materials")||c.materials.length===0)return[];let s=e?.material?.preprocess,i=e?.material?.process??EG,r=e?.material?.postprocess;return c.materials.map(a=>{s&&s(a);let o=i(a,t);return r&&r(a,o),o})},vj=c=>{if(!c.hasOwnProperty("extensions")||!c.extensions.hasOwnProperty("KHR_materials_variants"))return null;let t=c.extensions.KHR_materials_variants.variants,e={};for(let s=0;s{if(!c.hasOwnProperty("animations")||c.animations.length===0)return[];let i=s?.animation?.preprocess,r=s?.animation?.postprocess;return c.animations.map((a,o)=>{i&&i(a);let l=dj(a,o,c.accessors,e,t,c.meshes,c.nodes);return r&&r(a,l),l})},yj=(c,t,e,s)=>{let i=t.accessors;e.forEach((r,a)=>{let o=r.ext.attributes,l;if(o.hasOwnProperty("TRANSLATION")){let d=i[o.TRANSLATION];l=x_(d,s)}let h;if(o.hasOwnProperty("ROTATION")){let d=i[o.ROTATION];h=x_(d,s)}let f;if(o.hasOwnProperty("SCALE")){let d=i[o.SCALE];f=x_(d,s)}let u=(l?l.length/3:0)||(h?h.length/4:0)||(f?f.length/3:0);if(u){let d=new Float32Array(u*16),p=new x,m=new $,_=new x(1,1,1),S=new W,g=0;for(let T=0;T{if(!c.hasOwnProperty("nodes")||c.nodes.length===0)return[];let s=t?.node?.preprocess,i=t?.node?.process??pj,r=t?.node?.postprocess,a=c.nodes.map((o,l)=>{s&&s(o);let h=i(o,l,e);return r&&r(o,h),h});for(let o=0;o{let e=[],s=c.scenes.length;if(s===1&&c.scenes[0].nodes?.length===1){let i=c.scenes[0].nodes[0];e.push(t[i])}else for(let i=0;i{let s=null;if(c.hasOwnProperty("nodes")&&c.hasOwnProperty("cameras")&&c.cameras.length>0){let i=e?.camera?.preprocess,r=e?.camera?.process??mj,a=e?.camera?.postprocess;c.nodes.forEach((o,l)=>{if(o.hasOwnProperty("camera")){let h=c.cameras[o.camera];if(h){i&&i(h);let f=r(h,t[l]);a&&a(h,f),f&&(s||(s=new Map),s.set(o,f))}}})}return s},Pj=(c,t,e)=>{let s=null;if(c.hasOwnProperty("nodes")&&c.hasOwnProperty("extensions")&&c.extensions.hasOwnProperty("KHR_lights_punctual")&&c.extensions.KHR_lights_punctual.hasOwnProperty("lights")){let i=c.extensions.KHR_lights_punctual.lights;if(i.length){let r=e?.light?.preprocess,a=e?.light?.process??_j,o=e?.light?.postprocess;c.nodes.forEach((l,h)=>{if(l.hasOwnProperty("extensions")&&l.extensions.hasOwnProperty("KHR_lights_punctual")&&l.extensions.KHR_lights_punctual.hasOwnProperty("light")){let f=l.extensions.KHR_lights_punctual.light,u=i[f];if(u){r&&r(u);let d=a(u,t[h]);o&&o(u,d),d&&(s||(s=new Map),s.set(l,d))}}})}}return s},wj=(c,t,e)=>{c.nodes.forEach(s=>{s.hasOwnProperty("mesh")&&s.hasOwnProperty("skin")&&t[s.mesh].meshes.forEach(r=>{r.skin=e[s.skin]})})},Ij=async(c,t,e,s,i)=>{let r=i?.global?.preprocess,a=i?.global?.postprocess;r&&r(t),t.asset&&t.asset.generator;let o=new Map,l=Ej(t,i,o),h=Aj(t,l),f=Pj(t,l,i),u=Cj(t,l,i),d=vj(t),p=await Promise.all(e),{meshes:m,meshVariants:_,meshDefaultMaterials:S,promises:g}=Sj(c,t,p,i),T=Tj(t,l,p,i);yj(c,t,o,p);let C=await Promise.all(s),v=C.map(w=>w.resource),E=xj(t,v,i),y=gj(c,t,l,p),P=[];for(let w=0;w{let e=(i,r)=>{switch(i){case 9728:return 0;case 9729:return 1;case 9984:return 2;case 9985:return 4;case 9986:return 3;case 9987:return 5;default:return r}},s=(i,r)=>{switch(i){case 33071:return 1;case 33648:return 2;case 10497:return 0;default:return r}};c&&(t=t??{},c.minFilter=e(t.minFilter,5),c.magFilter=e(t.magFilter,1),c.addressU=s(t.wrapS,0),c.addressV=s(t.wrapT,0))},bj=0,S_=c=>c.extensions?.KHR_texture_basisu?.source??c.extensions?.EXT_texture_webp?.source??c.source,Dj=(c,t,e,s,i)=>{if(!c.images||c.images.length===0)return[];let r=i?.image?.preprocess,a=i?.image?.processAsync,o=i?.image?.postprocess,l={"image/png":"png","image/jpeg":"jpg","image/basis":"basis","image/ktx":"ktx","image/ktx2":"ktx2","image/vnd-ms.dds":"dds"},h=d=>{let p=new Set;return d.hasOwnProperty("materials")&&d.materials.forEach(m=>{if(m.hasOwnProperty("pbrMetallicRoughness")){let _=m.pbrMetallicRoughness;if(_.hasOwnProperty("baseColorTexture")){let S=d.textures[_.baseColorTexture.index];p.add(S_(S))}}if(m.hasOwnProperty("emissiveTexture")){let _=d.textures[m.emissiveTexture.index];p.add(S_(_))}if(m.hasOwnProperty("extensions")){let _=m.extensions.KHR_materials_sheen;if(_&&_.hasOwnProperty("sheenColorTexture")){let T=d.textures[_.sheenColorTexture.index];p.add(S_(T))}let S=m.extensions.KHR_materials_pbrSpecularGlossiness;if(S&&S.hasOwnProperty("specularGlossinessTexture")){let T=d.textures[S.specularGlossinessTexture.index];p.add(S_(T))}let g=m.extensions.KHR_materials_specular;if(g&&g.hasOwnProperty("specularColorTexture")){let T=d.textures[g.specularColorTexture.index];p.add(S_(T))}}}),p},f=(d,p,m,_,S,g)=>new Promise((T,C)=>{let v=E=>{let y=`${d.name||"gltf-texture"}-${bj++}`,P={url:p||y};if(E&&(P.contents=E.slice(0).buffer),_){let I=l[_];I&&(P.filename=`${P.url}.${I}`)}let A={srgb:g},w=new ae(y,"texture",P,A,S);w.on("load",I=>T(I)),w.on("error",I=>C(I)),s.add(w),s.load(w)};m?m.then(E=>v(E)):v(null)}),u=h(c);return c.images.map((d,p)=>{r&&r(d);let m;return a?m=new Promise((_,S)=>{a(d,(g,T)=>{g?S(g):_(T)})}):m=new Promise(_=>{_(null)}),m=m.then(_=>{let S=u.has(p);return _||(d.hasOwnProperty("uri")?TG(d.uri)?f(d,d.uri,null,VK(d.uri),null,S):f(d,Ja.test(d.uri)?d.uri:xe.join(e,d.uri),null,null,{crossOrigin:"anonymous"},S):d.hasOwnProperty("bufferView")&&d.hasOwnProperty("mimeType")?f(d,null,t[d.bufferView],d.mimeType,null,S):Promise.reject(new Error(`Invalid image found in gltf (neither uri or bufferView found). index=${p}`)))}),o&&(m=m.then(_=>(o(d,_),_))),m})},Lj=(c,t,e)=>{if(!c?.images?.length||!c?.textures?.length)return[];let s=e?.texture?.preprocess,i=e?.texture?.processAsync,r=e?.texture?.postprocess,a=new Set;return c.textures.map(o=>{s&&s(o);let l;return i?l=new Promise((h,f)=>{i(o,c.images,(u,d)=>{u?f(u):h(d)})}):l=new Promise(h=>{h(null)}),l=l.then(h=>{h=h??S_(o);let f=a.has(h);return a.add(h),t[h].then(u=>{let d=f?qK(u):u;return Rj(d.resource,(c.samplers??[])[o.sampler]),d})}),r&&(l=l.then(h=>(r(o,h),h))),l})},Mj=(c,t,e,s)=>{if(!c.buffers||c.buffers.length===0)return[];let i=s?.buffer?.preprocess,r=s?.buffer?.processAsync,a=s?.buffer?.postprocess;return c.buffers.map((o,l)=>{i&&i(o);let h;return r?h=new Promise((f,u)=>{r(o,(d,p)=>{d?u(d):f(p)})}):h=new Promise(f=>{f(null)}),h=h.then(f=>{if(f)return f;if(o.hasOwnProperty("uri")){if(TG(o.uri)){let u=atob(o.uri.split(",")[1]),d=new Uint8Array(u.length);for(let p=0;p{Le.get(Ja.test(o.uri)?o.uri:xe.join(e,o.uri),{cache:!0,responseType:"arraybuffer",retry:!1},(p,m)=>{p?d(p):u(new Uint8Array(m))})})}return t}),a&&(h=h.then(f=>(a(c.buffers[l],f),f))),h})},Oj=(c,t)=>{let s=JSON.parse((i=>{if(typeof TextDecoder<"u")return new TextDecoder().decode(i);let r="";for(let a=0;a{let e=c instanceof ArrayBuffer?new DataView(c):new DataView(c.buffer,c.byteOffset,c.byteLength),s=e.getUint32(0,!0),i=e.getUint32(4,!0),r=e.getUint32(8,!0);if(s!==1179937895){t(`Invalid magic number found in glb header. Expected 0x46546C67, found 0x${s.toString(16)}`);return}if(i!==2){t(`Invalid version number found in glb header. Expected 2, found ${i}`);return}if(r<=0||r>e.byteLength){t(`Invalid length found in glb header. Found ${r}`);return}let a=[],o=12;for(;oe.byteLength&&t(`Invalid chunk length found in glb. Found ${l}`);let h=e.getUint32(o+4,!0),f=new Uint8Array(e.buffer,e.byteOffset+o+8,l);a.push({length:l,type:h,data:f}),o+=l+8}if(a.length!==1&&a.length!==2){t("Invalid number of chunks found in glb file.");return}if(a[0].type!==1313821514){t(`Invalid chunk type found in glb file. Expected 0x4E4F534A, found 0x${a[0].type.toString(16)}`);return}if(a.length>1&&a[1].type!==5130562){t(`Invalid chunk type found in glb file. Expected 0x004E4942, found 0x${a[1].type.toString(16)}`);return}t(null,{gltfChunk:a[0].data,binaryChunk:a.length===2?a[1].data:null})},Nj=(c,t,e)=>{let s=()=>{let i=new Uint8Array(t);return i[0]===103&&i[1]===108&&i[2]===84&&i[3]===70};c&&c.toLowerCase().endsWith(".glb")||s()?Fj(t,e):e(null,{gltfChunk:t,binaryChunk:null})},Bj=(c,t,e)=>{let s=[],i=e?.bufferView?.preprocess,r=e?.bufferView?.processAsync,a=e?.bufferView?.postprocess;if(!c.bufferViews?.length)return s;for(let o=0;o{r(l,t,(d,p)=>{d?u(d):f(p)})}):h=new Promise(f=>{f(null)}),h=h.then(f=>f||t[l.buffer].then(u=>new Uint8Array(u.buffer,u.byteOffset+(l.byteOffset||0),l.byteLength))),l.hasOwnProperty("byteStride")&&(h=h.then(f=>(f.byteStride=l.byteStride,f))),a&&(h=h.then(f=>(a(l,f),f))),s.push(h)}return s},Il=class{static parse(t,e,s,i,r,a,o){Nj(t,s,(l,h)=>{if(l){o(l);return}Oj(h.gltfChunk,(f,u)=>{if(f){o(f);return}let d=Mj(u,h.binaryChunk,e,a),p=Bj(u,d,a),m=Dj(u,p,e,r,a),_=Lj(u,m,a);Ij(i,u,p,_,a).then(S=>o(null,S)).catch(S=>o(S))})})}static createDefaultMaterial(){return EG({name:"defaultGlbMaterial"},[])}};var v_=class extends Re{constructor(t){super(t,"animation"),this.device=t.graphicsDevice,this.assets=t.assets}load(t,e,s){typeof t=="string"&&(t={load:t,original:t});let i={retry:this.maxRetries>0,maxRetries:this.maxRetries};(t.load.startsWith("blob:")||t.load.startsWith("data:"))&&(xe.getExtension(t.original).toLowerCase()===".glb"?i.responseType=Vt.ResponseType.ARRAY_BUFFER:i.responseType=Vt.ResponseType.JSON),Le.get(t.load,i,(r,a)=>{r?e(`Error loading animation resource: ${t.original} [${r}]`):xe.getExtension(t.original).toLowerCase()===".glb"?Il.parse("filename.glb","",a,this.device,this.assets,s?.options??{},(o,l)=>{if(o)e(o);else{let h=l.animations;if(s?.data?.events)for(let f=0;f0,maxRetries:this.maxRetries};t.load.startsWith("blob:")&&(s.responseType=Vt.ResponseType.JSON),Le.get(t.load,s,(i,r)=>{i?e(`Error loading animation clip resource: ${t.original} [${i}]`):e(null,r)})}open(t,e){let s=e.name,i=e.duration,r=e.inputs.map(l=>new an(1,l)),a=e.outputs.map(l=>new an(l.components,l.data)),o=e.curves.map(l=>new Th([l.path],l.inputIndex,l.outputIndex,l.interpolation));return new Qs(s,i,r,a,o)}};var y_=class extends Re{constructor(t){super(t,"animstategraph")}load(t,e){typeof t=="string"&&(t={load:t,original:t});let s={retry:this.maxRetries>0,maxRetries:this.maxRetries};t.load.startsWith("blob:")&&(s.responseType=Vt.ResponseType.JSON),Le.get(t.load,s,(i,r)=>{i?e(`Error loading animation state graph resource: ${t.original} [${i}]`):e(null,r)})}open(t,e){return new en(e)}};var Uj=[".ogg",".mp3",".wav",".mp4a",".m4a",".mp4",".aac",".opus"],E_=class extends Re{constructor(t){super(t,"audio"),this.manager=t.soundManager}_isSupported(t){let e=xe.getExtension(t);return Uj.indexOf(e)>-1}load(t,e){typeof t=="string"&&(t={load:t,original:t});let s=function(r){e(null,new sp(r))},i=function(r){let a=`Error loading audio url: ${t.original}`;r&&(a+=`: ${r.message||r}`),e(a)};if(this._createSound){if(!this._isSupported(t.original)){i(`Audio format for ${t.original} not supported`);return}this._createSound(t.load,s,i)}else i(null)}_createSound(t,e,s){let i=this.manager;if(!i.context){s("Audio manager has no audio context");return}let r={retry:this.maxRetries>0,maxRetries:this.maxRetries};(t.startsWith("blob:")||t.startsWith("data:"))&&(r.responseType=Vt.ResponseType.ARRAY_BUFFER),Le.get(t,r,(a,o)=>{if(a){s(a);return}i.context.decodeAudioData(o,e,s)})}};var A_=class extends Re{constructor(t){super(t,"binary")}load(t,e){typeof t=="string"&&(t={load:t,original:t}),Le.get(t.load,{responseType:Vt.ResponseType.ARRAY_BUFFER,retry:this.maxRetries>0,maxRetries:this.maxRetries},(s,i)=>{s?e(`Error loading binary resource: ${t.original} [${s}]`):e(null,i)})}openBinary(t){return t.buffer}};var C_=class c{constructor(t,e,s,i){let r=function(h,f,u){let d=c.createAsset(e.name,h,f,u);return s.add(d),d},a=[];for(let h=0;h{let f=new Ne(void 0,this._assets._loader._app);l._cloneInternal(f),o||(o=f);let u=null,d=null;for(let m=0;m{o.meshInstance.skinInstance=Eu.createCachedSkinInstance(o.meshInstance.mesh.skin,o.rootBone,o.entity),o.meshInstance.node.render.rootBone=o.rootBone}),c.createSceneHierarchy(a,Ne)}getMaterialVariants(){return this.data.variants?Object.keys(this.data.variants):[]}applyMaterialVariant(t,e){let s=e?this.data.variants[e]:null;if(s===void 0)return;let i=t.findComponents("render");for(let r=0;r{if(t===null)s.material=this._defaultMaterial;else{let i=this.data.meshVariants[s.mesh.id];i&&(s.material=this.data.materials[i[t]])}})}static createSceneHierarchy(t,e){let s=null;if(t.length===1)s=t[0];else{s=new e("SceneGroup");for(let i of t)s.addChild(i)}return s}static createModel(t,e){let s=function(a,o,l,h,f,u,d){let p=t.meshDefaultMaterials[o.id],m=p===void 0?e:f[p],_=new we(o,m,u);if(o.morph){let S=new Ar(o.morph);_.morphInstance=S,a.morphInstances.push(S)}if(d.hasOwnProperty("skin")){let S=d.skin,g=l[S];o.skin=g;let T=h[S];_.skinInstance=T,a.skinInstances.push(T)}a.meshInstances.push(_)},i=new Ei,r=[];for(let a of t.skins){let o=new er(a);o.bones=a.bones,r.push(o)}i.graph=c.createSceneHierarchy(t.scenes,Pe);for(let a=0;a{e(r)})};this.animations&&(s(this.animations),this.animations=null),this.textures&&(s(this.textures),this.textures=null),this.materials&&(s(this.materials),this.materials=null),this.renders&&(s(this.renders),this.renders=null),this._model&&(e(this._model),this._model=null),this.data=null,this.assets=null}};var zE=class{constructor(t,e,s){this._device=t,this._assets=e,this._defaultMaterial=Il.createDefaultMaterial(),this.maxRetries=s}_getUrlWithoutParams(t){return t.indexOf("?")>=0?t.split("?")[0]:t}load(t,e,s){ae.fetchArrayBuffer(t.load,(i,r)=>{i?e(i):Il.parse(this._getUrlWithoutParams(t.original),xe.extractPath(t.load),r,this._device,s.registry,s.options,(a,o)=>{a?e(a):e(null,new C_(o,s,this._assets,this._defaultMaterial))})},s,this.maxRetries)}open(t,e,s){return e}patch(t,e){}};var GE=class{instantiateModelEntity(t){return null}instantiateRenderEntity(t){return null}getMaterialVariants(){return null}applyMaterialVariant(t,e){}applyMaterialVariantInstances(t,e){}},P_=class extends Re{constructor(t){super(t,"container"),this.glbContainerParser=new zE(t.graphicsDevice,t.assets,0),this.parsers={}}set maxRetries(t){this.glbContainerParser.maxRetries=t;for(let e in this.parsers)this.parsers.hasOwnProperty(e)&&(this.parsers[e].maxRetries=t)}get maxRetries(){return this.glbContainerParser.maxRetries}_getUrlWithoutParams(t){return t.indexOf("?")>=0?t.split("?")[0]:t}_getParser(t){let e=t?xe.getExtension(this._getUrlWithoutParams(t)).toLowerCase().replace(".",""):null;return this.parsers[e]||this.glbContainerParser}load(t,e,s){typeof t=="string"&&(t={load:t,original:t}),this._getParser(t.original).load(t,e,s)}open(t,e,s){return this._getParser(t).open(t,e,s)}};var w_=class extends Re{constructor(e){super(e,"css");n(this,"decoder",null)}load(e,s){typeof e=="string"&&(e={load:e,original:e}),Le.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(i,r)=>{i?s(`Error loading css resource: ${e.original} [${i}]`):s(null,r)})}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)}};var I_=class extends Re{constructor(t){super(t,"cubemap"),this._device=t.graphicsDevice,this._registry=t.assets,this._loader=t.loader}load(t,e,s){this.loadAssets(s,e)}open(t,e,s){return s?s.resource:null}patch(t,e){this.loadAssets(t,(s,i)=>{s&&(e.fire("error",t),e.fire(`error:${t.id}`,s,t),t.fire("error",t))})}getAssetIds(t){let e=[];if(e[0]=t.file,(t.loadFaces||!t.file)&&t.data&&t.data.textures)for(let s=0;s<6;++s)e[s+1]=t.data.textures[s];else e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=null;return e}compareAssetIds(t,e){return t&&e?parseInt(t,10)===t||typeof t=="string"?t===e:t.url===e.url:t!==null==(e!==null)}update(t,e,s){let i=t.data||{},r=t._handlerState.assets,a=t._resources,o,l,h,f=[null,null,null,null,null,null,null],u=function(){return i.hasOwnProperty("type")?i.type:i.hasOwnProperty("rgbm")?i.rgbm?_i:Gt:null};if(!t.loaded||s[0]!==r[0]){if(s[0])if(o=s[0].resource,o.cubemap)for(h=0;h<6;++h)f[h+1]=new Z(this._device,{name:`${t.name}_prelitCubemap${o.width>>h}`,cubemap:!0,type:u()||o.type,width:o.width>>h,height:o.height>>h,format:o.format,levels:[o._levels[h]],addressU:1,addressV:1,mipmaps:h===0});else f[1]=o}else f[1]=a[1]||null,f[2]=a[2]||null,f[3]=a[3]||null,f[4]=a[4]||null,f[5]=a[5]||null,f[6]=a[6]||null;let d=s.slice(1);if(!t.loaded||!this.cmpArrays(d,r.slice(1))){if(d.indexOf(null)===-1){let p=d.map(g=>g.resource),m=[];for(l=0;lg._levels[l]));let _=p[0].format,S=new Z(this._device,{name:`${t.name}_faces`,cubemap:!0,type:u()||p[0].type,width:p[0].width,height:p[0].height,format:_===Ss?ce:_,mipmaps:i.mipmaps??!0,levels:m,minFilter:i.hasOwnProperty("minFilter")?i.minFilter:p[0].minFilter,magFilter:i.hasOwnProperty("magFilter")?i.magFilter:p[0].magFilter,anisotropy:i.hasOwnProperty("anisotropy")?i.anisotropy:1,addressU:1,addressV:1});f[0]=S}}else f[0]=a[0]||null;if(!this.cmpArrays(f,a))for(t.resources=f,t._handlerState.assetIds=e,t._handlerState.assets=s,h=0;h{let T=l.get(g);T?d(S,T):u(S,`failed to find dependent cubemap asset=${g}`)}).bind(null,m,_));else{let S=typeof _=="string"?{url:_,filename:_}:_,g=S.url.search(".dds")===-1?{type:"rgbp",addressu:"clamp",addressv:"clamp",mipmaps:!1}:null;p=new ae(`${t.name}_part_${m}`,"texture",S,g),l.add(p),d(m,p)}}}};var R_=class extends Re{constructor(t){super(t,"folder")}load(t,e){e(null,null)}};var Ou=class{constructor(t,e){this.type=e?e.type||vu:vu,this.em=1,this.textures=t,this.intensity=0,this._data=null,this.data=e}set data(t){if(this._data=t,!!t&&(this._data.intensity!==void 0&&(this.intensity=this._data.intensity),this._data.info||(this._data.info={}),(!this._data.version||this._data.version<2)&&(this._data.info.maps=[{width:this._data.info.width,height:this._data.info.height}],this._data.chars)))for(let e in this._data.chars)this._data.chars[e].map=0}get data(){return this._data}};function nb(c){return c.version<3&&(c.version<2&&(c.info.maps=c.info.maps||[{width:c.info.width,height:c.info.height}]),c.chars=Object.keys(c.chars||{}).reduce((t,e)=>{let s=c.chars[e],i=s.letter!==void 0?s.letter:Nr.fromCodePoint(e);return c.version<2&&(s.map=s.map||0),t[i]=s,t},{}),c.version=3),c}var b_=class extends Re{constructor(t){super(t,"font"),this._loader=t.loader,this.maxRetries=0}load(t,e,s){typeof t=="string"&&(t={load:t,original:t});let i=this;xe.getExtension(t.original)===".json"?Le.get(t.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(r,a)=>{if(r)e(`Error loading font resource: ${t.original} [${r}]`);else{let o=nb(a);i._loadTextures(t.load.replace(".json",".png"),o,(l,h)=>{l?e(l):e(null,{data:o,textures:h})})}}):(s&&s.data&&(s.data=nb(s.data)),this._loadTextures(t.load,s&&s.data,e))}_loadTextures(t,e,s){let i=e.info.maps.length,r=0,a=null,o=new Array(i),l=this._loader,h=function(f){let u=function(d,p){if(!a){if(d){a=d,s(d);return}p.upload(),o[f]=p,r++,r===i&&s(null,o)}};f===0?l.load(t,"texture",u):l.load(t.replace(".png",`${f}.png`),"texture",u)};for(let f=0;f{let y=(1<{v.x=o(E>>>21,11),v.y=o(E>>>11,10),v.z=o(E,11)},h=(v,E)=>{v.x=o(E>>>24,8),v.y=o(E>>>16,8),v.z=o(E>>>8,8),v.w=o(E,8)},f=(v,E)=>{let y=Math.SQRT2,P=(o(E>>>20,10)-.5)*y,A=(o(E>>>10,10)-.5)*y,w=(o(E,10)-.5)*y,I=Math.sqrt(1-(P*P+A*A+w*w));switch(E>>>30){case 0:v.set(P,A,w,I);break;case 1:v.set(I,A,w,P);break;case 2:v.set(A,I,w,P);break;case 3:v.set(A,w,I,P);break}},u=(v,E,y)=>v*(1-y)+E*y,{chunkData:d,chunkSize:p,vertexData:m,shData0:_,shData1:S,shData2:g,shBands:T}=t,C=[3,8,15][T-1];this.read=v=>{let E=Math.floor(v/256)*p;if(e&&(l(e,m[v*4+0]),e.x=u(d[E+0],d[E+3],e.x),e.y=u(d[E+1],d[E+4],e.y),e.z=u(d[E+2],d[E+5],e.z)),s&&f(s,m[v*4+1]),i&&(l(i,m[v*4+2]),i.x=u(d[E+6],d[E+9],i.x),i.y=u(d[E+7],d[E+10],i.y),i.z=u(d[E+8],d[E+11],i.z)),r&&(h(r,m[v*4+3]),p>12&&(r.x=u(d[E+12],d[E+15],r.x),r.y=u(d[E+13],d[E+16],r.y),r.z=u(d[E+14],d[E+17],r.z))),a&&T>0){let y=[_,S,g];for(let P=0;P<3;++P)for(let A=0;A<15;++A)a[P*15+A]=A>>21)/2047,T=(S>>>11&1023)/1023,C=(S&2047)/2047;r[_*3+0]=(1-g)*a+g*h,r[_*3+1]=(1-T)*o+T*f,r[_*3+2]=(1-C)*l+C*u}}return r}getChunks(t){let{chunkData:e,numChunks:s,chunkSize:i}=this,r,a,o,l,h,f;for(let u=0;u0){let f=[];for(let d=0;d<45;++d)f.push(`f_rest_${d}`);let u=Math.max(...["f_dc_0","f_dc_1","f_dc_2"].map(d=>t.indexOf(d)));t.splice(u+1,0,...f)}let s={};t.forEach(f=>{s[f]=new Float32Array(this.numSplats)});let i=new x,r=new $,a=new x,o=new Q,l=e>0?new Float32Array(45):null,h=this.createIter(i,r,a,o,l);for(let f=0;f=1?40:-Math.log(1/o.w-1),l)for(let u=0;u<45;++u)s[`f_rest_${u}`][f]=l[u];return new Qa([{name:"vertex",count:this.numSplats,properties:t.map(f=>({name:f,type:"float",byteSize:4,storage:s[f]}))}],this.comments)}};var kj=(c,t,e,s,i)=>{for(let r=0;r0&&(f.push({name:"shTexture0",format:At}),f.push({name:"shTexture1",format:At}),f.push({name:"shTexture2",format:At})),this._format=new Pr(t,f,{readGLSL:'#include "gsplatCompressedVS"',readWGSL:'#include "gsplatCompressedVS"'}),this.streams.init(this.format,o);let u=this.streams.getTexture("packedTexture");if(u.lock().set(l),u.unlock(),h>0){let S=this.streams.getTexture("shTexture0"),g=this.streams.getTexture("shTexture1"),T=this.streams.getTexture("shTexture2");S.lock().set(new Uint32Array(e.shData0.buffer)),S.unlock(),g.lock().set(new Uint32Array(e.shData1.buffer)),g.unlock(),T.lock().set(new Uint32Array(e.shData2.buffer)),T.unlock()}let p=this.evalChunkTextureSize(a),m=this.streams.createTexture("chunkTexture",ke,p);this.streams.textures.set("chunkTexture",m);let _=m.lock();if(kj(_,20,i,r,a),r===12)for(let S=0;S=s)this.head>0?(this.data.copyWithin(0,this.head,this.tail),this.data.set(t,e),this.head=0,this.tail=s):(this.data.set(t,this.tail),this.tail+=t.length);else{let i=new Uint8Array(s);this.head>0||this.tail0&&(this.data.copyWithin(0,this.head,this.tail),this.tail-=this.head,this.head=0)}get remaining(){return this.tail-this.head}getInt8(){let t=this.view.getInt8(this.head);return this.head++,t}getUint8(){let t=this.view.getUint8(this.head);return this.head++,t}getInt16(){let t=this.view.getInt16(this.head,!0);return this.head+=2,t}getUint16(){let t=this.view.getUint16(this.head,!0);return this.head+=2,t}getInt32(){let t=this.view.getInt32(this.head,!0);return this.head+=4,t}getUint32(){let t=this.view.getUint32(this.head,!0);return this.head+=4,t}getFloat32(){let t=this.view.getFloat32(this.head,!0);return this.head+=4,t}getFloat64(){let t=this.view.getFloat64(this.head,!0);return this.head+=8,t}},zj=c=>{let t=[],e=[],s;for(let i=1;i{let t=["min_x","min_y","min_z","max_x","max_y","max_z","min_scale_x","min_scale_y","min_scale_z","max_scale_x","max_scale_y","max_scale_z","min_r","min_g","min_b","max_r","max_g","max_b"],e=["packed_position","packed_rotation","packed_scale","packed_color"],s=new Array(45).fill("").map((a,o)=>`f_rest_${o}`),i=()=>c[0].name==="chunk"&&c[0].properties.every((a,o)=>a.name===t[o]&&a.type==="float")&&c[1].name==="vertex"&&c[1].properties.every((a,o)=>a.name===e[o]&&a.type==="uint"),r=()=>c[2].name==="sh"&&[9,24,45].indexOf(c[2].properties.length)!==-1&&c[2].properties.every((a,o)=>a.name===s[o]&&a.type==="uchar");return c.length===2&&i()||c.length===3&&i()&&r()},Vj=c=>c.length===1&&c[0].name==="vertex"&&c[0].properties.every(t=>t.type==="float"),Hj=async(c,t,e)=>{let s=new VE;s.comments=e;let i=t[0].count,r=t[0].properties.length,a=t[1].count,l=(f=>{let u=Math.ceil(Math.sqrt(f)),d=Math.ceil(f/u);return u*d})(a);s.numSplats=a,s.chunkData=new Float32Array(i*r),s.vertexData=new Uint32Array(l*4);let h=async(f,u)=>{let d=new Uint8Array(f),p=0;for(;p{let s=t[0],i=s.properties,r=i.length,a=i.map(u=>u.storage),o=i.reduce((u,d)=>u+d.byteSize,0),l=0,h,f=()=>{let u=c.data.buffer;h?.buffer!==u&&(h=new Float32Array(u,0,u.byteLength/4))};for(f();l{for(let s=0;sl+h.byteSize,0),a=i.properties.map(l=>{if(l.storage)switch(l.type){case"char":return(h,f)=>{l.storage[f]=h.getInt8()};case"uchar":return(h,f)=>{l.storage[f]=h.getUint8()};case"short":return(h,f)=>{l.storage[f]=h.getInt16()};case"ushort":return(h,f)=>{l.storage[f]=h.getUint16()};case"int":return(h,f)=>{l.storage[f]=h.getInt32()};case"uint":return(h,f)=>{l.storage[f]=h.getUint32()};case"float":return(h,f)=>{l.storage[f]=h.getFloat32()};case"double":return(h,f)=>{l.storage[f]=h.getFloat64()};default:throw new Error(`Unsupported property data type '${l.type}' in ply header`)}else return h=>{h.head+=l.byteSize}}),o=0;for(;o{let s=(d,p)=>{let m=d.length-p.length,_,S;for(_=0;_<=m;++_){for(S=0;S{if(d.length=AG.length&&!i(r.data,AG))throw new Error("Invalid ply header");if(a=s(r.data,CG),a!==-1)break}let o=new TextDecoder("ascii").decode(r.data.subarray(0,a)).split(` `),{elements:l,format:h,comments:f}=zj(o);if(h!=="binary_little_endian")throw new Error("Unsupported ply format");return r.head=a+CG.length,r.compact(),await(async()=>Gj(l)?await Hj(r,l,f):(l.forEach(d=>{d.properties.forEach(p=>{let m=hb.get(p.type);if(m){let _=!t||t(p.name)?new m(d.count):null;p.storage=_}})}),Vj(l)?await Wj(r,l,f):await Xj(r,l,f)))()},Kj=c=>!0,WE=class{constructor(t,e){n(this,"app");n(this,"maxRetries");this.app=t,this.maxRetries=e}async load(t,e,s){let i=this.app.scene?.gsplatCentersEnabled!==!1;try{let r=await(s.file?.contents??fetch(t.load));if(!r||!r.body)e("Error loading resource",null);else{let a=parseInt(r.headers.get("content-length")??"0",10),o=0,l=await Yj(r.body.getReader(),s.data.elementFilter??Kj,u=>{o+=u,s&&s.fire("progress",o,a)});s.fire("load:data",l),l.isCompressed||(s.data.reorder??!0)&&l.reorderData();let h=i,f=l.isCompressed&&!s.data.decompress?new HE(this.app.graphicsDevice,l,{prepareCenters:h}):new $o(this.app.graphicsDevice,l.isCompressed?l.decompress():l,{prepareCenters:h});e(null,f)}}catch(r){e(r,null)}}open(t,e){return e}};var jj=(c,t)=>{let e=new Map,s=t.length,i=()=>{let r=0,a=0;e.forEach(l=>{r+=l.loaded,a+=l.total});let o=e.size;o>0&&o{let a=(l,h)=>{e.set(r,{loaded:l,total:h}),i()},o=()=>{r.off("progress",a),r.off("load",o),r.off("error",o)};r.on("progress",a),r.on("load",o),r.on("error",o)})},qj=c=>{let t={version:1,count:c.means.shape[0],means:{mins:c.means.mins,maxs:c.means.maxs,files:c.means.files},scales:{mins:c.scales.mins,maxs:c.scales.maxs,files:c.scales.files},quats:{files:c.quats.files},sh0:{mins:c.sh0.mins,maxs:c.sh0.maxs,files:c.sh0.files}};return c.shN&&(t.shN={mins:c.shN.mins,maxs:c.shN.maxs,files:c.shN.files}),t},XE=class{constructor(t,e){n(this,"app");n(this,"maxRetries");this.app=t,this.maxRetries=e}_shouldAbort(t,e){return!!(e||!this.app.assets.get(t.id)||!this.app?.graphicsDevice||this.app.graphicsDevice._destroyed)}async loadTextures(t,e,s,i){let r=this.app.scene?.gsplatCentersEnabled!==!1;i.version!==2&&(i=qj(i));let{assets:a}=this.app,o=["means","quats","scales","sh0","shN"],l={},h=[],f=window.document?.baseURI??window.location.href;o.forEach(g=>{let T=i[g]?.files??[];l[g]=T.map(C=>{let v=new ae(C,"texture",{url:s.options?.mapUrl?.(C)??new URL(C,new URL(t.load,f).toString()).toString(),filename:C},{mipmaps:!1},{crossOrigin:"anonymous"}),E=new Promise((y,P)=>{v.on("load",()=>y(null)),v.on("error",A=>P(A))});return a.add(v),h.push(E),v})});let u=o.map(g=>l[g]).flat(),d=!1;if(s.once("unload",()=>{d=!0,u.forEach(g=>{a.remove(g),g.unload()})}),jj(s,u),u.forEach(g=>a.load(g)),await Promise.allSettled(h),this._shouldAbort(s,d)){u.forEach(g=>{a.remove(g),g.unload()}),e(null,null);return}let p=new ca;p.url=t.original,p.meta=i,p.numSplats=i.count,p.means_l=l.means[0].resource,p.means_u=l.means[1].resource,p.quats=l.quats[0].resource,p.scales=l.scales[0].resource,p.sh0=l.sh0[0].resource,p.sh_centroids=l.shN?.[0]?.resource,p.sh_labels=l.shN?.[1]?.resource,p.shBands=ca.calcBands(p.sh_centroids?.width);let m=s.data?.decompress;if(!m){if(this._shouldAbort(s,d)){p.destroy(),e(null,null);return}p.prepareCodebook(),r&&await p.prepareGpuData()}if(this._shouldAbort(s,d)){p.destroy(),e(null,null);return}let _=r,S=m?new $o(this.app.graphicsDevice,await p.decompress(),{prepareCenters:_}):new jc(this.app.graphicsDevice,p,{prepareCenters:_});if(this._shouldAbort(s,d)){S.destroy(),e(null,null);return}e(null,S)}load(t,e,s){if(s.data?.means)this.loadTextures(t,e,s,s.data);else{typeof t=="string"&&(t={load:t,original:t});let i={retry:this.maxRetries>0,maxRetries:this.maxRetries,responseType:Vt.ResponseType.JSON};Le.get(t.load,i,(r,a)=>{if(this._shouldAbort(s,!1)){e(null,null);return}r?e(`Error loading gsplat meta: ${t.original} [${r}]`):this.loadTextures(t,e,s,a)})}}};var $j=c=>{let t=new DataView(c),e=f=>t.getUint16(f,!0),s=f=>t.getUint32(f,!0),i=f=>({magic:s(f),numFiles:e(f+8),cdSizeBytes:s(f+12),cdOffsetBytes:s(f+16)}),r=f=>{let u=e(f+28),d=e(f+30),p=e(f+32);return{magic:s(f),compressionMethod:e(f+10),compressedSizeBytes:s(f+20),uncompressedSizeBytes:s(f+24),lfhOffsetBytes:s(f+42),filename:new TextDecoder().decode(new Uint8Array(c,f+46,u)),recordSizeBytes:46+u+d+p}},a=f=>{let u=e(f+26),d=e(f+28);return{magic:s(f),offsetBytes:f+30+u+d}},o=i(t.byteLength-22);if(o.magic!==101010256)throw new Error("Invalid zip file: EOCDR not found");if(o.cdOffsetBytes===4294967295||o.cdSizeBytes===4294967295)throw new Error("Invalid zip file: Zip64 not supported");let l=[],h=o.cdOffsetBytes;for(let f=0;f{let t=new DecompressionStream("deflate-raw"),e=new Blob([c]).stream().pipeThrough(t),s=await new Response(e).arrayBuffer();return new Uint8Array(s)},Qj=async(c,t)=>{let e=await(t.file?.contents??fetch(c.load));if(!e)throw new Error("Error loading resource");if(e instanceof Response){if(!e.ok)throw new Error(`Error loading resource: ${e.status} ${e.statusText}`);let s=parseInt(e.headers.get("content-length")??"0",10);if(!e.body||!e.body.getReader){let o=await e.arrayBuffer();return t.fire("progress",o.byteLength,s),o}let i=e.body.getReader(),r=[],a=0;try{for(;;){let{done:o,value:l}=await i.read();if(o)break;r.push(l),a+=l.byteLength,t.fire("progress",a,s)}}finally{i.releaseLock()}return new Blob(r).arrayBuffer()}return e},YE=class{constructor(t,e=3){n(this,"app");n(this,"maxRetries");this.app=t,this.maxRetries=e}async load(t,e,s){let i=this.app.scene?.gsplatCentersEnabled!==!1;try{let r=await Qj(t,s),a=$j(r);for(let g of a)g.compression==="deflate"&&(g.data=await Zj(g.data));let o=a.find(g=>g.filename==="meta.json");if(!o){e("Error: meta.json not found");return}let l;try{l=JSON.parse(new TextDecoder().decode(o.data))}catch(g){e(`Error parsing meta.json: ${g}`);return}let h=["means","scales","quats","sh0","shN"].map(g=>l[g]?.files??[]).flat(),f={},u=[];for(let g of h){let T=a.find(E=>E.filename===g),C;if(T)C=new ae(g,"texture",{url:`${t.load}/${g}`,filename:g,contents:T.data},{mipmaps:!1},{crossOrigin:"anonymous"});else{let E=new URL(g,new URL(g,window.location.href).toString()).toString();C=new ae(g,"texture",{url:E,filename:g},{mipmaps:!1},{crossOrigin:"anonymous"})}let v=new Promise((E,y)=>{C.on("load",()=>E(null)),C.on("error",P=>y(P))});this.app.assets.add(C),f[g]=C,u.push(v)}Object.values(f).forEach(g=>this.app.assets.load(g)),await Promise.allSettled(u);let{assets:d}=this.app;s.once("unload",()=>{Object.values(f).forEach(g=>{d.remove(g),g.unload()})});let p=s.data?.decompress,m=new ca;m.url=t.original,m.meta=l,m.numSplats=l.count,m.means_l=f[l.means.files[0]].resource,m.means_u=f[l.means.files[1]].resource,m.quats=f[l.quats.files[0]].resource,m.scales=f[l.scales.files[0]].resource,m.sh0=f[l.sh0.files[0]].resource,m.sh_centroids=f[l.shN?.files[0]]?.resource,m.sh_labels=f[l.shN?.files[1]]?.resource,m.shBands=ca.calcBands(m.sh_centroids?.width),p||(m.prepareCodebook(),i&&await m.prepareGpuData());let _=i,S=p?new $o(this.app.graphicsDevice,await m.decompress(),{prepareCenters:_}):new jc(this.app.graphicsDevice,m,{prepareCenters:_});e(null,S)}catch(r){e(r)}}};var KE=class{load(t){}unload(t){}getResource(t){}destroy(){}};var jE=class extends KE{constructor(e){super();n(this,"_urlToAsset",new Map);n(this,"_registry");n(this,"maxConcurrentLoads",2);n(this,"maxRetries",2);n(this,"_currentlyLoading",new Set);n(this,"_loadQueue",[]);n(this,"_retryCount",new Map);n(this,"_destroyed",!1);this._registry=e}destroy(){this._destroyed=!0;for(let e of this._urlToAsset.values())e.fire("unload",e),e.off("load"),e.off("error"),this._registry.remove(e),e.unload();this._urlToAsset.clear(),this._loadQueue.length=0,this._currentlyLoading.clear(),this._retryCount.clear()}_canLoad(){return!!this._registry.loader?.getHandler("gsplat")}load(e){this._urlToAsset.get(e)?.loaded||this._currentlyLoading.has(e)||this._loadQueue.includes(e)||(this._currentlyLoading.sizethis._onAssetLoadSuccess(e,s)),s.once("error",i=>this._onAssetLoadError(e,s,i)),!s.loaded&&!s.loading&&this._registry.load(s)}_onAssetLoadSuccess(e,s){this._destroyed||!this._urlToAsset.has(e)||(this._currentlyLoading.delete(e),this._retryCount.delete(e),this._processQueue())}_onAssetLoadError(e,s,i){if(this._destroyed||!this._canLoad()||!this._urlToAsset.has(e))return;let r=this._retryCount.get(e)||0;r0;){let e=this._loadQueue.shift();e&&this._startLoading(e)}}unload(e){this._currentlyLoading.delete(e);let s=this._loadQueue.indexOf(e);s!==-1&&this._loadQueue.splice(s,1),this._retryCount.delete(e);let i=this._urlToAsset.get(e);i&&(i.fire("unload",i),i.off("load"),i.off("error"),this._registry.remove(i),i.unload(),this._urlToAsset.delete(e)),this._processQueue()}getResource(e){return this._urlToAsset.get(e)?.resource}};var qE=class{constructor(t,e){n(this,"app");n(this,"maxRetries");this.app=t,this.maxRetries=e}load(t,e,s){typeof t=="string"&&(t={load:t,original:t});let i={retry:this.maxRetries>0,maxRetries:this.maxRetries,responseType:Vt.ResponseType.JSON};Le.get(t.load,i,(r,a)=>{if(r)e(`Error loading gsplat octree: ${t.original} [${r}]`);else{let o=new jE(this.app.assets),l=new d_(s.file.url,a,o);e(null,l)}})}};var D_=class extends Re{constructor(t){super(t,"gsplat"),this.parsers={ply:new WE(t,3),sog:new YE(t),json:new XE(t,3),octree:new qE(t,3)}}_getUrlWithoutParams(t){return t.indexOf("?")>=0?t.split("?")[0]:t}_getParser(t){let e=xe.getBasename(this._getUrlWithoutParams(t)).toLowerCase();if(e==="lod-meta.json")return this.parsers.octree;let s=xe.getExtension(e).replace(".","");return this.parsers[s]||this.parsers.ply}load(t,e,s){typeof t=="string"&&(t={load:t,original:t}),this._getParser(t.original).load(t,e,s)}open(t,e,s){return e}};var Fu=class{static setCompressedPRS(t,e,s){let i=s.singleVecs,r,a,o=e.___1;o||(r=s.tripleVecs,a=e.___2);let l=o?o[0]:r[a];t.setLocalPosition(i[l],i[l+1],i[l+2]),l=o?o[1]:r[a+1],t.setLocalEulerAngles(i[l],i[l+1],i[l+2]),l=o?o[2]:r[a+2],t.setLocalScale(i[l],i[l+1],i[l+2])}static oneCharToKey(t,e){let s=t.charCodeAt(0)-e.fieldFirstCode;return e.fieldArray[s]}static multCharToKey(t,e){let s=0;for(let i=0;i0,maxRetries:e},(i,r)=>{if(!i)s(i,r);else{let a=`Error while loading scene JSON ${t.original}`;i.message?(a+=`: ${i.message}`,i.stack&&(a+=` ${i.stack}`)):a+=`: ${i}`,s(a)}})}};var L_=class extends Re{constructor(t){super(t,"hierarchy")}load(t,e){Eh.load(t,this.maxRetries,e)}open(t,e){this._app.systems.script.preloading=!0;let i=new yh(this._app,!1).parse(e);return this._app.systems.script.preloading=!1,i}};var M_=class extends Re{constructor(e){super(e,"html");n(this,"decoder",null)}load(e,s){typeof e=="string"&&(e={load:e,original:e}),Le.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(i,r)=>{i?s(`Error loading html resource: ${e.original} [${i}]`):s(null,r)})}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)}};var O_=class extends Re{constructor(e){super(e,"json");n(this,"decoder",null)}load(e,s){typeof e=="string"&&(e={load:e,original:e});let i={retry:this.maxRetries>0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(i.responseType=Vt.ResponseType.JSON),Le.get(e.load,i,(r,a)=>{r?s(`Error loading JSON resource: ${e.original} [${r}]`):s(null,a)})}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),JSON.parse(this.decoder.decode(e))}};var ZE=class{constructor(){this.removeInvalid=!0,this.valid=!0,this.enumValidators={occludeSpecular:this._createEnumValidator([xT,Bo,vT]),cull:this._createEnumValidator([0,1,2,3]),blendType:this._createEnumValidator([rp,ea,ls,wt,Ms,ap,op,np,lp,cp,hp]),depthFunc:this._createEnumValidator([0,1,2,3,4,5,6,7])}}setInvalid(t,e){this.valid=!1,this.removeInvalid&&delete e[t]}validate(t){let e=Mc,s=WL,i=t.mappingFormat==="path";for(let r in t){let a=e[r];if(!a){s[r]?delete t[r]:this.valid=!1;continue}if(a.startsWith("enum")){let o=a.split(":")[1];this.enumValidators[o]&&(this.enumValidators[o](t[r])||this.setInvalid(r,t))}else if(a==="number")typeof t[r]!="number"&&this.setInvalid(r,t);else if(a==="boolean")typeof t[r]!="boolean"&&this.setInvalid(r,t);else if(a==="string")typeof t[r]!="string"&&this.setInvalid(r,t);else if(a==="vec2")t[r]instanceof Array&&t[r].length===2||this.setInvalid(r,t);else if(a==="rgb")t[r]instanceof Array&&t[r].length===3||this.setInvalid(r,t);else if(a==="texture")i?typeof t[r]=="string"||t[r]===null||t[r]instanceof Z||this.setInvalid(r,t):typeof t[r]=="number"||t[r]===null||t[r]instanceof Z||this.setInvalid(r,t);else if(a==="boundingbox")t[r].center&&t[r].center instanceof Array&&t[r].center.length===3||this.setInvalid(r,t),t[r].halfExtents&&t[r].halfExtents instanceof Array&&t[r].halfExtents.length===3||this.setInvalid(r,t);else if(a==="cubemap")typeof t[r]=="number"||t[r]===null||t[r]===void 0||t[r]instanceof Z&&t[r].cubemap||this.setInvalid(r,t);else if(a==="chunks"){let o=Object.keys(t[r]);for(let l=0;l=0}}};var F_=class{constructor(){this._validator=null}parse(t){let e=this.migrate(t),s=this._validate(e),i=new it;return this.initialize(i,s),i}initialize(t,e){if(e.validated||(e=this._validate(e)),e.chunks&&e.chunks&&Object.keys(e.chunks).length>0){let s=t.shaderChunks.glsl;Object.entries(e.chunks).forEach(([i,r])=>s.set(i,r))}for(let s in e){let i=Mc[s],r=e[s];if(i==="vec2")t[s]=new B(r[0],r[1]);else if(i==="rgb")t[s]=new F(r[0],r[1],r[2]);else if(i==="texture")r instanceof Z?t[s]=r:t[s]instanceof Z&&typeof r=="number"&&r>0||(t[s]=null);else if(i==="cubemap")r instanceof Z?t[s]=r:t[s]instanceof Z&&typeof r=="number"&&r>0||(t[s]=null),s==="cubeMap"&&!r&&(t.prefilteredCubemaps=null);else if(i==="boundingbox"){let a=new x(r.center[0],r.center[1],r.center[2]),o=new x(r.halfExtents[0],r.halfExtents[1],r.halfExtents[2]);t[s]=new ge(a,o)}else t[s]=e[s]}t.update()}migrate(t){t.shader&&delete t.shader,t.mapping_format&&(t.mappingFormat=t.mapping_format,delete t.mapping_format);let e,s=[["bumpMapFactor","bumpiness"],["aoUvSet","aoMapUv"],["aoMapVertexColor","aoVertexColor"],["diffuseMapVertexColor","diffuseVertexColor"],["emissiveMapVertexColor","emissiveVertexColor"],["specularMapVertexColor","specularVertexColor"],["metalnessMapVertexColor","metalnessVertexColor"],["opacityMapVertexColor","opacityVertexColor"],["glossMapVertexColor","glossVertexColor"],["lightMapVertexColor","lightVertexColor"],["specularMapTint","specularTint"],["metalnessMapTint","metalnessTint"],["clearCoatGlossiness","clearCoatGloss"]];for(e=0;e0,maxRetries:this.maxRetries},(s,i)=>{s?e&&e(`Error loading material: ${t.original} [${s}]`):e&&(i._engine=!0,e(null,i))})}open(t,e){let s=this._parser.parse(e);return e._engine&&(s._data=e,delete e._engine),s}patch(t,e){t.resource._data&&(t._data=t.resource._data,delete t.resource._data),t.data.name=t.name,t.resource.name=t.name,this._bindAndAssignAssets(t,e),t.off("unload",this._onAssetUnload,this),t.on("unload",this._onAssetUnload,this)}_onAssetUnload(t){delete t.data.parameters,delete t.data.chunks,delete t.data.name}_assignTexture(t,e,s){e.resource[t]=s}_getPlaceholderTexture(t){let e=Jj[t];return bo(this._device,e)}_assignPlaceholderTexture(t,e){e.resource[t]=this._getPlaceholderTexture(t)}_onTextureLoad(t,e,s){this._assignTexture(t,e,s.resource),e.resource.update()}_onTextureAdd(t,e,s){this._assets.load(s)}_onTextureRemoveOrUnload(t,e,s){let i=e.resource;i&&e.resource[t]===s.resource&&(this._assignPlaceholderTexture(t,e),i.update())}_assignCubemap(t,e,s){if(e.resource[t]=s[0],t==="cubeMap"){let i=s.slice(1);i.every(r=>r)?e.resource.prefilteredCubemaps=i:i[0]&&(e.resource.envAtlas=i[0])}}_onCubemapLoad(t,e,s){this._assignCubemap(t,e,s.resources),this._parser.initialize(e.resource,e.data)}_onCubemapAdd(t,e,s){this._assets.load(s)}_onCubemapRemoveOrUnload(t,e,s){let i=e.resource;e.data.prefilteredCubeMap128===s.resources[1]&&(this._assignCubemap(t,e,[null,null,null,null,null,null,null]),i.update())}_bindAndAssignAssets(t,e){let s=this._parser.migrate(t.data),i=t.resource,r=s.mappingFormat==="path",a=qf,o,l,h;for(o=0;o{if(i)e(i);else{let a=C_.createModel(r,this._defaultMaterial);r.destroy(),e(null,a)}})}};var eq={points:Aa,lines:Pn,lineloop:Eg,linestrip:mf,triangles:Yt,trianglestrip:Ks,trianglefan:dr},tq={int8:js,uint8:ai,int16:qs,uint16:Ri,int32:He,uint32:kt,float32:ye},JE=class{constructor(t){this._device=t.device,this._defaultMaterial=t.defaultMaterial}parse(t,e){let s=t.model;if(!s){e(null,null);return}if(s.version<=1){e("JsonModelParser#parse: Trying to parse unsupported model format.");return}let i=this._parseNodes(t),r=this._parseSkins(t,i),a=this._parseVertexBuffers(t),o=this._parseIndexBuffers(t,a),l=this._parseMorphs(t,i,a),h=this._parseMeshes(t,r.skins,l.morphs,a,o.buffer,o.data),f=this._parseMeshInstances(t,i,h,r.skins,r.instances,l.morphs,l.instances),u=new Ei;u.graph=i[0],u.meshInstances=f,u.skinInstances=r.instances,u.morphInstances=l.instances,u.getGraph().syncHierarchy(),e(null,u)}_parseNodes(t){let e=t.model,s=[],i;for(i=0;i0&&(l>65535?(i=new os(this._device,2,o),r=new Uint32Array(i.lock())):(i=new os(this._device,1,o),r=new Uint16Array(i.lock()))),{buffer:i,data:r}}_parseMeshes(t,e,s,i,r,a){let o=t.model,l=[],h=0;for(let f=0;fxe.getExtension(e)===".json"),this.addParser(new QE(this),(e,s)=>xe.getExtension(e)===".glb")}load(t,e,s){typeof t=="string"&&(t={load:t,original:t});let i={retry:this.maxRetries>0,maxRetries:this.maxRetries};(t.load.startsWith("blob:")||t.load.startsWith("data:"))&&(xe.getExtension(t.original).toLowerCase()===".glb"?i.responseType=Vt.ResponseType.ARRAY_BUFFER:i.responseType=Vt.ResponseType.JSON),Le.get(t.load,i,(r,a)=>{if(e)if(r)e(`Error loading model: ${t.original} [${r}]`);else{for(let o=0;o{h?e(h):e(null,f)},s);return}}e("No parsers found")}})}open(t,e){return e}patch(t,e){if(!t.resource)return;let s=t.data,i=this;t.resource.meshInstances.forEach((r,a)=>{if(s.mapping){let o=function(u){u.resource?r.material=u.resource:(u.once("load",o),e.load(u)),u.once("remove",d=>{r.material===d.resource&&(r.material=i.defaultMaterial)})};if(!s.mapping[a]){r.material=i.defaultMaterial;return}let l=s.mapping[a].material,h=s.mapping[a].path,f;if(l!==void 0)l?(f=e.get(l),f?o(f):e.once(`add:${l}`,o)):r.material=i.defaultMaterial;else if(h){let u=t.getAbsoluteUrl(s.mapping[a].path);f=e.getByUrl(u),f?o(f):e.once(`add:url:${u}`,o)}}})}addParser(t,e){this._parsers.push({parser:t,decider:e})}};var U_=class extends Re{constructor(t){super(t,"scene")}load(t,e){Eh.load(t,this.maxRetries,e)}open(t,e){this._app.systems.script.preloading=!0;let i=new yh(this._app,!1).parse(e),r=this._app.scene;return r.root=i,this._app.applySceneSettings(e.settings),this._app.systems.script.preloading=!1,r}};var eA=class eA{static push(t){eA._types.push(t)}};n(eA,"_types",[]);var Rl=eA;function PG(){return gm}function ub(c,t){if(gm.has(c))throw new Error(`Script name '${c}' is reserved, please rename the script`);let e=function(s){J.prototype.initEventHandler.call(this),Mr.prototype.initScriptType.call(this,s)};return e.prototype=Object.create(Mr.prototype),e.prototype.constructor=e,e.extend=Mr.extend,e.attributes=new ao(e),ax(e,c,t),e}var wG={};ao.reservedNames.forEach((c,t,e)=>{wG[c]=1});ub.reservedAttributes=wG;function ax(c,t,e){if(typeof c!="function")throw new Error(`script class: '${c}' must be a constructor function (i.e. class).`);if(!(c.prototype instanceof ks))throw new Error(`script class: '${Mr.__getScriptName(c)}' does not extend pc.Script.`);if(t=t||Qc(c),!t)return;if(gm.has(t))throw new Error(`script name: '${t}' is reserved, please change script name`);c.__name=t,(e?e.scripts:Pi.getApplication().scripts).add(c),Rl.push(c)}var k_=class extends Re{constructor(t){super(t,"script"),this._scripts={},this._cache={}}clearCache(){for(let t in this._cache){let e=this._cache[t],s=e.parentNode;s&&s.removeChild(e)}this._cache={}}load(t,e){typeof t=="string"&&(t={load:t,original:t});let s=this;fm.app=this._app;let i=(t.load,(o,l,h)=>{if(o)e(o);else{let f={};for(let d=0;d{e(`Script: ${a.target.src} failed to load`)},!1);let r=!1;i.onload=i.onreadystatechange=function(){!r&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")&&(r=!0,e(null,t,i))},i.src=t,s.appendChild(i)}_loadModule(t,e){let i=ue.browser&&window.location.origin!=="null"?window.location.origin+window.location.pathname:typeof document>"u"&&typeof location>"u"?EC("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:_documentCurrentScript&&_documentCurrentScript.tagName.toUpperCase()==="SCRIPT"&&_documentCurrentScript.src||new URL("playcanvas.min.js",document.baseURI).href,r=new URL(t,i);new Function("modulePath","return import(modulePath)")(r.toString()).then(a=>{let o=r.pathname.split("/").pop(),l=this._app.assets.find(o,"script")?.data?.scripts;for(let h in a){let f=a[h];if(f.prototype instanceof ks){let d=Object.prototype.hasOwnProperty.call(f,"scriptName")&&f.scriptName,p=Qc(f);if(!p)continue;ax(f,p),l&&this._app.scripts.addSchema(p,l[p])}}e(null,t,null)}).catch(a=>{e(a)})}};var z_=class extends Re{constructor(e){super(e,"shader");n(this,"decoder",null)}load(e,s){typeof e=="string"&&(e={load:e,original:e}),Le.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(i,r)=>{i?s(`Error loading shader resource: ${e.original} [${i}]`):s(null,r)})}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)}};function db(c){let t=this;t.resource&&(t.resource.atlas=c.resource)}function pb(c){this.registry.load(c)}var G_=class extends Re{constructor(t){super(t,"sprite"),this._assets=t.assets,this._device=t.graphicsDevice}load(t,e){typeof t=="string"&&(t={load:t,original:t}),xe.getExtension(t.original)===".json"&&Le.get(t.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(s,i)=>{s?e(s):e(null,i)})}open(t,e){let s=new Qp(this._device);return t&&(s.__data=e),s}patch(t,e){let s=t.resource;if(s.__data&&(t.data.pixelsPerUnit=s.__data.pixelsPerUnit,t.data.renderMode=s.__data.renderMode,t.data.frameKeys=s.__data.frameKeys,s.__data.textureAtlasAsset)){let i=e.getByUrl(s.__data.textureAtlasAsset);i&&(t.data.textureAtlasAsset=i.id)}s.startUpdate(),s.renderMode=t.data.renderMode,s.pixelsPerUnit=t.data.pixelsPerUnit,s.frameKeys=t.data.frameKeys,this._updateAtlas(t),s.endUpdate(),t.off("change",this._onAssetChange,this),t.on("change",this._onAssetChange,this)}_updateAtlas(t){let e=t.resource;if(!t.data.textureAtlasAsset){e.atlas=null;return}this._assets.off(`load:${t.data.textureAtlasAsset}`,db,t),this._assets.on(`load:${t.data.textureAtlasAsset}`,db,t);let s=this._assets.get(t.data.textureAtlasAsset);s&&s.resource?e.atlas=s.resource:s?this._assets.load(s):(this._assets.off(`add:${t.data.textureAtlasAsset}`,pb,t),this._assets.on(`add:${t.data.textureAtlasAsset}`,pb,t))}_onAssetChange(t,e,s,i){e==="data"&&s&&s.textureAtlasAsset&&i&&s.textureAtlasAsset!==i.textureAtlasAsset&&(this._assets.off(`load:${i.textureAtlasAsset}`,db,t),this._assets.off(`add:${i.textureAtlasAsset}`,pb,t))}};var Nu=class{constructor(t,e){n(this,"_app");n(this,"_data");n(this,"_templateRoot",null);this._app=t,this._data=e}instantiate(){return this._templateRoot||this._parseTemplate(),this._templateRoot.clone()}_parseTemplate(){let t=new yh(this._app,!0);this._templateRoot=t.parse(this._data)}set data(t){this._data=t,this._templateRoot=null}get data(){return this._data}};var V_=class extends Re{constructor(e){super(e,"template");n(this,"decoder",null)}load(e,s){typeof e=="string"&&(e={load:e,original:e});let i={retry:this.maxRetries>0,maxRetries:this.maxRetries};Le.get(e.load,i,(r,a)=>{r?s(`Error requesting template: ${e.original}`):s(r,a)})}open(e,s){return new Nu(this._app,s)}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),new Nu(this._app,JSON.parse(this.decoder.decode(e)))}patch(e,s){if(!e||!e.resource||!e.data||!e.data.entities)return;let i=e.resource;i.data=e.data}};var H_=class extends Re{constructor(e){super(e,"text");n(this,"decoder",null)}load(e,s){typeof e=="string"&&(e={load:e,original:e}),Le.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(i,r)=>{i?s(`Error loading text resource: ${e.original} [${i}]`):s(null,r)})}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)}};var tA={repeat:0,clamp:1,mirror:2},sA={nearest:0,linear:1,nearest_mip_nearest:2,linear_mip_nearest:4,nearest_mip_linear:3,linear_mip_linear:5},sq=/^data\.frames\.(\d+)$/,W_=class extends Re{constructor(t){super(t,"textureatlas"),this._loader=t.loader}load(t,e){typeof t=="string"&&(t={load:t,original:t});let s=this,i=this._loader.getHandler("texture");xe.getExtension(t.original)===".json"?Le.get(t.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(r,a)=>{if(r)e(r);else{let o=t.original.replace(".json",".png");s._loader.load(o,"texture",(l,h)=>{l?e(l):e(null,{data:a,texture:h})})}}):i.load(t,e)}open(t,e,s){let i=new Jp;if(e.texture&&e.data)i.texture=e.texture,i.__data=e.data;else{let a=this._loader.getHandler("texture").open(t,e,s);if(!a)return null;i.texture=a}return i}patch(t,e){if(!t.resource)return;t.resource.__data&&(t.resource.__data.minfilter!==void 0&&(t.data.minfilter=t.resource.__data.minfilter),t.resource.__data.magfilter!==void 0&&(t.data.magfilter=t.resource.__data.magfilter),t.resource.__data.addressu!==void 0&&(t.data.addressu=t.resource.__data.addressu),t.resource.__data.addressv!==void 0&&(t.data.addressv=t.resource.__data.addressv),t.resource.__data.mipmaps!==void 0&&(t.data.mipmaps=t.resource.__data.mipmaps),t.resource.__data.anisotropy!==void 0&&(t.data.anisotropy=t.resource.__data.anisotropy),t.resource.__data.rgbm!==void 0&&(t.data.rgbm=!!t.resource.__data.rgbm),t.data.frames=t.resource.__data.frames,delete t.resource.__data);let s=t.resource.texture;if(s&&(s.name=t.name,t.data.hasOwnProperty("minfilter")&&s.minFilter!==sA[t.data.minfilter]&&(s.minFilter=sA[t.data.minfilter]),t.data.hasOwnProperty("magfilter")&&s.magFilter!==sA[t.data.magfilter]&&(s.magFilter=sA[t.data.magfilter]),t.data.hasOwnProperty("addressu")&&s.addressU!==tA[t.data.addressu]&&(s.addressU=tA[t.data.addressu]),t.data.hasOwnProperty("addressv")&&s.addressV!==tA[t.data.addressv]&&(s.addressV=tA[t.data.addressv]),t.data.hasOwnProperty("mipmaps")&&s.mipmaps!==t.data.mipmaps&&(s.mipmaps=t.data.mipmaps),t.data.hasOwnProperty("anisotropy")&&s.anisotropy!==t.data.anisotropy&&(s.anisotropy=t.data.anisotropy),t.data.hasOwnProperty("rgbm"))){let r=t.data.rgbm?_i:Gt;s.type!==r&&(s.type=r)}t.resource.texture=s;let i={};for(let r in t.data.frames){let a=t.data.frames[r];i[r]={rect:new Q(a.rect),pivot:new B(a.pivot),border:new Q(a.border)}}t.resource.frames=i,t.off("change",this._onAssetChange,this),t.on("change",this._onAssetChange,this)}_onAssetChange(t,e,s){let i;if(e==="data"||e==="data.frames"){let r={};for(let a in s.frames)i=s.frames[a],r[a]={rect:new Q(i.rect),pivot:new B(i.pivot),border:new Q(i.border)};t.resource.frames=r}else{let r=e.match(sq);if(r){let a=r[1];s?(t.resource.frames[a]?(i=t.resource.frames[a],i.rect.set(s.rect[0],s.rect[1],s.rect[2],s.rect[3]),i.pivot.set(s.pivot[0],s.pivot[1]),i.border.set(s.border[0],s.border[1],s.border[2],s.border[3])):t.resource.frames[a]={rect:new Q(s.rect),pivot:new B(s.pivot),border:new Q(s.border)},t.resource.fire("set:frame",a,t.resource.frames[a])):t.resource.frames[a]&&(delete t.resource.frames[a],t.resource.fire("remove:frame",a))}}}};function IG(){let c={cTFETC1:0,cTFETC2:1,cTFBC1:2,cTFBC3:3,cTFPVRTC1_4_RGB:8,cTFPVRTC1_4_RGBA:9,cTFASTC_4x4:10,cTFATC_RGB:11,cTFATC_RGBA_INTERPOLATED_ALPHA:12,cTFRGBA32:13,cTFRGB565:14,cTFRGBA4444:16},t={astc:c.cTFASTC_4x4,dxt:c.cTFBC1,etc1:c.cTFETC1,etc2:c.cTFETC1,pvr:c.cTFPVRTC1_4_RGB,atc:c.cTFATC_RGB,none:c.cTFRGB565},e={astc:c.cTFASTC_4x4,dxt:c.cTFBC3,etc1:c.cTFRGBA4444,etc2:c.cTFETC2,pvr:c.cTFPVRTC1_4_RGBA,atc:c.cTFATC_RGBA_INTERPOLATED_ALPHA,none:c.cTFRGBA4444},s={ETC1:21,ETC2_RGB:22,ETC2_RGBA:23,DXT1:8,DXT5:10,PVRTC_4BPP_RGB_1:26,PVRTC_4BPP_RGBA_1:27,ASTC_4x4:28,ATC_RGB:29,ATC_RGBA:30,R8_G8_B8_A8:7,R5_G6_B5:3,R4_G4_B4_A4:5},i=(v,E)=>{switch(v){case c.cTFETC1:return E.formats.etc2?s.ETC2_RGB:s.ETC1;case c.cTFETC2:return s.ETC2_RGBA;case c.cTFBC1:return s.DXT1;case c.cTFBC3:return s.DXT5;case c.cTFPVRTC1_4_RGB:return s.PVRTC_4BPP_RGB_1;case c.cTFPVRTC1_4_RGBA:return s.PVRTC_4BPP_RGBA_1;case c.cTFASTC_4x4:return s.ASTC_4x4;case c.cTFATC_RGB:return s.ATC_RGB;case c.cTFATC_RGBA_INTERPOLATED_ALPHA:return s.ATC_RGBA;case c.cTFRGBA32:return s.R8_G8_B8_A8;case c.cTFRGB565:return s.R5_G6_B5;case c.cTFRGBA4444:return s.R4_G4_B4_A4}},r=v=>{let E=function(y,P){let A=y*.00784313725490196-1,w=P*(2/255)-1,I=Math.sqrt(1-Math.min(1,A*A+w*w));return Math.max(0,Math.min(255,Math.floor((I+1)*.5*255)))};for(let y=0;y{let E=new Uint16Array(v.length/4);for(let y=0;y>3}return E},o=(v,E)=>(v&v-1)===0&&(E&E-1)===0,l=()=>typeof performance<"u"?performance.now():0,h,f,u,d=(v,E,y)=>{if(y){if(v.formats.astc)return"astc"}else if(E){if(v.formats.etc2)return"etc2"}else{if(v.formats.etc2)return"etc2";if(v.formats.etc1)return"etc1"}return(A=>{for(let w=0;w{switch(y){case c.cTFETC1:case c.cTFETC2:return!0;case c.cTFBC1:case c.cTFBC3:return(v&3)===0&&(E&3)===0;case c.cTFPVRTC1_4_RGB:case c.cTFPVRTC1_4_RGBA:return o(v,E);case c.cTFASTC_4x4:return!0;case c.cTFATC_RGB:case c.cTFATC_RGBA_INTERPOLATED_ALPHA:return!0}return!1},m=(v,E,y)=>{if(!h.KTX2File)throw new Error("Basis transcoder module does not include support for KTX2.");let P=l(),A=new h.KTX2File(new Uint8Array(E)),w=A.getWidth(),I=A.getHeight(),D=A.getLevels(),O=!!A.getHasAlpha(),G=A.isUASTC&&A.isUASTC();if(!w||!I||!D)throw A.close(),A.delete(),new Error(`Invalid image dimensions url=${v} width=${w} height=${I} levels=${D}`);let M=d(y.deviceDetails,O,G),H=!!y.isGGGR&&M==="pvr",U;if(H?U=c.cTFRGBA32:(U=O?e[M]:t[M],p(w,I,U)||(U=O?c.cTFRGBA32:c.cTFRGB565)),!A.startTranscoding())throw A.close(),A.delete(),new Error(`Failed to start transcoding url=${v}`);let L,b=[];for(let N=0;N{let P=l(),A=new h.BasisFile(new Uint8Array(E)),w=A.getImageWidth(0,0),I=A.getImageHeight(0,0),D=A.getNumImages(),O=A.getNumLevels(0),G=!!A.getHasAlpha(),M=A.isUASTC&&A.isUASTC();if(!w||!I||!D||!O)throw A.close(),A.delete(),new Error(`Invalid image dimensions url=${v} width=${w} height=${I} images=${D} levels=${O}`);let H=d(y.deviceDetails,G,M),U=!!y.isGGGR&&H==="pvr",L;if(U?L=c.cTFRGBA32:(L=G?e[H]:t[H],p(w,I,L)||(L=G?c.cTFRGBA32:c.cTFRGB565)),!A.startTranscoding())throw A.close(),A.delete(),new Error(`Failed to start transcoding url=${v}`);let b,N=[];for(let k=0;ky.isKTX2?m(v,E,y):_(v,E,y),g=(v,E,y)=>{try{let P=S(v,E,y);P.levels=P.levels.map(A=>A.buffer),self.postMessage({url:v,data:P},P.levels)}catch(P){self.postMessage({url:v,err:P},null)}},T=(v,E)=>{let y=(P,A)=>(WebAssembly.instantiate(v.module,P).then(w=>{A(w)}).catch(w=>{}),{});self.BASIS(v.module?{instantiateWasm:y}:null).then(P=>{P.initializeBasis(),h=P,f=v.rgbPriority,u=v.rgbaPriority,E(null)})},C=[];self.onmessage=v=>{let E=v.data;switch(E.type){case"init":T(E.config,()=>{for(let y=0;y({astc:!!c.extCompressedTextureASTC,atc:!!c.extCompressedTextureATC,dxt:!!c.extCompressedTextureS3TC,etc1:!!c.extCompressedTextureETC1,etc2:!!c.extCompressedTextureETC,pvr:!!c.extCompressedTexturePVRTC}),rq=(c,t)=>{let e=a=>{let o=["/* basis */",a,"",`(${IG.toString()})() `].join(` `);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;rnew Uint16Array(r)):s.levels=s.levels.map(r=>new Uint8Array(r));for(let r=0;r{let r=i.data;this.queue.handleResponse(r.url,r.err,r.data),this.eager||this.queue.enqueueClient(this)}),this.worker.postMessage({type:"init",config:e}),this.eager=s}run(t){let e=[];t.data instanceof ArrayBuffer&&e.push(t.data),this.worker.postMessage({type:"transcode",url:t.url,format:t.format,data:t.data,options:t.options},e),this.eager&&this.queue.enqueueClient(this)}},aq=1,oq=["etc2","etc1","astc","dxt","pvr","atc"],nq=["astc","dxt","etc2","pvr","atc"],lq=5,Sb=new _b,RG=null,xb=!1;function vb(c){if(!xb){if(!c)c=RG||{};else if(c.lazyInit){RG=c;return}if(!c.glueUrl||!c.wasmUrl||!c.fallbackUrl){let t=Yl.getConfig("BASIS");t&&(c={glueUrl:t.glueUrl,wasmUrl:t.wasmUrl,fallbackUrl:t.fallbackUrl,numWorkers:t.numWorkers})}if(c.glueUrl||c.wasmUrl||c.fallbackUrl){xb=!0;let t=Math.max(1,Math.min(16,c.numWorkers||aq)),e=c.numWorkers===1||(c.hasOwnProperty("eagerWorkers")?c.eagerWorkers:!0);c.rgbPriority=c.rgbPriority||oq,c.rgbaPriority=c.rgbaPriority||nq,c.maxRetries=c.hasOwnProperty("maxRetries")?c.maxRetries:lq,rq(c,(s,i)=>{if(!s)for(let r=0;r{iA(i,t.load,a,e,{isGGGR:(s?.file?.variants?.basis?.opt&8)!==0})||e(`Basis module not found. Asset [${s.name}](${s.getFileUrl()}) basis texture variant will not be loaded.`)};ae.fetchArrayBuffer(t.load,(a,o)=>{a?e(a):r(o)},s,this.maxRetries)}open(t,e,s,i={}){let r=i.srgb?Cn(e.format):e.format,a=new Z(s,{name:t,addressU:e.cubemap?1:0,addressV:e.cubemap?1:0,width:e.width,height:e.height,format:r,cubemap:e.cubemap,levels:e.levels,...i});return a.upload(),a}};var aA=class extends nr{constructor(t,e){super(),this.crossOrigin=t.prefix?"anonymous":null,this.maxRetries=0,this.device=e}load(t,e,s){let i=!!s?.file?.contents;if(i){if(this.device.supportsImageBitmap){this._loadImageBitmapFromBlob(new Blob([s.file.contents]),e);return}t={load:URL.createObjectURL(new Blob([s.file.contents])),original:t.original}}let r=(o,l)=>{i&&URL.revokeObjectURL(t.load),e(o,l)},a;s&&s.options&&s.options.hasOwnProperty("crossOrigin")?a=s.options.crossOrigin:Ja.test(t.load)&&(a=this.crossOrigin),this.device.supportsImageBitmap?this._loadImageBitmap(t.load,t.original,a,r,s):this._loadImage(t.load,t.original,a,r,s)}open(t,e,s,i={}){let r=new Z(s,{name:t,width:e.width,height:e.height,format:i.srgb?st:ce,...i});return r.setSource(e),r}_loadImage(t,e,s,i,r){let a=new Image;s&&(a.crossOrigin=s);let o=0,l=this.maxRetries,h,f=1024*1024;r?.fire("progress",0,f),a.onload=function(){r?.fire("progress",f,f),i(null,a)},a.onerror=function(){if(!h)if(l>0&&++o<=l){let u=Math.pow(2,o)*100,p=t.indexOf("?")>=0?"&":"?";h=setTimeout(()=>{a.src=`${t+p}retry=${Date.now()}`,h=null},u)}else i(`Error loading Texture from: '${e}'`)},a.src=t}_loadImageBitmap(t,e,s,i,r){let a={cache:!0,responseType:"blob",retry:this.maxRetries>0,maxRetries:this.maxRetries,progress:r};Le.get(t,a,(o,l)=>{o?i(o):this._loadImageBitmapFromBlob(l,i)})}_loadImageBitmapFromBlob(t,e){createImageBitmap(t,{premultiplyAlpha:"none",colorSpaceConversion:"none"}).then(s=>e(null,s)).catch(s=>e(s))}};var Tb=[1481919403,3140563232,169478669],cq={33776:To,33778:Ql,33779:Gr,36196:Eo,37492:Jl,37496:ec,35840:Ao,35841:Vr,35842:Co,35843:Hr,32849:Ss,32856:ce,35905:yo,35907:st,35898:Gi,34843:vn,34842:Me};function hq(c,t,e,s){return c===Gi?new Uint32Array(t,e,s/4):new Uint8Array(t,e,s)}var oA=class extends nr{constructor(t){super(),this.maxRetries=0}load(t,e,s){ae.fetchArrayBuffer(t.load,e,s,this.maxRetries)}open(t,e,s,i={}){let r=this.parse(e);if(!r)return null;let a=i.srgb?Cn(r.format):r.format,o=new Z(s,{name:t,addressU:r.cubemap?1:0,addressV:r.cubemap?1:0,width:r.width,height:r.height,format:a,cubemap:r.cubemap,levels:r.levels,...i});return o.upload(),o}parse(t){let e=new Uint32Array(t);if(Tb[0]!==e[0]||Tb[1]!==e[1]||Tb[2]!==e[2])return null;let s={endianness:e[3],glType:e[4],glTypeSize:e[5],glFormat:e[6],glInternalFormat:e[7],glBaseInternalFormat:e[8],pixelWidth:e[9],pixelHeight:e[10],pixelDepth:e[11],numberOfArrayElements:e[12],numberOfFaces:e[13],numberOfMipmapLevels:e[14],bytesOfKeyValueData:e[15]};if(s.pixelDepth>1||s.numberOfArrayElements!==0)return null;let i=cq[s.glInternalFormat];if(i===void 0)return null;let r=16+s.bytesOfKeyValueData/4,a=s.numberOfFaces>1,o=[];for(let l=0;l<(s.numberOfMipmapLevels||1);l++){let h=e[r++];a&&o.push([]);let f=a?o[l]:o;for(let u=0;u<(a?6:1);++u)f.push(hq(i,t,r*4,h)),r+=h+3>>2}return{format:i,width:s.pixelWidth,height:s.pixelHeight,levels:o,cubemap:a}}};var fq={KHR_DF_MODEL_ETC1S:163,KHR_DF_MODEL_UASTC:166},nA=class extends nr{constructor(t,e){super(),this.maxRetries=0,this.device=e}load(t,e,s){ae.fetchArrayBuffer(t.load,(i,r)=>{i?e(i,r):this.parse(r,t,e,s)},s,this.maxRetries)}open(t,e,s,i={}){let r=i.srgb?Cn(e.format):e.format,a=new Z(s,{name:t,addressU:e.cubemap?1:0,addressV:e.cubemap?1:0,width:e.width,height:e.height,format:r,cubemap:e.cubemap,levels:e.levels,...i});return a.upload(),a}parse(t,e,s,i){let r=new Kl(t),a=[r.readU32be(),r.readU32be(),r.readU32be()];if(a[0]!==2873840728||a[1]!==540160187||a[2]!==218765834)return null;let o={vkFormat:r.readU32(),typeSize:r.readU32(),pixelWidth:r.readU32(),pixelHeight:r.readU32(),pixelDepth:r.readU32(),layerCount:r.readU32(),faceCount:r.readU32(),levelCount:r.readU32(),supercompressionScheme:r.readU32()},l={dfdByteOffset:r.readU32(),dfdByteLength:r.readU32(),kvdByteOffset:r.readU32(),kvdByteLength:r.readU32(),sgdByteOffset:r.readU64(),sgdByteLength:r.readU64()},h=[];for(let d=0;d1,...i});let G=128,M=d?6:1,H,U=4,L=4,b=f===p?8:16,N,k,z;for(let V=0;V32767)return this._readPixelsFlat(t,e,s);let r=[0,0,0,0];if(t.readArray(r),r[0]!==2||r[1]!==2||(r[2]&128)!==0)return t.skip(-4),this._readPixelsFlat(t,e,s);let a=new ArrayBuffer(e*s*4),o=new Uint8Array(a),l=i?0:e*4*(s-1),h,f,u,d,p,m;for(f=0;f128){if(p-=128,h+p>e)return null;for(m=t.readU8(),u=0;ue)return null;for(u=0;u>1),l=Math.max(1,r>>1),h=new a.constructor(o*l*4),f=Math.floor(i/o),u=Math.floor(r/l),d=f*u;for(let p=0;p>i-1),a=Math.max(1,c._height>>i-1);if(c._cubemap){let o=[];for(let l=0;l<6;++l)o.push(s(r,a,c._levels[i-1][l]));c._levels.push(o)}else c._levels.push(s(r,a,c._levels[i-1]))}c._levelsUpdated=c._cubemap?[[!0,!0,!0,!0,!0,!0]]:[!0]},X_=class extends Re{constructor(t){super(t,"texture");let e=t.assets,s=t.graphicsDevice;this._device=s,this._assets=e,this.imgParser=new aA(e,s),this.parsers={dds:new lA(e),ktx:new oA(e),ktx2:new nA(e,s),basis:new rA(e,s),hdr:new cA(e)}}set crossOrigin(t){this.imgParser.crossOrigin=t}get crossOrigin(){return this.imgParser.crossOrigin}set maxRetries(t){this.imgParser.maxRetries=t;for(let e in this.parsers)this.parsers.hasOwnProperty(e)&&(this.parsers[e].maxRetries=t)}get maxRetries(){return this.imgParser.maxRetries}_getUrlWithoutParams(t){return t.indexOf("?")>=0?t.split("?")[0]:t}_getParser(t){let e=xe.getExtension(this._getUrlWithoutParams(t)).toLowerCase().replace(".","");return this.parsers[e]||this.imgParser}_getTextureOptions(t){let e={};if(t){t.name?.length>0&&(e.name=t.name);let s=t.data;s.hasOwnProperty("minfilter")&&(e.minFilter=DG[s.minfilter]),s.hasOwnProperty("magfilter")&&(e.magFilter=DG[s.magfilter]),s.hasOwnProperty("addressu")&&(e.addressU=bG[s.addressu]),s.hasOwnProperty("addressv")&&(e.addressV=bG[s.addressv]),s.hasOwnProperty("mipmaps")&&(e.mipmaps=s.mipmaps),s.hasOwnProperty("anisotropy")&&(e.anisotropy=s.anisotropy),s.hasOwnProperty("flipY")&&(e.flipY=!!s.flipY),s.hasOwnProperty("srgb")&&(e.srgb=!!s.srgb),e.type=Gt,s.hasOwnProperty("type")?e.type=uq[s.type]:s.hasOwnProperty("rgbm")&&s.rgbm?e.type=_i:t.file&&(t.file.opt&8)!==0&&(e.type=Rn)}return e}load(t,e,s){typeof t=="string"&&(t={load:t,original:t}),this._getParser(t.original).load(t,e,s)}open(t,e,s){if(!t)return;let i=this._getTextureOptions(s),r=this._getParser(t).open(t,e,this._device,i);return r===null?r=new Z(this._device,{width:4,height:4,format:Ss}):(dq(r),e.unswizzledGGGR&&(s.file.variants.basis.opt&=-9)),r}patch(t,e){let s=t.resource;if(!s)return;let i=this._getTextureOptions(t);for(let r of Object.keys(i))s[r]=i[r]}};var yb="inline",Eb="immersive-vr",bl="immersive-ar",hA="viewer",pq="local",mq="local-floor",_q="bounded-floor",gq="unbounded",Sq="gaze",xq="screen",vq="tracked-pointer",Tq="none",yq="left",Eq="right",Aq="none",Ab="left",Cq="right",Pq="point",wq="plane",Iq="mesh",Cb="cpu-optimized",ox="gpu-optimized",nx="luminance-alpha",lx="unsigned-short",cx="float32";var Y_=class{constructor(t){n(this,"_manager");n(this,"_supported",ue.browser&&!!window.XRDOMOverlayState);n(this,"_root",null);this._manager=t}get supported(){return this._supported}get available(){return this._supported&&this._manager.active&&this._manager._session.domOverlayState!==null}get state(){return!this._supported||!this._manager.active||!this._manager._session.domOverlayState?null:this._manager._session.domOverlayState.type}set root(t){!this._supported||this._manager.active||(this._root=t)}get root(){return this._root}};var fA=[],LG=[],Ah=class extends J{constructor(e,s,i,r=null){super();n(this,"manager");n(this,"_xrHitTestSource");n(this,"_transient");n(this,"_inputSource");this.manager=e,this._xrHitTestSource=s,this._transient=i,this._inputSource=r}remove(){if(!this._xrHitTestSource)return;let e=this.manager.hitTest.sources,s=e.indexOf(this);s!==-1&&e.splice(s,1),this.onStop()}onStop(){this._xrHitTestSource.cancel(),this._xrHitTestSource=null,this.fire("remove"),this.manager.hitTest.fire("remove",this)}update(e){if(this._transient){let s=e.getHitTestResultsForTransientInput(this._xrHitTestSource);for(let i=0;i=r||(r=u,a=e[h],o.copy(f.transform.position),l.copy(f.transform.orientation))}this.fire("result",o,l,s||this._inputSource,a),this.manager.hitTest.fire("result",this,o,l,s||this._inputSource,a),fA.push(i),fA.push(o),LG.push(l)}};n(Ah,"EVENT_REMOVE","remove"),n(Ah,"EVENT_RESULT","result");var _a=class extends J{constructor(e){super();n(this,"manager");n(this,"_supported",ue.browser&&!!(window.XRSession&&window.XRSession.prototype.requestHitTestSource));n(this,"_available",!1);n(this,"_checkingAvailability",!1);n(this,"sources",[]);this.manager=e,this._supported&&(this.manager.on("start",this._onSessionStart,this),this.manager.on("end",this._onSessionEnd,this))}_onSessionStart(){if(this.manager.session.enabledFeatures){let e=this.manager.session.enabledFeatures.indexOf("hit-test")!==-1;if(!e)return;this._available=e,this.fire("available")}else this._checkingAvailability||(this._checkingAvailability=!0,this.manager.session.requestReferenceSpace(hA).then(e=>{this.manager.session.requestHitTestSource({space:e}).then(s=>{s.cancel(),this.manager.active&&(this._available=!0,this.fire("available"))}).catch(()=>{})}).catch(()=>{}))}_onSessionEnd(){if(this._available){this._available=!1;for(let e=0;e{if(!this.manager.session){let o=new Error("XR Session is not started (2)");r&&r(o),this.fire("error",o);return}this.manager.session.requestHitTestSource({space:a,entityTypes:e.entityTypes||void 0,offsetRay:s}).then(o=>{this._onHitTestSource(o,!1,e.inputSource,r)}).catch(o=>{r&&r(o),this.fire("error",o)})}).catch(a=>{r&&r(a),this.fire("error",a)}):this.manager.session.requestHitTestSourceForTransientInput({profile:e.profile,entityTypes:e.entityTypes||void 0,offsetRay:s}).then(a=>{this._onHitTestSource(a,!0,e.inputSource,r)}).catch(a=>{r&&r(a),this.fire("error",a)})}_onHitTestSource(e,s,i,r){if(!this.manager.session){e.cancel();let o=new Error("XR Session is not started (3)");r&&r(o),this.fire("error",o);return}let a=new Ah(this.manager,e,s,i??null);this.sources.push(a),r&&r(null,a),this.fire("add",a)}update(e){if(this._available)for(let s=0;s(this._bitmap=e,{image:this._bitmap,widthInMeters:this._width}))}destroy(){this._image=null,this._pose=null,this._bitmap&&(this._bitmap.close(),this._bitmap=null)}getPosition(){return this._pose&&this._position.copy(this._pose.transform.position),this._position}getRotation(){return this._pose&&this._rotation.copy(this._pose.transform.orientation),this._rotation}};n(Ch,"EVENT_TRACKED","tracked"),n(Ch,"EVENT_UNTRACKED","untracked");var Bu=class extends J{constructor(e){super();n(this,"_manager");n(this,"_supported",ue.browser&&!!window.XRImageTrackingResult);n(this,"_available",!1);n(this,"_images",[]);this._manager=e,this._supported&&(this._manager.on("start",this._onSessionStart,this),this._manager.on("end",this._onSessionEnd,this))}add(e,s){if(!this._supported||this._manager.active)return null;let i=new Ch(e,s);return this._images.push(i),i}remove(e){if(this._manager.active)return;let s=this._images.indexOf(e);s!==-1&&(e.destroy(),this._images.splice(s,1))}_onSessionStart(){this._manager.session.getTrackedImageScores().then(e=>{this._available=!0;for(let s=0;s{this._available=!1,this.fire("error",e)})}_onSessionEnd(){this._available=!1;for(let e=0;es.prepare())).then(s=>{e(null,s)}).catch(s=>{e(s,null)}):e(null,null)}update(e){if(!this._available)return;let s=e.getImageTrackingResults(),i={};for(let r=0;r0&&(NG.sub2(this._localPosition,this._localPositionLast).divScalar(o),this._linearVelocity.lerp(this._linearVelocity,NG,.15))}else this._velocitiesAvailable=!1}let i=e.getPose(this._xrInputSource.targetRaySpace,this._manager._referenceSpace);i&&(this._dirtyRay=!0,this._rayLocal.origin.copy(i.transform.position),this._rayLocal.direction.set(0,0,-1),BG.copy(i.transform.orientation),BG.transformVector(this._rayLocal.direction,this._rayLocal.direction))}}_updateTransforms(){this._dirtyLocal&&(this._dirtyLocal=!1,this._localTransform.setTRS(this._localPosition,this._localRotation,x.ONE));let e=this._manager.camera.parent;e?this._worldTransform.mul2(e.getWorldTransform(),this._localTransform):this._worldTransform.copy(this._localTransform)}_updateRayTransforms(){let e=this._dirtyRay;this._dirtyRay=!1;let s=this._manager.camera.parent;if(s){let i=s.getWorldTransform();i.getTranslation(this._position),this._rotation.setFromMat4(i),this._rotation.transformVector(this._rayLocal.origin,this._ray.origin),this._ray.origin.add(this._position),this._rotation.transformVector(this._rayLocal.direction,this._ray.direction)}else e&&(this._ray.origin.copy(this._rayLocal.origin),this._ray.direction.copy(this._rayLocal.direction))}getPosition(){return this._grip?(this._updateTransforms(),this._worldTransform.getTranslation(this._position),this._position):null}getLocalPosition(){return this._localPosition}getRotation(){return this._grip?(this._updateTransforms(),this._rotation.setFromMat4(this._worldTransform),this._rotation):null}getLocalRotation(){return this._localRotation}getLinearVelocity(){return this._velocitiesAvailable?this._linearVelocity:null}getOrigin(){return this._updateRayTransforms(),this._ray.origin}getDirection(){return this._updateRayTransforms(),this._ray.direction}hitTestStart(e={}){e.inputSource=this,e.profile=this._xrInputSource.profiles[0];let s=e.callback;e.callback=(i,r)=>{r&&this.onHitTestSourceAdd(r),s&&s(i,r)},this._manager.hitTest.start(e)}onHitTestSourceAdd(e){this._hitTestSources.push(e),this.fire("hittest:add",e),e.on("result",(s,i,r,a)=>{r===this&&this.fire("hittest:result",e,s,i,a)}),e.once("remove",()=>{this.onHitTestSourceRemove(e),this.fire("hittest:remove",e)})}onHitTestSourceRemove(e){let s=this._hitTestSources.indexOf(e);s!==-1&&this._hitTestSources.splice(s,1)}};n(Es,"EVENT_REMOVE","remove"),n(Es,"EVENT_SELECT","select"),n(Es,"EVENT_SELECTSTART","selectstart"),n(Es,"EVENT_SELECTEND","selectend"),n(Es,"EVENT_SQUEEZE","squeeze"),n(Es,"EVENT_SQUEEZESTART","squeezestart"),n(Es,"EVENT_SQUEEZEEND","squeezeend"),n(Es,"EVENT_HITTESTADD","hittest:add"),n(Es,"EVENT_HITTESTREMOVE","hittest:remove"),n(Es,"EVENT_HITTESTRESULT","hittest:result");var lr=class extends J{constructor(e){super();n(this,"manager");n(this,"_inputSources",[]);n(this,"_onInputSourcesChangeEvt");n(this,"velocitiesSupported",!1);this.manager=e,this.velocitiesSupported=!!(ue.browser&&window.XRPose?.prototype?.hasOwnProperty("linearVelocity")),this._onInputSourcesChangeEvt=s=>{this._onInputSourcesChange(s)},this.manager.on("start",this._onSessionStart,this),this.manager.on("end",this._onSessionEnd,this)}_onSessionStart(){let e=this.manager.session;e.addEventListener("inputsourceschange",this._onInputSourcesChangeEvt),e.addEventListener("select",i=>{let r=this._getByInputSource(i.inputSource);r.update(i.frame),r.fire("select",i),this.fire("select",r,i)}),e.addEventListener("selectstart",i=>{let r=this._getByInputSource(i.inputSource);r.update(i.frame),r._selecting=!0,r.fire("selectstart",i),this.fire("selectstart",r,i)}),e.addEventListener("selectend",i=>{let r=this._getByInputSource(i.inputSource);r.update(i.frame),r._selecting=!1,r.fire("selectend",i),this.fire("selectend",r,i)}),e.addEventListener("squeeze",i=>{let r=this._getByInputSource(i.inputSource);r.update(i.frame),r.fire("squeeze",i),this.fire("squeeze",r,i)}),e.addEventListener("squeezestart",i=>{let r=this._getByInputSource(i.inputSource);r.update(i.frame),r._squeezing=!0,r.fire("squeezestart",i),this.fire("squeezestart",r,i)}),e.addEventListener("squeezeend",i=>{let r=this._getByInputSource(i.inputSource);r.update(i.frame),r._squeezing=!1,r.fire("squeezeend",i),this.fire("squeezeend",r,i)});let s=e.inputSources;for(let i=0;i{let i=this._lightProbeRequested;this._lightProbeRequested=!1,this._manager.active?i&&(this._lightProbe=s):this.fire("error",new Error("XR session is not active"))}).catch(s=>{this._lightProbeRequested=!1,this.fire("error",s)})}end(){this._lightProbeRequested=!1,this._lightProbe=null,this._available=!1}update(e){if(!this._lightProbe)return;let s=e.getLightEstimate(this._lightProbe);if(!s)return;this._available||(this._available=!0,this.fire("available"));let i=s.primaryLightIntensity;this._intensity=Math.max(1,Math.max(i.x,Math.max(i.y,i.z))),j_.copy(i).mulScalar(1/this._intensity),this._color.set(j_.x,j_.y,j_.z),j_.set(0,0,0),UG.copy(s.primaryLightDirection),Pb.setLookAt(UG,j_,x.UP),kG.setFromAxisAngle(x.RIGHT,90),Pb.mul(kG),this._rotation.setFromMat4(Pb),this._sphericalHarmonics.set(s.sphericalHarmonicsCoefficients)}get supported(){return this._supported}get available(){return this._available}get intensity(){return this._available?this._intensity:null}get color(){return this._available?this._color:null}get rotation(){return this._available?this._rotation:null}get sphericalHarmonics(){return this._available?this._sphericalHarmonics:null}};n(wh,"EVENT_AVAILABLE","available"),n(wh,"EVENT_ERROR","error");var bq=0,Ih=class extends J{constructor(e,s){super();n(this,"_id");n(this,"_planeDetection");n(this,"_xrPlane");n(this,"_lastChangedTime");n(this,"_orientation");n(this,"_position",new x);n(this,"_rotation",new $);this._id=++bq,this._planeDetection=e,this._xrPlane=s,this._lastChangedTime=s.lastChangedTime,this._orientation=s.orientation}destroy(){this._xrPlane&&(this._xrPlane=null,this.fire("remove"))}update(e){let s=this._planeDetection._manager,i=e.getPose(this._xrPlane.planeSpace,s._referenceSpace);i&&(this._position.copy(i.transform.position),this._rotation.copy(i.transform.orientation)),this._lastChangedTime!==this._xrPlane.lastChangedTime&&(this._lastChangedTime=this._xrPlane.lastChangedTime,this.fire("change"))}getPosition(){return this._position}getRotation(){return this._rotation}get id(){return this._id}get orientation(){return this._orientation}get points(){return this._xrPlane.polygon}get label(){return this._xrPlane.semanticLabel||""}};n(Ih,"EVENT_REMOVE","remove"),n(Ih,"EVENT_CHANGE","change");var on=class extends J{constructor(e){super();n(this,"_manager");n(this,"_supported",ue.browser&&!!window.XRPlane);n(this,"_available",!1);n(this,"_planesIndex",new Map);n(this,"_planes",[]);this._manager=e,this._supported&&(this._manager.on("start",this._onSessionStart,this),this._manager.on("end",this._onSessionEnd,this))}_onSessionStart(){this._manager.session.enabledFeatures&&this._manager.session.enabledFeatures.indexOf("plane-detection")!==-1&&(this._available=!0,this.fire("available"))}_onSessionEnd(){for(let e=0;e{this._uuid=s,this._anchors._indexByUuid.set(this._uuid,this),e?.(null,s);for(let i of this._uuidRequests)i(null,s);this._uuidRequests=null,this.fire("persist",s)}).catch(s=>{e?.(s,null);for(let i of this._uuidRequests)i(s,null);this._uuidRequests=null})}forget(e){if(!this._uuid){e?.(new Error("Anchor is not persistent"));return}this._anchors.forget(this._uuid,s=>{this._uuid=null,e?.(s),this.fire("forget")})}get uuid(){return this._uuid}get persistent(){return!!this._uuid}};n(nn,"EVENT_DESTROY","destroy"),n(nn,"EVENT_CHANGE","change"),n(nn,"EVENT_PERSIST","persist"),n(nn,"EVENT_FORGET","forget");var oo=class extends J{constructor(e){super();n(this,"manager");n(this,"_supported",ue.browser&&!!window.XRAnchor);n(this,"_available",!1);n(this,"_checkingAvailability",!1);n(this,"_persistence",ue.browser&&!!window?.XRSession?.prototype.restorePersistentAnchor);n(this,"_creationQueue",[]);n(this,"_index",new Map);n(this,"_indexByUuid",new Map);n(this,"_list",[]);n(this,"_callbacksAnchors",new Map);this.manager=e,this._supported&&(this.manager.on("start",this._onSessionStart,this),this.manager.on("end",this._onSessionEnd,this))}_onSessionStart(){let e=this.manager.session.enabledFeatures?.indexOf("anchors")>=0;e&&(this._available=e,this.fire("available"))}_onSessionEnd(){if(!this._available)return;this._available=!1;for(let s=0;s{let o=this._createAnchor(a);i?.(null,o),this.fire("add",o)}).catch(a=>{i?.(a,null),this.fire("error",a)})}else this._creationQueue.push({transform:new XRRigidTransform(e,s),callback:i})}restore(e,s){if(!this._available){s?.(new Error("Anchors API is not available"),null);return}if(!this._persistence){s?.(new Error("Anchor Persistence is not supported"),null);return}if(!this.manager.active){s?.(new Error("WebXR session is not active"),null);return}this.manager.session.restorePersistentAnchor(e).then(i=>{let r=this._createAnchor(i,e);s?.(null,r),this.fire("add",r)}).catch(i=>{s?.(i,null),this.fire("error",i)})}forget(e,s){if(!this._available){s?.(new Error("Anchors API is not available"));return}if(!this._persistence){s?.(new Error("Anchor Persistence is not supported"));return}if(!this.manager.active){s?.(new Error("WebXR session is not active"));return}this.manager.session.deletePersistentAnchor(e).then(()=>{s?.(null)}).catch(i=>{s?.(i),this.fire("error",i)})}update(e){if(!this._available){!this.manager.session.enabledFeatures&&!this._checkingAvailability&&(this._checkingAvailability=!0,e.createAnchor(new XRRigidTransform,this.manager._referenceSpace).then(s=>{s.delete(),this.manager.active&&(this._available=!0,this.fire("available"))}).catch(()=>{}));return}if(this._creationQueue.length){for(let s=0;s{i.callback&&this._callbacksAnchors.set(r,i.callback)}).catch(r=>{i.callback&&i.callback(r,null),this.fire("error",r)})}this._creationQueue.length=0}for(let[s,i]of this._index)e.trackedAnchors.has(s)||(this._index.delete(s),i.destroy());for(let s=0;s{this._deviceAvailabilityCheck()}),this._deviceAvailabilityCheck())}get graphicsBinding(){return this.xrBridge?.graphicsBinding??null}destroy(){this.xrBridge&&(this.xrBridge.destroy(),this.xrBridge=null)}start(e,s,i,r){let a=r;if(typeof r=="object"&&(a=r.callback),!this._available[s]){Yx("WebXR"),a&&a(new Error("XR is not available"));return}if(this._session){a&&a(new Error("XR session is already started"));return}this._camera=e,this._camera.camera.xr=this,this._type=s,this._spaceType=i,this._framebufferScaleFactor=r?.framebufferScaleFactor??1,this._setClipPlanes(e.nearClip,e.farClip);let o={requiredFeatures:[i],optionalFeatures:[]};if(this.app.graphicsDevice?.isWebGPU&&o.requiredFeatures.push("webgpu"),s===bl){if(o.optionalFeatures.push("light-estimation"),o.optionalFeatures.push("hit-test"),r&&(r.imageTracking&&this.imageTracking.supported&&o.optionalFeatures.push("image-tracking"),r.planeDetection&&o.optionalFeatures.push("plane-detection"),r.meshDetection&&o.optionalFeatures.push("mesh-detection")),this.domOverlay.supported&&this.domOverlay.root&&(o.optionalFeatures.push("dom-overlay"),o.domOverlay={root:this.domOverlay.root}),r&&r.anchors&&this.anchors.supported&&o.optionalFeatures.push("anchors"),r&&r.depthSensing&&this.views.supportedDepth){o.optionalFeatures.push("depth-sensing");let h=[],f=[];if(h.push(ox,Cb),f.push(cx,nx,lx),r.depthSensing.usagePreference){let u=h.indexOf(r.depthSensing.usagePreference);u!==-1&&h.splice(u,1),h.unshift(r.depthSensing.usagePreference)}if(r.depthSensing.dataFormatPreference){let u=f.indexOf(r.depthSensing.dataFormatPreference);u!==-1&&f.splice(u,1),f.unshift(r.depthSensing.dataFormatPreference)}o.depthSensing={usagePreference:h,dataFormatPreference:f}}r&&r.cameraColor&&this.views.supportedColor&&o.optionalFeatures.push("camera-access")}o.optionalFeatures.push("hand-tracking"),r&&r.optionalFeatures&&(o.optionalFeatures=o.optionalFeatures.concat(r.optionalFeatures)),this.imageTracking.supported&&this.imageTracking.images.length?this.imageTracking.prepareImages((h,f)=>{if(h){a&&a(h),this.fire("error",h);return}f!==null&&(o.trackedImages=f),this._onStartOptionsReady(s,i,o,a)}):this._onStartOptionsReady(s,i,o,a)}_onStartOptionsReady(e,s,i,r){navigator.xr.requestSession(e,i).then(a=>{this._onSessionStart(a,s,r)}).catch(a=>{this._camera.camera.xr=null,this._camera=null,this._type=null,this._spaceType=null,r&&r(a),this.fire("error",a)})}end(e){if(!this._session){e&&e(new Error("XR Session is not initialized"));return}this.xrBridge?.releasePresentation(),e&&this.once("end",e),this._session.end()}isAvailable(e){return this._available[e]}_deviceAvailabilityCheck(){for(let e in this._available)this._sessionSupportCheck(e)}initiateRoomCapture(e){if(!this._session){e(new Error("Session is not active"));return}if(!this._session.initiateRoomCapture){e(new Error("Session does not support manual room capture"));return}this._session.initiateRoomCapture().then(()=>{e&&e(null)}).catch(s=>{e&&e(s)})}updateTargetFrameRate(e,s){if(!this._session?.updateTargetFrameRate){s?.(new Error("unable to update frameRate"));return}this._session.updateTargetFrameRate(e).then(()=>{s?.()}).catch(i=>{s?.(i)})}_sessionSupportCheck(e){navigator.xr.isSessionSupported(e).then(s=>{this._available[e]!==s&&(this._available[e]=s,this.fire("available",e,s),this.fire(`available:${e}`,s))}).catch(s=>{this.fire("error",s)})}_onSessionStart(e,s,i){let r=!1;this._session=e,this.xrBridge=new pA(this.app.graphicsDevice,this);let a=()=>{this.fire("visibility:change",e.visibilityState)},o=()=>{this._setClipPlanes(this._camera.nearClip,this._camera.farClip)},l=()=>{this.fire("frameratechange",this._session?.frameRate)},h=()=>{this._camera&&(this._camera.off("set_nearClip",o),this._camera.off("set_farClip",o),this._camera.camera.xr=null,this._camera=null),e.removeEventListener("end",h),e.removeEventListener("visibilitychange",a),e.removeEventListener("frameratechange",l),r||this.fire("end"),this.xrBridge&&(this.xrBridge.destroy(),this.xrBridge=null),this._session=null,this._referenceSpace=null,this._width=0,this._height=0,this._type=null,this._spaceType=null,this.app.systems&&this.app.requestAnimationFrame()};e.addEventListener("end",h),e.addEventListener("visibilitychange",a),this._camera.on("set_nearClip",o),this._camera.on("set_farClip",o);let u=this.app.graphicsDevice.maxPixelRatio/window.devicePixelRatio*this._framebufferScaleFactor;this.xrBridge.attachPresentation(this._session,{framebufferScaleFactor:u,depthNear:this._depthNear,depthFar:this._depthFar,onBindingError:d=>{this.fire("error",d)}}),this.session.supportedFrameRates?this._supportedFrameRates=Array.from(this.session.supportedFrameRates):this._supportedFrameRates=null,this._session.addEventListener("frameratechange",l),e.requestReferenceSpace(s).then(d=>{this._referenceSpace=d,this.app.requestAnimationFrame(),i&&i(null),this.fire("start")}).catch(d=>{r=!0,e.end(),i&&i(d),this.fire("error",d)})}_setClipPlanes(e,s){this._depthNear===e&&this._depthFar===s||(this._depthNear=e,this._depthFar=s,this._session&&this._session.updateRenderState({depthNear:this._depthNear,depthFar:this._depthFar}))}update(e){if(!this._session)return!1;this.xrBridge.getFramebufferSize(e,this._framebufferSize);let s=this._framebufferSize.x,i=this._framebufferSize.y;(this._width!==s||this._height!==i)&&(this._width=s,this._height=i,this.app.graphicsDevice.setResolution(s,i));let r=e.getViewerPose(this._referenceSpace);if(!r)return!1;let a=this.views.list.length;this.views.update(e,r.views);let o=r.transform.position,l=r.transform.orientation;if(this._localPosition.set(o.x,o.y,o.z),this._localRotation.set(l.x,l.y,l.z,l.w),a===0&&this.views.list.length>0){let h=new W,f=this.views.list[0];h.copy(f.projMat);let u=h.data,d=2*Math.atan(1/u[5])*180/Math.PI,p=u[5]/u[0],m=u[14]/(u[10]+1),_=u[14]/(u[10]-1);this._camera.camera.setXrProperties({aspectRatio:p,farClip:m,fov:d,horizontalFov:!1,nearClip:_})}return this._camera.camera._node.setLocalPosition(this._localPosition),this._camera.camera._node.setLocalRotation(this._localRotation),this.input.update(e),this._type===bl&&(this.hitTest.supported&&this.hitTest.update(e),this.lightEstimation.supported&&this.lightEstimation.update(e),this.imageTracking.supported&&this.imageTracking.update(e),this.anchors.supported&&this.anchors.update(e),this.planeDetection.supported&&this.planeDetection.update(e),this.meshDetection.supported&&this.meshDetection.update(e)),this.fire("update",e),this.xrBridge.beginFrame(e,this._referenceSpace),!0}get supported(){return this._supported}get active(){return!!this._session}get type(){return this._type}get spaceType(){return this._spaceType}get session(){return this._session}get frameRate(){return this._session?.frameRate??null}get supportedFrameRates(){return this._supportedFrameRates}get framebufferScaleFactor(){return this._framebufferScaleFactor}set fixedFoveation(e){let s=this.xrBridge?.presentationLayer;(s?.fixedFoveation??null)!==null&&(this.app.graphicsDevice.samples>1,s.fixedFoveation=e)}get fixedFoveation(){return this.xrBridge?.presentationLayer?.fixedFoveation??null}get camera(){return this._camera?this._camera.entity:null}get visibilityState(){return this._session?this._session.visibilityState:null}};n(no,"EVENT_AVAILABLE","available"),n(no,"EVENT_START","start"),n(no,"EVENT_END","end"),n(no,"EVENT_UPDATE","update"),n(no,"EVENT_ERROR","error");var mA=class extends Pi{constructor(t,e={}){super(t);let s=new Tm;s.graphicsDevice=e.graphicsDevice??this.createDevice(t,e),this.addComponentSystems(s),this.addResourceHandles(s),s.elementInput=e.elementInput,s.keyboard=e.keyboard,s.mouse=e.mouse,s.touch=e.touch,s.gamepads=e.gamepads,s.scriptPrefix=e.scriptPrefix,s.assetPrefix=e.assetPrefix,s.scriptsOrder=e.scriptsOrder,s.soundManager=new tp,s.lightmapper=Em,s.batchManager=Rp,s.xr=no,this.init(s)}createDevice(t,e){return e.graphicsDeviceOptions||(e.graphicsDeviceOptions={}),ue.browser&&navigator.xr&&(e.graphicsDeviceOptions.xrCompatible=!0),e.graphicsDeviceOptions.alpha=e.graphicsDeviceOptions.alpha||!1,new pc(t,e.graphicsDeviceOptions)}addComponentSystems(t){t.componentSystems=[Al,Fm,Gm,Pm,Rm,Xm,qm,o_,n_,h_,s_,bm,jm,Jm,zm,Lm,e_,t_,i_,Wm,Vm,r_,vh]}addResourceHandles(t){t.resourceHandlers=[g_,v_,T_,y_,B_,N_,X_,H_,O_,E_,k_,U_,I_,M_,w_,z_,L_,R_,b_,A_,W_,G_,V_,P_,D_]}};var _A=class extends J{constructor(e,s){super();n(this,"_assets",new Set);n(this,"_loadingAssets",new Set);n(this,"_waitingAssets",new Set);n(this,"_loading",!1);n(this,"_loaded",!1);n(this,"_failed",[]);this._registry=s,e.forEach(i=>{if(i instanceof ae)i.registry||(i.registry=s),this._assets.add(i);else{let r=s.get(i);r?this._assets.add(r):this._waitForAsset(i)}})}destroy(){this._registry.off("load",this._onLoad),this._registry.off("error",this._onError),this._waitingAssets.forEach(e=>{this._registry.off(`add:${e}`,this._onAddAsset)}),this.off("progress"),this.off("load")}_assetHasDependencies(e){return e.type==="model"&&e.file?.url&&e.file.url&&e.file.url.match(/.json$/g)}load(e,s){if(this._loading)return;this._loading=!0,this._callback=e,this._scope=s,this._registry.on("load",this._onLoad,this),this._registry.on("error",this._onError,this);let i=!1;this._assets.forEach(r=>{r.loaded||(i=!0,this._assetHasDependencies(r)&&this._registry.loadFromUrl(r.file.url,r.type,(a,o)=>{if(a){this._onError(a,r);return}this._onLoad(r)}),this._loadingAssets.add(r),this._registry.add(r))}),this._loadingAssets.forEach(r=>{this._assetHasDependencies(r)||this._registry.load(r)}),!i&&this._waitingAssets.size===0&&this._loadingComplete()}ready(e,s=this){this._loaded?e.call(s,Array.from(this._assets)):this.once("load",i=>{e.call(s,i)})}_loadingComplete(){this._loaded||(this._loaded=!0,this._registry.off("load",this._onLoad,this),this._registry.off("error",this._onError,this),this._failed.length?(this._callback&&this._callback.call(this._scope,"Failed to load some assets",this._failed),this.fire("error",this._failed)):(this._callback&&this._callback.call(this._scope),this.fire("load",Array.from(this._assets))))}_onLoad(e){this._loadingAssets.has(e)&&(this.fire("progress",e),this._loadingAssets.delete(e)),this._loadingAssets.size===0&&setTimeout(()=>{this._loadingComplete()},0)}_onError(e,s){this._loadingAssets.has(s)&&(this._failed.push(s),this._loadingAssets.delete(s)),this._loadingAssets.size===0&&setTimeout(()=>{this._loadingComplete()},0)}_onAddAsset(e){this._waitingAssets.delete(e),this._assets.add(e),e.loaded||(this._loadingAssets.add(e),this._registry.load(e))}_waitForAsset(e){this._waitingAssets.add(e),this._registry.once(`add:${e}`,this._onAddAsset,this)}};var zG=4096,GG=512,wb=class{constructor(t,e,s,i){this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=s,this.texture=new Z(t,{name:i,format:st,width:e,height:s,mipmaps:!0,minFilter:5,magFilter:1,addressU:1,addressV:1,levels:[this.canvas]}),this.ctx=this.canvas.getContext("2d",{alpha:!0})}destroy(){this.texture.destroy()}clear(t){let{width:e,height:s}=this.canvas;this.ctx.clearRect(0,0,e,s),this.ctx.fillStyle=t,this.ctx.fillRect(0,0,e,s)}},gA=class extends J{constructor(t,e={}){super(),this.type="bitmap",this.app=t,this.intensity=0,this.fontWeight=e.fontWeight||"normal",this.fontSize=parseInt(e.fontSize,10),this.glyphSize=this.fontSize,this.fontName=e.fontName||"Arial",this.color=e.color||new F(1,1,1),this.padding=e.padding||0,this.width=Math.min(zG,e.width||GG),this.height=Math.min(zG,e.height||GG),this.atlases=[],this.chars="",this.data={}}createTextures(t){let e=this._normalizeCharsSet(t);if(e.length!==this.chars.length){this._renderAtlas(e);return}for(let s=0;s0&&this._renderAtlas(this.chars.concat(s))}destroy(){this.atlases.forEach(t=>t.destroy()),this.chars=null,this.color=null,this.data=null,this.fontName=null,this.fontSize=null,this.glyphSize=null,this.intensity=null,this.atlases=null,this.type=null,this.fontWeight=null}_colorToRgbString(t,e){let s,i=Math.round(255*t.r),r=Math.round(255*t.g),a=Math.round(255*t.b);return e?s=`rgba(${i}, ${r}, ${a}, ${t.a})`:s=`rgb(${i}, ${r}, ${a})`,s}renderCharacter(t,e,s,i,r){t.fillStyle=r,t.fillText(e,s,i)}_getAtlas(t){return t>=this.atlases.length&&(this.atlases[t]=new wb(this.app.graphicsDevice,this.width,this.height,`font-atlas-${this.fontName}-${t}`)),this.atlases[t]}_renderAtlas(t){this.chars=t;let e=this.width,s=this.height,i=this._colorToRgbString(this.color,!1),r=this.color.a;this.color.a=1/255;let a=this._colorToRgbString(this.color,!0);this.color.a=r;let o="center",l="alphabetic",h=0,f=this._getAtlas(h++);f.clear(a),this.data=this._createJson(this.chars,this.fontName,e,s);let u=Nr.getSymbols(this.chars.join("")),d=0,p=0,m={};for(let E=0;EA&&(A=this.fontSize*this.fontSize/w,f.ctx.font=`${this.fontWeight} ${A.toString()}px ${this.fontName}`,w=this.fontSize),this.renderCharacter(f.ctx,y,C+g,v+T,i);let I=this.padding+(this.glyphSize-w)/2,D=-this.padding+m[y].descent-p,O=w;this._addChar(this.data,y,P,C,v,_,S,I,D,O,h-1,e,s),C+=_,C+_>e&&(C=0,v+=S,v+S>s&&(f=this._getAtlas(h++),f.clear(a),v=0))}this.atlases.splice(h).forEach(E=>E.destroy()),this.atlases.forEach(E=>E.texture.upload()),this.fire("render")}_createJson(t,e,s,i){return{version:3,intensity:this.intensity,info:{face:e,width:s,height:i,maps:[{width:s,height:i}]},chars:{}}}_addChar(t,e,s,i,r,a,o,l,h,f,u,d,p){t.info.maps.lengtht.texture)}};var hx=[],Dq=[[],[],[]],Lq=new Float32Array(2),$_=class extends yt{constructor(e,s){super(e);n(this,"viewBindGroups",[]);n(this,"blendState",Oe.NOBLEND);n(this,"camera");n(this,"scene");n(this,"layers");n(this,"mapping");n(this,"depth");n(this,"_qualifiedLayerIndices",[]);n(this,"_pickMeshInstances",new Map);this.renderer=s}destroy(){this.viewBindGroups.forEach(e=>{e.defaultUniformBuffer.destroy(),e.destroy()}),this.viewBindGroups.length=0}update(e,s,i,r,a){this.camera=e,this.scene=s,this.layers=i,this.mapping=r,this.depth=a,s.clusteredLightingEnabled&&(this.emptyWorldClusters=this.renderer.worldClustersAllocator.empty)}before(){this._qualifiedLayerIndices.length=0,this._pickMeshInstances.clear();let{camera:e,scene:s,layers:i}=this,r=s.layers.layerList,a=s.layers.subLayerEnabled,o=this.renderer.gsplatDirector,l=this.renderTarget?.width??1,h=this.renderTarget?.height??1;for(let f=0;f0){let _=r.clusteredLightingEnabled;_&&this.emptyWorldClusters.activate(),s.setCameraUniforms(i.camera,o),s.dispatchGlobalLights(r),e.scope.resolve("shadowAtlasParams").setValue(Lq),e.supportsUniformBuffers&&(s.initViewBindGroupFormat(_),s.setupViewUniformBuffers(this.viewBindGroups,s.viewUniformFormat,s.viewBindGroupFormat,null));let S=this.depth?Sp:ta;s.renderForward(i.camera,o,hx,Dq,S,g=>{e.setBlendState(this.blendState)}),hx.length=0}}}};var Ib=new Set,Mq=new Q,VG=new Float32Array(1),Oq=new Int32Array(VG.buffer),SA=class{constructor(t,e,s,i=!1){n(this,"device");n(this,"renderPass");n(this,"depth");n(this,"width");n(this,"height");n(this,"renderTarget",null);n(this,"colorBuffer",null);n(this,"depthBuffer",null);n(this,"renderTargetDepth",null);n(this,"mapping",new Map);n(this,"deviceValid",!0);this.device=t.graphicsDevice,this.renderPass=new $_(this.device,t.renderer),this.depth=i,this.width=0,this.height=0,this.resize(e,s),this.allocateRenderTarget(),this.device.on("destroy",()=>{this.deviceValid=!1})}destroy(){this.releaseRenderTarget(),this.renderPass?.destroy()}getSelection(t,e,s=1,i=1){let r=this.device;if(r.isWebGPU)return[];e=this.renderTarget.height-(e+i);let a=this.sanitizeRect(t,e,s,i);r.setRenderTarget(this.renderTarget),r.updateBegin();let o=new Uint8Array(4*a.z*a.w);return r.readPixels(a.x,a.y,a.z,a.w,o),r.updateEnd(),this.decodePixels(o,this.mapping)}getSelectionAsync(t,e,s=1,i=1){return!this.renderTarget||!this.renderTarget.colorBuffer?Promise.resolve([]):this._readTexture(this.renderTarget.colorBuffer,t,e,s,i,this.renderTarget).then(r=>this.decodePixels(r,this.mapping))}_readTexture(t,e,s,i,r,a){this.device?.isWebGL2&&(s=a.height-(s+r));let o=this.sanitizeRect(e,s,i,r);return t.read(o.x,o.y,o.z,o.w,{immediate:!0,renderTarget:a})}async getWorldPointAsync(t,e){let s=this.renderPass.camera;if(!s)return null;let r=new W().mul2(s.camera.projectionMatrix,s.camera.viewMatrix).invert(),a=s.nearClip,o=s.farClip,l=s.projection===ni,h=await this.getPointDepthAsync(t,e);if(h===null)return null;let f=l?h:o*h/(h*(o-a)+a),u=new Q(t/this.width*2-1,(1-e/this.height)*2-1,f*2-1,1);return r.transformVec4(u,u),u.mulScalar(1/u.w),new x(u.x,u.y,u.z)}async getPointDepthAsync(t,e){if(!this.depthBuffer)return null;let s=await this._readTexture(this.depthBuffer,t,e,1,1,this.renderTargetDepth),i=(s[0]<<24|s[1]<<16|s[2]<<8|s[3])>>>0;return i===4294967295?null:(Oq[0]=i,VG[0])}sanitizeRect(t,e,s,i){let r=this.renderTarget.width,a=this.renderTarget.height;return t=R.clamp(Math.floor(t),0,r-1),e=R.clamp(Math.floor(e),0,a-1),s=Math.floor(Math.max(s,1)),s=Math.min(s,r-t),i=Math.floor(Math.max(i,1)),i=Math.min(i,a-e),Mq.set(t,e,s,i)}decodePixels(t,e){let s=[];if(this.deviceValid){let i=t.length;for(let r=0;r>>0;f!==4294967295&&Ib.add(e.get(f))}Ib.forEach(r=>{r&&s.push(r)}),Ib.clear()}return s}createTexture(t){return Z.createDataTexture2D(this.device,t,this.width,this.height,ce)}allocateRenderTarget(){this.colorBuffer=this.createTexture("pick");let t=[this.colorBuffer];this.depth&&(this.depthBuffer=this.createTexture("pick-depth"),t.push(this.depthBuffer),this.renderTargetDepth=new me({colorBuffer:this.depthBuffer,depth:!1})),this.renderTarget=new me({colorBuffers:t,depth:!0})}releaseRenderTarget(){this.renderTarget?.destroyTextureBuffers(),this.renderTarget?.destroy(),this.renderTarget=null,this.renderTargetDepth?.destroy(),this.renderTargetDepth=null,this.colorBuffer=null,this.depthBuffer=null}prepare(t,e,s){s instanceof Dt&&(s=[s]),this.renderTarget?.resize(this.width,this.height),this.renderTargetDepth?.resize(this.width,this.height),this.mapping.clear();let i=this.renderPass;i.init(this.renderTarget),i.setClearColor(F.WHITE),i.depthStencilOps.clearDepth=!0,i.update(t,e,s,this.mapping,this.depth),i.render()}resize(t,e){this.width=Math.floor(t),this.height=Math.floor(e)}};var xA=class extends Re{constructor(t){super(t,"scenesettings")}load(t,e){Eh.load(t,this.maxRetries,e)}open(t,e){return e.settings}};var bh,Dh,Rb=new x,HG=new x,Dl=new ws,dx=new ws,Mb=new ws;Dl.end=new x;dx.end=new x;Mb.end=new x;var Z_=new x,vA=new x,bb=new x,WG=new x,Db=new x,TA=new x,yA=new x,EA=new x,AA=new x,Lb=new x,Fq=new x,Q_=new x,fx=new x,CA=new x,PA=new x,ux=new x,XG=new x,YG=new x,KG=new x,jG=new x,Nq=new Q;function qG(c,t,e){return Fq.cross(c,t).dot(e)}function Bq(c,t,e){Z_.sub2(t,c),vA.sub2(e[0],c),bb.sub2(e[1],c),WG.sub2(e[2],c),TA.cross(WG,Z_);let s=vA.dot(TA),i,r;if(s>=0){if(i=-bb.dot(TA),i<0||(r=qG(Z_,bb,vA),r<0))return-1;let a=1/(i+s+r);yA.copy(e[0]).mulScalar(i*a),EA.copy(e[1]).mulScalar(s*a),AA.copy(e[2]).mulScalar(r*a),Lb.copy(yA).add(EA).add(AA)}else{if(Db.sub2(e[3],c),i=Db.dot(TA),i<0||(r=qG(Z_,vA,Db),r<0))return-1;s=-s;let a=1/(i+s+r);yA.copy(e[0]).mulScalar(i*a),EA.copy(e[3]).mulScalar(s*a),AA.copy(e[2]).mulScalar(r*a),Lb.copy(yA).add(EA).add(AA)}return Z_.sub2(e[0],e[2]).lengthSq()<1e-4*1e-4||Z_.sub2(e[1],e[3]).lengthSq()<1e-4*1e-4?-1:Lb.sub(c).lengthSq()}var Gu=class{constructor(t,e,s){this.event=t,this.element=e,this.camera=s,this._stopPropagation=!1}stopPropagation(){this._stopPropagation=!0,this.event&&(this.event.stopImmediatePropagation(),this.event.stopPropagation())}},Ll=class extends Gu{constructor(t,e,s,i,r,a,o){super(t,e,s),this.x=i,this.y=r,this.ctrlKey=t.ctrlKey||!1,this.altKey=t.altKey||!1,this.shiftKey=t.shiftKey||!1,this.metaKey=t.metaKey||!1,this.button=t.button,qi.isPointerLocked()?(this.dx=t.movementX||t.webkitMovementX||t.mozMovementX||0,this.dy=t.movementY||t.webkitMovementY||t.mozMovementY||0):(this.dx=i-a,this.dy=r-o),this.wheelDelta=0,t.type==="wheel"&&(t.deltaY>0?this.wheelDelta=1:t.deltaY<0&&(this.wheelDelta=-1))}},Ml=class extends Gu{constructor(t,e,s,i,r,a){super(t,e,s),this.touches=t.touches,this.changedTouches=t.changedTouches,this.x=i,this.y=r,this.touch=a}},ga=class extends Gu{constructor(t,e,s,i){super(t,e,s),this.inputSource=i}},J_=class c{constructor(t,e){this._app=null,this._attached=!1,this._target=null,this._enabled=!0,this._lastX=0,this._lastY=0,this._upHandler=this._handleUp.bind(this),this._downHandler=this._handleDown.bind(this),this._moveHandler=this._handleMove.bind(this),this._wheelHandler=this._handleWheel.bind(this),this._touchstartHandler=this._handleTouchStart.bind(this),this._touchendHandler=this._handleTouchEnd.bind(this),this._touchcancelHandler=this._touchendHandler,this._touchmoveHandler=this._handleTouchMove.bind(this),this._sortHandler=this._sortElements.bind(this),this._elements=[],this._hoveredElement=null,this._pressedElement=null,this._touchedElements={},this._touchesForWhichTouchLeaveHasFired={},this._selectedElements={},this._selectedPressedElements={},this._useMouse=!e||e.useMouse!==!1,this._useTouch=!e||e.useTouch!==!1,this._useXr=!e||e.useXr!==!1,this._selectEventsAttached=!1,ue.touch&&(this._clickedEntities={}),this.attach(t)}set enabled(t){this._enabled=t}get enabled(){return this._enabled}set app(t){this._app=t}get app(){return this._app||ys()}attach(t){this._attached&&(this._attached=!1,this.detach()),this._target=t,this._attached=!0;let e=ue.passiveEvents?{passive:!0}:!1;this._useMouse&&(window.addEventListener("mouseup",this._upHandler,e),window.addEventListener("mousedown",this._downHandler,e),window.addEventListener("mousemove",this._moveHandler,e),window.addEventListener("wheel",this._wheelHandler,e)),this._useTouch&&ue.touch&&(this._target.addEventListener("touchstart",this._touchstartHandler,e),this._target.addEventListener("touchend",this._touchendHandler,!1),this._target.addEventListener("touchmove",this._touchmoveHandler,!1),this._target.addEventListener("touchcancel",this._touchcancelHandler,!1)),this.attachSelectEvents()}attachSelectEvents(){!this._selectEventsAttached&&this._useXr&&this.app&&this.app.xr&&this.app.xr.supported&&(this._clickedEntities||(this._clickedEntities={}),this._selectEventsAttached=!0,this.app.xr.on("start",this._onXrStart,this))}detach(){if(!this._attached)return;this._attached=!1;let t=ue.passiveEvents?{passive:!0}:!1;this._useMouse&&(window.removeEventListener("mouseup",this._upHandler,t),window.removeEventListener("mousedown",this._downHandler,t),window.removeEventListener("mousemove",this._moveHandler,t),window.removeEventListener("wheel",this._wheelHandler,t)),this._useTouch&&(this._target.removeEventListener("touchstart",this._touchstartHandler,t),this._target.removeEventListener("touchend",this._touchendHandler,!1),this._target.removeEventListener("touchmove",this._touchmoveHandler,!1),this._target.removeEventListener("touchcancel",this._touchcancelHandler,!1)),this._selectEventsAttached&&(this._selectEventsAttached=!1,this.app.xr.off("start",this._onXrStart,this),this.app.xr.off("end",this._onXrEnd,this),this.app.xr.off("update",this._onXrUpdate,this),this.app.xr.input.off("selectstart",this._onSelectStart,this),this.app.xr.input.off("selectend",this._onSelectEnd,this),this.app.xr.input.off("remove",this._onXrInputRemove,this)),this._target=null}addElement(t){this._elements.indexOf(t)===-1&&this._elements.push(t)}removeElement(t){let e=this._elements.indexOf(t);e!==-1&&this._elements.splice(e,1)}_handleUp(t){this._enabled&&(qi.isPointerLocked()||(this._calcMouseCoords(t),this._onElementMouseEvent("mouseup",t)))}_handleDown(t){this._enabled&&(qi.isPointerLocked()||(this._calcMouseCoords(t),this._onElementMouseEvent("mousedown",t)))}_handleMove(t){this._enabled&&(this._calcMouseCoords(t),this._onElementMouseEvent("mousemove",t),this._lastX=bh,this._lastY=Dh)}_handleWheel(t){this._enabled&&(this._calcMouseCoords(t),this._onElementMouseEvent("mousewheel",t))}_determineTouchedElements(t){let e={},s=this.app.systems.camera.cameras;for(let i=s.length-1;i>=0;i--){let r=s[i],a=0,o=t.changedTouches.length;for(let l=0;l=0;d--)this._getTargetElementByCoords(e[d],u.x,u.y)===o&&(this._clickedEntities[o.entity.guid]||(this._fireEvent("click",new Ml(t,o,l,h,f,r)),this._clickedEntities[o.entity.guid]=Date.now()));this._fireEvent(t.type,new Ml(t,o,l,h,f,r))}}_handleTouchMove(t){if(t.preventDefault(),!this._enabled)return;let e=this._determineTouchedElements(t);for(let s=0,i=t.changedTouches.length;s=0&&(a=r[o],s=this._getTargetElementByCoords(a,bh,Dh),!s);o--);if(this._hoveredElement=s,(t==="mousemove"||t==="mouseup")&&this._pressedElement?this._fireEvent(t,new Ll(e,this._pressedElement,a,bh,Dh,this._lastX,this._lastY)):s&&(this._fireEvent(t,new Ll(e,s,a,bh,Dh,this._lastX,this._lastY)),t==="mousedown"&&(this._pressedElement=s)),i!==this._hoveredElement&&(i&&this._fireEvent("mouseleave",new Ll(e,i,a,bh,Dh,this._lastX,this._lastY)),this._hoveredElement&&this._fireEvent("mouseenter",new Ll(e,this._hoveredElement,a,bh,Dh,this._lastX,this._lastY))),t==="mouseup"&&this._pressedElement){if(this._pressedElement===this._hoveredElement){let o=this._hoveredElement.entity.guid,l=!this._clickedEntities;if(this._clickedEntities){let h=this._clickedEntities[o]||0;l=Date.now()-h>300,delete this._clickedEntities[o]}l&&this._fireEvent("click",new Ll(e,this._hoveredElement,a,bh,Dh,this._lastX,this._lastY))}this._pressedElement=null}}_onXrStart(){this.app.xr.on("end",this._onXrEnd,this),this.app.xr.on("update",this._onXrUpdate,this),this.app.xr.input.on("selectstart",this._onSelectStart,this),this.app.xr.input.on("selectend",this._onSelectEnd,this),this.app.xr.input.on("remove",this._onXrInputRemove,this)}_onXrEnd(){this.app.xr.off("update",this._onXrUpdate,this),this.app.xr.input.off("selectstart",this._onSelectStart,this),this.app.xr.input.off("selectend",this._onSelectEnd,this),this.app.xr.input.off("remove",this._onXrInputRemove,this)}_onXrUpdate(){if(!this._enabled)return;let t=this.app.xr.input.inputSources;for(let e=0;e=0&&(l=o[f],i=this._getTargetElementByRay(Mb,l),!i);f--);}e._elementEntity=i||null,i?(this._selectedElements[e.id]=i,a=i):delete this._selectedElements[e.id],r!==a&&(r&&this._fireEvent("selectleave",new ga(s,r,l,e)),a&&this._fireEvent("selectenter",new ga(s,a,l,e)));let h=this._selectedPressedElements[e.id];t==="selectmove"&&h&&this._fireEvent("selectmove",new ga(s,h,l,e)),t==="selectstart"&&(this._selectedPressedElements[e.id]=a,a&&this._fireEvent("selectstart",new ga(s,a,l,e))),!e.elementInput&&h&&(delete this._selectedPressedElements[e.id],r&&this._fireEvent("selectend",new ga(s,h,l,e))),t==="selectend"&&e.elementInput&&(delete this._selectedPressedElements[e.id],h&&this._fireEvent("selectend",new ga(s,h,l,e)),h&&h===r&&this._fireEvent("click",new ga(s,h,l,e)))}_fireEvent(t,e){let s=e.element;for(;s.fire(t,e),!(e._stopPropagation||!s.entity.parent||(s=s.entity.parent.element,!s)););}_calcMouseCoords(t){let e=this._target.getBoundingClientRect(),s=Math.floor(e.left),i=Math.floor(e.top);bh=t.clientX-s,Dh=t.clientY-i}_sortElements(t,e){let s=this.app.scene.layers.sortTransparentLayers(t.layers,e.layers);return s!==0?s:t.screen&&!e.screen?-1:!t.screen&&e.screen?1:!t.screen&&!e.screen?0:t.screen.screen.screenSpace&&!e.screen.screen.screenSpace?-1:e.screen.screen.screenSpace&&!t.screen.screen.screenSpace?1:e.drawOrder-t.drawOrder}_getTargetElementByCoords(t,e,s){let i=this._calculateRayScreen(e,s,t,Dl)?Dl:null,r=this._calculateRay3d(e,s,t,dx)?dx:null;return this._getTargetElement(t,i,r)}_getTargetElementByRay(t,e){Dl.origin.copy(t.origin),Dl.direction.copy(t.direction),Dl.end.copy(Dl.direction).mulScalar(e.farClip*2).add(Dl.origin);let s=Dl,i=e.worldToScreen(s.origin,Rb),r=this._calculateRayScreen(i.x,i.y,e,dx)?dx:null;return this._getTargetElement(e,r,s)}_getTargetElement(t,e,s){let i=null,r=1/0;this._elements.sort(this._sortHandler);for(let a=0,o=this._elements.length;at.layersSet.has(h)))if(l.screen&&l.screen.screen.screenSpace){if(!e)continue;if(this._checkElement(e,l,!0)>=0){i=l;break}}else{if(!s)continue;let h=this._checkElement(s,l,!1);if(h>=0&&(h=h&&p<=f&&m<=u&&m>=d?(p=r*(p-h)/o,m=a*(m-d)/l,m=a-m,i.origin.set(p,m,1),i.direction.set(0,0,-1),i.end.copy(i.direction).mulScalar(2).add(i.origin),!0):!1}_calculateRay3d(t,e,s,i){let r=this._target.clientWidth,a=this._target.clientHeight,o=s.rect.z*r,l=s.rect.w*a,h=s.rect.x*r,f=h+o,u=(1-s.rect.y)*a,d=u-l,p=t,m=e;return t>=h&&t<=f&&e<=u&&m>=d?(p=r*(p-h)/o,m=a*(m-d)/l,s.screenToWorld(p,m,s.nearClip,Rb),s.screenToWorld(p,m,s.farClip,HG),i.origin.copy(Rb),i.direction.set(0,0,-1),i.end.copy(HG),!0):!1}_checkElement(t,e,s){if(e.maskedBy&&this._checkElement(t,e.maskedBy.element,s)<0)return-1;let i;s?i=c.calculateScaleToScreen(e):i=c.calculateScaleToWorld(e);let r=c.buildHitCorners(e,s?e.screenCorners:e.worldCorners,i);return Bq(t.origin,t.end,r)}static buildHitCorners(t,e,s){let i=e;if(t.entity&&t.entity.button){let a=t.entity.button.hitPadding||Nq;fx.copy(t.entity.up),CA.copy(fx).mulScalar(-1),ux.copy(t.entity.right),PA.copy(ux).mulScalar(-1),fx.mulScalar(a.w*s.y),CA.mulScalar(a.y*s.y),ux.mulScalar(a.z*s.x),PA.mulScalar(a.x*s.x),XG.copy(i[0]).add(CA).add(PA),YG.copy(i[1]).add(CA).add(ux),KG.copy(i[2]).add(fx).add(ux),jG.copy(i[3]).add(fx).add(PA),i=[XG,YG,KG,jG]}if(s.x<0){let a=i[2].x,o=i[0].x;i[0].x=a,i[1].x=o,i[2].x=o,i[3].x=a}if(s.y<0){let a=i[2].y,o=i[0].y;i[0].y=a,i[1].y=a,i[2].y=o,i[3].y=o}if(s.z<0){let a=i[2].x,o=i[2].y,l=i[2].z;i[2].x=i[0].x,i[2].y=i[0].y,i[2].z=i[0].z,i[0].x=a,i[0].y=o,i[0].z=l}return i}static calculateScaleToScreen(t){let e=t.entity,s=t.screen.screen.scale;for(Q_.set(s,s,s);e&&!e.screen;)Q_.mul(e.getLocalScale()),e=e.parent;return Q_}static calculateScaleToWorld(t){let e=t.entity;for(Q_.set(1,1,1);e;)Q_.mul(e.getLocalScale()),e=e.parent;return Q_}};B.prototype.scale=B.prototype.mulScalar;x.prototype.scale=x.prototype.mulScalar;Q.prototype.scale=Q.prototype.mulScalar;var Uq=vo,kq=ya,zq=xn,Gq=Ea,Vq=Ss,Hq=ce,Wq=yo,Xq=st,Yq=11,Kq=12,jq=11,qq=12,$q="1.51",Zq="1.55",Qq="1.56",Jq="1.57",e$="1.58",t$="1.60",s$="1.62",i$="1.65",r$="1.70",a$="2.1",o$="2.3",n$="2.5",l$="2.6",c$="2.7",h$="2.8",f$=new Q;function u$(c,t){return _e.fromGeometry(c,new wr(t))}function d$(c,t){return _e.fromGeometry(c,new $a(t))}function p$(c,t){return _e.fromGeometry(c,new ci(t))}function m$(c,t){return _e.fromGeometry(c,new Za(t))}function _$(c,t){return _e.fromGeometry(c,new Yc(t))}function g$(c,t){return _e.fromGeometry(c,new qa(t))}function S$(c,t){return _e.fromGeometry(c,new Ci(t))}function x$(c,t,e={}){let s=new Jt;return s.positions=t,s.normals=e.normals,s.tangents=e.tangents,s.colors=e.colors,s.uvs=e.uvs,s.uvs1=e.uvs1,s.blendIndices=e.blendIndices,s.blendWeights=e.blendWeights,s.indices=e.indices,_e.fromGeometry(c,s,e)}function v$(c,t,e,s,i){let r;if(i){let a=t?t.width:c.width,o=t?t.height:c.height;r=f$.set(i.x*a,i.y*o,i.z*a,i.w*o)}Qt(c,t,s,r)}Object.defineProperties(me.prototype,{_glFrameBuffer:{get:function(){return this.impl._glFrameBuffer},set:function(c){}}});Object.defineProperty(Ft,"defaultInstancingFormat",{get:function(){return null}});Object.defineProperties(Z.prototype,{rgbm:{get:function(){return this.type===_i},set:function(c){this.type=c?_i:Gt}},swizzleGGGR:{get:function(){return this.type===Rn},set:function(c){this.type=c?Rn:Gt}},_glTexture:{get:function(){return this.impl._glTexture}}});Object.defineProperty(tt.prototype,"boneLimit",{get:function(){return 1024}});Object.defineProperty(tt.prototype,"webgl2",{get:function(){return this.isWebGL2}});Object.defineProperty(tt.prototype,"textureFloatHighPrecision",{get:function(){return!0}});Object.defineProperty(tt.prototype,"extBlendMinmax",{get:function(){return!0}});Object.defineProperty(tt.prototype,"extTextureHalfFloat",{get:function(){return!0}});Object.defineProperty(tt.prototype,"extTextureLod",{get:function(){return!0}});Object.defineProperty(tt.prototype,"textureHalfFloatFilterable",{get:function(){return!0}});Object.defineProperty(tt.prototype,"supportsMrt",{get:function(){return!0}});Object.defineProperty(tt.prototype,"supportsVolumeTextures",{get:function(){return!0}});Object.defineProperty(tt.prototype,"supportsInstancing",{get:function(){return!0}});Object.defineProperty(tt.prototype,"textureHalfFloatUpdatable",{get:function(){return!0}});Object.defineProperty(tt.prototype,"extTextureFloat",{get:function(){return!0}});Object.defineProperty(tt.prototype,"extStandardDerivatives",{get:function(){return!0}});Oe.DEFAULT=Object.freeze(new Oe);var ss=new Oe,Ol=new Pt;tt.prototype.setBlendFunction=function(c,t){let e=this.blendState;ss.copy(e),ss.setColorBlend(e.colorOp,c,t),ss.setAlphaBlend(e.alphaOp,c,t),this.setBlendState(ss)};tt.prototype.setBlendFunctionSeparate=function(c,t,e,s){let i=this.blendState;ss.copy(i),ss.setColorBlend(i.colorOp,c,t),ss.setAlphaBlend(i.alphaOp,e,s),this.setBlendState(ss)};tt.prototype.setBlendEquation=function(c){let t=this.blendState;ss.copy(t),ss.setColorBlend(c,t.colorSrcFactor,t.colorDstFactor),ss.setAlphaBlend(c,t.alphaSrcFactor,t.alphaDstFactor),this.setBlendState(ss)};tt.prototype.setBlendEquationSeparate=function(c,t){let e=this.blendState;ss.copy(e),ss.setColorBlend(c,e.colorSrcFactor,e.colorDstFactor),ss.setAlphaBlend(t,e.alphaSrcFactor,e.alphaDstFactor),this.setBlendState(ss)};tt.prototype.setColorWrite=function(c,t,e,s){let i=this.blendState;ss.copy(i),ss.setColorWrite(c,t,e,s),this.setBlendState(ss)};tt.prototype.getBlending=function(){return this.blendState.blend};tt.prototype.setBlending=function(c){ss.copy(this.blendState),ss.blend=c,this.setBlendState(ss)};tt.prototype.setDepthWrite=function(c){Ol.copy(this.depthState),Ol.write=c,this.setDepthState(Ol)};tt.prototype.setDepthFunc=function(c){Ol.copy(this.depthState),Ol.func=c,this.setDepthState(Ol)};tt.prototype.setDepthTest=function(c){Ol.copy(this.depthState),Ol.test=c,this.setDepthState(Ol)};tt.prototype.getCullMode=function(){return this.cullMode};var T$=fl,y$=ul,E$=Xa,A$=new Proxy({},{get(c,t){return ne.get(ys().graphicsDevice,fe).get(t)},set(c,t,e){return ne.get(ys().graphicsDevice,fe).set(t,e),!0}});Object.defineProperty(Bt.prototype,"defaultMaterial",{get:function(){return ra(ys().graphicsDevice)}});Object.defineProperty(Bt.prototype,"fogColor",{set:function(c){this.fog.color=c},get:function(){return this.fog.color}});Object.defineProperty(Bt.prototype,"fogEnd",{set:function(c){this.fog.end=c},get:function(){return this.fog.end}});Object.defineProperty(Bt.prototype,"fogStart",{set:function(c){this.fog.start=c},get:function(){return this.fog.start}});Object.defineProperty(Bt.prototype,"fogDensity",{set:function(c){this.fog.density=c},get:function(){return this.fog.density}});Object.defineProperty(Bt.prototype,"toneMapping",{set:function(c){},get:function(){}});Object.defineProperty(Bt.prototype,"gammaCorrection",{set:function(c){},get:function(){}});Object.defineProperty(Bt.prototype,"rendering",{set:function(c){},get:function(){}});Object.defineProperty(ol.prototype,"_meshInstances",{get:function(){return null}});Object.defineProperty(Bt.prototype,"drawCalls",{get:function(){return null}});["128","64","32","16","8","4"].forEach((c,t)=>{Object.defineProperty(Bt.prototype,`skyboxPrefiltered${c}`,{get:function(){return this._prefilteredCubemaps[t]},set:function(e){this._prefilteredCubemaps[t]=e,this.updateShaders=!0}})});Object.defineProperty(Bt.prototype,"models",{get:function(){return this._models||(this._models=[]),this._models}});function hi(c,t,e=""){Object.defineProperty(c.prototype,t,{set:function(s){},get:function(){}})}hi(Dt,"renderTarget");hi(Dt,"onPreCull");hi(Dt,"onPreRender");hi(Dt,"onPreRenderOpaque");hi(Dt,"onPreRenderTransparent");hi(Dt,"onPostCull");hi(Dt,"onPostRender");hi(Dt,"onPostRenderOpaque");hi(Dt,"onPostRenderTransparent");hi(Dt,"onDrawCall");hi(Dt,"layerReference");hi(ar,"onPreCull","Use Scene#EVENT_PRECULL event instead.");hi(ar,"onPostCull","Use Scene#EVENT_POSTCULL event instead.");hi(ar,"onPreRender","Use Scene#EVENT_PRERENDER event instead.");hi(ar,"onPostRender","Use Scene#EVENT_POSTRENDER event instead.");hi(ar,"onPreRenderLayer","Use Scene#EVENT_PRERENDER_LAYER event instead.");hi(ar,"onPostRenderLayer","Use Scene#EVENT_POSTRENDER_LAYER event instead.");Bc.prototype.renderComposition=function(c){ys().renderComposition(c)};we.prototype.syncAabb=function(){};Ko.prototype.getTarget=function(c){return this.targets[c]};Pe.prototype.getChildren=function(){return this.children};Pe.prototype.getName=function(){return this.name};Pe.prototype.getPath=function(){return this.path};Pe.prototype.getRoot=function(){return this.root};Pe.prototype.getParent=function(){return this.parent};Pe.prototype.setName=function(c){this.name=c};Object.defineProperty(Us.prototype,"shader",{set:function(c){},get:function(){return null}});Object.defineProperty(Us.prototype,"blend",{set:function(c){this.blendState.blend=c},get:function(){return this.blendState.blend}});Object.defineProperty(it.prototype,"shininess",{get:function(){return this.gloss*100},set:function(c){this.gloss=c*.01}});Object.defineProperty(it.prototype,"useGammaTonemap",{get:function(){return this.useTonemap},set:function(c){this.useTonemap=c}});Object.defineProperty(it.prototype,"anisotropy",{get:function(){let c=Math.sign(Math.cos(this.anisotropyRotation*R.DEG_TO_RAD*2));return this.anisotropyIntensity*c},set:function(c){this.anisotropyIntensity=Math.abs(c),c>=0?this.anisotropyRotation=0:this.anisotropyRotation=90}});function lo(c,t){Object.defineProperty(it.prototype,t,{get:function(){return this[c]},set:function(e){this[c]=e}})}function wA(c){Object.defineProperty(it.prototype,c,{get:function(){return!0},set:function(t){}})}wA("sheenTint");wA("diffuseTint");wA("emissiveTint");wA("ambientTint");lo("specularTint","specularMapTint");lo("aoVertexColor","aoMapVertexColor");lo("diffuseVertexColor","diffuseMapVertexColor");lo("specularVertexColor","specularMapVertexColor");lo("emissiveVertexColor","emissiveMapVertexColor");lo("metalnessVertexColor","metalnessMapVertexColor");lo("glossVertexColor","glossMapVertexColor");lo("opacityVertexColor","opacityMapVertexColor");lo("lightVertexColor","lightMapVertexColor");lo("sheenGloss","sheenGlossiess");lo("clearCoatGloss","clearCostGlossiness");function ZG(c,t){c!=="pass"&&Object.defineProperty(tr.prototype,c,{get:function(){return this.litOptions[t||c]},set:function(e){this.litOptions[t||c]=e}})}ZG("refraction","useRefraction");var C$=new Xa,$G=Object.getOwnPropertyNames(C$);for(let c in $G)ZG($G[c]);ha.prototype.getAssetById=function(c){return this.get(c)};Object.defineProperty(Es.prototype,"ray",{get:function(){return this._rayLocal}});Object.defineProperty(Es.prototype,"position",{get:function(){return this._localPosition}});Object.defineProperty(Es.prototype,"rotation",{get:function(){return this._localRotation}});var P$="keydown",w$="keyup",I$="mousedown",R$="mousemove",b$="mouseup",D$="mousewheel",L$="touchstart",M$="touchend",O$="touchmove",F$="touchcancel",N$="gamepadconnected",B$="gamepaddisconnected",U$="select",k$="selectstart",z$="selectend";Object.defineProperty(J_.prototype,"wheel",{get:function(){return this.wheelDelta*-2}});Object.defineProperty(za.prototype,"wheel",{get:function(){return this.wheelDelta*-2}});var G$=Sl,V$=Ui,H$=tn,W$=1,X$=2,Y$=4,K$=1,j$=2,q$=3,$$=4,Z$=5;Pi.prototype.isFullscreen=function(){return!!document.fullscreenElement};Pi.prototype.enableFullscreen=function(c,t,e){c=c||this.graphicsDevice.canvas;let s=function(){t(),document.removeEventListener("fullscreenchange",s)},i=function(){e(),document.removeEventListener("fullscreenerror",i)};t&&document.addEventListener("fullscreenchange",s,!1),e&&document.addEventListener("fullscreenerror",i,!1),c.requestFullscreen?c.requestFullscreen(Element.ALLOW_KEYBOARD_INPUT):e()};Pi.prototype.disableFullscreen=function(c){let t=function(){c(),document.removeEventListener("fullscreenchange",t)};c&&document.addEventListener("fullscreenchange",t,!1),document.exitFullscreen()};Pi.prototype.getSceneUrl=function(c){let t=this.scenes.find(c);return t?t.url:null};Pi.prototype.loadScene=function(c,t){this.scenes.loadScene(c,t)};Pi.prototype.loadSceneHierarchy=function(c,t){this.scenes.loadSceneHierarchy(c,t)};Pi.prototype.loadSceneSettings=function(c,t){this.scenes.loadSceneSettings(c,t)};Tl.prototype.setVisible=function(c){this.enabled=c};Object.defineProperty(Js.prototype,"bodyType",{get:function(){return this.type},set:function(c){this.type=c}});Js.prototype.syncBodyToEntity=function(){this._updateDynamic()};Al.prototype.setGravity=function(){arguments.length===1?this.gravity.copy(arguments[0]):this.gravity.set(arguments[0],arguments[1],arguments[2])};var IA=class{constructor(t){this._frameIndex=0,this._frameTimings=[],this._timings=[],this._prevTimings=[],this.unitsName="ms",this.decimalPlaces=1,this.enabled=!0,t.on("frameupdate",this.begin.bind(this,"update")),t.on("framerender",this.mark.bind(this,"render")),t.on("frameend",this.mark.bind(this,"other"))}begin(t){if(!this.enabled)return;this._frameIndex0){let s=this._frameTimings[this._frameIndex-1];s[1]=e-s[1]}else if(this._timings.length>0){let s=this._timings[this._timings.length-1];s[1]=e-s[1]}if(this._frameIndex>=this._frameTimings.length)this._frameTimings.push([t,e]);else{let s=this._frameTimings[this._frameIndex];s[0]=t,s[1]=e}this._frameIndex++}get timings(){return this._timings.slice(0,-1).map(t=>t[1])}};var RA=class{constructor(t){this.device=t,t.gpuProfiler&&(t.gpuProfiler.enabled=!0),this.enabled=!0,this.unitsName="ms",this.decimalPlaces=1,this._timings=[]}get timings(){return this._timings[0]=this.device.gpuProfiler?._frameTime??0,this._timings}};var eg=class{constructor(t,e,s,i,r){this.app=t,this.values=[],this.statNames=e,this.unitsName=i,this.decimalPlaces=s,this.multiplier=r||1;let a=(o,l)=>o.split(".").reduce((h,f)=>h?h instanceof Map?h.get(f):h[f]:null,l||this);t.on("frameupdate",o=>{for(let l=0;li+r,0);if(this.avgTotal+=s,this.avgTimer+=t,this.avgCount++,this.maxValue=Math.max(this.maxValue,s),this.avgTimer>this.textRefreshRate&&(this.timingText=(this.avgTotal/this.avgCount).toFixed(this.timer.decimalPlaces),this.maxText=this.maxValue.toFixed(this.timer.decimalPlaces),this.avgTimer=0,this.avgTotal=0,this.avgCount=0,this.maxValue=0),this.enabled){let i=1.5*this.watermark;if(this.sample[0]=Math.floor(s/i*255),this.sample[1]=0,this.sample[2]=0,this.sample[3]=this.watermark/i*255,this.yOffset>=this.texture.height)return;let r=this.texture.lock();if(this.needsClear){let a=this.yOffset*this.texture.width*4;r.fill(0,a,a+this.texture.width*4),this.needsClear=!1}r.set(this.sample,(this.cursor+this.yOffset*this.texture.width)*4),this.texture.unlock(),this.cursor++,this.cursor===this.texture.width&&(this.cursor=0)}}render(t,e,s,i,r){t.quad(e+i,s,-i,r,this.enabled?this.cursor:0,this.enabled?.5+this.yOffset:this.texture.height-1,-i,0,this.texture,this.graphType)}};var bA=class{constructor(t,e){let s=p=>{p.font='10px "Lucida Console", Monaco, monospace',p.textAlign="left",p.textBaseline="alphabetic"},i=p=>p==="."||p.length===1&&p.charCodeAt(0)>=48&&p.charCodeAt(0)<=57,r=document.createElement("canvas"),a=r.getContext("2d",{alpha:!0});s(a);let o=new Map,l=5,h=512,f=l,u=l;e.forEach(p=>{let m=a.measureText(p),_=Math.ceil(-m.actualBoundingBoxLeft),S=Math.ceil(m.actualBoundingBoxRight),g=Math.ceil(m.actualBoundingBoxAscent),T=Math.ceil(m.actualBoundingBoxDescent),C=_+S,v=g+T;f+C+l>=h&&(f=l,u+=16),o.set(p,{l:_,r:S,a:g,d:T,w:C,h:v,x:f,y:u}),f+=C+l}),r.width=512,r.height=R.nextPowerOfTwo(u+16+l),s(a),a.fillStyle="rgb(0, 0, 0)",a.fillRect(0,0,r.width,r.height),o.forEach((p,m)=>{a.fillStyle=i(m)?"rgb(255, 240, 100)":"rgb(150, 220, 230)",a.fillText(m,p.x-p.l,p.y+p.a)}),this.placements=o;let d=a.getImageData(0,0,r.width,r.height).data;for(let p=0;p 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; var graphTex_sampler : sampler; var wordsTex : texture_2d; 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=this.maxQuads)return;let u=this.targetSize.width,d=this.targetSize.height,p=t/u,m=e/d,_=(t+s)/u,S=(e+i)/d,g=h.width,T=h.height,C=r/g,v=a/T,E=(r+(o??s))/g,y=(a+(l??i))/T;this.data.set([p,m,f,C,v,0,0,_,m,f,E,v,1,0,_,S,f,E,y,1,1,p,S,f,C,y,0,1],28*this.quads),this.quads++,this.prim.count+=6}startFrame(){this.quads=0,this.prim.count=0,this.targetSize.width=this.device.canvas.scrollWidth,this.targetSize.height=this.device.canvas.scrollHeight}render(t,e,s,i,r,a){this.buffer.setData(this.data.buffer),this.uniforms.clr.set(r,0),this.material.setParameter("clr",this.uniforms.clr),this.material.setParameter("graphTex",s),this.material.setParameter("wordsTex",i),t.drawMeshInstance(this.meshInstance,e)}};var s9={animUpdate:"anim",physicsTime:"physics",renderTime:"render",gsplatSort:"gsplatSort"},i9=new Set(["physicsTime","animUpdate","gsplatSort"]),px=class px{constructor(t,e=px.getDefaultOptions()){let s=t.graphicsDevice;this.graphRows=new Map,this.freeRows=[],this.nextRowIndex=0,this.sizes=e.sizes,this.initGraphs(t,s,e);let i=new Set(["","ms","0","1","2","3","4","5","6","7","8","9",".","-"," "].concat(this.graphs.map(h=>h.name)).concat(e.stats?e.stats.map(h=>h.unitsName):[]).filter(h=>!!h));for(let h=97;h<=122;h++)i.add(String.fromCharCode(h));for(let h=65;h<=90;h++)i.add(String.fromCharCode(h));this.wordAtlas=new bA(s,i),this._activeSizeIndex=e.startSizeIndex;let r=e.gpuTimingMinSize??1,a=e.cpuTimingMinSize??1,o=e.vramTimingMinSize??1;if(r{this.opacity=1}),l.addEventListener("mouseleave",h=>{this.opacity=this._activeSizeIndex>0?.85:.7}),l.addEventListener("click",h=>{h.preventDefault(),this._enabled&&(this.activeSizeIndex=(this.activeSizeIndex+1)%this.sizes.length,this.resize(this.sizes[this.activeSizeIndex].width,this.sizes[this.activeSizeIndex].height,this.sizes[this.activeSizeIndex].graphs))}),s.on("resizecanvas",this.updateDiv,this),s.on("losecontext",this.loseContext,this),t.on("postrender",this.postRender,this),this.app=t,this.drawLayer=t.scene.layers.getLayerById(Va),this.device=s,this.render2d=new DA(s),this.div=l,this.width=0,this.height=0,this.gspacing=2,this.clr=[1,1,1,e.startSizeIndex>0?.85:.7],this._enabled=!0,this.gpuTimingMinSize=r,this.gpuPassGraphs=new Map,this.cpuTimingMinSize=a,this.cpuGraphs=new Map,this.vramTimingMinSize=o,this.vramGraphs=new Map,this.frameIndex=0,this.textRefreshRate=e.textRefreshRate,this.activeSizeIndex=this._activeSizeIndex}destroy(){this.device.off("resizecanvas",this.updateDiv,this),this.device.off("losecontext",this.loseContext,this),this.app.off("postrender",this.postRender,this),this.graphs.forEach(t=>t.destroy()),this.gpuPassGraphs.clear(),this.cpuGraphs.clear(),this.vramGraphs.clear(),this.wordAtlas.destroy(),this.texture.destroy(),this.div.remove()}static getDefaultOptions(t=[]){let e={sizes:[{width:100,height:16,spacing:0,graphs:!1},{width:128,height:32,spacing:2,graphs:!0},{width:256,height:64,spacing:2,graphs:!0}],startSizeIndex:0,textRefreshRate:500,cpu:{enabled:!0,watermark:33},gpu:{enabled:!0,watermark:33},stats:[{name:"Frame",stats:["frame.ms"],decimalPlaces:1,unitsName:"ms",watermark:33},{name:"DrawCalls",stats:["drawCalls.total"],watermark:1e3},{name:"VRAM",stats:["vram.totalUsed"],decimalPlaces:1,multiplier:95367431640625e-20,unitsName:"MB",watermark:1024}],gpuTimingMinSize:1,cpuTimingMinSize:1,vramTimingMinSize:1};if(t.length>0){let s=e.stats.findIndex(a=>a.name==="Frame"),i=s!==-1?s+1:e.stats.length,r=t.flatMap(a=>px.statPresets[a]??[]).reverse();e.stats.splice(i,0,...r)}return e}set activeSizeIndex(t){this._activeSizeIndex=t,this.gspacing=this.sizes[t].spacing,this.resize(this.sizes[t].width,this.sizes[t].height,this.sizes[t].graphs),this.opacity=t>0?.85:.7,t{if(i.name==="VRAM"){let r=new eg(t,i.stats,i.decimalPlaces,i.unitsName,i.multiplier),a=new Lh(i.name,t,i.watermark,s.textRefreshRate,r);this.graphs.push(a)}}),s.cpu.enabled){let i=new IA(t),r=new Lh("CPU",t,s.cpu.watermark,s.textRefreshRate,i);r.graphType=.66,this.graphs.push(r)}if(s.gpu.enabled){let i=new RA(e),r=new Lh("GPU",t,s.gpu.watermark,s.textRefreshRate,i);r.graphType=.33,this.graphs.push(r)}s.stats&&s.stats.forEach(i=>{if(i.name==="VRAM")return;let r=new eg(t,i.stats,i.decimalPlaces,i.unitsName,i.multiplier),a=new Lh(i.name,t,i.watermark,s.textRefreshRate,r);this.graphs.push(a)}),this.texture=new Z(e,{name:"mini-stats-graph-texture",width:1,height:1,mipmaps:!1,minFilter:0,magFilter:0,addressU:0,addressV:0}),this.graphs.forEach(i=>{i.texture=this.texture,this.allocateRow(i)})}render(){let t=this.graphs,e=this.wordAtlas,s=this.render2d,i=this.width,r=this.height,a=this.gspacing;s.startFrame();for(let o=0;o0){f+=5,f+=e.render(s,"max",f,h),f+=5;let d=l.maxText;for(let p=0;pt.loseContext())}updateSubStats(t,e,s,i,r){let a=[];for(let[h,f]of t)(s instanceof Map?s.get(h)||0:s[h]||0)>0?f.lastNonZeroFrame=this.frameIndex:r>0&&i==="gpu"&&this.frameIndex-f.lastNonZeroFrame>r&&a.push(h);for(let h of a){let f=t.get(h);if(f){let u=this.graphs.indexOf(f.graph);u!==-1&&this.graphs.splice(u,1),this.freeRow(f.graph),f.graph.destroy(),t.delete(h)}}let o=s instanceof Map?s:Object.entries(s),l=this.graphs.find(h=>h.name===e);for(let[h,f]of o)if(!t.has(h)){if((i==="gpu"||i9.has(h))&&f===0)continue;let d=h;i==="frame"&&(d=s9[h]||h);let p=` ${d}`,m=l?.watermark??10,_=1,S=i==="vram"?"MB":"ms",g=i==="vram"?1/(1024*1024):1,T=`${i}.${h}`,C=new eg(this.app,[T],_,S,g),v=new Lh(p,this.app,m,this.textRefreshRate,C);i==="gpu"?v.graphType=.33:i==="frame"&&(v.graphType=.66),v.texture=this.texture,this.allocateRow(v);let E=this.sizes[this._activeSizeIndex];v.enabled=E.graphs;let y=this.graphs.findIndex(A=>A.name===e);y===-1&&(y=0);let P=y;for(let A=y-1;A>=0&&this.graphs[A].name.startsWith(" ");A--)P=A;this.graphs.splice(P,0,v),t.set(h,{graph:v,lastNonZeroFrame:f>0?this.frameIndex:this.frameIndex-r-1})}if(l)for(let h of t.values())h.graph.watermark=l.watermark}allocateRow(t){let e;return this.freeRows.length>0?e=this.freeRows.pop():(e=this.nextRowIndex++,this.ensureTextureHeight(this.nextRowIndex)),this.graphRows.set(t,e),t.yOffset=e,t.needsClear=!0,e}freeRow(t){let e=this.graphRows.get(t);e!==void 0&&(this.freeRows.push(e),this.graphRows.delete(t))}clearSubGraphs(t,e,s){for(let i of t.values()){let r=this.graphs.indexOf(i.graph);r!==-1&&this.graphs.splice(r,1),this.freeRow(i.graph),i.graph.destroy()}if(t.clear(),e){let i=this.graphs.find(r=>r.name===e);i&&(i.graphType=s)}}ensureTextureHeight(t){let e=this.sizes[this.sizes.length-1].width,s=R.nextPowerOfTwo(e),i=R.nextPowerOfTwo(t);i>this.texture.height&&this.texture.resize(s,i)}postRender(){if(this._enabled){if(this.render(),this._activeSizeIndex>=this.gpuTimingMinSize){let t=this.app.stats.gpu;t&&this.updateSubStats(this.gpuPassGraphs,"GPU",t,"gpu",240)}if(this._activeSizeIndex>=this.cpuTimingMinSize){let t={scriptUpdate:this.app.stats.frame.scriptUpdate,scriptPostUpdate:this.app.stats.frame.scriptPostUpdate,animUpdate:this.app.stats.frame.animUpdate,physicsTime:this.app.stats.frame.physicsTime,renderTime:this.app.stats.frame.renderTime,gsplatSort:this.app.stats.frame.gsplatSort};this.updateSubStats(this.cpuGraphs,"CPU",t,"frame",240)}if(this._activeSizeIndex>=this.vramTimingMinSize){let t=this.app.stats.vram,e={tex:t.tex,geom:t.geom};this.device.isWebGPU&&(e.buffers=t.buffers),this.updateSubStats(this.vramGraphs,"VRAM",e,"vram",0)}}this.frameIndex++}};n(px,"statPresets",{gsplats:[{name:"GSplats",stats:["frame.gsplats"],decimalPlaces:3,multiplier:1/1e6,unitsName:"M",watermark:10}],gsplatsCopy:[{name:"GsplatsCopy",stats:["frame.gsplatBufferCopy"],decimalPlaces:1,multiplier:1,unitsName:"%",watermark:100}]});var LA=px;var r9=` varying vec2 vUv0; uniform vec2 uOffset; uniform float uSrcMultiplier; 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; 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<{i.material instanceof it&&(i.material.onUpdateShader=null,i.deleteParameter("material_emissive"))})}removeAllEntities(){this.renderingLayer.clearMeshInstances()}blendOutlines(){let t=this.app.graphicsDevice;t.scope.resolve("source").setValue(this.rt.colorBuffer),t.setDrawStates(this.blendState),this.quadRenderer.render()}onPostRender(){let t=this.app.graphicsDevice,e=t.scope.resolve("uOffset"),s=t.scope.resolve("source"),i=t.scope.resolve("uSrcMultiplier"),{rt:r,tempRt:a,shaderExtend:o}=this,{width:l,height:h}=r;tg[0]=1/l/2,tg[1]=0,e.setValue(tg),s.setValue(r.colorBuffer),i.setValue(0),Qt(t,a,o),tg[0]=0,tg[1]=1/h/2,e.setValue(tg),s.setValue(a.colorBuffer),i.setValue(1),Qt(t,r,o)}createRenderTarget(t,e,s,i){let r=new Z(this.app.graphicsDevice,{name:t,width:e,height:s,format:st,mipmaps:!1,addressU:1,addressV:1,minFilter:5,magFilter:1});return new me({colorBuffer:r,depth:i,flipY:this.app.graphicsDevice.isWebGPU})}updateRenderTarget(t){let e=t.renderTarget?.width??this.app.graphicsDevice.width,s=t.renderTarget?.height??this.app.graphicsDevice.height,i=this.outlineCameraEntity.camera;(!i.renderTarget||i.renderTarget.width!==e||i.renderTarget.height!==s)&&(this.rt.resize(e,s),this.tempRt.resize(e,s))}frameUpdate(t,e,s){let i=t.camera;this.updateRenderTarget(i);let r=this.app.scene.on("prerender:layer",(o,l,h)=>{i===o&&h===s&&l===e&&(this.blendOutlines(),r.off())});this.outlineCameraEntity.setLocalPosition(t.getPosition()),this.outlineCameraEntity.setLocalRotation(t.getRotation());let a=this.outlineCameraEntity.camera;a.projection=i.projection,a.horizontalFov=i.horizontalFov,a.fov=i.fov,a.orthoHeight=i.orthoHeight,a.nearClip=i.nearClip,a.farClip=i.farClip}};var sg=class{constructor(){}textureToCanvas(t,e={}){let s=t.getSource();if(typeof HTMLImageElement<"u"&&s instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&s instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&s instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&s instanceof ImageBitmap){let{width:u,height:d}=this.calcTextureSize(s.width,s.height,e.maxTextureSize),p=document.createElement("canvas");p.width=u,p.height=d;let m=p.getContext("2d");if(m===null)return Promise.resolve(void 0);if(m.drawImage(s,0,0,p.width,p.height),e.color){let{r:_,g:S,b:g}=e.color,T=m.getImageData(0,0,u,d),C=T.data;for(let v=0;v{l.destroy(),h.destroy();let d=new Uint8ClampedArray(r*a*4);d.set(u);let p=new ImageData(d,r,a),m=document.createElement("canvas");m.width=r,m.height=a;let _=m.getContext("2d");return _?(_.putImageData(p,0,0),Promise.resolve(m)):Promise.resolve(void 0)})}calcTextureSize(t,e,s){if(s){let i=Math.min(s/Math.max(t,e),1);t=Math.round(t*i),e=Math.round(e*i)}return{width:t,height:e}}};var wi=Uint8Array,Or=Uint16Array,kb=Int32Array,zb=new wi([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Gb=new wi([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),rV=new wi([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),hV=function(c,t){for(var e=new Or(31),s=0;s<31;++s)e[s]=t+=1<>1|(ht&21845)<<1,Fl=(Fl&52428)>>2|(Fl&13107)<<2,Fl=(Fl&61680)>>4|(Fl&3855)<<4,Nb[ht]=((Fl&65280)>>8|(Fl&255)<<8)>>1;var Fl,ht,gx=(function(c,t,e){for(var s=c.length,i=0,r=new Or(t);i>l]=h}else for(o=new Or(s),i=0;i>15-c[i]);return o}),Vu=new wi(288);for(ht=0;ht<144;++ht)Vu[ht]=8;var ht;for(ht=144;ht<256;++ht)Vu[ht]=9;var ht;for(ht=256;ht<280;++ht)Vu[ht]=7;var ht;for(ht=280;ht<288;++ht)Vu[ht]=8;var ht,FA=new wi(32);for(ht=0;ht<32;++ht)FA[ht]=5;var ht,n9=gx(Vu,9,0);var l9=gx(FA,5,0);var dV=function(c){return(c+7)/8|0},pV=function(c,t,e){return(t==null||t<0)&&(t=0),(e==null||e>c.length)&&(e=c.length),new wi(c.subarray(t,e))};var c9=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],BA=function(c,t,e){var s=new Error(t||c9[c]);if(s.code=c,Error.captureStackTrace&&Error.captureStackTrace(s,BA),!e)throw s;return s};var Nl=function(c,t,e){e<<=t&7;var s=t/8|0;c[s]|=e,c[s+1]|=e>>8},mx=function(c,t,e){e<<=t&7;var s=t/8|0;c[s]|=e,c[s+1]|=e>>8,c[s+2]|=e>>16},Ob=function(c,t){for(var e=[],s=0;sd&&(d=r[s].s);var p=new Or(d+1),m=Bb(e[f-1],p,0);if(m>t){var s=0,_=0,S=m-t,g=1<t)_+=g-(1<>=S;_>0;){var C=r[s].s;p[C]=0&&_;--s){var v=r[s].s;p[v]==t&&(--p[v],++_)}m=t}return{t:new wi(p),l:m}},Bb=function(c,t,e){return c.s==-1?Math.max(Bb(c.l,t,e+1),Bb(c.r,t,e+1)):t[c.s]=e},oV=function(c){for(var t=c.length;t&&!c[--t];);for(var e=new Or(++t),s=0,i=c[0],r=1,a=function(l){e[s++]=l},o=1;o<=t;++o)if(c[o]==i&&o!=t)++r;else{if(!i&&r>2){for(;r>138;r-=138)a(32754);r>2&&(a(r>10?r-11<<5|28690:r-3<<5|12305),r=0)}else if(r>3){for(a(i),--r;r>6;r-=6)a(8304);r>2&&(a(r-3<<5|8208),r=0)}for(;r--;)a(i);r=1,i=c[o]}return{c:e.subarray(0,s),n:t}},_x=function(c,t){for(var e=0,s=0;s>8,c[i+2]=c[i]^255,c[i+3]=c[i+1]^255;for(var r=0;r4&&!I[rV[O-1]];--O);var G=h+5<<3,M=_x(i,Vu)+_x(r,FA)+a,H=_x(i,d)+_x(r,_)+a+14+3*O+_x(P,I)+2*P[16]+3*P[17]+7*P[18];if(l>=0&&G<=M&&G<=H)return mV(t,f,c.subarray(l,l+h));var U,L,b,N;if(Nl(t,f,1+(H15&&(Nl(t,f,q[A]>>5&127),f+=q[A]>>12)}}else U=n9,L=Vu,b=l9,N=FA;for(var A=0;A255){var re=te>>18&31;mx(t,f,U[re+257]),f+=L[re+257],re>7&&(Nl(t,f,te>>23&31),f+=zb[re]);var j=te&31;mx(t,f,b[j]),f+=N[j],j>3&&(mx(t,f,te>>5&8191),f+=Gb[j])}else mx(t,f,U[te]),f+=L[te]}return mx(t,f,U[256]),f+L[256]},h9=new kb([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),_V=new wi(0),f9=function(c,t,e,s,i,r){var a=r.z||c.length,o=new wi(s+a+5*(1+Math.ceil(a/7e3))+i),l=o.subarray(s,o.length-i),h=r.l,f=(r.r||0)&7;if(t){f&&(l[0]=r.r>>3);for(var u=h9[t-1],d=u>>13,p=u&8191,m=(1<7e3||I>24576)&&(U>423||!h)){f=nV(c,l,0,v,E,y,A,I,O,w-O,f),I=P=A=0,O=w;for(var L=0;L<286;++L)E[L]=0;for(var L=0;L<30;++L)y[L]=0}var b=2,N=0,k=p,z=M-H&32767;if(U>2&&G==C(w-z))for(var V=Math.min(d,U)-1,q=Math.min(32767,w),re=Math.min(258,U);z<=q&&--k&&M!=H;){if(c[w+b]==c[w+b-z]){for(var te=0;teb){if(b=te,N=z,te>V)break;for(var j=Math.min(z,te-2),oe=0,L=0;Loe&&(oe=ot,H=be)}}}M=H,H=_[M],z+=M-H&32767}if(N){v[I++]=268435456|Fb[b]<<18|aV[N];var Ve=Fb[b]&31,Lt=aV[N]&31;A+=zb[Ve]+Gb[Lt],++E[257+Ve],++y[Lt],D=w+b,++P}else v[I++]=c[w],++E[c[w]]}}for(w=Math.max(w,D);w=a&&(l[f/8|0]=h,Vs=a),f=mV(l,f+1,c.subarray(w,Vs))}r.i=a}return pV(o,0,s+dV(f)+i)},u9=(function(){for(var c=new Int32Array(256),t=0;t<256;++t){for(var e=t,s=9;--s;)e=(e&1&&-306674912)^e>>>1;c[t]=e}return c})(),d9=function(){var c=-1;return{p:function(t){for(var e=c,s=0;s>>8;c=e},d:function(){return~c}}};var p9=function(c,t,e,s,i){if(!i&&(i={l:1},t.dictionary)){var r=t.dictionary.subarray(-32768),a=new wi(r.length+c.length);a.set(r),a.set(c,r.length),c=a,i.w=r.length}return f9(c,t.level==null?6:t.level,t.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(c.length)))*1.5):20:12+t.mem,e,s,i)},gV=function(c,t){var e={};for(var s in c)e[s]=c[s];for(var s in t)e[s]=t[s];return e};var fi=function(c,t,e){for(;e;++t)c[t]=e,e>>>=8};function m9(c,t){return p9(c,t||{},0,0)}var SV=function(c,t,e,s){for(var i in c){var r=c[i],a=t+i,o=s;Array.isArray(r)&&(o=gV(s,r[1]),r=r[0]),ArrayBuffer.isView(r)?e[a]=[r,o]:(e[a+="/"]=[new wi(0),o],SV(r,a,e,s))}},lV=typeof TextEncoder<"u"&&new TextEncoder,_9=typeof TextDecoder<"u"&&new TextDecoder,g9=0;try{_9.decode(_V,{stream:!0}),g9=1}catch{}function NA(c,t){if(t){for(var e=new wi(c.length),s=0;s>1)),a=0,o=function(f){r[a++]=f},s=0;sr.length){var l=new wi(a+8+(i-s<<1));l.set(r),r=l}var h=c.charCodeAt(s);h<128||t?o(h):h<2048?(o(192|h>>6),o(128|h&63)):h>55295&&h<57344?(h=65536+(h&1047552)|c.charCodeAt(++s)&1023,o(240|h>>18),o(128|h>>12&63),o(128|h>>6&63),o(128|h&63)):(o(224|h>>12),o(128|h>>6&63),o(128|h&63))}return pV(r,0,a)}var Ub=function(c){var t=0;if(c)for(var e in c){var s=c[e].length;s>65535&&BA(9),t+=s+4}return t},cV=function(c,t,e,s,i,r,a,o){var l=s.length,h=e.extra,f=o&&o.length,u=Ub(h);fi(c,t,a!=null?33639248:67324752),t+=4,a!=null&&(c[t++]=20,c[t++]=e.os),c[t]=20,t+=2,c[t++]=e.flag<<1|(r<0&&8),c[t++]=i&&8,c[t++]=e.compression&255,c[t++]=e.compression>>8;var d=new Date(e.mtime==null?Date.now():e.mtime),p=d.getFullYear()-1980;if((p<0||p>119)&&BA(10),fi(c,t,p<<25|d.getMonth()+1<<21|d.getDate()<<16|d.getHours()<<11|d.getMinutes()<<5|d.getSeconds()>>1),t+=4,r!=-1&&(fi(c,t,e.crc),fi(c,t+4,r<0?-r-2:r),fi(c,t+8,e.size)),fi(c,t+12,l),fi(c,t+14,u),t+=16,a!=null&&(fi(c,t,f),fi(c,t+6,e.attrs),fi(c,t+10,a),t+=14),c.set(s,t),t+=l,u)for(var m in h){var _=h[m],S=_.length;fi(c,t,+m),fi(c,t+2,S),c.set(_,t+4),t+=4+S}return f&&(c.set(o,t),t+=f),t},S9=function(c,t,e,s,i){fi(c,t,101010256),fi(c,t+8,e),fi(c,t+10,e),fi(c,t+12,s),fi(c,t+16,i)};function xV(c,t){t||(t={});var e={},s=[];SV(c,"",e,t);var i=0,r=0;for(var a in e){var o=e[a],l=o[0],h=o[1],f=h.level==0?0:8,u=NA(a),d=u.length,p=h.comment,m=p&&NA(p),_=m&&m.length,S=Ub(h.extra);d>65535&&BA(11);var g=f?m9(l,h):l,T=g.length,C=d9();C.p(l),s.push(gV(h,{size:l.length,crc:C.d(),c:g,f:u,m,u:d!=a.length||m&&p.length!=_,o:i,compression:f})),i+=30+d+S+T,r+=76+2*(d+S)+(_||0)+T}for(var v=new wi(r+22),E=i,y=r-i,P=0;P` def "Materials" { ${c.join(` `)} } `,T9=(c,t,e,s,i,r)=>` def "Mesh" { def Mesh "Mesh" { int[] faceVertexCounts = [${c}] int[] faceVertexIndices = [${t}] normal3f[] normals = [${e}] ( interpolation = "vertex" ) point3f[] points = [${s}] texCoord2f[] primvars:st = [${i}] ( interpolation = "vertex" ) texCoord2f[] primvars:st1 = [${r}] ( interpolation = "vertex" ) uniform token subdivisionScheme = "none" } } `,y9=(c,t,e,s)=>` def Xform "${c}" ( prepend references = ${t} ) { matrix4d xformOp:transform = ${e} uniform token[] xformOpOrder = ["xformOp:transform"] rel material:binding = ${s} } `,TV=(c,t,e)=>` ${c} inputs:${t} = ${e}`,UA=class extends sg{constructor(){super(...arguments);n(this,"meshMap");n(this,"materialMap");n(this,"materials");n(this,"textureMap");n(this,"nodeNames");n(this,"files")}init(){this.meshMap=new Map,this.textureMap=new Map,this.materialMap=new Map,this.materials=[],this.files={},this.nodeNames=new Set}done(){this.meshMap=null,this.textureMap=null,this.materialMap=null,this.materials=null,this.files=null,this.nodeNames=null}build(e,s={}){this.init(),this.addFile(null,vV);let i=[];e&&e.findComponents("render").forEach(u=>{i.push(...u.meshInstances)});let r="";i.forEach(f=>{r+=this.buildMeshInstance(f)}),r+=v9(this.materials),this.addFile(null,vV,"",r);let a={maxTextureSize:s.maxTextureSize},o=Array.from(this.textureMap.keys()),l=[];for(let f=0;f_?new Promise(S=>_.toBlob(S,d,1)).then(S=>S.arrayBuffer()):new Promise(S=>S(null)));l.push(m)}return Promise.all(l).then(f=>{f.forEach((d,p)=>{let m=o[p],_=this.getTextureFileIds(m);this.files[_.fileName]=new Uint8Array(d)}),this.alignFiles();let u=xV(this.files,{level:0});return this.done(),u})}alignFiles(){let e=0;for(let s in this.files){let i=this.files[s],r=34+s.length;e+=r;let a=e&63;if(a!==4){let o=64-a,l=new Uint8Array(o);this.files[s]=[i,{extra:{12345:l}}]}e=i.length}}getFileIds(e,s,i,r="usda"){let a=`${e?`${e}/`:""}${s}.${r}`,o=`@./${a}@`;return{name:s,fileName:a,refName:o}}getTextureFileIds(e){return this.getFileIds("texture",`Texture_${e.id}`,"Texture","png")}addFile(e,s,i="",r=""){let a=null;r&&(r=`${x9} ${r}`,a=NA(r));let o=this.getFileIds(e,s,i);return this.files[o.fileName]=a,o.refName}getMaterialRef(e){let s=this.materialMap.get(e);return s||(s=this.buildMaterial(e),this.materialMap.set(e,s)),s}getMeshRef(e){let s=this.meshMap.get(e);return s||(s=this.buildMesh(e),this.meshMap.set(e,s)),s}buildArray2(e){let s=[],i=e.length;for(let r=0;r`<${i}${p}>`,a=(p,m,_,S,g,T,C,v)=>` def Shader "Transform2d_${_}" ( sdrMetadata = { string role = "math" } ) { uniform token info:id = "UsdTransform2d" float2 inputs:in.connect = ${r(`/uvReader_${S}.outputs:result`)} float inputs:rotation = ${C} float2 inputs:scale = (${g.x}, ${g.y}) float2 inputs:translation = (${T.x}, ${T.y}) float2 outputs:result } def Shader "Texture_${p.id}_${_}" { uniform token info:id = "UsdUVTexture" asset inputs:file = @${m.fileName}@ float2 inputs:st.connect = ${r(`/Transform2d_${_}.outputs:result`)} token inputs:wrapS = "repeat" token inputs:wrapT = "repeat" float4 inputs:scale = (${v.r}, ${v.g}, ${v.b}, ${v.a}) float outputs:r float outputs:g float outputs:b float3 outputs:rgb float outputs:a } `,o=[],l=[],h=(p,m,_,S,g,T=!1,C=!1)=>{let v=e[p];if(v){let E=this.getTextureFileIds(v);this.textureMap.set(v,E.refName);let y=e[`${p}Channel`]||"rgb",P=r(`/${E.name}_${g}.outputs:${y}`);o.push(TV(_,`${S}.connect`,P)),T&&e.alphaTest>0;let A=e[`${p}Tiling`],w=e[`${p}Offset`],I=e[`${p}Rotation`],D=e[`${p}Uv`]===1?"st1":"st",O=C&&m?m:F.WHITE;l.push(a(v,E,g,D,A,w,I,O))}else if(m){let E=_==="float"?`${m}`:`(${m.r}, ${m.g}, ${m.b})`;o.push(TV(_,S,E))}};h("diffuseMap",e.diffuse,"color3f","diffuseColor","diffuse",!1,!0),(e.transparent||e.alphaTest>0)&&h("opacityMap",e.opacity,"float","opacity","opacity",!0),h("normalMap",null,"normal3f","normal","normal"),h("emissiveMap",e.emissive,"color3f","emissiveColor","emissive",!1,!0),h("aoMap",null,"float","occlusion","occlusion");let f=e.useMetalness?e.metalness:0;h("metalnessMap",f,"float","metallic","metallic");let u=e.glossInvert?e.gloss:1-e.gloss;h("glossMap",u,"float","roughness","roughness");let d=` def Material "${s}" { def Shader "PreviewSurface" { uniform token info:id = "UsdPreviewSurface" ${o.join(` `)} int inputs:useSpecularWorkflow = 0 token outputs:surface } token outputs:surface.connect = ${r("/PreviewSurface.outputs:surface")} def Shader "uvReader_st" { uniform token info:id = "UsdPrimvarReader_float2" token inputs:varname = "st" float2 inputs:fallback = (0.0, 0.0) float2 outputs:result } def Shader "uvReader_st1" { uniform token info:id = "UsdPrimvarReader_float2" token inputs:varname = "st1" float2 inputs:fallback = (0.0, 0.0) float2 outputs:result } ${l.join(` `)} } `;return this.materials.push(d),r("")}buildMesh(e){let s=[],i=[],r=[],a=[],o=[];e.getVertexStream(ee,s),e.getVertexStream(Ot,r),e.getVertexStream(_t,a),e.getVertexStream(ri,o),e.getIndices(i);let l=i.length||s.length,h=Array(l/3).fill(3).join(", ");if(!i.length)for(let p=0;p{switch(c){case 0:return 5121;case 1:return 5123;case 2:return 5125}return 0},EV=c=>{switch(c){case js:return 5120;case ai:return 5121;case qs:return 5122;case Ri:return 5123;case He:return 5124;case kt:return 5125;case ye:return 5126}return 0},A9=c=>{switch(c){case 1:return"SCALAR";case 2:return"VEC2";case 3:return"VEC3";case 4:return"VEC4"}return 0},C9=c=>{switch(c){case ee:return"POSITION";case Ot:return"NORMAL";case vs:return"TANGENT";case Ct:return"COLOR_0";case $t:return"JOINTS_0";case bs:return"WEIGHTS_0";case _t:return"TEXCOORD_0";case ri:return"TEXCOORD_1";case Ca:return"TEXCOORD_2";case Pa:return"TEXCOORD_3";case wa:return"TEXCOORD_4";case Ia:return"TEXCOORD_5";case Ra:return"TEXCOORD_6";case ba:return"TEXCOORD_7"}return""},AV=function(c){switch(c){case 0:return 9728;case 1:return 9729;case 2:return 9984;case 4:return 9985;case 3:return 9986;case 5:return 9987}return 0},CV=function(c){switch(c){case 1:return 33071;case 2:return 33648;case 0:return 10497}return 0};function P9(c){let e=c.getContext("2d").getImageData(0,0,c.width,c.height).data;for(let s=3;s{e.entities.push(l)});let o=l=>{l.forEach(h=>{let f=h.material;s.indexOf(f)<0&&(e.materials.push(f),PV.forEach(S=>{let g=f[S];g&&a.indexOf(g)<0&&(S!=="normalMap"&&e.compressableTexture.add(g),a.push(g))}));let u=h.node,d=r.find(S=>S.node===u);d||(d={node:u,meshInstances:[]},r.push(d)),d.meshInstances.push(h);let p=h.mesh,m=p.vertexBuffer;i.indexOf(m)<0&&i.unshift(m);let _=p.indexBuffer[0];i.indexOf(_)<0&&i.push(_),p.skin&&e.skins.indexOf(p.skin)<0&&e.skins.push(p.skin)})};return e.entities.forEach(l=>{l.camera&&e.cameras.push(l.camera),l.render&&l.render.enabled&&o(l.render.meshInstances),l.model&&l.model.enabled&&l.model.meshInstances&&o(l.model.meshInstances)}),e}writeBufferViews(t,e){e.bufferViews=[];for(let s of t.buffers)c.writeBufferView(t,e,s)}static writeBufferView(t,e,s){e.buffers=e.buffers??[],e.buffers[0]=e.buffers[0]??{byteLength:0};let i=e.buffers[0];i.byteLength=R.roundUp(i.byteLength,4);let r=i.byteLength,a=(l,h,f,u)=>{let d={buffer:0,byteLength:h,byteOffset:f};return(l===Vb||l===yV)&&(d.target=l),u!==void 0&&(d.byteStride=u),e.bufferViews.push(d)-1},o;if(s instanceof ft){o=s.lock();let l=s.getFormat();if(l.interleaved){let h=a(Vb,o.byteLength,r,l.size);t.bufferViewMap.set(s,[h])}else{let h=[];for(let f of l.elements){let u=a(Vb,f.size*l.vertexCount,r+f.offset,f.size);h.push(u)}t.bufferViewMap.set(s,h)}}else if(s instanceof os){o=s.lock();let l=a(yV,o.byteLength,r);t.bufferViewMap.set(s,[l])}else{o=s;let l=a(void 0,o.byteLength,r);t.bufferViewMap.set(s,[l])}i.byteLength+=o.byteLength}writeCameras(t,e){t.cameras.length>0&&(e.cameras=t.cameras.map(s=>{let i=s.projection,r=s.nearClip,a=s.farClip,o={};if(i===ni)o.type="orthographic",o.orthographic={xmag:1,ymag:1,znear:r,zfar:a};else{let l=s.fov;o.type="perspective",o.perspective={yfov:l*R.DEG_TO_RAD,znear:r,zfar:a}}return o}))}attachTexture(t,e,s,i,r,a){let o=e[r];if(o){let l=t.textures.indexOf(o);l<0,s[i]={index:l};let h=e[`${r}Uv`]??0;h!==0&&(s[i].texCoord=h);let f=e[`${r}Tiling`],u=e[`${r}Offset`],d=e[`${r}Rotation`];(f&&!f.equals(B.ONE)||u&&!u.equals(B.ZERO)||d!==0)&&(s[i].extensions={KHR_texture_transform:{}},a.extensionsUsed=a.extensionsUsed??[],a.extensionsUsed.includes("KHR_texture_transform")||a.extensionsUsed.push("KHR_texture_transform"),a.extensionsRequired=a.extensionsRequired??[],a.extensionsRequired.includes("KHR_texture_transform")||a.extensionsRequired.push("KHR_texture_transform"),f&&!f.equals(B.ONE)&&(s[i].extensions.KHR_texture_transform.scale=[f.x,f.y]),u&&!u.equals(B.ZERO)&&(s[i].extensions.KHR_texture_transform.offset=[u.x,u.y-1+f.y]),d!==0&&(s[i].extensions.KHR_texture_transform.rotation=d*R.DEG_TO_RAD))}}addExtension(t,e,s,i={}){e.extensions=e.extensions||{},e.extensions[s]=i,t.extensionsUsed=t.extensionsUsed??[],t.extensionsUsed.includes(s)||t.extensionsUsed.push(s)}writeStandardMaterial(t,e,s,i){let{diffuse:r,emissive:a,opacity:o,metalness:l,gloss:h,glossInvert:f}=e,u=s.pbrMetallicRoughness,d=e.useLighting?r:a;if(!d.equals(F.WHITE)||o!==1){let{r:_,g:S,b:g}=d.clone().linear();u.baseColorFactor=[_,S,g,o]}e.useMetalness?l!==1&&(u.metallicFactor=l):u.metallicFactor=0;let p=f?h:1-h;if(p!==1&&(u.roughnessFactor=p),this.attachTexture(t,e,u,"baseColorTexture",e.useLighting?"diffuseMap":"emissiveMap",i),this.attachTexture(t,e,u,"metallicRoughnessTexture","metalnessMap",i),e.useLighting&&!a.equals(F.BLACK)){let{r:_,g:S,b:g}=a.clone().linear();s.emissiveFactor=[_,S,g]}if(e.enableGGXSpecular&&(e.anisotropyIntensity!==0||e.anisotropyRotation!==0||e.anisotropyMap)){let _={};e.anisotropyIntensity!==0&&(_.anisotropyStrength=e.anisotropyIntensity),e.anisotropyRotation!==0&&(_.anisotropyRotation=e.anisotropyRotation*R.DEG_TO_RAD),this.attachTexture(t,e,_,"anisotropyTexture","anisotropyMap",i),Object.keys(_).length>0&&this.addExtension(i,s,"KHR_materials_anisotropy",_)}if(e.clearCoat>0){let _={clearcoatFactor:Math.min(e.clearCoat*4,1)};e.clearCoatGloss!==0&&(_.clearcoatRoughnessFactor=e.clearCoatGloss),this.attachTexture(t,e,_,"clearcoatTexture","clearCoatMap",i),this.attachTexture(t,e,_,"clearcoatRoughnessTexture","clearCoatGlossMap",i),e.clearCoatNormalMap&&(this.attachTexture(t,e,_,"clearcoatNormalTexture","clearCoatNormalMap",i),e.clearCoatBumpiness!==1&&(_.clearcoatNormalTexture.scale=e.clearCoatBumpiness)),this.addExtension(i,s,"KHR_materials_clearcoat",_)}e.dispersion!==0&&this.addExtension(i,s,"KHR_materials_dispersion",{dispersion:e.dispersion}),e.useLighting&&e.emissiveIntensity!==1&&this.addExtension(i,s,"KHR_materials_emissive_strength",{emissiveStrength:e.emissiveIntensity});let m=1/1.5;if(e.refractionIndex!==m&&e.refractionIndex>0&&this.addExtension(i,s,"KHR_materials_ior",{ior:1/e.refractionIndex}),e.useIridescence){let _={};e.iridescence!==0&&(_.iridescenceFactor=e.iridescence),e.iridescenceRefractionIndex!==1.3&&(_.iridescenceIor=e.iridescenceRefractionIndex),e.iridescenceThicknessMin!==100&&(_.iridescenceThicknessMinimum=e.iridescenceThicknessMin),e.iridescenceThicknessMax!==400&&(_.iridescenceThicknessMaximum=e.iridescenceThicknessMax),this.attachTexture(t,e,_,"iridescenceTexture","iridescenceMap",i),this.attachTexture(t,e,_,"iridescenceThicknessTexture","iridescenceThicknessMap",i),Object.keys(_).length>0&&this.addExtension(i,s,"KHR_materials_iridescence",_)}if(e.useSheen){let _={};if(!e.sheen.equals(F.BLACK)){let{r:S,g,b:T}=e.sheen.clone().linear();_.sheenColorFactor=[S,g,T]}e.sheenGloss!==0&&(_.sheenRoughnessFactor=e.sheenGloss),this.attachTexture(t,e,_,"sheenColorTexture","sheenMap",i),this.attachTexture(t,e,_,"sheenRoughnessTexture","sheenGlossMap",i),Object.keys(_).length>0&&this.addExtension(i,s,"KHR_materials_sheen",_)}if(e.useMetalnessSpecularColor||!e.useMetalness){let _={};if(!e.specular.equals(F.WHITE)){let{r:S,g,b:T}=e.specular.clone().linear();_.specularColorFactor=[S,g,T]}e.specularityFactor!==1&&(_.specularFactor=e.specularityFactor),this.attachTexture(t,e,_,"specularColorTexture","specularMap",i),this.attachTexture(t,e,_,"specularTexture","specularityFactorMap",i),Object.keys(_).length>0&&this.addExtension(i,s,"KHR_materials_specular",_)}if(e.useDynamicRefraction&&(e.refraction!==0||e.refractionMap)){let _={};e.refraction!==0&&(_.transmissionFactor=e.refraction),this.attachTexture(t,e,_,"transmissionTexture","refractionMap",i),Object.keys(_).length>0&&this.addExtension(i,s,"KHR_materials_transmission",_)}if(e.useLighting||this.addExtension(i,s,"KHR_materials_unlit"),e.useDynamicRefraction&&(e.thickness!==0||e.attenuationDistance!==0||!e.attenuation.equals(F.WHITE)||e.thicknessMap)){let _={};if(e.thickness!==0&&(_.thicknessFactor=e.thickness),e.attenuationDistance!==0&&(_.attenuationDistance=e.attenuationDistance),!e.attenuation.equals(F.WHITE)){let{r:S,g,b:T}=e.attenuation.clone().linear();_.attenuationColor=[S,g,T]}this.attachTexture(t,e,_,"thicknessTexture","thicknessMap",i),Object.keys(_).length>0&&this.addExtension(i,s,"KHR_materials_volume",_)}}writeMaterials(t,e){t.materials.length>0&&(e.materials=t.materials.map(s=>{let{name:i,blendType:r,cull:a,alphaTest:o}=s,l={pbrMetallicRoughness:{}};return i&&i.length>0&&(l.name=i),s instanceof it&&this.writeStandardMaterial(t,s,l,e),r===ls?l.alphaMode="BLEND":r===wt&&o!==0&&(l.alphaMode="MASK",l.alphaCutoff=o),a===0&&(l.doubleSided=!0),this.attachTexture(t,s,l,"normalTexture","normalMap",e),this.attachTexture(t,s,l,"occlusionTexture","aoMap",e),this.attachTexture(t,s,l,"emissiveTexture","emissiveMap",e),l}))}writeNodes(t,e){t.entities.length>0&&(e.nodes=t.entities.map(s=>{let i=s.name,r=s.getLocalPosition(),a=s.getLocalRotation(),o=s.getLocalScale(),l={};i&&i.length>0&&(l.name=i),r.equals(x.ZERO)||(l.translation=[r.x,r.y,r.z]),a.equals($.IDENTITY)||(l.rotation=[a.x,a.y,a.z,a.w]),o.equals(x.ONE)||(l.scale=[o.x,o.y,o.z]),s.camera&&s.camera.enabled&&(l.camera=t.cameras.indexOf(s.camera));let h=t.entityMeshInstances.find(f=>f.node===s);if(h){l.mesh=t.entityMeshInstances.indexOf(h);let f=h.meshInstances[0];f&&f.mesh.skin&&(l.skin=t.skins.indexOf(f.mesh.skin))}return s.children.length>0&&(l.children=[],s.children.forEach(f=>{l.children.push(t.entities.indexOf(f))})),l}))}writeMeshes(t,e,s){t.entityMeshInstances.length>0&&(e.accessors=[],e.meshes=[],t.entityMeshInstances.forEach(i=>{let r={primitives:[]};i.meshInstances.forEach(o=>{let l=c.createPrimitive(t,e,o.mesh,s);l.material=t.materials.indexOf(o.material),r.primitives.push(l)}),e.meshes.push(r)}))}static createPrimitive(t,e,s,i={}){let r={attributes:{}},{vertexBuffer:a}=s,{format:o}=a,{interleaved:l,elements:h}=o,f=a.getNumVertices();h.forEach((d,p)=>{let m=C9(d.name);if(i.stripUnusedAttributes){let C=!0;if(m.startsWith("TEXCOORD_")){let v=parseInt(m.split("_")[1],10);C=t.materials.some(E=>PV.some(y=>E[y]?(E[`${y}Uv`]??0)===v:!1))}if(m==="COLOR_0"&&(C=t.materials.some(v=>v.vertexColors)),m==="TANGENT"&&(C=t.materials.some(v=>v.normalMap)),(m==="JOINTS_0"||m==="WEIGHTS_0")&&(C=t.entityMeshInstances.some(v=>v.meshInstances.some(E=>E.mesh.skin))),!C)return}let _=t.bufferViewMap.get(a);_||(c.writeBufferView(t,e,a),t.buffers.push(a),_=t.bufferViewMap.get(a));let g={bufferView:_[l?0:p],byteOffset:l?d.offset:0,componentType:EV(d.dataType),type:A9(d.numComponents),count:f},T=e.accessors.push(g)-1;if(r.attributes[m]=T,d.name===ee){let C=[];s.getPositions(C);let v=new x,E=new x;ge.computeMinMax(C,v,E),g.min=[v.x,v.y,v.z],g.max=[E.x,E.y,E.z]}});let u=s.indexBuffer[0];if(u){let d=t.bufferViewMap.get(u);d||(c.writeBufferView(t,e,u),t.buffers.push(u),d=t.bufferViewMap.get(u));let m={bufferView:d[0],componentType:E9(u.getFormat()),count:u.getNumIndices(),type:"SCALAR"},_=e.accessors.push(m)-1;r.indices=_}return r}writeSkins(t,e){t.skins.length>0&&(e.skins=t.skins.map(s=>{let i=new Float32Array(s.inverseBindPose.length*16);for(let f=0;f{let u=t.entities.find(d=>d.name===f);return t.entities.indexOf(u)});return{inverseBindMatrices:l,joints:h}}))}convertTextures(t,e){let s={maxTextureSize:e.maxTextureSize},i=[];return t.forEach(r=>{let a=this.textureToCanvas(r,s);a.then(o=>new Promise(l=>l(o))),i.push(a)}),i}writeTextures(t,e,s,i){let r=t.textures,a=[];for(let o=0;o{let p=new FileReader;return p.readAsArrayBuffer(d),new Promise(m=>{p.onloadend=()=>{m(p)}})}).then(d=>{let p=this.getPaddedArrayBuffer(d.result);c.writeBufferView(t,s,p),t.buffers.push(p);let m=t.bufferViewMap.get(p);s.images[o]={mimeType:u,bufferView:m[0]},s.samplers[o]={minFilter:AV(l.minFilter),magFilter:AV(l.magFilter),wrapS:CV(l.addressU),wrapT:CV(l.addressV)},s.textures[o]={sampler:o,source:o}}))}return Promise.all(a)}getBlob(t,e){if(t.toBlob!==void 0)return new Promise(i=>{t.toBlob(i,e)});let s=1;return e==="image/jpeg"&&(s=.92),t.convertToBlob({type:e,quality:s})}getPaddedArrayBuffer(t,e=0){let s=R.roundUp(t.byteLength,4);if(s!==t.byteLength){let i=new Uint8Array(s);if(i.set(new Uint8Array(t)),e!==0)for(let r=t.byteLength;r{let r={asset:{version:"2.0",generator:"PlayCanvas GltfExporter"},scenes:[{nodes:[0]}],images:[],samplers:[],textures:[],scene:0};return this.writeBufferViews(t,r),this.writeCameras(t,r),this.writeMeshes(t,r,e),this.writeMaterials(t,r),this.writeNodes(t,r,e),this.writeSkins(t,r),await this.writeTextures(t,i,r,e),r.images.length||delete r.images,r.samplers.length||delete r.samplers,r.textures.length||delete r.textures,r})}build(t,e={}){let s=this.collectResources(t);return this.buildJson(s,e).then(i=>{let a=new TextEncoder().encode(JSON.stringify(i)),o=12,l=8,h=a.length,f=4-(h&3)&3,u=8,d=i.buffers.reduce((g,T)=>R.roundUp(g+T.byteLength,4),0),p=o+l+h+f;d>0&&(p+=u+d);let m=new ArrayBuffer(p),_=new DataView(m);_.setUint32(0,1179937895,!0),_.setUint32(4,2,!0),_.setUint32(8,p,!0),_.setUint32(12,h+f,!0),_.setUint32(16,1313821514,!0);let S=o+l;new Uint8Array(m,S,h).set(a),S+=h;for(let g=0;g0&&(_.setUint32(S,d,!0),_.setUint32(S+4,5130562,!0),S+=u,s.buffers.forEach(g=>{let T,C=s.bufferViewMap.get(g)[0],v=i.bufferViews[C].byteOffset;if(g instanceof ArrayBuffer)T=new Uint8Array(g);else{let y=g.lock();y instanceof ArrayBuffer?T=new Uint8Array(y):T=new Uint8Array(y.buffer,y.byteOffset,y.byteLength)}new Uint8Array(m,S+v,T.byteLength).set(T)})),Promise.resolve(m)})}};var cn="none",zA="lighting",GA="combine";var wV=` uniform sampler2D sourceTexture; uniform vec2 sourceInvResolution; varying vec2 uv0; #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; var sourceTextureSampler: sampler; uniform sourceInvResolution: vec2f; varying uv0: vec2f; #ifdef PREMULTIPLY var premultiplyTexture: texture_2d; 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; 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=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; 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; var bloomTextureSampler: sampler; uniform bloomIntensity: f32; var 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; var cocTextureSampler: sampler; var blurTexture: texture_2d; var blurTextureSampler: sampler; var dCoc: vec2f; var 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; var ssaoTextureSampler: sampler; var 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 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; var colorLUTSampler: sampler; #ifdef COLOR_LUT2 var colorLUT2: texture_2d; var colorLUT2Sampler: sampler; #endif fn sampleColorLUT(lut: texture_2d, lutSampler: sampler, uv_l: vec2f, uv_h: vec2f, t: f32) -> vec3f { let color_l: vec3f = textureSampleLevel(lut, lutSampler, uv_l, 0.0).rgb; let color_h: vec3f = textureSampleLevel(lut, lutSampler, uv_h, 0.0).rgb; return mix(color_l, color_h, vec3f(t)); } fn applyColorLUT(color: vec3f) -> vec3f { 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, 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; var sourceTextureSampler: sampler; var historyTexture: texture_2d; 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; var nearTextureSampler: sampler; #endif var farTexture: texture_2d; var farTextureSampler: sampler; var cocTexture: texture_2d; var cocTextureSampler: sampler; uniform kernel: array; 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{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; 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, totalWeight_ptr: ptr, 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, 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{i.firstCameraUse=!0}),s.forEach(i=>{i.lastCameraUse=!0})}collectPasses(){return[this.prePass,this.ssaoPass,this.scenePass,this.colorGrabPass,this.scenePassTransparent,this.taaPass,this.scenePassHalf,this.bloomPass,this.dofPass,this.composePass,this.afterPass]}createPasses(e){this.setupScenePrepass(e),this.setupSsaoPass(e);let s=this.setupScenePass(e),i=this.setupTaaPass(e);this.setupSceneHalfPass(e,i),this.setupBloomPass(e,this.sceneTextureHalf),this.setupDofPass(e,this.sceneTexture,this.sceneTextureHalf),this.setupComposePass(e),this.setupAfterPass(e,s)}setupScenePrepass(e){if(e.prepassEnabled){let{app:s,device:i,cameraComponent:r}=this,{scene:a,renderer:o}=s;this.prePass=new lg(i,a,o,r,this.sceneOptions)}}setupScenePassSettings(e){e.gammaCorrection=Zi,e.toneMapping=Rf}setupScenePass(e){let{app:s,device:i,cameraComponent:r}=this,{scene:a,renderer:o}=s,l=a.layers;this.scenePass=new Ya(i,l,a,o),this.setupScenePassSettings(this.scenePass),this.scenePass.init(this.rt,this.sceneOptions);let h=e.sceneColorMap?e.lastGrabLayerId:e.lastSceneLayerId,f=e.sceneColorMap?e.lastGrabLayerIsTransparent:e.lastSceneLayerIsTransparent,u={lastAddedIndex:0,clearRenderTarget:!0};return u.lastAddedIndex=this.scenePass.addLayers(l,r,u.lastAddedIndex,u.clearRenderTarget,h,f),u.clearRenderTarget=!1,e.sceneColorMap&&(this.colorGrabPass=new wc(i),this.colorGrabPass.source=this.rt,this.scenePassTransparent=new Ya(i,l,a,o),this.setupScenePassSettings(this.scenePassTransparent),this.scenePassTransparent.init(this.rt),u.lastAddedIndex=this.scenePassTransparent.addLayers(l,r,u.lastAddedIndex,u.clearRenderTarget,e.lastSceneLayerId,e.lastSceneLayerIsTransparent),this.scenePassTransparent.rendersAnything||(this.scenePassTransparent.destroy(),this.scenePassTransparent=null),this.scenePassTransparent&&e.prepassEnabled&&(this.scenePassTransparent.depthStencilOps.storeDepth=!0)),u}setupSsaoPass(e){let{ssaoBlurEnabled:s,ssaoType:i}=e,{device:r,cameraComponent:a}=this;i!==cn&&(this.ssaoPass=new cg(r,this.sceneTexture,a,s))}setupSceneHalfPass(e,s){this._sceneHalfEnabled&&(this.scenePassHalf=new hn(this.device,this.sceneTexture,{boxFilter:!0,removeInvalid:!0}),this.scenePassHalf.name="RenderPassSceneHalf",this.scenePassHalf.init(this.rtHalf,{resizeSource:s,scaleX:.5,scaleY:.5}),this.scenePassHalf.setClearColor(F.BLACK))}setupBloomPass(e,s){this._bloomEnabled&&(this.bloomPass=new rg(this.device,s,this.hdrFormat))}setupDofPass(e,s,i){e.dofEnabled&&(this.dofPass=new ng(this.device,this.cameraComponent,s,i,e.dofHighQuality,e.dofNearBlur))}setupTaaPass(e){let s=this.sceneTexture;return e.taaEnabled&&(this.taaPass=new og(this.device,this.sceneTexture,this.cameraComponent),s=this.taaPass.historyTexture),s}setupComposePass(e){this.composePass=new ag(this.device),this.composePass.bloomTexture=this.bloomPass?.bloomTexture,this.composePass.hdrScene=this.hdrFormat!==ce,this.composePass.taaEnabled=e.taaEnabled,this.composePass.cocTexture=this.dofPass?.cocTexture,this.composePass.blurTexture=this.dofPass?.blurTexture,this.composePass.blurTextureUpscale=!this.dofPass?.highQuality;let i=this.cameraComponent.renderTarget;this.composePass.init(i),this.composePass.ssaoTexture=e.ssaoType===GA?this.ssaoPass.ssaoTexture:null}setupAfterPass(e,s){let{app:i,cameraComponent:r}=this,{scene:a,renderer:o}=i,l=a.layers,h=r.renderTarget;this.afterPass=new Ya(this.device,l,a,o),this.afterPass.init(h),this.afterPass.addLayers(l,r,s.lastAddedIndex,s.clearRenderTarget)}frameUpdate(){this.layersDirty&&this.cameraFrame.update(),super.frameUpdate();let e=this.taaPass?.update()??this.rt.colorBuffer;this.composePass.sceneTexture=e,this.scenePassHalf?.setSourceTexture(e)}};var WA=class{constructor(t,e){n(this,"_enabled",!0);n(this,"rendering",{renderFormats:[Gi,Me,ke],stencil:!1,renderTargetScale:1,samples:1,sceneColorMap:!1,sceneDepthMap:!1,toneMapping:0,sharpness:0});n(this,"ssao",{type:cn,blurEnabled:!0,randomize:!1,intensity:.5,radius:30,samples:12,power:6,minAngle:10,scale:1});n(this,"bloom",{intensity:0,blurLevel:16});n(this,"grading",{enabled:!1,brightness:1,contrast:1,saturation:1,tint:new F(1,1,1,1)});n(this,"colorLUT",{texture:null,intensity:1,texture2:null,intensity2:1,blend:0});n(this,"vignette",{intensity:0,inner:.5,outer:1,curvature:.5,color:new F(0,0,0)});n(this,"taa",{enabled:!1,jitter:1});n(this,"fringing",{intensity:0});n(this,"colorEnhance",{enabled:!1,shadows:0,highlights:0,vibrance:0,midtones:0,dehaze:0});n(this,"dof",{enabled:!1,nearBlur:!1,focusDistance:100,focusRange:10,blurRadius:3,blurRings:4,blurRingPoints:5,highQuality:!0});n(this,"debug",null);n(this,"options",new Wu);n(this,"renderPassCamera",null);this.app=t,this.cameraComponent=e,this.updateOptions(),this.enable(),this.cameraLayersChanged=e.on("set:layers",()=>{this.renderPassCamera&&(this.renderPassCamera.layersDirty=!0)})}destroy(){this.disable(),this.cameraLayersChanged.off()}enable(){this.renderPassCamera=this.createRenderPass(),this.cameraComponent.framePasses=[this.renderPassCamera]}disable(){let t=this.cameraComponent;t.framePasses?.forEach(e=>{e.destroy()}),t.framePasses=[],t.rendering=null,t.jitter=0,t.shaderParams.ssaoEnabled=!1,this.renderPassCamera=null}createRenderPass(){return new hg(this.app,this,this.cameraComponent,this.options)}set enabled(t){this._enabled!==t&&(t?this.enable():this.disable(),this._enabled=t)}get enabled(){return this._enabled}updateOptions(){let{options:t,rendering:e,bloom:s,taa:i,ssao:r}=this;t.stencil=e.stencil,t.samples=e.samples,t.sceneColorMap=e.sceneColorMap,t.prepassEnabled=e.sceneDepthMap,t.bloomEnabled=s.intensity>0,t.taaEnabled=i.enabled,t.ssaoType=r.type,t.ssaoBlurEnabled=r.blurEnabled,t.formats=e.renderFormats.slice(),t.dofEnabled=this.dof.enabled,t.dofNearBlur=this.dof.nearBlur,t.dofHighQuality=this.dof.highQuality}update(){if(!this._enabled)return;let t=this.cameraComponent,{options:e,renderPassCamera:s,rendering:i,bloom:r,grading:a,colorEnhance:o,vignette:l,fringing:h,taa:f,ssao:u}=this;this.updateOptions(),s.update(e);let{composePass:d,bloomPass:p,ssaoPass:m,dofPass:_}=s;s.renderTargetScale=R.clamp(i.renderTargetScale,.1,1),d.toneMapping=i.toneMapping,d.sharpness=i.sharpness,e.bloomEnabled&&p&&(d.bloomIntensity=r.intensity,p.blurLevel=r.blurLevel),e.dofEnabled&&(_.focusDistance=this.dof.focusDistance,_.focusRange=this.dof.focusRange,_.blurRadius=this.dof.blurRadius,_.blurRings=this.dof.blurRings,_.blurRingPoints=this.dof.blurRingPoints),e.ssaoType!==cn&&(m.intensity=u.intensity,m.power=u.power,m.radius=u.radius,m.sampleCount=u.samples,m.minAngle=u.minAngle,m.scale=u.scale,m.randomize=u.randomize),d.gradingEnabled=a.enabled,a.enabled&&(d.gradingSaturation=a.saturation,d.gradingBrightness=a.brightness,d.gradingContrast=a.contrast,d.gradingTint=a.tint),d.colorLUT=this.colorLUT.texture,d.colorLUTIntensity=this.colorLUT.intensity,d.colorLUT2=this.colorLUT.texture2,d.colorLUT2Intensity=this.colorLUT.intensity2,d.colorLUTBlend=this.colorLUT.blend,d.vignetteEnabled=l.intensity>0,d.vignetteEnabled&&(d.vignetteInner=l.inner,d.vignetteOuter=l.outer,d.vignetteCurvature=l.curvature,d.vignetteIntensity=l.intensity,d.vignetteColor.copy(l.color)),d.fringingEnabled=h.intensity>0,d.fringingEnabled&&(d.fringingIntensity=h.intensity),d.colorEnhanceEnabled=o.enabled,o.enabled&&(d.colorEnhanceShadows=o.shadows,d.colorEnhanceHighlights=o.highlights,d.colorEnhanceVibrance=o.vibrance,d.colorEnhanceMidtones=o.midtones,d.colorEnhanceDehaze=o.dehaze),t.jitter=f.enabled?f.jitter:0,d.debug=this.debug,d.debug==="ssao"&&e.ssaoType===cn&&(d.debug=null),d.debug==="vignette"&&!d.vignetteEnabled&&(d.debug=null)}};var R9=new x,b9=new $,ei=class c{constructor(t=x.ZERO,e=x.ZERO,s=0){n(this,"position",new x);n(this,"angles",new x);n(this,"distance",0);n(this,"pitchRange",new B(-1/0,1/0));n(this,"yawRange",new B(-1/0,1/0));n(this,"xRange",new B(-1/0,1/0));n(this,"yRange",new B(-1/0,1/0));n(this,"zRange",new B(-1/0,1/0));this.set(t,e,s)}copy(t){return this.set(t.position,t.angles,t.distance)}clone(){return new c(this.position.clone(),this.angles.clone(),this.distance)}equalsApprox(t,e=1e-6){return this.position.equalsApprox(t.position,e)&&this.angles.equalsApprox(t.angles,e)&&Math.abs(this.distance-t.distance){let c=new Map;return{down:t=>{c.set(t.pointerId,[t.screenX,t.screenY])},move:t=>{if(!c.has(t.pointerId))return[0,0];let e=c.get(t.pointerId),s=t.screenX-e[0],i=t.screenY-e[1];return e[0]=t.screenX,e[1]=t.screenY,[s,i]},up:t=>{c.delete(t.pointerId)}}};var Xu=new B,Yu=class{constructor({range:t}={}){n(this,"_range",70);n(this,"_position",new B);n(this,"_value",new B);this._range=t??this._range}get value(){return this._value}down(t,e){return this._position.set(t,e),this._value.set(0,0),[t,e,t,e]}move(t,e){Xu.set(t-this._position.x,e-this._position.y),Xu.length()>this._range&&Xu.normalize().mulScalar(this._range),this._value.set(R.clamp(Xu.x/this._range,-1,1),R.clamp(Xu.y/this._range,-1,1));let{x:s,y:i}=this._position;return[s,i,s+Xu.x,i+Xu.y]}up(){return this._position.set(0,0),this._value.set(0,0),[-1,-1,-1,-1]}};var XA=class extends cr{constructor(){super({input:[0,0],doubleTap:[0]});n(this,"_movementState",Mh());n(this,"_layout","joystick");n(this,"_pointerData",new Map);n(this,"_lastPointer",{x:0,y:0,time:0});n(this,"_joystick");this._joystick=new Yu,this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this)}set layout(e){this._layout!==e&&(this._layout=e,this.read(),this._pointerData.clear())}get layout(){return this._layout}get joystick(){return this._joystick}_onPointerDown(e){let{pointerType:s,pointerId:i,clientX:r,clientY:a}=e;if(this._movementState.down(e),s!=="touch")return;this._element?.setPointerCapture(i),this._pointerData.set(i,{x:r,y:a});let o=Date.now();(this._lastPointer.x-r)**2+(this._lastPointer.y-a)**2<100&&o-this._lastPointer.time<250&&this.deltas.doubleTap.append([1]),this._lastPointer.x=r,this._lastPointer.y=a,this._lastPointer.time=o,this._layout==="joystick"&&this.fire("joystick:position",this._joystick.down(r,a))}_onPointerMove(e){let{pointerType:s,pointerId:i,target:r,clientX:a,clientY:o}=e,[l,h]=this._movementState.move(e);if(s!=="touch"||r!==this._element)return;let f=this._pointerData.get(i);f&&(f.x=a,f.y=o,this._layout==="joystick"?this.fire("joystick:position",this._joystick.move(a,o)):this.deltas.input.append([l,h]))}_onPointerUp(e){let{pointerType:s,pointerId:i}=e;this._movementState.up(e),!(s!=="touch"||(this._element?.releasePointerCapture(i),!this._pointerData.get(i)))&&(this._pointerData.delete(i),this._layout==="joystick"&&this.fire("joystick:position",this._joystick.up()))}attach(e){super.attach(e),this._element=e,this._element.addEventListener("pointerdown",this._onPointerDown),this._element.addEventListener("pointermove",this._onPointerMove),this._element.addEventListener("pointerup",this._onPointerUp),this._element.addEventListener("pointercancel",this._onPointerUp)}detach(){this._element&&(this._element.removeEventListener("pointerdown",this._onPointerDown),this._element.removeEventListener("pointermove",this._onPointerMove),this._element.removeEventListener("pointerup",this._onPointerUp),this._element.removeEventListener("pointercancel",this._onPointerUp),this._pointerData.clear(),super.detach())}read(){return this.deltas.input.append([this._joystick.value.x,this._joystick.value.y]),super.read()}destroy(){this._joystick.up(),super.destroy()}};var Wb=(c,t)=>c.indexOf(t)===0,Xb=(c,t)=>c.indexOf(t,c.length-t.length)!==-1,YA=class extends cr{constructor(e){super({leftInput:[0,0],rightInput:[0,0],doubleTap:[0]});n(this,"_movementState",Mh());n(this,"_layout","joystick-touch");n(this,"_pointerData",new Map);n(this,"_lastPointer",{x:0,y:0,time:0});n(this,"_leftJoystick");n(this,"_rightJoystick");e&&(this.layout=e),this._leftJoystick=new Yu,this._rightJoystick=new Yu,this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this)}set layout(e){this._layout!==e&&(this._layout=e,this.read(),this._pointerData.clear())}get layout(){return this._layout}get leftJoystick(){return this._leftJoystick}get rightJoystick(){return this._rightJoystick}_onPointerDown(e){let{pointerType:s,pointerId:i,clientX:r,clientY:a}=e;if(this._movementState.down(e),s!=="touch")return;this._element?.setPointerCapture(i);let o=r1&&(this._getMidPoint(this._pointerPos),this._pinchDist=this._getPinchDist()))}_onPointerMove(e){let{pointerType:s,target:i,pointerId:r}=e,[a,o]=this._movementState.move(e);if(s==="touch"&&i===this._element&&this._pointerEvents.size!==0)if(this._pointerEvents.set(r,e),this._pointerEvents.size>1){let l=this._getMidPoint(M9);this.deltas.touch.append([l.x-this._pointerPos.x,l.y-this._pointerPos.y]),this._pointerPos.copy(l);let h=this._getPinchDist();this._pinchDist>0&&this.deltas.pinch.append([this._pinchDist-h]),this._pinchDist=h}else this.deltas.touch.append([a,o])}_onPointerUp(e){let{pointerType:s,pointerId:i}=e;this._movementState.up(e),s==="touch"&&(this._element?.releasePointerCapture(i),this._pointerEvents.delete(i),this.deltas.count.append([-1]),this._pointerEvents.size<2&&(this._pinchDist=-1),this._pointerPos.set(0,0))}_onContextMenu(e){e.preventDefault()}_getMidPoint(e){if(this._pointerEvents.size<2)return e.set(0,0);let[s,i]=this._pointerEvents.values(),r=s.clientX-i.clientX,a=s.clientY-i.clientY;return e.set(i.clientX+r*.5,i.clientY+a*.5)}_getPinchDist(){if(this._pointerEvents.size<2)return 0;let[e,s]=this._pointerEvents.values(),i=e.clientX-s.clientX,r=e.clientY-s.clientY;return Math.sqrt(i*i+r*r)}attach(e){super.attach(e),this._element=e,this._element.addEventListener("pointerdown",this._onPointerDown),this._element.addEventListener("pointermove",this._onPointerMove),this._element.addEventListener("pointerup",this._onPointerUp),this._element.addEventListener("pointercancel",this._onPointerUp),this._element.addEventListener("contextmenu",this._onContextMenu)}detach(){this._element&&(this._element.removeEventListener("pointerdown",this._onPointerDown),this._element.removeEventListener("pointermove",this._onPointerMove),this._element.removeEventListener("pointerup",this._onPointerUp),this._element.removeEventListener("pointercancel",this._onPointerUp),this._element.removeEventListener("contextmenu",this._onContextMenu),this._pointerEvents.clear(),super.detach())}};var fH={passive:!1},uH={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,0:26,1:27,2:28,3:29,4:30,5:31,6:32,7:33,8:34,9:35,UP:36,DOWN:37,LEFT:38,RIGHT:39,SPACE:40,SHIFT:41,CTRL:42},jA=Object.keys(uH).length,Yb=Array(jA).fill(0),$A=class $A extends cr{constructor({pointerLock:e=!1}={}){super({key:Array(jA).fill(0),button:[0,0,0],mouse:[0,0],wheel:[0]});n(this,"_movementState",Mh());n(this,"_pointerId",-1);n(this,"_pointerLock");n(this,"_keyMap",new Map);n(this,"_keyPrev",Array(jA).fill(0));n(this,"_keyNow",Array(jA).fill(0));n(this,"_button",Array(3).fill(0));this._pointerLock=e??!1;let{keyCode:s}=$A;for(let i=0;i<26;i++){let r=`Key${String.fromCharCode(65+i)}`;this._keyMap.set(r,s.A+i)}for(let i=0;i<10;i++){let r=`Digit${i}`;this._keyMap.set(r,s[0]+i)}this._keyMap.set("ArrowUp",s.UP),this._keyMap.set("ArrowDown",s.DOWN),this._keyMap.set("ArrowLeft",s.LEFT),this._keyMap.set("ArrowRight",s.RIGHT),this._keyMap.set("Space",s.SPACE),this._keyMap.set("ShiftLeft",s.SHIFT),this._keyMap.set("ShiftRight",s.SHIFT),this._keyMap.set("ControlLeft",s.CTRL),this._keyMap.set("ControlRight",s.CTRL),this._onWheel=this._onWheel.bind(this),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onKeyDown=this._onKeyDown.bind(this),this._onKeyUp=this._onKeyUp.bind(this)}_onWheel(e){e.preventDefault(),this.deltas.wheel.append([e.deltaY])}_onPointerDown(e){this._movementState.down(e),e.pointerType==="mouse"&&(this._pointerLock?document.pointerLockElement!==this._element&&this._element?.requestPointerLock():this._element?.setPointerCapture(e.pointerId),this._clearButtons(),this._button[e.button]=1,this.deltas.button.append(this._button),this._pointerId===-1&&(this._pointerId=e.pointerId))}_onPointerMove(e){let[s,i]=this._pointerLock&&document.pointerLockElement===this._element?[e.movementX,e.movementY]:this._movementState.move(e);if(e.pointerType==="mouse"&&e.target===this._element){if(this._pointerLock){if(document.pointerLockElement!==this._element)return}else if(this._pointerId!==e.pointerId)return;this.deltas.mouse.append([s,i])}}_onPointerUp(e){this._movementState.up(e),e.pointerType==="mouse"&&(this._pointerLock||this._element?.releasePointerCapture(e.pointerId),this._clearButtons(),this.deltas.button.append(this._button),this._pointerId===e.pointerId&&(this._pointerId=-1))}_onContextMenu(e){e.preventDefault()}_onKeyDown(e){this._pointerLock&&document.pointerLockElement!==this._element||(e.stopPropagation(),this._setKey(e.code,1))}_onKeyUp(e){e.stopPropagation(),this._setKey(e.code,0)}_clearButtons(){for(let e=0;e1-Math.pow(c,t*1e3);var yx=new x,O9=new x,pH=new x,mH=new x,_H=new x,ZA=new $,QA=class extends fn{constructor(){super(...arguments);n(this,"_targetPose",new ei);n(this,"rotateDamping",.98);n(this,"moveDamping",.98)}set pitchRange(e){this._targetPose.pitchRange.copy(e),this._pose.copy(this._targetPose.rotate(x.ZERO))}get pitchRange(){return this._targetPose.pitchRange}set yawRange(e){this._targetPose.yawRange.copy(e),this._pose.copy(this._targetPose.rotate(x.ZERO))}get yawRange(){return this._targetPose.yawRange}attach(e,s=!0){this._targetPose.copy(e),s||this._pose.copy(this._targetPose)}detach(){this._targetPose.copy(this._pose)}update(e,s){let{move:i,rotate:r}=e.read();return this._targetPose.rotate(O9.set(-r[1],-r[0],0)),ZA.setFromEulerAngles(this._pose.angles),ZA.transformVector(x.FORWARD,pH),ZA.transformVector(x.RIGHT,mH),ZA.transformVector(x.UP,_H),yx.set(0,0,0),yx.add(pH.mulScalar(i[2])),yx.add(mH.mulScalar(i[0])),yx.add(_H.mulScalar(i[1])),this._targetPose.move(yx),this._pose.lerp(this._pose,this._targetPose,co(this.moveDamping,s),co(this.rotateDamping,s))}destroy(){this.detach()}};var F9=new x,Ku=new x,N9=new x,gH=new $,JA=class extends fn{constructor(){super(...arguments);n(this,"_targetRootPose",new ei);n(this,"_rootPose",new ei);n(this,"_targetChildPose",new ei);n(this,"_childPose",new ei);n(this,"rotateDamping",.98);n(this,"moveDamping",.98);n(this,"zoomDamping",.98)}set pitchRange(e){this._targetRootPose.pitchRange.copy(e),this._rootPose.copy(this._targetRootPose.rotate(x.ZERO))}get pitchRange(){return this._targetRootPose.pitchRange}set yawRange(e){this._targetRootPose.yawRange.copy(e),this._rootPose.copy(this._targetRootPose.rotate(x.ZERO))}get yawRange(){return this._targetRootPose.yawRange}set zoomRange(e){this._targetChildPose.zRange.copy(e),this._childPose.copy(this._targetChildPose.move(x.ZERO))}get zoomRange(){return this._targetRootPose.zRange}attach(e,s=!0){this._targetRootPose.set(e.getFocus(F9),e.angles,0),this._targetChildPose.position.set(0,0,e.distance),s||(this._rootPose.copy(this._targetRootPose),this._childPose.copy(this._targetChildPose))}detach(){this._targetRootPose.copy(this._rootPose),this._targetChildPose.copy(this._childPose)}update(e,s){let{move:i,rotate:r}=e.read();Ku.set(i[0],i[1],0),gH.setFromEulerAngles(this._rootPose.angles).transformVector(Ku,Ku),this._targetRootPose.move(Ku);let{z:a}=this._targetChildPose.position;return this._targetChildPose.move(Ku.set(0,0,a*(1+i[2])-a)),this._targetRootPose.rotate(N9.set(-r[1],-r[0],0)),this._rootPose.lerp(this._rootPose,this._targetRootPose,co(this.moveDamping,s),co(this.rotateDamping,s),1),this._childPose.lerp(this._childPose,this._targetChildPose,co(this.zoomDamping,s),1,1),gH.setFromEulerAngles(this._rootPose.angles).transformVector(this._childPose.position,Ku).add(this._rootPose.position),this._pose.set(Ku,this._rootPose.angles,this._childPose.position.z)}destroy(){this.detach()}};var SH=.001,B9=new x,xH=new x,U9=new $,eC=class extends fn{constructor(){super(...arguments);n(this,"_targetRootPose",new ei);n(this,"_rootPose",new ei);n(this,"_targetChildPose",new ei);n(this,"_childPose",new ei);n(this,"focusDamping",.98)}attach(e,s=!0){this._targetRootPose.set(e.getFocus(B9),e.angles,0),this._targetChildPose.position.set(0,0,e.distance),s||(this._rootPose.copy(this._targetRootPose),this._childPose.copy(this._targetChildPose))}detach(){this._targetRootPose.copy(this._rootPose),this._targetChildPose.copy(this._childPose)}complete(){return this._targetRootPose.equalsApprox(this._rootPose,SH)&&this._targetChildPose.equalsApprox(this._childPose,SH)}update(e,s){return e.read(),this._rootPose.lerp(this._rootPose,this._targetRootPose,co(this.focusDamping,s),co(this.focusDamping,s),1),this._childPose.lerp(this._childPose,this._targetChildPose,co(this.focusDamping,s),1,1),U9.setFromEulerAngles(this._rootPose.angles).transformVector(this._childPose.position,xH).add(this._rootPose.position),this._pose.set(xH,this._rootPose.angles,this._childPose.position.length())}destroy(){this.detach()}};var vH="local",TH="world",yH="x",EH="y",AH="z",CH="yz",PH="xz",wH="xy",IH="xyz",RH="face";var tC=new x,ju=new x,jb=new x,Ex=new $,k9=new W,z9=new W,sC=new ws,G9=1e-4,V9=.3,H9=.32,qb=1e-6,W9=1e-4,As=class As extends J{constructor(e,s,i="gizmo"){super();n(this,"_size",1);n(this,"_scale",1);n(this,"_coordSpace","world");n(this,"_app");n(this,"_device");n(this,"_handles",[]);n(this,"_mouseButtons",[!0,!0,!0]);n(this,"_camera");n(this,"_layer");n(this,"_renderUpdate",!1);n(this,"nodes",[]);n(this,"root");n(this,"intersectShapes",[]);n(this,"preventDefault",!0);this._layer=s,this._camera=e,this._camera.layers=this._camera.layers.concat(this._layer.id),this._app=this._camera.system.app,this._device=this._app.graphicsDevice,this.root=new Ne(i),this._app.root.addChild(this.root),this.root.enabled=!1,this._updateScale(),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._device.canvas.addEventListener("pointerdown",this._onPointerDown),this._device.canvas.addEventListener("pointermove",this._onPointerMove),this._device.canvas.addEventListener("pointerup",this._onPointerUp),this._handles.push(this._app.on("prerender",()=>this.prerender())),this._handles.push(this._app.on("update",()=>this.update())),this._handles.push(this._app.on("destroy",()=>this.destroy()))}static createLayer(e,s="Gizmo",i=e.scene.layers.layerList.length){let r=new Dt({name:s,clearDepthBuffer:!0,opaqueSortMode:Ho,transparentSortMode:Ho});return e.scene.layers.insert(r,i),r}set enabled(e){let s=this.root.getLocalPosition().distance(this.camera.entity.getPosition()),i=e?this.nodes.length>0&&s>W9:!1;i!==this.root.enabled&&(this.root.enabled=i,this._renderUpdate=!0)}get enabled(){return this.root.enabled}get mouseButtons(){return this._mouseButtons}set layer(e){this._layer!==e&&(this._camera.layers=this._camera.layers.filter(s=>s!==this._layer.id),this._layer=e,this._camera.layers=this._camera.layers.concat(this._layer.id),this.enabled=!0)}get layer(){return this._layer}set camera(e){this._camera!==e&&(this._camera.layers=this._camera.layers.filter(s=>s!==this._layer.id),this._camera=e,this._camera.layers=this._camera.layers.concat(this._layer.id),this.enabled=!0)}get camera(){return this._camera}set coordSpace(e){this._coordSpace=e??this._coordSpace,this._updateRotation()}get coordSpace(){return this._coordSpace}set size(e){this._size=e,this._updateScale()}get size(){return this._size}get facingDir(){if(this._camera.projection===ts){let e=this.root.getLocalPosition(),s=this._camera.entity.getPosition();return jb.sub2(s,e).normalize()}return jb.copy(this._camera.entity.forward).mulScalar(-1)}get cameraDir(){let e=this._camera.entity.getPosition(),s=this.root.getLocalPosition();return jb.sub2(e,s).normalize()}_onPointerDown(e){if(!this.enabled||document.pointerLockElement||!this.mouseButtons[e.button])return;let s=this._getSelection(e.offsetX,e.offsetY);s[0]&&(this.preventDefault&&e.preventDefault(),e.stopPropagation());let{canvas:i}=this._device;i.setPointerCapture(e.pointerId),this.fire(As.EVENT_POINTERDOWN,e.offsetX,e.offsetY,s[0])}_onPointerMove(e){if(!this.enabled||document.pointerLockElement)return;let s=this._getSelection(e.offsetX,e.offsetY);s[0]&&(this.preventDefault&&e.preventDefault(),e.stopPropagation()),this.fire(As.EVENT_POINTERMOVE,e.offsetX,e.offsetY,s[0])}_onPointerUp(e){if(!this.enabled||document.pointerLockElement||!this.mouseButtons[e.button])return;let s=this._getSelection(e.offsetX,e.offsetY);s[0]&&(this.preventDefault&&e.preventDefault(),e.stopPropagation());let{canvas:i}=this._device;i.releasePointerCapture(e.pointerId),this.fire(As.EVENT_POINTERUP,e.offsetX,e.offsetY,s[0])}_updatePosition(){if(ju.set(0,0,0),this._coordSpace==="local")ju.copy(this.nodes[this.nodes.length-1].getPosition());else{for(let e=0;el.priority!==0&&h.priority!==0?h.priority-l.priority:l.dist-h.dist),o[0].meshInstances):[]}attach(e=[]){if(Array.isArray(e)){if(e.length===0)return;this.nodes=e}else this.nodes=[e];this._updatePosition(),this._updateRotation(),this._updateScale(),this.fire(As.EVENT_NODESATTACH),this.enabled=!0}detach(){this.enabled=!1,this.fire(As.EVENT_NODESDETACH),this.nodes=[]}prerender(){}update(){this._renderUpdate&&(this._renderUpdate=!1,this.fire(As.EVENT_RENDERUPDATE)),this.enabled&&(this._updatePosition(),this._updateRotation(),this._updateScale())}destroy(){this.detach(),this._device.canvas.removeEventListener("pointerdown",this._onPointerDown),this._device.canvas.removeEventListener("pointermove",this._onPointerMove),this._device.canvas.removeEventListener("pointerup",this._onPointerUp),this._handles.forEach(e=>e.off()),this.root.destroy()}};n(As,"EVENT_POINTERDOWN","pointer:down"),n(As,"EVENT_POINTERMOVE","pointer:move"),n(As,"EVENT_POINTERUP","pointer:up"),n(As,"EVENT_POSITIONUPDATE","position:update"),n(As,"EVENT_ROTATIONUPDATE","rotation:update"),n(As,"EVENT_SCALEUPDATE","scale:update"),n(As,"EVENT_NODESATTACH","nodes:attach"),n(As,"EVENT_NODESDETACH","nodes:detach"),n(As,"EVENT_RENDERUPDATE","render:update");var ho=As;var fg=Object.freeze(new F(1,.3,.3)),ug=Object.freeze(new F(.3,1,.3)),dg=Object.freeze(new F(.3,.3,1)),Zpt=Object.freeze(new F(1,1,.5)),iC=Object.freeze(new F(.5,.5,.5,.5)),Bl=(c,t)=>new F(c.r,c.g,c.b,t);var Oh=new x,$b=new x,Zb=new x,qu=new ws,bH=new go,X9=new F,Y9=["x","y","z"],Fh=class Fh extends ho{constructor(e,s,i="gizmo:transform"){super(e,s,i);n(this,"_theme",{shapeBase:{x:fg.clone(),y:ug.clone(),z:dg.clone(),xyz:new F(.8,.8,.8,1),f:new F(.8,.8,.8,1)},shapeHover:{x:new F().lerp(fg,F.WHITE,.75),y:new F().lerp(ug,F.WHITE,.75),z:new F().lerp(dg,F.WHITE,.75),xyz:F.WHITE.clone(),f:F.WHITE.clone()},guideBase:{x:fg.clone(),y:ug.clone(),z:dg.clone()},guideOcclusion:.8,disabled:iC.clone()});n(this,"_rootStartPos",new x);n(this,"_rootStartRot",new $);n(this,"_shapes",{});n(this,"_shapeMap",new Map);n(this,"_hovering",new Set);n(this,"_hoverAxis","");n(this,"_hoverIsPlane",!1);n(this,"_selectedAxis","");n(this,"_selectedIsPlane",!1);n(this,"_selectionStartPoint",new x);n(this,"snap",!1);n(this,"snapIncrement",1);n(this,"dragMode","selected");this.on(ho.EVENT_POINTERDOWN,(r,a,o)=>{if(this._shapeMap.get(o)?.disabled||this._dragging||!o)return;this._hoverAxis="",this._hoverIsPlane=!1,this._selectedAxis=this._getAxis(o),this._selectedIsPlane=this._getIsPlane(o),this._rootStartPos.copy(this.root.getLocalPosition()),this._rootStartRot.copy(this.root.getRotation());let h=this._screenToPoint(r,a);this._selectionStartPoint.copy(h),this.fire(Fh.EVENT_TRANSFORMSTART,h,r,a)}),this.on(ho.EVENT_POINTERMOVE,(r,a,o)=>{if(this._shapeMap.get(o)?.disabled||(this._hover(o),!this._dragging))return;let h=this._screenToPoint(r,a);this.fire(Fh.EVENT_TRANSFORMMOVE,h,r,a)}),this.on(ho.EVENT_POINTERUP,(r,a,o)=>{this._hover(o),this._dragging&&(o&&(this._hoverAxis=this._selectedAxis,this._hoverIsPlane=this._selectedIsPlane),this._selectedAxis="",this._selectedIsPlane=!1,this.fire(Fh.EVENT_TRANSFORMEND))}),this.on(ho.EVENT_NODESDETACH,()=>{this._hoverAxis="",this._hoverIsPlane=!1,this._hover(),this.fire(ho.EVENT_POINTERUP)})}get theme(){return this._theme}set xAxisColor(e){this.setTheme({shapeBase:{x:e},shapeHover:{x:Bl(e,this.colorAlpha)},guideBase:{x:e},guideOcclusion:1})}get xAxisColor(){return this._theme.shapeBase.x}set yAxisColor(e){this.setTheme({shapeBase:{y:e},shapeHover:{y:Bl(e,this.colorAlpha)},guideBase:{y:e},guideOcclusion:1})}get yAxisColor(){return this._theme.shapeBase.y}set zAxisColor(e){this.setTheme({shapeBase:{z:e},shapeHover:{z:Bl(e,this.colorAlpha)},guideBase:{z:e},guideOcclusion:1})}get zAxisColor(){return this._theme.shapeBase.z}set colorAlpha(e){this.setTheme({shapeHover:{x:Bl(this._theme.shapeHover.x,e),y:Bl(this._theme.shapeHover.y,e),z:Bl(this._theme.shapeHover.z,e),xyz:Bl(this._theme.shapeHover.xyz,e),f:Bl(this._theme.shapeHover.f,e)}})}get colorAlpha(){return(this._theme.shapeHover.x.a+this._theme.shapeHover.y.a+this._theme.shapeHover.z.a+this._theme.shapeHover.xyz.a+this._theme.shapeHover.f.a)/5}get _dragging(){return!this._hoverAxis&&!!this._selectedAxis}_getAxis(e){return e?e.node.name.split(":")[1]:""}_getIsPlane(e){return e?e.node.name.indexOf("plane")!==-1:!1}_hover(e){if(this._dragging)return;let s=new Set(this._hovering),i=!1,r=a=>{s.has(a)?s.delete(a):(this._hovering.add(a),this._shapes[a]?.hover(!0),i=!0)};if(this._hoverAxis=this._getAxis(e),this._hoverIsPlane=this._getIsPlane(e),this._hoverAxis)if(this._hoverAxis==="xyz")r("x"),r("y"),r("z"),r("xyz");else if(this._hoverIsPlane)switch(this._hoverAxis){case"x":r("y"),r("z"),r("yz");break;case"y":r("x"),r("z"),r("xz");break;case"z":r("x"),r("y"),r("xy");break}else r(this._hoverAxis);for(let a of s)this._hovering.delete(a),this._shapes[a]?.hover(!1),i=!0;i&&(this._renderUpdate=!0)}_createRay(e){if(this._camera.projection===ts)return qu.origin.copy(this._camera.entity.getPosition()),qu.direction.sub2(e,qu.origin).normalize(),qu;let s=this._camera.farClip-this._camera.nearClip;return qu.origin.sub2(e,Oh.copy(this._camera.entity.forward).mulScalar(s)),qu.direction.copy(this._camera.entity.forward),qu}_createPlane(e,s,i){let r=Oh.copy(this.facingDir),a=bH.normal.set(0,0,0);return s?a.copy(this._camera.entity.forward).mulScalar(-1):(a[e]=1,this._rootStartRot.transformVector(a,a),i&&($b.cross(a,r).normalize(),a.cross($b,a).normalize())),bH.setFromPointNormal(this._rootStartPos,a)}_dirFromAxis(e,s){return e==="f"?s.copy(this._camera.entity.forward).mulScalar(-1):(s.set(0,0,0),s[e]=1),s}_projectToAxis(e,s){Oh.set(0,0,0),Oh[s]=1,e.copy(Oh.mulScalar(Oh.dot(e)));let i=e[s];e.set(0,0,0),e[s]=i}_screenToPoint(e,s,i=!1,r=!1){let a=this._camera.screenToWorld(e,s,1),o=this._selectedAxis,l=this._createRay(a);return this._createPlane(o,i,r).intersectsRay(l,Zb),Zb}_drawGuideLines(e,s,i,r){for(let a of Y9){if(i==="xyz"){this._drawSpanLine(e,s,a);continue}r?a!==i&&this._drawSpanLine(e,s,a):a===i&&this._drawSpanLine(e,s,a)}}_drawSpanLine(e,s,i){let r=this._dirFromAxis(i,Oh),a=this._theme.guideBase[i],o=Oh.copy(r).mulScalar(this._camera.farClip-this._camera.nearClip),l=$b.copy(o).mulScalar(-1);if(s.transformVector(o,o).add(e),s.transformVector(l,l).add(e),this._theme.guideOcclusion<1){let h=X9.copy(a);h.a*=1-this._theme.guideOcclusion,this._app.drawLine(o,l,h,!1,this._layer)}a.a!==0&&this._app.drawLine(o,l,a,!0)}_createTransform(){for(let e in this._shapes){let s=this._shapes[e];this.root.addChild(s.entity),this.intersectShapes.push(s);for(let i=0;i 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;e0?"1":"0"),this._material.setParameter("uDepth",this._depth),this._material.setParameter("uColor",s.toArray()),this._material.cull=this._cull,this._material.blendType=ls,this._material.update();let i=[];for(let r=0;r{this._storeNodePositions(),this._drag(!0)}),this.on(is.EVENT_TRANSFORMMOVE,i=>{let r=j9.copy(i).sub(this._selectionStartPoint);this.snap&&(r.mulScalar(1/this.snapIncrement),r.round(),r.mulScalar(this.snapIncrement)),this._setNodePositions(r)}),this.on(is.EVENT_TRANSFORMEND,()=>{this._drag(!1)}),this.on(is.EVENT_NODESDETACH,()=>{this._nodeLocalPositions.clear(),this._nodePositions.clear()})}set axisGap(e){this._setArrowProp("gap",e)}get axisGap(){return this._shapes.x.gap}set axisLineThickness(e){this._setArrowProp("lineThickness",e)}get axisLineThickness(){return this._shapes.x.lineThickness}set axisLineLength(e){this._setArrowProp("lineLength",e)}get axisLineLength(){return this._shapes.x.lineLength}set axisLineTolerance(e){this._setArrowProp("tolerance",e)}get axisLineTolerance(){return this._shapes.x.tolerance}set axisArrowThickness(e){this._setArrowProp("arrowThickness",e)}get axisArrowThickness(){return this._shapes.x.arrowThickness}set axisArrowLength(e){this._setArrowProp("arrowLength",e)}get axisArrowLength(){return this._shapes.x.arrowLength}set axisPlaneSize(e){this._setPlaneProp("size",e)}get axisPlaneSize(){return this._shapes.yz.size}set axisPlaneGap(e){this._setPlaneProp("gap",e)}get axisPlaneGap(){return this._shapes.yz.gap}set axisCenterSize(e){this._shapes.xyz.radius=e}get axisCenterSize(){return this._shapes.xyz.radius}set flipShapes(e){this.flipPlanes=e}get flipShapes(){return this.flipPlanes}_setArrowProp(e,s){this._shapes.x[e]=s,this._shapes.y[e]=s,this._shapes.z[e]=s}_setPlaneProp(e,s){this._shapes.yz[e]=s,this._shapes.xz[e]=s,this._shapes.xy[e]=s}_shapesLookAtCamera(){let e=this.cameraDir,s=!1,i,r;i=e.dot(this.root.right),r=1-Math.abs(i)>gg,this._shapes.x.entity.enabled!==r&&(this._shapes.x.entity.enabled=r,s=!0),i=e.dot(this.root.up),r=1-Math.abs(i)>gg,this._shapes.y.entity.enabled!==r&&(this._shapes.y.entity.enabled=r,s=!0),i=e.dot(this.root.forward),r=1-Math.abs(i)>gg,this._shapes.z.entity.enabled!==r&&(this._shapes.z.entity.enabled=r,s=!0);let a;ti.cross(e,this.root.right),r=1-ti.length()>gg,this._shapes.yz.entity.enabled!==r&&(this._shapes.yz.entity.enabled=r,s=!0),a=this.flipPlanes?fo.set(0,+(ti.dot(this.root.forward)<0),+(ti.dot(this.root.up)<0)):x.ZERO,this._shapes.yz.flipped.equals(a)||(this._shapes.yz.flipped=a,s=!0),ti.cross(e,this.root.forward),r=1-ti.length()>gg,this._shapes.xy.entity.enabled!==r&&(this._shapes.xy.entity.enabled=r,s=!0),a=this.flipPlanes?fo.set(+(ti.dot(this.root.up)<0),+(ti.dot(this.root.right)>0),0):x.ZERO,this._shapes.xy.flipped.equals(a)||(this._shapes.xy.flipped=a,s=!0),ti.cross(e,this.root.up),r=1-ti.length()>gg,this._shapes.xz.entity.enabled!==r&&(this._shapes.xz.entity.enabled=r,s=!0),a=this.flipPlanes?fo.set(+(ti.dot(this.root.forward)>0),0,+(ti.dot(this.root.right)>0)):x.ZERO,this._shapes.xz.flipped.equals(a)||(this._shapes.xz.flipped=a,s=!0),s&&(this._renderUpdate=!0)}_drag(e){for(let s in this._shapes){let i=this._shapes[s];switch(this.dragMode){case"show":continue;case"hide":{i.visible=!e;continue}case"selected":{if(this._selectedAxis==="xyz"){i.visible=e?s.length===1:!0;continue}if(this._selectedIsPlane){i.visible=e?s.length===1&&!s.includes(this._selectedAxis):!0;continue}i.visible=e?s===this._selectedAxis:!0}}}this._renderUpdate=!0}_storeNodePositions(){for(let e=0;e{this._app.root.addChild(i.entity),i.entity.enabled=!1}),this.on(is.EVENT_TRANSFORMSTART,(i,r,a)=>{this._screenPos.set(r,a),this._screenStartPos.set(r,a),this._selectionStartAngle=this._calculateArcAngle(i,r,a),this._storeNodeRotations(),this._storeGuidePoints(),this._drag(!0),this._angleGuide(!0)}),this.on(is.EVENT_TRANSFORMMOVE,(i,r,a)=>{let o=this._selectedAxis;if(o)if(this._screenPos.set(r,a),o==="xyz"){let l=Ke.copy(this.facingDir),h=$u.copy(i).sub(this._selectionStartPoint),f=Ke.cross(l,h).normalize(),u=this._screenPos.distance(this._screenStartPos);this._setNodeRotations(o,f,u)}else{let l=this._calculateArcAngle(i,r,a)-this._selectionStartAngle;this.snap&&(l=Math.round(l/this.snapIncrement)*this.snapIncrement);let h=this._dirFromAxis(o,Ke);this._setNodeRotations(o,h,l),this._updateGuidePoints(l),this._angleGuide(!0)}}),this.on(is.EVENT_TRANSFORMEND,()=>{this._drag(!1),this._angleGuide(!1)}),this.on(is.EVENT_NODESDETACH,()=>{this._nodeLocalRotations.clear(),this._nodeRotations.clear(),this._nodeOffsets.clear()})}set xyzTubeRadius(e){this._setDiskProp("tubeRadius",e)}get xyzTubeRadius(){return this._shapes.x.tubeRadius}set xyzRingRadius(e){this._setDiskProp("ringRadius",e)}get xyzRingRadius(){return this._shapes.x.ringRadius}set faceTubeRadius(e){this._shapes.f.tubeRadius=e}get faceTubeRadius(){return this._shapes.f.tubeRadius}set faceRingRadius(e){this._shapes.f.ringRadius=e}get faceRingRadius(){return this._shapes.f.ringRadius}set centerRadius(e){this._shapes.xyz.radius=e}get centerRadius(){return this._shapes.xyz.radius}set ringTolerance(e){this._setDiskProp("tolerance",e),this._shapes.f.tolerance=e}get ringTolerance(){return this._shapes.x.tolerance}set angleGuideThickness(e){this._guideAngleLines[0].thickness=e,this._guideAngleLines[1].thickness=e}get angleGuideThickness(){return this._guideAngleLines[0].thickness}set orbitRotation(e){this.rotationMode=e?"orbit":"absolute"}get orbitRotation(){return this.rotationMode==="orbit"}_setDiskProp(e,s){this._shapes.x[e]=s,this._shapes.y[e]=s,this._shapes.z[e]=s}_storeGuidePoints(){let e=this.root.getLocalPosition(),r=this._selectedAxis==="f"?this.faceRingRadius:this.xyzRingRadius;this._guideAngleStart.copy(this._selectionStartPoint).sub(e).normalize(),this._guideAngleStart.mulScalar(r),this._guideAngleEnd.copy(this._guideAngleStart)}_updateGuidePoints(e){let s=this._selectedAxis;s==="f"?Ke.copy(this.facingDir):(Ke.set(0,0,0),Ke[s]=1,this._rootStartRot.transformVector(Ke,Ke)),Sa.setFromAxisAngle(Ke,e),Sa.transformVector(this._guideAngleStart,this._guideAngleEnd),this._renderUpdate=!0}_angleGuide(e){let s=this._selectedAxis;if(e&&this.dragMode!=="show"&&s!=="xyz"){let i=this.root.getLocalPosition(),r=this._theme.shapeHover[s],a=J9.copy(r);a.a*=.3,this._guideAngleLines[0].draw(i,Ke.copy(this._guideAngleStart).add(i),this._scale,a),this._guideAngleLines[1].draw(i,Ke.copy(this._guideAngleEnd).add(i),this._scale,r),this._guideAngleLines[0].entity.enabled=!0,this._guideAngleLines[1].entity.enabled=!0}else this._guideAngleLines[0].entity.enabled=!1,this._guideAngleLines[1].entity.enabled=!1}_shapesLookAtCamera(){if(this._camera.projection===ts){let a=this._camera.entity.getPosition().sub(this.root.getPosition()).normalize(),o=Math.atan2(-a.y,Math.sqrt(a.x*a.x+a.z*a.z))*R.RAD_TO_DEG,l=Math.atan2(-a.x,-a.z)*R.RAD_TO_DEG;this._shapes.f.entity.setEulerAngles(-o+90,l,0)}else Sa.copy(this._camera.entity.getRotation()).getEulerAngles(Ke),this._shapes.f.entity.setEulerAngles(Ke),this._shapes.f.entity.rotateLocal(-90,0,0);let e,s,i,r=Ke.copy(this.facingDir);Sa.copy(this.root.getRotation()).invert().transformVector(r,r),e=Math.atan2(r.z,r.y)*R.RAD_TO_DEG,this._shapes.x.entity.setLocalEulerAngles(0,e-90,-90),e=Math.atan2(r.x,r.z)*R.RAD_TO_DEG,this._shapes.y.entity.setLocalEulerAngles(0,e,0),e=Math.atan2(r.y,r.x)*R.RAD_TO_DEG,this._shapes.z.entity.setLocalEulerAngles(90,0,e+90),this._dragging||(s=r.dot(this.root.right),i=1-Math.abs(s)>fC,this._shapes.x.show(i?"sector":"ring"),s=r.dot(this.root.up),i=1-Math.abs(s)>fC,this._shapes.y.show(i?"sector":"ring"),s=r.dot(this.root.forward),i=1-Math.abs(s)>fC,this._shapes.z.show(i?"sector":"ring")),r.equalsApprox(this._facingDir,e7)||(this._facingDir.copy(r),this._renderUpdate=!0)}_drag(e){for(let s in this._shapes){let i=this._shapes[s];if(i instanceof Nh)switch(this.dragMode){case"show":break;case"hide":{i.show(e?s===this._selectedAxis?"ring":"none":"sector");continue}case"selected":{i.show(e&&s===this._selectedAxis?"ring":"sector");break}}}this._renderUpdate=!0}_storeNodeRotations(){let e=this.root.getLocalPosition();for(let s=0;s1-fC)Ke.set(this._screenStartPos.y>=$u.y?1:-1,this._screenStartPos.x>=$u.x?-1:1,0).normalize();else{let u=Ke.cross(o.normal,h).normalize();this._camera.worldToScreen(u.add(r),NH),Ke.sub2(NH,$u).normalize()}$u.set(s,i,0),l=Ke.dot($u);break}case"orbit":{switch(Ke.sub2(e,r),a){case"x":{Sa.copy(this._rootStartRot).invert().transformVector(Ke,Ke),l=Math.atan2(Ke.z,Ke.y)*R.RAD_TO_DEG;break}case"y":{Sa.copy(this._rootStartRot).invert().transformVector(Ke,Ke),l=Math.atan2(Ke.x,Ke.z)*R.RAD_TO_DEG;break}case"z":{Sa.copy(this._rootStartRot).invert().transformVector(Ke,Ke),l=Math.atan2(Ke.y,Ke.x)*R.RAD_TO_DEG;break}case"f":{Sa.copy(this._camera.entity.getRotation()).invert().transformVector(Ke,Ke),l=Math.sign(f)*Math.atan2(Ke.y,Ke.x)*R.RAD_TO_DEG;break}}Ke.sub2(e,this._camera.entity.getPosition()).normalize().dot(this._camera.entity.forward)<0&&(l+=180);break}}return l}_drawGuideLines(e,s,i,r){for(let a of t7)i!=="xyz"&&(r?a!==i&&this._drawSpanLine(e,s,a):a===i&&this._drawSpanLine(e,s,a))}prerender(){super.prerender(),this.enabled&&this._shapesLookAtCamera()}destroy(){this._guideAngleLines.forEach(e=>e.destroy()),super.destroy()}};var dC=class extends hr{constructor(e,s={}){super(e,"boxCenter",s);n(this,"_size",.06);this._size=s.size??this._size,this.triData=[new ui(new ci,2)],this._createRenderComponent(this.entity,[_e.fromGeometry(this.device,new ci)]),this._update()}set size(e){this._size=e??this._size,this._update()}get size(){return this._size}_update(){this.entity.setLocalScale(this._size,this._size,this._size)}};var Zu=new x,pC=new x,mC=new $,Sg=class extends hr{constructor(e,s={}){super(e,"boxLine",s);n(this,"_gap",0);n(this,"_lineThickness",.02);n(this,"_lineLength",.5);n(this,"_boxSize",.12);n(this,"_tolerance",.1);n(this,"_box");n(this,"_line");n(this,"_flipped",!1);this._gap=s.gap??this._gap,this._lineThickness=s.lineThickness??this._lineThickness,this._lineLength=s.lineLength??this._lineLength,this._boxSize=s.boxSize??this._boxSize,this._tolerance=s.tolerance??this._tolerance,this.triData=[new ui(new ci),new ui(new Ci,1)],this._box=new Ne(`box:${this.axis}`),this.entity.addChild(this._box),this._createRenderComponent(this._box,[_e.fromGeometry(this.device,new ci)]),this._line=new Ne(`line:${this.axis}`),this.entity.addChild(this._line),this._createRenderComponent(this._line,[_e.fromGeometry(this.device,new Ci)]),this._update()}set gap(e){this._gap=e??this._gap,this._update()}get gap(){return this._gap}set lineThickness(e){this._lineThickness=e??this._lineThickness,this._update()}get lineThickness(){return this._lineThickness}set lineLength(e){this._lineLength=e??this._lineLength,this._update()}get lineLength(){return this._lineLength}set boxSize(e){this._boxSize=e??this._boxSize,this._update()}get boxSize(){return this._boxSize}set tolerance(e){this._tolerance=e,this._update()}get tolerance(){return this._tolerance}set flipped(e){this._flipped!==e&&(this._flipped=e,this._rotation.equals(x.ZERO)?Zu.set(0,0,this._flipped?180:0):Zu.copy(this._rotation).mulScalar(this._flipped?-1:1),this._line.enabled=!this._flipped,this.entity.setLocalEulerAngles(Zu))}get flipped(){return this._flipped}_update(){Zu.set(0,this._gap+this._boxSize*.5+this._lineLength,0),mC.set(0,0,0,1),pC.set(this._boxSize,this._boxSize,this._boxSize),this.triData[0].setTransform(Zu,mC,pC),Zu.set(0,this._gap+this._lineLength*.5,0),mC.set(0,0,0,1),pC.set(this._lineThickness+this._tolerance,this._lineLength,this._lineThickness+this._tolerance),this.triData[1].setTransform(Zu,mC,pC),this._box.setLocalPosition(0,this._gap+this._boxSize*.5+this._lineLength,0),this._box.setLocalScale(this._boxSize,this._boxSize,this._boxSize),this._line.setLocalPosition(0,this._gap+this._lineLength*.5,0),this._line.setLocalScale(this._lineThickness,this._lineLength,this._lineThickness)}};var si=new x,_C=new x,xa=new x,s7=new x,i7=new $,xg=.01,gC=class extends is{constructor(e,s){super(e,s,"gizmo:scale");n(this,"_shapes",{xyz:new dC(this._device,{axis:"xyz",layers:[this._layer.id],defaultColor:this._theme.shapeBase.xyz,hoverColor:this._theme.shapeHover.xyz,disabledColor:this._theme.disabled}),yz:new un(this._device,{axis:"x",layers:[this._layer.id],rotation:new x(0,0,-90),defaultColor:this._theme.shapeBase.x,hoverColor:this._theme.shapeHover.x,disabledColor:this._theme.disabled,depth:1}),xz:new un(this._device,{axis:"y",layers:[this._layer.id],rotation:new x(0,0,0),defaultColor:this._theme.shapeBase.y,hoverColor:this._theme.shapeHover.y,disabledColor:this._theme.disabled,depth:1}),xy:new un(this._device,{axis:"z",layers:[this._layer.id],rotation:new x(90,0,0),defaultColor:this._theme.shapeBase.z,hoverColor:this._theme.shapeHover.z,disabledColor:this._theme.disabled,depth:1}),x:new Sg(this._device,{axis:"x",layers:[this._layer.id],rotation:new x(0,0,-90),defaultColor:this._theme.shapeBase.x,hoverColor:this._theme.shapeHover.x,disabledColor:this._theme.disabled}),y:new Sg(this._device,{axis:"y",layers:[this._layer.id],rotation:new x(0,0,0),defaultColor:this._theme.shapeBase.y,hoverColor:this._theme.shapeHover.y,disabledColor:this._theme.disabled}),z:new Sg(this._device,{axis:"z",layers:[this._layer.id],rotation:new x(90,0,0),defaultColor:this._theme.shapeBase.z,hoverColor:this._theme.shapeHover.z,disabledColor:this._theme.disabled})});n(this,"_coordSpace","local");n(this,"_nodeScales",new Map);n(this,"_uniform",!1);n(this,"snapIncrement",1);n(this,"flipPlanes",!0);n(this,"lowerBoundScale",new x(-1/0,-1/0,-1/0));this._createTransform(),this.on(is.EVENT_TRANSFORMSTART,()=>{this._storeNodeScales(),this._drag(!0)}),this.on(is.EVENT_TRANSFORMMOVE,i=>{let r=s7.copy(i).sub(this._selectionStartPoint);this.snap&&(r.mulScalar(1/this.snapIncrement),r.round(),r.mulScalar(this.snapIncrement)),r.mulScalar(1/this._scale),this._setNodeScales(r.add(x.ONE))}),this.on(is.EVENT_TRANSFORMEND,()=>{this._drag(!1)}),this.on(is.EVENT_NODESDETACH,()=>{this._nodeScales.clear()})}set coordSpace(e){}get coordSpace(){return this._coordSpace}set uniform(e){this._uniform=e??this._uniform}get uniform(){return this._uniform}set axisGap(e){this._setArrowProp("gap",e)}get axisGap(){return this._shapes.x.gap}set axisLineThickness(e){this._setArrowProp("lineThickness",e)}get axisLineThickness(){return this._shapes.x.lineThickness}set axisLineLength(e){this._setArrowProp("lineLength",e)}get axisLineLength(){return this._shapes.x.lineLength}set axisLineTolerance(e){this._setArrowProp("tolerance",e)}get axisLineTolerance(){return this._shapes.x.tolerance}set axisBoxSize(e){this._setArrowProp("boxSize",e)}get axisBoxSize(){return this._shapes.x.boxSize}set axisPlaneSize(e){this._setPlaneProp("size",e)}get axisPlaneSize(){return this._shapes.yz.size}set axisPlaneGap(e){this._setPlaneProp("gap",e)}get axisPlaneGap(){return this._shapes.yz.gap}set axisCenterSize(e){this._shapes.xyz.size=e}get axisCenterSize(){return this._shapes.xyz.size}set flipShapes(e){this.flipPlanes=e}get flipShapes(){return this.flipPlanes}_setArrowProp(e,s){this._shapes.x[e]=s,this._shapes.y[e]=s,this._shapes.z[e]=s}_setPlaneProp(e,s){this._shapes.yz[e]=s,this._shapes.xz[e]=s,this._shapes.xy[e]=s}_shapesLookAtCamera(){let e=this.cameraDir,s=!1,i,r;i=e.dot(this.root.right),r=1-Math.abs(i)>xg,this._shapes.x.entity.enabled!==r&&(this._shapes.x.entity.enabled=r,s=!0),i=e.dot(this.root.up),r=1-Math.abs(i)>xg,this._shapes.y.entity.enabled!==r&&(this._shapes.y.entity.enabled=r,s=!0),i=e.dot(this.root.forward),r=1-Math.abs(i)>xg,this._shapes.z.entity.enabled!==r&&(this._shapes.z.entity.enabled=r,s=!0);let a;si.cross(e,this.root.right),r=1-si.length()>xg,this._shapes.yz.entity.enabled!==r&&(this._shapes.yz.entity.enabled=r,s=!0),a=this.flipPlanes?_C.set(0,+(si.dot(this.root.forward)<0),+(si.dot(this.root.up)<0)):x.ZERO,this._shapes.yz.flipped.equals(a)||(this._shapes.yz.flipped=a,s=!0),si.cross(e,this.root.forward),r=1-si.length()>xg,this._shapes.xy.entity.enabled!==r&&(this._shapes.xy.entity.enabled=r,s=!0),a=this.flipPlanes?_C.set(+(si.dot(this.root.up)<0),+(si.dot(this.root.right)>0),0):x.ZERO,this._shapes.xy.flipped.equals(a)||(this._shapes.xy.flipped=a,s=!0),si.cross(e,this.root.up),r=1-si.length()>xg,this._shapes.xz.entity.enabled!==r&&(this._shapes.xz.entity.enabled=r,s=!0),a=this.flipPlanes?_C.set(+(si.dot(this.root.forward)>0),0,+(si.dot(this.root.right)>0)):x.ZERO,this._shapes.xz.flipped.equals(a)||(this._shapes.xz.flipped=a,s=!0),s&&(this._renderUpdate=!0)}_drag(e){for(let s in this._shapes){let i=this._shapes[s];switch(this.dragMode){case"show":continue;case"hide":{i.visible=!e;continue}case"selected":{if(this._selectedAxis==="xyz"){i.visible=e?s.length===1:!0;continue}if(this._selectedIsPlane){i.visible=e?s.length===1&&!s.includes(this._selectedAxis):!0;continue}i.visible=e?s===this._selectedAxis:!0;continue}}}this._renderUpdate=!0}_storeNodeScales(){for(let e=0;e{this.fire(Gl.EVENT_CAMERAALIGN,x.RIGHT)}),this._shapes.py.children[0].addEventListener("pointerdown",()=>{this.fire(Gl.EVENT_CAMERAALIGN,x.UP)}),this._shapes.pz.children[0].addEventListener("pointerdown",()=>{this.fire(Gl.EVENT_CAMERAALIGN,x.BACK)}),this._shapes.nx.children[0].addEventListener("pointerdown",()=>{this.fire(Gl.EVENT_CAMERAALIGN,x.LEFT)}),this._shapes.ny.children[0].addEventListener("pointerdown",()=>{this.fire(Gl.EVENT_CAMERAALIGN,x.DOWN)}),this._shapes.nz.children[0].addEventListener("pointerdown",()=>{this.fire(Gl.EVENT_CAMERAALIGN,x.FORWARD)}),this.dom.appendChild(this._svg)}set anchor(e){this._anchor.copy(e),this.dom.style.top=this._anchor.x?"0px":"auto",this.dom.style.right=this._anchor.y?"0px":"auto",this.dom.style.bottom=this._anchor.z?"0px":"auto",this.dom.style.left=this._anchor.w?"0px":"auto"}get anchor(){return this._anchor}set colorX(e){this._colorX.copy(e),this._shapes.px.children[0].setAttribute("fill",this._colorX.toString(!1)),this._shapes.px.children[0].setAttribute("stroke",this._colorX.toString(!1)),this._shapes.nx.children[0].setAttribute("stroke",this._colorX.toString(!1)),this._shapes.xaxis.setAttribute("stroke",this._colorX.toString(!1))}get colorX(){return this._colorX}set colorY(e){this._colorY.copy(e),this._shapes.py.children[0].setAttribute("fill",this._colorY.toString(!1)),this._shapes.py.children[0].setAttribute("stroke",this._colorY.toString(!1)),this._shapes.ny.children[0].setAttribute("stroke",this._colorY.toString(!1)),this._shapes.yaxis.setAttribute("stroke",this._colorY.toString(!1))}get colorY(){return this._colorY}set colorZ(e){this._colorZ.copy(e),this._shapes.pz.children[0].setAttribute("fill",this._colorZ.toString(!1)),this._shapes.pz.children[0].setAttribute("stroke",this._colorZ.toString(!1)),this._shapes.nz.children[0].setAttribute("stroke",this._colorZ.toString(!1)),this._shapes.zaxis.setAttribute("stroke",this._colorZ.toString(!1))}get colorZ(){return this._colorZ}set colorNeg(e){this._colorNeg.copy(e),this._shapes.px.children[0].setAttribute("fill",this._colorNeg.toString(!1)),this._shapes.py.children[0].setAttribute("fill",this._colorNeg.toString(!1)),this._shapes.pz.children[0].setAttribute("fill",this._colorNeg.toString(!1))}get colorNeg(){return this._colorNeg}set radius(e){this._radius=e,this._shapes.px.children[0].setAttribute("r",`${e}`),this._shapes.py.children[0].setAttribute("r",`${e}`),this._shapes.pz.children[0].setAttribute("r",`${e}`),this._shapes.nx.children[0].setAttribute("r",`${e}`),this._shapes.ny.children[0].setAttribute("r",`${e}`),this._shapes.nz.children[0].setAttribute("r",`${e}`),this._resize()}get radius(){return this._radius}set textSize(e){this._textSize=e,this._shapes.px.children[1].setAttribute("font-size",`${e}`),this._shapes.py.children[1].setAttribute("font-size",`${e}`),this._shapes.pz.children[1].setAttribute("font-size",`${e}`)}get textSize(){return this._textSize}set lineThickness(e){this._lineThickness=e,this._shapes.xaxis.setAttribute("stroke-width",`${e}`),this._shapes.yaxis.setAttribute("stroke-width",`${e}`),this._shapes.zaxis.setAttribute("stroke-width",`${e}`),this._shapes.px.children[0].setAttribute("stroke-width",`${e}`),this._shapes.py.children[0].setAttribute("stroke-width",`${e}`),this._shapes.pz.children[0].setAttribute("stroke-width",`${e}`),this._shapes.nx.children[0].setAttribute("stroke-width",`${e}`),this._shapes.ny.children[0].setAttribute("stroke-width",`${e}`),this._shapes.nz.children[0].setAttribute("stroke-width",`${e}`),this._resize()}get lineThickness(){return this._lineThickness}set lineLength(e){this._lineLength=e,this._resize()}get lineLength(){return this._lineLength}_resize(){this._size=2*(this.lineLength+this.radius+this.lineThickness),this.dom.style.width=`${this._size}px`,this.dom.style.height=`${this._size}px`,this._svg.setAttribute("width",`${this._size}`),this._svg.setAttribute("height",`${this._size}`),this._group.setAttribute("transform",`translate(${this._size*.5}, ${this._size*.5})`)}_transform(e,s,i){e.setAttribute("transform",`translate(${s*this._lineLength}, ${i*this._lineLength})`)}_x2y2(e,s,i){e.setAttribute("x2",`${s*this._lineLength}`),e.setAttribute("y2",`${i*this._lineLength}`)}_line(e){let s=document.createElementNS(this._svg.namespaceURI,"line");return s.setAttribute("stroke",e),s.setAttribute("stroke-width",`${this._lineThickness}`),this._group.appendChild(s),s}_circle(e,s=!1,i){let r=document.createElementNS(this._svg.namespaceURI,"g"),a=document.createElementNS(this._svg.namespaceURI,"circle");if(a.setAttribute("fill",s?e:this._colorNeg.toString(!1)),a.setAttribute("stroke",e),a.setAttribute("stroke-width",`${this._lineThickness}`),a.setAttribute("r",`${this._radius}`),a.setAttribute("cx","0"),a.setAttribute("cy","0"),a.setAttribute("pointer-events","all"),r.appendChild(a),i){let o=document.createElementNS(this._svg.namespaceURI,"text");o.setAttribute("font-size",`${this._textSize}`),o.setAttribute("font-family","Arial"),o.setAttribute("font-weight","bold"),o.setAttribute("text-anchor","middle"),o.setAttribute("alignment-baseline","central"),o.textContent=i,r.appendChild(o)}return r.setAttribute("cursor","pointer"),this._group.appendChild(r),r}update(e){if(!this._size)return;SC.invert(e),SC.getX(Ul),SC.getY(kl),SC.getZ(zl),this._transform(this._shapes.px,Ul.x,-Ul.y),this._transform(this._shapes.nx,-Ul.x,Ul.y),this._transform(this._shapes.py,kl.x,-kl.y),this._transform(this._shapes.ny,-kl.x,kl.y),this._transform(this._shapes.pz,zl.x,-zl.y),this._transform(this._shapes.nz,-zl.x,zl.y),this._x2y2(this._shapes.xaxis,Ul.x,-Ul.y),this._x2y2(this._shapes.yaxis,kl.x,-kl.y),this._x2y2(this._shapes.zaxis,zl.x,-zl.y);let s=[{n:["xaxis","px"],value:Ul.z},{n:["yaxis","py"],value:kl.z},{n:["zaxis","pz"],value:zl.z},{n:["nx"],value:-Ul.z},{n:["ny"],value:-kl.z},{n:["nz"],value:-zl.z}].sort((r,a)=>r.value-a.value),i=document.createDocumentFragment();s.forEach(r=>{r.n.forEach(a=>{i.appendChild(this._shapes[a])})}),this._group.appendChild(i)}destroy(){this.dom.remove(),this.off()}};n(Gl,"EVENT_CAMERAALIGN","camera:align");var xC=Gl;return WH(r7);})(); for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(pc))) { Object.defineProperty(exports, key, descriptor.get ? { get: descriptor.get, set: (value) => Object.defineProperty(exports, key, { value, writable: true, enumerable: descriptor.enumerable, configurable: true }), enumerable: descriptor.enumerable, configurable: true } : descriptor); } }));