Cesium-Examples/libs/babylon/babylon.js
2025-03-19 11:00:22 +08:00

2 lines
4.9 MiB
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("babylonjs",[],t):"object"==typeof exports?exports.babylonjs=t():e.BABYLON=t()}("undefined"!=typeof self?self:"undefined"!=typeof global?global:this,(()=>(()=>{"use strict";var e={d:(t,i)=>{for(var r in i)e.o(i,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:i[r]})}};e.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),e.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),e.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var t={};e.d(t,{default:()=>YD});var i={};e.r(i),e.d(i,{AxesViewer:()=>Nh,BoneAxesViewer:()=>Fh,DebugLayer:()=>Lh,DebugLayerTab:()=>Mh,DirectionalLightFrustumViewer:()=>sp,PhysicsViewer:()=>np,RayHelper:()=>op,SkeletonViewer:()=>ap});var r={};e.r(r),e.d(r,{AbstractActionManager:()=>h,AbstractAssetTask:()=>YR,AbstractEngine:()=>Mi,AbstractMesh:()=>Uo,AbstractScene:()=>c,AcquireNativeObjectAsync:()=>df,Action:()=>ee,ActionEvent:()=>te,ActionManager:()=>be,AddBlock:()=>Ab,AddressMode:()=>Rf,AdvancedTimer:()=>jg,AlignBlock:()=>zS,AlphaState:()=>Ci,AmmoJSPlugin:()=>Bv,AnaglyphArcRotateCamera:()=>eu,AnaglyphFreeCamera:()=>tu,AnaglyphGamepadCamera:()=>iu,AnaglyphPostProcess:()=>Jc,AnaglyphUniversalCamera:()=>ru,Analyser:()=>ka,AndOrNotEvaluator:()=>Xe,Angle:()=>En,Animatable:()=>gn,AnimatedInputBlockTypes:()=>Zs,Animation:()=>at,AnimationAssetTask:()=>ZR,AnimationEvent:()=>kn,AnimationGroup:()=>zn,AnimationGroupMask:()=>Hn,AnimationGroupMaskMode:()=>bn,AnimationKeyInterpolation:()=>ge,AnimationPropertiesOverride:()=>yn,AnimationRange:()=>Se,AnisotropyBlock:()=>dT,ApplyPostProcess:()=>Rp,Arc2:()=>Sn,ArcFollowCamera:()=>Gc,ArcRotateCamera:()=>Nc,ArcRotateCameraGamepadInput:()=>lc,ArcRotateCameraInputsManager:()=>dc,ArcRotateCameraKeyboardMoveInput:()=>cc,ArcRotateCameraMouseWheelInput:()=>uc,ArcRotateCameraPointersInput:()=>hc,ArcRotateCameraVRDeviceOrientationInput:()=>pc,ArcTan2Block:()=>Kb,AssetContainer:()=>Va,AssetTaskState:()=>HR,AssetsManager:()=>oP,AssetsProgressEvent:()=>KR,AsyncLoop:()=>or,AttachToBoxBehavior:()=>cs,AudioEngine:()=>Oo,AudioSceneComponent:()=>Wa,AutoLayoutMode:()=>Uf,AutoReleaseWorkerPool:()=>yg,AutoRotationBehavior:()=>os,AxesViewer:()=>Nh,Axis:()=>_n,AxisDragGizmo:()=>Dh,AxisScaleGizmo:()=>mm,BRDFTextureTools:()=>Gm,BabylonFileLoaderConfiguration:()=>Hv,BackEase:()=>In,BackgroundMaterial:()=>Lm,BakedVertexAnimationManager:()=>Xa,BallAndSocketConstraint:()=>GA,BaseCameraMouseWheelInput:()=>tc,BaseCameraPointersInput:()=>ic,BaseError:()=>vt,BaseParticleSystem:()=>vl,BaseSixDofDragBehavior:()=>ys,BaseTexture:()=>Ya,BasisFileInfo:()=>Ry,BasisTools:()=>Uy,BasisToolsOptions:()=>Iy,BasisTranscodeConfiguration:()=>Py,BezierCurve:()=>Tn,BezierCurveEase:()=>Vn,BiPlanarBlock:()=>PT,BinaryFileAssetTask:()=>$R,BindBonesParameters:()=>na,BindFogParameters:()=>Qo,BindLight:()=>aa,BindLightProperties:()=>oa,BindLights:()=>sa,BindLogDepth:()=>Ko,BindMorphTargetParameters:()=>$o,BindSceneUniformBuffer:()=>ea,BindTextureMatrix:()=>ia,BlackAndWhitePostProcess:()=>gC,BlendFactor:()=>Wf,BlendOperation:()=>Hf,BloomEffect:()=>TC,BloomMergePostProcess:()=>bC,BlurPostProcess:()=>Om,Bone:()=>mn,BoneAxesViewer:()=>Fh,BoneIKController:()=>Zl,BoneLookController:()=>Jl,BonesBlock:()=>qy,BooleanGeometryBlock:()=>cx,BooleanGeometryOperations:()=>sx,BounceEase:()=>Mn,BouncingBehavior:()=>as,BoundingBlock:()=>lx,BoundingBox:()=>to,BoundingBoxGizmo:()=>gm,BoundingBoxRenderer:()=>cR,BoundingInfo:()=>so,BoundingSphere:()=>io,BoxBlock:()=>iS,BoxBuilder:()=>Vh,BoxParticleEmitter:()=>Dx,Buffer:()=>Dr,BufferBindingType:()=>Df,BufferMapState:()=>yf,BufferUsage:()=>bf,CSG:()=>EE,Camera:()=>$n,CameraGizmo:()=>Mm,CameraInputTypes:()=>rc,CameraInputsManager:()=>nc,CannonJSPlugin:()=>Lv,CanvasAlphaMode:()=>e_,CapsuleBlock:()=>dS,CapsuleBuilder:()=>Xh,CascadedShadowGenerator:()=>Tv,ChromaticAberrationPostProcess:()=>EC,CircleEase:()=>Pn,CircleOfConfusionPostProcess:()=>SC,ClampBlock:()=>Rb,ClearCoatBlock:()=>fT,ClipPlanesBlock:()=>Tb,ClipboardEventTypes:()=>fm,ClipboardInfo:()=>_m,CloudBlock:()=>xT,CloudPoint:()=>mA,Collider:()=>fh,Color3:()=>Z,Color3Gradient:()=>jx,Color4:()=>J,ColorCorrectionPostProcess:()=>xC,ColorCurves:()=>ur,ColorGradient:()=>Xx,ColorGradingTexture:()=>oy,ColorMergerBlock:()=>Db,ColorSplitterBlock:()=>yl,ColorWrite:()=>zf,CombineAction:()=>fe,CompareFunction:()=>Mf,CompatibilityOptions:()=>go,CompilationMessageType:()=>wf,CompleteGreasedLineColorTable:()=>QE,CompleteGreasedLineWidthTable:()=>KE,ComputeBindingType:()=>mh,ComputeEffect:()=>gh,ComputeNormalsBlock:()=>OS,ComputePassTimestampLocation:()=>Qf,ComputeShader:()=>yh,ComputeShaderParticleSystem:()=>Hx,Condition:()=>ie,ConditionBlock:()=>AS,ConditionBlockTests:()=>ES,ConditionalBlock:()=>ST,ConditionalBlockConditions:()=>TT,ConeParticleEmitter:()=>Nx,Constants:()=>u,ContainerAssetTask:()=>QR,ConversionMode:()=>PR,ConvolutionPostProcess:()=>AC,Coordinate:()=>fn,CopyTextureToTexture:()=>OR,CopyTools:()=>Za,CreateBox:()=>Uh,CreateBoxVertexData:()=>wh,CreateCapsule:()=>Hh,CreateCapsuleVertexData:()=>Wh,CreateCylinder:()=>xh,CreateCylinderVertexData:()=>Sh,CreateDashedLines:()=>_d,CreateDashedLinesVertexData:()=>dd,CreateDecal:()=>Wd,CreateDisc:()=>qh,CreateDiscVertexData:()=>Qh,CreateEnvTextureAsync:()=>Gp,CreateGeodesic:()=>Qd,CreateGoldberg:()=>Jd,CreateGoldbergVertexData:()=>Zd,CreateGreasedLine:()=>jE,CreateGreasedLineMaterial:()=>XE,CreateGround:()=>ih,CreateGroundFromHeightMap:()=>nh,CreateGroundFromHeightMapVertexData:()=>th,CreateGroundVertexData:()=>$u,CreateHemisphere:()=>Cm,CreateIcoSphere:()=>Bl,CreateIcoSphereVertexData:()=>wl,CreateImageBitmapFromSource:()=>Ao,CreateImageDataArrayBufferViews:()=>Wp,CreateLathe:()=>Id,CreateLineSystem:()=>pd,CreateLineSystemVertexData:()=>hd,CreateLines:()=>fd,CreatePlane:()=>fs,CreatePlaneVertexData:()=>ps,CreatePolygon:()=>Ed,CreatePolygonVertexData:()=>Td,CreatePolyhedron:()=>Fd,CreatePolyhedronVertexData:()=>Nd,CreateResizedCopy:()=>Cp,CreateRibbon:()=>Yh,CreateRibbonVertexData:()=>jh,CreateScreenshot:()=>PP,CreateScreenshotAsync:()=>IP,CreateScreenshotUsingRenderTarget:()=>OP,CreateScreenshotUsingRenderTargetAsync:()=>DP,CreateScreenshotWithResizeAsync:()=>MP,CreateSegmentedBoxVertexData:()=>Bh,CreateSphere:()=>Gh,CreateSphereVertexData:()=>kh,CreateText:()=>ip,CreateTextShapePaths:()=>tp,CreateTiledBox:()=>id,CreateTiledBoxVertexData:()=>td,CreateTiledGround:()=>rh,CreateTiledGroundVertexData:()=>eh,CreateTiledPlane:()=>$h,CreateTiledPlaneVertexData:()=>Jh,CreateTorus:()=>sh,CreateTorusKnot:()=>od,CreateTorusKnotVertexData:()=>nd,CreateTorusVertexData:()=>ah,CreateTube:()=>Od,CrossBlock:()=>Pb,CubeMapToSphericalPolynomialTools:()=>Lp,CubeTexture:()=>Nm,CubeTextureAssetTask:()=>iP,CubicEase:()=>On,CullMode:()=>Gf,CurrentScreenBlock:()=>nl,Curve3:()=>Cn,CurveBlock:()=>FT,CurveBlockTypes:()=>DT,CustomBlock:()=>Ib,CustomOptimization:()=>mP,CustomParticleEmitter:()=>kx,CustomProceduralTexture:()=>Wy,CylinderBlock:()=>hS,CylinderBuilder:()=>Ah,CylinderDirectedParticleEmitter:()=>Lx,CylinderParticleEmitter:()=>Fx,DDSTools:()=>hg,DataBuffer:()=>vr,DataReader:()=>BP,DataStorage:()=>UP,Database:()=>Ox,DebugBlock:()=>JS,DebugLayer:()=>Lh,DebugLayerTab:()=>Mh,DecalBuilder:()=>Hd,DecalMapConfiguration:()=>zT,DecalMapDefines:()=>GT,Decode:()=>St,DecodeBase64ToBinary:()=>Ct,DecodeBase64ToString:()=>At,DecodeBase64UrlToBinary:()=>Hi,DecodeBase64UrlToString:()=>ji,DeepCopier:()=>ye,DefaultCollisionCoordinator:()=>_h,DefaultKTX2DecoderOptions:()=>Eg,DefaultLoadingScreen:()=>xv,DefaultRenderingPipeline:()=>jC,Deferred:()=>aP,DepthCullingState:()=>Si,DepthOfFieldBlurPostProcess:()=>CC,DepthOfFieldEffect:()=>IC,DepthOfFieldEffectBlurLevel:()=>RC,DepthOfFieldMergePostProcess:()=>PC,DepthPeelingRenderer:()=>dR,DepthPeelingSceneComponent:()=>pR,DepthReducer:()=>_v,DepthRenderer:()=>pv,DepthRendererSceneComponent:()=>uR,DepthSortedParticle:()=>pA,DerivativeBlock:()=>ob,DesaturateBlock:()=>uT,DetailMapConfiguration:()=>Lu,DeviceInputEventType:()=>Mr,DeviceLostReason:()=>t_,DeviceOrientationCamera:()=>Fc,DeviceSource:()=>en,DeviceSourceManager:()=>rn,DeviceType:()=>Sr,DirectionalLight:()=>Am,DirectionalLightFrustumViewer:()=>sp,DiscBlock:()=>pS,DiscBuilder:()=>Zh,DiscardBlock:()=>rb,DisplayPassPostProcess:()=>MC,DistanceBlock:()=>Wb,DistanceConstraint:()=>zA,DistanceJoint:()=>Rs,DivideBlock:()=>Lb,DoNothingAction:()=>pe,DomManagement:()=>ft,DotBlock:()=>Mb,DracoCompression:()=>_E,DrawWrapper:()=>ho,DualSenseInput:()=>Rr,DualShockButton:()=>zc,DualShockDpad:()=>Wc,DualShockInput:()=>Cr,DualShockPad:()=>Xc,DumpTools:()=>Rl,DynamicFloat32Array:()=>YP,DynamicTexture:()=>Gu,EasingFunction:()=>Rn,EdgesRenderer:()=>_R,Effect:()=>Ei,EffectFallbacks:()=>ll,EffectLayer:()=>iv,EffectLayerSceneComponent:()=>rv,EffectRenderer:()=>Tl,EffectWrapper:()=>El,ElasticEase:()=>Dn,ElbowBlock:()=>CT,EncodeArrayBufferToBase64:()=>xt,EndsWith:()=>Tt,Engine:()=>Do,EngineFactory:()=>pm,EngineFormat:()=>mg,EngineInstrumentation:()=>ev,EngineStore:()=>M,EngineView:()=>pp,EnvironmentHelper:()=>wm,EnvironmentTextureTools:()=>Qp,Epsilon:()=>A,EquiRectangularCubeTexture:()=>ay,EquiRectangularCubeTextureAssetTask:()=>nP,ErrorCodes:()=>yt,ErrorFilter:()=>i_,EventConstants:()=>Qr,EventState:()=>d,ExecuteCodeAction:()=>_e,ExitFullscreen:()=>Po,ExitPointerlock:()=>Mo,ExponentialEase:()=>Nn,ExternalTexture:()=>w_,ExtractHighlightsPostProcess:()=>yC,ExtrudePolygon:()=>Sd,ExtrudeShape:()=>Ad,ExtrudeShapeCustom:()=>Cd,FactorGradient:()=>Yx,FadeInOutBehavior:()=>us,FeatureName:()=>vf,FileTools:()=>Xi,FileToolsOptions:()=>Li,FilesInput:()=>lP,FilesInputStore:()=>mt,FilterMode:()=>Pf,FilterPostProcess:()=>OC,FlowGraph:()=>SM,FlowGraphAbsBlock:()=>IO,FlowGraphAcosBlock:()=>aD,FlowGraphAcoshBlock:()=>pD,FlowGraphAddBlock:()=>vO,FlowGraphAsinBlock:()=>oD,FlowGraphAsinhBlock:()=>dD,FlowGraphAtan2Block:()=>lD,FlowGraphAtanBlock:()=>sD,FlowGraphAtanhBlock:()=>fD,FlowGraphBitwiseAndBlock:()=>DD,FlowGraphBitwiseLeftShiftBlock:()=>LD,FlowGraphBitwiseNotBlock:()=>OD,FlowGraphBitwiseOrBlock:()=>ND,FlowGraphBitwiseRightShiftBlock:()=>wD,FlowGraphBitwiseXorBlock:()=>FD,FlowGraphBlock:()=>fM,FlowGraphBranchBlock:()=>NM,FlowGraphCeilBlock:()=>NO,FlowGraphClampBlock:()=>zO,FlowGraphConditionalDataBlock:()=>QM,FlowGraphConnection:()=>YI,FlowGraphConnectionType:()=>HI,FlowGraphConsoleLogBlock:()=>RM,FlowGraphConstantBlock:()=>JM,FlowGraphContext:()=>yM,FlowGraphContextLogger:()=>AM,FlowGraphCoordinateTransformBlock:()=>ZM,FlowGraphCoordinator:()=>xM,FlowGraphCosBlock:()=>rD,FlowGraphCoshBlock:()=>uD,FlowGraphCountLeadingZerosBlock:()=>BD,FlowGraphCountOneBitsBlock:()=>VD,FlowGraphCountTrailingZerosBlock:()=>UD,FlowGraphCounterBlock:()=>GM,FlowGraphCrossBlock:()=>xD,FlowGraphCubeRootBlock:()=>bD,FlowGraphDataConnection:()=>cM,FlowGraphDebounceBlock:()=>WM,FlowGraphDegToRadBlock:()=>eD,FlowGraphDeterminantBlock:()=>PD,FlowGraphDivideBlock:()=>TO,FlowGraphDoNBlock:()=>FM,FlowGraphDotBlock:()=>SO,FlowGraphEBlock:()=>xO,FlowGraphEqBlock:()=>jO,FlowGraphEventBlock:()=>vM,FlowGraphExecutionBlock:()=>mM,FlowGraphExpBlock:()=>_D,FlowGraphFlipFlopBlock:()=>HM,FlowGraphFloorBlock:()=>DO,FlowGraphForLoopBlock:()=>LM,FlowGraphFractBlock:()=>FO,FlowGraphGetPropertyBlock:()=>$M,FlowGraphGetVariableBlock:()=>qM,FlowGraphGreaterThanBlock:()=>qO,FlowGraphGreaterThanOrEqualBlock:()=>ZO,FlowGraphInfBlock:()=>CO,FlowGraphInterpolateBlock:()=>XO,FlowGraphInvertMatrixBlock:()=>ID,FlowGraphIsInfBlock:()=>$O,FlowGraphIsNanBlock:()=>JO,FlowGraphLengthBlock:()=>ED,FlowGraphLessThanBlock:()=>KO,FlowGraphLessThanOrEqualBlock:()=>QO,FlowGraphLog10Block:()=>vD,FlowGraphLog2Block:()=>gD,FlowGraphLogBlock:()=>mD,FlowGraphLogicAndBlock:()=>cO,FlowGraphLogicNotBlock:()=>hO,FlowGraphLogicOrBlock:()=>uO,FlowGraphMatMulBlock:()=>MD,FlowGraphMaxBlock:()=>VO,FlowGraphMeshPickEventBlock:()=>EM,FlowGraphMinBlock:()=>UO,FlowGraphMultiGateBlock:()=>UM,FlowGraphMultiplyBlock:()=>bO,FlowGraphNaNBlock:()=>RO,FlowGraphNegBlock:()=>LO,FlowGraphNormalizeBlock:()=>SD,FlowGraphPauseAnimationBlock:()=>KM,FlowGraphPiBlock:()=>AO,FlowGraphPlayAnimationBlock:()=>jM,FlowGraphPowBlock:()=>TD,FlowGraphRadToDegBlock:()=>tD,FlowGraphRandomBlock:()=>EO,FlowGraphReceiveCustomEventBlock:()=>GD,FlowGraphRemainderBlock:()=>BO,FlowGraphRotate2DBlock:()=>AD,FlowGraphRotate3DBlock:()=>CD,FlowGraphSaturateBlock:()=>HO,FlowGraphSceneReadyEventBlock:()=>kD,FlowGraphSceneTickEventBlock:()=>zD,FlowGraphSendCustomEventBlock:()=>DM,FlowGraphSequenceBlock:()=>XM,FlowGraphSetPropertyBlock:()=>OM,FlowGraphSetVariableBlock:()=>PM,FlowGraphSignBlock:()=>MO,FlowGraphSignalConnection:()=>_M,FlowGraphSinBlock:()=>iD,FlowGraphSinhBlock:()=>cD,FlowGraphSqrtBlock:()=>yD,FlowGraphState:()=>TM,FlowGraphStopAnimationBlock:()=>YM,FlowGraphSubtractBlock:()=>yO,FlowGraphSwitchBlock:()=>VM,FlowGraphTanBlock:()=>nD,FlowGraphTanhBlock:()=>hD,FlowGraphThrottleBlock:()=>wM,FlowGraphTimerBlock:()=>BM,FlowGraphTransposeBlock:()=>RD,FlowGraphTruncBlock:()=>OO,FlowGraphWaitAllBlock:()=>kM,FlowGraphWhileLoopBlock:()=>zM,FluidRenderer:()=>wR,FluidRendererSceneComponent:()=>LR,FluidRenderingDebug:()=>SR,FluidRenderingObject:()=>AR,FluidRenderingObjectCustomParticles:()=>MR,FluidRenderingObjectParticleSystem:()=>CR,FluidRenderingTargetRenderer:()=>IR,FlyCamera:()=>wc,FlyCameraInputsManager:()=>Lc,FlyCameraKeyboardInput:()=>fc,FlyCameraMouseInput:()=>_c,FogBlock:()=>fb,FollowBehavior:()=>Es,FollowCamera:()=>kc,FollowCameraInputsManager:()=>Bc,FollowCameraKeyboardMoveInput:()=>mc,FollowCameraMouseWheelInput:()=>gc,FollowCameraPointersInput:()=>vc,FragCoordBlock:()=>ab,FragDepthBlock:()=>hb,FragmentOutputBlock:()=>qs,FramingBehavior:()=>ss,FreeCamera:()=>Oc,FreeCameraDeviceOrientationInput:()=>Ac,FreeCameraGamepadInput:()=>Rc,FreeCameraInputsManager:()=>xc,FreeCameraKeyboardMoveInput:()=>yc,FreeCameraMouseInput:()=>Tc,FreeCameraMouseWheelInput:()=>Ec,FreeCameraTouchInput:()=>Sc,FreeCameraVirtualJoystickInput:()=>Ic,FresnelBlock:()=>kb,FresnelParameters:()=>$v,FromHalfFloat:()=>Ip,FrontFace:()=>kf,FrontFacingBlock:()=>nb,Frustum:()=>ln,FxaaPostProcess:()=>DC,GIRSM:()=>kR,GIRSMManager:()=>GR,GIRSMRenderPluginMaterial:()=>WR,GPUParticleSystem:()=>sA,GUID:()=>qi,Gamepad:()=>ac,GamepadCamera:()=>Qc,GamepadManager:()=>jc,GamepadSystemSceneComponent:()=>Yc,GaussianSplattingMaterial:()=>aE,GaussianSplattingMesh:()=>Px,GenerateBase64StringFromPixelData:()=>Ka,GenerateBase64StringFromTexture:()=>Qa,GenerateBase64StringFromTextureAsync:()=>qa,GenericPad:()=>sc,GeodesicData:()=>Kd,Geometry:()=>vo,GeometryArcTan2Block:()=>ux,GeometryBufferRenderer:()=>BC,GeometryBufferRendererSceneComponent:()=>VC,GeometryClampBlock:()=>gx,GeometryCollectionBlock:()=>IS,GeometryCrossBlock:()=>yx,GeometryCurveBlock:()=>bx,GeometryCurveBlockTypes:()=>vx,GeometryDesaturateBlock:()=>Tx,GeometryDistanceBlock:()=>xx,GeometryDotBlock:()=>Ax,GeometryElbowBlock:()=>MS,GeometryInfoBlock:()=>ex,GeometryInputBlock:()=>tS,GeometryLengthBlock:()=>Cx,GeometryLerpBlock:()=>hx,GeometryModBlock:()=>_x,GeometryNLerpBlock:()=>dx,GeometryOptimizeBlock:()=>nS,GeometryOutputBlock:()=>$E,GeometryPosterizeBlock:()=>Ex,GeometryPowBlock:()=>mx,GeometryReplaceColorBlock:()=>Sx,GeometryRotate2dBlock:()=>Rx,GeometrySmoothStepBlock:()=>fx,GeometryStepBlock:()=>px,GeometryTextureBlock:()=>ox,GeometryTextureFetchBlock:()=>ax,GeometryTransformBlock:()=>BS,GeometryTrigonometryBlock:()=>wS,GeometryTrigonometryBlockOperations:()=>FS,GetClass:()=>s,GetClassName:()=>l,GetDOMTextContent:()=>dt,GetEnvInfo:()=>Vp,GetEnvironmentBRDFTexture:()=>km,GetFogState:()=>ha,GetFontOffset:()=>xo,GetInternalFormatFromBasisFormat:()=>My,GetPointsCount:()=>YE,GetTGAHeader:()=>by,GetTextureDataAsync:()=>Op,Gizmo:()=>Oh,GizmoAnchorPoint:()=>Rh,GizmoCoordinatesMode:()=>Ph,GizmoManager:()=>Sm,GlowLayer:()=>nv,GoldbergMesh:()=>qd,GradientBlock:()=>iT,GradientBlockColorStep:()=>tT,GradientHelper:()=>Kx,GrainPostProcess:()=>NC,GreasedLineBaseMesh:()=>BE,GreasedLineMaterialDefaults:()=>qT,GreasedLineMesh:()=>UE,GreasedLineMeshColorDistribution:()=>VE,GreasedLineMeshColorDistributionType:()=>BT,GreasedLineMeshColorMode:()=>wT,GreasedLineMeshMaterialType:()=>LT,GreasedLineMeshWidthDistribution:()=>kE,GreasedLinePluginMaterial:()=>$T,GreasedLineRibbonAutoDirectionMode:()=>LE,GreasedLineRibbonFacesMode:()=>FE,GreasedLineRibbonMesh:()=>HE,GreasedLineRibbonPointsMode:()=>NE,GreasedLineSimpleMaterial:()=>tE,GreasedLineTools:()=>ZT,GridBlock:()=>cS,GroundBuilder:()=>oh,GroundMesh:()=>Ju,HDRCubeTexture:()=>Pv,HDRCubeTextureAssetTask:()=>rP,HDRFiltering:()=>Rv,HDRTools:()=>Cv,Halton2DSequence:()=>cE,HandConstraintBehavior:()=>ql,HandConstraintOrientation:()=>Wl,HandConstraintVisibility:()=>Hl,HandConstraintZone:()=>zl,HandPart:()=>Vl,HandleFallbacksForShadows:()=>ua,HardwareScalingOptimization:()=>dP,HavokPlugin:()=>iC,HeightToNormalBlock:()=>ub,HemisphereBuilder:()=>Rm,HemisphericLight:()=>Ch,HemisphericParticleEmitter:()=>wx,HighlightLayer:()=>av,HighlightsPostProcess:()=>FC,Hinge2Joint:()=>Ms,HingeConstraint:()=>WA,HingeJoint:()=>Is,HtmlElementTexture:()=>sy,IWebXRControllerPhysicsOptions:()=>lI,IcoSphereBlock:()=>sS,IcoSphereBuilder:()=>Gl,ImageAssetTask:()=>eP,ImageProcessingBlock:()=>eb,ImageProcessingConfiguration:()=>pr,ImageProcessingPostProcess:()=>LC,ImageSourceBlock:()=>mb,IncrementValueAction:()=>ue,IndexFormat:()=>jf,InputBlock:()=>rl,InspectableType:()=>FP,InstancedLinesMesh:()=>ud,InstancedMesh:()=>La,InstancesBlock:()=>Zy,InstantiateBlock:()=>KS,InstantiateLinearBlock:()=>QS,InstantiateOnFacesBlock:()=>XS,InstantiateOnVerticesBlock:()=>HS,InstantiateOnVolumeBlock:()=>jS,InstantiateRadialBlock:()=>qS,InstantiatedEntries:()=>Ua,IntFloatConverterBlock:()=>ZS,InternalTexture:()=>Pi,InternalTextureSource:()=>Ti,InterpolateValueAction:()=>st,IntersectionInfo:()=>eo,IsBase64DataUrl:()=>zi,IsDocumentAvailable:()=>ht,IsFileURL:()=>Gi,IsNavigatorAvailable:()=>ut,IsWindowObjectExist:()=>ct,IsWrapper:()=>fr,JoystickAxis:()=>Cc,KeepAssets:()=>Ba,KeyboardEventTypes:()=>Xr,KeyboardInfo:()=>jr,KeyboardInfoPre:()=>Yr,KhronosTextureContainer:()=>gg,KhronosTextureContainer2:()=>Sg,LatheBuilder:()=>Md,Layer:()=>lv,LayerSceneComponent:()=>sv,LengthBlock:()=>Hb,LensFlare:()=>cv,LensFlareSystem:()=>uv,LensFlareSystemSceneComponent:()=>hv,LensFlaresOptimization:()=>_P,LensRenderingPipeline:()=>YC,LerpBlock:()=>Fb,Light:()=>wa,LightBlock:()=>_b,LightGizmo:()=>Im,LightInformationBlock:()=>$y,LineEdgesRenderer:()=>mR,LinesBuilder:()=>md,LinesMesh:()=>cd,LoadFile:()=>Vi,LoadFileError:()=>Di,LoadImage:()=>Bi,LoadOp:()=>Zf,LoadTextureFromTranscodeResult:()=>By,LockConstraint:()=>XA,Logger:()=>ae,MapMode:()=>Tf,MapRangeBlock:()=>SS,MappingBlock:()=>tx,MappingTypes:()=>$S,Material:()=>Ca,MaterialAnisotropicDefines:()=>Km,MaterialClearCoatDefines:()=>Hm,MaterialDefines:()=>Gs,MaterialDetailMapDefines:()=>Fu,MaterialFlags:()=>xu,MaterialGreasedLineDefines:()=>JT,MaterialHelper:()=>ey,MaterialIridescenceDefines:()=>jm,MaterialPluginBase:()=>Nu,MaterialPluginEvent:()=>Vo,MaterialPluginManager:()=>Cu,MaterialSheenDefines:()=>qm,MaterialSubSurfaceDefines:()=>Jm,MathBlock:()=>TS,MathBlockOperations:()=>yS,Matrix:()=>z,MatrixBuilderBlock:()=>ET,MatrixComposeBlock:()=>ix,MatrixDeterminantBlock:()=>IT,MatrixTransposeBlock:()=>OT,MaxBlock:()=>Gb,MergeGeometryBlock:()=>PS,MergeMeshesOptimization:()=>yP,Mesh:()=>Fa,MeshAssetTask:()=>qR,MeshAttributeExistsBlock:()=>NT,MeshAttributeExistsBlockTypes:()=>MT,MeshBlock:()=>aS,MeshBuilder:()=>rp,MeshDebugMode:()=>eE,MeshDebugPluginMaterial:()=>nE,MeshExploder:()=>sP,MeshLODLevel:()=>Pa,MeshParticleEmitter:()=>Gx,MeshUVSpaceRenderer:()=>SE,MeshoptCompression:()=>mE,MinBlock:()=>zb,MinMaxReducer:()=>fv,MipmapFilterMode:()=>If,MirrorTexture:()=>Dm,ModBlock:()=>bT,ModelShape:()=>dA,MorphTarget:()=>Iv,MorphTargetManager:()=>Ov,MorphTargetsBlock:()=>Jy,MotionBlurPostProcess:()=>kC,MotorEnabledJoint:()=>Ps,MultiMaterial:()=>Ra,MultiObserver:()=>cP,MultiPointerScaleBehavior:()=>vs,MultiRenderTarget:()=>ky,MultiplyBlock:()=>ml,NLerpBlock:()=>rT,NativeDataStream:()=>gp,NativeEngine:()=>mf,NativePointerInput:()=>Ar,NativeXRFrame:()=>jI,NativeXRLayerRenderTargetTextureProvider:()=>Qu,NativeXRLayerWrapper:()=>Ku,NativeXRRenderTarget:()=>qu,NegateBlock:()=>Xb,Node:()=>qe,NodeGeometry:()=>rS,NodeGeometryBlock:()=>JE,NodeGeometryBlockConnectionPointTypes:()=>GE,NodeGeometryBuildState:()=>eS,NodeGeometryConnectionPoint:()=>ZE,NodeGeometryConnectionPointCompatibilityStates:()=>zE,NodeGeometryConnectionPointDirection:()=>WE,NodeGeometryContextualSources:()=>qE,NodeMaterial:()=>Ll,NodeMaterialBlock:()=>Ws,NodeMaterialBlockConnectionPointMode:()=>Ks,NodeMaterialBlockConnectionPointTypes:()=>Ns,NodeMaterialBlockTargets:()=>Fs,NodeMaterialConnectionPoint:()=>zs,NodeMaterialConnectionPointCompatibilityStates:()=>Bs,NodeMaterialConnectionPointCustomObject:()=>Qy,NodeMaterialConnectionPointDirection:()=>Us,NodeMaterialDefines:()=>Fl,NodeMaterialModes:()=>fl,NodeMaterialOptimizer:()=>UT,NodeMaterialSystemValues:()=>Qs,NodeMaterialTeleportInBlock:()=>Sb,NodeMaterialTeleportOutBlock:()=>xb,NoiseBlock:()=>RS,NoiseProceduralTexture:()=>Hy,NormalBlendBlock:()=>aT,NormalizeBlock:()=>Ob,NormalizeVectorBlock:()=>NS,NullBlock:()=>fS,NullEngine:()=>cp,NullEngineOptions:()=>lp,Observable:()=>f,Observer:()=>p,OcclusionMaterial:()=>ty,Octree:()=>Th,OctreeBlock:()=>bh,OctreeSceneComponent:()=>Eh,OimoJSPlugin:()=>wv,OnAfterEnteringVRObservableEvent:()=>hh,OneMinusBlock:()=>Ub,Orientation:()=>vn,OutlineRenderer:()=>xR,PBRAnisotropicConfiguration:()=>Qm,PBRBaseMaterial:()=>ig,PBRBaseSimpleMaterial:()=>iy,PBRClearCoatConfiguration:()=>Xm,PBRIridescenceConfiguration:()=>Ym,PBRMaterial:()=>rg,PBRMaterialDefines:()=>tg,PBRMetallicRoughnessBlock:()=>yT,PBRMetallicRoughnessMaterial:()=>ry,PBRSheenConfiguration:()=>Zm,PBRSpecularGlossinessMaterial:()=>ny,PBRSubSurfaceConfiguration:()=>$m,PHI:()=>x,PadNumber:()=>Rt,PanoramaToCubeMapTools:()=>Av,Particle:()=>Qx,ParticleBlendMultiplyBlock:()=>sl,ParticleHelper:()=>cA,ParticleRampGradientBlock:()=>al,ParticleSystem:()=>aA,ParticleSystemSet:()=>lA,ParticleTextureBlock:()=>ol,ParticlesOptimization:()=>gP,PassCubePostProcess:()=>Zc,PassPostProcess:()=>qc,Path2:()=>xn,Path3D:()=>An,PathCursor:()=>Wn,PerfCollectionStrategy:()=>eI,PerfCounter:()=>an,PerformanceConfigurator:()=>I,PerformanceMonitor:()=>yo,PerformanceViewerCollector:()=>JP,PerturbNormalBlock:()=>ib,PhotoDome:()=>Um,Physics6DoFConstraint:()=>kA,Physics6DoFLimit:()=>VA,PhysicsActivationControl:()=>CA,PhysicsAggregate:()=>KA,PhysicsBody:()=>IA,PhysicsConstraint:()=>UA,PhysicsConstraintAxis:()=>bA,PhysicsConstraintAxisLimitMode:()=>yA,PhysicsConstraintMotorType:()=>SA,PhysicsConstraintType:()=>TA,PhysicsEngine:()=>Fv,PhysicsEngineV2:()=>RA,PhysicsEventType:()=>xA,PhysicsHelper:()=>sC,PhysicsImpostor:()=>Ds,PhysicsJoint:()=>Cs,PhysicsMaterialCombineMode:()=>PA,PhysicsMotionType:()=>AA,PhysicsRadialExplosionEventOptions:()=>dC,PhysicsRadialImpulseFalloff:()=>nC,PhysicsRaycastResult:()=>Nv,PhysicsShape:()=>MA,PhysicsShapeBox:()=>FA,PhysicsShapeCapsule:()=>DA,PhysicsShapeContainer:()=>BA,PhysicsShapeConvexHull:()=>LA,PhysicsShapeCylinder:()=>NA,PhysicsShapeMesh:()=>wA,PhysicsShapeSphere:()=>OA,PhysicsShapeType:()=>EA,PhysicsUpdraftEventOptions:()=>pC,PhysicsUpdraftMode:()=>oC,PhysicsViewer:()=>np,PhysicsVortexEventOptions:()=>fC,PickingInfo:()=>Fr,PipelineErrorReason:()=>Bf,PivotTools:()=>ds,Plane:()=>sn,PlaneBlock:()=>oS,PlaneBuilder:()=>_s,PlaneDragGizmo:()=>bm,PlaneRotationGizmo:()=>vm,PlayAnimationAction:()=>he,PlaySoundAction:()=>Te,PointColor:()=>uA,PointLight:()=>Sv,PointParticleEmitter:()=>Bx,PointerDragBehavior:()=>gs,PointerEventTypes:()=>Gr,PointerInfo:()=>Hr,PointerInfoBase:()=>zr,PointerInfoPre:()=>Wr,PointerInput:()=>xr,PointsCloudSystem:()=>vA,PointsGroup:()=>gA,Polar:()=>sE,Polygon:()=>yd,PolygonBuilder:()=>xd,PolygonMeshBuilder:()=>bd,PolyhedronBuilder:()=>Ld,PolyhedronData:()=>Yd,PositionGizmo:()=>Tm,PositionNormalTextureVertex:()=>$s,PositionNormalVertex:()=>Js,PostProcess:()=>hl,PostProcessManager:()=>Lr,PostProcessRenderEffect:()=>vC,PostProcessRenderPipeline:()=>WC,PostProcessRenderPipelineManager:()=>HC,PostProcessRenderPipelineManagerSceneComponent:()=>XC,PostProcessesOptimization:()=>fP,PosterizeBlock:()=>$b,PowBlock:()=>jb,PowerEase:()=>Fn,PowerPreference:()=>gf,PrePassOutputBlock:()=>pb,PrePassRenderer:()=>vR,PrePassRendererSceneComponent:()=>yR,PrePassTextureBlock:()=>Eb,PrecisionDate:()=>_t,PredicateCondition:()=>ne,PrepareAttributesForBakedVertexAnimation:()=>ra,PrepareAttributesForBones:()=>la,PrepareAttributesForInstances:()=>ca,PrepareAttributesForMorphTargets:()=>Zo,PrepareAttributesForMorphTargetsInfluencers:()=>qo,PrepareDefinesForAttributes:()=>ya,PrepareDefinesForBakedVertexAnimation:()=>va,PrepareDefinesForBones:()=>ma,PrepareDefinesForCamera:()=>Sa,PrepareDefinesForFrameBoundValues:()=>_a,PrepareDefinesForLight:()=>fa,PrepareDefinesForLights:()=>pa,PrepareDefinesForMergedUV:()=>ta,PrepareDefinesForMisc:()=>da,PrepareDefinesForMorphTargets:()=>ga,PrepareDefinesForMultiview:()=>ba,PrepareDefinesForOIT:()=>Ta,PrepareDefinesForPrePass:()=>Ea,PrepareUniformsAndSamplersForLight:()=>xa,PrepareUniformsAndSamplersList:()=>Aa,PressureObserverWrapper:()=>jP,PrimitiveTopology:()=>Vf,PrismaticConstraint:()=>jA,ProceduralTexture:()=>Ol,ProceduralTextureSceneComponent:()=>Il,PropertyTypeForEdition:()=>Xs,ProximityCastResult:()=>_C,PushAttributesForInstances:()=>Jo,PushMaterial:()=>ws,QuadraticEase:()=>Ln,QuadraticErrorSimplification:()=>DE,QuarticEase:()=>wn,Quaternion:()=>G,QueryType:()=>$f,QueueNewFrame:()=>Ii,QuinticEase:()=>Bn,RGBDTextureTools:()=>Np,RSMCreatePluginMaterial:()=>VR,Ragdoll:()=>qA,RagdollBoneProperties:()=>QA,RandomBlock:()=>CS,RandomBlockLocks:()=>xS,RandomGUID:()=>Qi,RandomNumberBlock:()=>Yb,RawCubeTexture:()=>Xy,RawTexture:()=>is,RawTexture2DArray:()=>Mv,RawTexture3D:()=>jy,Ray:()=>hs,RayHelper:()=>op,ReadFile:()=>Ui,ReadFileError:()=>Fi,RecastJSCrowd:()=>Mx,RecastJSPlugin:()=>Ix,ReciprocalBlock:()=>qb,ReflectBlock:()=>lT,ReflectionBlock:()=>pT,ReflectionProbe:()=>Uv,ReflectionTextureBaseBlock:()=>vb,ReflectionTextureBlock:()=>yb,ReflectiveShadowMap:()=>BR,Reflector:()=>XP,RefractBlock:()=>cT,RefractionBlock:()=>mT,RefractionPostProcess:()=>GC,RefractionTexture:()=>Yy,RegisterClass:()=>a,RegisterMaterialPlugin:()=>Mu,RegisterNativeTypeAsync:()=>pf,RemapBlock:()=>pl,RenderPassTimestampLocation:()=>qf,RenderTargetTexture:()=>Pl,RenderTargetWrapper:()=>cl,RenderTargetsOptimization:()=>vP,RenderingGroup:()=>wr,RenderingGroupInfo:()=>Br,RenderingManager:()=>Ur,ReplaceColorBlock:()=>Zb,RequestFile:()=>ki,RequestFileError:()=>Ni,RequestFullscreen:()=>Ro,RequestPointerlock:()=>Io,ResizeImageBitmap:()=>Co,RetryStrategy:()=>gt,RibbonBuilder:()=>Kh,RichType:()=>QI,RichTypeAny:()=>qI,RichTypeBoolean:()=>$I,RichTypeColor3:()=>nM,RichTypeColor4:()=>oM,RichTypeFlowGraphInteger:()=>sM,RichTypeMatrix:()=>rM,RichTypeNumber:()=>JI,RichTypeQuaternion:()=>aM,RichTypeString:()=>ZI,RichTypeVector2:()=>eM,RichTypeVector3:()=>tM,RichTypeVector4:()=>iM,RollingAverage:()=>bo,Rotate2dBlock:()=>sT,RotationGizmo:()=>ym,RotationXBlock:()=>US,RotationYBlock:()=>VS,RotationZBlock:()=>kS,RuntimeAnimation:()=>lt,RuntimeError:()=>bt,SSAO2RenderingPipeline:()=>QC,SSAORenderingPipeline:()=>qC,SSRRenderingPipeline:()=>rR,SamplerBindingType:()=>Nf,Scalar:()=>j,ScaleBlock:()=>Cb,ScaleGizmo:()=>Em,ScalingBlock:()=>GS,Scene:()=>pn,SceneComponentConstants:()=>Vr,SceneDepthBlock:()=>bb,SceneInstrumentation:()=>tv,SceneLoader:()=>Ls,SceneLoaderAnimationGroupLoadingMode:()=>Os,SceneLoaderFlags:()=>mo,SceneOptimization:()=>uP,SceneOptimizer:()=>TP,SceneOptimizerOptions:()=>bP,ScenePerformancePriority:()=>Kr,SceneRecorder:()=>VP,SceneSerializer:()=>AP,ScreenSizeBlock:()=>sb,ScreenSpaceBlock:()=>lb,ScreenSpaceCurvaturePostProcess:()=>lR,ScreenSpaceReflectionPostProcess:()=>JC,ScreenshotTools:()=>LP,SerializationHelper:()=>Ke,SetBasisTranscoderWorker:()=>Fy,SetColorsBlock:()=>vS,SetCorsBehavior:()=>wi,SetMaterialIDBlock:()=>LS,SetNormalsBlock:()=>mS,SetParentAction:()=>me,SetPositionsBlock:()=>_S,SetStateAction:()=>le,SetTangentsBlock:()=>bS,SetUVsBlock:()=>gS,SetValueAction:()=>ce,ShaderCodeInliner:()=>tf,ShaderLanguage:()=>pt,ShaderMaterial:()=>ld,ShaderStage:()=>Of,ShaderStore:()=>li,ShadowDepthWrapper:()=>kT,ShadowGenerator:()=>dv,ShadowGeneratorSceneComponent:()=>Ev,ShadowLight:()=>xm,ShadowMapBlock:()=>db,ShadowsOptimization:()=>pP,ShapeBuilder:()=>Pd,ShapeCastResult:()=>mC,SharpenPostProcess:()=>zC,SheenBlock:()=>hT,SimplexPerlin3DBlock:()=>oT,SimplicationQueueSceneComponent:()=>wE,SimplificationQueue:()=>RE,SimplificationSettings:()=>CE,SimplificationType:()=>xE,SineEase:()=>Un,SixDofDragBehavior:()=>bs,Size:()=>Ze,Skeleton:()=>rs,SkeletonViewer:()=>ap,SliderConstraint:()=>HA,SmartArray:()=>ar,SmartArrayNoDuplicate:()=>sr,SmoothStepBlock:()=>Qb,SolidParticle:()=>hA,SolidParticleSystem:()=>_A,SolidParticleVertex:()=>fA,Sound:()=>Ga,SoundTrack:()=>za,SourceTextureFormat:()=>fg,Space:()=>dn,SphereBlock:()=>lS,SphereBuilder:()=>zh,SphereDirectedParticleEmitter:()=>Vx,SphereParticleEmitter:()=>Ux,Spherical:()=>lE,SphericalHarmonics:()=>Ep,SphericalPolynomial:()=>Sp,SpotLight:()=>Pm,SpringConstraint:()=>YA,Sprite:()=>Vv,SpriteManager:()=>zv,SpriteMap:()=>XR,SpritePackedManager:()=>jR,SpriteSceneComponent:()=>kv,Stage:()=>kr,StandardMaterial:()=>Uu,StandardMaterialDefines:()=>Bu,StandardRenderingPipeline:()=>$C,StartsWith:()=>Et,StateCondition:()=>oe,StencilOperation:()=>Xf,StencilState:()=>Ai,StencilStateComposer:()=>xi,StepBlock:()=>Bb,StereoscopicArcRotateCamera:()=>su,StereoscopicFreeCamera:()=>lu,StereoscopicGamepadCamera:()=>cu,StereoscopicInterlacePostProcess:()=>ou,StereoscopicInterlacePostProcessI:()=>nu,StereoscopicScreenUniversalCamera:()=>hu,StereoscopicUniversalCamera:()=>uu,StickValues:()=>oc,StopAnimationAction:()=>de,StopSoundAction:()=>Ee,StorageBuffer:()=>$l,StorageTextureAccess:()=>Lf,StoreOp:()=>Jf,StringDictionary:()=>lr,StringTools:()=>Pt,SubEmitter:()=>Jx,SubEmitterType:()=>qx,SubMesh:()=>po,SubSurfaceBlock:()=>gT,SubSurfaceSceneComponent:()=>ER,SubtractBlock:()=>wb,SurfaceMagnetismBehavior:()=>Ts,SwitchBooleanAction:()=>se,SwitchInput:()=>Ir,TAARenderingPipeline:()=>nR,TBNBlock:()=>tb,TGATools:()=>Ey,Tags:()=>je,TargetCamera:()=>Mc,TargetedAnimation:()=>Gn,TeleportInBlock:()=>rx,TeleportOutBlock:()=>nx,TestBase64DataUrl:()=>Wi,TextFileAssetTask:()=>JR,Texture:()=>Ja,TextureAspect:()=>Af,TextureAssetTask:()=>tP,TextureBlock:()=>gb,TextureDimension:()=>Ef,TextureFormat:()=>Cf,TextureOptimization:()=>hP,TexturePacker:()=>zy,TexturePackerFrame:()=>Gy,TextureSampleType:()=>Ff,TextureSampler:()=>Ri,TextureTools:()=>Dp,TextureUsage:()=>Sf,TextureViewDimension:()=>xf,ThinEngine:()=>Er,ThinRenderTargetTexture:()=>Ky,ThinTexture:()=>ja,TiledBoxBuilder:()=>rd,TiledPlaneBuilder:()=>ed,TimerState:()=>Gg,TmpColors:()=>$,TmpVectors:()=>H,ToGammaSpace:()=>E,ToHalfFloat:()=>Pp,ToLinearSpace:()=>S,TonemapPostProcess:()=>aR,TonemappingOperator:()=>oR,Tools:()=>rr,TorusBlock:()=>uS,TorusBuilder:()=>lh,TorusKnotBuilder:()=>ad,TouchCamera:()=>Dc,TrailMesh:()=>AE,Trajectory:()=>kP,TrajectoryClassifier:()=>HP,TranscodeAsync:()=>Ly,TranscodeTarget:()=>_g,TransformBlock:()=>Hs,TransformNode:()=>Fo,TranslationBlock:()=>WS,TriPlanarBlock:()=>RT,TrigonometryBlock:()=>Dl,TrigonometryBlockOperations:()=>Ml,TubeBuilder:()=>Dd,TwirlBlock:()=>cb,UniformBuffer:()=>Or,UniversalCamera:()=>Kc,UnregisterAllMaterialPlugins:()=>Du,UnregisterMaterialPlugin:()=>Ou,UploadContent:()=>Ty,UploadEnvLevelsAsync:()=>Hp,UploadEnvSpherical:()=>Yp,UploadLevelsAsync:()=>jp,UtilityLayerRenderer:()=>Ih,VRCameraMetrics:()=>pu,VRDeviceOrientationArcRotateCamera:()=>bu,VRDeviceOrientationFreeCamera:()=>Tu,VRDeviceOrientationGamepadCamera:()=>Eu,VRDistortionCorrectionPostProcess:()=>fu,VRExperienceHelper:()=>dh,VRMultiviewToSingleviewPostProcess:()=>vu,ValidatedNativeDataStream:()=>r_,ValueCondition:()=>re,Vector2:()=>U,Vector2ToFixed:()=>uE,Vector3:()=>V,Vector3ToFixed:()=>hE,Vector4:()=>k,Vector4ToFixed:()=>dE,VectorConverterBlock:()=>DS,VectorMergerBlock:()=>dl,VectorSplitterBlock:()=>Nb,VertexAnimationBaker:()=>ns,VertexBuffer:()=>Nr,VertexData:()=>_o,VertexDataMaterialInfo:()=>fo,VertexFormat:()=>Yf,VertexOutputBlock:()=>js,VertexStepMode:()=>Kf,VideoDome:()=>$g,VideoRecorder:()=>CP,VideoTexture:()=>Jg,ViewDirectionBlock:()=>Vb,Viewport:()=>Jn,VirtualJoystick:()=>Pc,VirtualJoysticksCamera:()=>du,VolumetricLightScatteringPostProcess:()=>sR,VoronoiNoiseBlock:()=>AT,WaveBlock:()=>eT,WaveBlockKind:()=>Jb,WebGL2ParticleSystem:()=>Wx,WebGL2ShaderProcessor:()=>gr,WebGLDataBuffer:()=>yr,WebGLHardwareTexture:()=>br,WebGLPipelineContext:()=>ci,WebGPUCacheBindGroups:()=>k_,WebGPUCacheRenderPipeline:()=>O_,WebGPUCacheRenderPipelineTree:()=>N_,WebGPUCacheSampler:()=>R_,WebGPUDataBuffer:()=>E_,WebGPUDrawContext:()=>U_,WebGPUEngine:()=>sm,WebGPURenderTargetWrapper:()=>dm,WebGPUTintWASM:()=>em,WebRequest:()=>Je,WebXRAbstractFeature:()=>As,WebXRAbstractMotionController:()=>Pg,WebXRAnchorSystem:()=>nI,WebXRBackgroundRemover:()=>sI,WebXRCamera:()=>Ag,WebXRControllerComponent:()=>Rg,WebXRControllerMovement:()=>gI,WebXRControllerPhysics:()=>cI,WebXRControllerPointerSelection:()=>Vg,WebXRDefaultExperience:()=>Qg,WebXRDefaultExperienceOptions:()=>Kg,WebXRDepthSensing:()=>DI,WebXRDomOverlay:()=>mI,WebXREnterExitUI:()=>Hg,WebXREnterExitUIButton:()=>zg,WebXREnterExitUIOptions:()=>Wg,WebXRExperienceHelper:()=>Cg,WebXREyeTracking:()=>yI,WebXRFeatureName:()=>Ss,WebXRFeaturePointSystem:()=>hI,WebXRFeaturesManager:()=>xs,WebXRGenericHandController:()=>BI,WebXRGenericTriggerMotionController:()=>Ig,WebXRHTCViveMotionController:()=>WI,WebXRHand:()=>Yl,WebXRHandJoint:()=>kl,WebXRHandTracking:()=>Kl,WebXRHitTest:()=>uI,WebXRHitTestLegacy:()=>iI,WebXRImageTracking:()=>_I,WebXRInput:()=>Ug,WebXRInputSource:()=>Bg,WebXRLayerRenderTargetTextureProvider:()=>Wu,WebXRLayers:()=>OI,WebXRLightEstimation:()=>vI,WebXRManagedOutputCanvas:()=>Yu,WebXRManagedOutputCanvasOptions:()=>ju,WebXRMeshDetector:()=>fI,WebXRMicrosoftMixedRealityController:()=>VI,WebXRMotionControllerManager:()=>Ng,WebXRMotionControllerTeleportation:()=>Yg,WebXRNearControllerMode:()=>Lg,WebXRNearInteraction:()=>kg,WebXROculusTouchMotionController:()=>GI,WebXRPlaneDetector:()=>aI,WebXRProfiledMotionController:()=>Og,WebXRRawCameraAccess:()=>wI,WebXRSessionManager:()=>Zu,WebXRSpaceWarp:()=>LI,WebXRSpaceWarpRenderTargetTextureProvider:()=>FI,WebXRState:()=>Vu,WebXRTrackingState:()=>ku,WebXRWalkingLocomotion:()=>xI,WeightedSound:()=>Ha,WorkerPool:()=>vg,WorleyNoise3DBlock:()=>nT,XRSpaceWarpRenderTarget:()=>NI,Xbox360Button:()=>Uc,Xbox360Dpad:()=>Vc,Xbox360Pad:()=>Hc,XboxInput:()=>Pr,_BabylonLoaderRegistered:()=>Wv,_BasisTextureLoader:()=>Vy,_CommonDispose:()=>So,_CommonInit:()=>Eo,_CreationDataStorage:()=>Ia,_DDSTextureLoader:()=>dg,_ENVTextureLoader:()=>pg,_HDRTextureLoader:()=>xy,_InstancesBatch:()=>Oa,_KTXTextureLoader:()=>xg,_MeshCollisionData:()=>Lo,_OcclusionDataStorage:()=>up,_PrimaryIsoTriangle:()=>jd,_TGATextureLoader:()=>Sy,_TimeToken:()=>hp,_UpdateRGBDAsync:()=>Kp,_forceSceneHelpersToBundle:()=>qg,_forceTransformFeedbackToBundle:()=>dp,_injectLTSFileTools:()=>Yi,_staticOffsetValueColor3:()=>rt,_staticOffsetValueColor4:()=>nt,_staticOffsetValueQuaternion:()=>$e,_staticOffsetValueSize:()=>it,_staticOffsetValueVector2:()=>tt,_staticOffsetValueVector3:()=>et,addClipPlaneUniforms:()=>Go,allocateAndCopyTypedBuffer:()=>To,bindClipPlane:()=>Ho,captureEquirectangularFromScene:()=>tI,className:()=>nr,createDetailMapPlugin:()=>QT,createPBRAnisotropicPlugin:()=>WT,createPBRBRDFPlugin:()=>HT,createPBRClearCoatPlugin:()=>XT,createPBRIridescencePlugin:()=>jT,createPBRSheenPlugin:()=>YT,createPBRSubSurfacePlugin:()=>KT,createYieldingScheduler:()=>jn,editableInPropertyPage:()=>Ys,expandToProperty:()=>Pe,extractMinAndMax:()=>uo,extractMinAndMaxIndexed:()=>co,getRichTypeFromValue:()=>lM,inlineScheduler:()=>Xn,makeAsyncFunction:()=>Zn,makeSyncFunction:()=>qn,nativeOverride:()=>ze,normalizeEnvInfo:()=>kp,prepareDefinesForClipPlanes:()=>Wo,prepareStringDefinesForClipPlanes:()=>zo,runCoroutine:()=>Yn,runCoroutineAsync:()=>Qn,runCoroutineSync:()=>Kn,serialize:()=>Ie,serializeAsCameraReference:()=>Ge,serializeAsColor3:()=>Oe,serializeAsColor4:()=>Be,serializeAsColorCurves:()=>we,serializeAsFresnelParameters:()=>De,serializeAsImageProcessingConfiguration:()=>Ue,serializeAsMatrix:()=>ke,serializeAsMeshReference:()=>Le,serializeAsQuaternion:()=>Ve,serializeAsTexture:()=>Me,serializeAsVector2:()=>Ne,serializeAsVector3:()=>Fe,setAndStartTimer:()=>Xg,setStereoscopicAnaglyphRigMode:()=>$c,setStereoscopicRigMode:()=>au,setVRRigMode:()=>yu});var n={};e.r(n),e.d(n,{AbstractActionManager:()=>h,AbstractAssetTask:()=>YR,AbstractEngine:()=>Mi,AbstractMesh:()=>Uo,AbstractScene:()=>c,AcquireNativeObjectAsync:()=>df,Action:()=>ee,ActionEvent:()=>te,ActionManager:()=>be,AddBlock:()=>Ab,AddressMode:()=>Rf,AdvancedTimer:()=>jg,AlignBlock:()=>zS,AlphaState:()=>Ci,AmmoJSPlugin:()=>Bv,AnaglyphArcRotateCamera:()=>eu,AnaglyphFreeCamera:()=>tu,AnaglyphGamepadCamera:()=>iu,AnaglyphPostProcess:()=>Jc,AnaglyphUniversalCamera:()=>ru,Analyser:()=>ka,AndOrNotEvaluator:()=>Xe,Angle:()=>En,Animatable:()=>gn,AnimatedInputBlockTypes:()=>Zs,Animation:()=>at,AnimationAssetTask:()=>ZR,AnimationEvent:()=>kn,AnimationGroup:()=>zn,AnimationGroupMask:()=>Hn,AnimationGroupMaskMode:()=>bn,AnimationKeyInterpolation:()=>ge,AnimationPropertiesOverride:()=>yn,AnimationRange:()=>Se,AnisotropyBlock:()=>dT,ApplyPostProcess:()=>Rp,Arc2:()=>Sn,ArcFollowCamera:()=>Gc,ArcRotateCamera:()=>Nc,ArcRotateCameraGamepadInput:()=>lc,ArcRotateCameraInputsManager:()=>dc,ArcRotateCameraKeyboardMoveInput:()=>cc,ArcRotateCameraMouseWheelInput:()=>uc,ArcRotateCameraPointersInput:()=>hc,ArcRotateCameraVRDeviceOrientationInput:()=>pc,ArcTan2Block:()=>Kb,AssetContainer:()=>Va,AssetTaskState:()=>HR,AssetsManager:()=>oP,AssetsProgressEvent:()=>KR,AsyncLoop:()=>or,AttachToBoxBehavior:()=>cs,AudioEngine:()=>Oo,AudioSceneComponent:()=>Wa,AutoLayoutMode:()=>Uf,AutoReleaseWorkerPool:()=>yg,AutoRotationBehavior:()=>os,AxesViewer:()=>Nh,Axis:()=>_n,AxisDragGizmo:()=>Dh,AxisScaleGizmo:()=>mm,BRDFTextureTools:()=>Gm,BabylonFileLoaderConfiguration:()=>Hv,BackEase:()=>In,BackgroundMaterial:()=>Lm,BakedVertexAnimationManager:()=>Xa,BallAndSocketConstraint:()=>GA,BaseCameraMouseWheelInput:()=>tc,BaseCameraPointersInput:()=>ic,BaseError:()=>vt,BaseParticleSystem:()=>vl,BaseSixDofDragBehavior:()=>ys,BaseTexture:()=>Ya,BasisFileInfo:()=>Ry,BasisTools:()=>Uy,BasisToolsOptions:()=>Iy,BasisTranscodeConfiguration:()=>Py,BezierCurve:()=>Tn,BezierCurveEase:()=>Vn,BiPlanarBlock:()=>PT,BinaryFileAssetTask:()=>$R,BindBonesParameters:()=>na,BindFogParameters:()=>Qo,BindLight:()=>aa,BindLightProperties:()=>oa,BindLights:()=>sa,BindLogDepth:()=>Ko,BindMorphTargetParameters:()=>$o,BindSceneUniformBuffer:()=>ea,BindTextureMatrix:()=>ia,BlackAndWhitePostProcess:()=>gC,BlendFactor:()=>Wf,BlendOperation:()=>Hf,BloomEffect:()=>TC,BloomMergePostProcess:()=>bC,BlurPostProcess:()=>Om,Bone:()=>mn,BoneAxesViewer:()=>Fh,BoneIKController:()=>Zl,BoneLookController:()=>Jl,BonesBlock:()=>qy,BooleanGeometryBlock:()=>cx,BooleanGeometryOperations:()=>sx,BounceEase:()=>Mn,BouncingBehavior:()=>as,BoundingBlock:()=>lx,BoundingBox:()=>to,BoundingBoxGizmo:()=>gm,BoundingBoxRenderer:()=>cR,BoundingInfo:()=>so,BoundingSphere:()=>io,BoxBlock:()=>iS,BoxBuilder:()=>Vh,BoxParticleEmitter:()=>Dx,Buffer:()=>Dr,BufferBindingType:()=>Df,BufferMapState:()=>yf,BufferUsage:()=>bf,CSG:()=>EE,Camera:()=>$n,CameraGizmo:()=>Mm,CameraInputTypes:()=>rc,CameraInputsManager:()=>nc,CannonJSPlugin:()=>Lv,CanvasAlphaMode:()=>e_,CapsuleBlock:()=>dS,CapsuleBuilder:()=>Xh,CascadedShadowGenerator:()=>Tv,ChromaticAberrationPostProcess:()=>EC,CircleEase:()=>Pn,CircleOfConfusionPostProcess:()=>SC,ClampBlock:()=>Rb,ClearCoatBlock:()=>fT,ClipPlanesBlock:()=>Tb,ClipboardEventTypes:()=>fm,ClipboardInfo:()=>_m,CloudBlock:()=>xT,CloudPoint:()=>mA,Collider:()=>fh,Color3:()=>Z,Color3Gradient:()=>jx,Color4:()=>J,ColorCorrectionPostProcess:()=>xC,ColorCurves:()=>ur,ColorGradient:()=>Xx,ColorGradingTexture:()=>oy,ColorMergerBlock:()=>Db,ColorSplitterBlock:()=>yl,ColorWrite:()=>zf,CombineAction:()=>fe,CompareFunction:()=>Mf,CompatibilityOptions:()=>go,CompilationMessageType:()=>wf,CompleteGreasedLineColorTable:()=>QE,CompleteGreasedLineWidthTable:()=>KE,ComputeBindingType:()=>mh,ComputeEffect:()=>gh,ComputeNormalsBlock:()=>OS,ComputePassTimestampLocation:()=>Qf,ComputeShader:()=>yh,ComputeShaderParticleSystem:()=>Hx,Condition:()=>ie,ConditionBlock:()=>AS,ConditionBlockTests:()=>ES,ConditionalBlock:()=>ST,ConditionalBlockConditions:()=>TT,ConeParticleEmitter:()=>Nx,Constants:()=>u,ContainerAssetTask:()=>QR,ConversionMode:()=>PR,ConvolutionPostProcess:()=>AC,Coordinate:()=>fn,CopyTextureToTexture:()=>OR,CopyTools:()=>Za,CreateBox:()=>Uh,CreateBoxVertexData:()=>wh,CreateCapsule:()=>Hh,CreateCapsuleVertexData:()=>Wh,CreateCylinder:()=>xh,CreateCylinderVertexData:()=>Sh,CreateDashedLines:()=>_d,CreateDashedLinesVertexData:()=>dd,CreateDecal:()=>Wd,CreateDisc:()=>qh,CreateDiscVertexData:()=>Qh,CreateEnvTextureAsync:()=>Gp,CreateGeodesic:()=>Qd,CreateGoldberg:()=>Jd,CreateGoldbergVertexData:()=>Zd,CreateGreasedLine:()=>jE,CreateGreasedLineMaterial:()=>XE,CreateGround:()=>ih,CreateGroundFromHeightMap:()=>nh,CreateGroundFromHeightMapVertexData:()=>th,CreateGroundVertexData:()=>$u,CreateHemisphere:()=>Cm,CreateIcoSphere:()=>Bl,CreateIcoSphereVertexData:()=>wl,CreateImageBitmapFromSource:()=>Ao,CreateImageDataArrayBufferViews:()=>Wp,CreateLathe:()=>Id,CreateLineSystem:()=>pd,CreateLineSystemVertexData:()=>hd,CreateLines:()=>fd,CreatePlane:()=>fs,CreatePlaneVertexData:()=>ps,CreatePolygon:()=>Ed,CreatePolygonVertexData:()=>Td,CreatePolyhedron:()=>Fd,CreatePolyhedronVertexData:()=>Nd,CreateResizedCopy:()=>Cp,CreateRibbon:()=>Yh,CreateRibbonVertexData:()=>jh,CreateScreenshot:()=>PP,CreateScreenshotAsync:()=>IP,CreateScreenshotUsingRenderTarget:()=>OP,CreateScreenshotUsingRenderTargetAsync:()=>DP,CreateScreenshotWithResizeAsync:()=>MP,CreateSegmentedBoxVertexData:()=>Bh,CreateSphere:()=>Gh,CreateSphereVertexData:()=>kh,CreateText:()=>ip,CreateTextShapePaths:()=>tp,CreateTiledBox:()=>id,CreateTiledBoxVertexData:()=>td,CreateTiledGround:()=>rh,CreateTiledGroundVertexData:()=>eh,CreateTiledPlane:()=>$h,CreateTiledPlaneVertexData:()=>Jh,CreateTorus:()=>sh,CreateTorusKnot:()=>od,CreateTorusKnotVertexData:()=>nd,CreateTorusVertexData:()=>ah,CreateTube:()=>Od,CrossBlock:()=>Pb,CubeMapToSphericalPolynomialTools:()=>Lp,CubeTexture:()=>Nm,CubeTextureAssetTask:()=>iP,CubicEase:()=>On,CullMode:()=>Gf,CurrentScreenBlock:()=>nl,Curve3:()=>Cn,CurveBlock:()=>FT,CurveBlockTypes:()=>DT,CustomBlock:()=>Ib,CustomOptimization:()=>mP,CustomParticleEmitter:()=>kx,CustomProceduralTexture:()=>Wy,CylinderBlock:()=>hS,CylinderBuilder:()=>Ah,CylinderDirectedParticleEmitter:()=>Lx,CylinderParticleEmitter:()=>Fx,DDSTools:()=>hg,DataBuffer:()=>vr,DataReader:()=>BP,DataStorage:()=>UP,Database:()=>Ox,Debug:()=>jD,DebugBlock:()=>JS,DebugLayer:()=>Lh,DebugLayerTab:()=>Mh,DecalBuilder:()=>Hd,DecalMapConfiguration:()=>zT,DecalMapDefines:()=>GT,Decode:()=>St,DecodeBase64ToBinary:()=>Ct,DecodeBase64ToString:()=>At,DecodeBase64UrlToBinary:()=>Hi,DecodeBase64UrlToString:()=>ji,DeepCopier:()=>ye,DefaultCollisionCoordinator:()=>_h,DefaultKTX2DecoderOptions:()=>Eg,DefaultLoadingScreen:()=>xv,DefaultRenderingPipeline:()=>jC,Deferred:()=>aP,DepthCullingState:()=>Si,DepthOfFieldBlurPostProcess:()=>CC,DepthOfFieldEffect:()=>IC,DepthOfFieldEffectBlurLevel:()=>RC,DepthOfFieldMergePostProcess:()=>PC,DepthPeelingRenderer:()=>dR,DepthPeelingSceneComponent:()=>pR,DepthReducer:()=>_v,DepthRenderer:()=>pv,DepthRendererSceneComponent:()=>uR,DepthSortedParticle:()=>pA,DerivativeBlock:()=>ob,DesaturateBlock:()=>uT,DetailMapConfiguration:()=>Lu,DeviceInputEventType:()=>Mr,DeviceLostReason:()=>t_,DeviceOrientationCamera:()=>Fc,DeviceSource:()=>en,DeviceSourceManager:()=>rn,DeviceType:()=>Sr,DirectionalLight:()=>Am,DirectionalLightFrustumViewer:()=>sp,DiscBlock:()=>pS,DiscBuilder:()=>Zh,DiscardBlock:()=>rb,DisplayPassPostProcess:()=>MC,DistanceBlock:()=>Wb,DistanceConstraint:()=>zA,DistanceJoint:()=>Rs,DivideBlock:()=>Lb,DoNothingAction:()=>pe,DomManagement:()=>ft,DotBlock:()=>Mb,DracoCompression:()=>_E,DrawWrapper:()=>ho,DualSenseInput:()=>Rr,DualShockButton:()=>zc,DualShockDpad:()=>Wc,DualShockInput:()=>Cr,DualShockPad:()=>Xc,DumpTools:()=>Rl,DynamicFloat32Array:()=>YP,DynamicTexture:()=>Gu,EasingFunction:()=>Rn,EdgesRenderer:()=>_R,Effect:()=>Ei,EffectFallbacks:()=>ll,EffectLayer:()=>iv,EffectLayerSceneComponent:()=>rv,EffectRenderer:()=>Tl,EffectWrapper:()=>El,ElasticEase:()=>Dn,ElbowBlock:()=>CT,EncodeArrayBufferToBase64:()=>xt,EndsWith:()=>Tt,Engine:()=>Do,EngineFactory:()=>pm,EngineFormat:()=>mg,EngineInstrumentation:()=>ev,EngineStore:()=>M,EngineView:()=>pp,EnvironmentHelper:()=>wm,EnvironmentTextureTools:()=>Qp,Epsilon:()=>A,EquiRectangularCubeTexture:()=>ay,EquiRectangularCubeTextureAssetTask:()=>nP,ErrorCodes:()=>yt,ErrorFilter:()=>i_,EventConstants:()=>Qr,EventState:()=>d,ExecuteCodeAction:()=>_e,ExitFullscreen:()=>Po,ExitPointerlock:()=>Mo,ExponentialEase:()=>Nn,ExternalTexture:()=>w_,ExtractHighlightsPostProcess:()=>yC,ExtrudePolygon:()=>Sd,ExtrudeShape:()=>Ad,ExtrudeShapeCustom:()=>Cd,FactorGradient:()=>Yx,FadeInOutBehavior:()=>us,FeatureName:()=>vf,FileTools:()=>Xi,FileToolsOptions:()=>Li,FilesInput:()=>lP,FilesInputStore:()=>mt,FilterMode:()=>Pf,FilterPostProcess:()=>OC,FlowGraph:()=>SM,FlowGraphAbsBlock:()=>IO,FlowGraphAcosBlock:()=>aD,FlowGraphAcoshBlock:()=>pD,FlowGraphAddBlock:()=>vO,FlowGraphAsinBlock:()=>oD,FlowGraphAsinhBlock:()=>dD,FlowGraphAtan2Block:()=>lD,FlowGraphAtanBlock:()=>sD,FlowGraphAtanhBlock:()=>fD,FlowGraphBitwiseAndBlock:()=>DD,FlowGraphBitwiseLeftShiftBlock:()=>LD,FlowGraphBitwiseNotBlock:()=>OD,FlowGraphBitwiseOrBlock:()=>ND,FlowGraphBitwiseRightShiftBlock:()=>wD,FlowGraphBitwiseXorBlock:()=>FD,FlowGraphBlock:()=>fM,FlowGraphBranchBlock:()=>NM,FlowGraphCeilBlock:()=>NO,FlowGraphClampBlock:()=>zO,FlowGraphConditionalDataBlock:()=>QM,FlowGraphConnection:()=>YI,FlowGraphConnectionType:()=>HI,FlowGraphConsoleLogBlock:()=>RM,FlowGraphConstantBlock:()=>JM,FlowGraphContext:()=>yM,FlowGraphContextLogger:()=>AM,FlowGraphCoordinateTransformBlock:()=>ZM,FlowGraphCoordinator:()=>xM,FlowGraphCosBlock:()=>rD,FlowGraphCoshBlock:()=>uD,FlowGraphCountLeadingZerosBlock:()=>BD,FlowGraphCountOneBitsBlock:()=>VD,FlowGraphCountTrailingZerosBlock:()=>UD,FlowGraphCounterBlock:()=>GM,FlowGraphCrossBlock:()=>xD,FlowGraphCubeRootBlock:()=>bD,FlowGraphDataConnection:()=>cM,FlowGraphDebounceBlock:()=>WM,FlowGraphDegToRadBlock:()=>eD,FlowGraphDeterminantBlock:()=>PD,FlowGraphDivideBlock:()=>TO,FlowGraphDoNBlock:()=>FM,FlowGraphDotBlock:()=>SO,FlowGraphEBlock:()=>xO,FlowGraphEqBlock:()=>jO,FlowGraphEventBlock:()=>vM,FlowGraphExecutionBlock:()=>mM,FlowGraphExpBlock:()=>_D,FlowGraphFlipFlopBlock:()=>HM,FlowGraphFloorBlock:()=>DO,FlowGraphForLoopBlock:()=>LM,FlowGraphFractBlock:()=>FO,FlowGraphGetPropertyBlock:()=>$M,FlowGraphGetVariableBlock:()=>qM,FlowGraphGreaterThanBlock:()=>qO,FlowGraphGreaterThanOrEqualBlock:()=>ZO,FlowGraphInfBlock:()=>CO,FlowGraphInterpolateBlock:()=>XO,FlowGraphInvertMatrixBlock:()=>ID,FlowGraphIsInfBlock:()=>$O,FlowGraphIsNanBlock:()=>JO,FlowGraphLengthBlock:()=>ED,FlowGraphLessThanBlock:()=>KO,FlowGraphLessThanOrEqualBlock:()=>QO,FlowGraphLog10Block:()=>vD,FlowGraphLog2Block:()=>gD,FlowGraphLogBlock:()=>mD,FlowGraphLogicAndBlock:()=>cO,FlowGraphLogicNotBlock:()=>hO,FlowGraphLogicOrBlock:()=>uO,FlowGraphMatMulBlock:()=>MD,FlowGraphMaxBlock:()=>VO,FlowGraphMeshPickEventBlock:()=>EM,FlowGraphMinBlock:()=>UO,FlowGraphMultiGateBlock:()=>UM,FlowGraphMultiplyBlock:()=>bO,FlowGraphNaNBlock:()=>RO,FlowGraphNegBlock:()=>LO,FlowGraphNormalizeBlock:()=>SD,FlowGraphPauseAnimationBlock:()=>KM,FlowGraphPiBlock:()=>AO,FlowGraphPlayAnimationBlock:()=>jM,FlowGraphPowBlock:()=>TD,FlowGraphRadToDegBlock:()=>tD,FlowGraphRandomBlock:()=>EO,FlowGraphReceiveCustomEventBlock:()=>GD,FlowGraphRemainderBlock:()=>BO,FlowGraphRotate2DBlock:()=>AD,FlowGraphRotate3DBlock:()=>CD,FlowGraphSaturateBlock:()=>HO,FlowGraphSceneReadyEventBlock:()=>kD,FlowGraphSceneTickEventBlock:()=>zD,FlowGraphSendCustomEventBlock:()=>DM,FlowGraphSequenceBlock:()=>XM,FlowGraphSetPropertyBlock:()=>OM,FlowGraphSetVariableBlock:()=>PM,FlowGraphSignBlock:()=>MO,FlowGraphSignalConnection:()=>_M,FlowGraphSinBlock:()=>iD,FlowGraphSinhBlock:()=>cD,FlowGraphSqrtBlock:()=>yD,FlowGraphState:()=>TM,FlowGraphStopAnimationBlock:()=>YM,FlowGraphSubtractBlock:()=>yO,FlowGraphSwitchBlock:()=>VM,FlowGraphTanBlock:()=>nD,FlowGraphTanhBlock:()=>hD,FlowGraphThrottleBlock:()=>wM,FlowGraphTimerBlock:()=>BM,FlowGraphTransposeBlock:()=>RD,FlowGraphTruncBlock:()=>OO,FlowGraphWaitAllBlock:()=>kM,FlowGraphWhileLoopBlock:()=>zM,FluidRenderer:()=>wR,FluidRendererSceneComponent:()=>LR,FluidRenderingDebug:()=>SR,FluidRenderingObject:()=>AR,FluidRenderingObjectCustomParticles:()=>MR,FluidRenderingObjectParticleSystem:()=>CR,FluidRenderingTargetRenderer:()=>IR,FlyCamera:()=>wc,FlyCameraInputsManager:()=>Lc,FlyCameraKeyboardInput:()=>fc,FlyCameraMouseInput:()=>_c,FogBlock:()=>fb,FollowBehavior:()=>Es,FollowCamera:()=>kc,FollowCameraInputsManager:()=>Bc,FollowCameraKeyboardMoveInput:()=>mc,FollowCameraMouseWheelInput:()=>gc,FollowCameraPointersInput:()=>vc,FragCoordBlock:()=>ab,FragDepthBlock:()=>hb,FragmentOutputBlock:()=>qs,FramingBehavior:()=>ss,FreeCamera:()=>Oc,FreeCameraDeviceOrientationInput:()=>Ac,FreeCameraGamepadInput:()=>Rc,FreeCameraInputsManager:()=>xc,FreeCameraKeyboardMoveInput:()=>yc,FreeCameraMouseInput:()=>Tc,FreeCameraMouseWheelInput:()=>Ec,FreeCameraTouchInput:()=>Sc,FreeCameraVirtualJoystickInput:()=>Ic,FresnelBlock:()=>kb,FresnelParameters:()=>$v,FromHalfFloat:()=>Ip,FrontFace:()=>kf,FrontFacingBlock:()=>nb,Frustum:()=>ln,FxaaPostProcess:()=>DC,GIRSM:()=>kR,GIRSMManager:()=>GR,GIRSMRenderPluginMaterial:()=>WR,GPUParticleSystem:()=>sA,GUID:()=>qi,Gamepad:()=>ac,GamepadCamera:()=>Qc,GamepadManager:()=>jc,GamepadSystemSceneComponent:()=>Yc,GaussianSplattingMaterial:()=>aE,GaussianSplattingMesh:()=>Px,GenerateBase64StringFromPixelData:()=>Ka,GenerateBase64StringFromTexture:()=>Qa,GenerateBase64StringFromTextureAsync:()=>qa,GenericPad:()=>sc,GeodesicData:()=>Kd,Geometry:()=>vo,GeometryArcTan2Block:()=>ux,GeometryBufferRenderer:()=>BC,GeometryBufferRendererSceneComponent:()=>VC,GeometryClampBlock:()=>gx,GeometryCollectionBlock:()=>IS,GeometryCrossBlock:()=>yx,GeometryCurveBlock:()=>bx,GeometryCurveBlockTypes:()=>vx,GeometryDesaturateBlock:()=>Tx,GeometryDistanceBlock:()=>xx,GeometryDotBlock:()=>Ax,GeometryElbowBlock:()=>MS,GeometryInfoBlock:()=>ex,GeometryInputBlock:()=>tS,GeometryLengthBlock:()=>Cx,GeometryLerpBlock:()=>hx,GeometryModBlock:()=>_x,GeometryNLerpBlock:()=>dx,GeometryOptimizeBlock:()=>nS,GeometryOutputBlock:()=>$E,GeometryPosterizeBlock:()=>Ex,GeometryPowBlock:()=>mx,GeometryReplaceColorBlock:()=>Sx,GeometryRotate2dBlock:()=>Rx,GeometrySmoothStepBlock:()=>fx,GeometryStepBlock:()=>px,GeometryTextureBlock:()=>ox,GeometryTextureFetchBlock:()=>ax,GeometryTransformBlock:()=>BS,GeometryTrigonometryBlock:()=>wS,GeometryTrigonometryBlockOperations:()=>FS,GetClass:()=>s,GetClassName:()=>l,GetDOMTextContent:()=>dt,GetEnvInfo:()=>Vp,GetEnvironmentBRDFTexture:()=>km,GetFogState:()=>ha,GetFontOffset:()=>xo,GetInternalFormatFromBasisFormat:()=>My,GetPointsCount:()=>YE,GetTGAHeader:()=>by,GetTextureDataAsync:()=>Op,Gizmo:()=>Oh,GizmoAnchorPoint:()=>Rh,GizmoCoordinatesMode:()=>Ph,GizmoManager:()=>Sm,GlowLayer:()=>nv,GoldbergMesh:()=>qd,GradientBlock:()=>iT,GradientBlockColorStep:()=>tT,GradientHelper:()=>Kx,GrainPostProcess:()=>NC,GreasedLineBaseMesh:()=>BE,GreasedLineMaterialDefaults:()=>qT,GreasedLineMesh:()=>UE,GreasedLineMeshColorDistribution:()=>VE,GreasedLineMeshColorDistributionType:()=>BT,GreasedLineMeshColorMode:()=>wT,GreasedLineMeshMaterialType:()=>LT,GreasedLineMeshWidthDistribution:()=>kE,GreasedLinePluginMaterial:()=>$T,GreasedLineRibbonAutoDirectionMode:()=>LE,GreasedLineRibbonFacesMode:()=>FE,GreasedLineRibbonMesh:()=>HE,GreasedLineRibbonPointsMode:()=>NE,GreasedLineSimpleMaterial:()=>tE,GreasedLineTools:()=>ZT,GridBlock:()=>cS,GroundBuilder:()=>oh,GroundMesh:()=>Ju,HDRCubeTexture:()=>Pv,HDRCubeTextureAssetTask:()=>rP,HDRFiltering:()=>Rv,HDRTools:()=>Cv,Halton2DSequence:()=>cE,HandConstraintBehavior:()=>ql,HandConstraintOrientation:()=>Wl,HandConstraintVisibility:()=>Hl,HandConstraintZone:()=>zl,HandPart:()=>Vl,HandleFallbacksForShadows:()=>ua,HardwareScalingOptimization:()=>dP,HavokPlugin:()=>iC,HeightToNormalBlock:()=>ub,HemisphereBuilder:()=>Rm,HemisphericLight:()=>Ch,HemisphericParticleEmitter:()=>wx,HighlightLayer:()=>av,HighlightsPostProcess:()=>FC,Hinge2Joint:()=>Ms,HingeConstraint:()=>WA,HingeJoint:()=>Is,HtmlElementTexture:()=>sy,IWebXRControllerPhysicsOptions:()=>lI,IcoSphereBlock:()=>sS,IcoSphereBuilder:()=>Gl,ImageAssetTask:()=>eP,ImageProcessingBlock:()=>eb,ImageProcessingConfiguration:()=>pr,ImageProcessingPostProcess:()=>LC,ImageSourceBlock:()=>mb,IncrementValueAction:()=>ue,IndexFormat:()=>jf,InputBlock:()=>rl,InspectableType:()=>FP,InstancedLinesMesh:()=>ud,InstancedMesh:()=>La,InstancesBlock:()=>Zy,InstantiateBlock:()=>KS,InstantiateLinearBlock:()=>QS,InstantiateOnFacesBlock:()=>XS,InstantiateOnVerticesBlock:()=>HS,InstantiateOnVolumeBlock:()=>jS,InstantiateRadialBlock:()=>qS,InstantiatedEntries:()=>Ua,IntFloatConverterBlock:()=>ZS,InternalTexture:()=>Pi,InternalTextureSource:()=>Ti,InterpolateValueAction:()=>st,IntersectionInfo:()=>eo,IsBase64DataUrl:()=>zi,IsDocumentAvailable:()=>ht,IsFileURL:()=>Gi,IsNavigatorAvailable:()=>ut,IsWindowObjectExist:()=>ct,IsWrapper:()=>fr,JoystickAxis:()=>Cc,KeepAssets:()=>Ba,KeyboardEventTypes:()=>Xr,KeyboardInfo:()=>jr,KeyboardInfoPre:()=>Yr,KhronosTextureContainer:()=>gg,KhronosTextureContainer2:()=>Sg,LatheBuilder:()=>Md,Layer:()=>lv,LayerSceneComponent:()=>sv,LengthBlock:()=>Hb,LensFlare:()=>cv,LensFlareSystem:()=>uv,LensFlareSystemSceneComponent:()=>hv,LensFlaresOptimization:()=>_P,LensRenderingPipeline:()=>YC,LerpBlock:()=>Fb,Light:()=>wa,LightBlock:()=>_b,LightGizmo:()=>Im,LightInformationBlock:()=>$y,LineEdgesRenderer:()=>mR,LinesBuilder:()=>md,LinesMesh:()=>cd,LoadFile:()=>Vi,LoadFileError:()=>Di,LoadImage:()=>Bi,LoadOp:()=>Zf,LoadTextureFromTranscodeResult:()=>By,LockConstraint:()=>XA,Logger:()=>ae,MapMode:()=>Tf,MapRangeBlock:()=>SS,MappingBlock:()=>tx,MappingTypes:()=>$S,Material:()=>Ca,MaterialAnisotropicDefines:()=>Km,MaterialClearCoatDefines:()=>Hm,MaterialDefines:()=>Gs,MaterialDetailMapDefines:()=>Fu,MaterialFlags:()=>xu,MaterialGreasedLineDefines:()=>JT,MaterialHelper:()=>ey,MaterialIridescenceDefines:()=>jm,MaterialPluginBase:()=>Nu,MaterialPluginEvent:()=>Vo,MaterialPluginManager:()=>Cu,MaterialSheenDefines:()=>qm,MaterialSubSurfaceDefines:()=>Jm,MathBlock:()=>TS,MathBlockOperations:()=>yS,Matrix:()=>z,MatrixBuilderBlock:()=>ET,MatrixComposeBlock:()=>ix,MatrixDeterminantBlock:()=>IT,MatrixTransposeBlock:()=>OT,MaxBlock:()=>Gb,MergeGeometryBlock:()=>PS,MergeMeshesOptimization:()=>yP,Mesh:()=>Fa,MeshAssetTask:()=>qR,MeshAttributeExistsBlock:()=>NT,MeshAttributeExistsBlockTypes:()=>MT,MeshBlock:()=>aS,MeshBuilder:()=>rp,MeshDebugMode:()=>eE,MeshDebugPluginMaterial:()=>nE,MeshExploder:()=>sP,MeshLODLevel:()=>Pa,MeshParticleEmitter:()=>Gx,MeshUVSpaceRenderer:()=>SE,MeshoptCompression:()=>mE,MinBlock:()=>zb,MinMaxReducer:()=>fv,MipmapFilterMode:()=>If,MirrorTexture:()=>Dm,ModBlock:()=>bT,ModelShape:()=>dA,MorphTarget:()=>Iv,MorphTargetManager:()=>Ov,MorphTargetsBlock:()=>Jy,MotionBlurPostProcess:()=>kC,MotorEnabledJoint:()=>Ps,MultiMaterial:()=>Ra,MultiObserver:()=>cP,MultiPointerScaleBehavior:()=>vs,MultiRenderTarget:()=>ky,MultiplyBlock:()=>ml,NLerpBlock:()=>rT,NativeDataStream:()=>gp,NativeEngine:()=>mf,NativePointerInput:()=>Ar,NativeXRFrame:()=>jI,NativeXRLayerRenderTargetTextureProvider:()=>Qu,NativeXRLayerWrapper:()=>Ku,NativeXRRenderTarget:()=>qu,NegateBlock:()=>Xb,Node:()=>qe,NodeGeometry:()=>rS,NodeGeometryBlock:()=>JE,NodeGeometryBlockConnectionPointTypes:()=>GE,NodeGeometryBuildState:()=>eS,NodeGeometryConnectionPoint:()=>ZE,NodeGeometryConnectionPointCompatibilityStates:()=>zE,NodeGeometryConnectionPointDirection:()=>WE,NodeGeometryContextualSources:()=>qE,NodeMaterial:()=>Ll,NodeMaterialBlock:()=>Ws,NodeMaterialBlockConnectionPointMode:()=>Ks,NodeMaterialBlockConnectionPointTypes:()=>Ns,NodeMaterialBlockTargets:()=>Fs,NodeMaterialConnectionPoint:()=>zs,NodeMaterialConnectionPointCompatibilityStates:()=>Bs,NodeMaterialConnectionPointCustomObject:()=>Qy,NodeMaterialConnectionPointDirection:()=>Us,NodeMaterialDefines:()=>Fl,NodeMaterialModes:()=>fl,NodeMaterialOptimizer:()=>UT,NodeMaterialSystemValues:()=>Qs,NodeMaterialTeleportInBlock:()=>Sb,NodeMaterialTeleportOutBlock:()=>xb,NoiseBlock:()=>RS,NoiseProceduralTexture:()=>Hy,NormalBlendBlock:()=>aT,NormalizeBlock:()=>Ob,NormalizeVectorBlock:()=>NS,NullBlock:()=>fS,NullEngine:()=>cp,NullEngineOptions:()=>lp,Observable:()=>f,Observer:()=>p,OcclusionMaterial:()=>ty,Octree:()=>Th,OctreeBlock:()=>bh,OctreeSceneComponent:()=>Eh,OimoJSPlugin:()=>wv,OnAfterEnteringVRObservableEvent:()=>hh,OneMinusBlock:()=>Ub,Orientation:()=>vn,OutlineRenderer:()=>xR,PBRAnisotropicConfiguration:()=>Qm,PBRBaseMaterial:()=>ig,PBRBaseSimpleMaterial:()=>iy,PBRClearCoatConfiguration:()=>Xm,PBRIridescenceConfiguration:()=>Ym,PBRMaterial:()=>rg,PBRMaterialDefines:()=>tg,PBRMetallicRoughnessBlock:()=>yT,PBRMetallicRoughnessMaterial:()=>ry,PBRSheenConfiguration:()=>Zm,PBRSpecularGlossinessMaterial:()=>ny,PBRSubSurfaceConfiguration:()=>$m,PHI:()=>x,PadNumber:()=>Rt,PanoramaToCubeMapTools:()=>Av,Particle:()=>Qx,ParticleBlendMultiplyBlock:()=>sl,ParticleHelper:()=>cA,ParticleRampGradientBlock:()=>al,ParticleSystem:()=>aA,ParticleSystemSet:()=>lA,ParticleTextureBlock:()=>ol,ParticlesOptimization:()=>gP,PassCubePostProcess:()=>Zc,PassPostProcess:()=>qc,Path2:()=>xn,Path3D:()=>An,PathCursor:()=>Wn,PerfCollectionStrategy:()=>eI,PerfCounter:()=>an,PerformanceConfigurator:()=>I,PerformanceMonitor:()=>yo,PerformanceViewerCollector:()=>JP,PerturbNormalBlock:()=>ib,PhotoDome:()=>Um,Physics6DoFConstraint:()=>kA,Physics6DoFLimit:()=>VA,PhysicsActivationControl:()=>CA,PhysicsAggregate:()=>KA,PhysicsBody:()=>IA,PhysicsConstraint:()=>UA,PhysicsConstraintAxis:()=>bA,PhysicsConstraintAxisLimitMode:()=>yA,PhysicsConstraintMotorType:()=>SA,PhysicsConstraintType:()=>TA,PhysicsEngine:()=>Fv,PhysicsEngineV2:()=>RA,PhysicsEventType:()=>xA,PhysicsHelper:()=>sC,PhysicsImpostor:()=>Ds,PhysicsJoint:()=>Cs,PhysicsMaterialCombineMode:()=>PA,PhysicsMotionType:()=>AA,PhysicsRadialExplosionEventOptions:()=>dC,PhysicsRadialImpulseFalloff:()=>nC,PhysicsRaycastResult:()=>Nv,PhysicsShape:()=>MA,PhysicsShapeBox:()=>FA,PhysicsShapeCapsule:()=>DA,PhysicsShapeContainer:()=>BA,PhysicsShapeConvexHull:()=>LA,PhysicsShapeCylinder:()=>NA,PhysicsShapeMesh:()=>wA,PhysicsShapeSphere:()=>OA,PhysicsShapeType:()=>EA,PhysicsUpdraftEventOptions:()=>pC,PhysicsUpdraftMode:()=>oC,PhysicsViewer:()=>np,PhysicsVortexEventOptions:()=>fC,PickingInfo:()=>Fr,PipelineErrorReason:()=>Bf,PivotTools:()=>ds,Plane:()=>sn,PlaneBlock:()=>oS,PlaneBuilder:()=>_s,PlaneDragGizmo:()=>bm,PlaneRotationGizmo:()=>vm,PlayAnimationAction:()=>he,PlaySoundAction:()=>Te,PointColor:()=>uA,PointLight:()=>Sv,PointParticleEmitter:()=>Bx,PointerDragBehavior:()=>gs,PointerEventTypes:()=>Gr,PointerInfo:()=>Hr,PointerInfoBase:()=>zr,PointerInfoPre:()=>Wr,PointerInput:()=>xr,PointsCloudSystem:()=>vA,PointsGroup:()=>gA,Polar:()=>sE,Polygon:()=>yd,PolygonBuilder:()=>xd,PolygonMeshBuilder:()=>bd,PolyhedronBuilder:()=>Ld,PolyhedronData:()=>Yd,PositionGizmo:()=>Tm,PositionNormalTextureVertex:()=>$s,PositionNormalVertex:()=>Js,PostProcess:()=>hl,PostProcessManager:()=>Lr,PostProcessRenderEffect:()=>vC,PostProcessRenderPipeline:()=>WC,PostProcessRenderPipelineManager:()=>HC,PostProcessRenderPipelineManagerSceneComponent:()=>XC,PostProcessesOptimization:()=>fP,PosterizeBlock:()=>$b,PowBlock:()=>jb,PowerEase:()=>Fn,PowerPreference:()=>gf,PrePassOutputBlock:()=>pb,PrePassRenderer:()=>vR,PrePassRendererSceneComponent:()=>yR,PrePassTextureBlock:()=>Eb,PrecisionDate:()=>_t,PredicateCondition:()=>ne,PrepareAttributesForBakedVertexAnimation:()=>ra,PrepareAttributesForBones:()=>la,PrepareAttributesForInstances:()=>ca,PrepareAttributesForMorphTargets:()=>Zo,PrepareAttributesForMorphTargetsInfluencers:()=>qo,PrepareDefinesForAttributes:()=>ya,PrepareDefinesForBakedVertexAnimation:()=>va,PrepareDefinesForBones:()=>ma,PrepareDefinesForCamera:()=>Sa,PrepareDefinesForFrameBoundValues:()=>_a,PrepareDefinesForLight:()=>fa,PrepareDefinesForLights:()=>pa,PrepareDefinesForMergedUV:()=>ta,PrepareDefinesForMisc:()=>da,PrepareDefinesForMorphTargets:()=>ga,PrepareDefinesForMultiview:()=>ba,PrepareDefinesForOIT:()=>Ta,PrepareDefinesForPrePass:()=>Ea,PrepareUniformsAndSamplersForLight:()=>xa,PrepareUniformsAndSamplersList:()=>Aa,PressureObserverWrapper:()=>jP,PrimitiveTopology:()=>Vf,PrismaticConstraint:()=>jA,ProceduralTexture:()=>Ol,ProceduralTextureSceneComponent:()=>Il,PropertyTypeForEdition:()=>Xs,ProximityCastResult:()=>_C,PushAttributesForInstances:()=>Jo,PushMaterial:()=>ws,QuadraticEase:()=>Ln,QuadraticErrorSimplification:()=>DE,QuarticEase:()=>wn,Quaternion:()=>G,QueryType:()=>$f,QueueNewFrame:()=>Ii,QuinticEase:()=>Bn,RGBDTextureTools:()=>Np,RSMCreatePluginMaterial:()=>VR,Ragdoll:()=>qA,RagdollBoneProperties:()=>QA,RandomBlock:()=>CS,RandomBlockLocks:()=>xS,RandomGUID:()=>Qi,RandomNumberBlock:()=>Yb,RawCubeTexture:()=>Xy,RawTexture:()=>is,RawTexture2DArray:()=>Mv,RawTexture3D:()=>jy,Ray:()=>hs,RayHelper:()=>op,ReadFile:()=>Ui,ReadFileError:()=>Fi,RecastJSCrowd:()=>Mx,RecastJSPlugin:()=>Ix,ReciprocalBlock:()=>qb,ReflectBlock:()=>lT,ReflectionBlock:()=>pT,ReflectionProbe:()=>Uv,ReflectionTextureBaseBlock:()=>vb,ReflectionTextureBlock:()=>yb,ReflectiveShadowMap:()=>BR,Reflector:()=>XP,RefractBlock:()=>cT,RefractionBlock:()=>mT,RefractionPostProcess:()=>GC,RefractionTexture:()=>Yy,RegisterClass:()=>a,RegisterMaterialPlugin:()=>Mu,RegisterNativeTypeAsync:()=>pf,RemapBlock:()=>pl,RenderPassTimestampLocation:()=>qf,RenderTargetTexture:()=>Pl,RenderTargetWrapper:()=>cl,RenderTargetsOptimization:()=>vP,RenderingGroup:()=>wr,RenderingGroupInfo:()=>Br,RenderingManager:()=>Ur,ReplaceColorBlock:()=>Zb,RequestFile:()=>ki,RequestFileError:()=>Ni,RequestFullscreen:()=>Ro,RequestPointerlock:()=>Io,ResizeImageBitmap:()=>Co,RetryStrategy:()=>gt,RibbonBuilder:()=>Kh,RichType:()=>QI,RichTypeAny:()=>qI,RichTypeBoolean:()=>$I,RichTypeColor3:()=>nM,RichTypeColor4:()=>oM,RichTypeFlowGraphInteger:()=>sM,RichTypeMatrix:()=>rM,RichTypeNumber:()=>JI,RichTypeQuaternion:()=>aM,RichTypeString:()=>ZI,RichTypeVector2:()=>eM,RichTypeVector3:()=>tM,RichTypeVector4:()=>iM,RollingAverage:()=>bo,Rotate2dBlock:()=>sT,RotationGizmo:()=>ym,RotationXBlock:()=>US,RotationYBlock:()=>VS,RotationZBlock:()=>kS,RuntimeAnimation:()=>lt,RuntimeError:()=>bt,SSAO2RenderingPipeline:()=>QC,SSAORenderingPipeline:()=>qC,SSRRenderingPipeline:()=>rR,SamplerBindingType:()=>Nf,Scalar:()=>j,ScaleBlock:()=>Cb,ScaleGizmo:()=>Em,ScalingBlock:()=>GS,Scene:()=>pn,SceneComponentConstants:()=>Vr,SceneDepthBlock:()=>bb,SceneInstrumentation:()=>tv,SceneLoader:()=>Ls,SceneLoaderAnimationGroupLoadingMode:()=>Os,SceneLoaderFlags:()=>mo,SceneOptimization:()=>uP,SceneOptimizer:()=>TP,SceneOptimizerOptions:()=>bP,ScenePerformancePriority:()=>Kr,SceneRecorder:()=>VP,SceneSerializer:()=>AP,ScreenSizeBlock:()=>sb,ScreenSpaceBlock:()=>lb,ScreenSpaceCurvaturePostProcess:()=>lR,ScreenSpaceReflectionPostProcess:()=>JC,ScreenshotTools:()=>LP,SerializationHelper:()=>Ke,SetBasisTranscoderWorker:()=>Fy,SetColorsBlock:()=>vS,SetCorsBehavior:()=>wi,SetMaterialIDBlock:()=>LS,SetNormalsBlock:()=>mS,SetParentAction:()=>me,SetPositionsBlock:()=>_S,SetStateAction:()=>le,SetTangentsBlock:()=>bS,SetUVsBlock:()=>gS,SetValueAction:()=>ce,ShaderCodeInliner:()=>tf,ShaderLanguage:()=>pt,ShaderMaterial:()=>ld,ShaderStage:()=>Of,ShaderStore:()=>li,ShadowDepthWrapper:()=>kT,ShadowGenerator:()=>dv,ShadowGeneratorSceneComponent:()=>Ev,ShadowLight:()=>xm,ShadowMapBlock:()=>db,ShadowsOptimization:()=>pP,ShapeBuilder:()=>Pd,ShapeCastResult:()=>mC,SharpenPostProcess:()=>zC,SheenBlock:()=>hT,SimplexPerlin3DBlock:()=>oT,SimplicationQueueSceneComponent:()=>wE,SimplificationQueue:()=>RE,SimplificationSettings:()=>CE,SimplificationType:()=>xE,SineEase:()=>Un,SixDofDragBehavior:()=>bs,Size:()=>Ze,Skeleton:()=>rs,SkeletonViewer:()=>ap,SliderConstraint:()=>HA,SmartArray:()=>ar,SmartArrayNoDuplicate:()=>sr,SmoothStepBlock:()=>Qb,SolidParticle:()=>hA,SolidParticleSystem:()=>_A,SolidParticleVertex:()=>fA,Sound:()=>Ga,SoundTrack:()=>za,SourceTextureFormat:()=>fg,Space:()=>dn,SphereBlock:()=>lS,SphereBuilder:()=>zh,SphereDirectedParticleEmitter:()=>Vx,SphereParticleEmitter:()=>Ux,Spherical:()=>lE,SphericalHarmonics:()=>Ep,SphericalPolynomial:()=>Sp,SpotLight:()=>Pm,SpringConstraint:()=>YA,Sprite:()=>Vv,SpriteManager:()=>zv,SpriteMap:()=>XR,SpritePackedManager:()=>jR,SpriteSceneComponent:()=>kv,Stage:()=>kr,StandardMaterial:()=>Uu,StandardMaterialDefines:()=>Bu,StandardRenderingPipeline:()=>$C,StartsWith:()=>Et,StateCondition:()=>oe,StencilOperation:()=>Xf,StencilState:()=>Ai,StencilStateComposer:()=>xi,StepBlock:()=>Bb,StereoscopicArcRotateCamera:()=>su,StereoscopicFreeCamera:()=>lu,StereoscopicGamepadCamera:()=>cu,StereoscopicInterlacePostProcess:()=>ou,StereoscopicInterlacePostProcessI:()=>nu,StereoscopicScreenUniversalCamera:()=>hu,StereoscopicUniversalCamera:()=>uu,StickValues:()=>oc,StopAnimationAction:()=>de,StopSoundAction:()=>Ee,StorageBuffer:()=>$l,StorageTextureAccess:()=>Lf,StoreOp:()=>Jf,StringDictionary:()=>lr,StringTools:()=>Pt,SubEmitter:()=>Jx,SubEmitterType:()=>qx,SubMesh:()=>po,SubSurfaceBlock:()=>gT,SubSurfaceSceneComponent:()=>ER,SubtractBlock:()=>wb,SurfaceMagnetismBehavior:()=>Ts,SwitchBooleanAction:()=>se,SwitchInput:()=>Ir,TAARenderingPipeline:()=>nR,TBNBlock:()=>tb,TGATools:()=>Ey,Tags:()=>je,TargetCamera:()=>Mc,TargetedAnimation:()=>Gn,TeleportInBlock:()=>rx,TeleportOutBlock:()=>nx,TestBase64DataUrl:()=>Wi,TextFileAssetTask:()=>JR,Texture:()=>Ja,TextureAspect:()=>Af,TextureAssetTask:()=>tP,TextureBlock:()=>gb,TextureDimension:()=>Ef,TextureFormat:()=>Cf,TextureOptimization:()=>hP,TexturePacker:()=>zy,TexturePackerFrame:()=>Gy,TextureSampleType:()=>Ff,TextureSampler:()=>Ri,TextureTools:()=>Dp,TextureUsage:()=>Sf,TextureViewDimension:()=>xf,ThinEngine:()=>Er,ThinRenderTargetTexture:()=>Ky,ThinTexture:()=>ja,TiledBoxBuilder:()=>rd,TiledPlaneBuilder:()=>ed,TimerState:()=>Gg,TmpColors:()=>$,TmpVectors:()=>H,ToGammaSpace:()=>E,ToHalfFloat:()=>Pp,ToLinearSpace:()=>S,TonemapPostProcess:()=>aR,TonemappingOperator:()=>oR,Tools:()=>rr,TorusBlock:()=>uS,TorusBuilder:()=>lh,TorusKnotBuilder:()=>ad,TouchCamera:()=>Dc,TrailMesh:()=>AE,Trajectory:()=>kP,TrajectoryClassifier:()=>HP,TranscodeAsync:()=>Ly,TranscodeTarget:()=>_g,TransformBlock:()=>Hs,TransformNode:()=>Fo,TranslationBlock:()=>WS,TriPlanarBlock:()=>RT,TrigonometryBlock:()=>Dl,TrigonometryBlockOperations:()=>Ml,TubeBuilder:()=>Dd,TwirlBlock:()=>cb,UniformBuffer:()=>Or,UniversalCamera:()=>Kc,UnregisterAllMaterialPlugins:()=>Du,UnregisterMaterialPlugin:()=>Ou,UploadContent:()=>Ty,UploadEnvLevelsAsync:()=>Hp,UploadEnvSpherical:()=>Yp,UploadLevelsAsync:()=>jp,UtilityLayerRenderer:()=>Ih,VRCameraMetrics:()=>pu,VRDeviceOrientationArcRotateCamera:()=>bu,VRDeviceOrientationFreeCamera:()=>Tu,VRDeviceOrientationGamepadCamera:()=>Eu,VRDistortionCorrectionPostProcess:()=>fu,VRExperienceHelper:()=>dh,VRMultiviewToSingleviewPostProcess:()=>vu,ValidatedNativeDataStream:()=>r_,ValueCondition:()=>re,Vector2:()=>U,Vector2ToFixed:()=>uE,Vector3:()=>V,Vector3ToFixed:()=>hE,Vector4:()=>k,Vector4ToFixed:()=>dE,VectorConverterBlock:()=>DS,VectorMergerBlock:()=>dl,VectorSplitterBlock:()=>Nb,VertexAnimationBaker:()=>ns,VertexBuffer:()=>Nr,VertexData:()=>_o,VertexDataMaterialInfo:()=>fo,VertexFormat:()=>Yf,VertexOutputBlock:()=>js,VertexStepMode:()=>Kf,VideoDome:()=>$g,VideoRecorder:()=>CP,VideoTexture:()=>Jg,ViewDirectionBlock:()=>Vb,Viewport:()=>Jn,VirtualJoystick:()=>Pc,VirtualJoysticksCamera:()=>du,VolumetricLightScatteringPostProcess:()=>sR,VoronoiNoiseBlock:()=>AT,WaveBlock:()=>eT,WaveBlockKind:()=>Jb,WebGL2ParticleSystem:()=>Wx,WebGL2ShaderProcessor:()=>gr,WebGLDataBuffer:()=>yr,WebGLHardwareTexture:()=>br,WebGLPipelineContext:()=>ci,WebGPUCacheBindGroups:()=>k_,WebGPUCacheRenderPipeline:()=>O_,WebGPUCacheRenderPipelineTree:()=>N_,WebGPUCacheSampler:()=>R_,WebGPUDataBuffer:()=>E_,WebGPUDrawContext:()=>U_,WebGPUEngine:()=>sm,WebGPURenderTargetWrapper:()=>dm,WebGPUTintWASM:()=>em,WebRequest:()=>Je,WebXRAbstractFeature:()=>As,WebXRAbstractMotionController:()=>Pg,WebXRAnchorSystem:()=>nI,WebXRBackgroundRemover:()=>sI,WebXRCamera:()=>Ag,WebXRControllerComponent:()=>Rg,WebXRControllerMovement:()=>gI,WebXRControllerPhysics:()=>cI,WebXRControllerPointerSelection:()=>Vg,WebXRDefaultExperience:()=>Qg,WebXRDefaultExperienceOptions:()=>Kg,WebXRDepthSensing:()=>DI,WebXRDomOverlay:()=>mI,WebXREnterExitUI:()=>Hg,WebXREnterExitUIButton:()=>zg,WebXREnterExitUIOptions:()=>Wg,WebXRExperienceHelper:()=>Cg,WebXREyeTracking:()=>yI,WebXRFeatureName:()=>Ss,WebXRFeaturePointSystem:()=>hI,WebXRFeaturesManager:()=>xs,WebXRGenericHandController:()=>BI,WebXRGenericTriggerMotionController:()=>Ig,WebXRHTCViveMotionController:()=>WI,WebXRHand:()=>Yl,WebXRHandJoint:()=>kl,WebXRHandTracking:()=>Kl,WebXRHitTest:()=>uI,WebXRHitTestLegacy:()=>iI,WebXRImageTracking:()=>_I,WebXRInput:()=>Ug,WebXRInputSource:()=>Bg,WebXRLayerRenderTargetTextureProvider:()=>Wu,WebXRLayers:()=>OI,WebXRLightEstimation:()=>vI,WebXRManagedOutputCanvas:()=>Yu,WebXRManagedOutputCanvasOptions:()=>ju,WebXRMeshDetector:()=>fI,WebXRMicrosoftMixedRealityController:()=>VI,WebXRMotionControllerManager:()=>Ng,WebXRMotionControllerTeleportation:()=>Yg,WebXRNearControllerMode:()=>Lg,WebXRNearInteraction:()=>kg,WebXROculusTouchMotionController:()=>GI,WebXRPlaneDetector:()=>aI,WebXRProfiledMotionController:()=>Og,WebXRRawCameraAccess:()=>wI,WebXRSessionManager:()=>Zu,WebXRSpaceWarp:()=>LI,WebXRSpaceWarpRenderTargetTextureProvider:()=>FI,WebXRState:()=>Vu,WebXRTrackingState:()=>ku,WebXRWalkingLocomotion:()=>xI,WeightedSound:()=>Ha,WorkerPool:()=>vg,WorleyNoise3DBlock:()=>nT,XRSpaceWarpRenderTarget:()=>NI,Xbox360Button:()=>Uc,Xbox360Dpad:()=>Vc,Xbox360Pad:()=>Hc,XboxInput:()=>Pr,_BabylonLoaderRegistered:()=>Wv,_BasisTextureLoader:()=>Vy,_CommonDispose:()=>So,_CommonInit:()=>Eo,_CreationDataStorage:()=>Ia,_DDSTextureLoader:()=>dg,_ENVTextureLoader:()=>pg,_HDRTextureLoader:()=>xy,_InstancesBatch:()=>Oa,_KTXTextureLoader:()=>xg,_MeshCollisionData:()=>Lo,_OcclusionDataStorage:()=>up,_PrimaryIsoTriangle:()=>jd,_TGATextureLoader:()=>Sy,_TimeToken:()=>hp,_UpdateRGBDAsync:()=>Kp,_forceSceneHelpersToBundle:()=>qg,_forceTransformFeedbackToBundle:()=>dp,_injectLTSFileTools:()=>Yi,_staticOffsetValueColor3:()=>rt,_staticOffsetValueColor4:()=>nt,_staticOffsetValueQuaternion:()=>$e,_staticOffsetValueSize:()=>it,_staticOffsetValueVector2:()=>tt,_staticOffsetValueVector3:()=>et,addClipPlaneUniforms:()=>Go,allocateAndCopyTypedBuffer:()=>To,bindClipPlane:()=>Ho,captureEquirectangularFromScene:()=>tI,className:()=>nr,createDetailMapPlugin:()=>QT,createPBRAnisotropicPlugin:()=>WT,createPBRBRDFPlugin:()=>HT,createPBRClearCoatPlugin:()=>XT,createPBRIridescencePlugin:()=>jT,createPBRSheenPlugin:()=>YT,createPBRSubSurfacePlugin:()=>KT,createYieldingScheduler:()=>jn,editableInPropertyPage:()=>Ys,expandToProperty:()=>Pe,extractMinAndMax:()=>uo,extractMinAndMaxIndexed:()=>co,getRichTypeFromValue:()=>lM,inlineScheduler:()=>Xn,makeAsyncFunction:()=>Zn,makeSyncFunction:()=>qn,nativeOverride:()=>ze,normalizeEnvInfo:()=>kp,prepareDefinesForClipPlanes:()=>Wo,prepareStringDefinesForClipPlanes:()=>zo,runCoroutine:()=>Yn,runCoroutineAsync:()=>Qn,runCoroutineSync:()=>Kn,serialize:()=>Ie,serializeAsCameraReference:()=>Ge,serializeAsColor3:()=>Oe,serializeAsColor4:()=>Be,serializeAsColorCurves:()=>we,serializeAsFresnelParameters:()=>De,serializeAsImageProcessingConfiguration:()=>Ue,serializeAsMatrix:()=>ke,serializeAsMeshReference:()=>Le,serializeAsQuaternion:()=>Ve,serializeAsTexture:()=>Me,serializeAsVector2:()=>Ne,serializeAsVector3:()=>Fe,setAndStartTimer:()=>Xg,setStereoscopicAnaglyphRigMode:()=>$c,setStereoscopicRigMode:()=>au,setVRRigMode:()=>yu});var o={};function a(e,t){o[e]=t}function s(e){return o[e]}function l(e){for(var t in o)if(e instanceof o[t]&&!t.includes("Abstract"))return t;return"Unknown"}var c=function(){function e(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[]}return e.AddParser=function(e,t){this._BabylonFileParsers[e]=t},e.GetParser=function(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null},e.AddIndividualParser=function(e,t){this._IndividualBabylonFileParsers[e]=t},e.GetIndividualParser=function(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null},e.Parse=function(e,t,i,r){for(var n in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,n)&&this._BabylonFileParsers[n](e,t,i,r)},Object.defineProperty(e.prototype,"environmentTexture",{get:function(){return this._environmentTexture},set:function(e){this._environmentTexture=e},enumerable:!1,configurable:!0}),e.prototype.getNodes=function(){var e=[];return e=(e=(e=(e=e.concat(this.meshes)).concat(this.lights)).concat(this.cameras)).concat(this.transformNodes),this.skeletons.forEach((function(t){return e=e.concat(t.bones)})),e},e._BabylonFileParsers={},e._IndividualBabylonFileParsers={},e}();a("BABYLON.AbstractScene",c);var u=function(){function e(){}return e.ALPHA_DISABLE=0,e.ALPHA_ADD=1,e.ALPHA_COMBINE=2,e.ALPHA_SUBTRACT=3,e.ALPHA_MULTIPLY=4,e.ALPHA_MAXIMIZED=5,e.ALPHA_ONEONE=6,e.ALPHA_PREMULTIPLIED=7,e.ALPHA_PREMULTIPLIED_PORTERDUFF=8,e.ALPHA_INTERPOLATE=9,e.ALPHA_SCREENMODE=10,e.ALPHA_ONEONE_ONEONE=11,e.ALPHA_ALPHATOCOLOR=12,e.ALPHA_REVERSEONEMINUS=13,e.ALPHA_SRC_DSTONEMINUSSRCALPHA=14,e.ALPHA_ONEONE_ONEZERO=15,e.ALPHA_EXCLUSION=16,e.ALPHA_LAYER_ACCUMULATE=17,e.ALPHA_EQUATION_ADD=0,e.ALPHA_EQUATION_SUBSTRACT=1,e.ALPHA_EQUATION_REVERSE_SUBTRACT=2,e.ALPHA_EQUATION_MAX=3,e.ALPHA_EQUATION_MIN=4,e.ALPHA_EQUATION_DARKEN=5,e.DELAYLOADSTATE_NONE=0,e.DELAYLOADSTATE_LOADED=1,e.DELAYLOADSTATE_LOADING=2,e.DELAYLOADSTATE_NOTLOADED=4,e.NEVER=512,e.ALWAYS=519,e.LESS=513,e.EQUAL=514,e.LEQUAL=515,e.GREATER=516,e.GEQUAL=518,e.NOTEQUAL=517,e.KEEP=7680,e.ZERO=0,e.REPLACE=7681,e.INCR=7682,e.DECR=7683,e.INVERT=5386,e.INCR_WRAP=34055,e.DECR_WRAP=34056,e.TEXTURE_CLAMP_ADDRESSMODE=0,e.TEXTURE_WRAP_ADDRESSMODE=1,e.TEXTURE_MIRROR_ADDRESSMODE=2,e.TEXTURE_CREATIONFLAG_STORAGE=1,e.TEXTUREFORMAT_ALPHA=0,e.TEXTUREFORMAT_LUMINANCE=1,e.TEXTUREFORMAT_LUMINANCE_ALPHA=2,e.TEXTUREFORMAT_RGB=4,e.TEXTUREFORMAT_RGBA=5,e.TEXTUREFORMAT_RED=6,e.TEXTUREFORMAT_R=6,e.TEXTUREFORMAT_RG=7,e.TEXTUREFORMAT_RED_INTEGER=8,e.TEXTUREFORMAT_R_INTEGER=8,e.TEXTUREFORMAT_RG_INTEGER=9,e.TEXTUREFORMAT_RGB_INTEGER=10,e.TEXTUREFORMAT_RGBA_INTEGER=11,e.TEXTUREFORMAT_BGRA=12,e.TEXTUREFORMAT_DEPTH24_STENCIL8=13,e.TEXTUREFORMAT_DEPTH32_FLOAT=14,e.TEXTUREFORMAT_DEPTH16=15,e.TEXTUREFORMAT_DEPTH24=16,e.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17,e.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18,e.TEXTUREFORMAT_STENCIL8=19,e.TEXTUREFORMAT_UNDEFINED=4294967295,e.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492,e.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493,e.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495,e.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494,e.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779,e.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919,e.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778,e.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918,e.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777,e.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776,e.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917,e.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916,e.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808,e.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840,e.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196,e.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492,e.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493,e.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494,e.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495,e.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496,e.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497,e.TEXTURETYPE_UNSIGNED_BYTE=0,e.TEXTURETYPE_UNSIGNED_INT=0,e.TEXTURETYPE_FLOAT=1,e.TEXTURETYPE_HALF_FLOAT=2,e.TEXTURETYPE_BYTE=3,e.TEXTURETYPE_SHORT=4,e.TEXTURETYPE_UNSIGNED_SHORT=5,e.TEXTURETYPE_INT=6,e.TEXTURETYPE_UNSIGNED_INTEGER=7,e.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,e.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,e.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,e.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,e.TEXTURETYPE_UNSIGNED_INT_24_8=12,e.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,e.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,e.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,e.TEXTURETYPE_UNDEFINED=16,e.TEXTURE_2D=3553,e.TEXTURE_2D_ARRAY=35866,e.TEXTURE_CUBE_MAP=34067,e.TEXTURE_CUBE_MAP_ARRAY=3735928559,e.TEXTURE_3D=32879,e.TEXTURE_NEAREST_SAMPLINGMODE=1,e.TEXTURE_NEAREST_NEAREST=1,e.TEXTURE_BILINEAR_SAMPLINGMODE=2,e.TEXTURE_LINEAR_LINEAR=2,e.TEXTURE_TRILINEAR_SAMPLINGMODE=3,e.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,e.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,e.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,e.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,e.TEXTURE_NEAREST_LINEAR=7,e.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,e.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,e.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,e.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,e.TEXTURE_LINEAR_NEAREST=12,e.TEXTURE_EXPLICIT_MODE=0,e.TEXTURE_SPHERICAL_MODE=1,e.TEXTURE_PLANAR_MODE=2,e.TEXTURE_CUBIC_MODE=3,e.TEXTURE_PROJECTION_MODE=4,e.TEXTURE_SKYBOX_MODE=5,e.TEXTURE_INVCUBIC_MODE=6,e.TEXTURE_EQUIRECTANGULAR_MODE=7,e.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,e.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,e.TEXTURE_FILTERING_QUALITY_OFFLINE=4096,e.TEXTURE_FILTERING_QUALITY_HIGH=64,e.TEXTURE_FILTERING_QUALITY_MEDIUM=16,e.TEXTURE_FILTERING_QUALITY_LOW=8,e.SCALEMODE_FLOOR=1,e.SCALEMODE_NEAREST=2,e.SCALEMODE_CEILING=3,e.MATERIAL_TextureDirtyFlag=1,e.MATERIAL_LightDirtyFlag=2,e.MATERIAL_FresnelDirtyFlag=4,e.MATERIAL_AttributesDirtyFlag=8,e.MATERIAL_MiscDirtyFlag=16,e.MATERIAL_PrePassDirtyFlag=32,e.MATERIAL_AllDirtyFlag=63,e.MATERIAL_TriangleFillMode=0,e.MATERIAL_WireFrameFillMode=1,e.MATERIAL_PointFillMode=2,e.MATERIAL_PointListDrawMode=3,e.MATERIAL_LineListDrawMode=4,e.MATERIAL_LineLoopDrawMode=5,e.MATERIAL_LineStripDrawMode=6,e.MATERIAL_TriangleStripDrawMode=7,e.MATERIAL_TriangleFanDrawMode=8,e.MATERIAL_ClockWiseSideOrientation=0,e.MATERIAL_CounterClockWiseSideOrientation=1,e.ACTION_NothingTrigger=0,e.ACTION_OnPickTrigger=1,e.ACTION_OnLeftPickTrigger=2,e.ACTION_OnRightPickTrigger=3,e.ACTION_OnCenterPickTrigger=4,e.ACTION_OnPickDownTrigger=5,e.ACTION_OnDoublePickTrigger=6,e.ACTION_OnPickUpTrigger=7,e.ACTION_OnPickOutTrigger=16,e.ACTION_OnLongPressTrigger=8,e.ACTION_OnPointerOverTrigger=9,e.ACTION_OnPointerOutTrigger=10,e.ACTION_OnEveryFrameTrigger=11,e.ACTION_OnIntersectionEnterTrigger=12,e.ACTION_OnIntersectionExitTrigger=13,e.ACTION_OnKeyDownTrigger=14,e.ACTION_OnKeyUpTrigger=15,e.PARTICLES_BILLBOARDMODE_Y=2,e.PARTICLES_BILLBOARDMODE_ALL=7,e.PARTICLES_BILLBOARDMODE_STRETCHED=8,e.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9,e.MESHES_CULLINGSTRATEGY_STANDARD=0,e.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,e.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,e.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,e.SCENELOADER_NO_LOGGING=0,e.SCENELOADER_MINIMAL_LOGGING=1,e.SCENELOADER_SUMMARY_LOGGING=2,e.SCENELOADER_DETAILED_LOGGING=3,e.PREPASS_IRRADIANCE_TEXTURE_TYPE=0,e.PREPASS_POSITION_TEXTURE_TYPE=1,e.PREPASS_VELOCITY_TEXTURE_TYPE=2,e.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3,e.PREPASS_COLOR_TEXTURE_TYPE=4,e.PREPASS_DEPTH_TEXTURE_TYPE=5,e.PREPASS_NORMAL_TEXTURE_TYPE=6,e.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7,e.BUFFER_CREATIONFLAG_READ=1,e.BUFFER_CREATIONFLAG_WRITE=2,e.BUFFER_CREATIONFLAG_READWRITE=3,e.BUFFER_CREATIONFLAG_UNIFORM=4,e.BUFFER_CREATIONFLAG_VERTEX=8,e.BUFFER_CREATIONFLAG_INDEX=16,e.BUFFER_CREATIONFLAG_STORAGE=32,e.BUFFER_CREATIONFLAG_INDIRECT=64,e.RENDERPASS_MAIN=0,e.INPUT_ALT_KEY=18,e.INPUT_CTRL_KEY=17,e.INPUT_META_KEY1=91,e.INPUT_META_KEY2=92,e.INPUT_META_KEY3=93,e.INPUT_SHIFT_KEY=16,e.SNAPSHOTRENDERING_STANDARD=0,e.SNAPSHOTRENDERING_FAST=1,e.PERSPECTIVE_CAMERA=0,e.ORTHOGRAPHIC_CAMERA=1,e.FOVMODE_VERTICAL_FIXED=0,e.FOVMODE_HORIZONTAL_FIXED=1,e.RIG_MODE_NONE=0,e.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,e.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,e.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,e.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,e.RIG_MODE_STEREOSCOPIC_INTERLACED=14,e.RIG_MODE_VR=20,e.RIG_MODE_CUSTOM=22,e.MAX_SUPPORTED_UV_SETS=6,e.GL_ALPHA_EQUATION_ADD=32774,e.GL_ALPHA_EQUATION_MIN=32775,e.GL_ALPHA_EQUATION_MAX=32776,e.GL_ALPHA_EQUATION_SUBTRACT=32778,e.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779,e.GL_ALPHA_FUNCTION_SRC=768,e.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769,e.GL_ALPHA_FUNCTION_SRC_ALPHA=770,e.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771,e.GL_ALPHA_FUNCTION_DST_ALPHA=772,e.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773,e.GL_ALPHA_FUNCTION_DST_COLOR=774,e.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775,e.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776,e.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769,e.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770,e.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771,e.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772,e.SnippetUrl="https://snippet.babylonjs.com",e.FOGMODE_NONE=0,e.FOGMODE_EXP=1,e.FOGMODE_EXP2=2,e.FOGMODE_LINEAR=3,e.BYTE=5120,e.UNSIGNED_BYTE=5121,e.SHORT=5122,e.UNSIGNED_SHORT=5123,e.INT=5124,e.UNSIGNED_INT=5125,e.FLOAT=5126,e.PositionKind="position",e.NormalKind="normal",e.TangentKind="tangent",e.UVKind="uv",e.UV2Kind="uv2",e.UV3Kind="uv3",e.UV4Kind="uv4",e.UV5Kind="uv5",e.UV6Kind="uv6",e.ColorKind="color",e.ColorInstanceKind="instanceColor",e.MatricesIndicesKind="matricesIndices",e.MatricesWeightsKind="matricesWeights",e.MatricesIndicesExtraKind="matricesIndicesExtra",e.MatricesWeightsExtraKind="matricesWeightsExtra",e}(),h=function(){function e(){this.hoverCursor="",this.actions=[],this.isRecursive=!1}return Object.defineProperty(e,"HasTriggers",{get:function(){for(var t in e.Triggers)if(Object.prototype.hasOwnProperty.call(e.Triggers,t))return!0;return!1},enumerable:!1,configurable:!0}),Object.defineProperty(e,"HasPickTriggers",{get:function(){for(var t in e.Triggers)if(Object.prototype.hasOwnProperty.call(e.Triggers,t)){var i=parseInt(t);if(i>=u.ACTION_OnPickTrigger&&i<=u.ACTION_OnPickUpTrigger)return!0}return!1},enumerable:!1,configurable:!0}),e.HasSpecificTrigger=function(t){for(var i in e.Triggers)if(Object.prototype.hasOwnProperty.call(e.Triggers,i)&&parseInt(i)===t)return!0;return!1},e.Triggers={},e}(),d=function(){function e(e,t,i,r){void 0===t&&(t=!1),this.initialize(e,t,i,r)}return e.prototype.initialize=function(e,t,i,r){return void 0===t&&(t=!1),this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=r,this},e}(),p=function(){function e(e,t,i){void 0===i&&(i=null),this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}return e.prototype.remove=function(){this._remove&&this._remove()},e}(),f=function(){function e(e,t){void 0===t&&(t=!1),this.notifyIfTriggered=t,this._observers=new Array,this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new d(0),e&&(this._onObserverAdded=e)}return e.FromPromise=function(t,i){var r=new e;return t.then((function(e){r.notifyObservers(e)})).catch((function(e){if(!i)throw e;i.notifyObservers(e)})),r},Object.defineProperty(e.prototype,"observers",{get:function(){return this._observers},enumerable:!1,configurable:!0}),e.prototype.add=function(e,t,i,r,n){var o=this;if(void 0===t&&(t=-1),void 0===i&&(i=!1),void 0===r&&(r=null),void 0===n&&(n=!1),!e)return null;var a=new p(e,t,r);return a.unregisterOnNextCall=n,i?this._observers.unshift(a):this._observers.push(a),this._onObserverAdded&&this._onObserverAdded(a),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(a,this._lastNotifiedValue),a._remove=function(){o.remove(a)},a},e.prototype.addOnce=function(e){return this.add(e,void 0,void 0,void 0,!0)},e.prototype.remove=function(e){return!!e&&(e._remove=null,-1!==this._observers.indexOf(e)&&(this._deferUnregister(e),!0))},e.prototype.removeCallback=function(e,t){for(var i=0;i<this._observers.length;i++){var r=this._observers[i];if(!(r._willBeUnregistered||r.callback!==e||t&&t!==r.scope))return this._deferUnregister(r),!0}return!1},e.prototype._deferUnregister=function(e){var t=this;e._willBeUnregistered||(this._numObserversMarkedAsDeleted++,e.unregisterOnNextCall=!1,e._willBeUnregistered=!0,setTimeout((function(){t._remove(e)}),0))},e.prototype._remove=function(e,t){if(void 0===t&&(t=!0),!e)return!1;var i=this._observers.indexOf(e);return-1!==i&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0)},e.prototype.makeObserverTopPriority=function(e){this._remove(e,!1),this._observers.unshift(e)},e.prototype.makeObserverBottomPriority=function(e){this._remove(e,!1),this._observers.push(e)},e.prototype.notifyObservers=function(e,t,i,r,n){if(void 0===t&&(t=-1),this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;var o=this._eventState;o.mask=t,o.target=i,o.currentTarget=r,o.skipNextObservers=!1,o.lastReturnValue=e,o.userInfo=n;for(var a=0,s=this._observers;a<s.length;a++){var l=s[a];if(!l._willBeUnregistered&&(l.mask&t&&(l.unregisterOnNextCall&&this._deferUnregister(l),l.scope?o.lastReturnValue=l.callback.apply(l.scope,[e,o]):o.lastReturnValue=l.callback(e,o)),o.skipNextObservers))return!1}return!0},e.prototype.notifyObserver=function(e,t,i){if(void 0===i&&(i=-1),this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),!e._willBeUnregistered){var r=this._eventState;r.mask=i,r.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,r)}},e.prototype.hasObservers=function(){return this._observers.length-this._numObserversMarkedAsDeleted>0},e.prototype.clear=function(){for(;this._observers.length;){var e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()},e.prototype.cleanLastNotifiedState=function(){this._hasNotified=!1,this._lastNotifiedValue=void 0},e.prototype.clone=function(){var t=new e;return t._observers=this._observers.slice(0),t},e.prototype.hasSpecificMask=function(e){void 0===e&&(e=-1);for(var t=0,i=this._observers;t<i.length;t++){var r=i[t];if(r.mask&e||r.mask===e)return!0}return!1},e}(),_=function(e,t){return _=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},_(e,t)};function m(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}_(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}var g=function(){return g=Object.assign||function(e){for(var t,i=1,r=arguments.length;i<r;i++)for(var n in t=arguments[i])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},g.apply(this,arguments)};function v(e,t,i,r){var n,o=arguments.length,a=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,r);else for(var s=e.length-1;s>=0;s--)(n=e[s])&&(a=(o<3?n(a):o>3?n(t,i,a):n(t,i))||a);return o>3&&a&&Object.defineProperty(t,i,a),a}function y(e,t,i,r){return new(i||(i=Promise))((function(n,o){function a(e){try{l(r.next(e))}catch(e){o(e)}}function s(e){try{l(r.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(a,s)}l((r=r.apply(e,t||[])).next())}))}function b(e,t){var i,r,n,o,a={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(l){return function(s){if(i)throw new TypeError("Generator is already executing.");for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(i=1,r&&(n=2&s[0]?r.return:s[0]?r.throw||((n=r.return)&&n.call(r),0):r.next)&&!(n=n.call(r,s[1])).done)return n;switch(r=0,n&&(s=[2&s[0],n.value]),s[0]){case 0:case 1:n=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((n=(n=a.trys).length>0&&n[n.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!n||s[1]>n[0]&&s[1]<n[3])){a.label=s[1];break}if(6===s[0]&&a.label<n[1]){a.label=n[1],n=s;break}if(n&&a.label<n[2]){a.label=n[2],a.ops.push(s);break}n[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{i=n=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,l])}}}function T(e,t,i){if(i||2===arguments.length)for(var r,n=0,o=t.length;n<o;n++)!r&&n in t||(r||(r=Array.prototype.slice.call(t,0,n)),r[n]=t[n]);return e.concat(r||Array.prototype.slice.call(t))}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;var E=1/2.2,S=2.2,x=(1+Math.sqrt(5))/2,A=.001,C=function(){function e(){}return e.BuildArray=function(e,t){for(var i=[],r=0;r<e;++r)i.push(t());return i},e.BuildTuple=function(t,i){return e.BuildArray(t,i)},e}(),R=["push","splice","pop","shift","unshift"];function P(e,t){var i=R.map((function(i){return function(e,t,i){var r=e[t];if("function"!=typeof r)return null;var n=function(){var r=e.length,o=n.previous.apply(e,arguments);return i(t,r),o};return r.next=n,n.previous=r,e[t]=n,function(){var i=n.previous;if(i){var r=n.next;r?(i.next=r,r.previous=i):(i.next=void 0,e[t]=i),n.next=void 0,n.previous=void 0}}}(e,i,t)}));return function(){i.forEach((function(e){null==e||e()}))}}var I=function(){function e(){}return e.SetMatrixPrecision=function(t){if(e.MatrixTrackPrecisionChange=!1,t&&!e.MatrixUse64Bits&&e.MatrixTrackedMatrices)for(var i=0;i<e.MatrixTrackedMatrices.length;++i){var r=e.MatrixTrackedMatrices[i],n=r._m;r._m=new Array(16);for(var o=0;o<16;++o)r._m[o]=n[o]}e.MatrixUse64Bits=t,e.MatrixCurrentType=e.MatrixUse64Bits?Array:Float32Array,e.MatrixTrackedMatrices=null},e.MatrixUse64Bits=!1,e.MatrixTrackPrecisionChange=!0,e.MatrixCurrentType=Float32Array,e.MatrixTrackedMatrices=[],e}(),M=function(){function e(){}return Object.defineProperty(e,"LastCreatedEngine",{get:function(){return 0===this.Instances.length?null:this.Instances[this.Instances.length-1]},enumerable:!1,configurable:!0}),Object.defineProperty(e,"LastCreatedScene",{get:function(){return this._LastCreatedScene},enumerable:!1,configurable:!0}),e.Instances=[],e.OnEnginesDisposedObservable=new f,e._LastCreatedScene=null,e.UseFallbackTexture=!0,e.FallbackTexture="",e}();function O(e,t,i){return void 0===i&&(i=1401298e-51),Math.abs(e-t)<=i}function D(e,t){return e===t?e:Math.random()*(t-e)+e}function N(e,t,i){return e+(t-e)*i}function F(e,t,i){return void 0===t&&(t=0),void 0===i&&(i=1),Math.min(i,Math.max(t,e))}function L(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}function w(e){var t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()}var B=function(e){return parseInt(e.toString().replace(/\W/g,""))},U=function(){function e(e,t){void 0===e&&(e=0),void 0===t&&(t=0),this.x=e,this.y=t}return e.prototype.toString=function(){return"{X: ".concat(this.x," Y: ").concat(this.y,"}")},e.prototype.getClassName=function(){return"Vector2"},e.prototype.getHashCode=function(){var e=B(this.x);return 397*e^B(this.y)},e.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,this},e.prototype.fromArray=function(t,i){return void 0===i&&(i=0),e.FromArrayToRef(t,i,this),this},e.prototype.asArray=function(){return[this.x,this.y]},e.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this},e.prototype.copyFromFloats=function(e,t){return this.x=e,this.y=t,this},e.prototype.set=function(e,t){return this.copyFromFloats(e,t)},e.prototype.setAll=function(e){return this.copyFromFloats(e,e)},e.prototype.add=function(t){return new e(this.x+t.x,this.y+t.y)},e.prototype.addToRef=function(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t},e.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this},e.prototype.addInPlaceFromFloats=function(e,t){return this.x+=e,this.y+=t,this},e.prototype.addVector3=function(t){return new e(this.x+t.x,this.y+t.y)},e.prototype.subtract=function(t){return new e(this.x-t.x,this.y-t.y)},e.prototype.subtractToRef=function(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t},e.prototype.subtractInPlace=function(e){return this.x-=e.x,this.y-=e.y,this},e.prototype.multiplyInPlace=function(e){return this.x*=e.x,this.y*=e.y,this},e.prototype.multiply=function(t){return new e(this.x*t.x,this.y*t.y)},e.prototype.multiplyToRef=function(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t},e.prototype.multiplyByFloats=function(t,i){return new e(this.x*t,this.y*i)},e.prototype.divide=function(t){return new e(this.x/t.x,this.y/t.y)},e.prototype.divideToRef=function(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t},e.prototype.divideInPlace=function(e){return this.x=this.x/e.x,this.y=this.y/e.y,this},e.prototype.minimizeInPlace=function(e){return this.minimizeInPlaceFromFloats(e.x,e.y)},e.prototype.maximizeInPlace=function(e){return this.maximizeInPlaceFromFloats(e.x,e.y)},e.prototype.minimizeInPlaceFromFloats=function(e,t){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this},e.prototype.maximizeInPlaceFromFloats=function(e,t){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this},e.prototype.subtractFromFloats=function(t,i){return new e(this.x-t,this.y-i)},e.prototype.subtractFromFloatsToRef=function(e,t,i){return i.x=this.x-e,i.y=this.y-t,i},e.prototype.negate=function(){return new e(-this.x,-this.y)},e.prototype.negateInPlace=function(){return this.x*=-1,this.y*=-1,this},e.prototype.negateToRef=function(e){return e.x=-this.x,e.y=-this.y,e},e.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this},e.prototype.scale=function(t){return new e(this.x*t,this.y*t)},e.prototype.scaleToRef=function(e,t){return t.x=this.x*e,t.y=this.y*e,t},e.prototype.scaleAndAddToRef=function(e,t){return t.x+=this.x*e,t.y+=this.y*e,t},e.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y},e.prototype.equalsWithEpsilon=function(e,t){return void 0===t&&(t=A),e&&O(this.x,e.x,t)&&O(this.y,e.y,t)},e.prototype.equalsToFloats=function(e,t){return this.x===e&&this.y===t},e.prototype.floor=function(){return new e(Math.floor(this.x),Math.floor(this.y))},e.prototype.floorToRef=function(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e},e.prototype.fract=function(){return new e(this.x-Math.floor(this.x),this.y-Math.floor(this.y))},e.prototype.fractToRef=function(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e},e.prototype.rotateToRef=function(e,t){var i=Math.cos(e),r=Math.sin(e),n=i*this.x-r*this.y,o=r*this.x+i*this.y;return t.x=n,t.y=o,t},e.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},e.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},e.prototype.normalize=function(){return this.normalizeFromLength(this.length())},e.prototype.normalizeFromLength=function(e){return 0===e||1===e?this:this.scaleInPlace(1/e)},e.prototype.normalizeToNew=function(){var t=new e;return this.normalizeToRef(t),t},e.prototype.normalizeToRef=function(e){var t=this.length();return 0===t&&(e.x=this.x,e.y=this.y),this.scaleToRef(1/t,e)},e.prototype.clone=function(){return new e(this.x,this.y)},e.prototype.dot=function(e){return this.x*e.x+this.y*e.y},e.Zero=function(){return new e(0,0)},e.One=function(){return new e(1,1)},e.Random=function(t,i){return void 0===t&&(t=0),void 0===i&&(i=1),new e(D(t,i),D(t,i))},e.RandomToRef=function(e,t,i){return void 0===e&&(e=0),void 0===t&&(t=1),i.copyFromFloats(D(e,t),D(e,t))},Object.defineProperty(e,"ZeroReadOnly",{get:function(){return e._ZeroReadOnly},enumerable:!1,configurable:!0}),e.FromArray=function(t,i){return void 0===i&&(i=0),new e(t[i],t[i+1])},e.FromArrayToRef=function(e,t,i){return i.x=e[t],i.y=e[t+1],i},e.FromFloatsToRef=function(e,t,i){return i.copyFromFloats(e,t),i},e.CatmullRom=function(t,i,r,n,o){var a=o*o,s=o*a;return new e(.5*(2*i.x+(-t.x+r.x)*o+(2*t.x-5*i.x+4*r.x-n.x)*a+(-t.x+3*i.x-3*r.x+n.x)*s),.5*(2*i.y+(-t.y+r.y)*o+(2*t.y-5*i.y+4*r.y-n.y)*a+(-t.y+3*i.y-3*r.y+n.y)*s))},e.ClampToRef=function(e,t,i,r){return r.x=F(e.x,t.x,i.x),r.y=F(e.y,t.y,i.y),r},e.Clamp=function(t,i,r){return new e(F(t.x,i.x,r.x),F(t.y,i.y,r.y))},e.Hermite=function(t,i,r,n,o){var a=o*o,s=o*a,l=2*s-3*a+1,c=-2*s+3*a,u=s-2*a+o,h=s-a;return new e(t.x*l+r.x*c+i.x*u+n.x*h,t.y*l+r.y*c+i.y*u+n.y*h)},e.Hermite1stDerivative=function(t,i,r,n,o){return this.Hermite1stDerivativeToRef(t,i,r,n,o,new e)},e.Hermite1stDerivativeToRef=function(e,t,i,r,n,o){var a=n*n;return o.x=6*(a-n)*e.x+(3*a-4*n+1)*t.x+6*(-a+n)*i.x+(3*a-2*n)*r.x,o.y=6*(a-n)*e.y+(3*a-4*n+1)*t.y+6*(-a+n)*i.y+(3*a-2*n)*r.y,o},e.Lerp=function(t,i,r){return new e(t.x+(i.x-t.x)*r,t.y+(i.y-t.y)*r)},e.Dot=function(e,t){return e.x*t.x+e.y*t.y},e.Normalize=function(t){return e.NormalizeToRef(t,new e)},e.NormalizeToRef=function(e,t){return e.normalizeToRef(t),t},e.Minimize=function(t,i){return new e(t.x<i.x?t.x:i.x,t.y<i.y?t.y:i.y)},e.Maximize=function(t,i){return new e(t.x>i.x?t.x:i.x,t.y>i.y?t.y:i.y)},e.Transform=function(t,i){return e.TransformToRef(t,i,new e)},e.TransformToRef=function(e,t,i){var r=t.m,n=e.x*r[0]+e.y*r[4]+r[12],o=e.x*r[1]+e.y*r[5]+r[13];return i.x=n,i.y=o,i},e.PointInTriangle=function(e,t,i,r){var n=.5*(-i.y*r.x+t.y*(-i.x+r.x)+t.x*(i.y-r.y)+i.x*r.y),o=n<0?-1:1,a=(t.y*r.x-t.x*r.y+(r.y-t.y)*e.x+(t.x-r.x)*e.y)*o,s=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*o;return a>0&&s>0&&a+s<2*n*o},e.Distance=function(t,i){return Math.sqrt(e.DistanceSquared(t,i))},e.DistanceSquared=function(e,t){var i=e.x-t.x,r=e.y-t.y;return i*i+r*r},e.Center=function(t,i){return e.CenterToRef(t,i,new e)},e.CenterToRef=function(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)},e.DistanceOfPointFromSegment=function(t,i,r){var n=e.DistanceSquared(i,r);if(0===n)return e.Distance(t,i);var o=r.subtract(i),a=Math.max(0,Math.min(1,e.Dot(t.subtract(i),o)/n)),s=i.add(o.multiplyByFloats(a,a));return e.Distance(t,s)},e._ZeroReadOnly=e.Zero(),e}();Object.defineProperties(U.prototype,{dimension:{value:[2]},rank:{value:1}});var V=function(){function e(e,t,i){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),this._isDirty=!0,this._x=e,this._y=t,this._z=i}return Object.defineProperty(e.prototype,"x",{get:function(){return this._x},set:function(e){this._x=e,this._isDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"y",{get:function(){return this._y},set:function(e){this._y=e,this._isDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"z",{get:function(){return this._z},set:function(e){this._z=e,this._isDirty=!0},enumerable:!1,configurable:!0}),e.prototype.toString=function(){return"{X: ".concat(this._x," Y: ").concat(this._y," Z: ").concat(this._z,"}")},e.prototype.getClassName=function(){return"Vector3"},e.prototype.getHashCode=function(){var e=B(this._x);return 397*(e=397*e^B(this._y))^B(this._z)},e.prototype.asArray=function(){return[this._x,this._y,this._z]},e.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,this},e.prototype.fromArray=function(t,i){return void 0===i&&(i=0),e.FromArrayToRef(t,i,this),this},e.prototype.toQuaternion=function(){return G.RotationYawPitchRoll(this._y,this._x,this._z)},e.prototype.addInPlace=function(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._isDirty=!0,this},e.prototype.addInPlaceFromFloats=function(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this},e.prototype.add=function(t){return new e(this._x+t._x,this._y+t._y,this._z+t._z)},e.prototype.addToRef=function(e,t){return t.copyFromFloats(this._x+e._x,this._y+e._y,this._z+e._z)},e.prototype.subtractInPlace=function(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this},e.prototype.subtract=function(t){return new e(this._x-t._x,this._y-t._y,this._z-t._z)},e.prototype.subtractToRef=function(e,t){return this.subtractFromFloatsToRef(e._x,e._y,e._z,t)},e.prototype.subtractFromFloats=function(t,i,r){return new e(this._x-t,this._y-i,this._z-r)},e.prototype.subtractFromFloatsToRef=function(e,t,i,r){return r.copyFromFloats(this._x-e,this._y-t,this._z-i)},e.prototype.negate=function(){return new e(-this._x,-this._y,-this._z)},e.prototype.negateInPlace=function(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this},e.prototype.negateToRef=function(e){return e.copyFromFloats(-1*this._x,-1*this._y,-1*this._z)},e.prototype.scaleInPlace=function(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this},e.prototype.scale=function(t){return new e(this._x*t,this._y*t,this._z*t)},e.prototype.scaleToRef=function(e,t){return t.copyFromFloats(this._x*e,this._y*e,this._z*e)},e.prototype.getNormalToRef=function(e){var t=this.length(),i=Math.acos(this.y/t),r=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;var n=t*Math.sin(i)*Math.cos(r),o=t*Math.cos(i),a=t*Math.sin(i)*Math.sin(r);return e.set(n,o,a),e},e.prototype.applyRotationQuaternionToRef=function(e,t){var i=this._x,r=this._y,n=this._z,o=e._x,a=e._y,s=e._z,l=e._w,c=2*(a*n-s*r),u=2*(s*i-o*n),h=2*(o*r-a*i);return t._x=i+l*c+a*h-s*u,t._y=r+l*u+s*c-o*h,t._z=n+l*h+o*u-a*c,t._isDirty=!0,t},e.prototype.applyRotationQuaternionInPlace=function(e){return this.applyRotationQuaternionToRef(e,this)},e.prototype.applyRotationQuaternion=function(t){return this.applyRotationQuaternionToRef(t,new e)},e.prototype.scaleAndAddToRef=function(e,t){return t.addInPlaceFromFloats(this._x*e,this._y*e,this._z*e)},e.prototype.projectOnPlane=function(t,i){return this.projectOnPlaneToRef(t,i,new e)},e.prototype.projectOnPlaneToRef=function(t,i,r){var n=t.normal,o=t.d,a=W.Vector3[0];this.subtractToRef(i,a),a.normalize();var s=e.Dot(a,n);if(Math.abs(s)<1e-10)r.setAll(1/0);else{var l=-(e.Dot(i,n)+o)/s,c=a.scaleInPlace(l);i.addToRef(c,r)}return r},e.prototype.equals=function(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z},e.prototype.equalsWithEpsilon=function(e,t){return void 0===t&&(t=A),e&&O(this._x,e._x,t)&&O(this._y,e._y,t)&&O(this._z,e._z,t)},e.prototype.equalsToFloats=function(e,t,i){return this._x===e&&this._y===t&&this._z===i},e.prototype.multiplyInPlace=function(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this},e.prototype.multiply=function(e){return this.multiplyByFloats(e._x,e._y,e._z)},e.prototype.multiplyToRef=function(e,t){return t.copyFromFloats(this._x*e._x,this._y*e._y,this._z*e._z)},e.prototype.multiplyByFloats=function(t,i,r){return new e(this._x*t,this._y*i,this._z*r)},e.prototype.divide=function(t){return new e(this._x/t._x,this._y/t._y,this._z/t._z)},e.prototype.divideToRef=function(e,t){return t.copyFromFloats(this._x/e._x,this._y/e._y,this._z/e._z)},e.prototype.divideInPlace=function(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this},e.prototype.minimizeInPlace=function(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)},e.prototype.maximizeInPlace=function(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)},e.prototype.minimizeInPlaceFromFloats=function(e,t,i){return e<this._x&&(this.x=e),t<this._y&&(this.y=t),i<this._z&&(this.z=i),this},e.prototype.maximizeInPlaceFromFloats=function(e,t,i){return e>this._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this},e.prototype.isNonUniformWithinEpsilon=function(e){var t=Math.abs(this._x),i=Math.abs(this._y);if(!O(t,i,e))return!0;var r=Math.abs(this._z);return!O(t,r,e)||!O(i,r,e)},Object.defineProperty(e.prototype,"isNonUniform",{get:function(){var e=Math.abs(this._x);return e!==Math.abs(this._y)||e!==Math.abs(this._z)},enumerable:!1,configurable:!0}),e.prototype.floorToRef=function(e){return e._x=Math.floor(this._x),e._y=Math.floor(this._y),e._z=Math.floor(this._z),e._isDirty=!0,e},e.prototype.floor=function(){return new e(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z))},e.prototype.fractToRef=function(e){return e._x=this.x-Math.floor(this._x),e._y=this.y-Math.floor(this._y),e._z=this.z-Math.floor(this._z),e._isDirty=!0,e},e.prototype.fract=function(){return new e(this.x-Math.floor(this._x),this.y-Math.floor(this._y),this.z-Math.floor(this._z))},e.prototype.length=function(){return Math.sqrt(this.lengthSquared())},e.prototype.lengthSquared=function(){return this._x*this._x+this._y*this._y+this._z*this._z},Object.defineProperty(e.prototype,"hasAZeroComponent",{get:function(){return this._x*this._y*this._z==0},enumerable:!1,configurable:!0}),e.prototype.normalize=function(){return this.normalizeFromLength(this.length())},e.prototype.reorderInPlace=function(e){if("xyz"===(e=e.toLowerCase()))return this;var t=W.Vector3[0].copyFrom(this);return this.x=t[e[0]],this.y=t[e[1]],this.z=t[e[2]],this},e.prototype.rotateByQuaternionToRef=function(t,i){return t.toRotationMatrix(W.Matrix[0]),e.TransformCoordinatesToRef(this,W.Matrix[0],i),i},e.prototype.rotateByQuaternionAroundPointToRef=function(e,t,i){return this.subtractToRef(t,W.Vector3[0]),W.Vector3[0].rotateByQuaternionToRef(e,W.Vector3[0]),t.addToRef(W.Vector3[0],i),i},e.prototype.cross=function(t){return e.CrossToRef(this,t,new e)},e.prototype.normalizeFromLength=function(e){return 0===e||1===e?this:this.scaleInPlace(1/e)},e.prototype.normalizeToNew=function(){return this.normalizeToRef(new e)},e.prototype.normalizeToRef=function(e){var t=this.length();return 0===t||1===t?e.copyFrom(this):this.scaleToRef(1/t,e)},e.prototype.clone=function(){return new e(this._x,this._y,this._z)},e.prototype.copyFrom=function(e){return this.copyFromFloats(e._x,e._y,e._z)},e.prototype.copyFromFloats=function(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this},e.prototype.set=function(e,t,i){return this.copyFromFloats(e,t,i)},e.prototype.setAll=function(e){return this._x=this._y=this._z=e,this._isDirty=!0,this},e.GetClipFactor=function(t,i,r,n){var o=e.Dot(t,r);return(o-n)/(o-e.Dot(i,r))},e.GetAngleBetweenVectors=function(t,i,r){var n=t.normalizeToRef(W.Vector3[1]),o=i.normalizeToRef(W.Vector3[2]),a=e.Dot(n,o);a=F(a,-1,1);var s=Math.acos(a),l=W.Vector3[3];return e.CrossToRef(n,o,l),e.Dot(l,r)>0?isNaN(s)?0:s:isNaN(s)?-Math.PI:-Math.acos(a)},e.GetAngleBetweenVectorsOnPlane=function(t,i,r){W.Vector3[0].copyFrom(t);var n=W.Vector3[0];W.Vector3[1].copyFrom(i);var o=W.Vector3[1];W.Vector3[2].copyFrom(r);var a=W.Vector3[2],s=W.Vector3[3],l=W.Vector3[4];return n.normalize(),o.normalize(),a.normalize(),e.CrossToRef(a,n,s),e.CrossToRef(s,a,l),L(Math.atan2(e.Dot(o,s),e.Dot(o,l)))},e.PitchYawRollToMoveBetweenPointsToRef=function(e,t,i){var r=H.Vector3[0];return t.subtractToRef(e,r),i._y=Math.atan2(r.x,r.z)||0,i._x=Math.atan2(Math.sqrt(Math.pow(r.x,2)+Math.pow(r.z,2)),r.y)||0,i._z=0,i._isDirty=!0,i},e.PitchYawRollToMoveBetweenPoints=function(t,i){var r=e.Zero();return e.PitchYawRollToMoveBetweenPointsToRef(t,i,r)},e.SlerpToRef=function(t,i,r,n){r=F(r,0,1);var o=W.Vector3[0],a=W.Vector3[1];o.copyFrom(t);var s=o.length();o.normalizeFromLength(s),a.copyFrom(i);var l=a.length();a.normalizeFromLength(l);var c,u,h=e.Dot(o,a);if(h<1-A){var d=Math.acos(h),p=1/Math.sin(d);c=Math.sin((1-r)*d)*p,u=Math.sin(r*d)*p}else c=1-r,u=r;return o.scaleInPlace(c),a.scaleInPlace(u),n.copyFrom(o).addInPlace(a),n.scaleInPlace(N(s,l,r)),n},e.SmoothToRef=function(t,i,r,n,o){return e.SlerpToRef(t,i,0===n?1:r/n,o),o},e.FromArray=function(t,i){return void 0===i&&(i=0),new e(t[i],t[i+1],t[i+2])},e.FromFloatArray=function(t,i){return e.FromArray(t,i)},e.FromArrayToRef=function(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._isDirty=!0,i},e.FromFloatArrayToRef=function(t,i,r){return e.FromArrayToRef(t,i,r)},e.FromFloatsToRef=function(e,t,i,r){return r.copyFromFloats(e,t,i),r},e.Zero=function(){return new e(0,0,0)},e.One=function(){return new e(1,1,1)},e.Up=function(){return new e(0,1,0)},Object.defineProperty(e,"UpReadOnly",{get:function(){return e._UpReadOnly},enumerable:!1,configurable:!0}),Object.defineProperty(e,"DownReadOnly",{get:function(){return e._DownReadOnly},enumerable:!1,configurable:!0}),Object.defineProperty(e,"RightReadOnly",{get:function(){return e._RightReadOnly},enumerable:!1,configurable:!0}),Object.defineProperty(e,"LeftReadOnly",{get:function(){return e._LeftReadOnly},enumerable:!1,configurable:!0}),Object.defineProperty(e,"LeftHandedForwardReadOnly",{get:function(){return e._LeftHandedForwardReadOnly},enumerable:!1,configurable:!0}),Object.defineProperty(e,"RightHandedForwardReadOnly",{get:function(){return e._RightHandedForwardReadOnly},enumerable:!1,configurable:!0}),Object.defineProperty(e,"LeftHandedBackwardReadOnly",{get:function(){return e._LeftHandedBackwardReadOnly},enumerable:!1,configurable:!0}),Object.defineProperty(e,"RightHandedBackwardReadOnly",{get:function(){return e._RightHandedBackwardReadOnly},enumerable:!1,configurable:!0}),Object.defineProperty(e,"ZeroReadOnly",{get:function(){return e._ZeroReadOnly},enumerable:!1,configurable:!0}),Object.defineProperty(e,"OneReadOnly",{get:function(){return e._OneReadOnly},enumerable:!1,configurable:!0}),e.Down=function(){return new e(0,-1,0)},e.Forward=function(t){return void 0===t&&(t=!1),new e(0,0,t?-1:1)},e.Backward=function(t){return void 0===t&&(t=!1),new e(0,0,t?1:-1)},e.Right=function(){return new e(1,0,0)},e.Left=function(){return new e(-1,0,0)},e.Random=function(t,i){return void 0===t&&(t=0),void 0===i&&(i=1),new e(D(t,i),D(t,i),D(t,i))},e.RandomToRef=function(e,t,i){return void 0===e&&(e=0),void 0===t&&(t=1),i.copyFromFloats(D(e,t),D(e,t),D(e,t))},e.TransformCoordinates=function(t,i){var r=e.Zero();return e.TransformCoordinatesToRef(t,i,r),r},e.TransformCoordinatesToRef=function(t,i,r){return e.TransformCoordinatesFromFloatsToRef(t._x,t._y,t._z,i,r),r},e.TransformCoordinatesFromFloatsToRef=function(e,t,i,r,n){var o=r.m,a=e*o[0]+t*o[4]+i*o[8]+o[12],s=e*o[1]+t*o[5]+i*o[9]+o[13],l=e*o[2]+t*o[6]+i*o[10]+o[14],c=1/(e*o[3]+t*o[7]+i*o[11]+o[15]);return n._x=a*c,n._y=s*c,n._z=l*c,n._isDirty=!0,n},e.TransformNormal=function(t,i){var r=e.Zero();return e.TransformNormalToRef(t,i,r),r},e.TransformNormalToRef=function(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i},e.TransformNormalFromFloatsToRef=function(e,t,i,r,n){var o=r.m;return n._x=e*o[0]+t*o[4]+i*o[8],n._y=e*o[1]+t*o[5]+i*o[9],n._z=e*o[2]+t*o[6]+i*o[10],n._isDirty=!0,n},e.CatmullRom=function(t,i,r,n,o){var a=o*o,s=o*a;return new e(.5*(2*i._x+(-t._x+r._x)*o+(2*t._x-5*i._x+4*r._x-n._x)*a+(-t._x+3*i._x-3*r._x+n._x)*s),.5*(2*i._y+(-t._y+r._y)*o+(2*t._y-5*i._y+4*r._y-n._y)*a+(-t._y+3*i._y-3*r._y+n._y)*s),.5*(2*i._z+(-t._z+r._z)*o+(2*t._z-5*i._z+4*r._z-n._z)*a+(-t._z+3*i._z-3*r._z+n._z)*s))},e.Clamp=function(t,i,r){var n=new e;return e.ClampToRef(t,i,r,n),n},e.ClampToRef=function(e,t,i,r){var n=e._x;n=(n=n>i._x?i._x:n)<t._x?t._x:n;var o=e._y;o=(o=o>i._y?i._y:o)<t._y?t._y:o;var a=e._z;return a=(a=a>i._z?i._z:a)<t._z?t._z:a,r.copyFromFloats(n,o,a),r},e.CheckExtends=function(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)},e.Hermite=function(t,i,r,n,o){var a=o*o,s=o*a,l=2*s-3*a+1,c=-2*s+3*a,u=s-2*a+o,h=s-a;return new e(t._x*l+r._x*c+i._x*u+n._x*h,t._y*l+r._y*c+i._y*u+n._y*h,t._z*l+r._z*c+i._z*u+n._z*h)},e.Hermite1stDerivative=function(t,i,r,n,o){var a=new e;return this.Hermite1stDerivativeToRef(t,i,r,n,o,a),a},e.Hermite1stDerivativeToRef=function(e,t,i,r,n,o){var a=n*n;return o._x=6*(a-n)*e._x+(3*a-4*n+1)*t._x+6*(-a+n)*i._x+(3*a-2*n)*r._x,o._y=6*(a-n)*e._y+(3*a-4*n+1)*t._y+6*(-a+n)*i._y+(3*a-2*n)*r._y,o._z=6*(a-n)*e._z+(3*a-4*n+1)*t._z+6*(-a+n)*i._z+(3*a-2*n)*r._z,o._isDirty=!0,o},e.Lerp=function(t,i,r){var n=new e(0,0,0);return e.LerpToRef(t,i,r,n),n},e.LerpToRef=function(e,t,i,r){return r._x=e._x+(t._x-e._x)*i,r._y=e._y+(t._y-e._y)*i,r._z=e._z+(t._z-e._z)*i,r._isDirty=!0,r},e.Dot=function(e,t){return e._x*t._x+e._y*t._y+e._z*t._z},e.prototype.dot=function(e){return this._x*e._x+this._y*e._y+this._z*e._z},e.Cross=function(t,i){var r=new e;return e.CrossToRef(t,i,r),r},e.CrossToRef=function(e,t,i){var r=e._y*t._z-e._z*t._y,n=e._z*t._x-e._x*t._z,o=e._x*t._y-e._y*t._x;return i.copyFromFloats(r,n,o),i},e.Normalize=function(t){var i=e.Zero();return e.NormalizeToRef(t,i),i},e.NormalizeToRef=function(e,t){return e.normalizeToRef(t),t},e.Project=function(t,i,r,n){var o=new e;return e.ProjectToRef(t,i,r,n,o),o},e.ProjectToRef=function(t,i,r,n,o){var a,s=n.width,l=n.height,c=n.x,u=n.y,h=W.Matrix[1],d=null===(a=M.LastCreatedEngine)||void 0===a?void 0:a.isNDCHalfZRange,p=d?1:.5,f=d?0:.5;z.FromValuesToRef(s/2,0,0,0,0,-l/2,0,0,0,0,p,0,c+s/2,l/2+u,f,1,h);var _=W.Matrix[0];return i.multiplyToRef(r,_),_.multiplyToRef(h,_),e.TransformCoordinatesToRef(t,_,o),o},e.Reflect=function(t,i){return this.ReflectToRef(t,i,new e)},e.ReflectToRef=function(t,i,r){var n=H.Vector3[0];return n.copyFrom(i).scaleInPlace(2*e.Dot(t,i)),r.copyFrom(t).subtractInPlace(n)},e._UnprojectFromInvertedMatrixToRef=function(t,i,r){e.TransformCoordinatesToRef(t,i,r);var n=i.m,o=t._x*n[3]+t._y*n[7]+t._z*n[11]+n[15];return O(o,1)&&r.scaleInPlace(1/o),r},e.UnprojectFromTransform=function(e,t,i,r,n){return this.Unproject(e,t,i,r,n,z.IdentityReadOnly)},e.Unproject=function(t,i,r,n,o,a){var s=new e;return e.UnprojectToRef(t,i,r,n,o,a,s),s},e.UnprojectToRef=function(t,i,r,n,o,a,s){return e.UnprojectFloatsToRef(t._x,t._y,t._z,i,r,n,o,a,s),s},e.UnprojectFloatsToRef=function(t,i,r,n,o,a,s,l,c){var u,h=W.Matrix[0];a.multiplyToRef(s,h),h.multiplyToRef(l,h),h.invert();var d=W.Vector3[0];return d.x=t/n*2-1,d.y=-(i/o*2-1),(null===(u=M.LastCreatedEngine)||void 0===u?void 0:u.isNDCHalfZRange)?d.z=r:d.z=2*r-1,e._UnprojectFromInvertedMatrixToRef(d,h,c),c},e.Minimize=function(t,i){var r=new e;return r.copyFrom(t),r.minimizeInPlace(i),r},e.Maximize=function(t,i){var r=new e;return r.copyFrom(t),r.maximizeInPlace(i),r},e.Distance=function(t,i){return Math.sqrt(e.DistanceSquared(t,i))},e.DistanceSquared=function(e,t){var i=e._x-t._x,r=e._y-t._y,n=e._z-t._z;return i*i+r*r+n*n},e.ProjectOnTriangleToRef=function(t,i,r,n,o){var a=W.Vector3[0],s=W.Vector3[1],l=W.Vector3[2],c=W.Vector3[3],u=W.Vector3[4];r.subtractToRef(i,a),n.subtractToRef(i,s),n.subtractToRef(r,l);var h=a.length(),d=s.length(),p=l.length();if(h<A||d<A||p<A)return o.copyFrom(i),e.Distance(t,i);t.subtractToRef(i,u),e.CrossToRef(a,s,c);var f=c.length();if(f<A)return o.copyFrom(i),e.Distance(t,i);c.normalizeFromLength(f);var _=u.length();if(_<A)return o.copyFrom(i),0;u.normalizeFromLength(_);var m=e.Dot(c,u),g=W.Vector3[5],v=W.Vector3[6];g.copyFrom(c).scaleInPlace(-_*m),v.copyFrom(t).addInPlace(g);var y=W.Vector3[4],b=W.Vector3[5],T=W.Vector3[7],E=W.Vector3[8];y.copyFrom(a).scaleInPlace(1/h),E.copyFrom(s).scaleInPlace(1/d),y.addInPlace(E).scaleInPlace(-1),b.copyFrom(a).scaleInPlace(-1/h),E.copyFrom(l).scaleInPlace(1/p),b.addInPlace(E).scaleInPlace(-1),T.copyFrom(l).scaleInPlace(-1/p),E.copyFrom(s).scaleInPlace(-1/d),T.addInPlace(E).scaleInPlace(-1);var S=W.Vector3[9];S.copyFrom(v).subtractInPlace(i),e.CrossToRef(y,S,E);var x=e.Dot(E,c);S.copyFrom(v).subtractInPlace(r),e.CrossToRef(b,S,E);var C=e.Dot(E,c);S.copyFrom(v).subtractInPlace(n),e.CrossToRef(T,S,E);var R,P,I=e.Dot(E,c),M=W.Vector3[10];x>0&&C<0?(M.copyFrom(a),R=i,P=r):C>0&&I<0?(M.copyFrom(l),R=r,P=n):(M.copyFrom(s).scaleInPlace(-1),R=n,P=i);var O=W.Vector3[9],D=W.Vector3[4];if(R.subtractToRef(v,E),P.subtractToRef(v,O),e.CrossToRef(E,O,D),!(e.Dot(D,c)<0))return o.copyFrom(v),Math.abs(_*m);var N=W.Vector3[5];e.CrossToRef(M,D,N),N.normalize();var L=W.Vector3[9];L.copyFrom(R).subtractInPlace(v);var w=L.length();if(w<A)return o.copyFrom(R),e.Distance(t,R);L.normalizeFromLength(w);var B=e.Dot(N,L),U=W.Vector3[7];U.copyFrom(v).addInPlace(N.scaleInPlace(w*B)),E.copyFrom(U).subtractInPlace(R),_=M.length(),M.normalizeFromLength(_);var V=e.Dot(E,M)/Math.max(_,A);return V=F(V,0,1),U.copyFrom(R).addInPlace(M.scaleInPlace(V*_)),o.copyFrom(U),e.Distance(t,U)},e.Center=function(t,i){return e.CenterToRef(t,i,e.Zero())},e.CenterToRef=function(e,t,i){return i.copyFromFloats((e._x+t._x)/2,(e._y+t._y)/2,(e._z+t._z)/2)},e.RotationFromAxis=function(t,i,r){var n=new e;return e.RotationFromAxisToRef(t,i,r,n),n},e.RotationFromAxisToRef=function(e,t,i,r){var n=W.Quaternion[0];return G.RotationQuaternionFromAxisToRef(e,t,i,n),n.toEulerAnglesToRef(r),r},e._UpReadOnly=e.Up(),e._DownReadOnly=e.Down(),e._LeftHandedForwardReadOnly=e.Forward(!1),e._RightHandedForwardReadOnly=e.Forward(!0),e._LeftHandedBackwardReadOnly=e.Backward(!1),e._RightHandedBackwardReadOnly=e.Backward(!0),e._RightReadOnly=e.Right(),e._LeftReadOnly=e.Left(),e._ZeroReadOnly=e.Zero(),e._OneReadOnly=e.One(),e}();Object.defineProperties(V.prototype,{dimension:{value:[3]},rank:{value:1}});var k=function(){function e(e,t,i,r){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),this.x=e,this.y=t,this.z=i,this.w=r}return e.prototype.toString=function(){return"{X: ".concat(this.x," Y: ").concat(this.y," Z: ").concat(this.z," W: ").concat(this.w,"}")},e.prototype.getClassName=function(){return"Vector4"},e.prototype.getHashCode=function(){var e=B(this.x);return 397*(e=397*(e=397*e^B(this.y))^B(this.z))^B(this.w)},e.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},e.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,this},e.prototype.fromArray=function(t,i){return void 0===i&&(i=0),e.FromArrayToRef(t,i,this),this},e.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this},e.prototype.addInPlaceFromFloats=function(e,t,i,r){return this.x+=e,this.y+=t,this.z+=i,this.w+=r,this},e.prototype.add=function(t){return new e(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},e.prototype.addToRef=function(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t.z=this.z+e.z,t.w=this.w+e.w,t},e.prototype.subtractInPlace=function(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this},e.prototype.subtract=function(t){return new e(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},e.prototype.subtractToRef=function(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t.z=this.z-e.z,t.w=this.w-e.w,t},e.prototype.subtractFromFloats=function(t,i,r,n){return new e(this.x-t,this.y-i,this.z-r,this.w-n)},e.prototype.subtractFromFloatsToRef=function(e,t,i,r,n){return n.x=this.x-e,n.y=this.y-t,n.z=this.z-i,n.w=this.w-r,n},e.prototype.negate=function(){return new e(-this.x,-this.y,-this.z,-this.w)},e.prototype.negateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this.w*=-1,this},e.prototype.negateToRef=function(e){return e.x=-this.x,e.y=-this.y,e.z=-this.z,e.w=-this.w,e},e.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},e.prototype.scale=function(t){return new e(this.x*t,this.y*t,this.z*t,this.w*t)},e.prototype.scaleToRef=function(e,t){return t.x=this.x*e,t.y=this.y*e,t.z=this.z*e,t.w=this.w*e,t},e.prototype.scaleAndAddToRef=function(e,t){return t.x+=this.x*e,t.y+=this.y*e,t.z+=this.z*e,t.w+=this.w*e,t},e.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w},e.prototype.equalsWithEpsilon=function(e,t){return void 0===t&&(t=A),e&&O(this.x,e.x,t)&&O(this.y,e.y,t)&&O(this.z,e.z,t)&&O(this.w,e.w,t)},e.prototype.equalsToFloats=function(e,t,i,r){return this.x===e&&this.y===t&&this.z===i&&this.w===r},e.prototype.multiplyInPlace=function(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this},e.prototype.multiply=function(t){return new e(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},e.prototype.multiplyToRef=function(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t.z=this.z*e.z,t.w=this.w*e.w,t},e.prototype.multiplyByFloats=function(t,i,r,n){return new e(this.x*t,this.y*i,this.z*r,this.w*n)},e.prototype.divide=function(t){return new e(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},e.prototype.divideToRef=function(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t.z=this.z/e.z,t.w=this.w/e.w,t},e.prototype.divideInPlace=function(e){return this.divideToRef(e,this)},e.prototype.minimizeInPlace=function(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),e.z<this.z&&(this.z=e.z),e.w<this.w&&(this.w=e.w),this},e.prototype.maximizeInPlace=function(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this},e.prototype.minimizeInPlaceFromFloats=function(e,t,i,r){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this.z=Math.min(i,this.z),this.w=Math.min(r,this.w),this},e.prototype.maximizeInPlaceFromFloats=function(e,t,i,r){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this.z=Math.max(i,this.z),this.w=Math.max(r,this.w),this},e.prototype.floorToRef=function(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e.z=Math.floor(this.z),e.w=Math.floor(this.w),e},e.prototype.floor=function(){return new e(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))},e.prototype.fractToRef=function(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e.z=this.z-Math.floor(this.z),e.w=this.w-Math.floor(this.w),e},e.prototype.fract=function(){return new e(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))},e.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},e.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},e.prototype.normalize=function(){return this.normalizeFromLength(this.length())},e.prototype.normalizeFromLength=function(e){return 0===e||1===e?this:this.scaleInPlace(1/e)},e.prototype.normalizeToNew=function(){return this.normalizeToRef(new e)},e.prototype.normalizeToRef=function(e){var t=this.length();return 0===t||1===t?(e.x=this.x,e.y=this.y,e.z=this.z,e.w=this.w,e):this.scaleToRef(1/t,e)},e.prototype.toVector3=function(){return new V(this.x,this.y,this.z)},e.prototype.clone=function(){return new e(this.x,this.y,this.z,this.w)},e.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},e.prototype.copyFromFloats=function(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this},e.prototype.set=function(e,t,i,r){return this.copyFromFloats(e,t,i,r)},e.prototype.setAll=function(e){return this.x=this.y=this.z=this.w=e,this},e.prototype.dot=function(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w},e.FromArray=function(t,i){return i||(i=0),new e(t[i],t[i+1],t[i+2],t[i+3])},e.FromArrayToRef=function(e,t,i){return i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3],i},e.FromFloatArrayToRef=function(t,i,r){return e.FromArrayToRef(t,i,r),r},e.FromFloatsToRef=function(e,t,i,r,n){return n.x=e,n.y=t,n.z=i,n.w=r,n},e.Zero=function(){return new e(0,0,0,0)},e.One=function(){return new e(1,1,1,1)},e.Random=function(t,i){return void 0===t&&(t=0),void 0===i&&(i=1),new e(D(t,i),D(t,i),D(t,i),D(t,i))},e.RandomToRef=function(e,t,i){return void 0===e&&(e=0),void 0===t&&(t=1),i.x=D(e,t),i.y=D(e,t),i.z=D(e,t),i.w=D(e,t),i},e.Clamp=function(t,i,r){return e.ClampToRef(t,i,r,new e)},e.ClampToRef=function(e,t,i,r){return r.x=F(e.x,t.x,i.x),r.y=F(e.y,t.y,i.y),r.z=F(e.z,t.z,i.z),r.w=F(e.w,t.w,i.w),r},e.CheckExtends=function(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)},Object.defineProperty(e,"ZeroReadOnly",{get:function(){return e._ZeroReadOnly},enumerable:!1,configurable:!0}),e.Normalize=function(t){return e.NormalizeToRef(t,new e)},e.NormalizeToRef=function(e,t){return e.normalizeToRef(t),t},e.Minimize=function(t,i){var r=new e;return r.copyFrom(t),r.minimizeInPlace(i),r},e.Maximize=function(t,i){var r=new e;return r.copyFrom(t),r.maximizeInPlace(i),r},e.Distance=function(t,i){return Math.sqrt(e.DistanceSquared(t,i))},e.DistanceSquared=function(e,t){var i=e.x-t.x,r=e.y-t.y,n=e.z-t.z,o=e.w-t.w;return i*i+r*r+n*n+o*o},e.Center=function(t,i){return e.CenterToRef(t,i,new e)},e.CenterToRef=function(e,t,i){return i.x=(e.x+t.x)/2,i.y=(e.y+t.y)/2,i.z=(e.z+t.z)/2,i.w=(e.w+t.w)/2,i},e.TransformCoordinates=function(t,i){return e.TransformCoordinatesToRef(t,i,new e)},e.TransformCoordinatesToRef=function(t,i,r){return e.TransformCoordinatesFromFloatsToRef(t._x,t._y,t._z,i,r),r},e.TransformCoordinatesFromFloatsToRef=function(e,t,i,r,n){var o=r.m,a=e*o[0]+t*o[4]+i*o[8]+o[12],s=e*o[1]+t*o[5]+i*o[9]+o[13],l=e*o[2]+t*o[6]+i*o[10]+o[14],c=e*o[3]+t*o[7]+i*o[11]+o[15];return n.x=a,n.y=s,n.z=l,n.w=c,n},e.TransformNormal=function(t,i){return e.TransformNormalToRef(t,i,new e)},e.TransformNormalToRef=function(e,t,i){var r=t.m,n=e.x*r[0]+e.y*r[4]+e.z*r[8],o=e.x*r[1]+e.y*r[5]+e.z*r[9],a=e.x*r[2]+e.y*r[6]+e.z*r[10];return i.x=n,i.y=o,i.z=a,i.w=e.w,i},e.TransformNormalFromFloatsToRef=function(e,t,i,r,n,o){var a=n.m;return o.x=e*a[0]+t*a[4]+i*a[8],o.y=e*a[1]+t*a[5]+i*a[9],o.z=e*a[2]+t*a[6]+i*a[10],o.w=r,o},e.FromVector3=function(t,i){return void 0===i&&(i=0),new e(t._x,t._y,t._z,i)},e.Dot=function(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w},e._ZeroReadOnly=e.Zero(),e}();Object.defineProperties(k.prototype,{dimension:{value:[4]},rank:{value:1}});var G=function(){function e(e,t,i,r){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=1),this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=r}return Object.defineProperty(e.prototype,"x",{get:function(){return this._x},set:function(e){this._x=e,this._isDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"y",{get:function(){return this._y},set:function(e){this._y=e,this._isDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"z",{get:function(){return this._z},set:function(e){this._z=e,this._isDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"w",{get:function(){return this._w},set:function(e){this._w=e,this._isDirty=!0},enumerable:!1,configurable:!0}),e.prototype.toString=function(){return"{X: ".concat(this._x," Y: ").concat(this._y," Z: ").concat(this._z," W: ").concat(this._w,"}")},e.prototype.getClassName=function(){return"Quaternion"},e.prototype.getHashCode=function(){var e=B(this._x);return 397*(e=397*(e=397*e^B(this._y))^B(this._z))^B(this._w)},e.prototype.asArray=function(){return[this._x,this._y,this._z,this._w]},e.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,this},e.prototype.fromArray=function(t,i){return void 0===i&&(i=0),e.FromArrayToRef(t,i,this)},e.prototype.equals=function(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w},e.prototype.equalsWithEpsilon=function(e,t){return void 0===t&&(t=A),e&&O(this._x,e._x,t)&&O(this._y,e._y,t)&&O(this._z,e._z,t)&&O(this._w,e._w,t)},e.prototype.clone=function(){return new e(this._x,this._y,this._z,this._w)},e.prototype.copyFrom=function(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this},e.prototype.copyFromFloats=function(e,t,i,r){return this._x=e,this._y=t,this._z=i,this._w=r,this._isDirty=!0,this},e.prototype.set=function(e,t,i,r){return this.copyFromFloats(e,t,i,r)},e.prototype.setAll=function(e){return this.copyFromFloats(e,e,e,e)},e.prototype.add=function(t){return new e(this._x+t._x,this._y+t._y,this._z+t._z,this._w+t._w)},e.prototype.addInPlace=function(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this},e.prototype.addToRef=function(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._w=this._w+e._w,t._isDirty=!0,t},e.prototype.addInPlaceFromFloats=function(e,t,i,r){return this._x+=e,this._y+=t,this._z+=i,this._w+=r,this._isDirty=!0,this},e.prototype.subtractToRef=function(e,t){return t._x=this._x-e._x,t._y=this._y-e._y,t._z=this._z-e._z,t._w=this._w-e._w,t._isDirty=!0,t},e.prototype.subtractFromFloats=function(t,i,r,n){return this.subtractFromFloatsToRef(t,i,r,n,new e)},e.prototype.subtractFromFloatsToRef=function(e,t,i,r,n){return n._x=this._x-e,n._y=this._y-t,n._z=this._z-i,n._w=this._w-r,n._isDirty=!0,n},e.prototype.subtract=function(t){return new e(this._x-t._x,this._y-t._y,this._z-t._z,this._w-t._w)},e.prototype.subtractInPlace=function(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._w-=e._w,this._isDirty=!0,this},e.prototype.scale=function(t){return new e(this._x*t,this._y*t,this._z*t,this._w*t)},e.prototype.scaleToRef=function(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._w=this._w*e,t._isDirty=!0,t},e.prototype.scaleInPlace=function(e){return this._x*=e,this._y*=e,this._z*=e,this._w*=e,this._isDirty=!0,this},e.prototype.scaleAndAddToRef=function(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._w+=this._w*e,t._isDirty=!0,t},e.prototype.multiply=function(t){var i=new e(0,0,0,1);return this.multiplyToRef(t,i),i},e.prototype.multiplyToRef=function(e,t){var i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,r=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,n=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,o=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,r,n,o),t},e.prototype.multiplyInPlace=function(e){return this.multiplyToRef(e,this)},e.prototype.multiplyByFloats=function(e,t,i,r){return this._x*=e,this._y*=t,this._z*=i,this._w*=r,this._isDirty=!0,this},e.prototype.divide=function(e){throw new ReferenceError("Can not divide a quaternion")},e.prototype.divideToRef=function(e,t){throw new ReferenceError("Can not divide a quaternion")},e.prototype.divideInPlace=function(e){throw new ReferenceError("Can not divide a quaternion")},e.prototype.minimizeInPlace=function(){throw new ReferenceError("Can not minimize a quaternion")},e.prototype.minimizeInPlaceFromFloats=function(){throw new ReferenceError("Can not minimize a quaternion")},e.prototype.maximizeInPlace=function(){throw new ReferenceError("Can not maximize a quaternion")},e.prototype.maximizeInPlaceFromFloats=function(){throw new ReferenceError("Can not maximize a quaternion")},e.prototype.negate=function(){return this.negateToRef(new e)},e.prototype.negateInPlace=function(){return this._x=-this._x,this._y=-this._y,this._z=-this._z,this._w=-this._w,this._isDirty=!0,this},e.prototype.negateToRef=function(e){return e._x=-this._x,e._y=-this._y,e._z=-this._z,e._w=-this._w,e._isDirty=!0,e},e.prototype.equalsToFloats=function(e,t,i,r){return this._x===e&&this._y===t&&this._z===i&&this._w===r},e.prototype.floorToRef=function(e){throw new ReferenceError("Can not floor a quaternion")},e.prototype.floor=function(){throw new ReferenceError("Can not floor a quaternion")},e.prototype.fractToRef=function(e){throw new ReferenceError("Can not fract a quaternion")},e.prototype.fract=function(){throw new ReferenceError("Can not fract a quaternion")},e.prototype.conjugateToRef=function(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e},e.prototype.conjugateInPlace=function(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this},e.prototype.conjugate=function(){return new e(-this._x,-this._y,-this._z,this._w)},e.prototype.invert=function(){var e=this.conjugate(),t=this.lengthSquared();return 0==t||1==t||e.scaleInPlace(1/t),e},e.prototype.invertInPlace=function(){this.conjugateInPlace();var e=this.lengthSquared();return 0==e||1==e||this.scaleInPlace(1/e),this},e.prototype.lengthSquared=function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},e.prototype.length=function(){return Math.sqrt(this.lengthSquared())},e.prototype.normalize=function(){return this.normalizeFromLength(this.length())},e.prototype.normalizeFromLength=function(e){return 0===e||1===e?this:this.scaleInPlace(1/e)},e.prototype.normalizeToNew=function(){var t=new e(0,0,0,1);return this.normalizeToRef(t),t},e.prototype.normalizeToRef=function(e){var t=this.length();return 0===t||1===t?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)},e.prototype.toEulerAngles=function(){var e=V.Zero();return this.toEulerAnglesToRef(e),e},e.prototype.toEulerAnglesToRef=function(e){var t=this._z,i=this._x,r=this._y,n=this._w,o=r*t-i*n,a=.4999999;if(o<-a)e._y=2*Math.atan2(r,n),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(o>a)e._y=2*Math.atan2(r,n),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{var s=n*n,l=t*t,c=i*i,u=r*r;e._z=Math.atan2(2*(i*r+t*n),-l-c+u+s),e._x=Math.asin(-2*o),e._y=Math.atan2(2*(t*i+r*n),l-c-u+s),e._isDirty=!0}return e},e.prototype.toRotationMatrix=function(e){return z.FromQuaternionToRef(this,e),e},e.prototype.fromRotationMatrix=function(t){return e.FromRotationMatrixToRef(t,this),this},e.prototype.dot=function(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w},e.FromRotationMatrix=function(t){var i=new e;return e.FromRotationMatrixToRef(t,i),i},e.FromRotationMatrixToRef=function(e,t){var i,r=e.m,n=r[0],o=r[4],a=r[8],s=r[1],l=r[5],c=r[9],u=r[2],h=r[6],d=r[10],p=n+l+d;return p>0?(i=.5/Math.sqrt(p+1),t._w=.25/i,t._x=(h-c)*i,t._y=(a-u)*i,t._z=(s-o)*i,t._isDirty=!0):n>l&&n>d?(i=2*Math.sqrt(1+n-l-d),t._w=(h-c)/i,t._x=.25*i,t._y=(o+s)/i,t._z=(a+u)/i,t._isDirty=!0):l>d?(i=2*Math.sqrt(1+l-n-d),t._w=(a-u)/i,t._x=(o+s)/i,t._y=.25*i,t._z=(c+h)/i,t._isDirty=!0):(i=2*Math.sqrt(1+d-n-l),t._w=(s-o)/i,t._x=(a+u)/i,t._y=(c+h)/i,t._z=.25*i,t._isDirty=!0),t},e.Dot=function(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w},e.AreClose=function(t,i,r){void 0===r&&(r=.1);var n=e.Dot(t,i);return 1-n*n<=r},e.SmoothToRef=function(t,i,r,n,o){var a=0===n?1:r/n;return a=F(a,0,1),e.SlerpToRef(t,i,a,o),o},e.Zero=function(){return new e(0,0,0,0)},e.Inverse=function(t){return new e(-t._x,-t._y,-t._z,t._w)},e.InverseToRef=function(e,t){return t.set(-e._x,-e._y,-e._z,e._w),t},e.Identity=function(){return new e(0,0,0,1)},e.IsIdentity=function(e){return e&&0===e._x&&0===e._y&&0===e._z&&1===e._w},e.RotationAxis=function(t,i){return e.RotationAxisToRef(t,i,new e)},e.RotationAxisToRef=function(e,t,i){var r=Math.sin(t/2);return e.normalize(),i._w=Math.cos(t/2),i._x=e._x*r,i._y=e._y*r,i._z=e._z*r,i._isDirty=!0,i},e.FromArray=function(t,i){return i||(i=0),new e(t[i],t[i+1],t[i+2],t[i+3])},e.FromArrayToRef=function(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i},e.FromFloatsToRef=function(e,t,i,r,n){return n.copyFromFloats(e,t,i,r),n},e.FromEulerAngles=function(t,i,r){var n=new e;return e.RotationYawPitchRollToRef(i,t,r,n),n},e.FromEulerAnglesToRef=function(t,i,r,n){return e.RotationYawPitchRollToRef(i,t,r,n),n},e.FromEulerVector=function(t){var i=new e;return e.RotationYawPitchRollToRef(t._y,t._x,t._z,i),i},e.FromEulerVectorToRef=function(t,i){return e.RotationYawPitchRollToRef(t._y,t._x,t._z,i),i},e.FromUnitVectorsToRef=function(e,t,i,r){void 0===r&&(r=A);var n=V.Dot(e,t)+1;return n<r?Math.abs(e.x)>Math.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(V.CrossToRef(e,t,H.Vector3[0]),i.set(H.Vector3[0].x,H.Vector3[0].y,H.Vector3[0].z,n)),i.normalize()},e.RotationYawPitchRoll=function(t,i,r){var n=new e;return e.RotationYawPitchRollToRef(t,i,r,n),n},e.RotationYawPitchRollToRef=function(e,t,i,r){var n=.5*i,o=.5*t,a=.5*e,s=Math.sin(n),l=Math.cos(n),c=Math.sin(o),u=Math.cos(o),h=Math.sin(a),d=Math.cos(a);return r._x=d*c*l+h*u*s,r._y=h*u*l-d*c*s,r._z=d*u*s-h*c*l,r._w=d*u*l+h*c*s,r._isDirty=!0,r},e.RotationAlphaBetaGamma=function(t,i,r){var n=new e;return e.RotationAlphaBetaGammaToRef(t,i,r,n),n},e.RotationAlphaBetaGammaToRef=function(e,t,i,r){var n=.5*(i+e),o=.5*(i-e),a=.5*t;return r._x=Math.cos(o)*Math.sin(a),r._y=Math.sin(o)*Math.sin(a),r._z=Math.sin(n)*Math.cos(a),r._w=Math.cos(n)*Math.cos(a),r._isDirty=!0,r},e.RotationQuaternionFromAxis=function(t,i,r){var n=new e(0,0,0,0);return e.RotationQuaternionFromAxisToRef(t,i,r,n),n},e.RotationQuaternionFromAxisToRef=function(t,i,r,n){var o=W.Matrix[0];return z.FromXYZAxesToRef(t.normalize(),i.normalize(),r.normalize(),o),e.FromRotationMatrixToRef(o,n),n},e.FromLookDirectionLH=function(t,i){var r=new e;return e.FromLookDirectionLHToRef(t,i,r),r},e.FromLookDirectionLHToRef=function(t,i,r){var n=W.Matrix[0];return z.LookDirectionLHToRef(t,i,n),e.FromRotationMatrixToRef(n,r),r},e.FromLookDirectionRH=function(t,i){var r=new e;return e.FromLookDirectionRHToRef(t,i,r),r},e.FromLookDirectionRHToRef=function(t,i,r){var n=W.Matrix[0];return z.LookDirectionRHToRef(t,i,n),e.FromRotationMatrixToRef(n,r)},e.Slerp=function(t,i,r){var n=e.Identity();return e.SlerpToRef(t,i,r,n),n},e.SlerpToRef=function(e,t,i,r){var n,o,a=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,s=!1;if(a<0&&(s=!0,a=-a),a>.999999)o=1-i,n=s?-i:i;else{var l=Math.acos(a),c=1/Math.sin(l);o=Math.sin((1-i)*l)*c,n=s?-Math.sin(i*l)*c:Math.sin(i*l)*c}return r._x=o*e._x+n*t._x,r._y=o*e._y+n*t._y,r._z=o*e._z+n*t._z,r._w=o*e._w+n*t._w,r._isDirty=!0,r},e.Hermite=function(t,i,r,n,o){var a=o*o,s=o*a,l=2*s-3*a+1,c=-2*s+3*a,u=s-2*a+o,h=s-a;return new e(t._x*l+r._x*c+i._x*u+n._x*h,t._y*l+r._y*c+i._y*u+n._y*h,t._z*l+r._z*c+i._z*u+n._z*h,t._w*l+r._w*c+i._w*u+n._w*h)},e.Hermite1stDerivative=function(t,i,r,n,o){var a=new e;return this.Hermite1stDerivativeToRef(t,i,r,n,o,a),a},e.Hermite1stDerivativeToRef=function(e,t,i,r,n,o){var a=n*n;return o._x=6*(a-n)*e._x+(3*a-4*n+1)*t._x+6*(-a+n)*i._x+(3*a-2*n)*r._x,o._y=6*(a-n)*e._y+(3*a-4*n+1)*t._y+6*(-a+n)*i._y+(3*a-2*n)*r._y,o._z=6*(a-n)*e._z+(3*a-4*n+1)*t._z+6*(-a+n)*i._z+(3*a-2*n)*r._z,o._w=6*(a-n)*e._w+(3*a-4*n+1)*t._w+6*(-a+n)*i._w+(3*a-2*n)*r._w,o._isDirty=!0,o},e.Normalize=function(t){var i=e.Zero();return e.NormalizeToRef(t,i),i},e.NormalizeToRef=function(e,t){return e.normalizeToRef(t),t},e.Clamp=function(t,i,r){var n=new e;return e.ClampToRef(t,i,r,n),n},e.ClampToRef=function(e,t,i,r){return r.copyFromFloats(F(e.x,t.x,i.x),F(e.y,t.y,i.y),F(e.z,t.z,i.z),F(e.w,t.w,i.w))},e.Random=function(t,i){return void 0===t&&(t=0),void 0===i&&(i=1),new e(D(t,i),D(t,i),D(t,i),D(t,i))},e.RandomToRef=function(e,t,i){return void 0===e&&(e=0),void 0===t&&(t=1),i.copyFromFloats(D(e,t),D(e,t),D(e,t),D(e,t))},e.Minimize=function(){throw new ReferenceError("Quaternion.Minimize does not make sense")},e.Maximize=function(){throw new ReferenceError("Quaternion.Maximize does not make sense")},e.Distance=function(t,i){return Math.sqrt(e.DistanceSquared(t,i))},e.DistanceSquared=function(e,t){var i=e.x-t.x,r=e.y-t.y,n=e.z-t.z,o=e.w-t.w;return i*i+r*r+n*n+o*o},e.Center=function(t,i){return e.CenterToRef(t,i,e.Zero())},e.CenterToRef=function(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)},e}();Object.defineProperties(G.prototype,{dimension:{value:[4]},rank:{value:1}});var z=function(){function e(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,I.MatrixTrackPrecisionChange&&I.MatrixTrackedMatrices.push(this),this._m=new I.MatrixCurrentType(16),this.markAsUpdated()}return Object.defineProperty(e,"Use64Bits",{get:function(){return I.MatrixUse64Bits},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"m",{get:function(){return this._m},enumerable:!1,configurable:!0}),e.prototype.markAsUpdated=function(){this.updateFlag=e._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0},e.prototype._updateIdentityStatus=function(e,t,i,r){void 0===t&&(t=!1),void 0===i&&(i=!1),void 0===r&&(r=!0),this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=!this._isIdentity&&t,this._isIdentity3x2Dirty=!this._isIdentity3x2&&r},e.prototype.isIdentity=function(){if(this._isIdentityDirty){this._isIdentityDirty=!1;var e=this._m;this._isIdentity=1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]}return this._isIdentity},e.prototype.isIdentityAs3x2=function(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,1!==this._m[0]||1!==this._m[5]||1!==this._m[15]||0!==this._m[1]||0!==this._m[2]||0!==this._m[3]||0!==this._m[4]||0!==this._m[6]||0!==this._m[7]||0!==this._m[8]||0!==this._m[9]||0!==this._m[10]||0!==this._m[11]||0!==this._m[12]||0!==this._m[13]||0!==this._m[14]?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2},e.prototype.determinant=function(){if(!0===this._isIdentity)return 1;var e=this._m,t=e[0],i=e[1],r=e[2],n=e[3],o=e[4],a=e[5],s=e[6],l=e[7],c=e[8],u=e[9],h=e[10],d=e[11],p=e[12],f=e[13],_=e[14],m=e[15],g=h*m-_*d,v=u*m-f*d,y=u*_-f*h,b=c*m-p*d,T=c*_-h*p,E=c*f-p*u;return t*+(a*g-s*v+l*y)+i*-(o*g-s*b+l*T)+r*+(o*v-a*b+l*E)+n*-(o*y-a*T+s*E)},e.prototype.toString=function(){return"{".concat(this.m[0],", ").concat(this.m[1],", ").concat(this.m[2],", ").concat(this.m[3],"\n").concat(this.m[4],", ").concat(this.m[5],", ").concat(this.m[6],", ").concat(this.m[7],"\n").concat(this.m[8],", ").concat(this.m[9],", ").concat(this.m[10],", ").concat(this.m[11],"\n").concat(this.m[12],", ").concat(this.m[13],", ").concat(this.m[14],", ").concat(this.m[15],"}")},e.prototype.toArray=function(e,t){if(void 0===e&&(e=null),void 0===t&&(t=0),!e)return this._m;for(var i=this._m,r=0;r<16;r++)e[t+r]=i[r];return this},e.prototype.asArray=function(){return this._m},e.prototype.fromArray=function(t,i){return void 0===i&&(i=0),e.FromArrayToRef(t,i,this)},e.prototype.copyFromFloats=function(){for(var t=[],i=0;i<arguments.length;i++)t[i]=arguments[i];return e.FromArrayToRef(t,0,this)},e.prototype.set=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var i=this._m,r=0;r<16;r++)i[r]=e[r];return this.markAsUpdated(),this},e.prototype.setAll=function(e){for(var t=this._m,i=0;i<16;i++)t[i]=e;return this.markAsUpdated(),this},e.prototype.invert=function(){return this.invertToRef(this),this},e.prototype.reset=function(){return e.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this},e.prototype.add=function(t){var i=new e;return this.addToRef(t,i),i},e.prototype.addToRef=function(e,t){for(var i=this._m,r=t._m,n=e.m,o=0;o<16;o++)r[o]=i[o]+n[o];return t.markAsUpdated(),t},e.prototype.addToSelf=function(e){for(var t=this._m,i=e.m,r=0;r<16;r++)t[r]+=i[r];return this.markAsUpdated(),this},e.prototype.addInPlace=function(e){for(var t=this._m,i=e.m,r=0;r<16;r++)t[r]+=i[r];return this.markAsUpdated(),this},e.prototype.addInPlaceFromFloats=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var i=this._m,r=0;r<16;r++)i[r]+=e[r];return this.markAsUpdated(),this},e.prototype.subtract=function(e){for(var t=this._m,i=e.m,r=0;r<16;r++)t[r]-=i[r];return this.markAsUpdated(),this},e.prototype.subtractToRef=function(e,t){for(var i=this._m,r=e.m,n=t._m,o=0;o<16;o++)n[o]=i[o]-r[o];return t.markAsUpdated(),t},e.prototype.subtractInPlace=function(e){for(var t=this._m,i=e.m,r=0;r<16;r++)t[r]-=i[r];return this.markAsUpdated(),this},e.prototype.subtractFromFloats=function(){for(var t=[],i=0;i<arguments.length;i++)t[i]=arguments[i];return this.subtractFromFloatsToRef.apply(this,T(T([],t,!1),[new e],!1))},e.prototype.subtractFromFloatsToRef=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var i=e.pop(),r=this._m,n=i._m,o=e,a=0;a<16;a++)n[a]=r[a]-o[a];return i.markAsUpdated(),i},e.prototype.invertToRef=function(t){if(!0===this._isIdentity)return e.IdentityToRef(t),t;var i=this._m,r=i[0],n=i[1],o=i[2],a=i[3],s=i[4],l=i[5],c=i[6],u=i[7],h=i[8],d=i[9],p=i[10],f=i[11],_=i[12],m=i[13],g=i[14],v=i[15],y=p*v-g*f,b=d*v-m*f,T=d*g-m*p,E=h*v-_*f,S=h*g-p*_,x=h*m-_*d,A=+(l*y-c*b+u*T),C=-(s*y-c*E+u*S),R=+(s*b-l*E+u*x),P=-(s*T-l*S+c*x),I=r*A+n*C+o*R+a*P;if(0===I)return t.copyFrom(this),t;var M=1/I,O=c*v-g*u,D=l*v-m*u,N=l*g-m*c,F=s*v-_*u,L=s*g-_*c,w=s*m-_*l,B=c*f-p*u,U=l*f-d*u,V=l*p-d*c,k=s*f-h*u,G=s*p-h*c,z=s*d-h*l,W=-(n*y-o*b+a*T),H=+(r*y-o*E+a*S),X=-(r*b-n*E+a*x),j=+(r*T-n*S+o*x),Y=+(n*O-o*D+a*N),K=-(r*O-o*F+a*L),Q=+(r*D-n*F+a*w),q=-(r*N-n*L+o*w),Z=-(n*B-o*U+a*V),J=+(r*B-o*k+a*G),$=-(r*U-n*k+a*z),ee=+(r*V-n*G+o*z);return e.FromValuesToRef(A*M,W*M,Y*M,Z*M,C*M,H*M,K*M,J*M,R*M,X*M,Q*M,$*M,P*M,j*M,q*M,ee*M,t),t},e.prototype.addAtIndex=function(e,t){return this._m[e]+=t,this.markAsUpdated(),this},e.prototype.multiplyAtIndex=function(e,t){return this._m[e]*=t,this.markAsUpdated(),this},e.prototype.setTranslationFromFloats=function(e,t,i){return this._m[12]=e,this._m[13]=t,this._m[14]=i,this.markAsUpdated(),this},e.prototype.addTranslationFromFloats=function(e,t,i){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=i,this.markAsUpdated(),this},e.prototype.setTranslation=function(e){return this.setTranslationFromFloats(e._x,e._y,e._z)},e.prototype.getTranslation=function(){return new V(this._m[12],this._m[13],this._m[14])},e.prototype.getTranslationToRef=function(e){return e.x=this._m[12],e.y=this._m[13],e.z=this._m[14],e},e.prototype.removeRotationAndScaling=function(){var t=this.m;return e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t[12],t[13],t[14],t[15],this),this._updateIdentityStatus(0===t[12]&&0===t[13]&&0===t[14]&&1===t[15]),this},e.prototype.copyFrom=function(e){e.copyToArray(this._m);var t=e;return this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this},e.prototype.copyToArray=function(e,t){void 0===t&&(t=0);var i=this._m;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],this},e.prototype.multiply=function(t){var i=new e;return this.multiplyToRef(t,i),i},e.prototype.multiplyInPlace=function(e){for(var t=this._m,i=e.m,r=0;r<16;r++)t[r]*=i[r];return this.markAsUpdated(),this},e.prototype.multiplyByFloats=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var i=this._m,r=0;r<16;r++)i[r]*=e[r];return this.markAsUpdated(),this},e.prototype.multiplyByFloatsToRef=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var i=e.pop(),r=this._m,n=i._m,o=e,a=0;a<16;a++)n[a]=r[a]*o[a];return i.markAsUpdated(),i},e.prototype.multiplyToRef=function(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)},e.prototype.multiplyToArray=function(e,t,i){var r=this._m,n=e.m,o=r[0],a=r[1],s=r[2],l=r[3],c=r[4],u=r[5],h=r[6],d=r[7],p=r[8],f=r[9],_=r[10],m=r[11],g=r[12],v=r[13],y=r[14],b=r[15],T=n[0],E=n[1],S=n[2],x=n[3],A=n[4],C=n[5],R=n[6],P=n[7],I=n[8],M=n[9],O=n[10],D=n[11],N=n[12],F=n[13],L=n[14],w=n[15];return t[i]=o*T+a*A+s*I+l*N,t[i+1]=o*E+a*C+s*M+l*F,t[i+2]=o*S+a*R+s*O+l*L,t[i+3]=o*x+a*P+s*D+l*w,t[i+4]=c*T+u*A+h*I+d*N,t[i+5]=c*E+u*C+h*M+d*F,t[i+6]=c*S+u*R+h*O+d*L,t[i+7]=c*x+u*P+h*D+d*w,t[i+8]=p*T+f*A+_*I+m*N,t[i+9]=p*E+f*C+_*M+m*F,t[i+10]=p*S+f*R+_*O+m*L,t[i+11]=p*x+f*P+_*D+m*w,t[i+12]=g*T+v*A+y*I+b*N,t[i+13]=g*E+v*C+y*M+b*F,t[i+14]=g*S+v*R+y*O+b*L,t[i+15]=g*x+v*P+y*D+b*w,this},e.prototype.divide=function(t){return this.divideToRef(t,new e)},e.prototype.divideToRef=function(e,t){for(var i=this._m,r=e.m,n=t._m,o=0;o<16;o++)n[o]=i[o]/r[o];return t.markAsUpdated(),t},e.prototype.divideInPlace=function(e){for(var t=this._m,i=e.m,r=0;r<16;r++)t[r]/=i[r];return this.markAsUpdated(),this},e.prototype.minimizeInPlace=function(e){for(var t=this._m,i=e.m,r=0;r<16;r++)t[r]=Math.min(t[r],i[r]);return this.markAsUpdated(),this},e.prototype.minimizeInPlaceFromFloats=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var i=this._m,r=0;r<16;r++)i[r]=Math.min(i[r],e[r]);return this.markAsUpdated(),this},e.prototype.maximizeInPlace=function(e){for(var t=this._m,i=e.m,r=0;r<16;r++)t[r]=Math.min(t[r],i[r]);return this.markAsUpdated(),this},e.prototype.maximizeInPlaceFromFloats=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var i=this._m,r=0;r<16;r++)i[r]=Math.min(i[r],e[r]);return this.markAsUpdated(),this},e.prototype.negate=function(){return this.negateToRef(new e)},e.prototype.negateInPlace=function(){for(var e=this._m,t=0;t<16;t++)e[t]=-e[t];return this.markAsUpdated(),this},e.prototype.negateToRef=function(e){for(var t=this._m,i=e._m,r=0;r<16;r++)i[r]=-t[r];return e.markAsUpdated(),e},e.prototype.equals=function(e){var t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;var i=this.m,r=t.m;return i[0]===r[0]&&i[1]===r[1]&&i[2]===r[2]&&i[3]===r[3]&&i[4]===r[4]&&i[5]===r[5]&&i[6]===r[6]&&i[7]===r[7]&&i[8]===r[8]&&i[9]===r[9]&&i[10]===r[10]&&i[11]===r[11]&&i[12]===r[12]&&i[13]===r[13]&&i[14]===r[14]&&i[15]===r[15]},e.prototype.equalsWithEpsilon=function(e,t){void 0===t&&(t=0);for(var i=this._m,r=e.m,n=0;n<16;n++)if(!O(i[n],r[n],t))return!1;return!0},e.prototype.equalsToFloats=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var i=this._m,r=0;r<16;r++)if(i[r]!=e[r])return!1;return!0},e.prototype.floor=function(){return this.floorToRef(new e)},e.prototype.floorToRef=function(e){for(var t=this._m,i=e._m,r=0;r<16;r++)i[r]=Math.floor(t[r]);return e.markAsUpdated(),e},e.prototype.fract=function(){return this.fractToRef(new e)},e.prototype.fractToRef=function(e){for(var t=this._m,i=e._m,r=0;r<16;r++)i[r]=t[r]-Math.floor(t[r]);return e.markAsUpdated(),e},e.prototype.clone=function(){var t=new e;return t.copyFrom(this),t},e.prototype.getClassName=function(){return"Matrix"},e.prototype.getHashCode=function(){for(var e=B(this._m[0]),t=1;t<16;t++)e=397*e^B(this._m[t]);return e},e.prototype.decomposeToTransformNode=function(e){return e.rotationQuaternion=e.rotationQuaternion||new G,this.decompose(e.scaling,e.rotationQuaternion,e.position)},e.prototype.decompose=function(t,i,r,n,o){if(void 0===o&&(o=!0),this._isIdentity)return r&&r.setAll(0),t&&t.setAll(1),i&&i.copyFromFloats(0,0,0,1),!0;var a=this._m;if(r&&r.copyFromFloats(a[12],a[13],a[14]),(t=t||W.Vector3[0]).x=Math.sqrt(a[0]*a[0]+a[1]*a[1]+a[2]*a[2]),t.y=Math.sqrt(a[4]*a[4]+a[5]*a[5]+a[6]*a[6]),t.z=Math.sqrt(a[8]*a[8]+a[9]*a[9]+a[10]*a[10]),n){var s=(o?n.absoluteScaling.x:n.scaling.x)<0?-1:1,l=(o?n.absoluteScaling.y:n.scaling.y)<0?-1:1,c=(o?n.absoluteScaling.z:n.scaling.z)<0?-1:1;t.x*=s,t.y*=l,t.z*=c}else this.determinant()<=0&&(t.y*=-1);if(0===t._x||0===t._y||0===t._z)return i&&i.copyFromFloats(0,0,0,1),!1;if(i){var u=1/t._x,h=1/t._y,d=1/t._z;e.FromValuesToRef(a[0]*u,a[1]*u,a[2]*u,0,a[4]*h,a[5]*h,a[6]*h,0,a[8]*d,a[9]*d,a[10]*d,0,0,0,0,1,W.Matrix[0]),G.FromRotationMatrixToRef(W.Matrix[0],i)}return!0},e.prototype.getRow=function(e){if(e<0||e>3)return null;var t=4*e;return new k(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])},e.prototype.getRowToRef=function(e,t){if(e>=0&&e<=3){var i=4*e;t.x=this._m[i+0],t.y=this._m[i+1],t.z=this._m[i+2],t.w=this._m[i+3]}return t},e.prototype.setRow=function(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)},e.prototype.transpose=function(){var t=new e;return e.TransposeToRef(this,t),t},e.prototype.transposeToRef=function(t){return e.TransposeToRef(this,t),t},e.prototype.setRowFromFloats=function(e,t,i,r,n){if(e<0||e>3)return this;var o=4*e;return this._m[o+0]=t,this._m[o+1]=i,this._m[o+2]=r,this._m[o+3]=n,this.markAsUpdated(),this},e.prototype.scale=function(t){var i=new e;return this.scaleToRef(t,i),i},e.prototype.scaleToRef=function(e,t){for(var i=0;i<16;i++)t._m[i]=this._m[i]*e;return t.markAsUpdated(),t},e.prototype.scaleAndAddToRef=function(e,t){for(var i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t.markAsUpdated(),t},e.prototype.scaleInPlace=function(e){for(var t=this._m,i=0;i<16;i++)t[i]*=e;return this.markAsUpdated(),this},e.prototype.toNormalMatrix=function(t){var i=W.Matrix[0];this.invertToRef(i),i.transposeToRef(t);var r=t._m;return e.FromValuesToRef(r[0],r[1],r[2],0,r[4],r[5],r[6],0,r[8],r[9],r[10],0,0,0,0,1,t),t},e.prototype.getRotationMatrix=function(){var t=new e;return this.getRotationMatrixToRef(t),t},e.prototype.getRotationMatrixToRef=function(t){var i=W.Vector3[0];if(!this.decompose(i))return e.IdentityToRef(t),t;var r=this._m,n=1/i._x,o=1/i._y,a=1/i._z;return e.FromValuesToRef(r[0]*n,r[1]*n,r[2]*n,0,r[4]*o,r[5]*o,r[6]*o,0,r[8]*a,r[9]*a,r[10]*a,0,0,0,0,1,t),t},e.prototype.toggleModelMatrixHandInPlace=function(){var e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this},e.prototype.toggleProjectionMatrixHandInPlace=function(){var e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this},e.FromArray=function(t,i){void 0===i&&(i=0);var r=new e;return e.FromArrayToRef(t,i,r),r},e.FromArrayToRef=function(e,t,i){for(var r=0;r<16;r++)i._m[r]=e[r+t];return i.markAsUpdated(),i},e.FromFloat32ArrayToRefScaled=function(e,t,i,r){for(var n=0;n<16;n++)r._m[n]=e[n+t]*i;return r.markAsUpdated(),r},Object.defineProperty(e,"IdentityReadOnly",{get:function(){return e._IdentityReadOnly},enumerable:!1,configurable:!0}),e.FromValuesToRef=function(e,t,i,r,n,o,a,s,l,c,u,h,d,p,f,_,m){var g=m._m;g[0]=e,g[1]=t,g[2]=i,g[3]=r,g[4]=n,g[5]=o,g[6]=a,g[7]=s,g[8]=l,g[9]=c,g[10]=u,g[11]=h,g[12]=d,g[13]=p,g[14]=f,g[15]=_,m.markAsUpdated()},e.FromValues=function(t,i,r,n,o,a,s,l,c,u,h,d,p,f,_,m){var g=new e,v=g._m;return v[0]=t,v[1]=i,v[2]=r,v[3]=n,v[4]=o,v[5]=a,v[6]=s,v[7]=l,v[8]=c,v[9]=u,v[10]=h,v[11]=d,v[12]=p,v[13]=f,v[14]=_,v[15]=m,g.markAsUpdated(),g},e.Compose=function(t,i,r){var n=new e;return e.ComposeToRef(t,i,r,n),n},e.ComposeToRef=function(e,t,i,r){var n=r._m,o=t._x,a=t._y,s=t._z,l=t._w,c=o+o,u=a+a,h=s+s,d=o*c,p=o*u,f=o*h,_=a*u,m=a*h,g=s*h,v=l*c,y=l*u,b=l*h,T=e._x,E=e._y,S=e._z;return n[0]=(1-(_+g))*T,n[1]=(p+b)*T,n[2]=(f-y)*T,n[3]=0,n[4]=(p-b)*E,n[5]=(1-(d+g))*E,n[6]=(m+v)*E,n[7]=0,n[8]=(f+y)*S,n[9]=(m-v)*S,n[10]=(1-(d+_))*S,n[11]=0,n[12]=i._x,n[13]=i._y,n[14]=i._z,n[15]=1,r.markAsUpdated(),r},e.Identity=function(){var t=e.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return t._updateIdentityStatus(!0),t},e.IdentityToRef=function(t){return e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(!0),t},e.Zero=function(){var t=e.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return t._updateIdentityStatus(!1),t},e.RotationX=function(t){var i=new e;return e.RotationXToRef(t,i),i},e.Invert=function(t){var i=new e;return t.invertToRef(i),i},e.RotationXToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);return e.FromValuesToRef(1,0,0,0,0,n,r,0,0,-r,n,0,0,0,0,1,i),i._updateIdentityStatus(1===n&&0===r),i},e.RotationY=function(t){var i=new e;return e.RotationYToRef(t,i),i},e.RotationYToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);return e.FromValuesToRef(n,0,-r,0,0,1,0,0,r,0,n,0,0,0,0,1,i),i._updateIdentityStatus(1===n&&0===r),i},e.RotationZ=function(t){var i=new e;return e.RotationZToRef(t,i),i},e.RotationZToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);return e.FromValuesToRef(n,r,0,0,-r,n,0,0,0,0,1,0,0,0,0,1,i),i._updateIdentityStatus(1===n&&0===r),i},e.RotationAxis=function(t,i){var r=new e;return e.RotationAxisToRef(t,i,r),r},e.RotationAxisToRef=function(e,t,i){var r=Math.sin(-t),n=Math.cos(-t),o=1-n;e.normalize();var a=i._m;return a[0]=e._x*e._x*o+n,a[1]=e._x*e._y*o-e._z*r,a[2]=e._x*e._z*o+e._y*r,a[3]=0,a[4]=e._y*e._x*o+e._z*r,a[5]=e._y*e._y*o+n,a[6]=e._y*e._z*o-e._x*r,a[7]=0,a[8]=e._z*e._x*o-e._y*r,a[9]=e._z*e._y*o+e._x*r,a[10]=e._z*e._z*o+n,a[11]=0,a[12]=0,a[13]=0,a[14]=0,a[15]=1,i.markAsUpdated(),i},e.RotationAlignToRef=function(e,t,i,r){void 0===r&&(r=!1);var n=V.Dot(t,e),o=i._m;if(n<-1+A)o[0]=-1,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=r?1:-1,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=r?-1:1,o[11]=0;else{var a=V.Cross(t,e),s=1/(1+n);o[0]=a._x*a._x*s+n,o[1]=a._y*a._x*s-a._z,o[2]=a._z*a._x*s+a._y,o[3]=0,o[4]=a._x*a._y*s+a._z,o[5]=a._y*a._y*s+n,o[6]=a._z*a._y*s-a._x,o[7]=0,o[8]=a._x*a._z*s-a._y,o[9]=a._y*a._z*s+a._x,o[10]=a._z*a._z*s+n,o[11]=0}return o[12]=0,o[13]=0,o[14]=0,o[15]=1,i.markAsUpdated(),i},e.RotationYawPitchRoll=function(t,i,r){var n=new e;return e.RotationYawPitchRollToRef(t,i,r,n),n},e.RotationYawPitchRollToRef=function(e,t,i,r){return G.RotationYawPitchRollToRef(e,t,i,W.Quaternion[0]),W.Quaternion[0].toRotationMatrix(r),r},e.Scaling=function(t,i,r){var n=new e;return e.ScalingToRef(t,i,r,n),n},e.ScalingToRef=function(t,i,r,n){return e.FromValuesToRef(t,0,0,0,0,i,0,0,0,0,r,0,0,0,0,1,n),n._updateIdentityStatus(1===t&&1===i&&1===r),n},e.Translation=function(t,i,r){var n=new e;return e.TranslationToRef(t,i,r,n),n},e.TranslationToRef=function(t,i,r,n){return e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,i,r,1,n),n._updateIdentityStatus(0===t&&0===i&&0===r),n},e.Lerp=function(t,i,r){var n=new e;return e.LerpToRef(t,i,r,n),n},e.LerpToRef=function(e,t,i,r){for(var n=r._m,o=e.m,a=t.m,s=0;s<16;s++)n[s]=o[s]*(1-i)+a[s]*i;return r.markAsUpdated(),r},e.DecomposeLerp=function(t,i,r){var n=new e;return e.DecomposeLerpToRef(t,i,r,n),n},e.DecomposeLerpToRef=function(t,i,r,n){var o=W.Vector3[0],a=W.Quaternion[0],s=W.Vector3[1];t.decompose(o,a,s);var l=W.Vector3[2],c=W.Quaternion[1],u=W.Vector3[3];i.decompose(l,c,u);var h=W.Vector3[4];V.LerpToRef(o,l,r,h);var d=W.Quaternion[2];G.SlerpToRef(a,c,r,d);var p=W.Vector3[5];return V.LerpToRef(s,u,r,p),e.ComposeToRef(h,d,p,n),n},e.LookAtLH=function(t,i,r){var n=new e;return e.LookAtLHToRef(t,i,r,n),n},e.LookAtLHToRef=function(t,i,r,n){var o=W.Vector3[0],a=W.Vector3[1],s=W.Vector3[2];i.subtractToRef(t,s),s.normalize(),V.CrossToRef(r,s,o);var l=o.lengthSquared();0===l?o.x=1:o.normalizeFromLength(Math.sqrt(l)),V.CrossToRef(s,o,a),a.normalize();var c=-V.Dot(o,t),u=-V.Dot(a,t),h=-V.Dot(s,t);return e.FromValuesToRef(o._x,a._x,s._x,0,o._y,a._y,s._y,0,o._z,a._z,s._z,0,c,u,h,1,n),n},e.LookAtRH=function(t,i,r){var n=new e;return e.LookAtRHToRef(t,i,r,n),n},e.LookAtRHToRef=function(t,i,r,n){var o=W.Vector3[0],a=W.Vector3[1],s=W.Vector3[2];t.subtractToRef(i,s),s.normalize(),V.CrossToRef(r,s,o);var l=o.lengthSquared();0===l?o.x=1:o.normalizeFromLength(Math.sqrt(l)),V.CrossToRef(s,o,a),a.normalize();var c=-V.Dot(o,t),u=-V.Dot(a,t),h=-V.Dot(s,t);return e.FromValuesToRef(o._x,a._x,s._x,0,o._y,a._y,s._y,0,o._z,a._z,s._z,0,c,u,h,1,n),n},e.LookDirectionLH=function(t,i){var r=new e;return e.LookDirectionLHToRef(t,i,r),r},e.LookDirectionLHToRef=function(t,i,r){var n=W.Vector3[0];n.copyFrom(t),n.scaleInPlace(-1);var o=W.Vector3[1];return V.CrossToRef(i,n,o),e.FromValuesToRef(o._x,o._y,o._z,0,i._x,i._y,i._z,0,n._x,n._y,n._z,0,0,0,0,1,r),r},e.LookDirectionRH=function(t,i){var r=new e;return e.LookDirectionRHToRef(t,i,r),r},e.LookDirectionRHToRef=function(t,i,r){var n=W.Vector3[2];return V.CrossToRef(i,t,n),e.FromValuesToRef(n._x,n._y,n._z,0,i._x,i._y,i._z,0,t._x,t._y,t._z,0,0,0,0,1,r),r},e.OrthoLH=function(t,i,r,n,o){var a=new e;return e.OrthoLHToRef(t,i,r,n,a,o),a},e.OrthoLHToRef=function(t,i,r,n,o,a){var s=2/t,l=2/i,c=2/(n-r),u=-(n+r)/(n-r);return e.FromValuesToRef(s,0,0,0,0,l,0,0,0,0,c,0,0,0,u,1,o),a&&o.multiplyToRef(X,o),o._updateIdentityStatus(1===s&&1===l&&1===c&&0===u),o},e.OrthoOffCenterLH=function(t,i,r,n,o,a,s){var l=new e;return e.OrthoOffCenterLHToRef(t,i,r,n,o,a,l,s),l},e.OrthoOffCenterLHToRef=function(t,i,r,n,o,a,s,l){var c=2/(i-t),u=2/(n-r),h=2/(a-o),d=-(a+o)/(a-o),p=(t+i)/(t-i),f=(n+r)/(r-n);return e.FromValuesToRef(c,0,0,0,0,u,0,0,0,0,h,0,p,f,d,1,s),l&&s.multiplyToRef(X,s),s.markAsUpdated(),s},e.ObliqueOffCenterLHToRef=function(t,i,r,n,o,a,s,l,c,u,h){var d=-s*Math.cos(l),p=-s*Math.sin(l);return e.TranslationToRef(0,0,-c,W.Matrix[1]),e.FromValuesToRef(1,0,0,0,0,1,0,0,d,p,1,0,0,0,0,1,W.Matrix[0]),W.Matrix[1].multiplyToRef(W.Matrix[0],W.Matrix[0]),e.TranslationToRef(0,0,c,W.Matrix[1]),W.Matrix[0].multiplyToRef(W.Matrix[1],W.Matrix[0]),e.OrthoOffCenterLHToRef(t,i,r,n,o,a,u,h),W.Matrix[0].multiplyToRef(u,u),u},e.OrthoOffCenterRH=function(t,i,r,n,o,a,s){var l=new e;return e.OrthoOffCenterRHToRef(t,i,r,n,o,a,l,s),l},e.OrthoOffCenterRHToRef=function(t,i,r,n,o,a,s,l){return e.OrthoOffCenterLHToRef(t,i,r,n,o,a,s,l),s._m[10]*=-1,s},e.ObliqueOffCenterRHToRef=function(t,i,r,n,o,a,s,l,c,u,h){var d=s*Math.cos(l),p=s*Math.sin(l);return e.TranslationToRef(0,0,c,W.Matrix[1]),e.FromValuesToRef(1,0,0,0,0,1,0,0,d,p,1,0,0,0,0,1,W.Matrix[0]),W.Matrix[1].multiplyToRef(W.Matrix[0],W.Matrix[0]),e.TranslationToRef(0,0,-c,W.Matrix[1]),W.Matrix[0].multiplyToRef(W.Matrix[1],W.Matrix[0]),e.OrthoOffCenterRHToRef(t,i,r,n,o,a,u,h),W.Matrix[0].multiplyToRef(u,u),u},e.PerspectiveLH=function(t,i,r,n,o,a){void 0===a&&(a=0);var s=new e,l=2*r/t,c=2*r/i,u=(n+r)/(n-r),h=-2*n*r/(n-r),d=Math.tan(a);return e.FromValuesToRef(l,0,0,0,0,c,0,d,0,0,u,1,0,0,h,0,s),o&&s.multiplyToRef(X,s),s._updateIdentityStatus(!1),s},e.PerspectiveFovLH=function(t,i,r,n,o,a,s){void 0===a&&(a=0),void 0===s&&(s=!1);var l=new e;return e.PerspectiveFovLHToRef(t,i,r,n,l,!0,o,a,s),l},e.PerspectiveFovLHToRef=function(t,i,r,n,o,a,s,l,c){void 0===a&&(a=!0),void 0===l&&(l=0),void 0===c&&(c=!1);var u=r,h=n,d=1/Math.tan(.5*t),p=a?d/i:d,f=a?d:d*i,_=c&&0===u?-1:0!==h?(h+u)/(h-u):1,m=c&&0===u?2*h:0!==h?-2*h*u/(h-u):-2*u,g=Math.tan(l);return e.FromValuesToRef(p,0,0,0,0,f,0,g,0,0,_,1,0,0,m,0,o),s&&o.multiplyToRef(X,o),o._updateIdentityStatus(!1),o},e.PerspectiveFovReverseLHToRef=function(t,i,r,n,o,a,s,l){void 0===a&&(a=!0),void 0===l&&(l=0);var c=1/Math.tan(.5*t),u=a?c/i:c,h=a?c:c*i,d=Math.tan(l);return e.FromValuesToRef(u,0,0,0,0,h,0,d,0,0,-r,1,0,0,1,0,o),s&&o.multiplyToRef(X,o),o._updateIdentityStatus(!1),o},e.PerspectiveFovRH=function(t,i,r,n,o,a,s){void 0===a&&(a=0),void 0===s&&(s=!1);var l=new e;return e.PerspectiveFovRHToRef(t,i,r,n,l,!0,o,a,s),l},e.PerspectiveFovRHToRef=function(t,i,r,n,o,a,s,l,c){void 0===a&&(a=!0),void 0===l&&(l=0),void 0===c&&(c=!1);var u=r,h=n,d=1/Math.tan(.5*t),p=a?d/i:d,f=a?d:d*i,_=c&&0===u?1:0!==h?-(h+u)/(h-u):-1,m=c&&0===u?2*h:0!==h?-2*h*u/(h-u):-2*u,g=Math.tan(l);return e.FromValuesToRef(p,0,0,0,0,f,0,g,0,0,_,-1,0,0,m,0,o),s&&o.multiplyToRef(X,o),o._updateIdentityStatus(!1),o},e.PerspectiveFovReverseRHToRef=function(t,i,r,n,o,a,s,l){void 0===a&&(a=!0),void 0===l&&(l=0);var c=1/Math.tan(.5*t),u=a?c/i:c,h=a?c:c*i,d=Math.tan(l);return e.FromValuesToRef(u,0,0,0,0,h,0,d,0,0,-r,-1,0,0,-1,0,o),s&&o.multiplyToRef(X,o),o._updateIdentityStatus(!1),o},e.GetFinalMatrix=function(t,i,r,n,o,a){var s=t.width,l=t.height,c=t.x,u=t.y,h=e.FromValues(s/2,0,0,0,0,-l/2,0,0,0,0,a-o,0,c+s/2,l/2+u,o,1),d=new e;return i.multiplyToRef(r,d),d.multiplyToRef(n,d),d.multiplyToRef(h,d)},e.GetAsMatrix2x2=function(e){var t=e.m,i=[t[0],t[1],t[4],t[5]];return I.MatrixUse64Bits?i:new Float32Array(i)},e.GetAsMatrix3x3=function(e){var t=e.m,i=[t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]];return I.MatrixUse64Bits?i:new Float32Array(i)},e.Transpose=function(t){var i=new e;return e.TransposeToRef(t,i),i},e.TransposeToRef=function(e,t){var i=e.m,r=i[0],n=i[4],o=i[8],a=i[12],s=i[1],l=i[5],c=i[9],u=i[13],h=i[2],d=i[6],p=i[10],f=i[14],_=i[3],m=i[7],g=i[11],v=i[15],y=t._m;return y[0]=r,y[1]=n,y[2]=o,y[3]=a,y[4]=s,y[5]=l,y[6]=c,y[7]=u,y[8]=h,y[9]=d,y[10]=p,y[11]=f,y[12]=_,y[13]=m,y[14]=g,y[15]=v,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t},e.Reflection=function(t){var i=new e;return e.ReflectionToRef(t,i),i},e.ReflectionToRef=function(t,i){t.normalize();var r=t.normal.x,n=t.normal.y,o=t.normal.z,a=-2*r,s=-2*n,l=-2*o;return e.FromValuesToRef(a*r+1,s*r,l*r,0,a*n,s*n+1,l*n,0,a*o,s*o,l*o+1,0,a*t.d,s*t.d,l*t.d,1,i),i},e.FromXYZAxesToRef=function(t,i,r,n){return e.FromValuesToRef(t._x,t._y,t._z,0,i._x,i._y,i._z,0,r._x,r._y,r._z,0,0,0,0,1,n),n},e.FromQuaternionToRef=function(e,t){var i=e._x*e._x,r=e._y*e._y,n=e._z*e._z,o=e._x*e._y,a=e._z*e._w,s=e._z*e._x,l=e._y*e._w,c=e._y*e._z,u=e._x*e._w;return t._m[0]=1-2*(r+n),t._m[1]=2*(o+a),t._m[2]=2*(s-l),t._m[3]=0,t._m[4]=2*(o-a),t._m[5]=1-2*(n+i),t._m[6]=2*(c+u),t._m[7]=0,t._m[8]=2*(s+l),t._m[9]=2*(c-u),t._m[10]=1-2*(r+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t},e._UpdateFlagSeed=0,e._IdentityReadOnly=e.Identity(),e}();Object.defineProperties(z.prototype,{dimension:{value:[4,4]},rank:{value:2}});var W=function(){function e(){}return e.Vector3=C.BuildTuple(11,V.Zero),e.Matrix=C.BuildTuple(2,z.Identity),e.Quaternion=C.BuildTuple(3,G.Zero),e}(),H=function(){function e(){}return e.Vector2=C.BuildTuple(3,U.Zero),e.Vector3=C.BuildTuple(13,V.Zero),e.Vector4=C.BuildTuple(3,k.Zero),e.Quaternion=C.BuildTuple(2,G.Zero),e.Matrix=C.BuildTuple(8,z.Identity),e}();a("BABYLON.Vector2",U),a("BABYLON.Vector3",V),a("BABYLON.Vector4",k),a("BABYLON.Matrix",z);var X=z.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1),j=function(){function e(){}return e.Sign=function(e){return 0==(e=+e)||isNaN(e)?e:e>0?1:-1},e.Log2=function(e){return Math.log(e)*Math.LOG2E},e.ILog2=function(e){if(Math.log2)return Math.floor(Math.log2(e));if(e<0)return NaN;if(0===e)return-1/0;var t=0;if(e<1){for(;e<1;)t++,e*=2;t=-t}else if(e>1)for(;e>1;)t++,e=Math.floor(e/2);return t},e.Repeat=function(e,t){return e-Math.floor(e/t)*t},e.Normalize=function(e,t,i){return(e-t)/(i-t)},e.Denormalize=function(e,t,i){return e*(i-t)+t},e.DeltaAngle=function(t,i){var r=e.Repeat(i-t,360);return r>180&&(r-=360),r},e.PingPong=function(t,i){var r=e.Repeat(t,2*i);return i-Math.abs(r-i)},e.SmoothStep=function(t,i,r){var n=e.Clamp(r);return i*(n=-2*n*n*n+3*n*n)+t*(1-n)},e.MoveTowards=function(t,i,r){return Math.abs(i-t)<=r?i:t+e.Sign(i-t)*r},e.MoveTowardsAngle=function(t,i,r){var n=e.DeltaAngle(t,i),o=0;return-r<n&&n<r?o=i:(i=t+n,o=e.MoveTowards(t,i,r)),o},e.LerpAngle=function(t,i,r){var n=e.Repeat(i-t,360);return n>180&&(n-=360),t+n*F(r)},e.InverseLerp=function(e,t,i){return e!=t?F((i-e)/(t-e)):0},e.Hermite=function(e,t,i,r,n){var o=n*n,a=n*o;return e*(2*a-3*o+1)+i*(-2*a+3*o)+t*(a-2*o+n)+r*(a-o)},e.Hermite1stDerivative=function(e,t,i,r,n){var o=n*n;return 6*(o-n)*e+(3*o-4*n+1)*t+6*(-o+n)*i+(3*o-2*n)*r},e.RangeToPercent=function(e,t,i){return(e-t)/(i-t)},e.PercentToRange=function(e,t,i){return(i-t)*e+t},e.HCF=function(t,i){var r=t%i;return 0===r?i:e.HCF(i,r)},e.TwoPi=2*Math.PI,e.WithinEpsilon=O,e.ToHex=w,e.Clamp=F,e.Lerp=N,e.RandomRange=D,e.NormalizeRadians=L,e}();function Y(e){return Math.pow(e,S)}function K(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function Q(e){return Math.pow(e,E)}function q(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}var Z=function(){function e(e,t,i){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),this.r=e,this.g=t,this.b=i}return e.prototype.toString=function(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"},e.prototype.getClassName=function(){return"Color3"},e.prototype.getHashCode=function(){var e=255*this.r|0;return 397*(e=397*e^255*this.g)^255*this.b},e.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this},e.prototype.fromArray=function(t,i){return void 0===i&&(i=0),e.FromArrayToRef(t,i,this),this},e.prototype.toColor4=function(e){return void 0===e&&(e=1),new J(this.r,this.g,this.b,e)},e.prototype.asArray=function(){return[this.r,this.g,this.b]},e.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},e.prototype.multiply=function(t){return new e(this.r*t.r,this.g*t.g,this.b*t.b)},e.prototype.multiplyToRef=function(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t},e.prototype.multiplyInPlace=function(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this},e.prototype.multiplyByFloats=function(t,i,r){return new e(this.r*t,this.g*i,this.b*r)},e.prototype.divide=function(e){throw new ReferenceError("Can not divide a color")},e.prototype.divideToRef=function(e,t){throw new ReferenceError("Can not divide a color")},e.prototype.divideInPlace=function(e){throw new ReferenceError("Can not divide a color")},e.prototype.minimizeInPlace=function(e){return this.minimizeInPlaceFromFloats(e.r,e.g,e.b)},e.prototype.maximizeInPlace=function(e){return this.maximizeInPlaceFromFloats(e.r,e.g,e.b)},e.prototype.minimizeInPlaceFromFloats=function(e,t,i){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this},e.prototype.maximizeInPlaceFromFloats=function(e,t,i){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this},e.prototype.floorToRef=function(e){throw new ReferenceError("Can not floor a color")},e.prototype.floor=function(){throw new ReferenceError("Can not floor a color")},e.prototype.fractToRef=function(e){throw new ReferenceError("Can not fract a color")},e.prototype.fract=function(){throw new ReferenceError("Can not fract a color")},e.prototype.equals=function(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b},e.prototype.equalsFloats=function(e,t,i){return this.equalsToFloats(e,t,i)},e.prototype.equalsToFloats=function(e,t,i){return this.r===e&&this.g===t&&this.b===i},e.prototype.equalsWithEpsilon=function(e,t){return void 0===t&&(t=A),j.WithinEpsilon(this.r,e.r,t)&&j.WithinEpsilon(this.g,e.g,t)&&j.WithinEpsilon(this.b,e.b,t)},e.prototype.negate=function(){throw new ReferenceError("Can not negate a color")},e.prototype.negateInPlace=function(){throw new ReferenceError("Can not negate a color")},e.prototype.negateToRef=function(e){throw new ReferenceError("Can not negate a color")},e.prototype.scale=function(t){return new e(this.r*t,this.g*t,this.b*t)},e.prototype.scaleInPlace=function(e){return this.r*=e,this.g*=e,this.b*=e,this},e.prototype.scaleToRef=function(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t},e.prototype.scaleAndAddToRef=function(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t},e.prototype.clampToRef=function(e,t,i){return void 0===e&&(e=0),void 0===t&&(t=1),i.r=F(this.r,e,t),i.g=F(this.g,e,t),i.b=F(this.b,e,t),i},e.prototype.add=function(t){return new e(this.r+t.r,this.g+t.g,this.b+t.b)},e.prototype.addInPlace=function(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this},e.prototype.addInPlaceFromFloats=function(e,t,i){return this.r+=e,this.g+=t,this.b+=i,this},e.prototype.addToRef=function(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t},e.prototype.subtract=function(t){return new e(this.r-t.r,this.g-t.g,this.b-t.b)},e.prototype.subtractToRef=function(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t},e.prototype.subtractInPlace=function(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this},e.prototype.subtractFromFloats=function(t,i,r){return new e(this.r-t,this.g-i,this.b-r)},e.prototype.subtractFromFloatsToRef=function(e,t,i,r){return r.r=this.r-e,r.g=this.g-t,r.b=this.b-i,r},e.prototype.clone=function(){return new e(this.r,this.g,this.b)},e.prototype.copyFrom=function(e){return this.r=e.r,this.g=e.g,this.b=e.b,this},e.prototype.copyFromFloats=function(e,t,i){return this.r=e,this.g=t,this.b=i,this},e.prototype.set=function(e,t,i){return this.copyFromFloats(e,t,i)},e.prototype.setAll=function(e){return this.r=this.g=this.b=e,this},e.prototype.toHexString=function(){var e=Math.round(255*this.r),t=Math.round(255*this.g),i=Math.round(255*this.b);return"#"+w(e)+w(t)+w(i)},e.prototype.toHSV=function(){return this.toHSVToRef(new e)},e.prototype.toHSVToRef=function(e){var t=this.r,i=this.g,r=this.b,n=Math.max(t,i,r),o=Math.min(t,i,r),a=0,s=0,l=n,c=n-o;return 0!==n&&(s=c/n),n!=o&&(n==t?(a=(i-r)/c,i<r&&(a+=6)):n==i?a=(r-t)/c+2:n==r&&(a=(t-i)/c+4),a*=60),e.r=a,e.g=s,e.b=l,e},e.prototype.toLinearSpace=function(t){void 0===t&&(t=!1);var i=new e;return this.toLinearSpaceToRef(i,t),i},e.prototype.toLinearSpaceToRef=function(e,t){return void 0===t&&(t=!1),t?(e.r=K(this.r),e.g=K(this.g),e.b=K(this.b)):(e.r=Y(this.r),e.g=Y(this.g),e.b=Y(this.b)),this},e.prototype.toGammaSpace=function(t){void 0===t&&(t=!1);var i=new e;return this.toGammaSpaceToRef(i,t),i},e.prototype.toGammaSpaceToRef=function(e,t){return void 0===t&&(t=!1),t?(e.r=q(this.r),e.g=q(this.g),e.b=q(this.b)):(e.r=Q(this.r),e.g=Q(this.g),e.b=Q(this.b)),this},e.HSVtoRGBToRef=function(e,t,i,r){var n=i*t,o=e/60,a=n*(1-Math.abs(o%2-1)),s=0,l=0,c=0;o>=0&&o<=1?(s=n,l=a):o>=1&&o<=2?(s=a,l=n):o>=2&&o<=3?(l=n,c=a):o>=3&&o<=4?(l=a,c=n):o>=4&&o<=5?(s=a,c=n):o>=5&&o<=6&&(s=n,c=a);var u=i-n;return r.r=s+u,r.g=l+u,r.b=c+u,r},e.FromHSV=function(t,i,r){var n=new e(0,0,0);return e.HSVtoRGBToRef(t,i,r,n),n},e.FromHexString=function(t){if("#"!==t.substring(0,1)||7!==t.length)return new e(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),n=parseInt(t.substring(5,7),16);return e.FromInts(i,r,n)},e.FromArray=function(t,i){return void 0===i&&(i=0),new e(t[i],t[i+1],t[i+2])},e.FromArrayToRef=function(e,t,i){void 0===t&&(t=0),i.r=e[t],i.g=e[t+1],i.b=e[t+2]},e.FromInts=function(t,i,r){return new e(t/255,i/255,r/255)},e.Lerp=function(t,i,r){var n=new e(0,0,0);return e.LerpToRef(t,i,r,n),n},e.LerpToRef=function(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i},e.Hermite=function(t,i,r,n,o){var a=o*o,s=o*a,l=2*s-3*a+1,c=-2*s+3*a,u=s-2*a+o,h=s-a;return new e(t.r*l+r.r*c+i.r*u+n.r*h,t.g*l+r.g*c+i.g*u+n.g*h,t.b*l+r.b*c+i.b*u+n.b*h)},e.Hermite1stDerivative=function(t,i,r,n,o){var a=e.Black();return this.Hermite1stDerivativeToRef(t,i,r,n,o,a),a},e.Hermite1stDerivativeToRef=function(e,t,i,r,n,o){var a=n*n;o.r=6*(a-n)*e.r+(3*a-4*n+1)*t.r+6*(-a+n)*i.r+(3*a-2*n)*r.r,o.g=6*(a-n)*e.g+(3*a-4*n+1)*t.g+6*(-a+n)*i.g+(3*a-2*n)*r.g,o.b=6*(a-n)*e.b+(3*a-4*n+1)*t.b+6*(-a+n)*i.b+(3*a-2*n)*r.b},e.Red=function(){return new e(1,0,0)},e.Green=function(){return new e(0,1,0)},e.Blue=function(){return new e(0,0,1)},e.Black=function(){return new e(0,0,0)},Object.defineProperty(e,"BlackReadOnly",{get:function(){return e._BlackReadOnly},enumerable:!1,configurable:!0}),e.White=function(){return new e(1,1,1)},e.Purple=function(){return new e(.5,0,.5)},e.Magenta=function(){return new e(1,0,1)},e.Yellow=function(){return new e(1,1,0)},e.Gray=function(){return new e(.5,.5,.5)},e.Teal=function(){return new e(0,1,1)},e.Random=function(){return new e(Math.random(),Math.random(),Math.random())},e._BlackReadOnly=e.Black(),e}();Object.defineProperties(Z.prototype,{dimension:{value:[3]},rank:{value:1}});var J=function(){function e(e,t,i,r){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=1),this.r=e,this.g=t,this.b=i,this.a=r}return e.prototype.asArray=function(){return[this.r,this.g,this.b,this.a]},e.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this},e.prototype.fromArray=function(e,t){return void 0===t&&(t=0),this.r=e[t],this.g=e[t+1],this.b=e[t+2],this.a=e[t+3],this},e.prototype.equals=function(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a},e.prototype.add=function(t){return new e(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},e.prototype.addToRef=function(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t.a=this.a+e.a,t},e.prototype.addInPlace=function(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this},e.prototype.addInPlaceFromFloats=function(e,t,i,r){return this.r+=e,this.g+=t,this.b+=i,this.a+=r,this},e.prototype.subtract=function(t){return new e(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},e.prototype.subtractToRef=function(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,t},e.prototype.subtractInPlace=function(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this.a-=e.a,this},e.prototype.subtractFromFloats=function(t,i,r,n){return new e(this.r-t,this.g-i,this.b-r,this.a-n)},e.prototype.subtractFromFloatsToRef=function(e,t,i,r,n){return n.r=this.r-e,n.g=this.g-t,n.b=this.b-i,n.a=this.a-r,n},e.prototype.scale=function(t){return new e(this.r*t,this.g*t,this.b*t,this.a*t)},e.prototype.scaleInPlace=function(e){return this.r*=e,this.g*=e,this.b*=e,this.a*=e,this},e.prototype.scaleToRef=function(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,t},e.prototype.scaleAndAddToRef=function(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,t},e.prototype.clampToRef=function(e,t,i){return void 0===e&&(e=0),void 0===t&&(t=1),i.r=F(this.r,e,t),i.g=F(this.g,e,t),i.b=F(this.b,e,t),i.a=F(this.a,e,t),i},e.prototype.multiply=function(t){return new e(this.r*t.r,this.g*t.g,this.b*t.b,this.a*t.a)},e.prototype.multiplyToRef=function(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t},e.prototype.multiplyInPlace=function(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this.a*=e.a,this},e.prototype.multiplyByFloats=function(t,i,r,n){return new e(this.r*t,this.g*i,this.b*r,this.a*n)},e.prototype.divide=function(e){throw new ReferenceError("Can not divide a color")},e.prototype.divideToRef=function(e,t){throw new ReferenceError("Can not divide a color")},e.prototype.divideInPlace=function(e){throw new ReferenceError("Can not divide a color")},e.prototype.minimizeInPlace=function(e){return this.r=Math.min(this.r,e.r),this.g=Math.min(this.g,e.g),this.b=Math.min(this.b,e.b),this.a=Math.min(this.a,e.a),this},e.prototype.maximizeInPlace=function(e){return this.r=Math.max(this.r,e.r),this.g=Math.max(this.g,e.g),this.b=Math.max(this.b,e.b),this.a=Math.max(this.a,e.a),this},e.prototype.minimizeInPlaceFromFloats=function(e,t,i,r){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this.a=Math.min(r,this.a),this},e.prototype.maximizeInPlaceFromFloats=function(e,t,i,r){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this.a=Math.max(r,this.a),this},e.prototype.floorToRef=function(e){throw new ReferenceError("Can not floor a color")},e.prototype.floor=function(){throw new ReferenceError("Can not floor a color")},e.prototype.fractToRef=function(e){throw new ReferenceError("Can not fract a color")},e.prototype.fract=function(){throw new ReferenceError("Can not fract a color")},e.prototype.negate=function(){throw new ReferenceError("Can not negate a color")},e.prototype.negateInPlace=function(){throw new ReferenceError("Can not negate a color")},e.prototype.negateToRef=function(e){throw new ReferenceError("Can not negate a color")},e.prototype.equalsWithEpsilon=function(e,t){return void 0===t&&(t=A),j.WithinEpsilon(this.r,e.r,t)&&j.WithinEpsilon(this.g,e.g,t)&&j.WithinEpsilon(this.b,e.b,t)&&j.WithinEpsilon(this.a,e.a,t)},e.prototype.equalsToFloats=function(e,t,i,r){return this.r===e&&this.g===t&&this.b===i&&this.a===r},e.prototype.toString=function(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"},e.prototype.getClassName=function(){return"Color4"},e.prototype.getHashCode=function(){var e=255*this.r|0;return 397*(e=397*(e=397*e^255*this.g)^255*this.b)^255*this.a},e.prototype.clone=function(){return(new e).copyFrom(this)},e.prototype.copyFrom=function(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this},e.prototype.copyFromFloats=function(e,t,i,r){return this.r=e,this.g=t,this.b=i,this.a=r,this},e.prototype.set=function(e,t,i,r){return this.copyFromFloats(e,t,i,r)},e.prototype.setAll=function(e){return this.r=this.g=this.b=this.a=e,this},e.prototype.toHexString=function(e){void 0===e&&(e=!1);var t=Math.round(255*this.r),i=Math.round(255*this.g),r=Math.round(255*this.b);if(e)return"#"+w(t)+w(i)+w(r);var n=Math.round(255*this.a);return"#"+w(t)+w(i)+w(r)+w(n)},e.prototype.toLinearSpace=function(t){void 0===t&&(t=!1);var i=new e;return this.toLinearSpaceToRef(i,t),i},e.prototype.toLinearSpaceToRef=function(e,t){return void 0===t&&(t=!1),t?(e.r=K(this.r),e.g=K(this.g),e.b=K(this.b)):(e.r=Y(this.r),e.g=Y(this.g),e.b=Y(this.b)),e.a=this.a,this},e.prototype.toGammaSpace=function(t){void 0===t&&(t=!1);var i=new e;return this.toGammaSpaceToRef(i,t),i},e.prototype.toGammaSpaceToRef=function(e,t){return void 0===t&&(t=!1),t?(e.r=q(this.r),e.g=q(this.g),e.b=q(this.b)):(e.r=Q(this.r),e.g=Q(this.g),e.b=Q(this.b)),e.a=this.a,this},e.FromHexString=function(t){if("#"!==t.substring(0,1)||9!==t.length&&7!==t.length)return new e(0,0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),n=parseInt(t.substring(5,7),16),o=9===t.length?parseInt(t.substring(7,9),16):255;return e.FromInts(i,r,n,o)},e.Lerp=function(t,i,r){return e.LerpToRef(t,i,r,new e)},e.LerpToRef=function(e,t,i,r){return r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i,r.a=e.a+(t.a-e.a)*i,r},e.Hermite=function(t,i,r,n,o){var a=o*o,s=o*a,l=2*s-3*a+1,c=-2*s+3*a,u=s-2*a+o,h=s-a;return new e(t.r*l+r.r*c+i.r*u+n.r*h,t.g*l+r.g*c+i.g*u+n.g*h,t.b*l+r.b*c+i.b*u+n.b*h,t.a*l+r.a*c+i.a*u+n.a*h)},e.Hermite1stDerivative=function(t,i,r,n,o){var a=new e;return this.Hermite1stDerivativeToRef(t,i,r,n,o,a),a},e.Hermite1stDerivativeToRef=function(e,t,i,r,n,o){var a=n*n;o.r=6*(a-n)*e.r+(3*a-4*n+1)*t.r+6*(-a+n)*i.r+(3*a-2*n)*r.r,o.g=6*(a-n)*e.g+(3*a-4*n+1)*t.g+6*(-a+n)*i.g+(3*a-2*n)*r.g,o.b=6*(a-n)*e.b+(3*a-4*n+1)*t.b+6*(-a+n)*i.b+(3*a-2*n)*r.b,o.a=6*(a-n)*e.a+(3*a-4*n+1)*t.a+6*(-a+n)*i.a+(3*a-2*n)*r.a},e.FromColor3=function(t,i){return void 0===i&&(i=1),new e(t.r,t.g,t.b,i)},e.FromArray=function(t,i){return void 0===i&&(i=0),new e(t[i],t[i+1],t[i+2],t[i+3])},e.FromArrayToRef=function(e,t,i){void 0===t&&(t=0),i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]},e.FromInts=function(t,i,r,n){return new e(t/255,i/255,r/255,n/255)},e.CheckColors4=function(e,t){if(e.length===3*t){for(var i=[],r=0;r<e.length;r+=3){var n=r/3*4;i[n]=e[r],i[n+1]=e[r+1],i[n+2]=e[r+2],i[n+3]=1}return i}return e},e}();Object.defineProperties(J.prototype,{dimension:{value:[4]},rank:{value:1}});var $=function(){function e(){}return e.Color3=C.BuildArray(3,Z.Black),e.Color4=C.BuildArray(3,(function(){return new J(0,0,0,0)})),e}();a("BABYLON.Color3",Z),a("BABYLON.Color4",J);var ee=function(){function e(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new f,e.parameter?(this.trigger=e.trigger,this._triggerParameter=e.parameter):e.trigger?this.trigger=e.trigger:this.trigger=e,this._nextActiveAction=this,this._condition=t}return e.prototype._prepare=function(){},e.prototype.getTriggerParameter=function(){return this._triggerParameter},e.prototype.setTriggerParameter=function(e){this._triggerParameter=e},e.prototype._evaluateConditionForCurrentFrame=function(){var e=this._condition;if(!e)return!0;var t=this._actionManager.getScene().getRenderId();return e._evaluationId!==t&&(e._evaluationId=t,e._currentResult=e.isValid()),e._currentResult},e.prototype._executeCurrent=function(e){this._evaluateConditionForCurrentFrame()&&(this.onBeforeExecuteObservable.notifyObservers(this),this._nextActiveAction.execute(e),this.skipToNextActiveAction())},e.prototype.execute=function(e){},e.prototype.skipToNextActiveAction=function(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this},e.prototype.then=function(e){return this._child=e,e._actionManager=this._actionManager,e._prepare(),e},e.prototype._getProperty=function(e){return this._actionManager._getProperty(e)},e.prototype._getEffectiveTarget=function(e,t){return this._actionManager._getEffectiveTarget(e,t)},e.prototype.serialize=function(e){return null},e.prototype._serialize=function(e,t){var i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){var r=this._condition.serialize();return r.children.push(i),t&&t.children.push(r),r}return t&&t.children.push(i),i},e._SerializeValueAsString=function(e){return"number"==typeof e?e.toString():"boolean"==typeof e?e?"true":"false":e instanceof U?e.x+", "+e.y:e instanceof V?e.x+", "+e.y+", "+e.z:e instanceof Z?e.r+", "+e.g+", "+e.b:e instanceof J?e.r+", "+e.g+", "+e.b+", "+e.a:e},e._GetTargetProperty=function(e){return{name:"target",targetType:e._isMesh?"MeshProperties":e._isLight?"LightProperties":e._isCamera?"CameraProperties":e._isMaterial?"MaterialProperties":"SceneProperties",value:e._isScene?"Scene":e.name}},e}();a("BABYLON.Action",ee);var te=function(){function e(e,t,i,r,n,o){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=r,this.sourceEvent=n,this.additionalData=o}return e.CreateNew=function(t,i,r){var n=t.getScene();return new e(t,n.pointerX,n.pointerY,n.meshUnderPointer||t,i,r)},e.CreateNewFromSprite=function(t,i,r,n){return new e(t,i.pointerX,i.pointerY,i.meshUnderPointer,r,n)},e.CreateNewFromScene=function(t,i){return new e(null,t.pointerX,t.pointerY,t.meshUnderPointer,i)},e.CreateNewFromPrimitive=function(t,i,r,n){return new e(t,i.x,i.y,null,r,n)},e}(),ie=function(){function e(e){this._actionManager=e}return e.prototype.isValid=function(){return!0},e.prototype._getProperty=function(e){return this._actionManager._getProperty(e)},e.prototype._getEffectiveTarget=function(e,t){return this._actionManager._getEffectiveTarget(e,t)},e.prototype.serialize=function(){},e.prototype._serialize=function(e){return{type:2,children:[],name:e.name,properties:e.properties}},e}(),re=function(e){function t(i,r,n,o,a){void 0===a&&(a=t.IsEqual);var s=e.call(this,i)||this;return s.propertyPath=n,s.value=o,s.operator=a,s._target=r,s._effectiveTarget=s._getEffectiveTarget(r,s.propertyPath),s._property=s._getProperty(s.propertyPath),s}return m(t,e),Object.defineProperty(t,"IsEqual",{get:function(){return t._IsEqual},enumerable:!1,configurable:!0}),Object.defineProperty(t,"IsDifferent",{get:function(){return t._IsDifferent},enumerable:!1,configurable:!0}),Object.defineProperty(t,"IsGreater",{get:function(){return t._IsGreater},enumerable:!1,configurable:!0}),Object.defineProperty(t,"IsLesser",{get:function(){return t._IsLesser},enumerable:!1,configurable:!0}),t.prototype.isValid=function(){switch(this.operator){case t.IsGreater:return this._effectiveTarget[this._property]>this.value;case t.IsLesser:return this._effectiveTarget[this._property]<this.value;case t.IsEqual:case t.IsDifferent:var e;return e=this.value.equals?this.value.equals(this._effectiveTarget[this._property]):this.value===this._effectiveTarget[this._property],this.operator===t.IsEqual?e:!e}return!1},t.prototype.serialize=function(){return this._serialize({name:"ValueCondition",properties:[ee._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:ee._SerializeValueAsString(this.value)},{name:"operator",value:t.GetOperatorName(this.operator)}]})},t.GetOperatorName=function(e){switch(e){case t._IsEqual:return"IsEqual";case t._IsDifferent:return"IsDifferent";case t._IsGreater:return"IsGreater";case t._IsLesser:return"IsLesser";default:return""}},t._IsEqual=0,t._IsDifferent=1,t._IsGreater=2,t._IsLesser=3,t}(ie),ne=function(e){function t(t,i){var r=e.call(this,t)||this;return r.predicate=i,r}return m(t,e),t.prototype.isValid=function(){return this.predicate()},t}(ie),oe=function(e){function t(t,i,r){var n=e.call(this,t)||this;return n.value=r,n._target=i,n}return m(t,e),t.prototype.isValid=function(){return this._target.state===this.value},t.prototype.serialize=function(){return this._serialize({name:"StateCondition",properties:[ee._GetTargetProperty(this._target),{name:"value",value:this.value}]})},t}(ie);a("BABYLON.ValueCondition",re),a("BABYLON.PredicateCondition",ne),a("BABYLON.StateCondition",oe);var ae=function(){function e(){}return e._CheckLimit=function(t,i){var r=e._LogLimitOutputs[t];return r?r.current++:(r={limit:i,current:1},e._LogLimitOutputs[t]=r),r.current<=r.limit},e._GenerateLimitMessage=function(t,i){var r;void 0===i&&(i=1);var n=e._LogLimitOutputs[t];if(n&&e.MessageLimitReached){var o=this._Levels[i];n.current===n.limit&&e[o.name](e.MessageLimitReached.replace(/%LIMIT%/g,""+n.limit).replace(/%TYPE%/g,null!==(r=o.name)&&void 0!==r?r:""))}},e._AddLogEntry=function(t){e._LogCache=t+e._LogCache,e.OnNewCacheEntry&&e.OnNewCacheEntry(t)},e._FormatMessage=function(e){var t=function(e){return e<10?"0"+e:""+e},i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e},e._LogDisabled=function(e,t){},e._LogEnabled=function(t,i,r){void 0===t&&(t=1);var n=Array.isArray(i)?i[0]:i;if(void 0===r||e._CheckLimit(n,r)){var o=e._FormatMessage(n),a=this._Levels[t],s=Array.isArray(i)?i.slice(1):[];a.logFunc&&a.logFunc.apply(a,T(["BJS - "+o],s,!1));var l="<div style='color:".concat(a.color,"'>").concat(o,"</div><br>");e._AddLogEntry(l),e._GenerateLimitMessage(n,t)}},Object.defineProperty(e,"LogCache",{get:function(){return e._LogCache},enumerable:!1,configurable:!0}),e.ClearLogCache=function(){e._LogCache="",e._LogLimitOutputs={},e.errorsCount=0},Object.defineProperty(e,"LogLevels",{set:function(t){var i=this;e.Log=e._LogDisabled,e.Warn=e._LogDisabled,e.Error=e._LogDisabled,[e.MessageLogLevel,e.WarningLogLevel,e.ErrorLogLevel].forEach((function(r){(t&r)===r&&(e[i._Levels[r].name]=e._LogEnabled.bind(e,r))}))},enumerable:!1,configurable:!0}),e.NoneLogLevel=0,e.MessageLogLevel=1,e.WarningLogLevel=2,e.ErrorLogLevel=4,e.AllLogLevel=7,e.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",e._LogCache="",e._LogLimitOutputs={},e._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],e.errorsCount=0,e.Log=e._LogEnabled.bind(e,e.MessageLogLevel),e.Warn=e._LogEnabled.bind(e,e.WarningLogLevel),e.Error=e._LogEnabled.bind(e,e.ErrorLogLevel),e}(),se=function(e){function t(t,i,r,n){var o=e.call(this,t,n)||this;return o.propertyPath=r,o._target=o._effectiveTarget=i,o}return m(t,e),t.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)},t.prototype.execute=function(){this._effectiveTarget[this._property]=!this._effectiveTarget[this._property]},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"SwitchBooleanAction",properties:[ee._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},t)},t}(ee),le=function(e){function t(t,i,r,n){var o=e.call(this,t,n)||this;return o.value=r,o._target=i,o}return m(t,e),t.prototype.execute=function(){this._target.state=this.value},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"SetStateAction",properties:[ee._GetTargetProperty(this._target),{name:"value",value:this.value}]},t)},t}(ee),ce=function(e){function t(t,i,r,n,o){var a=e.call(this,t,o)||this;return a.propertyPath=r,a.value=n,a._target=a._effectiveTarget=i,a}return m(t,e),t.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)},t.prototype.execute=function(){this._effectiveTarget[this._property]=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"SetValueAction",properties:[ee._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:ee._SerializeValueAsString(this.value)}]},t)},t}(ee),ue=function(e){function t(t,i,r,n,o){var a=e.call(this,t,o)||this;return a.propertyPath=r,a.value=n,a._target=a._effectiveTarget=i,a}return m(t,e),t.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath),"number"!=typeof this._effectiveTarget[this._property]&&ae.Warn("Warning: IncrementValueAction can only be used with number values")},t.prototype.execute=function(){this._effectiveTarget[this._property]+=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"IncrementValueAction",properties:[ee._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:ee._SerializeValueAsString(this.value)}]},t)},t}(ee),he=function(e){function t(t,i,r,n,o,a){var s=e.call(this,t,a)||this;return s.from=r,s.to=n,s.loop=o,s._target=i,s}return m(t,e),t.prototype._prepare=function(){},t.prototype.execute=function(){this._actionManager.getScene().beginAnimation(this._target,this.from,this.to,this.loop)},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"PlayAnimationAction",properties:[ee._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:ee._SerializeValueAsString(this.loop)||!1}]},t)},t}(ee),de=function(e){function t(t,i,r){var n=e.call(this,t,r)||this;return n._target=i,n}return m(t,e),t.prototype._prepare=function(){},t.prototype.execute=function(){this._actionManager.getScene().stopAnimation(this._target)},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"StopAnimationAction",properties:[ee._GetTargetProperty(this._target)]},t)},t}(ee),pe=function(e){function t(t,i){return void 0===t&&(t=u.ACTION_NothingTrigger),e.call(this,t,i)||this}return m(t,e),t.prototype.execute=function(){},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"DoNothingAction",properties:[]},t)},t}(ee),fe=function(e){function t(t,i,r,n){void 0===n&&(n=!0);var o=e.call(this,t,r)||this;return o.children=i,o.enableChildrenConditions=n,o}return m(t,e),t.prototype._prepare=function(){for(var e=0;e<this.children.length;e++)this.children[e]._actionManager=this._actionManager,this.children[e]._prepare()},t.prototype.execute=function(e){for(var t=0,i=this.children;t<i.length;t++){var r=i[t];this.enableChildrenConditions&&!r._evaluateConditionForCurrentFrame()||r.execute(e)}},t.prototype.serialize=function(t){for(var i=e.prototype._serialize.call(this,{name:"CombineAction",properties:[],combine:[]},t),r=0;r<this.children.length;r++)i.combine.push(this.children[r].serialize(null));return i},t}(ee),_e=function(e){function t(t,i,r){var n=e.call(this,t,r)||this;return n.func=i,n}return m(t,e),t.prototype.execute=function(e){this.func(e)},t}(ee),me=function(e){function t(t,i,r,n){var o=e.call(this,t,n)||this;return o._target=i,o._parent=r,o}return m(t,e),t.prototype._prepare=function(){},t.prototype.execute=function(){if(this._target.parent!==this._parent){var e=this._parent.getWorldMatrix().clone();e.invert(),this._target.position=V.TransformCoordinates(this._target.position,e),this._target.parent=this._parent}},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"SetParentAction",properties:[ee._GetTargetProperty(this._target),ee._GetTargetProperty(this._parent)]},t)},t}(ee);a("BABYLON.SetParentAction",me),a("BABYLON.ExecuteCodeAction",_e),a("BABYLON.DoNothingAction",pe),a("BABYLON.StopAnimationAction",de),a("BABYLON.PlayAnimationAction",he),a("BABYLON.IncrementValueAction",ue),a("BABYLON.SetValueAction",ce),a("BABYLON.SetStateAction",le),a("BABYLON.SetParentAction",me),a("BABYLON.SwitchBooleanAction",se),a("BABYLON.CombineAction",fe);var ge,ve=function(e,t,i){return e?e.getClassName&&"Mesh"===e.getClassName()?null:!e.getClassName||"SubMesh"!==e.getClassName()&&"PhysicsBody"!==e.getClassName()?e.clone?e.clone():Array.isArray(e)?e.slice():i&&"object"==typeof e?g({},e):null:e.clone(t):null},ye=function(){function e(){}return e.DeepCopy=function(e,t,i,r,n){void 0===n&&(n=!1);for(var o=function(e){var t=[];do{Object.getOwnPropertyNames(e).forEach((function(e){-1===t.indexOf(e)&&t.push(e)}))}while(e=Object.getPrototypeOf(e));return t}(e),a=0,s=o;a<s.length;a++){var l=s[a];if(("_"!==l[0]||r&&-1!==r.indexOf(l))&&!(l.endsWith("Observable")||i&&-1!==i.indexOf(l))){var c=e[l],u=typeof c;if("function"!==u)try{if("object"===u)if(c instanceof Uint8Array)t[l]=Uint8Array.from(c);else if(c instanceof Array){if(t[l]=[],c.length>0)if("object"==typeof c[0])for(var h=0;h<c.length;h++){var d=ve(c[h],t,n);-1===t[l].indexOf(d)&&t[l].push(d)}else t[l]=c.slice(0)}else t[l]=ve(c,t,n);else t[l]=c}catch(e){ae.Warn(e.message)}}}},e}(),be=function(e){function t(t){var i=e.call(this)||this;return(t=t||M.LastCreatedScene)?(i._scene=t,t.actionManagers.push(i),i):i}return m(t,e),t.prototype.dispose=function(){for(var e=this,i=this._scene.actionManagers.indexOf(this),r=0;r<this.actions.length;r++){var n=this.actions[r];t.Triggers[n.trigger]--,0===t.Triggers[n.trigger]&&delete t.Triggers[n.trigger]}this.actions.length=0,i>-1&&this._scene.actionManagers.splice(i,1);for(var o=0,a=this._scene.meshes.filter((function(t){return t.actionManager===e}));o<a.length;o++)a[o].actionManager=null},t.prototype.getScene=function(){return this._scene},t.prototype.hasSpecificTriggers=function(e){for(var t=0;t<this.actions.length;t++){var i=this.actions[t];if(e.indexOf(i.trigger)>-1)return!0}return!1},t.prototype.hasSpecificTriggers2=function(e,t){for(var i=0;i<this.actions.length;i++){var r=this.actions[i];if(e==r.trigger||t==r.trigger)return!0}return!1},t.prototype.hasSpecificTrigger=function(e,t){for(var i=0;i<this.actions.length;i++){var r=this.actions[i];if(r.trigger===e){if(!t)return!0;if(t(r.getTriggerParameter()))return!0}}return!1},Object.defineProperty(t.prototype,"hasPointerTriggers",{get:function(){for(var e=0;e<this.actions.length;e++){var i=this.actions[e];if(i.trigger>=t.OnPickTrigger&&i.trigger<=t.OnPointerOutTrigger)return!0}return!1},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hasPickTriggers",{get:function(){for(var e=0;e<this.actions.length;e++){var i=this.actions[e];if(i.trigger>=t.OnPickTrigger&&i.trigger<=t.OnPickUpTrigger)return!0}return!1},enumerable:!1,configurable:!0}),t.prototype.registerAction=function(e){return e.trigger===t.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(ae.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,t.Triggers[e.trigger]?t.Triggers[e.trigger]++:t.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)},t.prototype.unregisterAction=function(e){var i=this.actions.indexOf(e);return-1!==i&&(this.actions.splice(i,1),t.Triggers[e.trigger]-=1,0===t.Triggers[e.trigger]&&delete t.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0)},t.prototype.processTrigger=function(e,i){for(var r=0;r<this.actions.length;r++){var n=this.actions[r];if(n.trigger===e){if(i&&(e===t.OnKeyUpTrigger||e===t.OnKeyDownTrigger)){var o=n.getTriggerParameter();if("function"==typeof o){if(!o(i))continue}else if(o&&o!==i.sourceEvent.keyCode){if(!o.toLowerCase)continue;var a=o.toLowerCase();if(a!==i.sourceEvent.key){var s=i.sourceEvent.charCode?i.sourceEvent.charCode:i.sourceEvent.keyCode;if(String.fromCharCode(s).toLowerCase()!==a)continue}}}n._executeCurrent(i)}}},t.prototype._getEffectiveTarget=function(e,t){for(var i=t.split("."),r=0;r<i.length-1;r++)e=e[i[r]];return e},t.prototype._getProperty=function(e){var t=e.split(".");return t[t.length-1]},t.prototype.serialize=function(e){for(var i={children:new Array,name:e,type:3,properties:new Array},r=0;r<this.actions.length;r++){var n={type:0,children:new Array,name:t.GetTriggerName(this.actions[r].trigger),properties:new Array},o=this.actions[r].triggerOptions;if(o&&"number"!=typeof o)if(o.parameter instanceof Node)n.properties.push(ee._GetTargetProperty(o.parameter));else if("object"==typeof o.parameter){var a={};ye.DeepCopy(o.parameter,a,["mesh"]),o.parameter&&o.parameter.mesh&&(a._meshId=o.parameter.mesh.id),n.properties.push({name:"parameter",targetType:null,value:a})}else n.properties.push({name:"parameter",targetType:null,value:o.parameter});this.actions[r].serialize(n),i.children.push(n)}return i},t.Parse=function(e,i,r){var n=new t(r);null===i?r.actionManager=n:i.actionManager=n;for(var o=function(e,t,i,r){if(null===r){var n=parseFloat(t);return"true"===t||"false"===t?"true"===t:isNaN(n)?t:n}for(var o=r.split("."),a=t.split(","),s=0;s<o.length;s++)i=i[o[s]];if("boolean"==typeof i)return"true"===a[0];if("string"==typeof i)return a[0];var l=[];for(s=0;s<a.length;s++)l.push(parseFloat(a[s]));return i instanceof V?V.FromArray(l):i instanceof k?k.FromArray(l):i instanceof Z?Z.FromArray(l):i instanceof J?J.FromArray(l):parseFloat(a[0])},a=function(e,i,l,c,u){if(void 0===u&&(u=null),!e.detached){var h=[],d=null,p=null,f=e.combine&&e.combine.length>0;if(2===e.type?h.push(n):h.push(i),f){for(var _=[],m=0;m<e.combine.length;m++)a(e.combine[m],t.NothingTrigger,l,c,_);h.push(_)}else for(var g=0;g<e.properties.length;g++){var v=e.properties[g].value,y=e.properties[g].name,b=e.properties[g].targetType;"target"===y?v=d="SceneProperties"===b?r:"MaterialProperties"===b?r.getMaterialByName(v):r.getNodeByName(v):"parent"===y?v=r.getNodeByName(v):"sound"===y?r.getSoundByName&&(v=r.getSoundByName(v)):"propertyPath"!==y?v=2===e.type&&"operator"===y?re[v]:o(0,v,d,"value"===y?p:null):p=v,h.push(v)}if(null===u?h.push(l):h.push(null),"InterpolateValueAction"===e.name){var E=h[h.length-2];h[h.length-1]=E,h[h.length-2]=l}var S,x,A=(S=h,(x=s("BABYLON."+e.name))&&new(x.bind.apply(x,T([void 0],S,!1))));if(A instanceof ie&&null!==l){var C=new pe(i,l);c?c.then(C):n.registerAction(C),c=C}for(null===u?A instanceof ie?(l=A,A=c):(l=null,c?c.then(A):n.registerAction(A)):u.push(A),g=0;g<e.children.length;g++)a(e.children[g],i,l,A,null)}},l=0;l<e.children.length;l++){var c=void 0,u=e.children[l];if(u.properties.length>0){var h=u.properties[0].value,d=null===u.properties[0].targetType?h:r.getMeshByName(h);d._meshId&&(d.mesh=r.getMeshById(d._meshId)),c={trigger:t[u.name],parameter:d}}else c=t[u.name];for(var p=0;p<u.children.length;p++)u.detached||a(u.children[p],c,null,null)}},t.GetTriggerName=function(e){switch(e){case u.ACTION_NothingTrigger:return"NothingTrigger";case u.ACTION_OnPickTrigger:return"OnPickTrigger";case u.ACTION_OnLeftPickTrigger:return"OnLeftPickTrigger";case u.ACTION_OnRightPickTrigger:return"OnRightPickTrigger";case u.ACTION_OnCenterPickTrigger:return"OnCenterPickTrigger";case u.ACTION_OnPickDownTrigger:return"OnPickDownTrigger";case u.ACTION_OnDoublePickTrigger:return"OnDoublePickTrigger";case u.ACTION_OnPickUpTrigger:return"OnPickUpTrigger";case u.ACTION_OnLongPressTrigger:return"OnLongPressTrigger";case u.ACTION_OnPointerOverTrigger:return"OnPointerOverTrigger";case u.ACTION_OnPointerOutTrigger:return"OnPointerOutTrigger";case u.ACTION_OnEveryFrameTrigger:return"OnEveryFrameTrigger";case u.ACTION_OnIntersectionEnterTrigger:return"OnIntersectionEnterTrigger";case u.ACTION_OnIntersectionExitTrigger:return"OnIntersectionExitTrigger";case u.ACTION_OnKeyDownTrigger:return"OnKeyDownTrigger";case u.ACTION_OnKeyUpTrigger:return"OnKeyUpTrigger";case u.ACTION_OnPickOutTrigger:return"OnPickOutTrigger";default:return""}},t.NothingTrigger=u.ACTION_NothingTrigger,t.OnPickTrigger=u.ACTION_OnPickTrigger,t.OnLeftPickTrigger=u.ACTION_OnLeftPickTrigger,t.OnRightPickTrigger=u.ACTION_OnRightPickTrigger,t.OnCenterPickTrigger=u.ACTION_OnCenterPickTrigger,t.OnPickDownTrigger=u.ACTION_OnPickDownTrigger,t.OnDoublePickTrigger=u.ACTION_OnDoublePickTrigger,t.OnPickUpTrigger=u.ACTION_OnPickUpTrigger,t.OnPickOutTrigger=u.ACTION_OnPickOutTrigger,t.OnLongPressTrigger=u.ACTION_OnLongPressTrigger,t.OnPointerOverTrigger=u.ACTION_OnPointerOverTrigger,t.OnPointerOutTrigger=u.ACTION_OnPointerOutTrigger,t.OnEveryFrameTrigger=u.ACTION_OnEveryFrameTrigger,t.OnIntersectionEnterTrigger=u.ACTION_OnIntersectionEnterTrigger,t.OnIntersectionExitTrigger=u.ACTION_OnIntersectionExitTrigger,t.OnKeyDownTrigger=u.ACTION_OnKeyDownTrigger,t.OnKeyUpTrigger=u.ACTION_OnKeyUpTrigger,t}(h),Te=function(e){function t(t,i,r){var n=e.call(this,t,r)||this;return n._sound=i,n}return m(t,e),t.prototype._prepare=function(){},t.prototype.execute=function(){void 0!==this._sound&&this._sound.play()},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"PlaySoundAction",properties:[{name:"sound",value:this._sound.name}]},t)},t}(ee),Ee=function(e){function t(t,i,r){var n=e.call(this,t,r)||this;return n._sound=i,n}return m(t,e),t.prototype._prepare=function(){},t.prototype.execute=function(){void 0!==this._sound&&this._sound.stop()},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"StopSoundAction",properties:[{name:"sound",value:this._sound.name}]},t)},t}(ee);a("BABYLON.PlaySoundAction",Te),a("BABYLON.StopSoundAction",Ee),function(e){e[e.NONE=0]="NONE",e[e.STEP=1]="STEP"}(ge||(ge={}));var Se=function(){function e(e,t,i){this.name=e,this.from=t,this.to=i}return e.prototype.clone=function(){return new e(this.name,this.from,this.to)},e}(),xe={},Ae={};function Ce(e){var t=e.getClassName();if(xe[t])return xe[t];xe[t]={};for(var i=xe[t],r=e,n=t;n;){var o=Ae[n];for(var a in o)i[a]=o[a];var s=void 0,l=!1;do{if(!(s=Object.getPrototypeOf(r)).getClassName){l=!0;break}if(s.getClassName()!==n)break;r=s}while(s);if(l)break;n=s.getClassName(),r=s}return i}function Re(e,t){return function(i,r){var n=function(e){var t=e.getClassName();return Ae[t]||(Ae[t]={}),Ae[t]}(i);n[r]||(n[r]={type:e,sourceName:t})}}function Pe(e,t){return void 0===t&&(t=null),function(e,t){return void 0===t&&(t=null),function(i,r){var n=t||"_"+r;Object.defineProperty(i,r,{get:function(){return this[n]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[n]!==t&&(this[n]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function Ie(e){return Re(0,e)}function Me(e){return Re(1,e)}function Oe(e){return Re(2,e)}function De(e){return Re(3,e)}function Ne(e){return Re(4,e)}function Fe(e){return Re(5,e)}function Le(e){return Re(6,e)}function we(e){return Re(7,e)}function Be(e){return Re(8,e)}function Ue(e){return Re(9,e)}function Ve(e){return Re(10,e)}function ke(e){return Re(12,e)}function Ge(e){return Re(11,e)}function ze(e,t,i,r){var n=i.value;i.value=function(){for(var i=[],o=0;o<arguments.length;o++)i[o]=arguments[o];var a=n;if("undefined"!=typeof _native&&_native[t]){var s=_native[t];a=r?function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return r.apply(void 0,e)?s.apply(void 0,e):n.apply(void 0,e)}:s}return e[t]=a,a.apply(void 0,i)}}ze.filter=function(e){return function(t,i,r){return ze(t,i,r,e)}};var We={};function He(e,t){if(void 0===t&&(t=!1),!t||!We[e])return We[e]=!0,"".concat(e," needs to be imported before as it contains a side-effect required by your code.")}var Xe=function(){function e(){}return e.Eval=function(t,i){return"true"===(t=t.match(/\([^()]*\)/g)?t.replace(/\([^()]*\)/g,(function(t){return t=t.slice(1,t.length-1),e._HandleParenthesisContent(t,i)})):e._HandleParenthesisContent(t,i))||"false"!==t&&e.Eval(t,i)},e._HandleParenthesisContent=function(t,i){var r;i=i||function(e){return"true"===e};var n=t.split("||");for(var o in n)if(Object.prototype.hasOwnProperty.call(n,o)){var a=e._SimplifyNegation(n[o].trim()),s=a.split("&&");if(s.length>1)for(var l=0;l<s.length;++l){var c=e._SimplifyNegation(s[l].trim());if(!(r="true"!==c&&"false"!==c?"!"===c[0]?!i(c.substring(1)):i(c):"true"===c)){a="false";break}}if(r||"true"===a){r=!0;break}r="true"!==a&&"false"!==a?"!"===a[0]?!i(a.substring(1)):i(a):"true"===a}return r?"true":"false"},e._SimplifyNegation=function(e){return"!true"===(e=(e=e.replace(/^[\s!]+/,(function(e){return(e=e.replace(/[\s]/g,(function(){return""}))).length%2?"!":""}))).trim())?e="false":"!false"===e&&(e="true"),e},e}(),je=function(){function e(){}return e.EnableFor=function(t){t._tags=t._tags||{},t.hasTags=function(){return e.HasTags(t)},t.addTags=function(i){return e.AddTagsTo(t,i)},t.removeTags=function(i){return e.RemoveTagsFrom(t,i)},t.matchesTagsQuery=function(i){return e.MatchesQuery(t,i)}},e.DisableFor=function(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery},e.HasTags=function(e){if(!e._tags)return!1;var t=e._tags;for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i))return!0;return!1},e.GetTags=function(e,t){if(void 0===t&&(t=!0),!e._tags)return null;if(t){var i=[];for(var r in e._tags)Object.prototype.hasOwnProperty.call(e._tags,r)&&!0===e._tags[r]&&i.push(r);return i.join(" ")}return e._tags},e.AddTagsTo=function(t,i){i&&"string"==typeof i&&i.split(" ").forEach((function(i){e._AddTagTo(t,i)}))},e._AddTagTo=function(t,i){""!==(i=i.trim())&&"true"!==i&&"false"!==i&&(i.match(/[\s]/)||i.match(/^([!]|([|]|[&]){2})/)||(e.EnableFor(t),t._tags[i]=!0))},e.RemoveTagsFrom=function(t,i){if(e.HasTags(t)){var r=i.split(" ");for(var n in r)e._RemoveTagFrom(t,r[n])}},e._RemoveTagFrom=function(e,t){delete e._tags[t]},e.MatchesQuery=function(t,i){return void 0===i||(""===i?e.HasTags(t):Xe.Eval(i,(function(i){return e.HasTags(t)&&t._tags[i]})))},e}(),Ye=function(e,t,i,r){void 0===r&&(r={});var n=e();je&&je.HasTags(t)&&je.AddTagsTo(n,je.GetTags(t,!0));var o=Ce(n),a={};for(var s in o){var l=o[s],c=t[s],u=l.type;if(null!=c&&("uniqueId"!==s||Ke.AllowLoadingUniqueId))switch(u){case 0:case 6:case 11:n[s]=c;break;case 1:r.cloneTexturesOnlyOnce&&a[c.uniqueId]?n[s]=a[c.uniqueId]:(n[s]=i||c.isRenderTarget?c:c.clone(),a[c.uniqueId]=n[s]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:n[s]=i?c:c.clone()}}return n},Ke=function(){function e(){}return e.AppendSerializedAnimations=function(e,t){if(e.animations){t.animations=[];for(var i=0;i<e.animations.length;i++){var r=e.animations[i];t.animations.push(r.serialize())}}},e.Serialize=function(t,i){i||(i={}),je&&(i.tags=je.GetTags(t));var r=Ce(t);for(var n in r){var o=r[n],a=o.sourceName||n,s=o.type,l=t[n];if(null!=l&&("uniqueId"!==n||e.AllowLoadingUniqueId))switch(s){case 0:i[a]=l;break;case 1:case 3:case 7:case 9:i[a]=l.serialize();break;case 2:case 4:case 5:case 8:case 10:case 12:i[a]=l.asArray();break;case 6:case 11:i[a]=l.id}}return i},e.ParseProperties=function(t,i,r,n){n||(n="");var o=Ce(i);for(var a in o){var s=o[a],l=t[s.sourceName||a],c=s.type;if(null!=l&&("uniqueId"!==a||e.AllowLoadingUniqueId)){var u=i;switch(c){case 0:u[a]=l;break;case 1:r&&(u[a]=e._TextureParser(l,r,n));break;case 2:u[a]=Z.FromArray(l);break;case 3:u[a]=e._FresnelParametersParser(l);break;case 4:u[a]=U.FromArray(l);break;case 5:u[a]=V.FromArray(l);break;case 6:r&&(u[a]=r.getLastMeshById(l));break;case 7:u[a]=e._ColorCurvesParser(l);break;case 8:u[a]=J.FromArray(l);break;case 9:u[a]=e._ImageProcessingConfigurationParser(l);break;case 10:u[a]=G.FromArray(l);break;case 11:r&&(u[a]=r.getCameraById(l));break;case 12:u[a]=z.FromArray(l)}}}},e.Parse=function(t,i,r,n){void 0===n&&(n=null);var o=t();return je&&je.AddTagsTo(o,i.tags),e.ParseProperties(i,o,r,n),o},e.Clone=function(e,t,i){return void 0===i&&(i={}),Ye(e,t,!1,i)},e.Instanciate=function(e,t){return Ye(e,t,!0)},e.AllowLoadingUniqueId=!1,e._ImageProcessingConfigurationParser=function(e){throw He("ImageProcessingConfiguration")},e._FresnelParametersParser=function(e){throw He("FresnelParameters")},e._ColorCurvesParser=function(e){throw He("ColorCurves")},e._TextureParser=function(e,t,i){throw He("Texture")},e}(),Qe=function(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new f,this._onClonedObservable=new f},qe=function(){function e(e,t,i){void 0===t&&(t=null),void 0===i&&(i=!0),this._isDirty=!1,this._nodeDataStorage=new Qe,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new f,this._parentContainer=null,this.animations=[],this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=z.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new f,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||M.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache(),i&&this._addToSceneRootNodes()}return e.AddNodeConstructor=function(e,t){this._NodeConstructors[e]=t},e.Construct=function(e,t,i,r){var n=this._NodeConstructors[e];return n?n(t,i,r):null},Object.defineProperty(e.prototype,"accessibilityTag",{get:function(){return this._accessibilityTag},set:function(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"doNotSerialize",{get:function(){return!!this._nodeDataStorage._doNotSerialize||!!this._parentNode&&this._parentNode.doNotSerialize},set:function(e){this._nodeDataStorage._doNotSerialize=e},enumerable:!1,configurable:!0}),e.prototype.isDisposed=function(){return this._nodeDataStorage._isDisposed},Object.defineProperty(e.prototype,"parent",{get:function(){return this._parentNode},set:function(e){if(this._parentNode!==e){var t=this._parentNode;if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){var i=this._parentNode._children.indexOf(this);-1!==i&&this._parentNode._children.splice(i,1),e||this._nodeDataStorage._isDisposed||this._addToSceneRootNodes()}this._parentNode=e,this._isDirty=!0,this._parentNode&&(void 0!==this._parentNode._children&&null!==this._parentNode._children||(this._parentNode._children=new Array),this._parentNode._children.push(this),t||this._removeFromSceneRootNodes()),this._syncParentEnabledState()}},enumerable:!1,configurable:!0}),e.prototype._serializeAsParent=function(e){e.parentId=this.uniqueId},e.prototype._addToSceneRootNodes=function(){-1===this._nodeDataStorage._sceneRootNodesIndex&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))},e.prototype._removeFromSceneRootNodes=function(){if(-1!==this._nodeDataStorage._sceneRootNodesIndex){var e=this._scene.rootNodes,t=e.length-1;e[this._nodeDataStorage._sceneRootNodesIndex]=e[t],e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}},Object.defineProperty(e.prototype,"animationPropertiesOverride",{get:function(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride},set:function(e){this._animationPropertiesOverride=e},enumerable:!1,configurable:!0}),e.prototype.getClassName=function(){return"Node"},Object.defineProperty(e.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onEnabledStateChangedObservable",{get:function(){return this._nodeDataStorage._onEnabledStateChangedObservable},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onClonedObservable",{get:function(){return this._nodeDataStorage._onClonedObservable},enumerable:!1,configurable:!0}),e.prototype.getScene=function(){return this._scene},e.prototype.getEngine=function(){return this._scene.getEngine()},e.prototype.addBehavior=function(e,t){var i=this;return void 0===t&&(t=!1),-1!==this._behaviors.indexOf(e)||(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce((function(){e.attach(i)})):e.attach(this),this._behaviors.push(e)),this},e.prototype.removeBehavior=function(e){var t=this._behaviors.indexOf(e);return-1===t||(this._behaviors[t].detach(),this._behaviors.splice(t,1)),this},Object.defineProperty(e.prototype,"behaviors",{get:function(){return this._behaviors},enumerable:!1,configurable:!0}),e.prototype.getBehaviorByName=function(e){for(var t=0,i=this._behaviors;t<i.length;t++){var r=i[t];if(r.name===e)return r}return null},e.prototype.getWorldMatrix=function(){return this._currentRenderId!==this._scene.getRenderId()&&this.computeWorldMatrix(),this._worldMatrix},e.prototype._getWorldMatrixDeterminant=function(){return this._worldMatrixDeterminantIsDirty&&(this._worldMatrixDeterminantIsDirty=!1,this._worldMatrixDeterminant=this._worldMatrix.determinant()),this._worldMatrixDeterminant},Object.defineProperty(e.prototype,"worldMatrixFromCache",{get:function(){return this._worldMatrix},enumerable:!1,configurable:!0}),e.prototype._initCache=function(){this._cache={}},e.prototype.updateCache=function(e){!e&&this.isSynchronized()||this._updateCache()},e.prototype._getActionManagerForTrigger=function(e,t){return void 0===t&&(t=!0),this.parent?this.parent._getActionManagerForTrigger(e,!1):null},e.prototype._updateCache=function(e){},e.prototype._isSynchronized=function(){return!0},e.prototype._markSyncedWithParent=function(){this._parentNode&&(this._parentUpdateId=this._parentNode._childUpdateId)},e.prototype.isSynchronizedWithParent=function(){return!this._parentNode||!this._parentNode._isDirty&&this._parentUpdateId===this._parentNode._childUpdateId&&this._parentNode.isSynchronized()},e.prototype.isSynchronized=function(){return!(this._parentNode&&!this.isSynchronizedWithParent())&&this._isSynchronized()},e.prototype.isReady=function(e){return void 0===e&&(e=!1),this._nodeDataStorage._isReady},e.prototype.markAsDirty=function(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this},e.prototype.isEnabled=function(e){return void 0===e&&(e=!0),!1===e?this._nodeDataStorage._isEnabled:!!this._nodeDataStorage._isEnabled&&this._nodeDataStorage._isParentEnabled},e.prototype._syncParentEnabledState=function(){this._nodeDataStorage._isParentEnabled=!this._parentNode||this._parentNode.isEnabled(),this._children&&this._children.forEach((function(e){e._syncParentEnabledState()}))},e.prototype.setEnabled=function(e){this._nodeDataStorage._isEnabled!==e&&(this._nodeDataStorage._isEnabled=e,this._syncParentEnabledState(),this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e))},e.prototype.isDescendantOf=function(e){return!!this.parent&&(this.parent===e||this.parent.isDescendantOf(e))},e.prototype._getDescendants=function(e,t,i){if(void 0===t&&(t=!1),this._children)for(var r=0;r<this._children.length;r++){var n=this._children[r];i&&!i(n)||e.push(n),t||n._getDescendants(e,!1,i)}},e.prototype.getDescendants=function(e,t){var i=[];return this._getDescendants(i,e,t),i},e.prototype.getChildMeshes=function(e,t){var i=[];return this._getDescendants(i,e,(function(e){return(!t||t(e))&&void 0!==e.cullingStrategy})),i},e.prototype.getChildren=function(e,t){return void 0===t&&(t=!0),this.getDescendants(t,e)},e.prototype._setReady=function(e){e!==this._nodeDataStorage._isReady&&(e?(this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0):this._nodeDataStorage._isReady=!1)},e.prototype.getAnimationByName=function(e){for(var t=0;t<this.animations.length;t++){var i=this.animations[t];if(i.name===e)return i}return null},e.prototype.createAnimationRange=function(t,i,r){if(!this._ranges[t]){this._ranges[t]=e._AnimationRangeFactory(t,i,r);for(var n=0,o=this.animations.length;n<o;n++)this.animations[n]&&this.animations[n].createRange(t,i,r)}},e.prototype.deleteAnimationRange=function(e,t){void 0===t&&(t=!0);for(var i=0,r=this.animations.length;i<r;i++)this.animations[i]&&this.animations[i].deleteRange(e,t);this._ranges[e]=null},e.prototype.getAnimationRange=function(e){return this._ranges[e]||null},e.prototype.clone=function(t,i,r){var n=this,o=Ke.Clone((function(){return new e(t,n.getScene())}),this);if(i&&(o.parent=i),!r)for(var a=this.getDescendants(!0),s=0;s<a.length;s++){var l=a[s];l.clone(t+"."+l.name,o)}return o},e.prototype.getAnimationRanges=function(){var e,t=[];for(e in this._ranges)t.push(this._ranges[e]);return t},e.prototype.beginAnimation=function(e,t,i,r){var n=this.getAnimationRange(e);return n?this._scene.beginAnimation(this,n.from,n.to,t,i,r):null},e.prototype.serializeAnimationRanges=function(){var e=[];for(var t in this._ranges){var i=this._ranges[t];if(i){var r={};r.name=t,r.from=i.from,r.to=i.to,e.push(r)}}return e},e.prototype.computeWorldMatrix=function(e){return this._worldMatrix||(this._worldMatrix=z.Identity()),this._worldMatrix},e.prototype.dispose=function(e,t){if(void 0===t&&(t=!1),this._nodeDataStorage._isDisposed=!0,!e)for(var i=0,r=this.getDescendants(!0);i<r.length;i++)r[i].dispose(e,t);this.parent?this.parent=null:this._removeFromSceneRootNodes(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onEnabledStateChangedObservable.clear(),this.onClonedObservable.clear();for(var n=0,o=this._behaviors;n<o.length;n++)o[n].detach();this._behaviors.length=0,this.metadata=null},e.ParseAnimationRanges=function(e,t,i){if(t.ranges)for(var r=0;r<t.ranges.length;r++){var n=t.ranges[r];e.createAnimationRange(n.name,n.from,n.to)}},e.prototype.getHierarchyBoundingVectors=function(e,t){var i,r;void 0===e&&(e=!0),void 0===t&&(t=null),this.getScene().incrementRenderId(),this.computeWorldMatrix(!0);var n=this;if(n.getBoundingInfo&&n.subMeshes){var o=n.getBoundingInfo();i=o.boundingBox.minimumWorld.clone(),r=o.boundingBox.maximumWorld.clone()}else i=new V(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new V(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);if(e)for(var a=0,s=this.getDescendants(!1);a<s.length;a++){var l=s[a];if(l.computeWorldMatrix(!0),(!t||t(l))&&l.getBoundingInfo&&0!==l.getTotalVertices()){var c=l.getBoundingInfo().boundingBox,u=c.minimumWorld,h=c.maximumWorld;V.CheckExtends(u,i,r),V.CheckExtends(h,i,r)}}return{min:i,max:r}},e._AnimationRangeFactory=function(e,t,i){throw He("AnimationRange")},e._NodeConstructors={},v([Ie()],e.prototype,"name",void 0),v([Ie()],e.prototype,"id",void 0),v([Ie()],e.prototype,"uniqueId",void 0),v([Ie()],e.prototype,"state",void 0),v([Ie()],e.prototype,"metadata",void 0),e}(),Ze=function(){function e(e,t){this.width=e,this.height=t}return e.prototype.toString=function(){return"{W: ".concat(this.width,", H: ").concat(this.height,"}")},e.prototype.getClassName=function(){return"Size"},e.prototype.getHashCode=function(){var e=0|this.width;return 397*e^this.height},e.prototype.copyFrom=function(e){this.width=e.width,this.height=e.height},e.prototype.copyFromFloats=function(e,t){return this.width=e,this.height=t,this},e.prototype.set=function(e,t){return this.copyFromFloats(e,t)},e.prototype.multiplyByFloats=function(t,i){return new e(this.width*t,this.height*i)},e.prototype.clone=function(){return new e(this.width,this.height)},e.prototype.equals=function(e){return!!e&&this.width===e.width&&this.height===e.height},Object.defineProperty(e.prototype,"surface",{get:function(){return this.width*this.height},enumerable:!1,configurable:!0}),e.Zero=function(){return new e(0,0)},e.prototype.add=function(t){return new e(this.width+t.width,this.height+t.height)},e.prototype.subtract=function(t){return new e(this.width-t.width,this.height-t.height)},e.prototype.scale=function(t){return new e(this.width*t,this.height*t)},e.Lerp=function(t,i,r){return new e(t.width+(i.width-t.width)*r,t.height+(i.height-t.height)*r)},e}(),Je=function(){function e(){this._xhr="undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest,this._requestURL=""}return Object.defineProperty(e,"IsCustomRequestAvailable",{get:function(){return Object.keys(e.CustomRequestHeaders).length>0||e.CustomRequestModifiers.length>0},enumerable:!1,configurable:!0}),e.prototype._injectCustomRequestHeaders=function(){if(!this._shouldSkipRequestModifications(this._requestURL))for(var t in e.CustomRequestHeaders){var i=e.CustomRequestHeaders[t];i&&this._xhr.setRequestHeader(t,i)}},e.prototype._shouldSkipRequestModifications=function(t){return e.SkipRequestModificationForBabylonCDN&&(t.includes("preview.babylonjs.com")||t.includes("cdn.babylonjs.com"))},Object.defineProperty(e.prototype,"onprogress",{get:function(){return this._xhr.onprogress},set:function(e){this._xhr.onprogress=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"readyState",{get:function(){return this._xhr.readyState},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"status",{get:function(){return this._xhr.status},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"statusText",{get:function(){return this._xhr.statusText},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"response",{get:function(){return this._xhr.response},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"responseURL",{get:function(){return this._xhr.responseURL},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"responseText",{get:function(){return this._xhr.responseText},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"responseType",{get:function(){return this._xhr.responseType},set:function(e){this._xhr.responseType=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"timeout",{get:function(){return this._xhr.timeout},set:function(e){this._xhr.timeout=e},enumerable:!1,configurable:!0}),e.prototype.addEventListener=function(e,t,i){this._xhr.addEventListener(e,t,i)},e.prototype.removeEventListener=function(e,t,i){this._xhr.removeEventListener(e,t,i)},e.prototype.abort=function(){this._xhr.abort()},e.prototype.send=function(t){e.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(t)},e.prototype.open=function(t,i){for(var r=0,n=e.CustomRequestModifiers;r<n.length;r++){var o=n[r];if(this._shouldSkipRequestModifications(i))return;o(this._xhr,i)}i=(i=i.replace("file:http:","http:")).replace("file:https:","https:"),this._requestURL=i,this._xhr.open(t,i,!0)},e.prototype.setRequestHeader=function(e,t){this._xhr.setRequestHeader(e,t)},e.prototype.getResponseHeader=function(e){return this._xhr.getResponseHeader(e)},e.CustomRequestHeaders={},e.CustomRequestModifiers=new Array,e.SkipRequestModificationForBabylonCDN=!0,e}(),$e=Object.freeze(new G(0,0,0,0)),et=Object.freeze(V.Zero()),tt=Object.freeze(U.Zero()),it=Object.freeze(Ze.Zero()),rt=Object.freeze(Z.Black()),nt=Object.freeze(new J(0,0,0,0)),ot={key:0,repeatCount:0,loopMode:2},at=function(){function e(t,i,r,n,o,a){this.name=t,this.targetProperty=i,this.framePerSecond=r,this.dataType=n,this.loopMode=o,this.enableBlending=a,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=i.split("."),this.dataType=n,this.loopMode=void 0===o?e.ANIMATIONLOOPMODE_CYCLE:o,this.uniqueId=e._UniqueIdGenerator++}return e._PrepareAnimation=function(t,i,r,n,o,a,s,l){var c=void 0;if(!isNaN(parseFloat(o))&&isFinite(o)?c=e.ANIMATIONTYPE_FLOAT:o instanceof G?c=e.ANIMATIONTYPE_QUATERNION:o instanceof V?c=e.ANIMATIONTYPE_VECTOR3:o instanceof U?c=e.ANIMATIONTYPE_VECTOR2:o instanceof Z?c=e.ANIMATIONTYPE_COLOR3:o instanceof J?c=e.ANIMATIONTYPE_COLOR4:o instanceof Ze&&(c=e.ANIMATIONTYPE_SIZE),null==c)return null;var u=new e(t,i,r,c,s),h=[{frame:0,value:o},{frame:n,value:a}];return u.setKeys(h),void 0!==l&&u.setEasingFunction(l),u},e.CreateAnimation=function(t,i,r,n){var o=new e(t+"Animation",t,r,i,e.ANIMATIONLOOPMODE_CONSTANT);return o.setEasingFunction(n),o},e.CreateAndStartAnimation=function(t,i,r,n,o,a,s,l,c,u,h){var d=e._PrepareAnimation(t,r,n,o,a,s,l,c);return d?(i.getScene&&(h=i.getScene()),h?h.beginDirectAnimation(i,[d],0,o,1===d.loopMode,1,u):null):null},e.CreateAndStartHierarchyAnimation=function(t,i,r,n,o,a,s,l,c,u,h){var d=e._PrepareAnimation(t,n,o,a,s,l,c,u);return d?i.getScene().beginDirectHierarchyAnimation(i,r,[d],0,a,1===d.loopMode,1,h):null},e.CreateMergeAndStartAnimation=function(t,i,r,n,o,a,s,l,c,u){var h=e._PrepareAnimation(t,r,n,o,a,s,l,c);return h?(i.animations.push(h),i.getScene().beginAnimation(i,0,o,1===h.loopMode,1,u)):null},e.MakeAnimationAdditive=function(t,i,r,n,o){var a,s,l;void 0===n&&(n=!1);var c=t;if((l="object"==typeof i?i:{referenceFrame:null!=i?i:0,range:r,cloneOriginalAnimation:n,clonedAnimationName:o}).cloneOriginalAnimation&&((c=t.clone()).name=l.clonedAnimationName||c.name),!c._keys.length)return c;var u=l.referenceFrame&&l.referenceFrame>=0?l.referenceFrame:0,h=0,d=c._keys[0],p=c._keys.length-1,f=c._keys[p],_={referenceValue:d.value,referencePosition:H.Vector3[0],referenceQuaternion:H.Quaternion[0],referenceScaling:H.Vector3[1],keyPosition:H.Vector3[2],keyQuaternion:H.Quaternion[1],keyScaling:H.Vector3[3]},m=d.frame,g=f.frame;if(l.range){var v=c.getRange(l.range);v&&(m=v.from,g=v.to)}else m=null!==(a=l.fromFrame)&&void 0!==a?a:m,g=null!==(s=l.toFrame)&&void 0!==s?s:g;if(m!==d.frame&&(h=c.createKeyForFrame(m)),g!==f.frame&&(p=c.createKeyForFrame(g)),1===c._keys.length){var y=c._getKeyValue(c._keys[0]);_.referenceValue=y.clone?y.clone():y}else u<=d.frame?(y=c._getKeyValue(d.value),_.referenceValue=y.clone?y.clone():y):u>=f.frame?(y=c._getKeyValue(f.value),_.referenceValue=y.clone?y.clone():y):(ot.key=0,y=c._interpolate(u,ot),_.referenceValue=y.clone?y.clone():y);c.dataType===e.ANIMATIONTYPE_QUATERNION?_.referenceValue.normalize().conjugateInPlace():c.dataType===e.ANIMATIONTYPE_MATRIX&&(_.referenceValue.decompose(_.referenceScaling,_.referenceQuaternion,_.referencePosition),_.referenceQuaternion.normalize().conjugateInPlace());for(var b=Number.MAX_VALUE,T=l.clipKeys?[]:null,E=h;E<=p;E++){var S=c._keys[E];if(T&&(S={frame:S.frame,value:S.value.clone?S.value.clone():S.value,inTangent:S.inTangent,outTangent:S.outTangent,interpolation:S.interpolation,lockedTangent:S.lockedTangent},b===Number.MAX_VALUE&&(b=S.frame),S.frame-=b,T.push(S)),!E||c.dataType===e.ANIMATIONTYPE_FLOAT||S.value!==d.value)switch(c.dataType){case e.ANIMATIONTYPE_MATRIX:S.value.decompose(_.keyScaling,_.keyQuaternion,_.keyPosition),_.keyPosition.subtractInPlace(_.referencePosition),_.keyScaling.divideInPlace(_.referenceScaling),_.referenceQuaternion.multiplyToRef(_.keyQuaternion,_.keyQuaternion),z.ComposeToRef(_.keyScaling,_.keyQuaternion,_.keyPosition,S.value);break;case e.ANIMATIONTYPE_QUATERNION:_.referenceValue.multiplyToRef(S.value,S.value);break;case e.ANIMATIONTYPE_VECTOR2:case e.ANIMATIONTYPE_VECTOR3:case e.ANIMATIONTYPE_COLOR3:case e.ANIMATIONTYPE_COLOR4:S.value.subtractToRef(_.referenceValue,S.value);break;case e.ANIMATIONTYPE_SIZE:S.value.width-=_.referenceValue.width,S.value.height-=_.referenceValue.height;break;default:S.value-=_.referenceValue}}return T&&c.setKeys(T,!0),c},e.TransitionTo=function(e,t,i,r,n,o,a,s){if(void 0===s&&(s=null),a<=0)return i[e]=t,s&&s(),null;var l=n*(a/1e3);o.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(o);var c=r.beginAnimation(i,0,l,!1);return c.onAnimationEnd=s,c},Object.defineProperty(e.prototype,"runtimeAnimations",{get:function(){return this._runtimeAnimations},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hasRunningRuntimeAnimations",{get:function(){for(var e=0,t=this._runtimeAnimations;e<t.length;e++)if(!t[e].isStopped())return!0;return!1},enumerable:!1,configurable:!0}),e.prototype.toString=function(e){var t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";var i=!0;for(var r in this._ranges)i&&(t+=", ",i=!1),t+=r;t+="}"}return t},e.prototype.addEvent=function(e){this._events.push(e),this._events.sort((function(e,t){return e.frame-t.frame}))},e.prototype.removeEvents=function(e){for(var t=0;t<this._events.length;t++)this._events[t].frame===e&&(this._events.splice(t,1),t--)},e.prototype.getEvents=function(){return this._events},e.prototype.createRange=function(e,t,i){this._ranges[e]||(this._ranges[e]=new Se(e,t,i))},e.prototype.deleteRange=function(e,t){void 0===t&&(t=!0);var i=this._ranges[e];if(i){if(t)for(var r=i.from,n=i.to,o=this._keys.length-1;o>=0;o--)this._keys[o].frame>=r&&this._keys[o].frame<=n&&this._keys.splice(o,1);this._ranges[e]=null}},e.prototype.getRange=function(e){return this._ranges[e]},e.prototype.getKeys=function(){return this._keys},e.prototype.getHighestFrame=function(){for(var e=0,t=0,i=this._keys.length;t<i;t++)e<this._keys[t].frame&&(e=this._keys[t].frame);return e},e.prototype.getEasingFunction=function(){return this._easingFunction},e.prototype.setEasingFunction=function(e){this._easingFunction=e},e.prototype.floatInterpolateFunction=function(e,t,i){return j.Lerp(e,t,i)},e.prototype.floatInterpolateFunctionWithTangents=function(e,t,i,r,n){return j.Hermite(e,t,i,r,n)},e.prototype.quaternionInterpolateFunction=function(e,t,i){return G.Slerp(e,t,i)},e.prototype.quaternionInterpolateFunctionWithTangents=function(e,t,i,r,n){return G.Hermite(e,t,i,r,n).normalize()},e.prototype.vector3InterpolateFunction=function(e,t,i){return V.Lerp(e,t,i)},e.prototype.vector3InterpolateFunctionWithTangents=function(e,t,i,r,n){return V.Hermite(e,t,i,r,n)},e.prototype.vector2InterpolateFunction=function(e,t,i){return U.Lerp(e,t,i)},e.prototype.vector2InterpolateFunctionWithTangents=function(e,t,i,r,n){return U.Hermite(e,t,i,r,n)},e.prototype.sizeInterpolateFunction=function(e,t,i){return Ze.Lerp(e,t,i)},e.prototype.color3InterpolateFunction=function(e,t,i){return Z.Lerp(e,t,i)},e.prototype.color3InterpolateFunctionWithTangents=function(e,t,i,r,n){return Z.Hermite(e,t,i,r,n)},e.prototype.color4InterpolateFunction=function(e,t,i){return J.Lerp(e,t,i)},e.prototype.color4InterpolateFunctionWithTangents=function(e,t,i,r,n){return J.Hermite(e,t,i,r,n)},e.prototype._getKeyValue=function(e){return"function"==typeof e?e():e},e.prototype.evaluate=function(e){return ot.key=0,this._interpolate(e,ot)},e.prototype._interpolate=function(t,i,r){var n;if(void 0===r&&(r=!1),i.loopMode===e.ANIMATIONLOOPMODE_CONSTANT&&i.repeatCount>0)return i.highLimitValue.clone?i.highLimitValue.clone():i.highLimitValue;for(var o=this._keys,a=o.length,s=i.key;s>=0&&t<o[s].frame;)--s;for(;s+1<=a-1&&t>=o[s+1].frame;)++s;if(i.key=s,s<0)return r?void 0:this._getKeyValue(o[0].value);if(s+1>a-1)return r?void 0:this._getKeyValue(o[a-1].value);var l=o[s],c=o[s+1];if(!r||t!==l.frame&&t!==c.frame){var u=this._getKeyValue(l.value),h=this._getKeyValue(c.value);if(l.interpolation===ge.STEP)return c.frame>t?u:h;var d=void 0!==l.outTangent&&void 0!==c.inTangent,p=c.frame-l.frame,f=(t-l.frame)/p,_=l.easingFunction||this.getEasingFunction();switch(null!==_&&(f=_.ease(f)),this.dataType){case e.ANIMATIONTYPE_FLOAT:var m=d?this.floatInterpolateFunctionWithTangents(u,l.outTangent*p,h,c.inTangent*p,f):this.floatInterpolateFunction(u,h,f);switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:case e.ANIMATIONLOOPMODE_YOYO:return m;case e.ANIMATIONLOOPMODE_RELATIVE:case e.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(null!==(n=i.offsetValue)&&void 0!==n?n:0)*i.repeatCount+m}break;case e.ANIMATIONTYPE_QUATERNION:var g=d?this.quaternionInterpolateFunctionWithTangents(u,l.outTangent.scale(p),h,c.inTangent.scale(p),f):this.quaternionInterpolateFunction(u,h,f);switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:case e.ANIMATIONLOOPMODE_YOYO:return g;case e.ANIMATIONLOOPMODE_RELATIVE:case e.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return g.addInPlace((i.offsetValue||$e).scale(i.repeatCount))}return g;case e.ANIMATIONTYPE_VECTOR3:var v=d?this.vector3InterpolateFunctionWithTangents(u,l.outTangent.scale(p),h,c.inTangent.scale(p),f):this.vector3InterpolateFunction(u,h,f);switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:case e.ANIMATIONLOOPMODE_YOYO:return v;case e.ANIMATIONLOOPMODE_RELATIVE:case e.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return v.add((i.offsetValue||et).scale(i.repeatCount))}break;case e.ANIMATIONTYPE_VECTOR2:var y=d?this.vector2InterpolateFunctionWithTangents(u,l.outTangent.scale(p),h,c.inTangent.scale(p),f):this.vector2InterpolateFunction(u,h,f);switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:case e.ANIMATIONLOOPMODE_YOYO:return y;case e.ANIMATIONLOOPMODE_RELATIVE:case e.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return y.add((i.offsetValue||tt).scale(i.repeatCount))}break;case e.ANIMATIONTYPE_SIZE:switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:case e.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(u,h,f);case e.ANIMATIONLOOPMODE_RELATIVE:case e.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(u,h,f).add((i.offsetValue||it).scale(i.repeatCount))}break;case e.ANIMATIONTYPE_COLOR3:var b=d?this.color3InterpolateFunctionWithTangents(u,l.outTangent.scale(p),h,c.inTangent.scale(p),f):this.color3InterpolateFunction(u,h,f);switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:case e.ANIMATIONLOOPMODE_YOYO:return b;case e.ANIMATIONLOOPMODE_RELATIVE:case e.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return b.add((i.offsetValue||rt).scale(i.repeatCount))}break;case e.ANIMATIONTYPE_COLOR4:var T=d?this.color4InterpolateFunctionWithTangents(u,l.outTangent.scale(p),h,c.inTangent.scale(p),f):this.color4InterpolateFunction(u,h,f);switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:case e.ANIMATIONLOOPMODE_YOYO:return T;case e.ANIMATIONLOOPMODE_RELATIVE:case e.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return T.add((i.offsetValue||nt).scale(i.repeatCount))}break;case e.ANIMATIONTYPE_MATRIX:switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:case e.ANIMATIONLOOPMODE_YOYO:return e.AllowMatricesInterpolation?this.matrixInterpolateFunction(u,h,f,i.workValue):u;case e.ANIMATIONLOOPMODE_RELATIVE:case e.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return u}}return 0}},e.prototype.matrixInterpolateFunction=function(t,i,r,n){return e.AllowMatrixDecomposeForInterpolation?n?(z.DecomposeLerpToRef(t,i,r,n),n):z.DecomposeLerp(t,i,r):n?(z.LerpToRef(t,i,r,n),n):z.Lerp(t,i,r)},e.prototype.clone=function(){var t=new e(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(t.enableBlending=this.enableBlending,t.blendingSpeed=this.blendingSpeed,this._keys&&t.setKeys(this._keys),this._ranges)for(var i in t._ranges={},this._ranges){var r=this._ranges[i];r&&(t._ranges[i]=r.clone())}return t},e.prototype.setKeys=function(e,t){void 0===t&&(t=!1),this._keys=t?e:e.slice(0)},e.prototype.createKeyForFrame=function(e){ot.key=0;var t=this._interpolate(e,ot,!0);if(!t)return this._keys[ot.key].frame===e?ot.key:ot.key+1;var i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(ot.key+1,0,i),ot.key+1},e.prototype.serialize=function(){var t={};t.name=this.name,t.property=this.targetProperty,t.framePerSecond=this.framePerSecond,t.dataType=this.dataType,t.loopBehavior=this.loopMode,t.enableBlending=this.enableBlending,t.blendingSpeed=this.blendingSpeed;var i=this.dataType;t.keys=[];for(var r=this.getKeys(),n=0;n<r.length;n++){var o=r[n],a={};switch(a.frame=o.frame,i){case e.ANIMATIONTYPE_FLOAT:a.values=[o.value],void 0!==o.inTangent&&a.values.push(o.inTangent),void 0!==o.outTangent&&(void 0===o.inTangent&&a.values.push(void 0),a.values.push(o.outTangent)),void 0!==o.interpolation&&(void 0===o.inTangent&&a.values.push(void 0),void 0===o.outTangent&&a.values.push(void 0),a.values.push(o.interpolation));break;case e.ANIMATIONTYPE_QUATERNION:case e.ANIMATIONTYPE_MATRIX:case e.ANIMATIONTYPE_VECTOR3:case e.ANIMATIONTYPE_COLOR3:case e.ANIMATIONTYPE_COLOR4:a.values=o.value.asArray(),null!=o.inTangent&&a.values.push(o.inTangent.asArray()),null!=o.outTangent&&(void 0===o.inTangent&&a.values.push(void 0),a.values.push(o.outTangent.asArray())),void 0!==o.interpolation&&(void 0===o.inTangent&&a.values.push(void 0),void 0===o.outTangent&&a.values.push(void 0),a.values.push(o.interpolation))}t.keys.push(a)}for(var s in t.ranges=[],this._ranges){var l=this._ranges[s];if(l){var c={};c.name=s,c.from=l.from,c.to=l.to,t.ranges.push(c)}}return t},e._UniversalLerp=function(e,t,i){var r=e.constructor;return r.Lerp?r.Lerp(e,t,i):r.Slerp?r.Slerp(e,t,i):e.toFixed?e*(1-i)+i*t:t},e.Parse=function(t){var i,r,n=new e(t.name,t.property,t.framePerSecond,t.dataType,t.loopBehavior),o=t.dataType,a=[];for(t.enableBlending&&(n.enableBlending=t.enableBlending),t.blendingSpeed&&(n.blendingSpeed=t.blendingSpeed),r=0;r<t.keys.length;r++){var s=t.keys[r],l=void 0,c=void 0,u=void 0;switch(o){case e.ANIMATIONTYPE_FLOAT:i=s.values[0],s.values.length>=2&&(l=s.values[1]),s.values.length>=3&&(c=s.values[2]),s.values.length>=4&&(u=s.values[3]);break;case e.ANIMATIONTYPE_QUATERNION:if(i=G.FromArray(s.values),s.values.length>=8){var h=G.FromArray(s.values.slice(4,8));h.equals(G.Zero())||(l=h)}if(s.values.length>=12){var d=G.FromArray(s.values.slice(8,12));d.equals(G.Zero())||(c=d)}s.values.length>=13&&(u=s.values[12]);break;case e.ANIMATIONTYPE_MATRIX:i=z.FromArray(s.values),s.values.length>=17&&(u=s.values[16]);break;case e.ANIMATIONTYPE_COLOR3:i=Z.FromArray(s.values),s.values[3]&&(l=Z.FromArray(s.values[3])),s.values[4]&&(c=Z.FromArray(s.values[4])),s.values[5]&&(u=s.values[5]);break;case e.ANIMATIONTYPE_COLOR4:i=J.FromArray(s.values),s.values[4]&&(l=J.FromArray(s.values[4])),s.values[5]&&(c=J.FromArray(s.values[5])),s.values[6]&&(u=J.FromArray(s.values[6]));break;case e.ANIMATIONTYPE_VECTOR3:default:i=V.FromArray(s.values),s.values[3]&&(l=V.FromArray(s.values[3])),s.values[4]&&(c=V.FromArray(s.values[4])),s.values[5]&&(u=s.values[5])}var p={};p.frame=s.frame,p.value=i,null!=l&&(p.inTangent=l),null!=c&&(p.outTangent=c),null!=u&&(p.interpolation=u),a.push(p)}if(n.setKeys(a),t.ranges)for(r=0;r<t.ranges.length;r++)i=t.ranges[r],n.createRange(i.name,i.from,i.to);return n},e.AppendSerializedAnimations=function(e,t){Ke.AppendSerializedAnimations(e,t)},e.ParseFromFileAsync=function(e,t){var i=this;return new Promise((function(r,n){var o=new Je;o.addEventListener("readystatechange",(function(){if(4==o.readyState)if(200==o.status){var t=JSON.parse(o.responseText);if(t.animations&&(t=t.animations),t.length){for(var a=[],s=0,l=t;s<l.length;s++){var c=l[s];a.push(i.Parse(c))}r(a)}else a=i.Parse(t),e&&(a.name=e),r(a)}else n("Unable to load the animation")})),o.open("GET",t),o.send()}))},e.ParseFromSnippetAsync=function(e){var t=this;return new Promise((function(i,r){var n=new Je;n.addEventListener("readystatechange",(function(){if(4==n.readyState)if(200==n.status){var o=JSON.parse(JSON.parse(n.responseText).jsonPayload);if(o.animations){for(var a=[],s=0,l=(h=JSON.parse(o.animations)).animations;s<l.length;s++){var c=l[s];(u=t.Parse(c)).snippetId=e,a.push(u)}i(a)}else{var u,h=JSON.parse(o.animation);(u=t.Parse(h)).snippetId=e,i(u)}}else r("Unable to load the snippet "+e)})),n.open("GET",t.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))},e._UniqueIdGenerator=0,e.AllowMatricesInterpolation=!1,e.AllowMatrixDecomposeForInterpolation=!0,e.SnippetUrl=u.SnippetUrl,e.ANIMATIONTYPE_FLOAT=0,e.ANIMATIONTYPE_VECTOR3=1,e.ANIMATIONTYPE_QUATERNION=2,e.ANIMATIONTYPE_MATRIX=3,e.ANIMATIONTYPE_COLOR3=4,e.ANIMATIONTYPE_COLOR4=7,e.ANIMATIONTYPE_VECTOR2=5,e.ANIMATIONTYPE_SIZE=6,e.ANIMATIONLOOPMODE_RELATIVE=0,e.ANIMATIONLOOPMODE_CYCLE=1,e.ANIMATIONLOOPMODE_CONSTANT=2,e.ANIMATIONLOOPMODE_YOYO=4,e.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5,e.CreateFromSnippetAsync=e.ParseFromSnippetAsync,e}();a("BABYLON.Animation",at),qe._AnimationRangeFactory=function(e,t,i){return new Se(e,t,i)};var st=function(e){function t(t,i,r,n,o,a,s,l){void 0===o&&(o=1e3);var c=e.call(this,t,a)||this;return c.duration=1e3,c.onInterpolationDoneObservable=new f,c.propertyPath=r,c.value=n,c.duration=o,c.stopOtherAnimations=s,c.onInterpolationDone=l,c._target=c._effectiveTarget=i,c}return m(t,e),t.prototype._prepare=function(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)},t.prototype.execute=function(){var e,t=this,i=this._actionManager.getScene(),r=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];if("number"==typeof this.value)e=at.ANIMATIONTYPE_FLOAT;else if(this.value instanceof Z)e=at.ANIMATIONTYPE_COLOR3;else if(this.value instanceof V)e=at.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof z)e=at.ANIMATIONTYPE_MATRIX;else{if(!(this.value instanceof G))return void ae.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");e=at.ANIMATIONTYPE_QUATERNION}var n=new at("InterpolateValueAction",this._property,1e3/this.duration*100,e,at.ANIMATIONLOOPMODE_CONSTANT);n.setKeys(r),this.stopOtherAnimations&&i.stopAnimation(this._effectiveTarget),i.beginDirectAnimation(this._effectiveTarget,[n],0,100,!1,1,(function(){t.onInterpolationDoneObservable.notifyObservers(t),t.onInterpolationDone&&t.onInterpolationDone()}))},t.prototype.serialize=function(t){return e.prototype._serialize.call(this,{name:"InterpolateValueAction",properties:[ee._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:ee._SerializeValueAsString(this.value)},{name:"duration",value:ee._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:ee._SerializeValueAsString(this.stopOtherAnimations)||!1}]},t)},t}(ee);a("BABYLON.InterpolateValueAction",st);var lt=function(){function e(e,t,i,r){var n=this;if(this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._absoluteFrameOffset=0,this._previousElapsedTime=0,this._yoyoDirection=1,this._previousAbsoluteFrame=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=r,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===at.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=z.Zero()),this._keys=this._animation.getKeys(),this._minFrame=this._keys[0].frame,this._maxFrame=this._keys[this._keys.length-1].frame,this._minValue=this._keys[0].value,this._maxValue=this._keys[this._keys.length-1].value,0!==this._minFrame){var o={frame:0,value:this._minValue};this._keys.splice(0,0,o)}if(this._target instanceof Array){for(var a=0,s=0,l=this._target;s<l.length;s++){var c=l[s];this._preparePath(c,a),this._getOriginalValues(a),a++}this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];var u=t.getEvents();u&&u.length>0&&u.forEach((function(e){n._events.push(e._clone())})),this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}return Object.defineProperty(e.prototype,"currentFrame",{get:function(){return this._currentFrame},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"weight",{get:function(){return this._weight},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentValue",{get:function(){return this._currentValue},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"targetPath",{get:function(){return this._targetPath},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"target",{get:function(){return this._currentActiveTarget},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isAdditive",{get:function(){return this._host&&this._host.isAdditive},enumerable:!1,configurable:!0}),e.prototype._preparePath=function(e,t){void 0===t&&(t=0);var i=this._animation.targetPropertyPath;if(i.length>1){for(var r=e,n=0;n<i.length-1;n++){var o=i[n];if(void 0===(r=r[o]))throw new Error("Invalid property (".concat(o,") in property path (").concat(i.join("."),")"))}this._targetPath=i[i.length-1],this._activeTargets[t]=r}else this._targetPath=i[0],this._activeTargets[t]=e;if(void 0===this._activeTargets[t][this._targetPath])throw new Error("Invalid property (".concat(this._targetPath,") in property path (").concat(i.join("."),")"))},Object.defineProperty(e.prototype,"animation",{get:function(){return this._animation},enumerable:!1,configurable:!0}),e.prototype.reset=function(e){if(void 0===e&&(e=!1),e)if(this._target instanceof Array)for(var t=0,i=0,r=this._target;i<r.length;i++){var n=r[i];void 0!==this._originalValue[t]&&this._setValue(n,this._activeTargets[t],this._originalValue[t],-1,t),t++}else void 0!==this._originalValue[0]&&this._setValue(this._target,this._directTarget,this._originalValue[0],-1,0);for(this._offsetsCache={},this._highLimitsCache={},this._currentFrame=0,this._blendingFactor=0,t=0;t<this._events.length;t++)this._events[t].isDone=!1},e.prototype.isStopped=function(){return this._stopped},e.prototype.dispose=function(){var e=this._animation.runtimeAnimations.indexOf(this);e>-1&&this._animation.runtimeAnimations.splice(e,1)},e.prototype.setValue=function(e,t){if(this._targetIsArray)for(var i=0;i<this._target.length;i++){var r=this._target[i];this._setValue(r,this._activeTargets[i],e,t,i)}else this._setValue(this._target,this._directTarget,e,t,0)},e.prototype._getOriginalValues=function(e){var t;void 0===e&&(e=0);var i=this._activeTargets[e];(t=i.getLocalMatrix&&"_matrix"===this._targetPath?i.getLocalMatrix():i[this._targetPath])&&t.clone?this._originalValue[e]=t.clone():this._originalValue[e]=t},e.prototype._setValue=function(e,t,i,r,n){if(this._currentActiveTarget=t,this._weight=r,this._enableBlending&&this._blendingFactor<=1){if(!this._originalBlendValue){var o=t[this._targetPath];o.clone?this._originalBlendValue=o.clone():this._originalBlendValue=o}this._originalBlendValue.m?at.AllowMatrixDecomposeForInterpolation?this._currentValue?z.DecomposeLerpToRef(this._originalBlendValue,i,this._blendingFactor,this._currentValue):this._currentValue=z.DecomposeLerp(this._originalBlendValue,i,this._blendingFactor):this._currentValue?z.LerpToRef(this._originalBlendValue,i,this._blendingFactor,this._currentValue):this._currentValue=z.Lerp(this._originalBlendValue,i,this._blendingFactor):this._currentValue=at._UniversalLerp(this._originalBlendValue,i,this._blendingFactor);var a=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.blendingSpeed:this._animation.blendingSpeed;this._blendingFactor+=a}else this._currentValue?this._currentValue.copyFrom?this._currentValue.copyFrom(i):this._currentValue=i:(null==i?void 0:i.clone)?this._currentValue=i.clone():this._currentValue=i;-1!==r?this._scene._registerTargetForLateAnimationBinding(this,this._originalValue[n]):this._animationState.loopMode===at.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT?this._currentValue.addToRef?this._currentValue.addToRef(this._originalValue[n],t[this._targetPath]):t[this._targetPath]=this._originalValue[n]+this._currentValue:t[this._targetPath]=this._currentValue,e.markAsDirty&&e.markAsDirty(this._animation.targetProperty)},e.prototype._getCorrectLoopMode=function(){return this._target&&this._target.animationPropertiesOverride?this._target.animationPropertiesOverride.loopMode:this._animation.loopMode},e.prototype.goToFrame=function(e){var t=this._animation.getKeys();e<t[0].frame?e=t[0].frame:e>t[t.length-1].frame&&(e=t[t.length-1].frame);var i=this._events;if(i.length)for(var r=0;r<i.length;r++)i[r].onlyOnce||(i[r].isDone=i[r].frame<e);this._currentFrame=e;var n=this._animation._interpolate(e,this._animationState);this.setValue(n,-1)},e.prototype._prepareForSpeedRatioChange=function(e){var t=this._previousElapsedTime*(this._animation.framePerSecond*e)/1e3;this._absoluteFrameOffset=this._previousAbsoluteFrame-t},e.prototype.animate=function(e,t,i,r,n,o){void 0===o&&(o=-1);var a=this._animation,s=a.targetPropertyPath;if(!s||s.length<1)return this._stopped=!0,!1;var l=!0;(t<this._minFrame||t>this._maxFrame)&&(t=this._minFrame),(i<this._minFrame||i>this._maxFrame)&&(i=this._maxFrame);var c,u,h=i-t,d=e*(a.framePerSecond*n)/1e3+this._absoluteFrameOffset,p=0,f=!1,_=r&&this._animationState.loopMode===at.ANIMATIONLOOPMODE_YOYO;if(_){var m=(d-t)/h,g=Math.sin(m*Math.PI);d=Math.abs(g)*h+t;var v=g>=0?1:-1;this._yoyoDirection!==v&&(f=!0),this._yoyoDirection=v}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=d,!r&&i>=t&&(d>=h&&n>0||d<=0&&n<0))l=!1,p=a._getKeyValue(this._maxValue);else if(!r&&t>=i&&(d<=h&&n<0||d>=0&&n>0))l=!1,p=a._getKeyValue(this._minValue);else if(this._animationState.loopMode!==at.ANIMATIONLOOPMODE_CYCLE){var y=i.toString()+t.toString();if(!this._offsetsCache[y]){this._animationState.repeatCount=0,this._animationState.loopMode=at.ANIMATIONLOOPMODE_CYCLE;var b=a._interpolate(t,this._animationState),T=a._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),a.dataType){case at.ANIMATIONTYPE_FLOAT:this._offsetsCache[y]=T-b;break;case at.ANIMATIONTYPE_QUATERNION:case at.ANIMATIONTYPE_VECTOR3:case at.ANIMATIONTYPE_VECTOR2:case at.ANIMATIONTYPE_SIZE:case at.ANIMATIONTYPE_COLOR3:this._offsetsCache[y]=T.subtract(b)}this._highLimitsCache[y]=T}p=this._highLimitsCache[y],c=this._offsetsCache[y]}if(void 0===c)switch(a.dataType){case at.ANIMATIONTYPE_FLOAT:c=0;break;case at.ANIMATIONTYPE_QUATERNION:c=$e;break;case at.ANIMATIONTYPE_VECTOR3:c=et;break;case at.ANIMATIONTYPE_VECTOR2:c=tt;break;case at.ANIMATIONTYPE_SIZE:c=it;break;case at.ANIMATIONTYPE_COLOR3:c=rt;break;case at.ANIMATIONTYPE_COLOR4:c=nt}if(this._host&&this._host.syncRoot){var E=this._host.syncRoot;u=t+h*((E.masterFrame-E.fromFrame)/(E.toFrame-E.fromFrame))}else u=d>0&&t>i||d<0&&t<i?l&&0!==h?i+d%h:t:l&&0!==h?t+d%h:i;var S=this._events;if(!_&&(n>0&&this.currentFrame>u||n<0&&this.currentFrame<u)||_&&f){this._onLoop();for(var x=0;x<S.length;x++)S[x].onlyOnce||(S[x].isDone=!1);this._animationState.key=n>0?0:a.getKeys().length-1}this._currentFrame=u,this._animationState.repeatCount=0===h?0:d/h|0,this._animationState.highLimitValue=p,this._animationState.offsetValue=c;var A=a._interpolate(u,this._animationState);if(this.setValue(A,o),S.length)for(x=0;x<S.length;x++)if(h>=0&&u>=S[x].frame&&S[x].frame>=t||h<0&&u<=S[x].frame&&S[x].frame<=t){var C=S[x];C.isDone||(C.onlyOnce&&(S.splice(x,1),x--),C.isDone=!0,C.action(u))}return l||(this._stopped=!0),l},e}();function ct(){return"undefined"!=typeof window}function ut(){return"undefined"!=typeof navigator}function ht(){return"undefined"!=typeof document}function dt(e){for(var t="",i=e.firstChild;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t}var pt,ft={IsWindowObjectExist:ct,IsNavigatorAvailable:ut,IsDocumentAvailable:ht,GetDOMTextContent:dt},_t=function(){function e(){}return Object.defineProperty(e,"Now",{get:function(){return ct()&&window.performance&&window.performance.now?window.performance.now():Date.now()},enumerable:!1,configurable:!0}),e}(),mt=function(){function e(){}return e.FilesToLoad={},e}(),gt=function(){function e(){}return e.ExponentialBackoff=function(e,t){return void 0===e&&(e=3),void 0===t&&(t=500),function(i,r,n){return 0!==r.status||n>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,n)*t}},e}(),vt=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t._setPrototypeOf=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},t}(Error),yt={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002},bt=function(e){function t(i,r,n){var o=e.call(this,i)||this;return o.errorCode=r,o.innerError=n,o.name="RuntimeError",vt._setPrototypeOf(o,t.prototype),o}return m(t,e),t}(vt),Tt=function(e,t){return e.endsWith(t)},Et=function(e,t){return!!e&&e.startsWith(t)},St=function(e){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);for(var t="",i=0;i<e.byteLength;i++)t+=String.fromCharCode(e[i]);return t},xt=function(e){for(var t,i,r,n,o,a,s,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",c="",u=0,h=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);u<h.length;)n=(t=h[u++])>>2,o=(3&t)<<4|(i=u<h.length?h[u++]:Number.NaN)>>4,a=(15&i)<<2|(r=u<h.length?h[u++]:Number.NaN)>>6,s=63&r,isNaN(i)?a=s=64:isNaN(r)&&(s=64),c+=l.charAt(n)+l.charAt(o)+l.charAt(a)+l.charAt(s);return c},At=function(e){return atob(e)},Ct=function(e){for(var t=At(e),i=t.length,r=new Uint8Array(new ArrayBuffer(i)),n=0;n<i;n++)r[n]=t.charCodeAt(n);return r.buffer},Rt=function(e,t){for(var i=String(e);i.length<t;)i="0"+i;return i},Pt={EndsWith:Tt,StartsWith:Et,Decode:St,EncodeArrayBufferToBase64:xt,DecodeBase64ToString:At,DecodeBase64ToBinary:Ct,PadNumber:Rt},It=function(){function e(){this.children=[]}return e.prototype.isValid=function(e){return!0},e.prototype.process=function(e,t){var i,r,n,o,a,s,l,c="";if(this.line){var u=this.line,h=t.processor;if(h){h.lineProcessor&&(u=h.lineProcessor(u,t.isFragment,t.processingContext));var d=null!==(r=null===(i=t.processor)||void 0===i?void 0:i.attributeKeywordName)&&void 0!==r?r:"attribute",p=t.isFragment&&(null===(n=t.processor)||void 0===n?void 0:n.varyingFragmentKeywordName)?null===(o=t.processor)||void 0===o?void 0:o.varyingFragmentKeywordName:!t.isFragment&&(null===(a=t.processor)||void 0===a?void 0:a.varyingVertexKeywordName)?null===(s=t.processor)||void 0===s?void 0:s.varyingVertexKeywordName:"varying";!t.isFragment&&h.attributeProcessor&&this.line.startsWith(d)?u=h.attributeProcessor(this.line,e,t.processingContext):h.varyingProcessor&&((null===(l=h.varyingCheck)||void 0===l?void 0:l.call(h,this.line,t.isFragment))||!h.varyingCheck&&this.line.startsWith(p))?u=h.varyingProcessor(this.line,t.isFragment,e,t.processingContext):h.uniformProcessor&&h.uniformRegexp&&h.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(u=h.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):h.uniformBufferProcessor&&h.uniformBufferRegexp&&h.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(u=h.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):h.textureProcessor&&h.textureRegexp&&h.textureRegexp.test(this.line)?u=h.textureProcessor(this.line,t.isFragment,e,t.processingContext):(h.uniformProcessor||h.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?h.uniformProcessor&&(u=h.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):h.uniformBufferProcessor&&(u=h.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&-1!==this.line.indexOf("}")&&(t.lookForClosingBracketForUniformBuffer=!1,h.endOfUniformBufferProcessor&&(u=h.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}c+=u+"\n"}return this.children.forEach((function(i){c+=i.process(e,t)})),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),c},e}(),Mt=function(){function e(){this._lines=[]}return Object.defineProperty(e.prototype,"currentLine",{get:function(){return this._lines[this.lineIndex]},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"canRead",{get:function(){return this.lineIndex<this._lines.length-1},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"lines",{set:function(e){this._lines.length=0;for(var t=0,i=e;t<i.length;t++){var r=i[t];if(r&&"\r"!==r)if("#"!==r[0]){var n=r.trim();if(n)if(n.startsWith("//"))this._lines.push(r);else{var o=n.indexOf(";");if(-1===o)this._lines.push(n);else if(o===n.length-1)n.length>1&&this._lines.push(n);else for(var a=r.split(";"),s=0;s<a.length;s++){var l=a[s];l&&(l=l.trim())&&this._lines.push(l+(s!==a.length-1?";":""))}}}else this._lines.push(r)}},enumerable:!1,configurable:!0}),e}(),Ot=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.prototype.process=function(e,t){for(var i=0;i<this.children.length;i++){var r=this.children[i];if(r.isValid(e))return r.process(e,t)}return""},t}(It),Dt=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.prototype.isValid=function(e){return this.testExpression.isTrue(e)},t}(It),Nt=function(){function e(){}return e.prototype.isTrue=function(e){return!0},e.postfixToInfix=function(t){for(var i=[],r=0,n=t;r<n.length;r++){var o=n[r];if(void 0===e._OperatorPriority[o])i.push(o);else{var a=i[i.length-1],s=i[i.length-2];i.length-=2,i.push("(".concat(s).concat(o).concat(a,")"))}}return i[i.length-1]},e.infixToPostfix=function(t){var i=e._InfixToPostfixCache.get(t);if(i)return i.accessTime=Date.now(),i.result;if(!(t.includes("&&")||t.includes("||")||t.includes(")")||t.includes("(")))return[t];for(var r=[],n=-1,o=function(){""!==(u=u.trim())&&(r.push(u),u="")},a=function(t){n<e._Stack.length-1&&(e._Stack[++n]=t)},s=function(){return e._Stack[n]},l=function(){return-1===n?"!!INVALID EXPRESSION!!":e._Stack[n--]},c=0,u="";c<t.length;){var h=t.charAt(c),d=c<t.length-1?t.substr(c,2):"";if("("===h)u="",a(h);else if(")"===h){for(o();-1!==n&&"("!==s();)r.push(l());l()}else if(e._OperatorPriority[d]>1){for(o();-1!==n&&e._OperatorPriority[s()]>=e._OperatorPriority[d];)r.push(l());a(d),c++}else u+=h;c++}for(o();-1!==n;)"("===s()?l():r.push(l());return e._InfixToPostfixCache.size>=e.InfixToPostfixCacheLimitSize&&e.ClearCache(),e._InfixToPostfixCache.set(t,{result:r,accessTime:Date.now()}),r},e.ClearCache=function(){for(var t=Array.from(e._InfixToPostfixCache.entries()).sort((function(e,t){return e[1].accessTime-t[1].accessTime})),i=0;i<e.InfixToPostfixCacheCleanupSize;i++)e._InfixToPostfixCache.delete(t[i][0])},e.InfixToPostfixCacheLimitSize=5e4,e.InfixToPostfixCacheCleanupSize=25e3,e._InfixToPostfixCache=new Map,e._OperatorPriority={")":0,"(":1,"||":2,"&&":3},e._Stack=["","","","","","","","","","","","","","","","","","","",""],e}(),Ft=function(e){function t(t,i){void 0===i&&(i=!1);var r=e.call(this)||this;return r.define=t,r.not=i,r}return m(t,e),t.prototype.isTrue=function(e){var t=void 0!==e[this.define];return this.not&&(t=!t),t},t}(Nt),Lt=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.prototype.isTrue=function(e){return this.leftOperand.isTrue(e)||this.rightOperand.isTrue(e)},t}(Nt),wt=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.prototype.isTrue=function(e){return this.leftOperand.isTrue(e)&&this.rightOperand.isTrue(e)},t}(Nt),Bt=function(e){function t(t,i,r){var n=e.call(this)||this;return n.define=t,n.operand=i,n.testValue=r,n}return m(t,e),t.prototype.isTrue=function(e){var t=e[this.define];void 0===t&&(t=this.define);var i=!1,r=parseInt(t),n=parseInt(this.testValue);switch(this.operand){case">":i=r>n;break;case"<":i=r<n;break;case"<=":i=r<=n;break;case">=":i=r>=n;break;case"==":i=r===n;break;case"!=":i=r!==n}return i},t}(Nt);!function(e){e[e.GLSL=0]="GLSL",e[e.WGSL=1]="WGSL"}(pt||(pt={}));var Ut={};function Vt(e,t,i){return void 0===i&&(i=""),i+(t?t+"\n":"")+e}function kt(e,t,i,r,n,o,a){var s=a||Ut.loadFile;if(s)return s(e,t,i,r,n,o);throw He("FileTools")}function Gt(e,t,i,r){if(e)return t?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,i?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(r?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);var n="";return t&&(n+="#define IS_NDC_HALF_ZRANGE"),i&&(n&&(n+="\n"),n+="#define USE_REVERSE_DEPTHBUFFER"),r&&(n&&(n+="\n"),n+="#define USE_EXACT_SRGB_CONVERSIONS"),n}var zt=/defined\s*?\((.+?)\)/g,Wt=/defined\s*?\[(.+?)\]/g,Ht=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,Xt=/__decl__/,jt=/light\{X\}.(\w*)/g,Yt=/\{X\}/g,Kt=[],Qt=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;function qt(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}function Zt(e,t,i,r){var n;(null===(n=t.processor)||void 0===n?void 0:n.preProcessShaderCode)&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),oi(e,t,(function(e){t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));var n=function(e,t,i){var r=function(e,t){var i;if(null===(i=t.processor)||void 0===i?void 0:i.noPrecision)return e;var r=t.shouldUseHighPrecisionShader;return-1===e.indexOf("precision highp float")?e=r?"precision highp float;\n"+e:"precision mediump float;\n"+e:r||(e=e.replace("precision highp float","precision mediump float")),e}(e,t);if(!t.processor)return r;if(t.processor.shaderLanguage===pt.GLSL&&-1!==r.indexOf("#version 3")&&(r=r.replace("#version 300 es",""),!t.processor.parseGLES3))return r;var n=t.defines,o=ni(t,i);return t.processor.preProcessor&&(r=t.processor.preProcessor(r,n,t.isFragment,t.processingContext)),r=ri(r,o,t),t.processor.postProcessor&&(r=t.processor.postProcessor(r,n,t.isFragment,t.processingContext,i?{drawBuffersExtensionDisabled:!i.getCaps().drawBuffersExtension}:{})),(null==i?void 0:i._features.needShaderCodeInlining)&&(r=i.inlineShaderCode(r)),r}(e,t,r);i(n,e)}))}function Jt(e,t,i){return i.processor&&i.processor.finalizeShaders?i.processor.finalizeShaders(e,t,i.processingContext):{vertexCode:e,fragmentCode:t}}function $t(e){var t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new Ft(t[1].trim(),"!"===e[0]);for(var i="",r=0,n=0,o=["==","!=",">=","<=","<",">"];n<o.length&&(i=o[n],!((r=e.indexOf(i))>-1));n++);if(-1===r)return new Ft(e);var a=e.substring(0,r).trim(),s=e.substring(r+i.length).trim();return new Bt(a,i,s)}function ei(e,t){var i=new Dt,r=e.substring(0,t),n=e.substring(t);return n=n.substring(0,(n.indexOf("//")+1||n.length+1)-1).trim(),i.testExpression="#ifdef"===r?new Ft(n):"#ifndef"===r?new Ft(n,!0):function(e){e=e.replace(zt,"defined[$1]");for(var t=[],i=0,r=Nt.infixToPostfix(e);i<r.length;i++){var n=r[i];if("||"!==n&&"&&"!==n)t.push(n);else if(t.length>=2){var o=t[t.length-1],a=t[t.length-2];t.length-=2;var s="&&"==n?new wt:new Lt;"string"==typeof o&&(o=o.replace(Wt,"defined($1)")),"string"==typeof a&&(a=a.replace(Wt,"defined($1)")),s.leftOperand="string"==typeof a?$t(a):a,s.rightOperand="string"==typeof o?$t(o):o,t.push(s)}}var l=t[t.length-1];return"string"==typeof l&&(l=l.replace(Wt,"defined($1)")),"string"==typeof l?$t(l):l}(n),i}function ti(e,t,i){for(var r=e.currentLine;ii(e,i);){var n=(r=e.currentLine).substring(0,5).toLowerCase();if("#else"===n){var o=new It;return t.children.push(o),void ii(e,o)}if("#elif"===n){var a=ei(r,5);t.children.push(a),i=a}}}function ii(e,t){for(;e.canRead;){e.lineIndex++;var i=e.currentLine;if(i.indexOf("#")>=0){var r=Qt.exec(i);if(r&&r.length){switch(r[0]){case"#ifdef":var n=new Ot;t.children.push(n);var o=ei(i,6);n.children.push(o),ti(e,n,o);break;case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":n=new Ot,t.children.push(n),o=ei(i,7),n.children.push(o),ti(e,n,o);break;case"#if":n=new Ot,o=ei(i,3),t.children.push(n),n.children.push(o),ti(e,n,o)}continue}}var a=new It;if(a.line=i,t.children.push(a),"#"===i[0]&&"d"===i[1]){var s=i.replace(";","").split(" ");a.additionalDefineKey=s[1],3===s.length&&(a.additionalDefineValue=s[2])}}return!1}function ri(e,t,i){var r=new It,n=new Mt;return n.lineIndex=-1,n.lines=e.split("\n"),ii(n,r),r.process(t,i)}function ni(e,t){for(var i,r={},n=0,o=e.defines;n<o.length;n++){var a=o[n].replace("#define","").replace(";","").trim().split(" ");r[a[0]]=a.length>1?a[1]:""}return(null===(i=e.processor)||void 0===i?void 0:i.shaderLanguage)===pt.GLSL&&(r.GL_ES="true"),r.__VERSION__=e.version,r[e.platformName]="true",Gt(r,null==t?void 0:t.isNDCHalfZRange,null==t?void 0:t.useReverseDepthBuffer,null==t?void 0:t.useExactSrgbConversions),r}function oi(e,t,i){var r;for(Kt.length=0;null!==(r=Ht.exec(e));)Kt.push(r);for(var n=String(e),o=[e],a=!1,s=function(e){var r=e[1];if(-1!==r.indexOf("__decl__")&&(r=r.replace(Xt,""),t.supportsUniformBuffers&&(r=r.replace("Vertex","Ubo").replace("Fragment","Ubo")),r+="Declaration"),!t.includesShadersStore[r]){var n=t.shadersRepository+"ShadersInclude/"+r+".fx";return ai.loadFile(n,(function(e){t.includesShadersStore[r]=e,oi(o.join(""),t,i)})),{value:void 0}}var s=t.includesShadersStore[r];if(e[2])for(var l=e[3].split(","),c=0;c<l.length;c+=2){var u=new RegExp(l[c],"g"),h=l[c+1];s=s.replace(u,h)}if(e[4]){var d=e[5];if(-1!==d.indexOf("..")){var p=d.split(".."),f=parseInt(p[0]),_=parseInt(p[1]),m=s.slice(0);s="",isNaN(_)&&(_=t.indexParameters[p[1]]);for(var g=f;g<_;g++)t.supportsUniformBuffers||(m=m.replace(jt,(function(e,t){return t+"{X}"}))),s+=m.replace(Yt,g.toString())+"\n"}else t.supportsUniformBuffers||(s=s.replace(jt,(function(e,t){return t+"{X}"}))),s=s.replace(Yt,d)}for(var v=[],y=0,b=o;y<b.length;y++){var T=b[y].split(e[0]);for(g=0;g<T.length-1;g++)v.push(T[g]),v.push(s);v.push(T[T.length-1])}o=v,a=a||s.indexOf("#include<")>=0||s.indexOf("#include <")>=0},l=0,c=Kt;l<c.length;l++){var u=s(c[l]);if("object"==typeof u)return u.value}Kt.length=0,n=o.join(""),a?oi(n.toString(),t,i):i(n)}var ai={loadFile:function(e,t,i,r,n,o){throw He("FileTools")}},si=function(){function e(){}return e.SetImmediate=function(e){ct()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)},e}(),li=function(){function e(){}return e.GetShadersRepository=function(t){return void 0===t&&(t=pt.GLSL),t===pt.GLSL?e.ShadersRepository:e.ShadersRepositoryWGSL},e.GetShadersStore=function(t){return void 0===t&&(t=pt.GLSL),t===pt.GLSL?e.ShadersStore:e.ShadersStoreWGSL},e.GetIncludesShadersStore=function(t){return void 0===t&&(t=pt.GLSL),t===pt.GLSL?e.IncludesShadersStore:e.IncludesShadersStoreWGSL},e.ShadersRepository="src/Shaders/",e.ShadersStore={},e.IncludesShadersStore={},e.ShadersRepositoryWGSL="src/ShadersWGSL/",e.ShadersStoreWGSL={},e.IncludesShadersStoreWGSL={},e}(),ci=function(){function e(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null,this._isDisposed=!1}return Object.defineProperty(e.prototype,"isAsync",{get:function(){return this.isParallelCompiled},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isReady",{get:function(){return!!this.program&&(!this.isParallelCompiled||this.engine._isRenderingStateCompiled(this))},enumerable:!1,configurable:!0}),e.prototype._handlesSpectorRebuildCallback=function(e){e&&this.program&&e(this.program)},e.prototype.setEngine=function(e){this.engine=e},e.prototype._fillEffectInformation=function(e,t,i,r,n,o,a,s){var l,c=this.engine;if(c.supportsUniformBuffers)for(var u in t)e.bindUniformBlock(u,t[u]);for(this.engine.getUniforms(this,i).forEach((function(e,t){r[i[t]]=e})),this._uniforms=r,l=0;l<n.length;l++)null==e.getUniform(n[l])&&(n.splice(l,1),l--);n.forEach((function(e,t){o[e]=t}));for(var h=0,d=c.getAttributes(this,a);h<d.length;h++){var p=d[h];s.push(p)}},e.prototype.dispose=function(){this._uniforms={},this._isDisposed=!0},e.prototype._cacheMatrix=function(e,t){var i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)},e.prototype._cacheFloat2=function(e,t,i){var r=this._valueCache[e];if(!r||2!==r.length)return r=[t,i],this._valueCache[e]=r,!0;var n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),n},e.prototype._cacheFloat3=function(e,t,i,r){var n=this._valueCache[e];if(!n||3!==n.length)return n=[t,i,r],this._valueCache[e]=n,!0;var o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==r&&(n[2]=r,o=!0),o},e.prototype._cacheFloat4=function(e,t,i,r,n){var o=this._valueCache[e];if(!o||4!==o.length)return o=[t,i,r,n],this._valueCache[e]=o,!0;var a=!1;return o[0]!==t&&(o[0]=t,a=!0),o[1]!==i&&(o[1]=i,a=!0),o[2]!==r&&(o[2]=r,a=!0),o[3]!==n&&(o[3]=n,a=!0),a},e.prototype.setInt=function(e,t){var i=this._valueCache[e];void 0!==i&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)},e.prototype.setInt2=function(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))},e.prototype.setInt3=function(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))},e.prototype.setInt4=function(e,t,i,r,n){this._cacheFloat4(e,t,i,r,n)&&(this.engine.setInt4(this._uniforms[e],t,i,r,n)||(this._valueCache[e]=null))},e.prototype.setIntArray=function(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)},e.prototype.setIntArray2=function(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)},e.prototype.setIntArray3=function(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)},e.prototype.setIntArray4=function(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)},e.prototype.setUInt=function(e,t){var i=this._valueCache[e];void 0!==i&&i===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)},e.prototype.setUInt2=function(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))},e.prototype.setUInt3=function(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setUInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))},e.prototype.setUInt4=function(e,t,i,r,n){this._cacheFloat4(e,t,i,r,n)&&(this.engine.setUInt4(this._uniforms[e],t,i,r,n)||(this._valueCache[e]=null))},e.prototype.setUIntArray=function(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)},e.prototype.setUIntArray2=function(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)},e.prototype.setUIntArray3=function(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)},e.prototype.setUIntArray4=function(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)},e.prototype.setArray=function(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)},e.prototype.setArray2=function(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)},e.prototype.setArray3=function(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)},e.prototype.setArray4=function(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)},e.prototype.setMatrices=function(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))},e.prototype.setMatrix=function(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))},e.prototype.setMatrix3x3=function(e,t){this._valueCache[e]=null,this.engine.setMatrix3x3(this._uniforms[e],t)},e.prototype.setMatrix2x2=function(e,t){this._valueCache[e]=null,this.engine.setMatrix2x2(this._uniforms[e],t)},e.prototype.setFloat=function(e,t){var i=this._valueCache[e];void 0!==i&&i===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)},e.prototype.setVector2=function(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))},e.prototype.setFloat2=function(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))},e.prototype.setVector3=function(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))},e.prototype.setFloat3=function(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setFloat3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))},e.prototype.setVector4=function(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))},e.prototype.setQuaternion=function(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))},e.prototype.setFloat4=function(e,t,i,r,n){this._cacheFloat4(e,t,i,r,n)&&(this.engine.setFloat4(this._uniforms[e],t,i,r,n)||(this._valueCache[e]=null))},e.prototype.setColor3=function(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))},e.prototype.setColor4=function(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))},e.prototype.setDirectColor4=function(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))},e.prototype._getVertexShaderCode=function(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null},e.prototype._getFragmentShaderCode=function(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null},e}(),ui=new WeakMap,hi={_webGLVersion:2,cachedPipelines:{}};function di(e){var t=ui.get(e);if(!t){if(!e)return hi;t={_webGLVersion:e.TEXTURE_BINDING_3D?2:1,_context:e,cachedPipelines:{}},ui.set(e,t)}return t}function pi(e,t,i,r,n,o){var a,s=di(r);return o||(o=null!==(a=s._createShaderProgramInjection)&&void 0!==a?a:_i),o(e,vi(t,"vertex",r,s._contextWasLost),vi(i,"fragment",r,s._contextWasLost),r,n,s.validateShaderPrograms)}function fi(e,t,i,r,n,o,a){var s;void 0===o&&(o=null);var l=di(n);a||(a=null!==(s=l._createShaderProgramInjection)&&void 0!==s?s:_i);var c=l._webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"";return a(e,gi(t,"vertex",r,c,n,l._contextWasLost),gi(i,"fragment",r,c,n,l._contextWasLost),n,o,l.validateShaderPrograms)}function _i(e,t,i,r,n,o){void 0===n&&(n=null);var a=r.createProgram();if(e.program=a,!a)throw new Error("Unable to create program");return r.attachShader(a,t),r.attachShader(a,i),r.linkProgram(a),e.context=r,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||mi(e,r,o),a}function mi(e,t,i){var r=e.context,n=e.vertexShader,o=e.fragmentShader,a=e.program;if(!r.getProgramParameter(a,r.LINK_STATUS)){var s,l;if(!t.getShaderParameter(n,t.COMPILE_STATUS)&&(s=t.getShaderInfoLog(n)))throw e.vertexCompilationError=s,new Error("VERTEX SHADER "+s);if(!t.getShaderParameter(o,t.COMPILE_STATUS)&&(s=t.getShaderInfoLog(o)))throw e.fragmentCompilationError=s,new Error("FRAGMENT SHADER "+s);if(l=r.getProgramInfoLog(a))throw e.programLinkError=l,new Error(l)}if(i&&(r.validateProgram(a),!r.getProgramParameter(a,r.VALIDATE_STATUS)&&(l=r.getProgramInfoLog(a))))throw e.programValidationError=l,new Error(l);r.deleteShader(n),r.deleteShader(o),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}function gi(e,t,i,r,n,o){return vi(Vt(e,i,r),t,n,o)}function vi(e,t,i,r){var n=i.createShader("vertex"===t?i.VERTEX_SHADER:i.FRAGMENT_SHADER);if(!n){for(var o=i.NO_ERROR,a=i.NO_ERROR;(a=i.getError())!==i.NO_ERROR;)o=a;throw new Error("Something went wrong while creating a gl ".concat(t," shader object. gl error=").concat(o,", gl isContextLost=").concat(i.isContextLost(),", _contextWasLost=").concat(r))}return i.shaderSource(n,e),i.compileShader(n),n}function yi(e){var t=e._name,i=e.context;if(t&&i){var r=di(i),n=r.cachedPipelines[t];null==n||n.dispose(),delete r.cachedPipelines[t]}}function bi(e,t,i,r,n,o){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)r(dt(e));else if("source:"!==e.substr(0,7))if("base64:"!==e.substr(0,7)){var a=li.GetShadersStore(n);if(a[e+t+"Shader"])r(a[e+t+"Shader"]);else if(i&&a[e+i+"Shader"])r(a[e+i+"Shader"]);else{var s;if(s="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:li.GetShadersRepository(n)+e,!(o=o||kt))throw new Error("loadFileInjection is not defined");o(s+"."+t.toLowerCase()+".fx",r)}}else r(window.atob(e.substr(7)));else r(e.substr(7))}var Ti,Ei=function(){function e(t,i,r,n,o,a,s,l,c,u,h,d){var p,_,m,g;void 0===n&&(n=null),void 0===a&&(a=null),void 0===s&&(s=null),void 0===l&&(l=null),void 0===c&&(c=null),void 0===h&&(h=""),void 0===d&&(d=pt.GLSL),this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new f,this.onErrorObservable=new f,this._onBindObservable=null,this._isDisposed=!1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=t,this._key=h;var v,y=this._key.replace(/\r/g,"").replace(/\n/g,"|"),b=void 0;if(i.attributes){var T=i;if(this._engine=r,this._attributesNames=T.attributes,this._uniformsNames=T.uniformsNames.concat(T.samplers),this._samplerList=T.samplers.slice(),this.defines=T.defines,this.onError=T.onError,this.onCompiled=T.onCompiled,this._fallbacks=T.fallbacks,this._indexParameters=T.indexParameters,this._transformFeedbackVaryings=T.transformFeedbackVaryings||null,this._multiTarget=!!T.multiTarget,this._shaderLanguage=null!==(p=T.shaderLanguage)&&void 0!==p?p:pt.GLSL,T.uniformBuffersNames){this._uniformBuffersNamesList=T.uniformBuffersNames.slice();for(var E=0;E<T.uniformBuffersNames.length;E++)this._uniformBuffersNames[T.uniformBuffersNames[E]]=E}this._processFinalCode=null!==(_=T.processFinalCode)&&void 0!==_?_:null,this._processCodeAfterIncludes=null!==(m=T.processCodeAfterIncludes)&&void 0!==m?m:void 0,b=T.existingPipelineContext}else this._engine=o,this.defines=null==a?"":a,this._uniformsNames=r.concat(n),this._samplerList=n?n.slice():[],this._attributesNames=i,this._uniformBuffersNamesList=[],this._shaderLanguage=d,this.onError=c,this.onCompiled=l,this._indexParameters=u,this._fallbacks=s;"WEBGL2"===this._engine.shaderPlatformName&&(b=null!==(v=y,g=di(this._engine._gl).cachedPipelines[v])&&void 0!==g?g:b),this._attributeLocationByName={},this.uniqueId=e._UniqueIdSeed++,b?(this._pipelineContext=b,this._pipelineContext.setEngine(this._engine),this._onRenderingStateCompiled(this._pipelineContext),this._pipelineContext.program&&(this._pipelineContext.program.__SPECTOR_rebuildProgram=this._rebuildProgram.bind(this))):this._processShaderCode()}return Object.defineProperty(e,"ShadersRepository",{get:function(){return li.ShadersRepository},set:function(e){li.ShadersRepository=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onBindObservable",{get:function(){return this._onBindObservable||(this._onBindObservable=new f),this._onBindObservable},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"shaderLanguage",{get:function(){return this._shaderLanguage},enumerable:!1,configurable:!0}),e.prototype._processShaderCode=function(e,t){var i=this;void 0===e&&(e=null),void 0===t&&(t=!1),this._processingContext=this._engine._getShaderProcessingContext(this._shaderLanguage),function(e,t,i,r,n,o,a){var s,l,c=ct()?null==o?void 0:o.getHostDocument():null;s="string"==typeof t?t:t.vertexSource?"source:"+t.vertexSource:t.vertexElement?(null==c?void 0:c.getElementById(t.vertexElement))||t.vertexElement:t.vertex||t,l="string"==typeof t?t:t.fragmentSource?"source:"+t.fragmentSource:t.fragmentElement?(null==c?void 0:c.getElementById(t.fragmentElement))||t.fragmentElement:t.fragment||t;var u=[void 0,void 0],h=function(){if(u[0]&&u[1]){e.isFragment=!0;var s=u[0];Zt(u[1],e,(function(o,l){a&&(a._fragmentSourceCodeBeforeMigration=l),i&&(o=i("fragment",o));var c=Jt(s,o,e);e=null;var u=function(e,t,i,r){if(i){var n=i.vertexElement||i.vertex||i.spectorName||i,o=i.fragmentElement||i.fragment||i.spectorName||i;return{vertexSourceCode:(r===pt.WGSL?"//":"")+"#define SHADER_NAME vertex:"+n+"\n"+e,fragmentSourceCode:(r===pt.WGSL?"//":"")+"#define SHADER_NAME fragment:"+o+"\n"+t}}return{vertexSourceCode:e,fragmentSourceCode:t}}(c.vertexCode,c.fragmentCode,t,n);null==r||r(u.vertexSourceCode,u.fragmentSourceCode)}),o)}};bi(s,"Vertex","",(function(t){qt(e),Zt(t,e,(function(e,r){a&&(a._rawVertexSourceCode=t,a._vertexSourceCodeBeforeMigration=r),i&&(e=i("vertex",e)),u[0]=e,h()}),o)}),n),bi(l,"Fragment","Pixel",(function(e){a&&(a._rawFragmentSourceCode=e),u[1]=e,h()}),n)}({defines:this.defines.split("\n"),indexParameters:this._indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:null!=e?e:this._engine._getShaderProcessor(this._shaderLanguage),supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:li.GetShadersRepository(this._shaderLanguage),includesShadersStore:li.GetIncludesShadersStore(this._shaderLanguage),version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._processingContext,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:this._processCodeAfterIncludes},this.name,this._processFinalCode,(function(e,r){i._vertexSourceCode=e,i._fragmentSourceCode=r,i._prepareEffect(t)}),this._shaderLanguage,this._engine,this)},Object.defineProperty(e.prototype,"key",{get:function(){return this._key},enumerable:!1,configurable:!0}),e.prototype.isReady=function(){try{return this._isReadyInternal()}catch(e){return!1}},e.prototype._isReadyInternal=function(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady},e.prototype.getEngine=function(){return this._engine},e.prototype.getPipelineContext=function(){return this._pipelineContext},e.prototype.getAttributesNames=function(){return this._attributesNames},e.prototype.getAttributeLocation=function(e){return this._attributes[e]},e.prototype.getAttributeLocationByName=function(e){return this._attributeLocationByName[e]},e.prototype.getAttributesCount=function(){return this._attributes.length},e.prototype.getUniformIndex=function(e){return this._uniformsNames.indexOf(e)},e.prototype.getUniform=function(e){return this._uniforms[e]},e.prototype.getSamplers=function(){return this._samplerList},e.prototype.getUniformNames=function(){return this._uniformsNames},e.prototype.getUniformBuffersNames=function(){return this._uniformBuffersNamesList},e.prototype.getIndexParameters=function(){return this._indexParameters},e.prototype.getCompilationError=function(){return this._compilationError},e.prototype.allFallbacksProcessed=function(){return this._allFallbacksProcessed},e.prototype.executeWhenCompiled=function(e){var t=this;this.isReady()?e(this):(this.onCompileObservable.add((function(t){e(t)})),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout((function(){t._checkIsReady(null)}),16))},e.prototype._checkIsReady=function(e){var t=this;try{if(this._isReadyInternal())return}catch(t){return void this._processCompilationErrors(t,e)}this._isDisposed||setTimeout((function(){t._checkIsReady(e)}),16)},Object.defineProperty(e.prototype,"vertexSourceCode",{get:function(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getVertexShaderCode())&&void 0!==t?t:this._vertexSourceCode},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"fragmentSourceCode",{get:function(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getFragmentShaderCode())&&void 0!==t?t:this._fragmentSourceCode},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"vertexSourceCodeBeforeMigration",{get:function(){return this._vertexSourceCodeBeforeMigration},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"fragmentSourceCodeBeforeMigration",{get:function(){return this._fragmentSourceCodeBeforeMigration},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"rawVertexSourceCode",{get:function(){return this._rawVertexSourceCode},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"rawFragmentSourceCode",{get:function(){return this._rawFragmentSourceCode},enumerable:!1,configurable:!0}),e.prototype.getPipelineGenerationOptions=function(){return{platformName:this._engine.shaderPlatformName,shaderLanguage:this._shaderLanguage,shaderNameOrContent:this.name,key:this._key,defines:this.defines.split("\n"),addGlobalDefines:!1,extendedProcessingOptions:{indexParameters:this._indexParameters,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,supportsUniformBuffers:this._engine.supportsUniformBuffers},extendedCreatePipelineOptions:{transformFeedbackVaryings:this._transformFeedbackVaryings,createAsRaw:!(!this._vertexSourceCodeOverride||!this._fragmentSourceCodeOverride)}}},e.prototype._rebuildProgram=function(e,t,i,r){var n=this;this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=function(e,t){r&&r(t)},this.onCompiled=function(){var e,t,r=n.getEngine().scenes;if(r)for(var o=0;o<r.length;o++)r[o].markAllMaterialsAsDirty(u.MATERIAL_AllDirtyFlag);null===(t=(e=n._pipelineContext)._handlesSpectorRebuildCallback)||void 0===t||t.call(e,i)},this._fallbacks=null,this._prepareEffect()},e.prototype._onRenderingStateCompiled=function(e){if(this._pipelineContext=e,this._pipelineContext.setEngine(this._engine),this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,this._attributesNames,this._attributes),this._attributesNames)for(var t=0;t<this._attributesNames.length;t++){var i=this._attributesNames[t];this._attributeLocationByName[i]=this._attributes[t]}this._engine.bindSamplers(this),this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh()},e.prototype._prepareEffect=function(e){var t=this;void 0===e&&(e=!1);var i=this._pipelineContext;this._isReady=!1;try{var r=!(!this._vertexSourceCodeOverride||!this._fragmentSourceCodeOverride),n=r?null:this.defines,o=r?this._vertexSourceCodeOverride:this._vertexSourceCode,a=r?this._fragmentSourceCodeOverride:this._fragmentSourceCode,s=this._engine;this._pipelineContext=function(e,t,i,r){try{var n=e.existingPipelineContext||t(e.shaderProcessingContext);return n._name=e.name,e.name&&e.context&&(di(e.context).cachedPipelines[e.name]=n),i(n,e.vertex,e.fragment,!!e.createAsRaw,"","",e.rebuildRebind,e.defines,e.transformFeedbackVaryings,""),r(n,(function(){var t;null===(t=e.onRenderingStateCompiled)||void 0===t||t.call(e,n)})),n}catch(e){throw ae.Error("Error compiling effect"),e}}({existingPipelineContext:e?i:null,vertex:o,fragment:a,context:"WEBGL2"===s.shaderPlatformName?s._gl:void 0,rebuildRebind:function(e,i,r,n){return t._rebuildProgram(e,i,r,n)},defines:n,transformFeedbackVaryings:this._transformFeedbackVaryings,name:this._key.replace(/\r/g,"").replace(/\n/g,"|"),createAsRaw:r,parallelShaderCompile:s._caps.parallelShaderCompile,shaderProcessingContext:this._processingContext,onRenderingStateCompiled:function(r){i&&!e&&t._engine._deletePipelineContext(i),r&&t._onRenderingStateCompiled(r)}},this._engine.createPipelineContext.bind(this._engine),this._engine._preparePipelineContext.bind(this._engine),this._engine._executeWhenRenderingStateIsCompiled.bind(this._engine)),this._pipelineContext.isAsync&&this._checkIsReady(i)}catch(e){this._processCompilationErrors(e,i)}},e.prototype._getShaderCodeAndErrorLine=function(e,t,i){var r=i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/,n=null;if(t&&e){var o=t.match(r);if(o&&2===o.length){var a=parseInt(o[1]),s=e.split("\n",-1);s.length>=a&&(n="Offending line [".concat(a,"] in ").concat(i?"fragment":"vertex"," code: ").concat(s[a-1]))}}return[e,n]},e.prototype._processCompilationErrors=function(t,i){var r,n,o,a,s,l=this;void 0===i&&(i=null),this._compilationError=t.message;var c=this._attributesNames,u=this._fallbacks;if(ae.Error("Unable to compile effect:"),ae.Error("Uniforms: "+this._uniformsNames.map((function(e){return" "+e}))),ae.Error("Attributes: "+c.map((function(e){return" "+e}))),ae.Error("Defines:\n"+this.defines),e.LogShaderCodeOnCompilationError){var h=null,d=null,p=null;(null===(o=this._pipelineContext)||void 0===o?void 0:o._getVertexShaderCode())&&(p=(r=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1))[0],h=r[1],p&&(ae.Error("Vertex code:"),ae.Error(p))),(null===(a=this._pipelineContext)||void 0===a?void 0:a._getFragmentShaderCode())&&(p=(n=this._getShaderCodeAndErrorLine(null===(s=this._pipelineContext)||void 0===s?void 0:s._getFragmentShaderCode(),this._compilationError,!0))[0],d=n[1],p&&(ae.Error("Fragment code:"),ae.Error(p))),h&&ae.Error(h),d&&ae.Error(d)}ae.Error("Error: "+this._compilationError);var f=function(){l.onError&&l.onError(l,l._compilationError),l.onErrorObservable.notifyObservers(l)};i&&(this._pipelineContext=i,this._isReady=!0,f()),u?(this._pipelineContext=null,u.hasMoreFallbacks?(this._allFallbacksProcessed=!1,ae.Error("Trying next fallback."),this.defines=u.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,f(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,i||f())},Object.defineProperty(e.prototype,"isSupported",{get:function(){return""===this._compilationError},enumerable:!1,configurable:!0}),e.prototype._bindTexture=function(e,t){this._engine._bindTexture(this._samplers[e],t,e)},e.prototype.setTexture=function(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)},e.prototype.setDepthStencilTexture=function(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)},e.prototype.setTextureArray=function(e,t){var i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){for(var r=this._samplerList.indexOf(e),n=1;n<t.length;n++){var o=i+(n-1).toString();this._samplerList.splice(r+n,0,o)}for(var a=0,s=0,l=this._samplerList;s<l.length;s++){var c=l[s];this._samplers[c]=a,a+=1}}this._engine.setTextureArray(this._samplers[e],this._uniforms[e],t,e)},e.prototype.setTextureFromPostProcess=function(e,t){this._engine.setTextureFromPostProcess(this._samplers[e],t,e)},e.prototype.setTextureFromPostProcessOutput=function(e,t){this._engine.setTextureFromPostProcessOutput(this._samplers[e],t,e)},e.prototype.bindUniformBuffer=function(t,i){var r=this._uniformBuffersNames[i];void 0===r||e._BaseCache[r]===t&&this._engine._features.useUBOBindingCache||(e._BaseCache[r]=t,this._engine.bindUniformBufferBase(t,r,i))},e.prototype.bindUniformBlock=function(e,t){this._engine.bindUniformBlock(this._pipelineContext,e,t)},e.prototype.setInt=function(e,t){return this._pipelineContext.setInt(e,t),this},e.prototype.setInt2=function(e,t,i){return this._pipelineContext.setInt2(e,t,i),this},e.prototype.setInt3=function(e,t,i,r){return this._pipelineContext.setInt3(e,t,i,r),this},e.prototype.setInt4=function(e,t,i,r,n){return this._pipelineContext.setInt4(e,t,i,r,n),this},e.prototype.setIntArray=function(e,t){return this._pipelineContext.setIntArray(e,t),this},e.prototype.setIntArray2=function(e,t){return this._pipelineContext.setIntArray2(e,t),this},e.prototype.setIntArray3=function(e,t){return this._pipelineContext.setIntArray3(e,t),this},e.prototype.setIntArray4=function(e,t){return this._pipelineContext.setIntArray4(e,t),this},e.prototype.setUInt=function(e,t){return this._pipelineContext.setUInt(e,t),this},e.prototype.setUInt2=function(e,t,i){return this._pipelineContext.setUInt2(e,t,i),this},e.prototype.setUInt3=function(e,t,i,r){return this._pipelineContext.setUInt3(e,t,i,r),this},e.prototype.setUInt4=function(e,t,i,r,n){return this._pipelineContext.setUInt4(e,t,i,r,n),this},e.prototype.setUIntArray=function(e,t){return this._pipelineContext.setUIntArray(e,t),this},e.prototype.setUIntArray2=function(e,t){return this._pipelineContext.setUIntArray2(e,t),this},e.prototype.setUIntArray3=function(e,t){return this._pipelineContext.setUIntArray3(e,t),this},e.prototype.setUIntArray4=function(e,t){return this._pipelineContext.setUIntArray4(e,t),this},e.prototype.setFloatArray=function(e,t){return this._pipelineContext.setArray(e,t),this},e.prototype.setFloatArray2=function(e,t){return this._pipelineContext.setArray2(e,t),this},e.prototype.setFloatArray3=function(e,t){return this._pipelineContext.setArray3(e,t),this},e.prototype.setFloatArray4=function(e,t){return this._pipelineContext.setArray4(e,t),this},e.prototype.setArray=function(e,t){return this._pipelineContext.setArray(e,t),this},e.prototype.setArray2=function(e,t){return this._pipelineContext.setArray2(e,t),this},e.prototype.setArray3=function(e,t){return this._pipelineContext.setArray3(e,t),this},e.prototype.setArray4=function(e,t){return this._pipelineContext.setArray4(e,t),this},e.prototype.setMatrices=function(e,t){return this._pipelineContext.setMatrices(e,t),this},e.prototype.setMatrix=function(e,t){return this._pipelineContext.setMatrix(e,t),this},e.prototype.setMatrix3x3=function(e,t){return this._pipelineContext.setMatrix3x3(e,t),this},e.prototype.setMatrix2x2=function(e,t){return this._pipelineContext.setMatrix2x2(e,t),this},e.prototype.setFloat=function(e,t){return this._pipelineContext.setFloat(e,t),this},e.prototype.setBool=function(e,t){return this._pipelineContext.setInt(e,t?1:0),this},e.prototype.setVector2=function(e,t){return this._pipelineContext.setVector2(e,t),this},e.prototype.setFloat2=function(e,t,i){return this._pipelineContext.setFloat2(e,t,i),this},e.prototype.setVector3=function(e,t){return this._pipelineContext.setVector3(e,t),this},e.prototype.setFloat3=function(e,t,i,r){return this._pipelineContext.setFloat3(e,t,i,r),this},e.prototype.setVector4=function(e,t){return this._pipelineContext.setVector4(e,t),this},e.prototype.setQuaternion=function(e,t){return this._pipelineContext.setQuaternion(e,t),this},e.prototype.setFloat4=function(e,t,i,r,n){return this._pipelineContext.setFloat4(e,t,i,r,n),this},e.prototype.setColor3=function(e,t){return this._pipelineContext.setColor3(e,t),this},e.prototype.setColor4=function(e,t,i){return this._pipelineContext.setColor4(e,t,i),this},e.prototype.setDirectColor4=function(e,t){return this._pipelineContext.setDirectColor4(e,t),this},e.prototype.dispose=function(){this._pipelineContext&&yi(this._pipelineContext),this._engine._releaseEffect(this),this._isDisposed=!0},e.RegisterShader=function(e,t,i,r){void 0===r&&(r=pt.GLSL),t&&(li.GetShadersStore(r)["".concat(e,"PixelShader")]=t),i&&(li.GetShadersStore(r)["".concat(e,"VertexShader")]=i)},e.ResetCache=function(){e._BaseCache={}},e.LogShaderCodeOnCompilationError=!0,e._UniqueIdSeed=0,e._BaseCache={},e.ShadersStore=li.ShadersStore,e.IncludesShadersStore=li.IncludesShadersStore,e}(),Si=function(){function e(e){void 0===e&&(e=!0),this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1,e&&this.reset()}return Object.defineProperty(e.prototype,"isDirty",{get:function(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty||this._isFrontFaceDirty},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"zOffset",{get:function(){return this._zOffset},set:function(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"zOffsetUnits",{get:function(){return this._zOffsetUnits},set:function(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"cullFace",{get:function(){return this._cullFace},set:function(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"cull",{get:function(){return this._cull},set:function(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"depthFunc",{get:function(){return this._depthFunc},set:function(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"depthMask",{get:function(){return this._depthMask},set:function(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"depthTest",{get:function(){return this._depthTest},set:function(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"frontFace",{get:function(){return this._frontFace},set:function(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0)},enumerable:!1,configurable:!0}),e.prototype.reset=function(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._zOffsetUnits=0,this._frontFace=null,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!0,this._isFrontFaceDirty=!1},e.prototype.apply=function(e){this.isDirty&&(this._isCullDirty&&(this.cull?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(e.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(e.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(e.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset||this.zOffsetUnits?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,this.zOffsetUnits)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(e.frontFace(this.frontFace),this._isFrontFaceDirty=!1))},e}(),xi=function(){function e(e){void 0===e&&(e=!0),this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.useStencilGlobalOnly=!1,e&&this.reset()}return Object.defineProperty(e.prototype,"isDirty",{get:function(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"func",{get:function(){return this._func},set:function(e){this._func!==e&&(this._func=e,this._isStencilFuncDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"funcRef",{get:function(){return this._funcRef},set:function(e){this._funcRef!==e&&(this._funcRef=e,this._isStencilFuncDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"funcMask",{get:function(){return this._funcMask},set:function(e){this._funcMask!==e&&(this._funcMask=e,this._isStencilFuncDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"opStencilFail",{get:function(){return this._opStencilFail},set:function(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._isStencilOpDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"opDepthFail",{get:function(){return this._opDepthFail},set:function(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._isStencilOpDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"opStencilDepthPass",{get:function(){return this._opStencilDepthPass},set:function(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._isStencilOpDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"mask",{get:function(){return this._mask},set:function(e){this._mask!==e&&(this._mask=e,this._isStencilMaskDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"enabled",{get:function(){return this._enabled},set:function(e){this._enabled!==e&&(this._enabled=e,this._isStencilTestDirty=!0)},enumerable:!1,configurable:!0}),e.prototype.reset=function(){var e;this.stencilMaterial=void 0,null===(e=this.stencilGlobal)||void 0===e||e.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0},e.prototype.apply=function(e){var t;if(e){var i=!this.useStencilGlobalOnly&&!!(null===(t=this.stencilMaterial)||void 0===t?void 0:t.enabled);this.enabled=i?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=i?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=i?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=i?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=i?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=i?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=i?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=i?this.stencilMaterial.mask:this.stencilGlobal.mask,this.isDirty&&(this._isStencilTestDirty&&(this.enabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.mask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFunc(this.func,this.funcRef,this.funcMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOp(this.opStencilFail,this.opDepthFail,this.opStencilDepthPass),this._isStencilOpDirty=!1))}},e}(),Ai=function(){function e(){this.reset()}return e.prototype.reset=function(){this.enabled=!1,this.mask=255,this.func=e.ALWAYS,this.funcRef=1,this.funcMask=255,this.opStencilFail=e.KEEP,this.opDepthFail=e.KEEP,this.opStencilDepthPass=e.REPLACE},Object.defineProperty(e.prototype,"stencilFunc",{get:function(){return this.func},set:function(e){this.func=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stencilFuncRef",{get:function(){return this.funcRef},set:function(e){this.funcRef=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stencilFuncMask",{get:function(){return this.funcMask},set:function(e){this.funcMask=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stencilOpStencilFail",{get:function(){return this.opStencilFail},set:function(e){this.opStencilFail=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stencilOpDepthFail",{get:function(){return this.opDepthFail},set:function(e){this.opDepthFail=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stencilOpStencilDepthPass",{get:function(){return this.opStencilDepthPass},set:function(e){this.opStencilDepthPass=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stencilMask",{get:function(){return this.mask},set:function(e){this.mask=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stencilTest",{get:function(){return this.enabled},set:function(e){this.enabled=e},enumerable:!1,configurable:!0}),e.ALWAYS=u.ALWAYS,e.KEEP=u.KEEP,e.REPLACE=u.REPLACE,e}(),Ci=function(){function e(){this._blendFunctionParameters=new Array(4),this._blendEquationParameters=new Array(2),this._blendConstants=new Array(4),this._isBlendConstantsDirty=!1,this._alphaBlend=!1,this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this.reset()}return Object.defineProperty(e.prototype,"isDirty",{get:function(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty||this._isBlendEquationParametersDirty},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"alphaBlend",{get:function(){return this._alphaBlend},set:function(e){this._alphaBlend!==e&&(this._alphaBlend=e,this._isAlphaBlendDirty=!0)},enumerable:!1,configurable:!0}),e.prototype.setAlphaBlendConstants=function(e,t,i,r){this._blendConstants[0]===e&&this._blendConstants[1]===t&&this._blendConstants[2]===i&&this._blendConstants[3]===r||(this._blendConstants[0]=e,this._blendConstants[1]=t,this._blendConstants[2]=i,this._blendConstants[3]=r,this._isBlendConstantsDirty=!0)},e.prototype.setAlphaBlendFunctionParameters=function(e,t,i,r){this._blendFunctionParameters[0]===e&&this._blendFunctionParameters[1]===t&&this._blendFunctionParameters[2]===i&&this._blendFunctionParameters[3]===r||(this._blendFunctionParameters[0]=e,this._blendFunctionParameters[1]=t,this._blendFunctionParameters[2]=i,this._blendFunctionParameters[3]=r,this._isBlendFunctionParametersDirty=!0)},e.prototype.setAlphaEquationParameters=function(e,t){this._blendEquationParameters[0]===e&&this._blendEquationParameters[1]===t||(this._blendEquationParameters[0]=e,this._blendEquationParameters[1]=t,this._isBlendEquationParametersDirty=!0)},e.prototype.reset=function(){this._alphaBlend=!1,this._blendFunctionParameters[0]=null,this._blendFunctionParameters[1]=null,this._blendFunctionParameters[2]=null,this._blendFunctionParameters[3]=null,this._blendEquationParameters[0]=null,this._blendEquationParameters[1]=null,this._blendConstants[0]=null,this._blendConstants[1]=null,this._blendConstants[2]=null,this._blendConstants[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this._isBlendConstantsDirty=!1},e.prototype.apply=function(e){this.isDirty&&(this._isAlphaBlendDirty&&(this._alphaBlend?e.enable(e.BLEND):e.disable(e.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(e.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1),this._isBlendEquationParametersDirty&&(e.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1),this._isBlendConstantsDirty&&(e.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1))},e}(),Ri=function(){function e(){this.samplingMode=-1,this._useMipMaps=!0,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._comparisonFunction=0}return Object.defineProperty(e.prototype,"wrapU",{get:function(){return this._cachedWrapU},set:function(e){this._cachedWrapU=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"wrapV",{get:function(){return this._cachedWrapV},set:function(e){this._cachedWrapV=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"wrapR",{get:function(){return this._cachedWrapR},set:function(e){this._cachedWrapR=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"anisotropicFilteringLevel",{get:function(){return this._cachedAnisotropicFilteringLevel},set:function(e){this._cachedAnisotropicFilteringLevel=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"comparisonFunction",{get:function(){return this._comparisonFunction},set:function(e){this._comparisonFunction=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useMipMaps",{get:function(){return this._useMipMaps},set:function(e){this._useMipMaps=e},enumerable:!1,configurable:!0}),e.prototype.setParameters=function(e,t,i,r,n,o){return void 0===e&&(e=u.TEXTURE_WRAP_ADDRESSMODE),void 0===t&&(t=u.TEXTURE_WRAP_ADDRESSMODE),void 0===i&&(i=u.TEXTURE_WRAP_ADDRESSMODE),void 0===r&&(r=1),void 0===n&&(n=u.TEXTURE_BILINEAR_SAMPLINGMODE),void 0===o&&(o=0),this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=r,this.samplingMode=n,this._comparisonFunction=o,this},e.prototype.compareSampler=function(e){return this._cachedWrapU===e._cachedWrapU&&this._cachedWrapV===e._cachedWrapV&&this._cachedWrapR===e._cachedWrapR&&this._cachedAnisotropicFilteringLevel===e._cachedAnisotropicFilteringLevel&&this.samplingMode===e.samplingMode&&this._comparisonFunction===e._comparisonFunction&&this._useMipMaps===e._useMipMaps},e}();!function(e){e[e.Unknown=0]="Unknown",e[e.Url=1]="Url",e[e.Temp=2]="Temp",e[e.Raw=3]="Raw",e[e.Dynamic=4]="Dynamic",e[e.RenderTarget=5]="RenderTarget",e[e.MultiRenderTarget=6]="MultiRenderTarget",e[e.Cube=7]="Cube",e[e.CubeRaw=8]="CubeRaw",e[e.CubePrefiltered=9]="CubePrefiltered",e[e.Raw3D=10]="Raw3D",e[e.Raw2DArray=11]="Raw2DArray",e[e.DepthStencil=12]="DepthStencil",e[e.CubeRawRGBD=13]="CubeRawRGBD",e[e.Depth=14]="Depth"}(Ti||(Ti={}));var Pi=function(e){function t(i,r,n){void 0===n&&(n=!1);var o=e.call(this)||this;return o.isReady=!1,o.isCube=!1,o.is3D=!1,o.is2DArray=!1,o.isMultiview=!1,o.url="",o.generateMipMaps=!1,o.samples=0,o.type=-1,o.format=-1,o.onLoadedObservable=new f,o.onErrorObservable=new f,o.onRebuildCallback=null,o.width=0,o.height=0,o.depth=0,o.baseWidth=0,o.baseHeight=0,o.baseDepth=0,o.invertY=!1,o._invertVScale=!1,o._associatedChannel=-1,o._source=Ti.Unknown,o._buffer=null,o._bufferView=null,o._bufferViewArray=null,o._bufferViewArrayArray=null,o._size=0,o._extension="",o._files=null,o._workingCanvas=null,o._workingContext=null,o._cachedCoordinatesMode=null,o._isDisabled=!1,o._compression=null,o._sphericalPolynomial=null,o._sphericalPolynomialPromise=null,o._sphericalPolynomialComputed=!1,o._lodGenerationScale=0,o._lodGenerationOffset=0,o._useSRGBBuffer=!1,o._creationFlags=0,o._lodTextureHigh=null,o._lodTextureMid=null,o._lodTextureLow=null,o._isRGBD=!1,o._linearSpecularLOD=!1,o._irradianceTexture=null,o._hardwareTexture=null,o._maxLodLevel=null,o._references=1,o._gammaSpace=null,o._premulAlpha=!1,o._dynamicTextureSource=null,o._engine=i,o._source=r,o._uniqueId=t._Counter++,n||(o._hardwareTexture=i._createHardwareTexture()),o}return m(t,e),Object.defineProperty(t.prototype,"useMipMaps",{get:function(){return this.generateMipMaps},set:function(e){this.generateMipMaps=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"uniqueId",{get:function(){return this._uniqueId},enumerable:!1,configurable:!0}),t.prototype._setUniqueId=function(e){this._uniqueId=e},t.prototype.getEngine=function(){return this._engine},Object.defineProperty(t.prototype,"source",{get:function(){return this._source},enumerable:!1,configurable:!0}),t.prototype.incrementReferences=function(){this._references++},t.prototype.updateSize=function(e,t,i){void 0===i&&(i=1),this._engine.updateTextureDimensions(this,e,t,i),this.width=e,this.height=t,this.depth=i,this.baseWidth=e,this.baseHeight=t,this.baseDepth=i,this._size=e*t*i},t.prototype._rebuild=function(){var e,t,i=this;if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){var r=this.onRebuildCallback(this),n=function(e){e._swapAndDie(i,!1),i.isReady=r.isReady};r.isAsync?r.proxy.then(n):n(r.proxy)}else{var o;switch(this.source){case Ti.Temp:break;case Ti.Url:return void(o=this._engine.createTexture(null!==(e=this._originalUrl)&&void 0!==e?e:this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,(function(e){e._swapAndDie(i,!1),i.isReady=!0}),null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer));case Ti.Raw:(o=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer))._swapAndDie(this,!1),this.isReady=!0;break;case Ti.Raw3D:(o=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type))._swapAndDie(this,!1),this.isReady=!0;break;case Ti.Raw2DArray:(o=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type))._swapAndDie(this,!1),this.isReady=!0;break;case Ti.Dynamic:(o=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode))._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case Ti.Cube:return void(o=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,(function(){o._swapAndDie(i,!1),i.isReady=!0}),null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer));case Ti.CubeRaw:(o=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,null!==(t=this._originalFormat)&&void 0!==t?t:this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression))._swapAndDie(this,!1),this.isReady=!0;break;case Ti.CubeRawRGBD:return;case Ti.CubePrefiltered:return void((o=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,(function(e){e&&e._swapAndDie(i,!1),i.isReady=!0}),null,this.format,this._extension))._sphericalPolynomial=this._sphericalPolynomial);case Ti.DepthStencil:case Ti.Depth:}}},t.prototype._swapAndDie=function(e,t){var i;void 0===t&&(t=!0),null===(i=this._hardwareTexture)||void 0===i||i.setUsage(e._source,this.generateMipMaps,this.is2DArray,this.isCube,this.is3D,this.width,this.height,this.depth),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);var r=this._engine.getLoadedTexturesCache(),n=r.indexOf(this);-1!==n&&r.splice(n,1),-1===(n=r.indexOf(e))&&r.push(e)},t.prototype.dispose=function(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)},t._Counter=0,t}(Ri);function Ii(e,t){if(ct()){var i=(t||window).requestAnimationFrame;if("function"==typeof i)return i(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}var Mi=function(){function e(e,t,i){var r,n,o,a,s,l,c,h,d,p,_,m=this;this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new Si,this._stencilStateComposer=new xi,this._stencilState=new Ai,this._alphaState=new Ci,this._alphaMode=u.ALPHA_ADD,this._alphaEquation=u.ALPHA_DISABLE,this._activeRequests=[],this._badOS=!1,this._badDesktopOS=!1,this._compatibilityMode=!0,this._internalTexturesCache=new Array,this._currentRenderTarget=null,this._boundTexturesCache={},this._activeChannel=0,this._currentTextureChannel=-1,this._viewportCached={x:0,y:0,z:0,w:0},this._isWebGPU=!1,this.onCanvasBlurObservable=new f,this.onCanvasFocusObservable=new f,this.onNewSceneAddedObservable=new f,this.onResizeObservable=new f,this.onCanvasPointerOutObservable=new f,this.disablePerformanceMonitorInBackground=!1,this.disableVertexArrayObjects=!1,this._frameId=0,this.hostInformation={isMobile:!1},this.isFullscreen=!1,this.enableOfflineSupport=!1,this.disableManifestCheck=!1,this.disableContextMenu=!0,this.currentRenderPassId=u.RENDERPASS_MAIN,this.isPointerLock=!1,this.postProcesses=[],this.canvasTabIndex=1,this._contextWasLost=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this._renderTargetWrapperCache=new Array,this._compiledEffects={},this._isDisposed=!1,this.scenes=[],this._virtualScenes=new Array,this.onBeforeTextureInitObservable=new f,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this._windowIsBackground=!1,this._boundRenderFunction=function(){return m._renderLoop()},this.onBeforeShaderCompilationObservable=new f,this.onAfterShaderCompilationObservable=new f,this.onBeginFrameObservable=new f,this.onEndFrameObservable=new f,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new f,this.onContextRestoredObservable=new f,this._name="",this.premultipliedAlpha=!0,this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._doNotHandleContextLost=!1,this.cullBackFaces=null,this._renderPassNames=["main"],this._fps=60,this._deltaTime=0,this._deterministicLockstep=!1,this._lockstepMaxSteps=4,this._timeStep=1/60,this.onDisposeObservable=new f,M.Instances.push(this),this.startTime=_t.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,I.SetMatrixPrecision(!!t.useHighPrecisionMatrix),ut()&&navigator.userAgent&&(this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),this.adaptToDeviceRatio=null!=i&&i,t.antialias=null!=e?e:t.antialias,t.deterministicLockstep=null!==(r=t.deterministicLockstep)&&void 0!==r&&r,t.lockstepMaxSteps=null!==(n=t.lockstepMaxSteps)&&void 0!==n?n:4,t.timeStep=null!==(o=t.timeStep)&&void 0!==o?o:1/60,t.audioEngine=null===(a=t.audioEngine)||void 0===a||a,t.stencil=null===(s=t.stencil)||void 0===s||s,this._audioContext=null!==(c=null===(l=t.audioEngineOptions)||void 0===l?void 0:l.audioContext)&&void 0!==c?c:null,this._audioDestination=null!==(d=null===(h=t.audioEngineOptions)||void 0===h?void 0:h.audioDestination)&&void 0!==d?d:null,this.premultipliedAlpha=null===(p=t.premultipliedAlpha)||void 0===p||p,this._doNotHandleContextLost=!!t.doNotHandleContextLost,this._isStencilEnable=!!t.stencil,this.useExactSrgbConversions=null!==(_=t.useExactSrgbConversions)&&void 0!==_&&_;var g=ct()&&window.devicePixelRatio||1,v=t.limitDeviceRatio||g;i=i||t.adaptToDeviceRatio||!1,this._hardwareScalingLevel=i?1/Math.min(v,g):1,this._lastDevicePixelRatio=g,this._creationOptions=t}return Object.defineProperty(e.prototype,"frameId",{get:function(){return this._frameId},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isWebGPU",{get:function(){return this._isWebGPU},enumerable:!1,configurable:!0}),e.prototype._getShaderProcessor=function(e){return this._shaderProcessor},Object.defineProperty(e.prototype,"shaderPlatformName",{get:function(){return this._shaderPlatformName},enumerable:!1,configurable:!0}),e.prototype._clearEmptyResources=function(){this._emptyTexture=null,this._emptyCubeTexture=null,this._emptyTexture3D=null,this._emptyTexture2DArray=null},Object.defineProperty(e.prototype,"useReverseDepthBuffer",{get:function(){return this._useReverseDepthBuffer},set:function(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,this._depthCullingState.depthFunc=e?u.GEQUAL:u.LEQUAL)},enumerable:!1,configurable:!0}),e.prototype.setColorWrite=function(e){e!==this._colorWrite&&(this._colorWriteChanged=!0,this._colorWrite=e)},e.prototype.getColorWrite=function(){return this._colorWrite},Object.defineProperty(e.prototype,"depthCullingState",{get:function(){return this._depthCullingState},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"alphaState",{get:function(){return this._alphaState},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stencilState",{get:function(){return this._stencilState},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stencilStateComposer",{get:function(){return this._stencilStateComposer},enumerable:!1,configurable:!0}),e.prototype._getGlobalDefines=function(e){if(e)return this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);var t="";return this.isNDCHalfZRange&&(t+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(t&&(t+="\n"),t+="#define USE_REVERSE_DEPTHBUFFER"),this.useExactSrgbConversions&&(t&&(t+="\n"),t+="#define USE_EXACT_SRGB_CONVERSIONS"),t},e.prototype._rebuildInternalTextures=function(){for(var e=0,t=this._internalTexturesCache.slice();e<t.length;e++)t[e]._rebuild()},e.prototype._rebuildRenderTargetWrappers=function(){for(var e=0,t=this._renderTargetWrapperCache.slice();e<t.length;e++)t[e]._rebuild()},e.prototype._rebuildEffects=function(){for(var e in this._compiledEffects){var t=this._compiledEffects[e];t._pipelineContext=null,t._prepareEffect()}Ei.ResetCache()},e.prototype._rebuildGraphicsResources=function(){var e;this.wipeCaches(!0),this._rebuildEffects(),null===(e=this._rebuildComputeEffects)||void 0===e||e.call(this),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)},e.prototype._flagContextRestored=function(){ae.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1},e.prototype._restoreEngineAfterContextLost=function(e){var t=this;setTimeout((function(){return y(t,void 0,void 0,(function(){var t,i,r,n;return b(this,(function(o){switch(o.label){case 0:return this._clearEmptyResources(),t=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,r=this._depthCullingState.depthMask,n=this._stencilState.stencilTest,[4,e()];case 1:return o.sent(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=r,this._stencilState.stencilTest=n,this._flagContextRestored(),[2]}}))}))}),0)},Object.defineProperty(e.prototype,"isDisposed",{get:function(){return this._isDisposed},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"snapshotRendering",{get:function(){return!1},set:function(e){},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"snapshotRenderingMode",{get:function(){return u.SNAPSHOTRENDERING_STANDARD},set:function(e){},enumerable:!1,configurable:!0}),e.prototype.getClassName=function(){return"AbstractEngine"},Object.defineProperty(e.prototype,"emptyTexture",{get:function(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,u.TEXTUREFORMAT_RGBA,!1,!1,u.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"emptyTexture3D",{get:function(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,u.TEXTUREFORMAT_RGBA,!1,!1,u.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture3D},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"emptyTexture2DArray",{get:function(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,u.TEXTUREFORMAT_RGBA,!1,!1,u.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture2DArray},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"emptyCubeTexture",{get:function(){if(!this._emptyCubeTexture){var e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,u.TEXTUREFORMAT_RGBA,u.TEXTURETYPE_UNSIGNED_INT,!1,!1,u.TEXTURE_NEAREST_SAMPLINGMODE)}return this._emptyCubeTexture},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"activeRenderLoops",{get:function(){return this._activeRenderLoops},enumerable:!1,configurable:!0}),e.prototype.stopRenderLoop=function(e){if(!e)return this._activeRenderLoops.length=0,void this._cancelFrame();var t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),0==this._activeRenderLoops.length&&this._cancelFrame())},e.prototype._cancelFrame=function(){if(0!==this._frameHandler){var e=this._frameHandler;if(this._frameHandler=0,ct()){var t=(this.getHostWindow()||window).cancelAnimationFrame;if("function"==typeof t)return t(e)}else if("function"==typeof cancelAnimationFrame)return cancelAnimationFrame(e);return clearTimeout(e)}},e.prototype.beginFrame=function(){this.onBeginFrameObservable.notifyObservers(this)},e.prototype.endFrame=function(){this._frameId++,this.onEndFrameObservable.notifyObservers(this)},e.prototype._renderLoop=function(){if(this._frameHandler=0,!this._contextWasLost){var e=!0;if((this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e){this.beginFrame();for(var t=0;t<this._activeRenderLoops.length;t++)(0,this._activeRenderLoops[t])();this.endFrame()}}this._activeRenderLoops.length>0&&0===this._frameHandler&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))},e.prototype._queueNewFrame=function(e,t){return Ii(e,t)},e.prototype.runRenderLoop=function(e){-1===this._activeRenderLoops.indexOf(e)&&(this._activeRenderLoops.push(e),1===this._activeRenderLoops.length&&0===this._frameHandler&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))},e.prototype.getDepthBuffer=function(){return this._depthCullingState.depthTest},e.prototype.setDepthBuffer=function(e){this._depthCullingState.depthTest=e},e.prototype.setZOffset=function(e){this._depthCullingState.zOffset=this.useReverseDepthBuffer?-e:e},e.prototype.getZOffset=function(){var e=this._depthCullingState.zOffset;return this.useReverseDepthBuffer?-e:e},e.prototype.setZOffsetUnits=function(e){this._depthCullingState.zOffsetUnits=this.useReverseDepthBuffer?-e:e},e.prototype.getZOffsetUnits=function(){var e=this._depthCullingState.zOffsetUnits;return this.useReverseDepthBuffer?-e:e},e.prototype.getHostWindow=function(){return ct()?this._renderingCanvas&&this._renderingCanvas.ownerDocument&&this._renderingCanvas.ownerDocument.defaultView?this._renderingCanvas.ownerDocument.defaultView:window:null},Object.defineProperty(e.prototype,"compatibilityMode",{get:function(){return this._compatibilityMode},set:function(e){this._compatibilityMode=!0},enumerable:!1,configurable:!0}),e.prototype._rebuildTextures=function(){for(var e=0,t=this.scenes;e<t.length;e++)t[e]._rebuildTextures();for(var i=0,r=this._virtualScenes;i<r.length;i++)r[i]._rebuildTextures()},e.prototype._releaseRenderTargetWrapper=function(e){var t=this._renderTargetWrapperCache.indexOf(e);-1!==t&&this._renderTargetWrapperCache.splice(t,1)},Object.defineProperty(e.prototype,"currentViewport",{get:function(){return this._cachedViewport},enumerable:!1,configurable:!0}),e.prototype.setViewport=function(e,t,i){var r=t||this.getRenderWidth(),n=i||this.getRenderHeight(),o=e.x||0,a=e.y||0;this._cachedViewport=e,this._viewport(o*r,a*n,r*e.width,n*e.height)},e.prototype.createCanvasImage=function(){return document.createElement("img")},Object.defineProperty(e.prototype,"description",{get:function(){var e=this.name+this.version;return this._caps.parallelShaderCompile&&(e+=" - Parallel shader compilation"),e},enumerable:!1,configurable:!0}),e.prototype._createTextureBase=function(t,i,r,n,o,a,s,l,c,h,d,p,f,_,m,g){var v=this;void 0===o&&(o=u.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===a&&(a=null),void 0===s&&(s=null),void 0===h&&(h=null),void 0===d&&(d=null),void 0===p&&(p=null),void 0===f&&(f=null);var y="data:"===(t=t||"").substr(0,5),b="blob:"===t.substr(0,5),T=y&&-1!==t.indexOf(";base64,"),E=d||new Pi(this,Ti.Url);E!==d&&(E.label=t.substring(0,60));var S=t;!this._transformTextureUrl||T||d||h||(t=this._transformTextureUrl(t)),S!==t&&(E._originalUrl=S);var x=t.lastIndexOf("."),A=f||(x>-1?t.substring(x).toLowerCase():""),C=null;A.indexOf("?")>-1&&(A=A.split("?")[0]);for(var R=0,P=e._TextureLoaders;R<P.length;R++){var I=P[R];if(I.canLoad(A,_)){C=I;break}}n&&n.addPendingData(E),E.url=t,E.generateMipMaps=!i,E.samplingMode=o,E.invertY=r,E._useSRGBBuffer=this._getUseSRGBBuffer(!!g,i),this._doNotHandleContextLost||(E._buffer=h);var O=null;a&&!d&&(O=E.onLoadedObservable.add(a)),d||this._internalTexturesCache.push(E);var D=function(e,r){n&&n.removePendingData(E),t===S?(O&&E.onLoadedObservable.remove(O),M.UseFallbackTexture&&t!==M.FallbackTexture&&v._createTextureBase(M.FallbackTexture,i,E.invertY,n,o,null,s,l,c,h,E),e=(e||"Unknown error")+(M.UseFallbackTexture?" - Fallback texture was used":""),E.onErrorObservable.notifyObservers({message:e,exception:r}),s&&s(e,r)):(ae.Warn("Failed to load ".concat(t,", falling back to ").concat(S)),v._createTextureBase(S,i,E.invertY,n,o,a,s,l,c,h,E,p,f,_,m,g))};if(C){var N=function(e){C.loadData(e,E,(function(e,t,i,r,a,s){s?D("TextureLoader failed to load data"):l(E,A,n,{width:e,height:t},E.invertY,!i,r,(function(){return a(),!1}),o)}),m)};h?h instanceof ArrayBuffer?N(new Uint8Array(h)):ArrayBuffer.isView(h)?N(h):s&&s("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(t,(function(e){return N(new Uint8Array(e))}),void 0,n?n.offlineProvider:void 0,!0,(function(e,t){D("Unable to load "+(e&&e.responseURL,t))}))}else{var F=function(e){b&&!v._doNotHandleContextLost&&(E._buffer=e),l(E,A,n,e,E.invertY,i,!1,c,o)};!y||T?h&&("string"==typeof h.decoding||h.close)?F(h):e._FileToolsLoadImage(t||"",F,D,n?n.offlineProvider:null,_,E.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof h||h instanceof ArrayBuffer||ArrayBuffer.isView(h)||h instanceof Blob?e._FileToolsLoadImage(h,F,D,n?n.offlineProvider:null,_,E.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):h&&F(h)}return E},e.prototype._rebuildBuffers=function(){for(var e=0,t=this._uniformBuffers;e<t.length;e++)t[e]._rebuildAfterContextLost()},Object.defineProperty(e.prototype,"_shouldUseHighPrecisionShader",{get:function(){return!(!this._caps.highPrecisionShaderSupported||!this._highPrecisionShadersAllowed)},enumerable:!1,configurable:!0}),e.prototype.getHostDocument=function(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:ht()?document:null},e.prototype.getLoadedTexturesCache=function(){return this._internalTexturesCache},e.prototype.clearInternalTexturesCache=function(){this._internalTexturesCache.length=0},e.prototype.getCaps=function(){return this._caps},e.prototype.resetTextureCache=function(){for(var e in this._boundTexturesCache)Object.prototype.hasOwnProperty.call(this._boundTexturesCache,e)&&(this._boundTexturesCache[e]=null);this._currentTextureChannel=-1},Object.defineProperty(e.prototype,"name",{get:function(){return this._name},set:function(e){this._name=e},enumerable:!1,configurable:!0}),Object.defineProperty(e,"NpmPackage",{get:function(){return"babylonjs@7.6.1"},enumerable:!1,configurable:!0}),Object.defineProperty(e,"Version",{get:function(){return"7.6.1"},enumerable:!1,configurable:!0}),e.prototype.getRenderingCanvas=function(){return this._renderingCanvas},e.prototype.getAudioContext=function(){return this._audioContext},e.prototype.getAudioDestination=function(){return this._audioDestination},e.prototype.setHardwareScalingLevel=function(e){this._hardwareScalingLevel=e,this.resize()},e.prototype.getHardwareScalingLevel=function(){return this._hardwareScalingLevel},Object.defineProperty(e.prototype,"doNotHandleContextLost",{get:function(){return this._doNotHandleContextLost},set:function(e){this._doNotHandleContextLost=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isStencilEnable",{get:function(){return this._isStencilEnable},enumerable:!1,configurable:!0}),e.prototype.getCreationOptions=function(){return this._creationOptions},e.prototype.resize=function(e){var t,i;if(void 0===e&&(e=!1),this.adaptToDeviceRatio){var r=ct()&&window.devicePixelRatio||1,n=this._lastDevicePixelRatio/r;this._lastDevicePixelRatio=r,this._hardwareScalingLevel*=n}if(ct()&&ht())if(this._renderingCanvas){var o=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||o.width||this._renderingCanvas.width||100,i=this._renderingCanvas.clientHeight||o.height||this._renderingCanvas.height||100}else t=window.innerWidth,i=window.innerHeight;else t=this._renderingCanvas?this._renderingCanvas.width:100,i=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,i/this._hardwareScalingLevel,e)},e.prototype.setSize=function(e,t,i){if(void 0===i&&(i=!1),!this._renderingCanvas)return!1;if(e|=0,t|=0,!i&&this._renderingCanvas.width===e&&this._renderingCanvas.height===t)return!1;if(this._renderingCanvas.width=e,this._renderingCanvas.height=t,this.scenes){for(var r=0;r<this.scenes.length;r++)for(var n=this.scenes[r],o=0;o<n.cameras.length;o++)n.cameras[o]._currentRenderId=0;this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this)}return!0},e.prototype._sharedInit=function(e){this._renderingCanvas=e},e.prototype._setupMobileChecks=function(){var e=this;navigator&&navigator.userAgent&&(this._checkForMobile=function(){var t=navigator.userAgent;e.hostInformation.isMobile=-1!==t.indexOf("Mobile")||-1!==t.indexOf("Mac")&&ht()&&"ontouchend"in document},this._checkForMobile(),ct()&&window.addEventListener("resize",this._checkForMobile))},e.prototype.createVideoElement=function(e){return document.createElement("video")},e.prototype._reportDrawCall=function(e){var t;void 0===e&&(e=1),null===(t=this._drawCalls)||void 0===t||t.addCount(e,!1)},e.prototype.getFps=function(){return this._fps},e.prototype.getDeltaTime=function(){return this._deltaTime},e.prototype.isDeterministicLockStep=function(){return this._deterministicLockstep},e.prototype.getLockstepMaxSteps=function(){return this._lockstepMaxSteps},e.prototype.getTimeStep=function(){return 1e3*this._timeStep},e.prototype._createImageBitmapFromSource=function(e,t){throw new Error("createImageBitmapFromSource is not implemented")},e.prototype.createImageBitmap=function(e,t){return createImageBitmap(e,t)},e.prototype.resizeImageBitmap=function(e,t,i){throw new Error("resizeImageBitmap is not implemented")},e.prototype.getFontOffset=function(e){throw new Error("getFontOffset is not implemented")},e._CreateCanvas=function(e,t){if("undefined"==typeof document)return new OffscreenCanvas(e,t);var i=document.createElement("canvas");return i.width=e,i.height=t,i},e.prototype.createCanvas=function(t,i){return e._CreateCanvas(t,i)},e._FileToolsLoadImage=function(e,t,i,r,n,o){throw He("FileTools")},e.prototype._loadFile=function(e,t,i,r,n,o){var a=this,s=kt(e,t,i,r,n,o);return this._activeRequests.push(s),s.onCompleteObservable.add((function(){var e=a._activeRequests.indexOf(s);-1!==e&&a._activeRequests.splice(e,1)})),s},e._FileToolsLoadFile=function(e,t,i,r,n,o){if(Ut.loadFile)return Ut.loadFile(e,t,i,r,n,o);throw He("FileTools")},e.prototype.dispose=function(){var e;for(this.hideLoadingUI(),this.releaseEffects(),this._isDisposed=!0,this.stopRenderLoop(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._renderingCanvas=null,this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(;this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();null===(e=this.releaseComputeEffects)||void 0===e||e.call(this),Ei.ResetCache();for(var t=0,i=this._activeRequests;t<i.length;t++)i[t].abort();this._boundRenderFunction=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onNewSceneAddedObservable.clear(),ct()&&window.removeEventListener("resize",this._checkForMobile);var r=M.Instances.indexOf(this);r>=0&&M.Instances.splice(r,1),M.Instances.length||M.OnEnginesDisposedObservable.notifyObservers(this),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()},e.DefaultLoadingScreenFactory=function(e){throw He("LoadingScreen")},e._TextureLoaders=[],e._RenderPassIdCounter=0,e._RescalePostProcessFactory=null,e}(),Oi=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i),Di=function(e){function t(i,r){var n=e.call(this,i,yt.LoadFileError)||this;return n.name="LoadFileError",vt._setPrototypeOf(n,t.prototype),r instanceof Je?n.request=r:n.file=r,n}return m(t,e),t}(bt),Ni=function(e){function t(i,r){var n=e.call(this,i,yt.RequestFileError)||this;return n.request=r,n.name="RequestFileError",vt._setPrototypeOf(n,t.prototype),n}return m(t,e),t}(bt),Fi=function(e){function t(i,r){var n=e.call(this,i,yt.ReadFileError)||this;return n.file=r,n.name="ReadFileError",vt._setPrototypeOf(n,t.prototype),n}return m(t,e),t}(bt),Li={DefaultRetryStrategy:gt.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:function(e){return e},ScriptBaseUrl:"",ScriptPreprocessUrl:function(e){return e},CleanUrl:function(e){return e.replace(/#/gm,"%23")}},wi=function(e,t){if((!e||0!==e.indexOf("data:"))&&Li.CorsBehavior)if("string"==typeof Li.CorsBehavior||Li.CorsBehavior instanceof String)t.crossOrigin=Li.CorsBehavior;else{var i=Li.CorsBehavior(e);i&&(t.crossOrigin=i)}},Bi=function(e,t,i,r,n,o){void 0===n&&(n="");var a,s=M.LastCreatedEngine;if("undefined"==typeof HTMLImageElement&&!(null==s?void 0:s._features.forceBitmapOverHTMLImageElement))return i("LoadImage is only supported in web or BabylonNative environments."),null;var l=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(a=URL.createObjectURL(new Blob([e],{type:n})),l=!0):a="data:".concat(n,";base64,")+xt(e):e instanceof Blob?(a=URL.createObjectURL(e),l=!0):(a=Li.CleanUrl(e),a=Li.PreprocessUrl(e));var c=function(t){if(i){var r=a||e.toString();i("Error while trying to load image: ".concat(0===r.indexOf("http")||r.length<=128?r:r.slice(0,128)+"..."),t)}};if(null==s?void 0:s._features.forceBitmapOverHTMLImageElement)return Vi(a,(function(r){s.createImageBitmap(new Blob([r],{type:n}),g({premultiplyAlpha:"none"},o)).then((function(e){t(e),l&&URL.revokeObjectURL(a)})).catch((function(t){i&&i("Error while trying to load image: "+e,t)}))}),void 0,r||void 0,!0,(function(e,t){c(t)})),null;var u=new Image;wi(a,u);var h=[],d=function(){h.forEach((function(e){e.target.removeEventListener(e.name,e.handler)})),h.length=0};h.push({target:u,name:"load",handler:function(){d(),t(u),l&&u.src&&URL.revokeObjectURL(u.src)}}),h.push({target:u,name:"error",handler:function(e){d(),c(e),l&&u.src&&URL.revokeObjectURL(u.src)}}),h.push({target:document,name:"securitypolicyviolation",handler:function(e){if(e.blockedURI===u.src){d();var t=new Error("CSP violation of policy ".concat(e.effectiveDirective," ").concat(e.blockedURI,". Current policy is ").concat(e.originalPolicy));M.UseFallbackTexture=!1,c(t),l&&u.src&&URL.revokeObjectURL(u.src),u.src=""}}}),h.forEach((function(e){e.target.addEventListener(e.name,e.handler)}));var p="blob:"===a.substring(0,5),f="data:"===a.substring(0,5),_=function(){p||f||!Je.IsCustomRequestAvailable?u.src=a:Vi(a,(function(e,t,i){var r=new Blob([e],{type:!n&&i?i:n}),o=URL.createObjectURL(r);l=!0,u.src=o}),void 0,r||void 0,!0,(function(e,t){c(t)}))};if(!p&&!f&&r&&r.enableTexturesOffline)r.open((function(){r&&r.loadImage(a,u)}),_);else{if(-1!==a.indexOf("file:")){var m=decodeURIComponent(a.substring(5).toLowerCase());if(mt.FilesToLoad[m]&&"undefined"!=typeof URL){try{var v=void 0;try{v=URL.createObjectURL(mt.FilesToLoad[m])}catch(e){v=URL.createObjectURL(mt.FilesToLoad[m])}u.src=v,l=!0}catch(e){u.src=""}return u}}_()}return u},Ui=function(e,t,i,r,n){var o=new FileReader,a={onCompleteObservable:new f,abort:function(){return o.abort()}};return o.onloadend=function(){return a.onCompleteObservable.notifyObservers(a)},n&&(o.onerror=function(){n(new Fi("Unable to read ".concat(e.name),e))}),o.onload=function(e){t(e.target.result)},i&&(o.onprogress=i),r?o.readAsArrayBuffer(e):o.readAsText(e),a},Vi=function(e,t,i,r,n,o,a){if(e.name)return Ui(e,t,i,n,o?function(e){o(void 0,e)}:void 0);var s=e;if(-1!==s.indexOf("file:")){var l=decodeURIComponent(s.substring(5).toLowerCase());0===l.indexOf("./")&&(l=l.substring(2));var c=mt.FilesToLoad[l];if(c)return Ui(c,t,i,n,o?function(e){return o(void 0,new Di(e.message,e.file))}:void 0)}var u=Wi(s),h=u.match,d=u.type;if(h){var p={onCompleteObservable:new f,abort:function(){return function(){}}};try{var _=n?Hi(s):ji(s);t(_,void 0,d)}catch(e){o?o(void 0,e):ae.Error(e.message||"Failed to parse the Data URL")}return si.SetImmediate((function(){p.onCompleteObservable.notifyObservers(p)})),p}return ki(s,(function(e,i){t(e,null==i?void 0:i.responseURL,null==i?void 0:i.getResponseHeader("content-type"))}),i,r,n,o?function(e){o(e.request,new Di(e.message,e.request))}:void 0,a)},ki=function(e,t,i,r,n,o,a){e=Li.CleanUrl(e),e=Li.PreprocessUrl(e);var s=Li.BaseUrl+e,l=!1,c={onCompleteObservable:new f,abort:function(){return l=!0}},u=function(){var e,r=new Je,u=null,h=function(){r&&(i&&r.removeEventListener("progress",i),e&&r.removeEventListener("readystatechange",e),r.removeEventListener("loadend",d))},d=function(){h(),c.onCompleteObservable.notifyObservers(c),c.onCompleteObservable.clear(),i=void 0,e=null,d=null,o=void 0,a=void 0,t=void 0};c.abort=function(){l=!0,d&&d(),r&&r.readyState!==(XMLHttpRequest.DONE||4)&&r.abort(),null!==u&&(clearTimeout(u),u=null),r=null};var p=function(e){var t=e.message||"Unknown error";o&&r?o(new Ni(t,r)):ae.Error(t)},f=function(c){if(r){if(r.open("GET",s),a)try{a(r)}catch(e){return void p(e)}n&&(r.responseType="arraybuffer"),i&&r.addEventListener("progress",i),d&&r.addEventListener("loadend",d),e=function(){if(!l&&r&&r.readyState===(XMLHttpRequest.DONE||4)){if(e&&r.removeEventListener("readystatechange",e),r.status>=200&&r.status<300||0===r.status&&(!ct()||Gi())){try{t&&t(n?r.response:r.responseText,r)}catch(e){p(e)}return}var i=Li.DefaultRetryStrategy;if(i){var a=i(s,r,c);if(-1!==a)return h(),r=new Je,void(u=setTimeout((function(){return f(c+1)}),a))}var d=new Ni("Error status: "+r.status+" "+r.statusText+" - Unable to load "+s,r);o&&o(d)}},r.addEventListener("readystatechange",e),r.send()}};f(0)};if(r&&r.enableSceneOffline){var h=function(e){e&&e.status>400?o&&o(e):u()};r.open((function(){r&&r.loadFile(Li.BaseUrl+e,(function(e){!l&&t&&t(e),c.onCompleteObservable.notifyObservers(c)}),i?function(e){!l&&i&&i(e)}:void 0,h,n)}),h)}else u();return c},Gi=function(){return"undefined"!=typeof location&&"file:"===location.protocol},zi=function(e){return Oi.test(e)},Wi=function(e){var t=Oi.exec(e);return null===t||0===t.length?{match:!1,type:""}:{match:!0,type:t[0].replace("data:","").replace("base64,","")}};function Hi(e){return Ct(e.split(",")[1])}var Xi,ji=function(e){return At(e.split(",")[1])};Mi._FileToolsLoadImage=Bi,Ut.loadFile=Vi,ai.loadFile=Vi;var Yi=function(e,t,i,r,n,o,a,s,l,c){Xi={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:i.DefaultRetryStrategy,BaseUrl:i.BaseUrl,CorsBehavior:i.CorsBehavior,PreprocessUrl:i.PreprocessUrl,IsBase64DataUrl:r,IsFileURL:n,LoadFile:o,LoadImage:a,ReadFile:s,RequestFile:l,SetCorsBehavior:c},Object.defineProperty(Xi,"DefaultRetryStrategy",{get:function(){return i.DefaultRetryStrategy},set:function(e){i.DefaultRetryStrategy=e}}),Object.defineProperty(Xi,"BaseUrl",{get:function(){return i.BaseUrl},set:function(e){i.BaseUrl=e}}),Object.defineProperty(Xi,"PreprocessUrl",{get:function(){return i.PreprocessUrl},set:function(e){i.PreprocessUrl=e}}),Object.defineProperty(Xi,"CorsBehavior",{get:function(){return i.CorsBehavior},set:function(e){i.CorsBehavior=e}})};Yi(Hi,ji,Li,zi,Gi,Vi,Bi,Ui,ki,wi);var Ki=function(){function e(){}return e.Instantiate=function(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];var t=s(e);if(t)return t;ae.Warn(e+" not found, you may have missed an import.");for(var i=e.split("."),r=window||this,n=0,o=i.length;n<o;n++)r=r[i[n]];return"function"!=typeof r?null:r},e.RegisteredExternalClasses={},e}();function Qi(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}var qi={RandomId:Qi};function Zi(e){var t=1;do{t*=2}while(t<e);return t===e}function Ji(e,t,i){return e*(1-i)+t*i}function $i(e){var t=er(e),i=tr(e);return t-e>e-i?i:t}function er(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}function tr(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}function ir(e,t,i){var r;switch(void 0===i&&(i=u.SCALEMODE_NEAREST),i){case u.SCALEMODE_FLOOR:r=tr(e);break;case u.SCALEMODE_NEAREST:r=$i(e);break;case u.SCALEMODE_CEILING:default:r=er(e)}return Math.min(r,t)}var rr=function(){function e(){}return Object.defineProperty(e,"BaseUrl",{get:function(){return Li.BaseUrl},set:function(e){Li.BaseUrl=e},enumerable:!1,configurable:!0}),Object.defineProperty(e,"CleanUrl",{get:function(){return Li.CleanUrl},set:function(e){Li.CleanUrl=e},enumerable:!1,configurable:!0}),e.IsAbsoluteUrl=function(e){return 0===e.indexOf("//")||-1!==e.indexOf("://")&&-1!==e.indexOf(".")&&-1!==e.indexOf("/")&&!(e.indexOf(":")>e.indexOf("/"))&&(e.indexOf("://")<e.indexOf(".")||0===e.indexOf("data:")||0===e.indexOf("blob:"))},Object.defineProperty(e,"ScriptBaseUrl",{get:function(){return Li.ScriptBaseUrl},set:function(e){Li.ScriptBaseUrl=e},enumerable:!1,configurable:!0}),Object.defineProperty(e,"ScriptPreprocessUrl",{get:function(){return Li.ScriptPreprocessUrl},set:function(e){Li.ScriptPreprocessUrl=e},enumerable:!1,configurable:!0}),Object.defineProperty(e,"DefaultRetryStrategy",{get:function(){return Li.DefaultRetryStrategy},set:function(e){Li.DefaultRetryStrategy=e},enumerable:!1,configurable:!0}),Object.defineProperty(e,"CorsBehavior",{get:function(){return Li.CorsBehavior},set:function(e){Li.CorsBehavior=e},enumerable:!1,configurable:!0}),Object.defineProperty(e,"UseFallbackTexture",{get:function(){return M.UseFallbackTexture},set:function(e){M.UseFallbackTexture=e},enumerable:!1,configurable:!0}),Object.defineProperty(e,"RegisteredExternalClasses",{get:function(){return Ki.RegisteredExternalClasses},set:function(e){Ki.RegisteredExternalClasses=e},enumerable:!1,configurable:!0}),Object.defineProperty(e,"fallbackTexture",{get:function(){return M.FallbackTexture},set:function(e){M.FallbackTexture=e},enumerable:!1,configurable:!0}),e.FetchToRef=function(e,t,i,r,n,o){var a=4*((Math.abs(e)*i%i|0)+(Math.abs(t)*r%r|0)*i);o.r=n[a]/255,o.g=n[a+1]/255,o.b=n[a+2]/255,o.a=n[a+3]/255},e.Mix=function(e,t,i){return 0},e.Instantiate=function(e){return Ki.Instantiate(e)},e.SetImmediate=function(e){si.SetImmediate(e)},e.IsExponentOfTwo=function(e){return!0},e.FloatRound=function(e){return Math.fround(e)},e.GetFilename=function(e){var t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)},e.GetFolderPath=function(e,t){void 0===t&&(t=!1);var i=e.lastIndexOf("/");return i<0?t?e:"":e.substring(0,i+1)},e.ToDegrees=function(e){return 180*e/Math.PI},e.ToRadians=function(e){return e*Math.PI/180},e.SmoothAngleChange=function(e,t,i){void 0===i&&(i=.9);var r=this.ToRadians(e),n=this.ToRadians(t);return this.ToDegrees(Math.atan2((1-i)*Math.sin(n)+i*Math.sin(r),(1-i)*Math.cos(n)+i*Math.cos(r)))},e.MakeArray=function(e,t){return!0===t||void 0!==e&&null!=e?Array.isArray(e)?e:[e]:null},e.GetPointerPrefix=function(e){var t="pointer";return ct()&&!window.PointerEvent&&(t="mouse"),!e._badDesktopOS||e._badOS||document&&"ontouchend"in document||(t="mouse"),t},e.SetCorsBehavior=function(e,t){wi(e,t)},e.SetReferrerPolicyBehavior=function(e,t){t.referrerPolicy=e},Object.defineProperty(e,"PreprocessUrl",{get:function(){return Li.PreprocessUrl},set:function(e){Li.PreprocessUrl=e},enumerable:!1,configurable:!0}),e.LoadImage=function(e,t,i,r,n,o){return Bi(e,t,i,r,n,o)},e.LoadFile=function(e,t,i,r,n,o){return Vi(e,t,i,r,n,o)},e.LoadFileAsync=function(e,t){return void 0===t&&(t=!0),new Promise((function(i,r){Vi(e,(function(e){i(e)}),void 0,void 0,t,(function(e,t){r(t)}))}))},e.GetBabylonScriptURL=function(t,i){if(!t)return"";if(e.ScriptBaseUrl&&t.startsWith(e._DefaultCdnUrl)){var r="/"===e.ScriptBaseUrl[e.ScriptBaseUrl.length-1]?e.ScriptBaseUrl.substring(0,e.ScriptBaseUrl.length-1):e.ScriptBaseUrl;t=t.replace(e._DefaultCdnUrl,r)}return t=e.ScriptPreprocessUrl(t),i&&(t=e.GetAbsoluteUrl(t)),t},e.LoadBabylonScript=function(t,i,r,n){t=e.GetBabylonScriptURL(t),e.LoadScript(t,i,r)},e.LoadBabylonScriptAsync=function(t){return t=e.GetBabylonScriptURL(t),e.LoadScriptAsync(t)},e.LoadScript=function(e,t,i,r){if("function"!=typeof importScripts)if(ct()){var n=document.getElementsByTagName("head")[0],o=document.createElement("script");o.setAttribute("type","text/javascript"),o.setAttribute("src",e),r&&(o.id=r),o.onload=function(){t&&t()},o.onerror=function(t){i&&i("Unable to load script '".concat(e,"'"),t)},n.appendChild(o)}else null==i||i("Cannot load script '".concat(e,"' outside of a window or a worker"));else try{importScripts(e),t()}catch(t){null==i||i("Unable to load script '".concat(e,"' in worker"),t)}},e.LoadScriptAsync=function(e,t){var i=this;return new Promise((function(r,n){i.LoadScript(e,(function(){r()}),(function(e,t){n(t||new Error(e))}),t)}))},e.ReadFileAsDataURL=function(e,t,i){var r=new FileReader,n={onCompleteObservable:new f,abort:function(){return r.abort()}};return r.onloadend=function(){n.onCompleteObservable.notifyObservers(n)},r.onload=function(e){t(e.target.result)},r.onprogress=i,r.readAsDataURL(e),n},e.ReadFile=function(e,t,i,r,n){return Ui(e,t,i,r,n)},e.FileAsURL=function(e){var t=new Blob([e]);return window.URL.createObjectURL(t)},e.Format=function(e,t){return void 0===t&&(t=2),e.toFixed(t)},e.DeepCopy=function(e,t,i,r){ye.DeepCopy(e,t,i,r)},e.IsEmpty=function(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0},e.RegisterTopRootEvents=function(e,t){for(var i=0;i<t.length;i++){var r=t[i];e.addEventListener(r.name,r.handler,!1);try{window.parent&&window.parent.addEventListener(r.name,r.handler,!1)}catch(e){}}},e.UnregisterTopRootEvents=function(e,t){for(var i=0;i<t.length;i++){var r=t[i];e.removeEventListener(r.name,r.handler);try{e.parent&&e.parent.removeEventListener(r.name,r.handler)}catch(e){}}},e.DumpFramebuffer=function(e,t,i,r,n,o,a){return void 0===n&&(n="image/png"),y(this,void 0,void 0,(function(){return b(this,(function(e){throw He("DumpTools")}))}))},e.DumpData=function(e,t,i,r,n,o,a,s,l){throw void 0===n&&(n="image/png"),void 0===a&&(a=!1),void 0===s&&(s=!1),He("DumpTools")},e.DumpDataAsync=function(e,t,i,r,n,o,a,s){throw void 0===r&&(r="image/png"),void 0===o&&(o=!1),void 0===a&&(a=!1),He("DumpTools")},e._IsOffScreenCanvas=function(e){return void 0!==e.convertToBlob},e.ToBlob=function(t,i,r,n){void 0===r&&(r="image/png"),e._IsOffScreenCanvas(t)||t.toBlob||(t.toBlob=function(e,t,i){var r=this;setTimeout((function(){for(var n=atob(r.toDataURL(t,i).split(",")[1]),o=n.length,a=new Uint8Array(o),s=0;s<o;s++)a[s]=n.charCodeAt(s);e(new Blob([a]))}))}),e._IsOffScreenCanvas(t)?t.convertToBlob({type:r,quality:n}).then((function(e){return i(e)})):t.toBlob((function(e){i(e)}),r,n)},e.DownloadBlob=function(t,i){if("download"in document.createElement("a")){if(!i){var r=new Date;i="screenshot_"+(r.getFullYear()+"-"+(r.getMonth()+1)).slice(2)+"-"+r.getDate()+"_"+r.getHours()+"-"+("0"+r.getMinutes()).slice(-2)+".png"}e.Download(t,i)}else if(t&&"undefined"!=typeof URL){var n=URL.createObjectURL(t),o=window.open("");if(!o)return;var a=o.document.createElement("img");a.onload=function(){URL.revokeObjectURL(n)},a.src=n,o.document.body.appendChild(a)}},e.EncodeScreenshotCanvasData=function(t,i,r,n,o){if(void 0===r&&(r="image/png"),"string"!=typeof n&&i){if(i){if(e._IsOffScreenCanvas(t))return void t.convertToBlob({type:r,quality:o}).then((function(e){var t=new FileReader;t.readAsDataURL(e),t.onloadend=function(){var e=t.result;i(e)}}));var a=t.toDataURL(r,o);i(a)}}else this.ToBlob(t,(function(t){t&&e.DownloadBlob(t,n),i&&i("")}),r,o)},e.Download=function(e,t){if("undefined"!=typeof URL){var i=window.URL.createObjectURL(e),r=document.createElement("a");document.body.appendChild(r),r.style.display="none",r.href=i,r.download=t,r.addEventListener("click",(function(){r.parentElement&&r.parentElement.removeChild(r)})),r.click(),window.URL.revokeObjectURL(i)}},e.BackCompatCameraNoPreventDefault=function(e){return"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]},e.CreateScreenshot=function(e,t,i,r,n,o,a){throw void 0===n&&(n="image/png"),void 0===o&&(o=!1),He("ScreenshotTools")},e.CreateScreenshotAsync=function(e,t,i,r,n){throw void 0===r&&(r="image/png"),He("ScreenshotTools")},e.CreateScreenshotUsingRenderTarget=function(e,t,i,r,n,o,a,s,l,c,u,h){throw void 0===n&&(n="image/png"),void 0===o&&(o=1),void 0===a&&(a=!1),void 0===l&&(l=!1),void 0===c&&(c=!1),void 0===u&&(u=!0),He("ScreenshotTools")},e.CreateScreenshotUsingRenderTargetAsync=function(e,t,i,r,n,o,a,s,l,c,u){throw void 0===r&&(r="image/png"),void 0===n&&(n=1),void 0===o&&(o=!1),void 0===s&&(s=!1),void 0===l&&(l=!1),void 0===c&&(c=!0),He("ScreenshotTools")},e.RandomId=function(){return Qi()},e.IsBase64=function(e){return zi(e)},e.DecodeBase64=function(e){return Hi(e)},Object.defineProperty(e,"errorsCount",{get:function(){return ae.errorsCount},enumerable:!1,configurable:!0}),e.Log=function(e){ae.Log(e)},e.Warn=function(e){ae.Warn(e)},e.Error=function(e){ae.Error(e)},Object.defineProperty(e,"LogCache",{get:function(){return ae.LogCache},enumerable:!1,configurable:!0}),e.ClearLogCache=function(){ae.ClearLogCache()},Object.defineProperty(e,"LogLevels",{set:function(e){ae.LogLevels=e},enumerable:!1,configurable:!0}),Object.defineProperty(e,"PerformanceLogLevel",{set:function(t){return(t&e.PerformanceUserMarkLogLevel)===e.PerformanceUserMarkLogLevel?(e.StartPerformanceCounter=e._StartUserMark,void(e.EndPerformanceCounter=e._EndUserMark)):(t&e.PerformanceConsoleLogLevel)===e.PerformanceConsoleLogLevel?(e.StartPerformanceCounter=e._StartPerformanceConsole,void(e.EndPerformanceCounter=e._EndPerformanceConsole)):(e.StartPerformanceCounter=e._StartPerformanceCounterDisabled,void(e.EndPerformanceCounter=e._EndPerformanceCounterDisabled))},enumerable:!1,configurable:!0}),e._StartPerformanceCounterDisabled=function(e,t){},e._EndPerformanceCounterDisabled=function(e,t){},e._StartUserMark=function(t,i){if(void 0===i&&(i=!0),!e._Performance){if(!ct())return;e._Performance=window.performance}i&&e._Performance.mark&&e._Performance.mark(t+"-Begin")},e._EndUserMark=function(t,i){void 0===i&&(i=!0),i&&e._Performance.mark&&(e._Performance.mark(t+"-End"),e._Performance.measure(t,t+"-Begin",t+"-End"))},e._StartPerformanceConsole=function(t,i){void 0===i&&(i=!0),i&&(e._StartUserMark(t,i),console.time&&console.time(t))},e._EndPerformanceConsole=function(t,i){void 0===i&&(i=!0),i&&(e._EndUserMark(t,i),console.timeEnd(t))},Object.defineProperty(e,"Now",{get:function(){return _t.Now},enumerable:!1,configurable:!0}),e.GetClassName=function(e,t){void 0===t&&(t=!1);var i=null;return!t&&e.getClassName?i=e.getClassName():(e instanceof Object&&(i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__),i||(i=typeof e)),i},e.First=function(e,t){for(var i=0,r=e;i<r.length;i++){var n=r[i];if(t(n))return n}return null},e.getFullClassName=function(e,t){void 0===t&&(t=!1);var i=null,r=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){var n=t?e:Object.getPrototypeOf(e);i=n.constructor.__bjsclassName__,r=n.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=r?r+".":"")+i:null},e.DelayAsync=function(e){return new Promise((function(t){setTimeout((function(){t()}),e)}))},e.IsSafari=function(){return!!ut()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)},e.UseCustomRequestHeaders=!1,e.CustomRequestHeaders=Je.CustomRequestHeaders,e.GetDOMTextContent=dt,e._DefaultCdnUrl="https://cdn.babylonjs.com",e.GetAbsoluteUrl="object"==typeof document?function(e){var t=document.createElement("a");return t.href=e,t.href}:"function"==typeof URL&&"object"==typeof location?function(e){return new URL(e,location.origin).href}:function(){throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},e.NoneLogLevel=ae.NoneLogLevel,e.MessageLogLevel=ae.MessageLogLevel,e.WarningLogLevel=ae.WarningLogLevel,e.ErrorLogLevel=ae.ErrorLogLevel,e.AllLogLevel=ae.AllLogLevel,e.IsWindowObjectExist=ct,e.PerformanceNoneLogLevel=0,e.PerformanceUserMarkLogLevel=1,e.PerformanceConsoleLogLevel=2,e.StartPerformanceCounter=e._StartPerformanceCounterDisabled,e.EndPerformanceCounter=e._EndPerformanceCounterDisabled,e}();function nr(e,t){return function(i){i.__bjsclassName__=e,i.__bjsmoduleName__=null!=t?t:null}}var or=function(){function e(e,t,i,r){void 0===r&&(r=0),this.iterations=e,this.index=r-1,this._done=!1,this._fn=t,this._successCallback=i}return e.prototype.executeNext=function(){this._done||(this.index+1<this.iterations?(++this.index,this._fn(this)):this.breakLoop())},e.prototype.breakLoop=function(){this._done=!0,this._successCallback()},e.Run=function(t,i,r,n){void 0===n&&(n=0);var o=new e(t,i,r,n);return o.executeNext(),o},e.SyncAsyncForLoop=function(t,i,r,n,o,a){return void 0===a&&(a=0),e.Run(Math.ceil(t/i),(function(e){o&&o()?e.breakLoop():setTimeout((function(){for(var n=0;n<i;++n){var a=e.index*i+n;if(a>=t)break;if(r(a),o&&o()){e.breakLoop();break}}e.executeNext()}),a)}),n)},e}();rr.Mix=Ji,rr.IsExponentOfTwo=Zi,M.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";var ar=function(){function e(t){this.length=0,this.data=new Array(t),this._id=e._GlobalId++}return e.prototype.push=function(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)},e.prototype.forEach=function(e){for(var t=0;t<this.length;t++)e(this.data[t])},e.prototype.sort=function(e){this.data.sort(e)},e.prototype.reset=function(){this.length=0},e.prototype.dispose=function(){this.reset(),this.data&&(this.data.length=0)},e.prototype.concat=function(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(var t=0;t<e.length;t++)this.data[this.length++]=(e.data||e)[t]}},e.prototype.indexOf=function(e){var t=this.data.indexOf(e);return t>=this.length?-1:t},e.prototype.contains=function(e){return-1!==this.indexOf(e)},e._GlobalId=0,e}(),sr=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._duplicateId=0,t}return m(t,e),t.prototype.push=function(t){e.prototype.push.call(this,t),t.__smartArrayFlags||(t.__smartArrayFlags={}),t.__smartArrayFlags[this._id]=this._duplicateId},t.prototype.pushNoDuplicate=function(e){return!(e.__smartArrayFlags&&e.__smartArrayFlags[this._id]===this._duplicateId||(this.push(e),0))},t.prototype.reset=function(){e.prototype.reset.call(this),this._duplicateId++},t.prototype.concatWithNoDuplicate=function(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(var t=0;t<e.length;t++){var i=(e.data||e)[t];this.pushNoDuplicate(i)}}},t}(ar),lr=function(){function e(){this._count=0,this._data={}}return e.prototype.copyFrom=function(e){var t=this;this.clear(),e.forEach((function(e,i){return t.add(e,i)}))},e.prototype.get=function(e){var t=this._data[e];if(void 0!==t)return t},e.prototype.getOrAddWithFactory=function(e,t){var i=this.get(e);return void 0!==i||(i=t(e))&&this.add(e,i),i},e.prototype.getOrAdd=function(e,t){var i=this.get(e);return void 0!==i?i:(this.add(e,t),t)},e.prototype.contains=function(e){return void 0!==this._data[e]},e.prototype.add=function(e,t){return void 0===this._data[e]&&(this._data[e]=t,++this._count,!0)},e.prototype.set=function(e,t){return void 0!==this._data[e]&&(this._data[e]=t,!0)},e.prototype.getAndRemove=function(e){var t=this.get(e);return void 0!==t?(delete this._data[e],--this._count,t):null},e.prototype.remove=function(e){return!!this.contains(e)&&(delete this._data[e],--this._count,!0)},e.prototype.clear=function(){this._data={},this._count=0},Object.defineProperty(e.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),e.prototype.forEach=function(e){for(var t in this._data)e(t,this._data[t])},e.prototype.first=function(e){for(var t in this._data){var i=e(t,this._data[t]);if(i)return i}return null},e}();function cr(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}var ur=function(){function e(){this._dirty=!0,this._tempColor=new J(0,0,0,0),this._globalCurve=new J(0,0,0,0),this._highlightsCurve=new J(0,0,0,0),this._midtonesCurve=new J(0,0,0,0),this._shadowsCurve=new J(0,0,0,0),this._positiveCurve=new J(0,0,0,0),this._negativeCurve=new J(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}return Object.defineProperty(e.prototype,"globalHue",{get:function(){return this._globalHue},set:function(e){this._globalHue=e,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"globalDensity",{get:function(){return this._globalDensity},set:function(e){this._globalDensity=e,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"globalSaturation",{get:function(){return this._globalSaturation},set:function(e){this._globalSaturation=e,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"globalExposure",{get:function(){return this._globalExposure},set:function(e){this._globalExposure=e,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"highlightsHue",{get:function(){return this._highlightsHue},set:function(e){this._highlightsHue=e,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"highlightsDensity",{get:function(){return this._highlightsDensity},set:function(e){this._highlightsDensity=e,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"highlightsSaturation",{get:function(){return this._highlightsSaturation},set:function(e){this._highlightsSaturation=e,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"highlightsExposure",{get:function(){return this._highlightsExposure},set:function(e){this._highlightsExposure=e,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"midtonesHue",{get:function(){return this._midtonesHue},set:function(e){this._midtonesHue=e,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"midtonesDensity",{get:function(){return this._midtonesDensity},set:function(e){this._midtonesDensity=e,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"midtonesSaturation",{get:function(){return this._midtonesSaturation},set:function(e){this._midtonesSaturation=e,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"midtonesExposure",{get:function(){return this._midtonesExposure},set:function(e){this._midtonesExposure=e,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"shadowsHue",{get:function(){return this._shadowsHue},set:function(e){this._shadowsHue=e,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"shadowsDensity",{get:function(){return this._shadowsDensity},set:function(e){this._shadowsDensity=e,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"shadowsSaturation",{get:function(){return this._shadowsSaturation},set:function(e){this._shadowsSaturation=e,this._dirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"shadowsExposure",{get:function(){return this._shadowsExposure},set:function(e){this._shadowsExposure=e,this._dirty=!0},enumerable:!1,configurable:!0}),e.prototype.getClassName=function(){return"ColorCurves"},e.Bind=function(e,t,i,r,n){void 0===i&&(i="vCameraColorCurvePositive"),void 0===r&&(r="vCameraColorCurveNeutral"),void 0===n&&(n="vCameraColorCurveNegative"),e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(r,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(n,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))},e.prototype._getColorGradingDataToRef=function(t,i,r,n,o){null!=t&&(t=e._Clamp(t,0,360),i=e._Clamp(i,-100,100),r=e._Clamp(r,-100,100),n=e._Clamp(n,-100,100),i=e._ApplyColorGradingSliderNonlinear(i),i*=.5,n=e._ApplyColorGradingSliderNonlinear(n),i<0&&(i*=-1,t=(t+180)%360),e._FromHSBToRef(t,i,50+.25*n,o),o.scaleToRef(2,o),o.a=1+.01*r)},e._ApplyColorGradingSliderNonlinear=function(e){e/=100;var t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),100*t},e._FromHSBToRef=function(t,i,r,n){var o=e._Clamp(t,0,360),a=e._Clamp(i/100,0,1),s=e._Clamp(r/100,0,1);if(0===a)n.r=s,n.g=s,n.b=s;else{o/=60;var l=Math.floor(o),c=o-l,u=s*(1-a),h=s*(1-a*c),d=s*(1-a*(1-c));switch(l){case 0:n.r=s,n.g=d,n.b=u;break;case 1:n.r=h,n.g=s,n.b=u;break;case 2:n.r=u,n.g=s,n.b=d;break;case 3:n.r=u,n.g=h,n.b=s;break;case 4:n.r=d,n.g=u,n.b=s;break;default:n.r=s,n.g=u,n.b=h}}n.a=1},e._Clamp=function(e,t,i){return Math.min(Math.max(e,t),i)},e.prototype.clone=function(){return Ke.Clone((function(){return new e}),this)},e.prototype.serialize=function(){return Ke.Serialize(this)},e.Parse=function(t){return Ke.Parse((function(){return new e}),t,null,null)},e.PrepareUniforms=cr,v([Ie()],e.prototype,"_globalHue",void 0),v([Ie()],e.prototype,"_globalDensity",void 0),v([Ie()],e.prototype,"_globalSaturation",void 0),v([Ie()],e.prototype,"_globalExposure",void 0),v([Ie()],e.prototype,"_highlightsHue",void 0),v([Ie()],e.prototype,"_highlightsDensity",void 0),v([Ie()],e.prototype,"_highlightsSaturation",void 0),v([Ie()],e.prototype,"_highlightsExposure",void 0),v([Ie()],e.prototype,"_midtonesHue",void 0),v([Ie()],e.prototype,"_midtonesDensity",void 0),v([Ie()],e.prototype,"_midtonesSaturation",void 0),v([Ie()],e.prototype,"_midtonesExposure",void 0),e}();function hr(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),(t.VIGNETTE||t.DITHER)&&e.push("vInverseScreenSize"),t.VIGNETTE&&(e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&cr(e),t.DITHER&&e.push("ditherIntensity")}function dr(e,t){t.COLORGRADING&&e.push("txColorTransform")}Ke._ColorCurvesParser=ur.Parse;var pr=function(){function e(){this.colorCurves=new ur,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=e.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new J(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=e.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new f}return Object.defineProperty(e.prototype,"colorCurvesEnabled",{get:function(){return this._colorCurvesEnabled},set:function(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"colorGradingTexture",{get:function(){return this._colorGradingTexture},set:function(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"colorGradingEnabled",{get:function(){return this._colorGradingEnabled},set:function(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"colorGradingWithGreenDepth",{get:function(){return this._colorGradingWithGreenDepth},set:function(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"colorGradingBGR",{get:function(){return this._colorGradingBGR},set:function(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"exposure",{get:function(){return this._exposure},set:function(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"toneMappingEnabled",{get:function(){return this._toneMappingEnabled},set:function(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"toneMappingType",{get:function(){return this._toneMappingType},set:function(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"contrast",{get:function(){return this._contrast},set:function(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"vignetteCentreY",{get:function(){return this.vignetteCenterY},set:function(e){this.vignetteCenterY=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"vignetteCentreX",{get:function(){return this.vignetteCenterX},set:function(e){this.vignetteCenterX=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"vignetteBlendMode",{get:function(){return this._vignetteBlendMode},set:function(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"vignetteEnabled",{get:function(){return this._vignetteEnabled},set:function(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"ditheringEnabled",{get:function(){return this._ditheringEnabled},set:function(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"ditheringIntensity",{get:function(){return this._ditheringIntensity},set:function(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"skipFinalColorClamp",{get:function(){return this._skipFinalColorClamp},set:function(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"applyByPostProcess",{get:function(){return this._applyByPostProcess},set:function(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())},enumerable:!1,configurable:!0}),e.prototype._updateParameters=function(){this.onUpdateParameters.notifyObservers(this)},e.prototype.getClassName=function(){return"ImageProcessingConfiguration"},e.prototype.prepareDefines=function(t,i){if(void 0===i&&(i=!1),i!==this.applyByPostProcess||!this._isEnabled)return t.VIGNETTE=!1,t.TONEMAPPING=0,t.CONTRAST=!1,t.EXPOSURE=!1,t.COLORCURVES=!1,t.COLORGRADING=!1,t.COLORGRADING3D=!1,t.DITHER=!1,t.IMAGEPROCESSING=!1,t.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,void(t.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled);if(t.VIGNETTE=this.vignetteEnabled,t.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===e._VIGNETTEMODE_MULTIPLY,t.VIGNETTEBLENDMODEOPAQUE=!t.VIGNETTEBLENDMODEMULTIPLY,this._toneMappingEnabled)switch(this._toneMappingType){case e.TONEMAPPING_KHR_PBR_NEUTRAL:t.TONEMAPPING=3;break;case e.TONEMAPPING_ACES:t.TONEMAPPING=2;break;default:t.TONEMAPPING=1}else t.TONEMAPPING=0;t.CONTRAST=1!==this.contrast,t.EXPOSURE=1!==this.exposure,t.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,t.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,t.COLORGRADING?t.COLORGRADING3D=this.colorGradingTexture.is3D:t.COLORGRADING3D=!1,t.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,t.SAMPLER3DBGRMAP=this.colorGradingBGR,t.DITHER=this._ditheringEnabled,t.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,t.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,t.IMAGEPROCESSING=t.VIGNETTE||!!t.TONEMAPPING||t.CONTRAST||t.EXPOSURE||t.COLORCURVES||t.COLORGRADING||t.DITHER},e.prototype.isReady=function(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()},e.prototype.bind=function(e,t){if(this._colorCurvesEnabled&&this.colorCurves&&ur.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){var i=1/e.getEngine().getRenderWidth(),r=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,r),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){var n=null!=t?t:r/i,o=Math.tan(.5*this.vignetteCameraFov),a=o*n,s=Math.sqrt(a*o);a=Ji(a,s,this.vignetteStretch),o=Ji(o,s,this.vignetteStretch),e.setFloat4("vignetteSettings1",a,o,-a*this.vignetteCenterX,-o*this.vignetteCenterY);var l=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,l)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);var c=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(c-1)/c,.5/c,c,this.colorGradingTexture.level)}},e.prototype.clone=function(){return Ke.Clone((function(){return new e}),this)},e.prototype.serialize=function(){return Ke.Serialize(this)},e.Parse=function(t){var i=Ke.Parse((function(){return new e}),t,null,null);return void 0!==t.vignetteCentreX&&(i.vignetteCenterX=t.vignetteCentreX),void 0!==t.vignetteCentreY&&(i.vignetteCenterY=t.vignetteCentreY),i},Object.defineProperty(e,"VIGNETTEMODE_MULTIPLY",{get:function(){return this._VIGNETTEMODE_MULTIPLY},enumerable:!1,configurable:!0}),Object.defineProperty(e,"VIGNETTEMODE_OPAQUE",{get:function(){return this._VIGNETTEMODE_OPAQUE},enumerable:!1,configurable:!0}),e.TONEMAPPING_STANDARD=0,e.TONEMAPPING_ACES=1,e.TONEMAPPING_KHR_PBR_NEUTRAL=2,e.PrepareUniforms=hr,e.PrepareSamplers=dr,e._VIGNETTEMODE_MULTIPLY=0,e._VIGNETTEMODE_OPAQUE=1,v([we()],e.prototype,"colorCurves",void 0),v([Ie()],e.prototype,"_colorCurvesEnabled",void 0),v([Me("colorGradingTexture")],e.prototype,"_colorGradingTexture",void 0),v([Ie()],e.prototype,"_colorGradingEnabled",void 0),v([Ie()],e.prototype,"_colorGradingWithGreenDepth",void 0),v([Ie()],e.prototype,"_colorGradingBGR",void 0),v([Ie()],e.prototype,"_exposure",void 0),v([Ie()],e.prototype,"_toneMappingEnabled",void 0),v([Ie()],e.prototype,"_toneMappingType",void 0),v([Ie()],e.prototype,"_contrast",void 0),v([Ie()],e.prototype,"vignetteStretch",void 0),v([Ie()],e.prototype,"vignetteCenterX",void 0),v([Ie()],e.prototype,"vignetteCenterY",void 0),v([Ie()],e.prototype,"vignetteWeight",void 0),v([Be()],e.prototype,"vignetteColor",void 0),v([Ie()],e.prototype,"vignetteCameraFov",void 0),v([Ie()],e.prototype,"_vignetteBlendMode",void 0),v([Ie()],e.prototype,"_vignetteEnabled",void 0),v([Ie()],e.prototype,"_ditheringEnabled",void 0),v([Ie()],e.prototype,"_ditheringIntensity",void 0),v([Ie()],e.prototype,"_skipFinalColorClamp",void 0),v([Ie()],e.prototype,"_applyByPostProcess",void 0),v([Ie()],e.prototype,"_isEnabled",void 0),e}();function fr(e){return void 0===e.getPipelineContext}Ke._ImageProcessingConfigurationParser=pr.Parse,a("BABYLON.ImageProcessingConfiguration",pr);var _r=function(){function e(){this.shaderLanguage=pt.GLSL}return e.prototype.postProcessor=function(e,t,i,r,n){return n.drawBuffersExtensionDisabled&&(e=e.replace(/#extension.+GL_EXT_draw_buffers.+(enable|require)/g,"")),e},e}(),mr=/(flat\s)?\s*varying\s*.*/,gr=function(){function e(){this.shaderLanguage=pt.GLSL}return e.prototype.attributeProcessor=function(e){return e.replace("attribute","in")},e.prototype.varyingCheck=function(e,t){return mr.test(e)},e.prototype.varyingProcessor=function(e,t){return e.replace("varying",t?"in":"out")},e.prototype.postProcessor=function(e,t,i){var r=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){var n=-1!==e.search(/layout *\(location *= *0\) *out/g);e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(r||n?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else if(-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;return e},e}(),vr=function(){function e(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=e._Counter++}return Object.defineProperty(e.prototype,"underlyingResource",{get:function(){return null},enumerable:!1,configurable:!0}),e._Counter=0,e}(),yr=function(e){function t(t){var i=e.call(this)||this;return i._buffer=t,i}return m(t,e),Object.defineProperty(t.prototype,"underlyingResource",{get:function(){return this._buffer},enumerable:!1,configurable:!0}),t}(vr),br=function(){function e(e,t){if(void 0===e&&(e=null),this._MSAARenderBuffers=null,this._context=t,!e&&!(e=t.createTexture()))throw new Error("Unable to create webGL texture");this.set(e)}return Object.defineProperty(e.prototype,"underlyingResource",{get:function(){return this._webGLTexture},enumerable:!1,configurable:!0}),e.prototype.setUsage=function(){},e.prototype.set=function(e){this._webGLTexture=e},e.prototype.reset=function(){this._webGLTexture=null,this._MSAARenderBuffers=null},e.prototype.addMSAARenderBuffer=function(e){this._MSAARenderBuffers||(this._MSAARenderBuffers=[]),this._MSAARenderBuffers.push(e)},e.prototype.releaseMSAARenderBuffers=function(){if(this._MSAARenderBuffers){for(var e=0,t=this._MSAARenderBuffers;e<t.length;e++){var i=t[e];this._context.deleteRenderbuffer(i)}this._MSAARenderBuffers=null}},e.prototype.getMSAARenderBuffer=function(e){var t,i;return void 0===e&&(e=0),null!==(i=null===(t=this._MSAARenderBuffers)||void 0===t?void 0:t[e])&&void 0!==i?i:null},e.prototype.release=function(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()},e}(),Tr=function(){},Er=function(e){function t(i,r,n,o){var a=this;if(n=n||{},(a=e.call(this,null!=r?r:n.antialias,n,o)||this)._name="WebGL",a.forcePOTTextures=!1,a.validateShaderPrograms=!1,a.disableUniformBuffers=!1,a._webGLVersion=1,a._vertexAttribArraysEnabled=[],a._uintIndicesCurrentlySet=!1,a._currentBoundBuffer=new Array,a._currentFramebuffer=null,a._dummyFramebuffer=null,a._currentBufferPointers=new Array,a._currentInstanceLocations=new Array,a._currentInstanceBuffers=new Array,a._vaoRecordInProgress=!1,a._mustWipeVertexAttributes=!1,a._nextFreeTextureSlots=new Array,a._maxSimultaneousTextures=0,a._maxMSAASamplesOverride=null,a._unpackFlipYCached=null,a.enableUnpackFlipYCached=!0,a._boundUniforms={},!i)return a;var s=null;if(i.getContext){if(s=i,a._renderingCanvas=s,void 0===n.preserveDrawingBuffer&&(n.preserveDrawingBuffer=!1),void 0===n.xrCompatible&&(n.xrCompatible=!1),navigator&&navigator.userAgent){a._setupMobileChecks();for(var l=navigator.userAgent,c=0,u=t.ExceptionList;c<u.length;c++){var h=u[c],d=h.key,p=h.targets;if(new RegExp(d).test(l)){if(h.capture&&h.captureConstraint){var f=h.capture,_=h.captureConstraint,m=new RegExp(f).exec(l);if(m&&m.length>0&&parseInt(m[m.length-1])>=_)continue}for(var g=0,v=p;g<v.length;g++)switch(v[g]){case"uniformBuffer":a.disableUniformBuffers=!0;break;case"vao":a.disableVertexArrayObjects=!0;break;case"antialias":n.antialias=!1;break;case"maxMSAASamples":a._maxMSAASamplesOverride=1}}}}if(a._doNotHandleContextLost||(a._onContextLost=function(e){e.preventDefault(),a._contextWasLost=!0,ae.Warn("WebGL context lost."),a.onContextLostObservable.notifyObservers(a)},a._onContextRestored=function(){a._restoreEngineAfterContextLost((function(){return a._initGLContext()}))},s.addEventListener("webglcontextlost",a._onContextLost,!1),s.addEventListener("webglcontextrestored",a._onContextRestored,!1),n.powerPreference=n.powerPreference||"high-performance"),a._badDesktopOS&&(n.xrCompatible=!1),!n.disableWebGL2Support)try{a._gl=s.getContext("webgl2",n)||s.getContext("experimental-webgl2",n),a._gl&&(a._webGLVersion=2,a._shaderPlatformName="WEBGL2",a._gl.deleteQuery||(a._webGLVersion=1,a._shaderPlatformName="WEBGL1"))}catch(e){}if(!a._gl){if(!s)throw new Error("The provided canvas is null or undefined.");try{a._gl=s.getContext("webgl",n)||s.getContext("experimental-webgl",n)}catch(e){throw new Error("WebGL not supported")}}if(!a._gl)throw new Error("WebGL not supported")}else{a._gl=i,a._renderingCanvas=a._gl.canvas,a._gl.renderbufferStorageMultisample?(a._webGLVersion=2,a._shaderPlatformName="WEBGL2"):a._shaderPlatformName="WEBGL1";var y=a._gl.getContextAttributes();y&&(n.stencil=y.stencil)}a._gl.pixelStorei(a._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,a._gl.NONE),void 0!==n.useHighPrecisionFloats&&(a._highPrecisionShadersAllowed=n.useHighPrecisionFloats),a.resize(),a._initGLContext(),a._initFeatures();for(var b=0;b<a._caps.maxVertexAttribs;b++)a._currentBufferPointers[b]=new Tr;a._shaderProcessor=a.webGLVersion>1?new gr:new _r;var T="Babylon.js v".concat(t.Version);ae.Log(T+" - ".concat(a.description)),a._renderingCanvas&&a._renderingCanvas.setAttribute&&a._renderingCanvas.setAttribute("data-engine",T);var E=di(a._gl);return E.validateShaderPrograms=a.validateShaderPrograms,E.parallelShaderCompile=a._caps.parallelShaderCompile,a}return m(t,e),Object.defineProperty(t.prototype,"name",{get:function(){return this._name},set:function(e){this._name=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"version",{get:function(){return this._webGLVersion},enumerable:!1,configurable:!0}),Object.defineProperty(t,"ShadersRepository",{get:function(){return Ei.ShadersRepository},set:function(e){Ei.ShadersRepository=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"supportsUniformBuffers",{get:function(){return this.webGLVersion>1&&!this.disableUniformBuffers},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"needPOTTextures",{get:function(){return this._webGLVersion<2||this.forcePOTTextures},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_supportsHardwareTextureRescaling",{get:function(){return!1},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"framebufferDimensionsObject",{set:function(e){this._framebufferDimensionsObject=e},enumerable:!1,configurable:!0}),t.prototype.snapshotRenderingReset=function(){this.snapshotRendering=!1},t.prototype._clearEmptyResources=function(){this._dummyFramebuffer=null,e.prototype._clearEmptyResources.call(this)},t.prototype._getShaderProcessingContext=function(e){return null},t.prototype.areAllEffectsReady=function(){for(var e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0},t.prototype._initGLContext=function(){var e;this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||null!==this._gl.getExtension("OES_standard_derivatives"),maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||null!==this._gl.getExtension("OES_element_index_uint"),fragmentDepthSupported:this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:1!==this._webGLVersion,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1},this._caps.supportFloatTexturesResolve=this._caps.colorBufferFloat,this._caps.rg11b10ufColorRenderable=this._caps.colorBufferFloat,this._glVersion=this._gl.getParameter(this._gl.VERSION);var t=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=t&&(this._glRenderer=this._gl.getParameter(t.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(t.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),36193!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=36193),34842!==this._gl.RGBA16F&&(this._gl.RGBA16F=34842),34836!==this._gl.RGBA32F&&(this._gl.RGBA32F=34836),35056!==this._gl.DEPTH24_STENCIL8&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(1===this._webGLVersion&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=(null!==(e=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT))&&void 0!==e?e:0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!(!this._caps.textureFloat||!this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!(!this._caps.textureFloat||!this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&5131!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=null!==this._maxMSAASamplesOverride?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES);else{var i=this._gl.getExtension("WEBGL_draw_buffers");if(null!==i){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=i.drawBuffersWEBGL.bind(i),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(var r=0;r<16;r++)this._gl["COLOR_ATTACHMENT"+r+"_WEBGL"]=i["COLOR_ATTACHMENT"+r+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{var n=this._gl.getExtension("WEBGL_depth_texture");null!=n&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=n.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{var o=this._gl.getExtension("OES_vertex_array_object");null!=o&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=o.createVertexArrayOES.bind(o),this._gl.bindVertexArray=o.bindVertexArrayOES.bind(o),this._gl.deleteVertexArray=o.deleteVertexArrayOES.bind(o))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{var a=this._gl.getExtension("ANGLE_instanced_arrays");null!=a?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=a.drawArraysInstancedANGLE.bind(a),this._gl.drawElementsInstanced=a.drawElementsInstancedANGLE.bind(a),this._gl.vertexAttribDivisor=a.vertexAttribDivisorANGLE.bind(a)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){var s=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),l=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);s&&l&&(this._caps.highPrecisionShaderSupported=0!==s.precision&&0!==l.precision)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{var c=this._gl.getExtension("EXT_blend_minmax");null!=c&&(this._caps.blendMinMax=!0,this._gl.MAX=c.MAX_EXT,this._gl.MIN=c.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{var u=this._gl.getExtension("EXT_sRGB");null!=u&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:u.SRGB_EXT,SRGB8:u.SRGB_ALPHA_EXT,SRGB8_ALPHA8:u.SRGB_ALPHA_EXT})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!(!this._creationOptions||!this._creationOptions.forceSRGBBufferSupportState)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(var h=0;h<this._maxSimultaneousTextures;h++)this._nextFreeTextureSlots.push(h);"Mali-G72"===this._glRenderer&&(this._caps.disableMorphTargetTexture=!0)},t.prototype._initFeatures=function(){this._features={forceBitmapOverHTMLImageElement:"undefined"==typeof HTMLImageElement,supportRenderAndCopyToLodForFloatTextures:1!==this._webGLVersion,supportDepthStencilTexture:1!==this._webGLVersion,supportShadowSamplers:1!==this._webGLVersion,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:1!==this._webGLVersion,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:1!==this._webGLVersion,basisNeedsPOT:1===this._webGLVersion,support3DTextures:1!==this._webGLVersion,needTypeSuffixInShaderConstants:1!==this._webGLVersion,supportMSAA:1!==this._webGLVersion,supportSSAO2:1!==this._webGLVersion,supportExtendedTextureFormats:1!==this._webGLVersion,supportSwitchCaseInShader:1!==this._webGLVersion,supportSyncTextureRead:!0,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!1,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1}},Object.defineProperty(t.prototype,"webGLVersion",{get:function(){return this._webGLVersion},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"ThinEngine"},t.prototype._prepareWorkingCanvas=function(){if(!this._workingCanvas){this._workingCanvas=this.createCanvas(1,1);var e=this._workingCanvas.getContext("2d");e&&(this._workingContext=e)}},t.prototype.getInfo=function(){return this.getGlInfo()},t.prototype.getGlInfo=function(){return{vendor:this._glVendor,renderer:this._glRenderer,version:this._glVersion}},t.prototype.extractDriverInfo=function(){var e=this.getGlInfo();return e&&e.renderer?e.renderer:""},t.prototype.getRenderWidth=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferWidth:this._gl.drawingBufferWidth},t.prototype.getRenderHeight=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferHeight:this._gl.drawingBufferHeight},t.prototype.clear=function(e,i,r,n){var o,a;void 0===n&&(n=!1);var s=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=s;var l=0;if(i&&e){var c=!0;if(this._currentRenderTarget){var h=null===(o=this._currentRenderTarget.texture)||void 0===o?void 0:o.format;if(h===u.TEXTUREFORMAT_RED_INTEGER||h===u.TEXTUREFORMAT_RG_INTEGER||h===u.TEXTUREFORMAT_RGB_INTEGER||h===u.TEXTUREFORMAT_RGBA_INTEGER){var d=null===(a=this._currentRenderTarget.texture)||void 0===a?void 0:a.type;d===u.TEXTURETYPE_UNSIGNED_INTEGER||d===u.TEXTURETYPE_UNSIGNED_SHORT?(t._TempClearColorUint32[0]=255*e.r,t._TempClearColorUint32[1]=255*e.g,t._TempClearColorUint32[2]=255*e.b,t._TempClearColorUint32[3]=255*e.a,this._gl.clearBufferuiv(this._gl.COLOR,0,t._TempClearColorUint32),c=!1):(t._TempClearColorInt32[0]=255*e.r,t._TempClearColorInt32[1]=255*e.g,t._TempClearColorInt32[2]=255*e.b,t._TempClearColorInt32[3]=255*e.a,this._gl.clearBufferiv(this._gl.COLOR,0,t._TempClearColorInt32),c=!1)}}c&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),l|=this._gl.COLOR_BUFFER_BIT)}r&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),l|=this._gl.DEPTH_BUFFER_BIT),n&&(this._gl.clearStencil(0),l|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(l)},t.prototype._viewport=function(e,t,i,r){e===this._viewportCached.x&&t===this._viewportCached.y&&i===this._viewportCached.z&&r===this._viewportCached.w||(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=r,this._gl.viewport(e,t,i,r))},t.prototype.endFrame=function(){e.prototype.endFrame.call(this),this._badOS&&this.flushFramebuffer()},Object.defineProperty(t.prototype,"performanceMonitor",{get:function(){throw new Error("Not Supported by ThinEngine")},enumerable:!1,configurable:!0}),t.prototype.bindFramebuffer=function(e,t,i,r,n,o,a){var s,l,c,u,h,d;void 0===t&&(t=0),void 0===o&&(o=0),void 0===a&&(a=0);var p=e;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(p._MSAAFramebuffer?p._MSAAFramebuffer:p._framebuffer);var f=this._gl;e.isMulti||(e.is2DArray||e.is3D?f.framebufferTextureLayer(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,null===(s=e.texture._hardwareTexture)||void 0===s?void 0:s.underlyingResource,o,a):e.isCube?f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_CUBE_MAP_POSITIVE_X+t,null===(l=e.texture._hardwareTexture)||void 0===l?void 0:l.underlyingResource,o):p._currentLOD!==o&&(f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_2D,null===(c=e.texture._hardwareTexture)||void 0===c?void 0:c.underlyingResource,o),p._currentLOD=o));var _=e._depthStencilTexture;if(_){e.is3D&&(e.texture.width===_.width&&e.texture.height===_.height&&e.texture.depth===_.depth||ae.Warn("Depth/Stencil attachment for 3D target must have same dimensions as color attachment"));var m=e._depthStencilTextureWithStencil?f.DEPTH_STENCIL_ATTACHMENT:f.DEPTH_ATTACHMENT;e.is2DArray||e.is3D?f.framebufferTextureLayer(f.FRAMEBUFFER,m,null===(u=_._hardwareTexture)||void 0===u?void 0:u.underlyingResource,o,a):e.isCube?f.framebufferTexture2D(f.FRAMEBUFFER,m,f.TEXTURE_CUBE_MAP_POSITIVE_X+t,null===(h=_._hardwareTexture)||void 0===h?void 0:h.underlyingResource,o):f.framebufferTexture2D(f.FRAMEBUFFER,m,f.TEXTURE_2D,null===(d=_._hardwareTexture)||void 0===d?void 0:d.underlyingResource,o)}this._cachedViewport&&!n?this.setViewport(this._cachedViewport,i,r):(i||(i=e.width,o&&(i/=Math.pow(2,o))),r||(r=e.height,o&&(r/=Math.pow(2,o))),this._viewport(0,0,i,r)),this.wipeCaches()},t.prototype.setState=function(e,t,i,r,n,o,a){var s,l;void 0===t&&(t=0),void 0===r&&(r=!1),void 0===a&&(a=0),(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);var c=null===(l=null!==(s=this.cullBackFaces)&&void 0!==s?s:n)||void 0===l||l?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==c||i)&&(this._depthCullingState.cullFace=c),this.setZOffset(t),this.setZOffsetUnits(a);var u=r?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==u||i)&&(this._depthCullingState.frontFace=u),this._stencilStateComposer.stencilMaterial=o},t.prototype._bindUnboundFramebuffer=function(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)},t.prototype._currentFrameBufferIsDefaultFrameBuffer=function(){return null===this._currentFramebuffer},t.prototype.generateMipmaps=function(e){var t=this._getTextureTarget(e);this._bindTextureDirectly(t,e,!0),this._gl.generateMipmap(t),this._bindTextureDirectly(t,null)},t.prototype.unBindFramebuffer=function(e,t,i){var r;void 0===t&&(t=!1);var n=e;this._currentRenderTarget=null;var o=this._gl;if(n._MSAAFramebuffer){if(e.isMulti)return void this.unBindMultiColorAttachmentFramebuffer(e,t,i);o.bindFramebuffer(o.READ_FRAMEBUFFER,n._MSAAFramebuffer),o.bindFramebuffer(o.DRAW_FRAMEBUFFER,n._framebuffer),o.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,o.COLOR_BUFFER_BIT,o.NEAREST)}!(null===(r=e.texture)||void 0===r?void 0:r.generateMipMaps)||t||e.isCube||this.generateMipmaps(e.texture),i&&(n._MSAAFramebuffer&&this._bindUnboundFramebuffer(n._framebuffer),i()),this._bindUnboundFramebuffer(null)},t.prototype.flushFramebuffer=function(){this._gl.flush()},t.prototype.restoreDefaultFramebuffer=function(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._bindUnboundFramebuffer(null),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()},t.prototype._resetVertexBufferBinding=function(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null},t.prototype.createVertexBuffer=function(e,t,i){return this._createVertexBuffer(e,this._gl.STATIC_DRAW)},t.prototype._createVertexBuffer=function(e,t){var i=this._gl.createBuffer();if(!i)throw new Error("Unable to create vertex buffer");var r=new yr(i);return this.bindArrayBuffer(r),"number"!=typeof e?e instanceof Array?(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t),r.capacity=4*e.length):(this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),r.capacity=e.byteLength):(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Uint8Array(e),t),r.capacity=e),this._resetVertexBufferBinding(),r.references=1,r},t.prototype.createDynamicVertexBuffer=function(e,t){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)},t.prototype._resetIndexBufferBinding=function(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null},t.prototype.createIndexBuffer=function(e,t,i){var r=this._gl.createBuffer(),n=new yr(r);if(!r)throw new Error("Unable to create index buffer");this.bindIndexBuffer(n);var o=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,o,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),n.references=1,n.is32Bits=4===o.BYTES_PER_ELEMENT,n},t.prototype._normalizeIndexData=function(e){if(2===e.BYTES_PER_ELEMENT)return e;if(this._caps.uintIndices){if(e instanceof Uint32Array)return e;for(var t=0;t<e.length;t++)if(e[t]>=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)},t.prototype.bindArrayBuffer=function(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)},t.prototype.bindUniformBlock=function(e,t,i){var r=e.program,n=this._gl.getUniformBlockIndex(r,t);this._gl.uniformBlockBinding(r,n,i)},t.prototype.bindIndexBuffer=function(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)},t.prototype._bindBuffer=function(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)},t.prototype.updateArrayBuffer=function(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)},t.prototype._vertexAttribPointer=function(e,t,i,r,n,o,a){var s=this._currentBufferPointers[t];if(s){var l=!1;s.active?(s.buffer!==e&&(s.buffer=e,l=!0),s.size!==i&&(s.size=i,l=!0),s.type!==r&&(s.type=r,l=!0),s.normalized!==n&&(s.normalized=n,l=!0),s.stride!==o&&(s.stride=o,l=!0),s.offset!==a&&(s.offset=a,l=!0)):(l=!0,s.active=!0,s.index=t,s.size=i,s.type=r,s.normalized=n,s.stride=o,s.offset=a,s.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),r===this._gl.UNSIGNED_INT||r===this._gl.INT?this._gl.vertexAttribIPointer(t,i,r,o,a):this._gl.vertexAttribPointer(t,i,r,n,o,a))}},t.prototype._bindIndexBufferWithCache=function(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)},t.prototype._bindVertexBuffersAttributes=function(e,t,i){var r=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(var n=0;n<r.length;n++){var o=t.getAttributeLocation(n);if(o>=0){var a=r[n],s=null;if(i&&(s=i[a]),s||(s=e[a]),!s)continue;this._gl.enableVertexAttribArray(o),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[o]=!0);var l=s.getBuffer();l&&(this._vertexAttribPointer(l,o,s.getSize(),s.type,s.normalized,s.byteStride,s.byteOffset),s.getIsInstanced()&&(this._gl.vertexAttribDivisor(o,s.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(o),this._currentInstanceBuffers.push(l))))}}},t.prototype.recordVertexArrayObject=function(e,t,i,r){var n=this._gl.createVertexArray();if(!n)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(n),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,r),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),n},t.prototype.bindVertexArrayObject=function(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)},t.prototype.bindBuffersDirectly=function(e,t,i,r,n){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==n){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=n;var o=n.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();for(var a=0,s=0;s<o;s++)if(s<i.length){var l=n.getAttributeLocation(s);l>=0&&(this._gl.enableVertexAttribArray(l),this._vertexAttribArraysEnabled[l]=!0,this._vertexAttribPointer(e,l,i[s],this._gl.FLOAT,!1,r,a)),a+=4*i[s]}}this._bindIndexBufferWithCache(t)},t.prototype._unbindVertexArrayObject=function(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))},t.prototype.bindBuffers=function(e,t,i,r){this._cachedVertexBuffers===e&&this._cachedEffectForVertexBuffers===i||(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,r)),this._bindIndexBufferWithCache(t)},t.prototype.unbindInstanceAttributes=function(){for(var e,t=0,i=this._currentInstanceLocations.length;t<i;t++){var r=this._currentInstanceBuffers[t];e!=r&&r.references&&(e=r,this.bindArrayBuffer(r));var n=this._currentInstanceLocations[t];this._gl.vertexAttribDivisor(n,0)}this._currentInstanceBuffers.length=0,this._currentInstanceLocations.length=0},t.prototype.releaseVertexArrayObject=function(e){this._gl.deleteVertexArray(e)},t.prototype._releaseBuffer=function(e){return e.references--,0===e.references&&(this._deleteBuffer(e),!0)},t.prototype._deleteBuffer=function(e){this._gl.deleteBuffer(e.underlyingResource)},t.prototype.updateAndBindInstancesBuffer=function(e,t,i){if(this.bindArrayBuffer(e),t&&this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t),void 0!==i[0].index)this.bindInstancesBuffer(e,i,!0);else for(var r=0;r<4;r++){var n=i[r];this._vertexAttribArraysEnabled[n]||(this._gl.enableVertexAttribArray(n),this._vertexAttribArraysEnabled[n]=!0),this._vertexAttribPointer(e,n,4,this._gl.FLOAT,!1,64,16*r),this._gl.vertexAttribDivisor(n,1),this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(e)}},t.prototype.bindInstancesBuffer=function(e,t,i){void 0===i&&(i=!0),this.bindArrayBuffer(e);var r=0;if(i)for(var n=0;n<t.length;n++)r+=4*(o=t[n]).attributeSize;for(n=0;n<t.length;n++){var o;void 0===(o=t[n]).index&&(o.index=this._currentEffect.getAttributeLocationByName(o.attributeName)),o.index<0||(this._vertexAttribArraysEnabled[o.index]||(this._gl.enableVertexAttribArray(o.index),this._vertexAttribArraysEnabled[o.index]=!0),this._vertexAttribPointer(e,o.index,o.attributeSize,o.attributeType||this._gl.FLOAT,o.normalized||!1,r,o.offset),this._gl.vertexAttribDivisor(o.index,void 0===o.divisor?1:o.divisor),this._currentInstanceLocations.push(o.index),this._currentInstanceBuffers.push(e))}},t.prototype.disableInstanceAttributeByName=function(e){if(this._currentEffect){var t=this._currentEffect.getAttributeLocationByName(e);this.disableInstanceAttribute(t)}},t.prototype.disableInstanceAttribute=function(e){for(var t,i=!1;-1!==(t=this._currentInstanceLocations.indexOf(e));)this._currentInstanceLocations.splice(t,1),this._currentInstanceBuffers.splice(t,1),i=!0,t=this._currentInstanceLocations.indexOf(e);i&&(this._gl.vertexAttribDivisor(e,0),this.disableAttributeByIndex(e))},t.prototype.disableAttributeByIndex=function(e){this._gl.disableVertexAttribArray(e),this._vertexAttribArraysEnabled[e]=!1,this._currentBufferPointers[e].active=!1},t.prototype.draw=function(e,t,i,r){this.drawElementsType(e?u.MATERIAL_TriangleFillMode:u.MATERIAL_WireFrameFillMode,t,i,r)},t.prototype.drawPointClouds=function(e,t,i){this.drawArraysType(u.MATERIAL_PointFillMode,e,t,i)},t.prototype.drawUnIndexed=function(e,t,i,r){this.drawArraysType(e?u.MATERIAL_TriangleFillMode:u.MATERIAL_WireFrameFillMode,t,i,r)},t.prototype.drawElementsType=function(e,t,i,r){this.applyStates(),this._reportDrawCall();var n=this._drawMode(e),o=this._uintIndicesCurrentlySet?this._gl.UNSIGNED_INT:this._gl.UNSIGNED_SHORT,a=this._uintIndicesCurrentlySet?4:2;r?this._gl.drawElementsInstanced(n,i,o,t*a,r):this._gl.drawElements(n,i,o,t*a)},t.prototype.drawArraysType=function(e,t,i,r){this.applyStates(),this._reportDrawCall();var n=this._drawMode(e);r?this._gl.drawArraysInstanced(n,t,i,r):this._gl.drawArrays(n,t,i)},t.prototype._drawMode=function(e){switch(e){case u.MATERIAL_TriangleFillMode:return this._gl.TRIANGLES;case u.MATERIAL_PointFillMode:return this._gl.POINTS;case u.MATERIAL_WireFrameFillMode:return this._gl.LINES;case u.MATERIAL_PointListDrawMode:return this._gl.POINTS;case u.MATERIAL_LineListDrawMode:return this._gl.LINES;case u.MATERIAL_LineLoopDrawMode:return this._gl.LINE_LOOP;case u.MATERIAL_LineStripDrawMode:return this._gl.LINE_STRIP;case u.MATERIAL_TriangleStripDrawMode:return this._gl.TRIANGLE_STRIP;case u.MATERIAL_TriangleFanDrawMode:return this._gl.TRIANGLE_FAN;default:return this._gl.TRIANGLES}},t.prototype._releaseEffect=function(e){this._compiledEffects[e._key]&&delete this._compiledEffects[e._key];var t=e.getPipelineContext();t&&this._deletePipelineContext(t)},t.prototype._deletePipelineContext=function(e){var t=e;t&&t.program&&(t.program.__SPECTOR_rebuildProgram=null,yi(t),this._gl.deleteProgram(t.program))},t.prototype._getGlobalDefines=function(e){return Gt(e,this.isNDCHalfZRange,this.useReverseDepthBuffer,this.useExactSrgbConversions)},t.prototype.createEffect=function(e,t,i,r,n,o,a,s,l,c){var u,h;void 0===c&&(c=pt.GLSL);var d="string"==typeof e?e:e.vertexToken||e.vertexSource||e.vertexElement||e.vertex,p="string"==typeof e?e:e.fragmentToken||e.fragmentSource||e.fragmentElement||e.fragment,f=this._getGlobalDefines(),_=null!==(u=null!=n?n:t.defines)&&void 0!==u?u:"";f&&(_+=f);var m=d+"+"+p+"@"+_;if(this._compiledEffects[m]){var g=this._compiledEffects[m];return a&&g.isReady()&&a(g),g}this._gl&&di(this._gl);var v=new Ei(e,t,i,r,this,n,o,a,s,l,m,null!==(h=t.shaderLanguage)&&void 0!==h?h:c);return this._compiledEffects[m]=v,v},t.prototype._getShaderSource=function(e){return this._gl.getShaderSource(e)},t.prototype.createRawShaderProgram=function(e,t,i,r,n){void 0===n&&(n=null);var o=di(this._gl);return o._contextWasLost=this._contextWasLost,o.validateShaderPrograms=this.validateShaderPrograms,pi(e,t,i,r||this._gl,n)},t.prototype.createShaderProgram=function(e,t,i,r,n,o){void 0===o&&(o=null);var a=di(this._gl);return a._contextWasLost=this._contextWasLost,a.validateShaderPrograms=this.validateShaderPrograms,fi(e,t,i,r,n||this._gl,o)},t.prototype.inlineShaderCode=function(e){return e},t.prototype.createPipelineContext=function(e){this._gl&&(di(this._gl).parallelShaderCompile=this._caps.parallelShaderCompile);var t=function(e,t){var i=new ci,r=di(e);return r.parallelShaderCompile&&(i.isParallelCompiled=!0),i.context=r._context,i}(this._gl);return t.engine=this,t},t.prototype.createMaterialContext=function(){},t.prototype.createDrawContext=function(){},t.prototype._finalizePipelineContext=function(e){return mi(e,this._gl,this.validateShaderPrograms)},t.prototype._preparePipelineContext=function(e,t,i,r,n,o,a,s,l,c){var u=di(this._gl);return u._contextWasLost=this._contextWasLost,u.validateShaderPrograms=this.validateShaderPrograms,u._createShaderProgramInjection=this._createShaderProgram.bind(this),u.createRawShaderProgramInjection=this.createRawShaderProgram.bind(this),u.createShaderProgramInjection=this.createShaderProgram.bind(this),u.loadFileInjection=this._loadFile.bind(this),function(e,t,i,r,n,o,a,s,l,c,u,h){var d,p;void 0===c&&(c="");var f=di(e.context);u||(u=null!==(d=f.createRawShaderProgramInjection)&&void 0!==d?d:pi),h||(h=null!==(p=f.createShaderProgramInjection)&&void 0!==p?p:fi);var _=e;_.program=r?u(_,t,i,_.context,l):h(_,t,i,s,_.context,l),_.program.__SPECTOR_rebuildProgram=a}(e,t,i,r,0,0,a,s,l,c)},t.prototype._createShaderProgram=function(e,t,i,r,n){return void 0===n&&(n=null),_i(e,t,i,r,n)},t.prototype._isRenderingStateCompiled=function(e){var t=e;return!(this._isDisposed||t._isDisposed||!this._gl.getProgramParameter(t.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)||(this._finalizePipelineContext(t),0))},t.prototype._executeWhenRenderingStateIsCompiled=function(e,t){!function(e,t){var i=e;if(i.isParallelCompiled){var r=i.onCompiled;i.onCompiled=function(){null==r||r(),t(e)}}else t(e)}(e,t)},t.prototype.getUniforms=function(e,t){for(var i=new Array,r=e,n=0;n<t.length;n++)i.push(this._gl.getUniformLocation(r.program,t[n]));return i},t.prototype.getAttributes=function(e,t){for(var i=[],r=e,n=0;n<t.length;n++)try{i.push(this._gl.getAttribLocation(r.program,t[n]))}catch(e){i.push(-1)}return i},t.prototype.enableEffect=function(e){(e=null!==e&&fr(e)?e.effect:e)&&e!==this._currentEffect&&(this._stencilStateComposer.stencilMaterial=void 0,this.bindSamplers(e),this._currentEffect=e,e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))},t.prototype.setInt=function(e,t){return!!e&&(this._gl.uniform1i(e,t),!0)},t.prototype.setInt2=function(e,t,i){return!!e&&(this._gl.uniform2i(e,t,i),!0)},t.prototype.setInt3=function(e,t,i,r){return!!e&&(this._gl.uniform3i(e,t,i,r),!0)},t.prototype.setInt4=function(e,t,i,r,n){return!!e&&(this._gl.uniform4i(e,t,i,r,n),!0)},t.prototype.setIntArray=function(e,t){return!!e&&(this._gl.uniform1iv(e,t),!0)},t.prototype.setIntArray2=function(e,t){return!(!e||t.length%2!=0||(this._gl.uniform2iv(e,t),0))},t.prototype.setIntArray3=function(e,t){return!(!e||t.length%3!=0||(this._gl.uniform3iv(e,t),0))},t.prototype.setIntArray4=function(e,t){return!(!e||t.length%4!=0||(this._gl.uniform4iv(e,t),0))},t.prototype.setUInt=function(e,t){return!!e&&(this._gl.uniform1ui(e,t),!0)},t.prototype.setUInt2=function(e,t,i){return!!e&&(this._gl.uniform2ui(e,t,i),!0)},t.prototype.setUInt3=function(e,t,i,r){return!!e&&(this._gl.uniform3ui(e,t,i,r),!0)},t.prototype.setUInt4=function(e,t,i,r,n){return!!e&&(this._gl.uniform4ui(e,t,i,r,n),!0)},t.prototype.setUIntArray=function(e,t){return!!e&&(this._gl.uniform1uiv(e,t),!0)},t.prototype.setUIntArray2=function(e,t){return!(!e||t.length%2!=0||(this._gl.uniform2uiv(e,t),0))},t.prototype.setUIntArray3=function(e,t){return!(!e||t.length%3!=0||(this._gl.uniform3uiv(e,t),0))},t.prototype.setUIntArray4=function(e,t){return!(!e||t.length%4!=0||(this._gl.uniform4uiv(e,t),0))},t.prototype.setArray=function(e,t){return!(!e||t.length<1||(this._gl.uniform1fv(e,t),0))},t.prototype.setArray2=function(e,t){return!(!e||t.length%2!=0||(this._gl.uniform2fv(e,t),0))},t.prototype.setArray3=function(e,t){return!(!e||t.length%3!=0||(this._gl.uniform3fv(e,t),0))},t.prototype.setArray4=function(e,t){return!(!e||t.length%4!=0||(this._gl.uniform4fv(e,t),0))},t.prototype.setMatrices=function(e,t){return!!e&&(this._gl.uniformMatrix4fv(e,!1,t),!0)},t.prototype.setMatrix3x3=function(e,t){return!!e&&(this._gl.uniformMatrix3fv(e,!1,t),!0)},t.prototype.setMatrix2x2=function(e,t){return!!e&&(this._gl.uniformMatrix2fv(e,!1,t),!0)},t.prototype.setFloat=function(e,t){return!!e&&(this._gl.uniform1f(e,t),!0)},t.prototype.setFloat2=function(e,t,i){return!!e&&(this._gl.uniform2f(e,t,i),!0)},t.prototype.setFloat3=function(e,t,i,r){return!!e&&(this._gl.uniform3f(e,t,i,r),!0)},t.prototype.setFloat4=function(e,t,i,r,n){return!!e&&(this._gl.uniform4f(e,t,i,r,n),!0)},t.prototype.applyStates=function(){if(this._depthCullingState.apply(this._gl),this._stencilStateComposer.apply(this._gl),this._alphaState.apply(this._gl),this._colorWriteChanged){this._colorWriteChanged=!1;var e=this._colorWrite;this._gl.colorMask(e,e,e,e)}},t.prototype.wipeCaches=function(e){this.preventCacheWipeBetweenFrames&&!e||(this._currentEffect=null,this._viewportCached.x=0,this._viewportCached.y=0,this._viewportCached.z=0,this._viewportCached.w=0,this._unbindVertexArrayObject(),e&&(this._currentProgram=null,this.resetTextureCache(),this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=this._gl.LEQUAL,this._alphaState.reset(),this._alphaMode=u.ALPHA_ADD,this._alphaEquation=u.ALPHA_DISABLE,this._colorWrite=!0,this._colorWriteChanged=!0,this._unpackFlipYCached=null,this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),this._mustWipeVertexAttributes=!0,this.unbindAllAttributes()),this._resetVertexBufferBinding(),this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null,this.bindIndexBuffer(null))},t.prototype.setTextureFromPostProcess=function(e,t,i){},t.prototype.setTextureFromPostProcessOutput=function(e,t,i){},t.prototype.setDepthStencilTexture=function(e,t,i,r){},t.prototype._getSamplingParameters=function(e,t){var i=this._gl,r=i.NEAREST,n=i.NEAREST;switch(e){case u.TEXTURE_LINEAR_LINEAR_MIPNEAREST:r=i.LINEAR,n=t?i.LINEAR_MIPMAP_NEAREST:i.LINEAR;break;case u.TEXTURE_LINEAR_LINEAR_MIPLINEAR:r=i.LINEAR,n=t?i.LINEAR_MIPMAP_LINEAR:i.LINEAR;break;case u.TEXTURE_NEAREST_NEAREST_MIPLINEAR:r=i.NEAREST,n=t?i.NEAREST_MIPMAP_LINEAR:i.NEAREST;break;case u.TEXTURE_NEAREST_NEAREST_MIPNEAREST:r=i.NEAREST,n=t?i.NEAREST_MIPMAP_NEAREST:i.NEAREST;break;case u.TEXTURE_NEAREST_LINEAR_MIPNEAREST:r=i.NEAREST,n=t?i.LINEAR_MIPMAP_NEAREST:i.LINEAR;break;case u.TEXTURE_NEAREST_LINEAR_MIPLINEAR:r=i.NEAREST,n=t?i.LINEAR_MIPMAP_LINEAR:i.LINEAR;break;case u.TEXTURE_NEAREST_LINEAR:r=i.NEAREST,n=i.LINEAR;break;case u.TEXTURE_NEAREST_NEAREST:r=i.NEAREST,n=i.NEAREST;break;case u.TEXTURE_LINEAR_NEAREST_MIPNEAREST:r=i.LINEAR,n=t?i.NEAREST_MIPMAP_NEAREST:i.NEAREST;break;case u.TEXTURE_LINEAR_NEAREST_MIPLINEAR:r=i.LINEAR,n=t?i.NEAREST_MIPMAP_LINEAR:i.NEAREST;break;case u.TEXTURE_LINEAR_LINEAR:r=i.LINEAR,n=i.LINEAR;break;case u.TEXTURE_LINEAR_NEAREST:r=i.LINEAR,n=i.NEAREST}return{min:n,mag:r}},t.prototype._createTexture=function(){var e=this._gl.createTexture();if(!e)throw new Error("Unable to create texture");return e},t.prototype._createHardwareTexture=function(){return new br(this._createTexture(),this._gl)},t.prototype._createInternalTexture=function(e,t,i,r){var n;void 0===i&&(i=!0),void 0===r&&(r=Ti.Unknown);var o,a=!1,s=u.TEXTURETYPE_UNSIGNED_INT,l=u.TEXTURE_TRILINEAR_SAMPLINGMODE,c=u.TEXTUREFORMAT_RGBA,h=!1,d=1;void 0!==t&&"object"==typeof t?(a=!!t.generateMipMaps,s=void 0===t.type?u.TEXTURETYPE_UNSIGNED_INT:t.type,l=void 0===t.samplingMode?u.TEXTURE_TRILINEAR_SAMPLINGMODE:t.samplingMode,c=void 0===t.format?u.TEXTUREFORMAT_RGBA:t.format,h=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,d=null!==(n=t.samples)&&void 0!==n?n:1,o=t.label):a=!!t,h&&(h=this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU)),(s!==u.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(s!==u.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(l=u.TEXTURE_NEAREST_SAMPLINGMODE),s!==u.TEXTURETYPE_FLOAT||this._caps.textureFloat||(s=u.TEXTURETYPE_UNSIGNED_INT,ae.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));var p=this._gl,f=new Pi(this,r),_=e.width||e,m=e.height||e,g=e.depth||0,v=e.layers||0,y=this._getSamplingParameters(l,a),b=0!==v?p.TEXTURE_2D_ARRAY:0!==g?p.TEXTURE_3D:p.TEXTURE_2D,T=this._getRGBABufferInternalSizedFormat(s,c,h),E=this._getInternalFormat(c),S=this._getWebGLTextureType(s);return this._bindTextureDirectly(b,f),0!==v?(f.is2DArray=!0,p.texImage3D(b,0,T,_,m,v,0,E,S,null)):0!==g?(f.is3D=!0,p.texImage3D(b,0,T,_,m,g,0,E,S,null)):p.texImage2D(b,0,T,_,m,0,E,S,null),p.texParameteri(b,p.TEXTURE_MAG_FILTER,y.mag),p.texParameteri(b,p.TEXTURE_MIN_FILTER,y.min),p.texParameteri(b,p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE),p.texParameteri(b,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE),a&&this._gl.generateMipmap(b),this._bindTextureDirectly(b,null),f._useSRGBBuffer=h,f.baseWidth=_,f.baseHeight=m,f.width=_,f.height=m,f.depth=v,f.isReady=!0,f.samples=d,f.generateMipMaps=a,f.samplingMode=l,f.type=s,f.format=c,f.label=o,this._internalTexturesCache.push(f),f},t.prototype._getUseSRGBBuffer=function(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||t)},t.prototype.createTexture=function(e,t,i,r,n,o,a,s,l,c,h,d,p,f,_){var m=this;return void 0===n&&(n=u.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null),void 0===l&&(l=null),void 0===c&&(c=null),void 0===h&&(h=null),this._createTextureBase(e,t,i,r,n,o,a,(function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return m._prepareWebGLTexture.apply(m,T(T([],e,!1),[c],!1))}),(function(e,t,i,n,o,a){var s=m._gl,l=i.width===e&&i.height===t;o._creationFlags=null!=f?f:0;var c=m._getTexImageParametersForCreateTexture(o.format,o._useSRGBBuffer);if(l)return s.texImage2D(s.TEXTURE_2D,0,c.internalFormat,c.format,c.type,i),!1;var u=m._caps.maxTextureSize;if(i.width>u||i.height>u||!m._supportsHardwareTextureRescaling)return m._prepareWorkingCanvas(),!(!m._workingCanvas||!m._workingContext||(m._workingCanvas.width=e,m._workingCanvas.height=t,m._workingContext.drawImage(i,0,0,i.width,i.height,0,0,e,t),s.texImage2D(s.TEXTURE_2D,0,c.internalFormat,c.format,c.type,m._workingCanvas),o.width=e,o.height=t,1));var h=new Pi(m,Ti.Temp);return m._bindTextureDirectly(s.TEXTURE_2D,h,!0),s.texImage2D(s.TEXTURE_2D,0,c.internalFormat,c.format,c.type,i),m._rescaleTexture(h,o,r,c.format,(function(){m._releaseTexture(h),m._bindTextureDirectly(s.TEXTURE_2D,o,!0),a()})),!0}),s,l,c,h,d,p,_)},t.prototype._getTexImageParametersForCreateTexture=function(e,t){var i,r;return 1===this.webGLVersion?r=i=this._getInternalFormat(e,t):(i=this._getInternalFormat(e,!1),r=this._getRGBABufferInternalSizedFormat(u.TEXTURETYPE_UNSIGNED_BYTE,e,t)),{internalFormat:r,format:i,type:this._gl.UNSIGNED_BYTE}},t.prototype._rescaleTexture=function(e,t,i,r,n){},t.prototype.createRawTexture=function(e,t,i,r,n,o,a,s,l,c,h){throw void 0===s&&(s=null),void 0===l&&(l=u.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=0),void 0===h&&(h=!1),He("Engine.RawTexture")},t.prototype.createRawCubeTexture=function(e,t,i,r,n,o,a,s){throw void 0===s&&(s=null),He("Engine.RawTexture")},t.prototype.createRawTexture3D=function(e,t,i,r,n,o,a,s,l,c){throw void 0===l&&(l=null),void 0===c&&(c=u.TEXTURETYPE_UNSIGNED_INT),He("Engine.RawTexture")},t.prototype.createRawTexture2DArray=function(e,t,i,r,n,o,a,s,l,c){throw void 0===l&&(l=null),void 0===c&&(c=u.TEXTURETYPE_UNSIGNED_INT),He("Engine.RawTexture")},t.prototype.createPrefilteredCubeTexture=function(e,t,i,r,n,o,a,s,l){throw He("Misc/dds")},t.prototype._unpackFlipY=function(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))},t.prototype._getUnpackAlignement=function(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)},t.prototype._getTextureTarget=function(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D},t.prototype.updateTextureSamplingMode=function(e,t,i){void 0===i&&(i=!1);var r=this._getTextureTarget(t),n=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(r,this._gl.TEXTURE_MAG_FILTER,n.mag,t),this._setTextureParameterInteger(r,this._gl.TEXTURE_MIN_FILTER,n.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(r)),this._bindTextureDirectly(r,null),t.samplingMode=e},t.prototype.updateTextureDimensions=function(e,t,i,r){void 0===r&&(r=1)},t.prototype.updateTextureWrappingMode=function(e,t,i,r){void 0===i&&(i=null),void 0===r&&(r=null);var n=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(n,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==i&&(this._setTextureParameterInteger(n,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==r&&(this._setTextureParameterInteger(n,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(r),e),e._cachedWrapR=r),this._bindTextureDirectly(n,null)},t.prototype._setupDepthStencilTexture=function(e,t,i,r,n,o){void 0===o&&(o=1);var a=t.width||t,s=t.height||t,l=t.layers||0,c=t.depth||0;e.baseWidth=a,e.baseHeight=s,e.width=a,e.height=s,e.is2DArray=l>0,e.depth=l||c,e.isReady=!0,e.samples=o,e.generateMipMaps=!1,e.samplingMode=r?u.TEXTURE_BILINEAR_SAMPLINGMODE:u.TEXTURE_NEAREST_SAMPLINGMODE,e.type=u.TEXTURETYPE_UNSIGNED_INT,e._comparisonFunction=n;var h=this._gl,d=this._getTextureTarget(e),p=this._getSamplingParameters(e.samplingMode,!1);h.texParameteri(d,h.TEXTURE_MAG_FILTER,p.mag),h.texParameteri(d,h.TEXTURE_MIN_FILTER,p.min),h.texParameteri(d,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(d,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===n?(h.texParameteri(d,h.TEXTURE_COMPARE_FUNC,u.LEQUAL),h.texParameteri(d,h.TEXTURE_COMPARE_MODE,h.NONE)):(h.texParameteri(d,h.TEXTURE_COMPARE_FUNC,n),h.texParameteri(d,h.TEXTURE_COMPARE_MODE,h.COMPARE_REF_TO_TEXTURE)))},t.prototype._uploadCompressedDataToTextureDirectly=function(e,t,i,r,n,o,a){void 0===o&&(o=0),void 0===a&&(a=0);var s=this._gl,l=s.TEXTURE_2D;if(e.isCube&&(l=s.TEXTURE_CUBE_MAP_POSITIVE_X+o),e._useSRGBBuffer)switch(t){case u.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2:case u.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL:this._caps.etc2?t=s.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case u.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC:this._caps.etc2?t=s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case u.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM:t=s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case u.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4:t=s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case u.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1:this._caps.s3tc_srgb?t=s.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case u.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1:this._caps.s3tc_srgb?t=s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case u.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5:this._caps.s3tc_srgb?t=s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}this._gl.compressedTexImage2D(l,a,t,i,r,0,n)},t.prototype._uploadDataToTextureDirectly=function(e,t,i,r,n,o){void 0===i&&(i=0),void 0===r&&(r=0),void 0===o&&(o=!1);var a=this._gl,s=this._getWebGLTextureType(e.type),l=this._getInternalFormat(e.format),c=void 0===n?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(n,e._useSRGBBuffer);this._unpackFlipY(e.invertY);var u=a.TEXTURE_2D;e.isCube&&(u=a.TEXTURE_CUBE_MAP_POSITIVE_X+i);var h=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),p=o?e.width:Math.pow(2,Math.max(h-r,0)),f=o?e.height:Math.pow(2,Math.max(d-r,0));a.texImage2D(u,r,c,p,f,0,l,s,t)},t.prototype.updateTextureData=function(e,t,i,r,n,o,a,s,l){void 0===a&&(a=0),void 0===s&&(s=0),void 0===l&&(l=!1);var c=this._gl,u=this._getWebGLTextureType(e.type),h=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);var d=c.TEXTURE_2D,p=c.TEXTURE_2D;e.isCube&&(p=c.TEXTURE_CUBE_MAP_POSITIVE_X+a,d=c.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),c.texSubImage2D(p,s,i,r,n,o,h,u,t),l&&this._gl.generateMipmap(p),this._bindTextureDirectly(d,null)},t.prototype._uploadArrayBufferViewToTexture=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0);var n=this._gl,o=e.isCube?n.TEXTURE_CUBE_MAP:n.TEXTURE_2D;this._bindTextureDirectly(o,e,!0),this._uploadDataToTextureDirectly(e,t,i,r),this._bindTextureDirectly(o,null,!0)},t.prototype._prepareWebGLTextureContinuation=function(e,t,i,r,n){var o=this._gl;if(o){var a=this._getSamplingParameters(n,!i);o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,a.mag),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,a.min),i||r||o.generateMipmap(o.TEXTURE_2D),this._bindTextureDirectly(o.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}},t.prototype._prepareWebGLTexture=function(e,t,i,r,n,o,a,s,l,c){var h=this,d=this.getCaps().maxTextureSize,p=Math.min(d,this.needPOTTextures?ir(r.width,d):r.width),f=Math.min(d,this.needPOTTextures?ir(r.height,d):r.height),_=this._gl;_&&(e._hardwareTexture?(this._bindTextureDirectly(_.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===n||!!n),e.baseWidth=r.width,e.baseHeight=r.height,e.width=p,e.height=f,e.isReady=!0,e.type=-1!==e.type?e.type:u.TEXTURETYPE_UNSIGNED_BYTE,e.format=-1!==e.format?e.format:null!=c?c:".jpg"!==t||e._useSRGBBuffer?u.TEXTUREFORMAT_RGBA:u.TEXTUREFORMAT_RGB,s(p,f,r,t,e,(function(){h._prepareWebGLTextureContinuation(e,i,o,a,l)}))||this._prepareWebGLTextureContinuation(e,i,o,a,l)):i&&i.removePendingData(e))},t.prototype._setupFramebufferDepthAttachments=function(e,t,i,r,n){void 0===n&&(n=1);var o=this._gl;if(e&&t)return this._createRenderBuffer(i,r,n,o.DEPTH_STENCIL,o.DEPTH24_STENCIL8,o.DEPTH_STENCIL_ATTACHMENT);if(t){var a=o.DEPTH_COMPONENT16;return this._webGLVersion>1&&(a=o.DEPTH_COMPONENT32F),this._createRenderBuffer(i,r,n,a,a,o.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,r,n,o.STENCIL_INDEX8,o.STENCIL_INDEX8,o.STENCIL_ATTACHMENT):null},t.prototype._createRenderBuffer=function(e,t,i,r,n,o,a){void 0===a&&(a=!0);var s=this._gl.createRenderbuffer();return this._updateRenderBuffer(s,e,t,i,r,n,o,a)},t.prototype._updateRenderBuffer=function(e,t,i,r,n,o,a,s){void 0===s&&(s=!0);var l=this._gl;return l.bindRenderbuffer(l.RENDERBUFFER,e),r>1&&l.renderbufferStorageMultisample?l.renderbufferStorageMultisample(l.RENDERBUFFER,r,o,t,i):l.renderbufferStorage(l.RENDERBUFFER,n,t,i),l.framebufferRenderbuffer(l.FRAMEBUFFER,a,l.RENDERBUFFER,e),s&&l.bindRenderbuffer(l.RENDERBUFFER,null),e},t.prototype._releaseTexture=function(e){var t;this._deleteTexture(null===(t=e._hardwareTexture)||void 0===t?void 0:t.underlyingResource),this.unbindAllTextures();var i=this._internalTexturesCache.indexOf(e);-1!==i&&this._internalTexturesCache.splice(i,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()},t.prototype._deleteTexture=function(e){e&&this._gl.deleteTexture(e)},t.prototype._setProgram=function(e){this._currentProgram!==e&&(function(e,t){t.useProgram(e)}(e,this._gl),this._currentProgram=e)},t.prototype.bindSamplers=function(e){var t=e.getPipelineContext();this._setProgram(t.program);for(var i=e.getSamplers(),r=0;r<i.length;r++){var n=e.getUniform(i[r]);n&&(this._boundUniforms[r]=n)}this._currentEffect=null},t.prototype._activateCurrentTexture=function(){this._currentTextureChannel!==this._activeChannel&&(this._gl.activeTexture(this._gl.TEXTURE0+this._activeChannel),this._currentTextureChannel=this._activeChannel)},t.prototype._bindTextureDirectly=function(e,t,i,r){var n,o;void 0===i&&(i=!1),void 0===r&&(r=!1);var a=!1,s=t&&t._associatedChannel>-1;if(i&&s&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||r){if(this._activateCurrentTexture(),t&&t.isMultiview)throw ae.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,null!==(o=null===(n=null==t?void 0:t._hardwareTexture)||void 0===n?void 0:n.underlyingResource)&&void 0!==o?o:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(a=!0,this._activateCurrentTexture());return s&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),a},t.prototype._bindTexture=function(e,t,i){if(void 0!==e){t&&(t._associatedChannel=e),this._activeChannel=e;var r=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(r,t)}},t.prototype.unbindAllTextures=function(){for(var e=0;e<this._maxSimultaneousTextures;e++)this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))},t.prototype.setTexture=function(e,t,i,r){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))},t.prototype._bindSamplerUniformToChannel=function(e,t){var i=this._boundUniforms[e];i&&i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)},t.prototype._getTextureWrapMode=function(e){switch(e){case u.TEXTURE_WRAP_ADDRESSMODE:return this._gl.REPEAT;case u.TEXTURE_CLAMP_ADDRESSMODE:return this._gl.CLAMP_TO_EDGE;case u.TEXTURE_MIRROR_ADDRESSMODE:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT},t.prototype._setTexture=function(e,t,i,r,n){if(void 0===i&&(i=!1),void 0===r&&(r=!1),void 0===n&&(n=""),!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;var o=t.getInternalTexture();o&&(o._associatedChannel=e),t.update()}else if(t.delayLoadState===u.DELAYLOADSTATE_NOTLOADED)return t.delayLoad(),!1;var a;a=r?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!i&&a&&(a._associatedChannel=e);var s=!0;this._boundTexturesCache[e]===a&&(i||this._bindSamplerUniformToChannel(a._associatedChannel,e),s=!1),this._activeChannel=e;var l=this._getTextureTarget(a);if(s&&this._bindTextureDirectly(l,a,i),a&&!a.isMultiview){if(a.isCube&&a._cachedCoordinatesMode!==t.coordinatesMode){a._cachedCoordinatesMode=t.coordinatesMode;var c=t.coordinatesMode!==u.TEXTURE_CUBIC_MODE&&t.coordinatesMode!==u.TEXTURE_SKYBOX_MODE?u.TEXTURE_WRAP_ADDRESSMODE:u.TEXTURE_CLAMP_ADDRESSMODE;t.wrapU=c,t.wrapV=c}a._cachedWrapU!==t.wrapU&&(a._cachedWrapU=t.wrapU,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),a)),a._cachedWrapV!==t.wrapV&&(a._cachedWrapV=t.wrapV,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),a)),a.is3D&&a._cachedWrapR!==t.wrapR&&(a._cachedWrapR=t.wrapR,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),a)),this._setAnisotropicLevel(l,a,t.anisotropicFilteringLevel)}return!0},t.prototype.setTextureArray=function(e,t,i,r){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(var n=0;n<i.length;n++){var o=i[n].getInternalTexture();o?(this._textureUnits[n]=e+n,o._associatedChannel=e+n):this._textureUnits[n]=-1}this._gl.uniform1iv(t,this._textureUnits);for(var a=0;a<i.length;a++)this._setTexture(this._textureUnits[a],i[a],!0)}},t.prototype._setAnisotropicLevel=function(e,t,i){var r=this._caps.textureAnisotropicFilterExtension;t.samplingMode!==u.TEXTURE_LINEAR_LINEAR_MIPNEAREST&&t.samplingMode!==u.TEXTURE_LINEAR_LINEAR_MIPLINEAR&&t.samplingMode!==u.TEXTURE_LINEAR_LINEAR&&(i=1),r&&t._cachedAnisotropicFilteringLevel!==i&&(this._setTextureParameterFloat(e,r.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(i,this._caps.maxAnisotropy),t),t._cachedAnisotropicFilteringLevel=i)},t.prototype._setTextureParameterFloat=function(e,t,i,r){this._bindTextureDirectly(e,r,!0,!0),this._gl.texParameterf(e,t,i)},t.prototype._setTextureParameterInteger=function(e,t,i,r){r&&this._bindTextureDirectly(e,r,!0,!0),this._gl.texParameteri(e,t,i)},t.prototype.unbindAllAttributes=function(){if(this._mustWipeVertexAttributes){this._mustWipeVertexAttributes=!1;for(var e=0;e<this._caps.maxVertexAttribs;e++)this.disableAttributeByIndex(e)}else{e=0;for(var t=this._vertexAttribArraysEnabled.length;e<t;e++)e>=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}},t.prototype.releaseEffects=function(){for(var e in this._compiledEffects){var t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}},t.prototype.dispose=function(){var t,i;e.prototype.dispose.call(this),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.unbindAllAttributes(),this._boundUniforms={},ct()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored))),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._currentProgram=null,this._creationOptions.loseContextOnDispose&&(null===(t=this._gl.getExtension("WEBGL_lose_context"))||void 0===t||t.loseContext()),i=this._gl,ui.delete(i)},t.prototype.attachContextLostEvent=function(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)},t.prototype.attachContextRestoredEvent=function(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)},t.prototype.getError=function(){return this._gl.getError()},t.prototype._canRenderToFloatFramebuffer=function(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(u.TEXTURETYPE_FLOAT)},t.prototype._canRenderToHalfFloatFramebuffer=function(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(u.TEXTURETYPE_HALF_FLOAT)},t.prototype._canRenderToFramebuffer=function(e){for(var t=this._gl;t.getError()!==t.NO_ERROR;);var i=!0,r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);var n=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,n),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);var o=t.checkFramebufferStatus(t.FRAMEBUFFER);if((i=(i=i&&o===t.FRAMEBUFFER_COMPLETE)&&t.getError()===t.NO_ERROR)&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);var a=t.RGBA,s=t.UNSIGNED_BYTE,l=new Uint8Array(4);t.readPixels(0,0,1,1,a,s,l),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(r),t.deleteFramebuffer(n),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i},t.prototype._getWebGLTextureType=function(e){if(1===this._webGLVersion){switch(e){case u.TEXTURETYPE_FLOAT:return this._gl.FLOAT;case u.TEXTURETYPE_HALF_FLOAT:return this._gl.HALF_FLOAT_OES;case u.TEXTURETYPE_UNSIGNED_BYTE:return this._gl.UNSIGNED_BYTE;case u.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.UNSIGNED_SHORT_4_4_4_4;case u.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.UNSIGNED_SHORT_5_5_5_1;case u.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case u.TEXTURETYPE_BYTE:return this._gl.BYTE;case u.TEXTURETYPE_UNSIGNED_BYTE:return this._gl.UNSIGNED_BYTE;case u.TEXTURETYPE_SHORT:return this._gl.SHORT;case u.TEXTURETYPE_UNSIGNED_SHORT:return this._gl.UNSIGNED_SHORT;case u.TEXTURETYPE_INT:return this._gl.INT;case u.TEXTURETYPE_UNSIGNED_INTEGER:return this._gl.UNSIGNED_INT;case u.TEXTURETYPE_FLOAT:return this._gl.FLOAT;case u.TEXTURETYPE_HALF_FLOAT:return this._gl.HALF_FLOAT;case u.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.UNSIGNED_SHORT_4_4_4_4;case u.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.UNSIGNED_SHORT_5_5_5_1;case u.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.UNSIGNED_SHORT_5_6_5;case u.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case u.TEXTURETYPE_UNSIGNED_INT_24_8:return this._gl.UNSIGNED_INT_24_8;case u.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case u.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case u.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE},t.prototype._getInternalFormat=function(e,t){void 0===t&&(t=!1);var i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case u.TEXTUREFORMAT_ALPHA:i=this._gl.ALPHA;break;case u.TEXTUREFORMAT_LUMINANCE:i=this._gl.LUMINANCE;break;case u.TEXTUREFORMAT_LUMINANCE_ALPHA:i=this._gl.LUMINANCE_ALPHA;break;case u.TEXTUREFORMAT_RED:i=this._gl.RED;break;case u.TEXTUREFORMAT_RG:i=this._gl.RG;break;case u.TEXTUREFORMAT_RGB:i=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case u.TEXTUREFORMAT_RGBA:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA}if(this._webGLVersion>1)switch(e){case u.TEXTUREFORMAT_RED_INTEGER:i=this._gl.RED_INTEGER;break;case u.TEXTUREFORMAT_RG_INTEGER:i=this._gl.RG_INTEGER;break;case u.TEXTUREFORMAT_RGB_INTEGER:i=this._gl.RGB_INTEGER;break;case u.TEXTUREFORMAT_RGBA_INTEGER:i=this._gl.RGBA_INTEGER}return i},t.prototype._getRGBABufferInternalSizedFormat=function(e,t,i){if(void 0===i&&(i=!1),1===this._webGLVersion){if(void 0!==t)switch(t){case u.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA;case u.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case u.TEXTUREFORMAT_LUMINANCE_ALPHA:return this._gl.LUMINANCE_ALPHA;case u.TEXTUREFORMAT_RGB:return i?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case u.TEXTURETYPE_BYTE:switch(t){case u.TEXTUREFORMAT_RED:return this._gl.R8_SNORM;case u.TEXTUREFORMAT_RG:return this._gl.RG8_SNORM;case u.TEXTUREFORMAT_RGB:return this._gl.RGB8_SNORM;case u.TEXTUREFORMAT_RED_INTEGER:return this._gl.R8I;case u.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG8I;case u.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB8I;case u.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case u.TEXTURETYPE_UNSIGNED_BYTE:switch(t){case u.TEXTUREFORMAT_RED:return this._gl.R8;case u.TEXTUREFORMAT_RG:return this._gl.RG8;case u.TEXTUREFORMAT_RGB:return i?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case u.TEXTUREFORMAT_RGBA:return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case u.TEXTUREFORMAT_RED_INTEGER:return this._gl.R8UI;case u.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG8UI;case u.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB8UI;case u.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGBA8UI;case u.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA;case u.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case u.TEXTUREFORMAT_LUMINANCE_ALPHA:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case u.TEXTURETYPE_SHORT:switch(t){case u.TEXTUREFORMAT_RED_INTEGER:return this._gl.R16I;case u.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG16I;case u.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB16I;case u.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA16I}case u.TEXTURETYPE_UNSIGNED_SHORT:switch(t){case u.TEXTUREFORMAT_RED_INTEGER:return this._gl.R16UI;case u.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG16UI;case u.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB16UI;case u.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA16UI}case u.TEXTURETYPE_INT:switch(t){case u.TEXTUREFORMAT_RED_INTEGER:return this._gl.R32I;case u.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG32I;case u.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB32I;case u.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA32I}case u.TEXTURETYPE_UNSIGNED_INTEGER:switch(t){case u.TEXTUREFORMAT_RED_INTEGER:return this._gl.R32UI;case u.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG32UI;case u.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB32UI;case u.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA32UI}case u.TEXTURETYPE_FLOAT:switch(t){case u.TEXTUREFORMAT_RED:return this._gl.R32F;case u.TEXTUREFORMAT_RG:return this._gl.RG32F;case u.TEXTUREFORMAT_RGB:return this._gl.RGB32F;case u.TEXTUREFORMAT_RGBA:default:return this._gl.RGBA32F}case u.TEXTURETYPE_HALF_FLOAT:switch(t){case u.TEXTUREFORMAT_RED:return this._gl.R16F;case u.TEXTUREFORMAT_RG:return this._gl.RG16F;case u.TEXTUREFORMAT_RGB:return this._gl.RGB16F;case u.TEXTUREFORMAT_RGBA:default:return this._gl.RGBA16F}case u.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.RGB565;case u.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:return this._gl.R11F_G11F_B10F;case u.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:return this._gl.RGB9_E5;case u.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.RGBA4;case u.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.RGB5_A1;case u.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:switch(t){case u.TEXTUREFORMAT_RGBA:return this._gl.RGB10_A2;case u.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGB10_A2UI;default:return this._gl.RGB10_A2}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8},t.prototype.readPixels=function(e,t,i,r,n,o){void 0===n&&(n=!0),void 0===o&&(o=!0);var a=n?4:3,s=n?this._gl.RGBA:this._gl.RGB,l=new Uint8Array(r*i*a);return o&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,r,s,this._gl.UNSIGNED_BYTE,l),Promise.resolve(l)},t.prototype.generateMipMapsForCubemap=function(e,t){},Object.defineProperty(t,"IsSupportedAsync",{get:function(){return Promise.resolve(this.isSupported())},enumerable:!1,configurable:!0}),Object.defineProperty(t,"IsSupported",{get:function(){return this.isSupported()},enumerable:!1,configurable:!0}),t.isSupported=function(){if(null!==this._HasMajorPerformanceCaveat)return!this._HasMajorPerformanceCaveat;if(null===this._IsSupported)try{var e=Mi._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=null!=t&&!!window.WebGLRenderingContext}catch(e){this._IsSupported=!1}return this._IsSupported},Object.defineProperty(t,"HasMajorPerformanceCaveat",{get:function(){if(null===this._HasMajorPerformanceCaveat)try{var e=Mi._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch(e){this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat},enumerable:!1,configurable:!0}),t._TempClearColorUint32=new Uint32Array(4),t._TempClearColorInt32=new Int32Array(4),t.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/12\\d\\..+?Mobile",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}],t.CollisionsEpsilon=.001,t._ConcatenateShader=Vt,t._IsSupported=null,t._HasMajorPerformanceCaveat=null,t.CeilingPOT=er,t.FloorPOT=tr,t.NearestPOT=$i,t.GetExponentOfTwo=ir,t.QueueNewFrame=Ii,t}(Mi);Er.prototype.createUniformBuffer=function(e,t){var i=this._gl.createBuffer();if(!i)throw new Error("Unable to create uniform buffer");var r=new yr(i);return this.bindUniformBuffer(r),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),r.references=1,r},Er.prototype.createDynamicUniformBuffer=function(e,t){var i=this._gl.createBuffer();if(!i)throw new Error("Unable to create dynamic uniform buffer");var r=new yr(i);return this.bindUniformBuffer(r),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),r.references=1,r},Er.prototype.updateUniformBuffer=function(e,t,i,r){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===r?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(i,i+r)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+r)),this.bindUniformBuffer(null)},Er.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},Er.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},Er.prototype.bindUniformBlock=function(e,t,i){var r=e.program,n=this._gl.getUniformBlockIndex(r,t);4294967295!==n&&this._gl.uniformBlockBinding(r,n,i)};var Sr,xr,Ar,Cr,Rr,Pr,Ir,Mr,Or=function(){function e(e,t,i,r,n){void 0===n&&(n=!1),this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||n,this._dynamic=i,this._name=null!=r?r:"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}return Object.defineProperty(e.prototype,"useUbo",{get:function(){return!this._noUBO},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isSync",{get:function(){return!this._needSync},enumerable:!1,configurable:!0}),e.prototype.isDynamic=function(){return void 0!==this._dynamic},e.prototype.getData=function(){return this._bufferData},e.prototype.getBuffer=function(){return this._buffer},e.prototype._fillAlignment=function(e){var t;if(t=e<=2?e:4,this._uniformLocationPointer%t!=0){var i=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;for(var r=this._uniformLocationPointer-i,n=0;n<r;n++)this._data.push(0)}},e.prototype.addUniform=function(e,t,i){if(void 0===i&&(i=0),!this._noUBO&&void 0===this._uniformLocations[e]){var r;if(i>0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},16==t?t*=i:t=t*i+(4-t)*i,r=[];for(var n=0;n<t;n++)r.push(0)}else{if(t instanceof Array)t=(r=t).length;else for(r=[],n=0;n<t;n++)r.push(0);this._fillAlignment(t)}for(this._uniformSizes[e]=t,this._uniformLocations[e]=this._uniformLocationPointer,this._uniformLocationPointer+=t,n=0;n<t;n++)this._data.push(r[n]);this._needSync=!0}},e.prototype.addMatrix=function(e,t){this.addUniform(e,Array.prototype.slice.call(t.asArray()))},e.prototype.addFloat2=function(e,t,i){var r=[t,i];this.addUniform(e,r)},e.prototype.addFloat3=function(e,t,i,r){var n=[t,i,r];this.addUniform(e,n)},e.prototype.addColor3=function(e,t){var i=[t.r,t.g,t.b];this.addUniform(e,i)},e.prototype.addColor4=function(e,t,i){var r=[t.r,t.g,t.b,i];this.addUniform(e,r)},e.prototype.addVector3=function(e,t){var i=[t.x,t.y,t.z];this.addUniform(e,i)},e.prototype.addMatrix3x3=function(e){this.addUniform(e,12)},e.prototype.addMatrix2x2=function(e){this.addUniform(e,8)},e.prototype.create=function(){this._noUBO||this._buffer||(this._fillAlignment(4),this._bufferData=new Float32Array(this._data),this._rebuild(),this._needSync=!0)},e.prototype._getNames=function(){var e=[],t=0;for(var i in this._uniformLocations)if(e.push(i),10==++t)break;return e.join(",")},e.prototype._rebuild=function(){!this._noUBO&&this._bufferData&&(this._dynamic?this._buffer=this._engine.createDynamicUniformBuffer(this._bufferData,this._name+"_UniformList:"+this._getNames()):this._buffer=this._engine.createUniformBuffer(this._bufferData,this._name+"_UniformList:"+this._getNames()),this._engine._features.trackUbosInFrame&&(this._buffers.push([this._buffer,this._engine._features.checkUbosContentBeforeUpload?this._bufferData.slice():void 0]),this._bufferIndex=this._buffers.length-1,this._createBufferOnWrite=!1))},e.prototype._rebuildAfterContextLost=function(){this._engine._features.trackUbosInFrame&&(this._buffers=[],this._currentFrameId=0),this._rebuild()},Object.defineProperty(e.prototype,"_numBuffers",{get:function(){return this._buffers.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"_indexBuffer",{get:function(){return this._bufferIndex},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"name",{get:function(){return this._name},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentEffect",{get:function(){return this._currentEffect},enumerable:!1,configurable:!0}),e.prototype._buffersEqual=function(e,t){for(var i=0;i<e.length;++i)if(e[i]!==t[i])return!1;return!0},e.prototype._copyBuffer=function(e,t){for(var i=0;i<e.length;++i)t[i]=e[i]},e.prototype.update=function(){if(!this._noUBO)if(this.bindUniformBuffer(),this._buffer)if(this._dynamic||this._needSync){if(this._buffers&&this._buffers.length>1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1]))return this._needSync=!1,void(this._createBufferOnWrite=this._engine._features.trackUbosInFrame);this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(e._UpdatedUbosInFrame[this._name]||(e._UpdatedUbosInFrame[this._name]=0),e._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}else this._createBufferOnWrite=this._engine._features.trackUbosInFrame;else this.create()},e.prototype._createNewBuffer=function(){this._bufferIndex+1<this._buffers.length?(this._bufferIndex++,this._buffer=this._buffers[this._bufferIndex][0],this._createBufferOnWrite=!1,this._needSync=!0):this._rebuild()},e.prototype._checkNewFrame=function(){this._engine._features.trackUbosInFrame&&this._currentFrameId!==this._engine.frameId&&(this._currentFrameId=this._engine.frameId,this._createBufferOnWrite=!1,this._buffers&&this._buffers.length>0?(this._needSync=0!==this._bufferIndex,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)},e.prototype.updateUniform=function(e,t,i){this._checkNewFrame();var r=this._uniformLocations[e];if(void 0===r){if(this._buffer)return void ae.Error("Cannot add an uniform after UBO has been created. uniformName="+e);this.addUniform(e,i),r=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(o=0;o<i;o++)this._bufferData[r+o]=t[o];else{for(var n=!1,o=0;o<i;o++)(16===i&&!this._engine._features.uniformBufferHardCheckMatrix||this._bufferData[r+o]!==Math.fround(t[o]))&&(n=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[r+o]=t[o]);this._needSync=this._needSync||n}},e.prototype.updateUniformArray=function(e,t,i){this._checkNewFrame();var r=this._uniformLocations[e];if(void 0!==r){this._buffer||this.create();var n=this._uniformArraySizes[e];if(this._dynamic)for(l=0;l<i;l++)this._bufferData[r+l]=t[l];else{for(var o=!1,a=0,s=0,l=0;l<i;l++)if(this._bufferData[r+4*s+a]!==rr.FloatRound(t[l])&&(o=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[r+4*s+a]=t[l]),++a===n.strideSize){for(;a<4;a++)this._bufferData[r+4*s+a]=0;a=0,s++}this._needSync=this._needSync||o}}else ae.Error("Cannot add an uniform Array dynamically. Please, add it using addUniform and make sure that uniform buffers are supported by the current engine.")},e.prototype._cacheMatrix=function(e,t){this._checkNewFrame();var i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)},e.prototype._updateMatrix3x3ForUniform=function(t,i){for(var r=0;r<3;r++)e._TempBuffer[4*r]=i[3*r],e._TempBuffer[4*r+1]=i[3*r+1],e._TempBuffer[4*r+2]=i[3*r+2],e._TempBuffer[4*r+3]=0;this.updateUniform(t,e._TempBuffer,12)},e.prototype._updateMatrix3x3ForEffect=function(e,t){this._currentEffect.setMatrix3x3(e,t)},e.prototype._updateMatrix2x2ForEffect=function(e,t){this._currentEffect.setMatrix2x2(e,t)},e.prototype._updateMatrix2x2ForUniform=function(t,i){for(var r=0;r<2;r++)e._TempBuffer[4*r]=i[2*r],e._TempBuffer[4*r+1]=i[2*r+1],e._TempBuffer[4*r+2]=0,e._TempBuffer[4*r+3]=0;this.updateUniform(t,e._TempBuffer,8)},e.prototype._updateFloatForEffect=function(e,t){this._currentEffect.setFloat(e,t)},e.prototype._updateFloatForUniform=function(t,i){e._TempBuffer[0]=i,this.updateUniform(t,e._TempBuffer,1)},e.prototype._updateFloat2ForEffect=function(e,t,i,r){void 0===r&&(r=""),this._currentEffect.setFloat2(e+r,t,i)},e.prototype._updateFloat2ForUniform=function(t,i,r){e._TempBuffer[0]=i,e._TempBuffer[1]=r,this.updateUniform(t,e._TempBuffer,2)},e.prototype._updateFloat3ForEffect=function(e,t,i,r,n){void 0===n&&(n=""),this._currentEffect.setFloat3(e+n,t,i,r)},e.prototype._updateFloat3ForUniform=function(t,i,r,n){e._TempBuffer[0]=i,e._TempBuffer[1]=r,e._TempBuffer[2]=n,this.updateUniform(t,e._TempBuffer,3)},e.prototype._updateFloat4ForEffect=function(e,t,i,r,n,o){void 0===o&&(o=""),this._currentEffect.setFloat4(e+o,t,i,r,n)},e.prototype._updateFloat4ForUniform=function(t,i,r,n,o){e._TempBuffer[0]=i,e._TempBuffer[1]=r,e._TempBuffer[2]=n,e._TempBuffer[3]=o,this.updateUniform(t,e._TempBuffer,4)},e.prototype._updateFloatArrayForEffect=function(e,t){this._currentEffect.setFloatArray(e,t)},e.prototype._updateFloatArrayForUniform=function(e,t){this.updateUniformArray(e,t,t.length)},e.prototype._updateArrayForEffect=function(e,t){this._currentEffect.setArray(e,t)},e.prototype._updateArrayForUniform=function(e,t){this.updateUniformArray(e,t,t.length)},e.prototype._updateIntArrayForEffect=function(e,t){this._currentEffect.setIntArray(e,t)},e.prototype._updateIntArrayForUniform=function(t,i){e._TempBufferInt32View.set(i),this.updateUniformArray(t,e._TempBuffer,i.length)},e.prototype._updateUIntArrayForEffect=function(e,t){this._currentEffect.setUIntArray(e,t)},e.prototype._updateUIntArrayForUniform=function(t,i){e._TempBufferUInt32View.set(i),this.updateUniformArray(t,e._TempBuffer,i.length)},e.prototype._updateMatrixForEffect=function(e,t){this._currentEffect.setMatrix(e,t)},e.prototype._updateMatrixForUniform=function(e,t){this._cacheMatrix(e,t)&&this.updateUniform(e,t.asArray(),16)},e.prototype._updateMatricesForEffect=function(e,t){this._currentEffect.setMatrices(e,t)},e.prototype._updateMatricesForUniform=function(e,t){this.updateUniform(e,t,t.length)},e.prototype._updateVector3ForEffect=function(e,t){this._currentEffect.setVector3(e,t)},e.prototype._updateVector3ForUniform=function(t,i){e._TempBuffer[0]=i.x,e._TempBuffer[1]=i.y,e._TempBuffer[2]=i.z,this.updateUniform(t,e._TempBuffer,3)},e.prototype._updateVector4ForEffect=function(e,t){this._currentEffect.setVector4(e,t)},e.prototype._updateVector4ForUniform=function(t,i){e._TempBuffer[0]=i.x,e._TempBuffer[1]=i.y,e._TempBuffer[2]=i.z,e._TempBuffer[3]=i.w,this.updateUniform(t,e._TempBuffer,4)},e.prototype._updateColor3ForEffect=function(e,t,i){void 0===i&&(i=""),this._currentEffect.setColor3(e+i,t)},e.prototype._updateColor3ForUniform=function(t,i){e._TempBuffer[0]=i.r,e._TempBuffer[1]=i.g,e._TempBuffer[2]=i.b,this.updateUniform(t,e._TempBuffer,3)},e.prototype._updateColor4ForEffect=function(e,t,i,r){void 0===r&&(r=""),this._currentEffect.setColor4(e+r,t,i)},e.prototype._updateDirectColor4ForEffect=function(e,t,i){void 0===i&&(i=""),this._currentEffect.setDirectColor4(e+i,t)},e.prototype._updateColor4ForUniform=function(t,i,r){e._TempBuffer[0]=i.r,e._TempBuffer[1]=i.g,e._TempBuffer[2]=i.b,e._TempBuffer[3]=r,this.updateUniform(t,e._TempBuffer,4)},e.prototype._updateDirectColor4ForUniform=function(t,i){e._TempBuffer[0]=i.r,e._TempBuffer[1]=i.g,e._TempBuffer[2]=i.b,e._TempBuffer[3]=i.a,this.updateUniform(t,e._TempBuffer,4)},e.prototype._updateIntForEffect=function(e,t,i){void 0===i&&(i=""),this._currentEffect.setInt(e+i,t)},e.prototype._updateIntForUniform=function(t,i){e._TempBufferInt32View[0]=i,this.updateUniform(t,e._TempBuffer,1)},e.prototype._updateInt2ForEffect=function(e,t,i,r){void 0===r&&(r=""),this._currentEffect.setInt2(e+r,t,i)},e.prototype._updateInt2ForUniform=function(t,i,r){e._TempBufferInt32View[0]=i,e._TempBufferInt32View[1]=r,this.updateUniform(t,e._TempBuffer,2)},e.prototype._updateInt3ForEffect=function(e,t,i,r,n){void 0===n&&(n=""),this._currentEffect.setInt3(e+n,t,i,r)},e.prototype._updateInt3ForUniform=function(t,i,r,n){e._TempBufferInt32View[0]=i,e._TempBufferInt32View[1]=r,e._TempBufferInt32View[2]=n,this.updateUniform(t,e._TempBuffer,3)},e.prototype._updateInt4ForEffect=function(e,t,i,r,n,o){void 0===o&&(o=""),this._currentEffect.setInt4(e+o,t,i,r,n)},e.prototype._updateInt4ForUniform=function(t,i,r,n,o){e._TempBufferInt32View[0]=i,e._TempBufferInt32View[1]=r,e._TempBufferInt32View[2]=n,e._TempBufferInt32View[3]=o,this.updateUniform(t,e._TempBuffer,4)},e.prototype._updateUIntForEffect=function(e,t,i){void 0===i&&(i=""),this._currentEffect.setUInt(e+i,t)},e.prototype._updateUIntForUniform=function(t,i){e._TempBufferUInt32View[0]=i,this.updateUniform(t,e._TempBuffer,1)},e.prototype._updateUInt2ForEffect=function(e,t,i,r){void 0===r&&(r=""),this._currentEffect.setUInt2(e+r,t,i)},e.prototype._updateUInt2ForUniform=function(t,i,r){e._TempBufferUInt32View[0]=i,e._TempBufferUInt32View[1]=r,this.updateUniform(t,e._TempBuffer,2)},e.prototype._updateUInt3ForEffect=function(e,t,i,r,n){void 0===n&&(n=""),this._currentEffect.setUInt3(e+n,t,i,r)},e.prototype._updateUInt3ForUniform=function(t,i,r,n){e._TempBufferUInt32View[0]=i,e._TempBufferUInt32View[1]=r,e._TempBufferUInt32View[2]=n,this.updateUniform(t,e._TempBuffer,3)},e.prototype._updateUInt4ForEffect=function(e,t,i,r,n,o){void 0===o&&(o=""),this._currentEffect.setUInt4(e+o,t,i,r,n)},e.prototype._updateUInt4ForUniform=function(t,i,r,n,o){e._TempBufferUInt32View[0]=i,e._TempBufferUInt32View[1]=r,e._TempBufferUInt32View[2]=n,e._TempBufferUInt32View[3]=o,this.updateUniform(t,e._TempBuffer,4)},e.prototype.setTexture=function(e,t){this._currentEffect.setTexture(e,t)},e.prototype.bindTexture=function(e,t){this._currentEffect._bindTexture(e,t)},e.prototype.updateUniformDirectly=function(e,t){this.updateUniform(e,t,t.length),this.update()},e.prototype.bindToEffect=function(e,t){this._currentEffect=e,this._currentEffectName=t},e.prototype.bindUniformBuffer=function(){!this._noUBO&&this._buffer&&this._currentEffect&&this._currentEffect.bindUniformBuffer(this._buffer,this._currentEffectName)},e.prototype.unbindEffect=function(){this._currentEffect=void 0,this._currentEffectName=void 0},e.prototype.setDataBuffer=function(e){if(!this._buffers)return this._buffer===e;for(var t=0;t<this._buffers.length;++t)if(this._buffers[t][0]===e)return this._bufferIndex=t,this._buffer=e,this._createBufferOnWrite=!1,this._currentEffect=void 0,!0;return!1},e.prototype.dispose=function(){if(!this._noUBO){var e=this._engine._uniformBuffers,t=e.indexOf(this);if(-1!==t&&(e[t]=e[e.length-1],e.pop()),this._engine._features.trackUbosInFrame&&this._buffers)for(var i=0;i<this._buffers.length;++i){var r=this._buffers[i][0];this._engine._releaseBuffer(r)}else this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._buffer=null)}},e._UpdatedUbosInFrame={},e._MAX_UNIFORM_SIZE=256,e._TempBuffer=new Float32Array(e._MAX_UNIFORM_SIZE),e._TempBufferInt32View=new Int32Array(e._TempBuffer.buffer),e._TempBufferUInt32View=new Uint32Array(e._TempBuffer.buffer),e}(),Dr=function(){function e(e,t,i,r,n,o,a,s,l){void 0===r&&(r=0),void 0===n&&(n=!1),void 0===o&&(o=!1),void 0===a&&(a=!1),this._isAlreadyOwned=!1,this._isDisposed=!1,e&&e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=o,this._divisor=s||1,this._label=l,t instanceof vr?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=a?r:r*Float32Array.BYTES_PER_ELEMENT,n||this.create()}return Object.defineProperty(e.prototype,"isDisposed",{get:function(){return this._isDisposed},enumerable:!1,configurable:!0}),e.prototype.createVertexBuffer=function(e,t,i,r,n,o,a){void 0===o&&(o=!1);var s=o?t:t*Float32Array.BYTES_PER_ELEMENT,l=r?o?r:r*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new Nr(this._engine,this,e,this._updatable,!0,l,void 0===n?this._instanced:n,s,i,void 0,void 0,!0,this._divisor||a)},e.prototype.isUpdatable=function(){return this._updatable},e.prototype.getData=function(){return this._data},e.prototype.getBuffer=function(){return this._buffer},e.prototype.getStrideSize=function(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT},e.prototype.create=function(e){void 0===e&&(e=null),!e&&this._buffer||(e=e||this._data)&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e,this._label),this._data=e):this._buffer=this._engine.createVertexBuffer(e,void 0,this._label))},e.prototype._rebuild=function(){if(this._data)this._buffer=null,this.create(this._data);else{if(!this._buffer)return;if(this._buffer.capacity>0)return void(this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label));ae.Warn('Missing data for buffer "'.concat(this._label,'" ').concat(this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":"",". Buffer reconstruction failed.")),this._buffer=null}},e.prototype.update=function(e){this.create(e)},e.prototype.updateDirectly=function(e,t,i,r){void 0===r&&(r=!1),this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,r?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),this._data=0===t&&void 0===i?e:null)},e.prototype._increaseReferences=function(){this._buffer&&(this._isAlreadyOwned?this._buffer.references++:this._isAlreadyOwned=!0)},e.prototype.dispose=function(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)},e}(),Nr=function(){function e(t,i,r,n,o,a,s,l,c,u,h,d,p,f){var _,m,g,v,y;void 0===h&&(h=!1),void 0===d&&(d=!1),void 0===p&&(p=1),void 0===f&&(f=!1),this._isDisposed=!1;var b=!1;if(this.engine=t,"object"==typeof n&&null!==n?(b=null!==(_=n.updatable)&&void 0!==_&&_,o=n.postponeInternalCreation,a=n.stride,s=n.instanced,l=n.offset,c=n.size,u=n.type,h=null!==(m=n.normalized)&&void 0!==m&&m,d=null!==(g=n.useBytes)&&void 0!==g&&g,p=null!==(v=n.divisor)&&void 0!==v?v:1,f=null!==(y=n.takeBufferOwnership)&&void 0!==y&&y,this._label=n.label):b=!!n,i instanceof Dr?(this._buffer=i,this._ownsBuffer=f):(this._buffer=new Dr(t,i,b,a,o,s,d,p,this._label),this._ownsBuffer=!0),this.uniqueId=e._Counter++,this._kind=r,void 0===u){var T=this.getData();this.type=T?e.GetDataType(T):e.FLOAT}else this.type=u;var E=e.GetTypeByteLength(this.type);d?(this._size=c||(a?a/E:e.DeduceStride(r)),this.byteStride=a||this._buffer.byteStride||this._size*E,this.byteOffset=l||0):(this._size=c||a||e.DeduceStride(r),this.byteStride=a?a*E:this._buffer.byteStride||this._size*E,this.byteOffset=(l||0)*E),this.normalized=h,this._instanced=void 0!==s&&s,this._instanceDivisor=s?p:0,this._alignBuffer(),this._computeHashCode()}return Object.defineProperty(e.prototype,"isDisposed",{get:function(){return this._isDisposed},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"instanceDivisor",{get:function(){return this._instanceDivisor},set:function(e){var t=0!=e;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"_maxVerticesCount",{get:function(){var e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0},enumerable:!1,configurable:!0}),e.prototype._computeHashCode=function(){this.hashCode=(this.type-5120|0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)},e.prototype._rebuild=function(){var e;null===(e=this._buffer)||void 0===e||e._rebuild()},e.prototype.getKind=function(){return this._kind},e.prototype.isUpdatable=function(){return this._buffer.isUpdatable()},e.prototype.getData=function(){return this._buffer.getData()},e.prototype.getFloatData=function(t,i){var r=this.getData();return r?e.GetFloatData(r,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,t,i):null},e.prototype.getBuffer=function(){return this._buffer.getBuffer()},e.prototype.getWrapperBuffer=function(){return this._buffer},e.prototype.getStrideSize=function(){return this.byteStride/e.GetTypeByteLength(this.type)},e.prototype.getOffset=function(){return this.byteOffset/e.GetTypeByteLength(this.type)},e.prototype.getSize=function(t){return void 0===t&&(t=!1),t?this._size*e.GetTypeByteLength(this.type):this._size},e.prototype.getIsInstanced=function(){return this._instanced},e.prototype.getInstanceDivisor=function(){return this._instanceDivisor},e.prototype.create=function(e){this._buffer.create(e),this._alignBuffer()},e.prototype.update=function(e){this._buffer.update(e),this._alignBuffer()},e.prototype.updateDirectly=function(e,t,i){void 0===i&&(i=!1),this._buffer.updateDirectly(e,t,void 0,i),this._alignBuffer()},e.prototype.dispose=function(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0},e.prototype.forEach=function(t,i){e.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,t,this.normalized,i)},e.prototype._alignBuffer=function(){},e.DeduceStride=function(t){switch(t){case e.UVKind:case e.UV2Kind:case e.UV3Kind:case e.UV4Kind:case e.UV5Kind:case e.UV6Kind:return 2;case e.NormalKind:case e.PositionKind:return 3;case e.ColorKind:case e.ColorInstanceKind:case e.MatricesIndicesKind:case e.MatricesIndicesExtraKind:case e.MatricesWeightsKind:case e.MatricesWeightsExtraKind:case e.TangentKind:return 4;default:throw new Error("Invalid kind '"+t+"'")}},e.GetDataType=function(t){return t instanceof Int8Array?e.BYTE:t instanceof Uint8Array?e.UNSIGNED_BYTE:t instanceof Int16Array?e.SHORT:t instanceof Uint16Array?e.UNSIGNED_SHORT:t instanceof Int32Array?e.INT:t instanceof Uint32Array?e.UNSIGNED_INT:e.FLOAT},e.GetTypeByteLength=function(t){switch(t){case e.BYTE:case e.UNSIGNED_BYTE:return 1;case e.SHORT:case e.UNSIGNED_SHORT:return 2;case e.INT:case e.UNSIGNED_INT:case e.FLOAT:return 4;default:throw new Error("Invalid type '".concat(t,"'"))}},e.ForEach=function(t,i,r,n,o,a,s,l){if(t instanceof Array)for(var c=i/4,u=r/4,h=0;h<a;h+=n){for(var d=0;d<n;d++)l(t[c+d],h+d);c+=u}else{var p=t instanceof ArrayBuffer?new DataView(t):new DataView(t.buffer,t.byteOffset,t.byteLength),f=e.GetTypeByteLength(o);for(h=0;h<a;h+=n){var _=i;for(d=0;d<n;d++)l(e._GetFloatValue(p,o,_,s),h+d),_+=f;i+=r}}},e._GetFloatValue=function(t,i,r,n){switch(i){case e.BYTE:var o=t.getInt8(r);return n&&(o=Math.max(o/127,-1)),o;case e.UNSIGNED_BYTE:return o=t.getUint8(r),n&&(o/=255),o;case e.SHORT:return o=t.getInt16(r,!0),n&&(o=Math.max(o/32767,-1)),o;case e.UNSIGNED_SHORT:return o=t.getUint16(r,!0),n&&(o/=65535),o;case e.INT:return t.getInt32(r,!0);case e.UNSIGNED_INT:return t.getUint32(r,!0);case e.FLOAT:return t.getFloat32(r,!0);default:throw new Error("Invalid component type ".concat(i))}},e.GetFloatData=function(t,i,r,n,o,a,s,l){var c=i*e.GetTypeByteLength(r),u=s*i;if(r!==e.FLOAT||o!==c){var h=new Float32Array(u);return e.ForEach(t,n,o,i,r,u,a,(function(e,t){return h[t]=e})),h}if(!(t instanceof Array||t instanceof Float32Array)||0!==n||t.length!==u){if(t instanceof Array){var d=n/4;return t.slice(d,d+u)}if(t instanceof ArrayBuffer)return new Float32Array(t,n,u);if(d=t.byteOffset+n,l){var p=new Float32Array(u),f=new Float32Array(t.buffer,d,u);return p.set(f),p}var _=d%4;return _&&(d=Math.max(0,d-_)),new Float32Array(t.buffer,d,u)}return l?t.slice():t},e._Counter=0,e.BYTE=u.BYTE,e.UNSIGNED_BYTE=u.UNSIGNED_BYTE,e.SHORT=u.SHORT,e.UNSIGNED_SHORT=u.UNSIGNED_SHORT,e.INT=u.INT,e.UNSIGNED_INT=u.UNSIGNED_INT,e.FLOAT=u.FLOAT,e.PositionKind=u.PositionKind,e.NormalKind=u.NormalKind,e.TangentKind=u.TangentKind,e.UVKind=u.UVKind,e.UV2Kind=u.UV2Kind,e.UV3Kind=u.UV3Kind,e.UV4Kind=u.UV4Kind,e.UV5Kind=u.UV5Kind,e.UV6Kind=u.UV6Kind,e.ColorKind=u.ColorKind,e.ColorInstanceKind=u.ColorInstanceKind,e.MatricesIndicesKind=u.MatricesIndicesKind,e.MatricesWeightsKind=u.MatricesWeightsKind,e.MatricesIndicesExtraKind=u.MatricesIndicesExtraKind,e.MatricesWeightsExtraKind=u.MatricesWeightsExtraKind,e}(),Fr=function(){function e(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshFaceId=-1,this.subMeshId=0,this.pickedSprite=null,this.thinInstanceIndex=-1,this.ray=null,this.originMesh=null,this.aimTransform=null,this.gripTransform=null}return e.prototype.getNormal=function(e,t){if(void 0===e&&(e=!1),void 0===t&&(t=!0),!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(Nr.NormalKind))return null;var i,r=this.pickedMesh.getIndices();0===(null==r?void 0:r.length)&&(r=null);var n=H.Vector3[0],o=H.Vector3[1],a=H.Vector3[2];if(t){var s=this.pickedMesh.getVerticesData(Nr.NormalKind),l=r?V.FromArrayToRef(s,3*r[3*this.faceId],n):n.copyFromFloats(s[3*this.faceId*3],s[3*this.faceId*3+1],s[3*this.faceId*3+2]),c=r?V.FromArrayToRef(s,3*r[3*this.faceId+1],o):o.copyFromFloats(s[3*(3*this.faceId+1)],s[3*(3*this.faceId+1)+1],s[3*(3*this.faceId+1)+2]),u=r?V.FromArrayToRef(s,3*r[3*this.faceId+2],a):a.copyFromFloats(s[3*(3*this.faceId+2)],s[3*(3*this.faceId+2)+1],s[3*(3*this.faceId+2)+2]);l=l.scale(this.bu),c=c.scale(this.bv),u=u.scale(1-this.bu-this.bv),i=new V(l.x+c.x+u.x,l.y+c.y+u.y,l.z+c.z+u.z)}else{var h=this.pickedMesh.getVerticesData(Nr.PositionKind),d=r?V.FromArrayToRef(h,3*r[3*this.faceId],n):n.copyFromFloats(h[3*this.faceId*3],h[3*this.faceId*3+1],h[3*this.faceId*3+2]),p=r?V.FromArrayToRef(h,3*r[3*this.faceId+1],o):o.copyFromFloats(h[3*(3*this.faceId+1)],h[3*(3*this.faceId+1)+1],h[3*(3*this.faceId+1)+2]),f=r?V.FromArrayToRef(h,3*r[3*this.faceId+2],a):a.copyFromFloats(h[3*(3*this.faceId+2)],h[3*(3*this.faceId+2)+1],h[3*(3*this.faceId+2)+2]),_=d.subtract(p),m=f.subtract(p);i=V.Cross(_,m)}var g=function(e,t){var i=e.getWorldMatrix();e.nonUniformScaling&&(H.Matrix[0].copyFrom(i),(i=H.Matrix[0]).setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(H.Matrix[1]),i=H.Matrix[1]),V.TransformNormalToRef(t,i,t)};if(e&&g(this.pickedMesh,i),this.ray){var v=H.Vector3[0].copyFrom(i);e||g(this.pickedMesh,v),V.Dot(v,this.ray.direction)>0&&i.negateInPlace()}return i.normalize(),i},e.prototype.getTextureCoordinates=function(e){if(void 0===e&&(e=Nr.UVKind),!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;var t=this.pickedMesh.getIndices();if(!t)return null;var i=this.pickedMesh.getVerticesData(e);if(!i)return null;var r=U.FromArray(i,2*t[3*this.faceId]),n=U.FromArray(i,2*t[3*this.faceId+1]),o=U.FromArray(i,2*t[3*this.faceId+2]);return r=r.scale(this.bu),n=n.scale(this.bv),o=o.scale(1-this.bu-this.bv),new U(r.x+n.x+o.x,r.y+n.y+o.y)},e}(),Lr=function(){function e(e){this._vertexBuffers={},this._scene=e}return e.prototype._prepareBuffers=function(){if(!this._vertexBuffers[Nr.PositionKind]){var e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[Nr.PositionKind]=new Nr(this._scene.getEngine(),e,Nr.PositionKind,!1,!1,2),this._buildIndexBuffer()}},e.prototype._buildIndexBuffer=function(){var e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)},e.prototype._rebuild=function(){var e=this._vertexBuffers[Nr.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())},e.prototype._prepareFrame=function(e,t){void 0===e&&(e=null),void 0===t&&(t=null);var i=this._scene.activeCamera;return!(!i||!(t=t||i._postProcesses.filter((function(e){return null!=e})))||0===t.length||!this._scene.postProcessesEnabled||(t[0].activate(i,e,null!=t),0))},e.prototype.directRender=function(e,t,i,r,n,o){var a;void 0===t&&(t=null),void 0===i&&(i=!1),void 0===r&&(r=0),void 0===n&&(n=0),void 0===o&&(o=!1);for(var s=this._scene.getEngine(),l=0;l<e.length;l++){l<e.length-1?e[l+1].activate(this._scene.activeCamera,null==t?void 0:t.texture):(t?s.bindFramebuffer(t,r,void 0,void 0,i,n):o||s.restoreDefaultFramebuffer(),null===(a=s._debugInsertMarker)||void 0===a||a.call(s,"post process ".concat(e[l].name," output")));var c=e[l],h=c.apply();h&&(c.onBeforeRenderObservable.notifyObservers(h),this._prepareBuffers(),s.bindBuffers(this._vertexBuffers,this._indexBuffer,h),s.drawElementsType(u.MATERIAL_TriangleFillMode,0,6),c.onAfterRenderObservable.notifyObservers(h))}s.setDepthBuffer(!0),s.setDepthWrite(!0)},e.prototype._finalizeFrame=function(e,t,i,r,n){var o;void 0===n&&(n=!1);var a=this._scene.activeCamera;if(a&&(r=r||a._postProcesses.filter((function(e){return null!=e})),0!==r.length&&this._scene.postProcessesEnabled)){for(var s=this._scene.getEngine(),l=0,c=r.length;l<c;l++){var h=r[l];if(l<c-1?h._outputTexture=r[l+1].activate(a,null==t?void 0:t.texture):(t?(s.bindFramebuffer(t,i,void 0,void 0,n),h._outputTexture=t):(s.restoreDefaultFramebuffer(),h._outputTexture=null),null===(o=s._debugInsertMarker)||void 0===o||o.call(s,"post process ".concat(r[l].name," output"))),e)break;var d=h.apply();d&&(h.onBeforeRenderObservable.notifyObservers(d),this._prepareBuffers(),s.bindBuffers(this._vertexBuffers,this._indexBuffer,d),s.drawElementsType(u.MATERIAL_TriangleFillMode,0,6),h.onAfterRenderObservable.notifyObservers(d))}s.setDepthBuffer(!0),s.setDepthWrite(!0),s.setAlphaMode(u.ALPHA_DISABLE)}},e.prototype.dispose=function(){var e=this._vertexBuffers[Nr.PositionKind];e&&(e.dispose(),this._vertexBuffers[Nr.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null)},e}(),wr=function(){function e(e,t,i,r,n){void 0===i&&(i=null),void 0===r&&(r=null),void 0===n&&(n=null),this.index=e,this._opaqueSubMeshes=new ar(256),this._transparentSubMeshes=new ar(256),this._alphaTestSubMeshes=new ar(256),this._depthOnlySubMeshes=new ar(256),this._particleSystems=new ar(256),this._spriteManagers=new ar(256),this._empty=!0,this._edgesRenderers=new sr(16),this._scene=t,this.opaqueSortCompareFn=i,this.alphaTestSortCompareFn=r,this.transparentSortCompareFn=n}return Object.defineProperty(e.prototype,"opaqueSortCompareFn",{set:function(t){this._opaqueSortCompareFn=t||e.PainterSortCompare,this._renderOpaque=this._renderOpaqueSorted},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"alphaTestSortCompareFn",{set:function(t){this._alphaTestSortCompareFn=t||e.PainterSortCompare,this._renderAlphaTest=this._renderAlphaTestSorted},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"transparentSortCompareFn",{set:function(t){this._transparentSortCompareFn=t||e.defaultTransparentSortCompare,this._renderTransparent=this._renderTransparentSorted},enumerable:!1,configurable:!0}),e.prototype.render=function(e,t,i,r){if(e)e(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes,this._depthOnlySubMeshes);else{var n=this._scene.getEngine();0!==this._depthOnlySubMeshes.length&&(n.setColorWrite(!1),this._renderAlphaTest(this._depthOnlySubMeshes),n.setColorWrite(!0)),0!==this._opaqueSubMeshes.length&&this._renderOpaque(this._opaqueSubMeshes),0!==this._alphaTestSubMeshes.length&&this._renderAlphaTest(this._alphaTestSubMeshes);var o=n.getStencilBuffer();if(n.setStencilBuffer(!1),t&&this._renderSprites(),i&&this._renderParticles(r),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),0!==this._transparentSubMeshes.length||this._scene.useOrderIndependentTransparency){if(n.setStencilBuffer(o),this._scene.useOrderIndependentTransparency){var a=this._scene.depthPeelingRenderer.render(this._transparentSubMeshes);a.length&&this._renderTransparent(a)}else this._renderTransparent(this._transparentSubMeshes);n.setAlphaMode(u.ALPHA_DISABLE)}if(n.setStencilBuffer(!1),this._edgesRenderers.length){for(var s=0;s<this._edgesRenderers.length;s++)this._edgesRenderers.data[s].render();n.setAlphaMode(u.ALPHA_DISABLE)}n.setStencilBuffer(o)}},e.prototype._renderOpaqueSorted=function(t){e._RenderSorted(t,this._opaqueSortCompareFn,this._scene.activeCamera,!1)},e.prototype._renderAlphaTestSorted=function(t){e._RenderSorted(t,this._alphaTestSortCompareFn,this._scene.activeCamera,!1)},e.prototype._renderTransparentSorted=function(t){e._RenderSorted(t,this._transparentSortCompareFn,this._scene.activeCamera,!0)},e._RenderSorted=function(t,i,r,n){var o,a=0,s=r?r.globalPosition:e._ZeroVector;if(n)for(;a<t.length;a++)(o=t.data[a])._alphaIndex=o.getMesh().alphaIndex,o._distanceToCamera=V.Distance(o.getBoundingInfo().boundingSphere.centerWorld,s);var l=t.length===t.data.length?t.data:t.data.slice(0,t.length);i&&l.sort(i);var c=l[0].getMesh().getScene();for(a=0;a<l.length;a++)if(o=l[a],!c._activeMeshesFrozenButKeepClipping||o.isInFrustum(c._frustumPlanes)){if(n){var h=o.getMaterial();if(h&&h.needDepthPrePass){var d=h.getScene().getEngine();d.setColorWrite(!1),d.setAlphaMode(u.ALPHA_DISABLE),o.render(!1),d.setColorWrite(!0)}}o.render(n)}},e.defaultTransparentSortCompare=function(t,i){return t._alphaIndex>i._alphaIndex?1:t._alphaIndex<i._alphaIndex?-1:e.backToFrontSortCompare(t,i)},e.backToFrontSortCompare=function(e,t){return e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0},e.frontToBackSortCompare=function(e,t){return e._distanceToCamera<t._distanceToCamera?-1:e._distanceToCamera>t._distanceToCamera?1:0},e.PainterSortCompare=function(e,t){var i=e.getMesh(),r=t.getMesh();return i.material&&r.material?i.material.uniqueId-r.material.uniqueId:i.uniqueId-r.uniqueId},e.prototype.prepare=function(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0},e.prototype.prepareSprites=function(){this._spriteManagers.reset()},e.prototype.dispose=function(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()},e.prototype.dispatch=function(e,t,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t.isEnabled()&&t.isVisible&&t._edgesRenderer.isEnabled&&this._edgesRenderers.pushNoDuplicate(t._edgesRenderer),this._empty=!1)},e.prototype.dispatchSprites=function(e){this._spriteManagers.push(e),this._empty=!1},e.prototype.dispatchParticles=function(e){this._particleSystems.push(e),this._empty=!1},e.prototype._renderParticles=function(e){if(0!==this._particleSystems.length){var t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(var i=0;i<this._particleSystems.length;i++){var r=this._particleSystems.data[i];if(0!==(t&&t.layerMask&r.layerMask)){var n=r.emitter;n.position&&e&&-1===e.indexOf(n)||this._scene._activeParticles.addCount(r.render(),!1)}}this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene)}},e.prototype._renderSprites=function(){if(this._scene.spritesEnabled&&0!==this._spriteManagers.length){var e=this._scene.activeCamera;this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);for(var t=0;t<this._spriteManagers.length;t++){var i=this._spriteManagers.data[t];0!==(e&&e.layerMask&i.layerMask)&&i.render()}this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene)}},e._ZeroVector=V.Zero(),e}(),Br=function(){},Ur=function(){function e(t){this._useSceneAutoClearSetup=!1,this._renderingGroups=new Array,this._autoClearDepthStencil={},this._customOpaqueSortCompareFn={},this._customAlphaTestSortCompareFn={},this._customTransparentSortCompareFn={},this._renderingGroupInfo=new Br,this._maintainStateBetweenFrames=!1,this._scene=t;for(var i=e.MIN_RENDERINGGROUPS;i<e.MAX_RENDERINGGROUPS;i++)this._autoClearDepthStencil[i]={autoClear:!0,depth:!0,stencil:!0}}return Object.defineProperty(e.prototype,"maintainStateBetweenFrames",{get:function(){return this._maintainStateBetweenFrames},set:function(e){e!==this._maintainStateBetweenFrames&&(this._maintainStateBetweenFrames=e,this._maintainStateBetweenFrames||this.restoreDispachedFlags())},enumerable:!1,configurable:!0}),e.prototype.restoreDispachedFlags=function(){for(var e=0,t=this._scene.meshes;e<t.length;e++){var i=t[e];if(i.subMeshes)for(var r=0,n=i.subMeshes;r<n.length;r++)n[r]._wasDispatched=!1}if(this._scene.spriteManagers)for(var o=0,a=this._scene.spriteManagers;o<a.length;o++)a[o]._wasDispatched=!1;for(var s=0,l=this._scene.particleSystems;s<l.length;s++)l[s]._wasDispatched=!1},e.prototype.getRenderingGroup=function(e){var t=e||0;return this._prepareRenderingGroup(t),this._renderingGroups[t]},e.prototype._clearDepthStencilBuffer=function(e,t){void 0===e&&(e=!0),void 0===t&&(t=!0),this._depthStencilBufferAlreadyCleaned||(this._scene.getEngine().clear(null,!1,e,t),this._depthStencilBufferAlreadyCleaned=!0)},e.prototype.render=function(t,i,r,n){var o=this._renderingGroupInfo;if(o.scene=this._scene,o.camera=this._scene.activeCamera,this._scene.spriteManagers&&n)for(var a=0;a<this._scene.spriteManagers.length;a++){var s=this._scene.spriteManagers[a];this.dispatchSprites(s)}for(a=e.MIN_RENDERINGGROUPS;a<e.MAX_RENDERINGGROUPS;a++){this._depthStencilBufferAlreadyCleaned=a===e.MIN_RENDERINGGROUPS;var l=this._renderingGroups[a];if(l&&!l._empty){var c=1<<a;if(o.renderingGroupId=a,this._scene.onBeforeRenderingGroupObservable.notifyObservers(o,c),e.AUTOCLEAR){var u=this._useSceneAutoClearSetup?this._scene.getAutoClearDepthStencilSetup(a):this._autoClearDepthStencil[a];u&&u.autoClear&&this._clearDepthStencilBuffer(u.depth,u.stencil)}for(var h=0,d=this._scene._beforeRenderingGroupDrawStage;h<d.length;h++)d[h].action(a);l.render(t,n,r,i);for(var p=0,f=this._scene._afterRenderingGroupDrawStage;p<f.length;p++)f[p].action(a);this._scene.onAfterRenderingGroupObservable.notifyObservers(o,c)}}},e.prototype.reset=function(){if(!this.maintainStateBetweenFrames)for(var t=e.MIN_RENDERINGGROUPS;t<e.MAX_RENDERINGGROUPS;t++){var i=this._renderingGroups[t];i&&i.prepare()}},e.prototype.resetSprites=function(){if(!this.maintainStateBetweenFrames)for(var t=e.MIN_RENDERINGGROUPS;t<e.MAX_RENDERINGGROUPS;t++){var i=this._renderingGroups[t];i&&i.prepareSprites()}},e.prototype.dispose=function(){this.freeRenderingGroups(),this._renderingGroups.length=0,this._renderingGroupInfo=null},e.prototype.freeRenderingGroups=function(){for(var t=e.MIN_RENDERINGGROUPS;t<e.MAX_RENDERINGGROUPS;t++){var i=this._renderingGroups[t];i&&i.dispose()}},e.prototype._prepareRenderingGroup=function(e){void 0===this._renderingGroups[e]&&(this._renderingGroups[e]=new wr(e,this._scene,this._customOpaqueSortCompareFn[e],this._customAlphaTestSortCompareFn[e],this._customTransparentSortCompareFn[e]))},e.prototype.dispatchSprites=function(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchSprites(e))},e.prototype.dispatchParticles=function(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchParticles(e))},e.prototype.dispatch=function(e,t,i){void 0===t&&(t=e.getMesh()),this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(t.renderingGroupId).dispatch(e,t,i))},e.prototype.setRenderingOrder=function(e,t,i,r){if(void 0===t&&(t=null),void 0===i&&(i=null),void 0===r&&(r=null),this._customOpaqueSortCompareFn[e]=t,this._customAlphaTestSortCompareFn[e]=i,this._customTransparentSortCompareFn[e]=r,this._renderingGroups[e]){var n=this._renderingGroups[e];n.opaqueSortCompareFn=this._customOpaqueSortCompareFn[e],n.alphaTestSortCompareFn=this._customAlphaTestSortCompareFn[e],n.transparentSortCompareFn=this._customTransparentSortCompareFn[e]}},e.prototype.setRenderingAutoClearDepthStencil=function(e,t,i,r){void 0===i&&(i=!0),void 0===r&&(r=!0),this._autoClearDepthStencil[e]={autoClear:t,depth:i,stencil:r}},e.prototype.getAutoClearDepthStencilSetup=function(e){return this._autoClearDepthStencil[e]},e.MAX_RENDERINGGROUPS=4,e.MIN_RENDERINGGROUPS=0,e.AUTOCLEAR=!0,e}(),Vr=function(){function e(){}return e.NAME_EFFECTLAYER="EffectLayer",e.NAME_LAYER="Layer",e.NAME_LENSFLARESYSTEM="LensFlareSystem",e.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer",e.NAME_PARTICLESYSTEM="ParticleSystem",e.NAME_GAMEPAD="Gamepad",e.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue",e.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer",e.NAME_PREPASSRENDERER="PrePassRenderer",e.NAME_DEPTHRENDERER="DepthRenderer",e.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer",e.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager",e.NAME_SPRITE="Sprite",e.NAME_SUBSURFACE="SubSurface",e.NAME_OUTLINERENDERER="Outline",e.NAME_PROCEDURALTEXTURE="ProceduralTexture",e.NAME_SHADOWGENERATOR="ShadowGenerator",e.NAME_OCTREE="Octree",e.NAME_PHYSICSENGINE="PhysicsEngine",e.NAME_AUDIO="Audio",e.NAME_FLUIDRENDERER="FluidRenderer",e.STEP_ISREADYFORMESH_EFFECTLAYER=0,e.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0,e.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0,e.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0,e.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1,e.STEP_BEFORECAMERADRAW_PREPASS=0,e.STEP_BEFORECAMERADRAW_EFFECTLAYER=1,e.STEP_BEFORECAMERADRAW_LAYER=2,e.STEP_BEFORERENDERTARGETDRAW_PREPASS=0,e.STEP_BEFORERENDERTARGETDRAW_LAYER=1,e.STEP_BEFORERENDERINGMESH_PREPASS=0,e.STEP_BEFORERENDERINGMESH_OUTLINE=1,e.STEP_AFTERRENDERINGMESH_PREPASS=0,e.STEP_AFTERRENDERINGMESH_OUTLINE=1,e.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0,e.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1,e.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0,e.STEP_BEFORECAMERAUPDATE_GAMEPAD=1,e.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0,e.STEP_BEFORECLEAR_PREPASS=1,e.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0,e.STEP_AFTERRENDERTARGETDRAW_PREPASS=0,e.STEP_AFTERRENDERTARGETDRAW_LAYER=1,e.STEP_AFTERCAMERADRAW_PREPASS=0,e.STEP_AFTERCAMERADRAW_EFFECTLAYER=1,e.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2,e.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3,e.STEP_AFTERCAMERADRAW_LAYER=4,e.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5,e.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0,e.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0,e.STEP_AFTERRENDER_AUDIO=0,e.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0,e.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1,e.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2,e.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3,e.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0,e.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1,e.STEP_POINTERMOVE_SPRITE=0,e.STEP_POINTERDOWN_SPRITE=0,e.STEP_POINTERUP_SPRITE=0,e}(),kr=function(e){function t(t){return e.apply(this,t)||this}return m(t,e),t.Create=function(){return Object.create(t.prototype)},t.prototype.registerStep=function(e,t,i){var r=0;for(Number.MAX_VALUE;r<this.length&&!(e<this[r].index);r++);this.splice(r,0,{index:e,component:t,action:i.bind(t)})},t.prototype.clear=function(){this.length=0},t}(Array),Gr=function(){function e(){}return e.POINTERDOWN=1,e.POINTERUP=2,e.POINTERMOVE=4,e.POINTERWHEEL=8,e.POINTERPICK=16,e.POINTERTAP=32,e.POINTERDOUBLETAP=64,e}(),zr=function(e,t){this.type=e,this.event=t},Wr=function(e){function t(t,i,r,n){var o=e.call(this,t,i)||this;return o.ray=null,o.originalPickingInfo=null,o.skipOnPointerObservable=!1,o.localPosition=new U(r,n),o}return m(t,e),t}(zr),Hr=function(e){function t(t,i,r,n){void 0===n&&(n=null);var o=e.call(this,t,i)||this;return o._pickInfo=r,o._inputManager=n,o}return m(t,e),Object.defineProperty(t.prototype,"pickInfo",{get:function(){return this._pickInfo||this._generatePickInfo(),this._pickInfo},enumerable:!1,configurable:!0}),t.prototype._generatePickInfo=function(){this._inputManager&&(this._pickInfo=this._inputManager._pickMove(this.event),this._inputManager._setRayOnPointerInfo(this._pickInfo,this.event),this._inputManager=null)},t}(zr),Xr=function(){function e(){}return e.KEYDOWN=1,e.KEYUP=2,e}(),jr=function(e,t){this.type=e,this.event=t},Yr=function(e){function t(t,i){var r=e.call(this,t,i)||this;return r.type=t,r.event=i,r.skipOnKeyboardObservable=!1,r}return m(t,e),Object.defineProperty(t.prototype,"skipOnPointerObservable",{get:function(){return this.skipOnKeyboardObservable},set:function(e){this.skipOnKeyboardObservable=e},enumerable:!1,configurable:!0}),t}(jr);!function(e){e[e.Generic=0]="Generic",e[e.Keyboard=1]="Keyboard",e[e.Mouse=2]="Mouse",e[e.Touch=3]="Touch",e[e.DualShock=4]="DualShock",e[e.Xbox=5]="Xbox",e[e.Switch=6]="Switch",e[e.DualSense=7]="DualSense"}(Sr||(Sr={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical",e[e.LeftClick=2]="LeftClick",e[e.MiddleClick=3]="MiddleClick",e[e.RightClick=4]="RightClick",e[e.BrowserBack=5]="BrowserBack",e[e.BrowserForward=6]="BrowserForward",e[e.MouseWheelX=7]="MouseWheelX",e[e.MouseWheelY=8]="MouseWheelY",e[e.MouseWheelZ=9]="MouseWheelZ",e[e.Move=12]="Move"}(xr||(xr={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical",e[e.LeftClick=2]="LeftClick",e[e.MiddleClick=3]="MiddleClick",e[e.RightClick=4]="RightClick",e[e.BrowserBack=5]="BrowserBack",e[e.BrowserForward=6]="BrowserForward",e[e.MouseWheelX=7]="MouseWheelX",e[e.MouseWheelY=8]="MouseWheelY",e[e.MouseWheelZ=9]="MouseWheelZ",e[e.DeltaHorizontal=10]="DeltaHorizontal",e[e.DeltaVertical=11]="DeltaVertical"}(Ar||(Ar={})),function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.L2=6]="L2",e[e.R2=7]="R2",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.L3=10]="L3",e[e.R3=11]="R3",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.TouchPad=17]="TouchPad",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(Cr||(Cr={})),function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.L2=6]="L2",e[e.R2=7]="R2",e[e.Create=8]="Create",e[e.Options=9]="Options",e[e.L3=10]="L3",e[e.R3=11]="R3",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.TouchPad=17]="TouchPad",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(Rr||(Rr={})),function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.LT=6]="LT",e[e.RT=7]="RT",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LS=10]="LS",e[e.RS=11]="RS",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.LStickXAxis=17]="LStickXAxis",e[e.LStickYAxis=18]="LStickYAxis",e[e.RStickXAxis=19]="RStickXAxis",e[e.RStickYAxis=20]="RStickYAxis"}(Pr||(Pr={})),function(e){e[e.B=0]="B",e[e.A=1]="A",e[e.Y=2]="Y",e[e.X=3]="X",e[e.L=4]="L",e[e.R=5]="R",e[e.ZL=6]="ZL",e[e.ZR=7]="ZR",e[e.Minus=8]="Minus",e[e.Plus=9]="Plus",e[e.LS=10]="LS",e[e.RS=11]="RS",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.Capture=17]="Capture",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(Ir||(Ir={})),function(e){e[e.PointerMove=0]="PointerMove",e[e.PointerDown=1]="PointerDown",e[e.PointerUp=2]="PointerUp"}(Mr||(Mr={}));var Kr,Qr=function(){function e(){}return e.DOM_DELTA_PIXEL=0,e.DOM_DELTA_LINE=1,e.DOM_DELTA_PAGE=2,e}(),qr=function(){function e(){}return e.CreateDeviceEvent=function(e,t,i,r,n,o,a){switch(e){case Sr.Keyboard:return this._CreateKeyboardEvent(i,r,n,o);case Sr.Mouse:if(i===xr.MouseWheelX||i===xr.MouseWheelY||i===xr.MouseWheelZ)return this._CreateWheelEvent(e,t,i,r,n,o);case Sr.Touch:return this._CreatePointerEvent(e,t,i,r,n,o,a);default:throw"Unable to generate event for device ".concat(Sr[e])}},e._CreatePointerEvent=function(e,t,i,r,n,o,a){var s=this._CreateMouseEvent(e,t,i,r,n,o);e===Sr.Mouse?(s.deviceType=Sr.Mouse,s.pointerId=1,s.pointerType="mouse"):(s.deviceType=Sr.Touch,s.pointerId=null!=a?a:t,s.pointerType="touch");var l=0;return l+=n.pollInput(e,t,xr.LeftClick),l+=2*n.pollInput(e,t,xr.RightClick),l+=4*n.pollInput(e,t,xr.MiddleClick),s.buttons=l,i===xr.Move?s.type="pointermove":i>=xr.LeftClick&&i<=xr.RightClick&&(s.type=1===r?"pointerdown":"pointerup",s.button=i-2),s},e._CreateWheelEvent=function(e,t,i,r,n,o){var a=this._CreateMouseEvent(e,t,i,r,n,o);switch(a.pointerId=1,a.type="wheel",a.deltaMode=Qr.DOM_DELTA_PIXEL,a.deltaX=0,a.deltaY=0,a.deltaZ=0,i){case xr.MouseWheelX:a.deltaX=r;break;case xr.MouseWheelY:a.deltaY=r;break;case xr.MouseWheelZ:a.deltaZ=r}return a},e._CreateMouseEvent=function(e,t,i,r,n,o){var a=this._CreateEvent(o),s=n.pollInput(e,t,xr.Horizontal),l=n.pollInput(e,t,xr.Vertical);return o?(a.movementX=0,a.movementY=0,a.offsetX=a.movementX-o.getBoundingClientRect().x,a.offsetY=a.movementY-o.getBoundingClientRect().y):(a.movementX=n.pollInput(e,t,Ar.DeltaHorizontal),a.movementY=n.pollInput(e,t,Ar.DeltaVertical),a.offsetX=0,a.offsetY=0),this._CheckNonCharacterKeys(a,n),a.clientX=s,a.clientY=l,a.x=s,a.y=l,a.deviceType=e,a.deviceSlot=t,a.inputIndex=i,a},e._CreateKeyboardEvent=function(e,t,i,r){var n=this._CreateEvent(r);return this._CheckNonCharacterKeys(n,i),n.deviceType=Sr.Keyboard,n.deviceSlot=0,n.inputIndex=e,n.type=1===t?"keydown":"keyup",n.key=String.fromCharCode(e),n.keyCode=e,n},e._CheckNonCharacterKeys=function(e,t){var i=t.isDeviceAvailable(Sr.Keyboard),r=i&&1===t.pollInput(Sr.Keyboard,0,u.INPUT_ALT_KEY),n=i&&1===t.pollInput(Sr.Keyboard,0,u.INPUT_CTRL_KEY),o=i&&(1===t.pollInput(Sr.Keyboard,0,u.INPUT_META_KEY1)||1===t.pollInput(Sr.Keyboard,0,u.INPUT_META_KEY2)||1===t.pollInput(Sr.Keyboard,0,u.INPUT_META_KEY3)),a=i&&1===t.pollInput(Sr.Keyboard,0,u.INPUT_SHIFT_KEY);e.altKey=r,e.ctrlKey=n,e.metaKey=o,e.shiftKey=a},e._CreateEvent=function(e){var t={preventDefault:function(){}};return t.target=e,t},e}(),Zr=function(){function e(e,t,i){var r=this;this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(function(e,t,n,o){var a=qr.CreateDeviceEvent(e,t,n,o,r);i(e,t,a)})):this._createDummyNativeInput()}return e.prototype.pollInput=function(e,t,i){return this._nativeInput.pollInput(e,t,i)},e.prototype.isDeviceAvailable=function(e){return e===Sr.Mouse||e===Sr.Touch},e.prototype.dispose=function(){this._nativeInput.dispose()},e.prototype._createDummyNativeInput=function(){return{pollInput:function(){return 0},isDeviceAvailable:function(){return!1},dispose:function(){}}},e}(),Jr=Object.keys(xr).length/2,$r=function(){function e(e,t,i,r){var n=this;this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=rr.IsSafari(),this._usingMacOS=ut()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=function(e){},this._keyboardUpEvent=function(e){},this._keyboardBlurEvent=function(e){},this._pointerMoveEvent=function(e){},this._pointerDownEvent=function(e){},this._pointerUpEvent=function(e){},this._pointerCancelEvent=function(e){},this._pointerWheelEvent=function(e){},this._pointerBlurEvent=function(e){},this._pointerMacOSChromeOutEvent=function(e){},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=ut()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._isUsingChromium=ut()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Chrome"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=function(e){},this._gamepadDisconnectedEvent=function(e){},this._eventPrefix=rr.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=r,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=function(){n._enableEvents()})}return e.prototype.pollInput=function(e,t,i){var r=this._inputs[e][t];if(!r)throw"Unable to find device ".concat(Sr[e]);e>=Sr.DualShock&&e<=Sr.DualSense&&this._updateDevice(e,t,i);var n=r[i];if(void 0===n)throw"Unable to find input ".concat(i," for device ").concat(Sr[e]," in slot ").concat(t);return i===xr.Move&&rr.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),n},e.prototype.isDeviceAvailable=function(e){return void 0!==this._inputs[e]},e.prototype.dispose=function(){this._onDeviceConnected=function(){},this._onDeviceDisconnected=function(){},this._onInputChanged=function(){},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()},e.prototype._enableEvents=function(){var e=null==this?void 0:this._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs)for(var t=0,i=this._inputs;t<i.length;t++){var r=i[t];if(r)for(var n in r){var o=r[+n];if(o)for(var a=0;a<o.length;a++)o[a]=0}}this._elementToAttachTo=e,this._elementToAttachTo.tabIndex=-1!==this._elementToAttachTo.tabIndex?this._elementToAttachTo.tabIndex:this._engine.canvasTabIndex,this._handleKeyActions(),this._handlePointerActions(),this._handleGamepadActions(),this._eventsAttached=!0,this._checkForConnectedDevices()}},e.prototype._disableEvents=function(){this._elementToAttachTo&&(this._elementToAttachTo.removeEventListener("blur",this._keyboardBlurEvent),this._elementToAttachTo.removeEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.removeEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.removeEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.removeEventListener(this._wheelEventName,this._pointerWheelEvent),this._usingMacOS&&this._isUsingChromium&&this._elementToAttachTo.removeEventListener("lostpointercapture",this._pointerMacOSChromeOutEvent),window.removeEventListener("gamepadconnected",this._gamepadConnectedEvent),window.removeEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)),this._pointerInputClearObserver&&this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver),this._eventsAttached=!1},e.prototype._checkForConnectedDevices=function(){if(navigator.getGamepads)for(var e=0,t=navigator.getGamepads();e<t.length;e++){var i=t[e];i&&this._addGamePad(i)}"function"==typeof matchMedia&&matchMedia("(pointer:fine)").matches&&this._addPointerDevice(Sr.Mouse,0,0,0)},e.prototype._addGamePad=function(e){var t=this._getGamepadDeviceType(e.id),i=e.index;this._gamepads=this._gamepads||new Array(e.index+1),this._registerDevice(t,i,e.buttons.length+e.axes.length),this._gamepads[i]=t},e.prototype._addPointerDevice=function(e,t,i,r){this._pointerActive||(this._pointerActive=!0),this._registerDevice(e,t,Jr);var n=this._inputs[e][t];n[0]=i,n[1]=r},e.prototype._registerDevice=function(e,t,i){if(void 0===t)throw"Unable to register device ".concat(Sr[e]," to undefined slot.");if(this._inputs[e]||(this._inputs[e]={}),!this._inputs[e][t]){var r=new Array(i);r.fill(0),this._inputs[e][t]=r,this._onDeviceConnected(e,t)}},e.prototype._unregisterDevice=function(e,t){this._inputs[e][t]&&(delete this._inputs[e][t],this._onDeviceDisconnected(e,t))},e.prototype._handleKeyActions=function(){var e=this;this._keyboardDownEvent=function(t){e._keyboardActive||(e._keyboardActive=!0,e._registerDevice(Sr.Keyboard,0,255));var i=e._inputs[Sr.Keyboard][0];if(i){i[t.keyCode]=1;var r=t;r.inputIndex=t.keyCode,e._usingMacOS&&t.metaKey&&"Meta"!==t.key&&(e._metaKeys.includes(t.keyCode)||e._metaKeys.push(t.keyCode)),e._onInputChanged(Sr.Keyboard,0,r)}},this._keyboardUpEvent=function(t){e._keyboardActive||(e._keyboardActive=!0,e._registerDevice(Sr.Keyboard,0,255));var i=e._inputs[Sr.Keyboard][0];if(i){i[t.keyCode]=0;var r=t;if(r.inputIndex=t.keyCode,e._usingMacOS&&"Meta"===t.key&&e._metaKeys.length>0){for(var n=0,o=e._metaKeys;n<o.length;n++){var a=o[n],s=qr.CreateDeviceEvent(Sr.Keyboard,0,a,0,e,e._elementToAttachTo);i[a]=0,e._onInputChanged(Sr.Keyboard,0,s)}e._metaKeys.splice(0,e._metaKeys.length)}e._onInputChanged(Sr.Keyboard,0,r)}},this._keyboardBlurEvent=function(){if(e._keyboardActive){for(var t=e._inputs[Sr.Keyboard][0],i=0;i<t.length;i++)if(0!==t[i]){t[i]=0;var r=qr.CreateDeviceEvent(Sr.Keyboard,0,i,0,e,e._elementToAttachTo);e._onInputChanged(Sr.Keyboard,0,r)}e._usingMacOS&&e._metaKeys.splice(0,e._metaKeys.length)}},this._elementToAttachTo.addEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.addEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.addEventListener("blur",this._keyboardBlurEvent)},e.prototype._handlePointerActions=function(){var e=this;this._maxTouchPoints=ut()&&navigator.maxTouchPoints||2,this._activeTouchIds||(this._activeTouchIds=new Array(this._maxTouchPoints));for(var t=0;t<this._maxTouchPoints;t++)this._activeTouchIds[t]=-1;this._pointerMoveEvent=function(t){var i=e._getPointerType(t),r=i===Sr.Mouse?0:e._activeTouchIds.indexOf(t.pointerId);if(i===Sr.Touch&&-1===r){var n=e._activeTouchIds.indexOf(-1);if(!(n>=0))return void rr.Warn("Max number of touches exceeded. Ignoring touches in excess of ".concat(e._maxTouchPoints));r=n,e._activeTouchIds[n]=t.pointerId,e._onDeviceConnected(i,r)}e._inputs[i]||(e._inputs[i]={}),e._inputs[i][r]||e._addPointerDevice(i,r,t.clientX,t.clientY);var o=e._inputs[i][r];if(o){var a=t;a.inputIndex=xr.Move,o[xr.Horizontal]=t.clientX,o[xr.Vertical]=t.clientY,i===Sr.Touch&&0===o[xr.LeftClick]&&(o[xr.LeftClick]=1),void 0===t.pointerId&&(t.pointerId=e._mouseId),e._onInputChanged(i,r,a),e._usingSafari||-1===t.button||(a.inputIndex=t.button+2,o[t.button+2]=o[t.button+2]?0:1,e._onInputChanged(i,r,a))}},this._pointerDownEvent=function(t){var i=e._getPointerType(t),r=i===Sr.Mouse?0:t.pointerId;if(i===Sr.Touch){var n=e._activeTouchIds.indexOf(-1);if(!(n>=0))return void rr.Warn("Max number of touches exceeded. Ignoring touches in excess of ".concat(e._maxTouchPoints));r=n,e._activeTouchIds[n]=t.pointerId}e._inputs[i]||(e._inputs[i]={}),e._inputs[i][r]?i===Sr.Touch&&e._onDeviceConnected(i,r):e._addPointerDevice(i,r,t.clientX,t.clientY);var o=e._inputs[i][r];if(o){var a=o[xr.Horizontal],s=o[xr.Vertical];if(i===Sr.Mouse){if(void 0===t.pointerId&&(t.pointerId=e._mouseId),!document.pointerLockElement)try{e._elementToAttachTo.setPointerCapture(e._mouseId)}catch(e){}}else if(t.pointerId&&!document.pointerLockElement)try{e._elementToAttachTo.setPointerCapture(t.pointerId)}catch(e){}o[xr.Horizontal]=t.clientX,o[xr.Vertical]=t.clientY,o[t.button+2]=1;var l=t;l.inputIndex=t.button+2,e._onInputChanged(i,r,l),a===t.clientX&&s===t.clientY||(l.inputIndex=xr.Move,e._onInputChanged(i,r,l))}},this._pointerUpEvent=function(t){var i,r,n,o,a,s=e._getPointerType(t),l=s===Sr.Mouse?0:e._activeTouchIds.indexOf(t.pointerId);if(s===Sr.Touch){if(-1===l)return;e._activeTouchIds[l]=-1}var c=null===(i=e._inputs[s])||void 0===i?void 0:i[l];if(c&&0!==c[t.button+2]){var u=c[xr.Horizontal],h=c[xr.Vertical];c[xr.Horizontal]=t.clientX,c[xr.Vertical]=t.clientY,c[t.button+2]=0;var d=t;void 0===t.pointerId&&(t.pointerId=e._mouseId),u===t.clientX&&h===t.clientY||(d.inputIndex=xr.Move,e._onInputChanged(s,l,d)),d.inputIndex=t.button+2,s===Sr.Mouse&&e._mouseId>=0&&(null===(n=(r=e._elementToAttachTo).hasPointerCapture)||void 0===n?void 0:n.call(r,e._mouseId))?e._elementToAttachTo.releasePointerCapture(e._mouseId):t.pointerId&&(null===(a=(o=e._elementToAttachTo).hasPointerCapture)||void 0===a?void 0:a.call(o,t.pointerId))&&e._elementToAttachTo.releasePointerCapture(t.pointerId),e._onInputChanged(s,l,d),s===Sr.Touch&&e._onDeviceDisconnected(s,l)}},this._pointerCancelEvent=function(t){var i,r,n,o;if("mouse"===t.pointerType){var a=e._inputs[Sr.Mouse][0];e._mouseId>=0&&(null===(r=(i=e._elementToAttachTo).hasPointerCapture)||void 0===r?void 0:r.call(i,e._mouseId))&&e._elementToAttachTo.releasePointerCapture(e._mouseId);for(var s=xr.LeftClick;s<=xr.BrowserForward;s++)if(1===a[s]){a[s]=0;var l=qr.CreateDeviceEvent(Sr.Mouse,0,s,0,e,e._elementToAttachTo);e._onInputChanged(Sr.Mouse,0,l)}}else{var c=e._activeTouchIds.indexOf(t.pointerId);if(-1===c)return;(null===(o=(n=e._elementToAttachTo).hasPointerCapture)||void 0===o?void 0:o.call(n,t.pointerId))&&e._elementToAttachTo.releasePointerCapture(t.pointerId),e._inputs[Sr.Touch][c][xr.LeftClick]=0,l=qr.CreateDeviceEvent(Sr.Touch,c,xr.LeftClick,0,e,e._elementToAttachTo,t.pointerId),e._onInputChanged(Sr.Touch,c,l),e._activeTouchIds[c]=-1,e._onDeviceDisconnected(Sr.Touch,c)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";var i=!1,r=function(){};try{var n=Object.defineProperty({},"passive",{get:function(){i=!0}});this._elementToAttachTo.addEventListener("test",r,n),this._elementToAttachTo.removeEventListener("test",r,n)}catch(e){}this._pointerBlurEvent=function(){var t,i,r,n,o;if(e.isDeviceAvailable(Sr.Mouse)){var a=e._inputs[Sr.Mouse][0];e._mouseId>=0&&(null===(i=(t=e._elementToAttachTo).hasPointerCapture)||void 0===i?void 0:i.call(t,e._mouseId))&&e._elementToAttachTo.releasePointerCapture(e._mouseId);for(var s=xr.LeftClick;s<=xr.BrowserForward;s++)if(1===a[s]){a[s]=0;var l=qr.CreateDeviceEvent(Sr.Mouse,0,s,0,e,e._elementToAttachTo);e._onInputChanged(Sr.Mouse,0,l)}}if(e.isDeviceAvailable(Sr.Touch)){a=e._inputs[Sr.Touch];for(var c=0;c<e._activeTouchIds.length;c++){var u=e._activeTouchIds[c];(null===(n=(r=e._elementToAttachTo).hasPointerCapture)||void 0===n?void 0:n.call(r,u))&&e._elementToAttachTo.releasePointerCapture(u),-1!==u&&1===(null===(o=a[c])||void 0===o?void 0:o[xr.LeftClick])&&(a[c][xr.LeftClick]=0,l=qr.CreateDeviceEvent(Sr.Touch,c,xr.LeftClick,0,e,e._elementToAttachTo,u),e._onInputChanged(Sr.Touch,c,l),e._activeTouchIds[c]=-1,e._onDeviceDisconnected(Sr.Touch,c))}}},this._pointerWheelEvent=function(t){var i=Sr.Mouse;e._inputs[i]||(e._inputs[i]=[]),e._inputs[i][0]||(e._pointerActive=!0,e._registerDevice(i,0,Jr));var r=e._inputs[i][0];if(r){r[xr.MouseWheelX]=t.deltaX||0,r[xr.MouseWheelY]=t.deltaY||t.wheelDelta||0,r[xr.MouseWheelZ]=t.deltaZ||0;var n=t;void 0===t.pointerId&&(t.pointerId=e._mouseId),0!==r[xr.MouseWheelX]&&(n.inputIndex=xr.MouseWheelX,e._onInputChanged(i,0,n)),0!==r[xr.MouseWheelY]&&(n.inputIndex=xr.MouseWheelY,e._onInputChanged(i,0,n)),0!==r[xr.MouseWheelZ]&&(n.inputIndex=xr.MouseWheelZ,e._onInputChanged(i,0,n))}},this._usingMacOS&&this._isUsingChromium&&(this._pointerMacOSChromeOutEvent=function(t){t.buttons>1&&e._pointerCancelEvent(t)},this._elementToAttachTo.addEventListener("lostpointercapture",this._pointerMacOSChromeOutEvent)),this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,!!i&&{passive:!1}),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add((function(){if(e.isDeviceAvailable(Sr.Mouse)){var t=e._inputs[Sr.Mouse][0];t[xr.MouseWheelX]=0,t[xr.MouseWheelY]=0,t[xr.MouseWheelZ]=0}}))},e.prototype._handleGamepadActions=function(){var e=this;this._gamepadConnectedEvent=function(t){e._addGamePad(t.gamepad)},this._gamepadDisconnectedEvent=function(t){if(e._gamepads){var i=e._getGamepadDeviceType(t.gamepad.id),r=t.gamepad.index;e._unregisterDevice(i,r),delete e._gamepads[r]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)},e.prototype._updateDevice=function(e,t,i){var r=navigator.getGamepads()[t];if(r&&e===this._gamepads[t]){var n=this._inputs[e][t];i>=r.buttons.length?n[i]=r.axes[i-r.buttons.length].valueOf():n[i]=r.buttons[i].value}},e.prototype._getGamepadDeviceType=function(e){return-1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?Sr.DualSense:Sr.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?Sr.Xbox:-1!==e.indexOf("057e")?Sr.Switch:Sr.Generic},e.prototype._getPointerType=function(e){var t=Sr.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=Sr.Touch),t},e}(),en=function(){function e(e,t,i){void 0===i&&(i=0),this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new f,this._deviceInputSystem=e}return e.prototype.getInput=function(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)},e}(),tn=function(){function e(e){var t=this;this._registeredManagers=new Array,this._refCount=0,this.registerManager=function(e){for(var i=0;i<t._devices.length;i++){var r=t._devices[i];for(var n in r){var o=+n;e._addDevice(new en(t._deviceInputSystem,i,o))}}t._registeredManagers.push(e)},this.unregisterManager=function(e){var i=t._registeredManagers.indexOf(e);i>-1&&t._registeredManagers.splice(i,1)};var i=Object.keys(Sr).length/2;this._devices=new Array(i);var r=function(e,i){t._devices[e]||(t._devices[e]=new Array),t._devices[e][i]||(t._devices[e][i]=i);for(var r=0,n=t._registeredManagers;r<n.length;r++){var o=n[r],a=new en(t._deviceInputSystem,e,i);o._addDevice(a)}},n=function(e,i){var r;(null===(r=t._devices[e])||void 0===r?void 0:r[i])&&delete t._devices[e][i];for(var n=0,o=t._registeredManagers;n<o.length;n++)o[n]._removeDevice(e,i)},o=function(e,i,r){if(r)for(var n=0,o=t._registeredManagers;n<o.length;n++)o[n]._onInputChanged(e,i,r)};"undefined"!=typeof _native?this._deviceInputSystem=new Zr(r,n,o):this._deviceInputSystem=new $r(e,r,n,o)}return e.prototype.dispose=function(){this._deviceInputSystem.dispose()},e}(),rn=function(){function e(e){var t=this,i=Object.keys(Sr).length/2;this._devices=new Array(i),this._firstDevice=new Array(i),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new tn(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new f((function(e){for(var i=0,r=t._devices;i<r.length;i++){var n=r[i];if(n)for(var o=0,a=n;o<a.length;o++){var s=a[o];s&&t.onDeviceConnectedObservable.notifyObserver(e,s)}}})),this.onDeviceDisconnectedObservable=new f,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add((function(){t.dispose()}))}return e.prototype.getDeviceSource=function(e,t){if(void 0===t){if(void 0===this._firstDevice[e])return null;t=this._firstDevice[e]}return this._devices[e]&&void 0!==this._devices[e][t]?this._devices[e][t]:null},e.prototype.getDeviceSources=function(e){return this._devices[e]?this._devices[e].filter((function(e){return!!e})):[]},e.prototype.dispose=function(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)},e.prototype._addDevice=function(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=new Array),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)},e.prototype._removeDevice=function(e,t){var i,r,n=null===(i=this._devices[e])||void 0===i?void 0:i[t];this.onDeviceDisconnectedObservable.notifyObservers(n),(null===(r=this._devices[e])||void 0===r?void 0:r[t])&&delete this._devices[e][t],this._updateFirstDevices(e)},e.prototype._onInputChanged=function(e,t,i){var r,n;null===(n=null===(r=this._devices[e])||void 0===r?void 0:r[t])||void 0===n||n.onInputChangedObservable.notifyObservers(i)},e.prototype._updateFirstDevices=function(e){switch(e){case Sr.Keyboard:case Sr.Mouse:this._firstDevice[e]=0;break;case Sr.Touch:case Sr.DualSense:case Sr.DualShock:case Sr.Xbox:case Sr.Switch:case Sr.Generic:delete this._firstDevice[e];var t=this._devices[e];if(t)for(var i=0;i<t.length;i++)if(t[i]){this._firstDevice[e]=i;break}}},e}(),nn=function(){function e(){this._singleClick=!1,this._doubleClick=!1,this._hasSwiped=!1,this._ignore=!1}return Object.defineProperty(e.prototype,"singleClick",{get:function(){return this._singleClick},set:function(e){this._singleClick=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"doubleClick",{get:function(){return this._doubleClick},set:function(e){this._doubleClick=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hasSwiped",{get:function(){return this._hasSwiped},set:function(e){this._hasSwiped=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"ignore",{get:function(){return this._ignore},set:function(e){this._ignore=e},enumerable:!1,configurable:!0}),e}(),on=function(){function e(e){this._alreadyAttached=!1,this._meshPickProceed=!1,this._currentPickResult=null,this._previousPickResult=null,this._totalPointersPressed=0,this._doubleClickOccured=!1,this._isSwiping=!1,this._swipeButtonPressed=-1,this._skipPointerTap=!1,this._isMultiTouchGesture=!1,this._pointerX=0,this._pointerY=0,this._startingPointerPosition=new U(0,0),this._previousStartingPointerPosition=new U(0,0),this._startingPointerTime=0,this._previousStartingPointerTime=0,this._pointerCaptures={},this._meshUnderPointerId={},this._movePointerInfo=null,this._cameraObserverCount=0,this._delayedClicks=[null,null,null,null,null],this._deviceSourceManager=null,this._scene=e||M.LastCreatedScene,this._scene}return Object.defineProperty(e.prototype,"meshUnderPointer",{get:function(){return this._movePointerInfo&&(this._movePointerInfo._generatePickInfo(),this._movePointerInfo=null),this._pointerOverMesh},enumerable:!1,configurable:!0}),e.prototype.getMeshUnderPointerByPointerId=function(e){return this._meshUnderPointerId[e]||null},Object.defineProperty(e.prototype,"unTranslatedPointer",{get:function(){return new U(this._unTranslatedPointerX,this._unTranslatedPointerY)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"pointerX",{get:function(){return this._pointerX},set:function(e){this._pointerX=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"pointerY",{get:function(){return this._pointerY},set:function(e){this._pointerY=e},enumerable:!1,configurable:!0}),e.prototype._updatePointerPosition=function(e){var t=this._scene.getEngine().getInputElementClientRect();t&&(this._pointerX=e.clientX-t.left,this._pointerY=e.clientY-t.top,this._unTranslatedPointerX=this._pointerX,this._unTranslatedPointerY=this._pointerY)},e.prototype._processPointerMove=function(e,t){var i=this._scene,r=i.getEngine(),n=r.getInputElement();n&&(n.tabIndex=r.canvasTabIndex,i.doNotHandleCursors||(n.style.cursor=i.defaultCursor)),this._setCursorAndPointerOverMesh(e,t,i);for(var o=0,a=i._pointerMoveStage;o<a.length;o++){var s=a[o],l=!!(null==(e=e||this._pickMove(t))?void 0:e.pickedMesh);e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,l,n)}var c,u=t.inputIndex>=xr.MouseWheelX&&t.inputIndex<=xr.MouseWheelZ?Gr.POINTERWHEEL:Gr.POINTERMOVE;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,u)),e?(c=new Hr(u,t,e),this._setRayOnPointerInfo(e,t)):(c=new Hr(u,t,null,this),this._movePointerInfo=c),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(c,u)},e.prototype._setRayOnPointerInfo=function(e,t){var i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,z.Identity(),i.activeCamera)))},e.prototype._addCameraPointerObserver=function(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)},e.prototype._removeCameraPointerObserver=function(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)},e.prototype._checkForPicking=function(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)},e.prototype._checkPrePointerObservable=function(e,t,i){var r=this._scene,n=new Wr(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(n.originalPickingInfo=e,n.ray=e.ray,"xr-near"===t.pointerType&&e.originMesh&&(n.nearInteractionPickingInfo=e)),r.onPrePointerObservable.notifyObservers(n,i),!!n.skipOnPointerObservable},e.prototype._pickMove=function(e){var t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i},e.prototype._setCursorAndPointerOverMesh=function(e,t,i){var r=i.getEngine().getInputElement();if(null==e?void 0:e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&r&&this._pointerOverMesh){var n=this._pointerOverMesh._getActionManagerForTrigger();n&&n.hasPointerTriggers&&(r.style.cursor=n.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)},e.prototype.simulatePointerMove=function(e,t){var i=new PointerEvent("pointermove",t);i.inputIndex=xr.Move,this._checkPrePointerObservable(e,i,Gr.POINTERMOVE)||this._processPointerMove(e,i)},e.prototype.simulatePointerDown=function(e,t){var i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,Gr.POINTERDOWN)||this._processPointerDown(e,i)},e.prototype._processPointerDown=function(t,i){var r,n=this,o=this._scene;if(null==t?void 0:t.pickedMesh){this._pickedDownMesh=t.pickedMesh;var a=t.pickedMesh._getActionManagerForTrigger();if(a){if(a.hasPickTriggers)switch(a.processTrigger(u.ACTION_OnPickDownTrigger,te.CreateNew(t.pickedMesh,i,t)),i.button){case 0:a.processTrigger(u.ACTION_OnLeftPickTrigger,te.CreateNew(t.pickedMesh,i,t));break;case 1:a.processTrigger(u.ACTION_OnCenterPickTrigger,te.CreateNew(t.pickedMesh,i,t));break;case 2:a.processTrigger(u.ACTION_OnRightPickTrigger,te.CreateNew(t.pickedMesh,i,t))}a.hasSpecificTrigger(u.ACTION_OnLongPressTrigger)&&window.setTimeout((function(){var t=o.pick(n._unTranslatedPointerX,n._unTranslatedPointerY,(function(e){return e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(u.ACTION_OnLongPressTrigger)&&e===n._pickedDownMesh}),!1,o.cameraToUseForPointers);(null==t?void 0:t.pickedMesh)&&a&&0!==n._totalPointersPressed&&Date.now()-n._startingPointerTime>e.LongPressDelay&&!n._isPointerSwiping()&&(n._startingPointerTime=0,a.processTrigger(u.ACTION_OnLongPressTrigger,te.CreateNew(t.pickedMesh,i)))}),e.LongPressDelay)}}else for(var s=0,l=o._pointerDownStage;s<l.length;s++)t=l[s].action(this._unTranslatedPointerX,this._unTranslatedPointerY,t,i,!1);var c=Gr.POINTERDOWN;t?(o.onPointerDown&&o.onPointerDown(i,t,c),r=new Hr(c,i,t),this._setRayOnPointerInfo(t,i)):r=new Hr(c,i,null,this),o.onPointerObservable.hasObservers()&&o.onPointerObservable.notifyObservers(r,c)},e.prototype._isPointerSwiping=function(){return this._isSwiping},e.prototype.simulatePointerUp=function(e,t,i){var r=new PointerEvent("pointerup",t);r.inputIndex=xr.Move;var n=new nn;i?n.doubleClick=!0:n.singleClick=!0,this._checkPrePointerObservable(e,r,Gr.POINTERUP)||this._processPointerUp(e,r,n)},e.prototype._processPointerUp=function(e,t,i){var r=this._scene;if(null==e?void 0:e.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(r.onPointerPick&&r.onPointerPick(t,e),i.singleClick&&!i.ignore&&r.onPointerObservable.observers.length>this._cameraObserverCount)){var n=Gr.POINTERPICK,o=new Hr(n,t,e);this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(o,n)}var a=e.pickedMesh._getActionManagerForTrigger();if(a&&!i.ignore){a.processTrigger(u.ACTION_OnPickUpTrigger,te.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&a.processTrigger(u.ACTION_OnPickTrigger,te.CreateNew(e.pickedMesh,t,e));var s=e.pickedMesh._getActionManagerForTrigger(u.ACTION_OnDoublePickTrigger);i.doubleClick&&s&&s.processTrigger(u.ACTION_OnDoublePickTrigger,te.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(var l=0,c=r._pointerUpStage;l<c.length;l++)e=c[l].action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){var h=this._pickedDownMesh._getActionManagerForTrigger(u.ACTION_OnPickOutTrigger);h&&h.processTrigger(u.ACTION_OnPickOutTrigger,te.CreateNew(this._pickedDownMesh,t))}if(!i.ignore&&(o=new Hr(Gr.POINTERUP,t,e),this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(o,Gr.POINTERUP),r.onPointerUp&&r.onPointerUp(t,e,Gr.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture&&(n=0,i.singleClick?n=Gr.POINTERTAP:i.doubleClick&&(n=Gr.POINTERDOUBLETAP),n))){var d=new Hr(n,t,e);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(n)&&r.onPointerObservable.notifyObservers(d,n)}},e.prototype.isPointerCaptured=function(e){return void 0===e&&(e=0),this._pointerCaptures[e]},e.prototype.attachControl=function(t,i,r,n){var o=this;void 0===t&&(t=!0),void 0===i&&(i=!0),void 0===r&&(r=!0),void 0===n&&(n=null);var a=this._scene,s=a.getEngine();n||(n=s.getInputElement()),this._alreadyAttached&&this.detachControl(),n&&(this._alreadyAttachedTo=n),this._deviceSourceManager=new rn(s),this._initActionManager=function(e){if(!o._meshPickProceed){var t=a.skipPointerUpPicking||0===a._registeredActions&&!o._checkForPicking()&&!a.onPointerUp?null:a.pick(o._unTranslatedPointerX,o._unTranslatedPointerY,a.pointerUpPredicate,a.pointerUpFastCheck,a.cameraToUseForPointers,a.pointerUpTrianglePredicate);o._currentPickResult=t,t&&(e=t.hit&&t.pickedMesh?t.pickedMesh._getActionManagerForTrigger():null),o._meshPickProceed=!0}return e},this._delayedSimpleClick=function(t,i,r){if((Date.now()-o._previousStartingPointerTime>e.DoubleClickDelay&&!o._doubleClickOccured||t!==o._previousButtonPressed)&&(o._doubleClickOccured=!1,i.singleClick=!0,i.ignore=!1,o._delayedClicks[t])){var n=o._delayedClicks[t].evt,s=Gr.POINTERTAP,l=new Hr(s,n,o._currentPickResult);a.onPointerObservable.hasObservers()&&a.onPointerObservable.hasSpecificMask(s)&&a.onPointerObservable.notifyObservers(l,s),o._delayedClicks[t]=null}},this._initClickEvent=function(t,i,r,n){var a,s,l=new nn;o._currentPickResult=null;var c=null,d=t.hasSpecificMask(Gr.POINTERPICK)||i.hasSpecificMask(Gr.POINTERPICK)||t.hasSpecificMask(Gr.POINTERTAP)||i.hasSpecificMask(Gr.POINTERTAP)||t.hasSpecificMask(Gr.POINTERDOUBLETAP)||i.hasSpecificMask(Gr.POINTERDOUBLETAP);!d&&h&&(c=o._initActionManager(c,l))&&(d=c.hasPickTriggers);var p=!1;if(d){var f=r.button;if(l.hasSwiped=o._isPointerSwiping(),!l.hasSwiped){var _=!e.ExclusiveDoubleClickMode;if(_||(_=!t.hasSpecificMask(Gr.POINTERDOUBLETAP)&&!i.hasSpecificMask(Gr.POINTERDOUBLETAP))&&!h.HasSpecificTrigger(u.ACTION_OnDoublePickTrigger)&&(c=o._initActionManager(c,l))&&(_=!c.hasSpecificTrigger(u.ACTION_OnDoublePickTrigger)),_)(Date.now()-o._previousStartingPointerTime>e.DoubleClickDelay||f!==o._previousButtonPressed)&&(l.singleClick=!0,n(l,o._currentPickResult),p=!0);else{var m={evt:r,clickInfo:l,timeoutId:window.setTimeout(o._delayedSimpleClick.bind(o,f,l,n),e.DoubleClickDelay)};o._delayedClicks[f]=m}var g=t.hasSpecificMask(Gr.POINTERDOUBLETAP)||i.hasSpecificMask(Gr.POINTERDOUBLETAP);!g&&h.HasSpecificTrigger(u.ACTION_OnDoublePickTrigger)&&(c=o._initActionManager(c,l))&&(g=c.hasSpecificTrigger(u.ACTION_OnDoublePickTrigger)),g&&(f===o._previousButtonPressed&&Date.now()-o._previousStartingPointerTime<e.DoubleClickDelay&&!o._doubleClickOccured?(l.hasSwiped||o._isPointerSwiping()?(o._doubleClickOccured=!1,o._previousStartingPointerTime=o._startingPointerTime,o._previousStartingPointerPosition.x=o._startingPointerPosition.x,o._previousStartingPointerPosition.y=o._startingPointerPosition.y,o._previousButtonPressed=f,e.ExclusiveDoubleClickMode?(o._delayedClicks[f]&&(clearTimeout(null===(s=o._delayedClicks[f])||void 0===s?void 0:s.timeoutId),o._delayedClicks[f]=null),n(l,o._previousPickResult)):n(l,o._currentPickResult)):(o._previousStartingPointerTime=0,o._doubleClickOccured=!0,l.doubleClick=!0,l.ignore=!1,e.ExclusiveDoubleClickMode&&o._delayedClicks[f]&&(clearTimeout(null===(a=o._delayedClicks[f])||void 0===a?void 0:a.timeoutId),o._delayedClicks[f]=null),n(l,o._currentPickResult)),p=!0):(o._doubleClickOccured=!1,o._previousStartingPointerTime=o._startingPointerTime,o._previousStartingPointerPosition.x=o._startingPointerPosition.x,o._previousStartingPointerPosition.y=o._startingPointerPosition.y,o._previousButtonPressed=f))}}p||n(l,o._currentPickResult)},this._onPointerMove=function(t){if(o._updatePointerPosition(t),o._isSwiping||-1===o._swipeButtonPressed||(o._isSwiping=Math.abs(o._startingPointerPosition.x-o._pointerX)>e.DragMovementThreshold||Math.abs(o._startingPointerPosition.y-o._pointerY)>e.DragMovementThreshold),s.isPointerLock&&s._verifyPointerLock(),!o._checkPrePointerObservable(null,t,t.inputIndex>=xr.MouseWheelX&&t.inputIndex<=xr.MouseWheelZ?Gr.POINTERWHEEL:Gr.POINTERMOVE)&&(a.cameraToUseForPointers||a.activeCamera))if(a.skipPointerMovePicking)o._processPointerMove(new Fr,t);else{a.pointerMovePredicate||(a.pointerMovePredicate=function(e){return e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||a.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!a.cameraToUseForPointers||!!(a.cameraToUseForPointers.layerMask&e.layerMask))});var i=a._registeredActions>0||a.constantlyUpdateMeshUnderPointer?o._pickMove(t):null;o._processPointerMove(i,t)}},this._onPointerDown=function(t){var i,r;if(o._totalPointersPressed++,o._pickedDownMesh=null,o._meshPickProceed=!1,e.ExclusiveDoubleClickMode)for(var s=0;s<o._delayedClicks.length;s++)if(o._delayedClicks[s])if(t.button===s)clearTimeout(null===(i=o._delayedClicks[s])||void 0===i?void 0:i.timeoutId);else{var l=o._delayedClicks[s].clickInfo;o._doubleClickOccured=!1,l.singleClick=!0,l.ignore=!1;var c=o._delayedClicks[s].evt,u=Gr.POINTERTAP,h=new Hr(u,c,o._currentPickResult);a.onPointerObservable.hasObservers()&&a.onPointerObservable.hasSpecificMask(u)&&a.onPointerObservable.notifyObservers(h,u),o._delayedClicks[s]=null}o._updatePointerPosition(t),-1===o._swipeButtonPressed&&(o._swipeButtonPressed=t.button),a.preventDefaultOnPointerDown&&n&&(t.preventDefault(),n.focus()),o._startingPointerPosition.x=o._pointerX,o._startingPointerPosition.y=o._pointerY,o._startingPointerTime=Date.now(),o._checkPrePointerObservable(null,t,Gr.POINTERDOWN)||(a.cameraToUseForPointers||a.activeCamera)&&(o._pointerCaptures[t.pointerId]=!0,a.pointerDownPredicate||(a.pointerDownPredicate=function(e){return e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!a.cameraToUseForPointers||!!(a.cameraToUseForPointers.layerMask&e.layerMask))}),o._pickedDownMesh=null,r=a.skipPointerDownPicking||0===a._registeredActions&&!o._checkForPicking()&&!a.onPointerDown?new Fr:a.pick(o._unTranslatedPointerX,o._unTranslatedPointerY,a.pointerDownPredicate,a.pointerDownFastCheck,a.cameraToUseForPointers,a.pointerDownTrianglePredicate),o._processPointerDown(r,t))},this._onPointerUp=function(e){0!==o._totalPointersPressed&&(o._totalPointersPressed--,o._pickedUpMesh=null,o._meshPickProceed=!1,o._updatePointerPosition(e),a.preventDefaultOnPointerUp&&n&&(e.preventDefault(),n.focus()),o._initClickEvent(a.onPrePointerObservable,a.onPointerObservable,e,(function(t,i){if(a.onPrePointerObservable.hasObservers()&&(o._skipPointerTap=!1,!t.ignore)){if(o._checkPrePointerObservable(null,e,Gr.POINTERUP))return o._swipeButtonPressed===e.button&&(o._isSwiping=!1,o._swipeButtonPressed=-1),void(0===e.buttons&&(o._pointerCaptures[e.pointerId]=!1));t.hasSwiped||(t.singleClick&&a.onPrePointerObservable.hasSpecificMask(Gr.POINTERTAP)&&o._checkPrePointerObservable(null,e,Gr.POINTERTAP)&&(o._skipPointerTap=!0),t.doubleClick&&a.onPrePointerObservable.hasSpecificMask(Gr.POINTERDOUBLETAP)&&o._checkPrePointerObservable(null,e,Gr.POINTERDOUBLETAP)&&(o._skipPointerTap=!0))}o._pointerCaptures[e.pointerId]?(0===e.buttons&&(o._pointerCaptures[e.pointerId]=!1),(a.cameraToUseForPointers||a.activeCamera)&&(a.pointerUpPredicate||(a.pointerUpPredicate=function(e){return e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!a.cameraToUseForPointers||!!(a.cameraToUseForPointers.layerMask&e.layerMask))}),!o._meshPickProceed&&(h&&h.HasTriggers||o._checkForPicking()||a.onPointerUp)&&o._initActionManager(null,t),i||(i=o._currentPickResult),o._processPointerUp(i,e,t),o._previousPickResult=o._currentPickResult,o._swipeButtonPressed===e.button&&(o._isSwiping=!1,o._swipeButtonPressed=-1))):o._swipeButtonPressed===e.button&&(o._isSwiping=!1,o._swipeButtonPressed=-1)})))},this._onKeyDown=function(e){var t=Xr.KEYDOWN;if(a.onPreKeyboardObservable.hasObservers()){var i=new Yr(t,e);if(a.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}a.onKeyboardObservable.hasObservers()&&(i=new jr(t,e),a.onKeyboardObservable.notifyObservers(i,t)),a.actionManager&&a.actionManager.processTrigger(u.ACTION_OnKeyDownTrigger,te.CreateNewFromScene(a,e))},this._onKeyUp=function(e){var t=Xr.KEYUP;if(a.onPreKeyboardObservable.hasObservers()){var i=new Yr(t,e);if(a.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}a.onKeyboardObservable.hasObservers()&&(i=new jr(t,e),a.onKeyboardObservable.notifyObservers(i,t)),a.actionManager&&a.actionManager.processTrigger(u.ACTION_OnKeyUpTrigger,te.CreateNewFromScene(a,e))},this._deviceSourceManager.onDeviceConnectedObservable.add((function(e){e.deviceType===Sr.Mouse?e.onInputChangedObservable.add((function(n){o._originMouseEvent=n,n.inputIndex===xr.LeftClick||n.inputIndex===xr.MiddleClick||n.inputIndex===xr.RightClick||n.inputIndex===xr.BrowserBack||n.inputIndex===xr.BrowserForward?i&&1===e.getInput(n.inputIndex)?o._onPointerDown(n):t&&0===e.getInput(n.inputIndex)&&o._onPointerUp(n):r&&(n.inputIndex===xr.Move?o._onPointerMove(n):n.inputIndex!==xr.MouseWheelX&&n.inputIndex!==xr.MouseWheelY&&n.inputIndex!==xr.MouseWheelZ||o._onPointerMove(n))})):e.deviceType===Sr.Touch?e.onInputChangedObservable.add((function(n){n.inputIndex===xr.LeftClick&&(i&&1===e.getInput(n.inputIndex)?(o._onPointerDown(n),o._totalPointersPressed>1&&(o._isMultiTouchGesture=!0)):t&&0===e.getInput(n.inputIndex)&&(o._onPointerUp(n),0===o._totalPointersPressed&&(o._isMultiTouchGesture=!1))),r&&n.inputIndex===xr.Move&&o._onPointerMove(n)})):e.deviceType===Sr.Keyboard&&e.onInputChangedObservable.add((function(e){"keydown"===e.type?o._onKeyDown(e):"keyup"===e.type&&o._onKeyUp(e)}))})),this._alreadyAttached=!0},e.prototype.detachControl=function(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)},e.prototype.setPointerOverMesh=function(e,t,i,r){if(void 0===t&&(t=0),this._meshUnderPointerId[t]!==e||e&&e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting){var n,o=this._meshUnderPointerId[t];o&&(n=o._getActionManagerForTrigger(u.ACTION_OnPointerOutTrigger))&&n.processTrigger(u.ACTION_OnPointerOutTrigger,te.CreateNew(o,r,{pointerId:t})),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,(n=e._getActionManagerForTrigger(u.ACTION_OnPointerOverTrigger))&&n.processTrigger(u.ACTION_OnPointerOverTrigger,te.CreateNew(e,r,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}},e.prototype.getPointerOverMesh=function(){return this.meshUnderPointer},e.prototype._invalidateMesh=function(e){for(var t in this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null),this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]},e.DragMovementThreshold=10,e.LongPressDelay=500,e.DoubleClickDelay=300,e.ExclusiveDoubleClickMode=!1,e}(),an=function(){function e(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}return Object.defineProperty(e.prototype,"min",{get:function(){return this._min},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"max",{get:function(){return this._max},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"average",{get:function(){return this._average},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"lastSecAverage",{get:function(){return this._lastSecAverage},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"current",{get:function(){return this._current},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"total",{get:function(){return this._totalAccumulated},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"count",{get:function(){return this._totalValueCount},enumerable:!1,configurable:!0}),e.prototype.fetchNewFrame=function(){this._totalValueCount++,this._current=0,this._lastSecValueCount++},e.prototype.addCount=function(t,i){e.Enabled&&(this._current+=t,i&&this._fetchResult())},e.prototype.beginMonitoring=function(){e.Enabled&&(this._startMonitoringTime=_t.Now)},e.prototype.endMonitoring=function(t){if(void 0===t&&(t=!0),e.Enabled){t&&this.fetchNewFrame();var i=_t.Now;this._current=i-this._startMonitoringTime,t&&this._fetchResult()}},e.prototype.endFrame=function(){this._fetchResult()},e.prototype._fetchResult=function(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;var e=_t.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)},e.Enabled=!0,e}(),sn=function(){function e(e,t,i,r){this.normal=new V(e,t,i),this.d=r}return e.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},e.prototype.clone=function(){return new e(this.normal.x,this.normal.y,this.normal.z,this.d)},e.prototype.getClassName=function(){return"Plane"},e.prototype.getHashCode=function(){var e=this.normal.getHashCode();return 397*e^this.d},e.prototype.normalize=function(){var e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),t=0;return 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this},e.prototype.transform=function(t){var i=e._TmpMatrix;t.invertToRef(i);var r=i.m,n=this.normal.x,o=this.normal.y,a=this.normal.z,s=this.d;return new e(n*r[0]+o*r[1]+a*r[2]+s*r[3],n*r[4]+o*r[5]+a*r[6]+s*r[7],n*r[8]+o*r[9]+a*r[10]+s*r[11],n*r[12]+o*r[13]+a*r[14]+s*r[15])},e.prototype.dotCoordinate=function(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d},e.prototype.copyFromPoints=function(e,t,i){var r,n=t.x-e.x,o=t.y-e.y,a=t.z-e.z,s=i.x-e.x,l=i.y-e.y,c=i.z-e.z,u=o*c-a*l,h=a*s-n*c,d=n*l-o*s,p=Math.sqrt(u*u+h*h+d*d);return r=0!==p?1/p:0,this.normal.x=u*r,this.normal.y=h*r,this.normal.z=d*r,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this},e.prototype.isFrontFacingTo=function(e,t){return V.Dot(this.normal,e)<=t},e.prototype.signedDistanceTo=function(e){return V.Dot(e,this.normal)+this.d},e.FromArray=function(t){return new e(t[0],t[1],t[2],t[3])},e.FromPoints=function(t,i,r){var n=new e(0,0,0,0);return n.copyFromPoints(t,i,r),n},e.FromPositionAndNormal=function(t,i){var r=new e(0,0,0,0);return this.FromPositionAndNormalToRef(t,i,r)},e.FromPositionAndNormalToRef=function(e,t,i){return i.normal.copyFrom(t),i.normal.normalize(),i.d=-e.dot(i.normal),i},e.SignedDistanceToPlaneFromPositionAndNormal=function(e,t,i){var r=-(t.x*e.x+t.y*e.y+t.z*e.z);return V.Dot(i,t)+r},e._TmpMatrix=z.Identity(),e}(),ln=function(){function e(){}return e.GetPlanes=function(t){for(var i=[],r=0;r<6;r++)i.push(new sn(0,0,0,0));return e.GetPlanesToRef(t,i),i},e.GetNearPlaneToRef=function(e,t){var i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()},e.GetFarPlaneToRef=function(e,t){var i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()},e.GetLeftPlaneToRef=function(e,t){var i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()},e.GetRightPlaneToRef=function(e,t){var i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()},e.GetTopPlaneToRef=function(e,t){var i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()},e.GetBottomPlaneToRef=function(e,t){var i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()},e.GetPlanesToRef=function(t,i){e.GetNearPlaneToRef(t,i[0]),e.GetFarPlaneToRef(t,i[1]),e.GetLeftPlaneToRef(t,i[2]),e.GetRightPlaneToRef(t,i[3]),e.GetTopPlaneToRef(t,i[4]),e.GetBottomPlaneToRef(t,i[5])},e.IsPointInFrustum=function(e,t){for(var i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0},e}(),cn=function(){function e(){}return Object.defineProperty(e,"UniqueId",{get:function(){var e=this._UniqueIdCounter;return this._UniqueIdCounter++,e},enumerable:!1,configurable:!0}),e._UniqueIdCounter=1,e}(),un=function(){function e(){}return e.CompareLightsPriority=function(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority},e.FALLOFF_DEFAULT=0,e.FALLOFF_PHYSICAL=1,e.FALLOFF_GLTF=2,e.FALLOFF_STANDARD=3,e.LIGHTMAP_DEFAULT=0,e.LIGHTMAP_SPECULAR=1,e.LIGHTMAP_SHADOWSONLY=2,e.INTENSITYMODE_AUTOMATIC=0,e.INTENSITYMODE_LUMINOUSPOWER=1,e.INTENSITYMODE_LUMINOUSINTENSITY=2,e.INTENSITYMODE_ILLUMINANCE=3,e.INTENSITYMODE_LUMINANCE=4,e.LIGHTTYPEID_POINTLIGHT=0,e.LIGHTTYPEID_DIRECTIONALLIGHT=1,e.LIGHTTYPEID_SPOTLIGHT=2,e.LIGHTTYPEID_HEMISPHERICLIGHT=3,e}(),hn=function(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1};!function(e){e[e.BackwardCompatible=0]="BackwardCompatible",e[e.Intermediate=1]="Intermediate",e[e.Aggressive=2]="Aggressive"}(Kr||(Kr={}));var dn,pn=function(e){function t(i,r){var n=e.call(this)||this;n._inputManager=new on(n),n.cameraToUseForPointers=null,n._isScene=!0,n._blockEntityCollection=!1,n.autoClear=!0,n.autoClearDepthAndStencil=!0,n.clearColor=new J(.2,.2,.3,1),n.ambientColor=new Z(0,0,0),n.environmentIntensity=1,n._performancePriority=Kr.BackwardCompatible,n.onScenePerformancePriorityChangedObservable=new f,n._forceWireframe=!1,n._skipFrustumClipping=!1,n._forcePointsCloud=!1,n.animationsEnabled=!0,n._animationPropertiesOverride=null,n.useConstantAnimationDeltaTime=!1,n.constantlyUpdateMeshUnderPointer=!1,n.hoverCursor="pointer",n.defaultCursor="",n.doNotHandleCursors=!1,n.preventDefaultOnPointerDown=!0,n.preventDefaultOnPointerUp=!0,n.metadata=null,n.reservedDataStore=null,n.disableOfflineSupportExceptionRules=[],n.onDisposeObservable=new f,n._onDisposeObserver=null,n.onBeforeRenderObservable=new f,n._onBeforeRenderObserver=null,n.onAfterRenderObservable=new f,n.onAfterRenderCameraObservable=new f,n._onAfterRenderObserver=null,n.onBeforeAnimationsObservable=new f,n.onAfterAnimationsObservable=new f,n.onBeforeDrawPhaseObservable=new f,n.onAfterDrawPhaseObservable=new f,n.onReadyObservable=new f,n.onBeforeCameraRenderObservable=new f,n._onBeforeCameraRenderObserver=null,n.onAfterCameraRenderObservable=new f,n._onAfterCameraRenderObserver=null,n.onBeforeActiveMeshesEvaluationObservable=new f,n.onAfterActiveMeshesEvaluationObservable=new f,n.onBeforeParticlesRenderingObservable=new f,n.onAfterParticlesRenderingObservable=new f,n.onDataLoadedObservable=new f,n.onNewCameraAddedObservable=new f,n.onCameraRemovedObservable=new f,n.onNewLightAddedObservable=new f,n.onLightRemovedObservable=new f,n.onNewGeometryAddedObservable=new f,n.onGeometryRemovedObservable=new f,n.onNewTransformNodeAddedObservable=new f,n.onTransformNodeRemovedObservable=new f,n.onNewMeshAddedObservable=new f,n.onMeshRemovedObservable=new f,n.onNewSkeletonAddedObservable=new f,n.onSkeletonRemovedObservable=new f,n.onNewMaterialAddedObservable=new f,n.onNewMultiMaterialAddedObservable=new f,n.onMaterialRemovedObservable=new f,n.onMultiMaterialRemovedObservable=new f,n.onNewTextureAddedObservable=new f,n.onTextureRemovedObservable=new f,n.onBeforeRenderTargetsRenderObservable=new f,n.onAfterRenderTargetsRenderObservable=new f,n.onBeforeStepObservable=new f,n.onAfterStepObservable=new f,n.onActiveCameraChanged=new f,n.onActiveCamerasChanged=new f,n.onBeforeRenderingGroupObservable=new f,n.onAfterRenderingGroupObservable=new f,n.onMeshImportedObservable=new f,n.onAnimationFileImportedObservable=new f,n._registeredForLateAnimationBindings=new sr(256),n._pointerPickingConfiguration=new hn,n.onPrePointerObservable=new f,n.onPointerObservable=new f,n.onPreKeyboardObservable=new f,n.onKeyboardObservable=new f,n._useRightHandedSystem=!1,n._timeAccumulator=0,n._currentStepId=0,n._currentInternalStep=0,n._fogEnabled=!0,n._fogMode=t.FOGMODE_NONE,n.fogColor=new Z(.2,.2,.3),n.fogDensity=.1,n.fogStart=0,n.fogEnd=1e3,n.needsPreviousWorldMatrices=!1,n._shadowsEnabled=!0,n._lightsEnabled=!0,n._unObserveActiveCameras=null,n._texturesEnabled=!0,n.physicsEnabled=!0,n.particlesEnabled=!0,n.spritesEnabled=!0,n._skeletonsEnabled=!0,n.lensFlaresEnabled=!0,n.collisionsEnabled=!0,n.gravity=new V(0,-9.807,0),n.postProcessesEnabled=!0,n.renderTargetsEnabled=!0,n.dumpNextRenderTargets=!1,n.customRenderTargets=[],n.importedMeshesFiles=[],n.probesEnabled=!0,n._meshesForIntersections=new sr(256),n.proceduralTexturesEnabled=!0,n._totalVertices=new an,n._activeIndices=new an,n._activeParticles=new an,n._activeBones=new an,n._animationTime=0,n.animationTimeScale=1,n._renderId=0,n._frameId=0,n._executeWhenReadyTimeoutId=null,n._intermediateRendering=!1,n._defaultFrameBufferCleared=!1,n._viewUpdateFlag=-1,n._projectionUpdateFlag=-1,n._toBeDisposed=new Array(256),n._activeRequests=new Array,n._pendingData=new Array,n._isDisposed=!1,n.dispatchAllSubMeshesOfActiveMeshes=!1,n._activeMeshes=new ar(256),n._processedMaterials=new ar(256),n._renderTargets=new sr(256),n._materialsRenderTargets=new sr(256),n._activeParticleSystems=new ar(256),n._activeSkeletons=new sr(32),n._softwareSkinnedMeshes=new sr(32),n._activeAnimatables=new Array,n._transformMatrix=z.Zero(),n.requireLightSorting=!1,n._components=[],n._serializableComponents=[],n._transientComponents=[],n._beforeCameraUpdateStage=kr.Create(),n._beforeClearStage=kr.Create(),n._beforeRenderTargetClearStage=kr.Create(),n._gatherRenderTargetsStage=kr.Create(),n._gatherActiveCameraRenderTargetsStage=kr.Create(),n._isReadyForMeshStage=kr.Create(),n._beforeEvaluateActiveMeshStage=kr.Create(),n._evaluateSubMeshStage=kr.Create(),n._preActiveMeshStage=kr.Create(),n._cameraDrawRenderTargetStage=kr.Create(),n._beforeCameraDrawStage=kr.Create(),n._beforeRenderTargetDrawStage=kr.Create(),n._beforeRenderingGroupDrawStage=kr.Create(),n._beforeRenderingMeshStage=kr.Create(),n._afterRenderingMeshStage=kr.Create(),n._afterRenderingGroupDrawStage=kr.Create(),n._afterCameraDrawStage=kr.Create(),n._afterCameraPostProcessStage=kr.Create(),n._afterRenderTargetDrawStage=kr.Create(),n._afterRenderTargetPostProcessStage=kr.Create(),n._afterRenderStage=kr.Create(),n._pointerMoveStage=kr.Create(),n._pointerDownStage=kr.Create(),n._pointerUpStage=kr.Create(),n._geometriesByUniqueId=null,n._defaultMeshCandidates={data:[],length:0},n._defaultSubMeshCandidates={data:[],length:0},n._preventFreeActiveMeshesAndRenderingGroups=!1,n._activeMeshesFrozen=!1,n._activeMeshesFrozenButKeepClipping=!1,n._skipEvaluateActiveMeshesCompletely=!1,n._allowPostProcessClearColor=!0,n.getDeterministicFrameTime=function(){return n._engine.getTimeStep()},n._registeredActions=0,n._blockMaterialDirtyMechanism=!1,n._perfCollector=null,n.activeCameras=[];var o=g({useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1},r);return i=n._engine=i||M.LastCreatedEngine,o.virtual?i._virtualScenes.push(n):(M._LastCreatedScene=n,i.scenes.push(n)),n._uid=null,n._renderingManager=new Ur(n),Lr&&(n.postProcessManager=new Lr(n)),ct()&&n.attachControl(),n._createUbo(),pr&&(n._imageProcessingConfiguration=new pr),n.setDefaultCandidateProviders(),o.useGeometryUniqueIdsMap&&(n._geometriesByUniqueId={}),n.useMaterialMeshMap=o.useMaterialMeshMap,n.useClonedMeshMap=o.useClonedMeshMap,r&&r.virtual||i.onNewSceneAddedObservable.notifyObservers(n),n}return m(t,e),t.DefaultMaterialFactory=function(e){throw He("StandardMaterial")},t.CollisionCoordinatorFactory=function(){throw He("DefaultCollisionCoordinator")},Object.defineProperty(t.prototype,"environmentTexture",{get:function(){return this._environmentTexture},set:function(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"performancePriority",{get:function(){return this._performancePriority},set:function(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case Kr.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case Kr.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case Kr.Aggressive:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1}this.onScenePerformancePriorityChangedObservable.notifyObservers(e)}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"forceWireframe",{get:function(){return this._forceWireframe},set:function(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(u.MATERIAL_MiscDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"skipFrustumClipping",{get:function(){return this._skipFrustumClipping},set:function(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"forcePointsCloud",{get:function(){return this._forcePointsCloud},set:function(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(u.MATERIAL_MiscDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"animationPropertiesOverride",{get:function(){return this._animationPropertiesOverride},set:function(e){this._animationPropertiesOverride=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"beforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"afterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"beforeCameraRender",{set:function(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"afterCameraRender",{set:function(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"pointerDownPredicate",{get:function(){return this._pointerPickingConfiguration.pointerDownPredicate},set:function(e){this._pointerPickingConfiguration.pointerDownPredicate=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"pointerUpPredicate",{get:function(){return this._pointerPickingConfiguration.pointerUpPredicate},set:function(e){this._pointerPickingConfiguration.pointerUpPredicate=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"pointerMovePredicate",{get:function(){return this._pointerPickingConfiguration.pointerMovePredicate},set:function(e){this._pointerPickingConfiguration.pointerMovePredicate=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"pointerDownFastCheck",{get:function(){return this._pointerPickingConfiguration.pointerDownFastCheck},set:function(e){this._pointerPickingConfiguration.pointerDownFastCheck=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"pointerUpFastCheck",{get:function(){return this._pointerPickingConfiguration.pointerUpFastCheck},set:function(e){this._pointerPickingConfiguration.pointerUpFastCheck=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"pointerMoveFastCheck",{get:function(){return this._pointerPickingConfiguration.pointerMoveFastCheck},set:function(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"skipPointerMovePicking",{get:function(){return this._pointerPickingConfiguration.skipPointerMovePicking},set:function(e){this._pointerPickingConfiguration.skipPointerMovePicking=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"skipPointerDownPicking",{get:function(){return this._pointerPickingConfiguration.skipPointerDownPicking},set:function(e){this._pointerPickingConfiguration.skipPointerDownPicking=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"skipPointerUpPicking",{get:function(){return this._pointerPickingConfiguration.skipPointerUpPicking},set:function(e){this._pointerPickingConfiguration.skipPointerUpPicking=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"unTranslatedPointer",{get:function(){return this._inputManager.unTranslatedPointer},enumerable:!1,configurable:!0}),Object.defineProperty(t,"DragMovementThreshold",{get:function(){return on.DragMovementThreshold},set:function(e){on.DragMovementThreshold=e},enumerable:!1,configurable:!0}),Object.defineProperty(t,"LongPressDelay",{get:function(){return on.LongPressDelay},set:function(e){on.LongPressDelay=e},enumerable:!1,configurable:!0}),Object.defineProperty(t,"DoubleClickDelay",{get:function(){return on.DoubleClickDelay},set:function(e){on.DoubleClickDelay=e},enumerable:!1,configurable:!0}),Object.defineProperty(t,"ExclusiveDoubleClickMode",{get:function(){return on.ExclusiveDoubleClickMode},set:function(e){on.ExclusiveDoubleClickMode=e},enumerable:!1,configurable:!0}),t.prototype.bindEyePosition=function(e,t,i){void 0===t&&(t="vEyePosition"),void 0===i&&(i=!1);var r=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,n=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return H.Vector4[0].set(r.x,r.y,r.z,n?-1:1),e&&(i?e.setFloat3(t,H.Vector4[0].x,H.Vector4[0].y,H.Vector4[0].z):e.setVector4(t,H.Vector4[0])),H.Vector4[0]},t.prototype.finalizeSceneUbo=function(){var e=this.getSceneUniformBuffer(),t=this.bindEyePosition(null);return e.updateFloat4("vEyePosition",t.x,t.y,t.z,t.w),e.update(),e},Object.defineProperty(t.prototype,"useRightHandedSystem",{get:function(){return this._useRightHandedSystem},set:function(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(u.MATERIAL_MiscDirtyFlag))},enumerable:!1,configurable:!0}),t.prototype.setStepId=function(e){this._currentStepId=e},t.prototype.getStepId=function(){return this._currentStepId},t.prototype.getInternalStep=function(){return this._currentInternalStep},Object.defineProperty(t.prototype,"fogEnabled",{get:function(){return this._fogEnabled},set:function(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(u.MATERIAL_MiscDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"fogMode",{get:function(){return this._fogMode},set:function(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(u.MATERIAL_MiscDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"prePass",{get:function(){return!!this.prePassRenderer&&this.prePassRenderer.defaultRT.enabled},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"shadowsEnabled",{get:function(){return this._shadowsEnabled},set:function(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(u.MATERIAL_LightDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"lightsEnabled",{get:function(){return this._lightsEnabled},set:function(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(u.MATERIAL_LightDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"activeCameras",{get:function(){return this._activeCameras},set:function(e){var t=this;this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=P(e,(function(){t.onActiveCamerasChanged.notifyObservers(t)}))),this._activeCameras=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"activeCamera",{get:function(){return this._activeCamera},set:function(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"defaultMaterial",{get:function(){return this._defaultMaterial||(this._defaultMaterial=t.DefaultMaterialFactory(this)),this._defaultMaterial},set:function(e){this._defaultMaterial=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"texturesEnabled",{get:function(){return this._texturesEnabled},set:function(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"skeletonsEnabled",{get:function(){return this._skeletonsEnabled},set:function(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(u.MATERIAL_AttributesDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"collisionCoordinator",{get:function(){return this._collisionCoordinator||(this._collisionCoordinator=t.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"renderingManager",{get:function(){return this._renderingManager},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"frustumPlanes",{get:function(){return this._frustumPlanes},enumerable:!1,configurable:!0}),t.prototype._registerTransientComponents=function(){if(this._transientComponents.length>0){for(var e=0,t=this._transientComponents;e<t.length;e++)t[e].register();this._transientComponents.length=0}},t.prototype._addComponent=function(e){this._components.push(e),this._transientComponents.push(e);var t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)},t.prototype._getComponent=function(e){for(var t=0,i=this._components;t<i.length;t++){var r=i[t];if(r.name===e)return r}return null},t.prototype.getClassName=function(){return"Scene"},t.prototype._getDefaultMeshCandidates=function(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates},t.prototype._getDefaultSubMeshCandidates=function(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates},t.prototype.setDefaultCandidateProviders=function(){var e=this;this.getActiveMeshCandidates=function(){return e._getDefaultMeshCandidates()},this.getActiveSubMeshCandidates=function(t){return e._getDefaultSubMeshCandidates(t)},this.getIntersectingSubMeshCandidates=function(t,i){return e._getDefaultSubMeshCandidates(t)},this.getCollidingSubMeshCandidates=function(t,i){return e._getDefaultSubMeshCandidates(t)}},Object.defineProperty(t.prototype,"meshUnderPointer",{get:function(){return this._inputManager.meshUnderPointer},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"pointerX",{get:function(){return this._inputManager.pointerX},set:function(e){this._inputManager.pointerX=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"pointerY",{get:function(){return this._inputManager.pointerY},set:function(e){this._inputManager.pointerY=e},enumerable:!1,configurable:!0}),t.prototype.getCachedMaterial=function(){return this._cachedMaterial},t.prototype.getCachedEffect=function(){return this._cachedEffect},t.prototype.getCachedVisibility=function(){return this._cachedVisibility},t.prototype.isCachedMaterialInvalid=function(e,t,i){return void 0===i&&(i=1),this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i},t.prototype.getEngine=function(){return this._engine},t.prototype.getTotalVertices=function(){return this._totalVertices.current},Object.defineProperty(t.prototype,"totalVerticesPerfCounter",{get:function(){return this._totalVertices},enumerable:!1,configurable:!0}),t.prototype.getActiveIndices=function(){return this._activeIndices.current},Object.defineProperty(t.prototype,"totalActiveIndicesPerfCounter",{get:function(){return this._activeIndices},enumerable:!1,configurable:!0}),t.prototype.getActiveParticles=function(){return this._activeParticles.current},Object.defineProperty(t.prototype,"activeParticlesPerfCounter",{get:function(){return this._activeParticles},enumerable:!1,configurable:!0}),t.prototype.getActiveBones=function(){return this._activeBones.current},Object.defineProperty(t.prototype,"activeBonesPerfCounter",{get:function(){return this._activeBones},enumerable:!1,configurable:!0}),t.prototype.getActiveMeshes=function(){return this._activeMeshes},t.prototype.getAnimationRatio=function(){return void 0!==this._animationRatio?this._animationRatio:1},t.prototype.getRenderId=function(){return this._renderId},t.prototype.getFrameId=function(){return this._frameId},t.prototype.incrementRenderId=function(){this._renderId++},t.prototype._createUbo=function(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())},t.prototype.simulatePointerMove=function(e,t){return this._inputManager.simulatePointerMove(e,t),this},t.prototype.simulatePointerDown=function(e,t){return this._inputManager.simulatePointerDown(e,t),this},t.prototype.simulatePointerUp=function(e,t,i){return this._inputManager.simulatePointerUp(e,t,i),this},t.prototype.isPointerCaptured=function(e){return void 0===e&&(e=0),this._inputManager.isPointerCaptured(e)},t.prototype.attachControl=function(e,t,i){void 0===e&&(e=!0),void 0===t&&(t=!0),void 0===i&&(i=!0),this._inputManager.attachControl(e,t,i)},t.prototype.detachControl=function(){this._inputManager.detachControl()},t.prototype.isReady=function(e){var t,i,r,n;if(void 0===e&&(e=!0),this._isDisposed)return!1;var o=this.getEngine(),a=o.currentRenderPassId;o.currentRenderPassId=null!==(i=null===(t=this.activeCamera)||void 0===t?void 0:t.renderPassId)&&void 0!==i?i:a;var s=!0;for(this._pendingData.length>0&&(s=!1),null===(r=this.prePassRenderer)||void 0===r||r.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&s&&(s=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),n=0;n<this.meshes.length;n++){var l=this.meshes[n];if(l.subMeshes&&0!==l.subMeshes.length)if(l.isReady(!0)){for(var c=l.hasThinInstances||"InstancedMesh"===l.getClassName()||"InstancedLinesMesh"===l.getClassName()||o.getCaps().instancedArrays&&l.instances.length>0,h=0,d=this._isReadyForMeshStage;h<d.length;h++)d[h].action(l,c)||(s=!1);if(e){var p=l.material||this.defaultMaterial;if(p)if(p._storeEffectOnSubMeshes)for(var f=0,_=l.subMeshes;f<_.length;f++){var m=_[f].getMaterial();m&&m.hasRenderTargetTextures&&null!=m.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(m)&&(this._processedMaterials.push(m),this._materialsRenderTargets.concatWithNoDuplicate(m.getRenderTargetTextures()))}else p.hasRenderTargetTextures&&null!=p.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(p)&&(this._processedMaterials.push(p),this._materialsRenderTargets.concatWithNoDuplicate(p.getRenderTargetTextures()))}}else s=!1}if(e)for(n=0;n<this._materialsRenderTargets.length;++n)this._materialsRenderTargets.data[n].isReadyForRendering()||(s=!1);for(n=0;n<this.geometries.length;n++)this.geometries[n].delayLoadState===u.DELAYLOADSTATE_LOADING&&(s=!1);if(this.activeCameras&&this.activeCameras.length>0)for(var g=0,v=this.activeCameras;g<v.length;g++)v[g].isReady(!0)||(s=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(s=!1));for(var y=0,b=this.particleSystems;y<b.length;y++)b[y].isReady()||(s=!1);if(this.layers)for(var T=0,E=this.layers;T<E.length;T++)E[T].isReady()||(s=!1);return o.areAllEffectsReady()||(s=!1),o.currentRenderPassId=a,s},t.prototype.resetCachedMaterial=function(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null},t.prototype.registerBeforeRender=function(e){this.onBeforeRenderObservable.add(e)},t.prototype.unregisterBeforeRender=function(e){this.onBeforeRenderObservable.removeCallback(e)},t.prototype.registerAfterRender=function(e){this.onAfterRenderObservable.add(e)},t.prototype.unregisterAfterRender=function(e){this.onAfterRenderObservable.removeCallback(e)},t.prototype._executeOnceBeforeRender=function(e){var t=this,i=function(){e(),setTimeout((function(){t.unregisterBeforeRender(i)}))};this.registerBeforeRender(i)},t.prototype.executeOnceBeforeRender=function(e,t){var i=this;void 0!==t?setTimeout((function(){i._executeOnceBeforeRender(e)}),t):this._executeOnceBeforeRender(e)},t.prototype.addPendingData=function(e){this._pendingData.push(e)},t.prototype.removePendingData=function(e){var t=this.isLoading,i=this._pendingData.indexOf(e);-1!==i&&this._pendingData.splice(i,1),t&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)},t.prototype.getWaitingItemsCount=function(){return this._pendingData.length},Object.defineProperty(t.prototype,"isLoading",{get:function(){return this._pendingData.length>0},enumerable:!1,configurable:!0}),t.prototype.executeWhenReady=function(e,t){void 0===t&&(t=!1),this.onReadyObservable.addOnce(e),null===this._executeWhenReadyTimeoutId&&this._checkIsReady(t)},t.prototype.whenReadyAsync=function(e){var t=this;return void 0===e&&(e=!1),new Promise((function(i){t.executeWhenReady((function(){i()}),e)}))},t.prototype._checkIsReady=function(e){var t=this;return void 0===e&&(e=!1),this._registerTransientComponents(),this.isReady(e)?(this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):this._isDisposed?(this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):void(this._executeWhenReadyTimeoutId=setTimeout((function(){t.incrementRenderId(),t._checkIsReady(e)}),100))},Object.defineProperty(t.prototype,"animatables",{get:function(){return this._activeAnimatables},enumerable:!1,configurable:!0}),t.prototype.resetLastAnimationTimeFrame=function(){this._animationTimeLast=_t.Now},t.prototype.getViewMatrix=function(){return this._viewMatrix},t.prototype.getProjectionMatrix=function(){return this._projectionMatrix},t.prototype.getTransformMatrix=function(){return this._transformMatrix},t.prototype.setTransformMatrix=function(e,t,i,r){i||r||!this._multiviewSceneUbo||(this._multiviewSceneUbo.dispose(),this._multiviewSceneUbo=null),this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag||(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?ln.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=ln.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,r):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))},t.prototype.getSceneUniformBuffer=function(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo},t.prototype.createSceneUniformBuffer=function(e){var t=new Or(this._engine,void 0,!1,null!=e?e:"scene");return t.addUniform("viewProjection",16),t.addUniform("view",16),t.addUniform("projection",16),t.addUniform("vEyePosition",4),t},t.prototype.setSceneUniformBuffer=function(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1},t.prototype.getUniqueId=function(){return cn.UniqueId},t.prototype.addMesh=function(e,t){var i=this;void 0===t&&(t=!1),this._blockEntityCollection||(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((function(e){i.addMesh(e)})))},t.prototype.removeMesh=function(e,t){var i=this;void 0===t&&(t=!1);var r=this.meshes.indexOf(e);return-1!==r&&(this.meshes[r]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((function(e){i.removeMesh(e)})),r},t.prototype.addTransformNode=function(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneTransformNodesArray||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))},t.prototype.removeTransformNode=function(e){var t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){var i=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=i,i._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t},t.prototype.removeSkeleton=function(e){var t=this.skeletons.indexOf(e);return-1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t},t.prototype.removeMorphTargetManager=function(e){var t=this.morphTargetManagers.indexOf(e);return-1!==t&&this.morphTargetManagers.splice(t,1),t},t.prototype.removeLight=function(e){var t=this.lights.indexOf(e);if(-1!==t){for(var i=0,r=this.meshes;i<r.length;i++)r[i]._removeLightSource(e,!1);this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes()}return this.onLightRemovedObservable.notifyObservers(e),t},t.prototype.removeCamera=function(e){var t=this.cameras.indexOf(e);if(-1!==t&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){var i=this.activeCameras.indexOf(e);-1!==i&&this.activeCameras.splice(i,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t},t.prototype.removeParticleSystem=function(e){var t=this.particleSystems.indexOf(e);return-1!==t&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t},t.prototype.removeAnimation=function(e){var t=this.animations.indexOf(e);return-1!==t&&this.animations.splice(t,1),t},t.prototype.stopAnimation=function(e,t,i){},t.prototype.removeAnimationGroup=function(e){var t=this.animationGroups.indexOf(e);return-1!==t&&this.animationGroups.splice(t,1),t},t.prototype.removeMultiMaterial=function(e){var t=this.multiMaterials.indexOf(e);return-1!==t&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t},t.prototype.removeMaterial=function(e){var t=e._indexInSceneMaterialArray;if(-1!==t&&t<this.materials.length){if(t!==this.materials.length-1){var i=this.materials[this.materials.length-1];this.materials[t]=i,i._indexInSceneMaterialArray=t}e._indexInSceneMaterialArray=-1,this.materials.pop()}return this.onMaterialRemovedObservable.notifyObservers(e),t},t.prototype.removeActionManager=function(e){var t=this.actionManagers.indexOf(e);return-1!==t&&this.actionManagers.splice(t,1),t},t.prototype.removeTexture=function(e){var t=this.textures.indexOf(e);return-1!==t&&this.textures.splice(t,1),this.onTextureRemovedObservable.notifyObservers(e),t},t.prototype.addLight=function(e){if(!this._blockEntityCollection){this.lights.push(e),this.sortLightsByPriority(),e.parent||e._addToSceneRootNodes();for(var t=0,i=this.meshes;t<i.length;t++){var r=i[t];-1===r.lightSources.indexOf(e)&&(r.lightSources.push(e),r._resyncLightSources())}this.onNewLightAddedObservable.notifyObservers(e)}},t.prototype.sortLightsByPriority=function(){this.requireLightSorting&&this.lights.sort(un.CompareLightsPriority)},t.prototype.addCamera=function(e){this._blockEntityCollection||(this.cameras.push(e),this.onNewCameraAddedObservable.notifyObservers(e),e.parent||e._addToSceneRootNodes())},t.prototype.addSkeleton=function(e){this._blockEntityCollection||(this.skeletons.push(e),this.onNewSkeletonAddedObservable.notifyObservers(e))},t.prototype.addParticleSystem=function(e){this._blockEntityCollection||this.particleSystems.push(e)},t.prototype.addAnimation=function(e){this._blockEntityCollection||this.animations.push(e)},t.prototype.addAnimationGroup=function(e){this._blockEntityCollection||this.animationGroups.push(e)},t.prototype.addMultiMaterial=function(e){this._blockEntityCollection||(this.multiMaterials.push(e),this.onNewMultiMaterialAddedObservable.notifyObservers(e))},t.prototype.addMaterial=function(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneMaterialArray||(e._indexInSceneMaterialArray=this.materials.length,this.materials.push(e),this.onNewMaterialAddedObservable.notifyObservers(e))},t.prototype.addMorphTargetManager=function(e){this._blockEntityCollection||this.morphTargetManagers.push(e)},t.prototype.addGeometry=function(e){this._blockEntityCollection||(this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=this.geometries.length),this.geometries.push(e))},t.prototype.addActionManager=function(e){this.actionManagers.push(e)},t.prototype.addTexture=function(e){this._blockEntityCollection||(this.textures.push(e),this.onNewTextureAddedObservable.notifyObservers(e))},t.prototype.switchActiveCamera=function(e,t){void 0===t&&(t=!0),this._engine.getInputElement()&&(this.activeCamera&&this.activeCamera.detachControl(),this.activeCamera=e,t&&e.attachControl())},t.prototype.setActiveCameraById=function(e){var t=this.getCameraById(e);return t?(this.activeCamera=t,t):null},t.prototype.setActiveCameraByName=function(e){var t=this.getCameraByName(e);return t?(this.activeCamera=t,t):null},t.prototype.getAnimationGroupByName=function(e){for(var t=0;t<this.animationGroups.length;t++)if(this.animationGroups[t].name===e)return this.animationGroups[t];return null},t.prototype._getMaterial=function(e,t){for(var i=0;i<this.materials.length;i++)if(t(r=this.materials[i]))return r;if(e)for(i=0;i<this.multiMaterials.length;i++){var r;if(t(r=this.multiMaterials[i]))return r}return null},t.prototype.getMaterialByUniqueID=function(e,t){return void 0===t&&(t=!1),this._getMaterial(t,(function(t){return t.uniqueId===e}))},t.prototype.getMaterialById=function(e,t){return void 0===t&&(t=!1),this._getMaterial(t,(function(t){return t.id===e}))},t.prototype.getMaterialByName=function(e,t){return void 0===t&&(t=!1),this._getMaterial(t,(function(t){return t.name===e}))},t.prototype.getLastMaterialById=function(e,t){void 0===t&&(t=!1);for(var i=this.materials.length-1;i>=0;i--)if(this.materials[i].id===e)return this.materials[i];if(t)for(i=this.multiMaterials.length-1;i>=0;i--)if(this.multiMaterials[i].id===e)return this.multiMaterials[i];return null},t.prototype.getTextureByUniqueId=function(e){for(var t=0;t<this.textures.length;t++)if(this.textures[t].uniqueId===e)return this.textures[t];return null},t.prototype.getTextureByName=function(e){for(var t=0;t<this.textures.length;t++)if(this.textures[t].name===e)return this.textures[t];return null},t.prototype.getCameraById=function(e){for(var t=0;t<this.cameras.length;t++)if(this.cameras[t].id===e)return this.cameras[t];return null},t.prototype.getCameraByUniqueId=function(e){for(var t=0;t<this.cameras.length;t++)if(this.cameras[t].uniqueId===e)return this.cameras[t];return null},t.prototype.getCameraByName=function(e){for(var t=0;t<this.cameras.length;t++)if(this.cameras[t].name===e)return this.cameras[t];return null},t.prototype.getBoneById=function(e){for(var t=0;t<this.skeletons.length;t++)for(var i=this.skeletons[t],r=0;r<i.bones.length;r++)if(i.bones[r].id===e)return i.bones[r];return null},t.prototype.getBoneByName=function(e){for(var t=0;t<this.skeletons.length;t++)for(var i=this.skeletons[t],r=0;r<i.bones.length;r++)if(i.bones[r].name===e)return i.bones[r];return null},t.prototype.getLightByName=function(e){for(var t=0;t<this.lights.length;t++)if(this.lights[t].name===e)return this.lights[t];return null},t.prototype.getLightById=function(e){for(var t=0;t<this.lights.length;t++)if(this.lights[t].id===e)return this.lights[t];return null},t.prototype.getLightByUniqueId=function(e){for(var t=0;t<this.lights.length;t++)if(this.lights[t].uniqueId===e)return this.lights[t];return null},t.prototype.getParticleSystemById=function(e){for(var t=0;t<this.particleSystems.length;t++)if(this.particleSystems[t].id===e)return this.particleSystems[t];return null},t.prototype.getGeometryById=function(e){for(var t=0;t<this.geometries.length;t++)if(this.geometries[t].id===e)return this.geometries[t];return null},t.prototype._getGeometryByUniqueId=function(e){if(this._geometriesByUniqueId){if(void 0!==(t=this._geometriesByUniqueId[e]))return this.geometries[t]}else for(var t=0;t<this.geometries.length;t++)if(this.geometries[t].uniqueId===e)return this.geometries[t];return null},t.prototype.pushGeometry=function(e,t){return!(!t&&this._getGeometryByUniqueId(e.uniqueId)||(this.addGeometry(e),this.onNewGeometryAddedObservable.notifyObservers(e),0))},t.prototype.removeGeometry=function(e){var t;if(this._geometriesByUniqueId){if(void 0===(t=this._geometriesByUniqueId[e.uniqueId]))return!1}else if((t=this.geometries.indexOf(e))<0)return!1;if(t!==this.geometries.length-1){var i=this.geometries[this.geometries.length-1];i&&(this.geometries[t]=i,this._geometriesByUniqueId&&(this._geometriesByUniqueId[i.uniqueId]=t))}return this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=void 0),this.geometries.pop(),this.onGeometryRemovedObservable.notifyObservers(e),!0},t.prototype.getGeometries=function(){return this.geometries},t.prototype.getMeshById=function(e){for(var t=0;t<this.meshes.length;t++)if(this.meshes[t].id===e)return this.meshes[t];return null},t.prototype.getMeshesById=function(e){return this.meshes.filter((function(t){return t.id===e}))},t.prototype.getTransformNodeById=function(e){for(var t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null},t.prototype.getTransformNodeByUniqueId=function(e){for(var t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].uniqueId===e)return this.transformNodes[t];return null},t.prototype.getTransformNodesById=function(e){return this.transformNodes.filter((function(t){return t.id===e}))},t.prototype.getMeshByUniqueId=function(e){for(var t=0;t<this.meshes.length;t++)if(this.meshes[t].uniqueId===e)return this.meshes[t];return null},t.prototype.getLastMeshById=function(e){for(var t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null},t.prototype.getLastTransformNodeById=function(e){for(var t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null},t.prototype.getLastEntryById=function(e){var t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null},t.prototype.getNodeById=function(e){var t=this.getMeshById(e);if(t)return t;var i=this.getTransformNodeById(e);if(i)return i;var r=this.getLightById(e);if(r)return r;var n=this.getCameraById(e);return n||(this.getBoneById(e)||null)},t.prototype.getNodeByName=function(e){var t=this.getMeshByName(e);if(t)return t;var i=this.getTransformNodeByName(e);if(i)return i;var r=this.getLightByName(e);if(r)return r;var n=this.getCameraByName(e);return n||(this.getBoneByName(e)||null)},t.prototype.getMeshByName=function(e){for(var t=0;t<this.meshes.length;t++)if(this.meshes[t].name===e)return this.meshes[t];return null},t.prototype.getTransformNodeByName=function(e){for(var t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].name===e)return this.transformNodes[t];return null},t.prototype.getLastSkeletonById=function(e){for(var t=this.skeletons.length-1;t>=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null},t.prototype.getSkeletonByUniqueId=function(e){for(var t=0;t<this.skeletons.length;t++)if(this.skeletons[t].uniqueId===e)return this.skeletons[t];return null},t.prototype.getSkeletonById=function(e){for(var t=0;t<this.skeletons.length;t++)if(this.skeletons[t].id===e)return this.skeletons[t];return null},t.prototype.getSkeletonByName=function(e){for(var t=0;t<this.skeletons.length;t++)if(this.skeletons[t].name===e)return this.skeletons[t];return null},t.prototype.getMorphTargetManagerById=function(e){for(var t=0;t<this.morphTargetManagers.length;t++)if(this.morphTargetManagers[t].uniqueId===e)return this.morphTargetManagers[t];return null},t.prototype.getMorphTargetById=function(e){for(var t=0;t<this.morphTargetManagers.length;++t)for(var i=this.morphTargetManagers[t],r=0;r<i.numTargets;++r){var n=i.getTarget(r);if(n.id===e)return n}return null},t.prototype.getMorphTargetByName=function(e){for(var t=0;t<this.morphTargetManagers.length;++t)for(var i=this.morphTargetManagers[t],r=0;r<i.numTargets;++r){var n=i.getTarget(r);if(n.name===e)return n}return null},t.prototype.getPostProcessByName=function(e){for(var t=0;t<this.postProcesses.length;++t){var i=this.postProcesses[t];if(i.name===e)return i}return null},t.prototype.isActiveMesh=function(e){return-1!==this._activeMeshes.indexOf(e)},Object.defineProperty(t.prototype,"uid",{get:function(){return this._uid||(this._uid=rr.RandomId()),this._uid},enumerable:!1,configurable:!0}),t.prototype.addExternalData=function(e,t){return this._externalData||(this._externalData=new lr),this._externalData.add(e,t)},t.prototype.getExternalData=function(e){return this._externalData?this._externalData.get(e):null},t.prototype.getOrAddExternalDataWithFactory=function(e,t){return this._externalData||(this._externalData=new lr),this._externalData.getOrAddWithFactory(e,t)},t.prototype.removeExternalData=function(e){return this._externalData.remove(e)},t.prototype._evaluateSubMesh=function(e,t,i,r){if(r||e.isInFrustum(this._frustumPlanes)){for(var n=0,o=this._evaluateSubMeshStage;n<o.length;n++)o[n].action(t,e);var a=e.getMaterial();null!=a&&(a.hasRenderTargetTextures&&null!=a.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(a)&&(this._processedMaterials.push(a),this._materialsRenderTargets.concatWithNoDuplicate(a.getRenderTargetTextures())),this._renderingManager.dispatch(e,t,a))}},t.prototype.freeProcessedMaterials=function(){this._processedMaterials.dispose()},Object.defineProperty(t.prototype,"blockfreeActiveMeshesAndRenderingGroups",{get:function(){return this._preventFreeActiveMeshesAndRenderingGroups},set:function(e){this._preventFreeActiveMeshesAndRenderingGroups!==e&&(e&&(this.freeActiveMeshes(),this.freeRenderingGroups()),this._preventFreeActiveMeshesAndRenderingGroups=e)},enumerable:!1,configurable:!0}),t.prototype.freeActiveMeshes=function(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._activeMeshes.dispose(),this.activeCamera&&this.activeCamera._activeMeshes&&this.activeCamera._activeMeshes.dispose(),this.activeCameras))for(var e=0;e<this.activeCameras.length;e++){var t=this.activeCameras[e];t&&t._activeMeshes&&t._activeMeshes.dispose()}},t.prototype.freeRenderingGroups=function(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._renderingManager&&this._renderingManager.freeRenderingGroups(),this.textures))for(var e=0;e<this.textures.length;e++){var t=this.textures[e];t&&t.renderList&&t.freeRenderingGroups()}},t.prototype._isInIntermediateRendering=function(){return this._intermediateRendering},t.prototype.freezeActiveMeshes=function(e,t,i,r,n){var o=this;return void 0===e&&(e=!1),void 0===r&&(r=!0),void 0===n&&(n=!1),this.executeWhenReady((function(){if(o.activeCamera){if(o._frustumPlanes||o.updateTransformMatrix(),o._evaluateActiveMeshes(),o._activeMeshesFrozen=!0,o._activeMeshesFrozenButKeepClipping=n,o._skipEvaluateActiveMeshesCompletely=e,r)for(var a=0;a<o._activeMeshes.length;a++)o._activeMeshes.data[a]._freeze();t&&t()}else i&&i("No active camera found")})),this},t.prototype.unfreezeActiveMeshes=function(){for(var e=0;e<this.meshes.length;e++){var t=this.meshes[e];t._internalAbstractMeshDataInfo&&(t._internalAbstractMeshDataInfo._isActive=!1)}for(e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._unFreeze();return this._activeMeshesFrozen=!1,this},t.prototype._executeActiveContainerCleanup=function(e){(!this._engine.snapshotRendering||this._engine.snapshotRenderingMode!==u.SNAPSHOTRENDERING_FAST)&&this._activeMeshesFrozen&&this._activeMeshes.length||this.onBeforeRenderObservable.addOnce((function(){return e.dispose()}))},t.prototype._evaluateActiveMeshes=function(){var e;if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===u.SNAPSHOTRENDERING_FAST)this._activeMeshes.length>0&&(null===(e=this.activeCamera)||void 0===e||e._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset());else if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely)for(var t=this._activeMeshes.length,i=0;i<t;i++)(l=this._activeMeshes.data[i]).computeWorldMatrix();if(this._activeParticleSystems){var r=this._activeParticleSystems.length;for(i=0;i<r;i++)this._activeParticleSystems.data[i].animate()}this._renderingManager.resetSprites()}else if(this.activeCamera){this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this),this.activeCamera._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset(),this._materialsRenderTargets.reset();for(var n=0,o=this._beforeEvaluateActiveMeshStage;n<o.length;n++)o[n].action();var a=this.getActiveMeshCandidates(),s=a.length;for(i=0;i<s;i++){var l;if((l=a.data[i])._internalAbstractMeshDataInfo._currentLODIsUpToDate=!1,!l.isBlocked&&(this._totalVertices.addCount(l.getTotalVertices(),!1),l.isReady()&&l.isEnabled()&&!l.scaling.hasAZeroComponent)){l.computeWorldMatrix(),l.actionManager&&l.actionManager.hasSpecificTriggers2(u.ACTION_OnIntersectionEnterTrigger,u.ACTION_OnIntersectionExitTrigger)&&this._meshesForIntersections.pushNoDuplicate(l);var c=this.customLODSelector?this.customLODSelector(l,this.activeCamera):l.getLOD(this.activeCamera);if(l._internalAbstractMeshDataInfo._currentLOD=c,l._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0,null!=c&&(c!==l&&0!==c.billboardMode&&c.computeWorldMatrix(),l._preActivate(),l.isVisible&&l.visibility>0&&l.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||l.alwaysSelectAsActiveMesh||l.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(l),this.activeCamera._activeMeshes.push(l),c!==l&&c._activate(this._renderId,!1);for(var h=0,d=this._preActiveMeshStage;h<d.length;h++)d[h].action(l);l._activate(this._renderId,!1)&&(l.isAnInstance?l._internalAbstractMeshDataInfo._actAsRegularMesh&&(c=l):c._internalAbstractMeshDataInfo._onlyForInstances=!1,c._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(l,c)),l._postActivate()}}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(var p=0;p<this.particleSystems.length;p++){var f=this.particleSystems[p];if(f.isStarted()&&f.emitter){var _=f.emitter;_.position&&!_.isEnabled()||(this._activeParticleSystems.push(f),f.animate(),this._renderingManager.dispatchParticles(f))}}this.onAfterParticlesRenderingObservable.notifyObservers(this)}}},t.prototype._activeMesh=function(e,t){this._skeletonsEnabled&&null!==t.skeleton&&void 0!==t.skeleton&&(this._activeSkeletons.pushNoDuplicate(t.skeleton)&&(t.skeleton.prepare(),this._activeBones.addCount(t.skeleton.bones.length,!1)),t.computeBonesUsingShaders||this._softwareSkinnedMeshes.pushNoDuplicate(t));var i=e.hasInstances||e.isAnInstance||this.dispatchAllSubMeshesOfActiveMeshes||this._skipFrustumClipping||t.alwaysSelectAsActiveMesh;if(t&&t.subMeshes&&t.subMeshes.length>0){var r=this.getActiveSubMeshCandidates(t),n=r.length;i=i||1===n;for(var o=0;o<n;o++){var a=r.data[o];this._evaluateSubMesh(a,t,e,i)}}},t.prototype.updateTransformMatrix=function(e){var t=this.activeCamera;if(t)if(t._renderingMultiview){var i=t._rigCameras[0],r=t._rigCameras[1];this.setTransformMatrix(i.getViewMatrix(),i.getProjectionMatrix(e),r.getViewMatrix(),r.getProjectionMatrix(e))}else this.setTransformMatrix(t.getViewMatrix(),t.getProjectionMatrix(e))},t.prototype._bindFrameBuffer=function(e,t){void 0===t&&(t=!0),e&&e._multiviewTexture?e._multiviewTexture._bindFrameBuffer():e&&e.outputRenderTarget?e.outputRenderTarget._bindFrameBuffer():this._engine._currentFrameBufferIsDefaultFrameBuffer()||this._engine.restoreDefaultFramebuffer(),t&&this._clearFrameBuffer(e)},t.prototype._clearFrameBuffer=function(e){if(e&&e._multiviewTexture);else if(e&&e.outputRenderTarget&&!e._renderingMultiview){var t=e.outputRenderTarget;t.onClearObservable.hasObservers()?t.onClearObservable.notifyObservers(this._engine):t.skipInitialClear||e.isRightCamera||(this.autoClear&&this._engine.clear(t.clearColor||this.clearColor,!t._cleared,!0,!0),t._cleared=!0)}else this._defaultFrameBufferCleared?this._engine.clear(null,!1,!0,!0):(this._defaultFrameBufferCleared=!0,this._clear())},t.prototype._renderForCamera=function(e,t,i){var r,n,o;if(void 0===i&&(i=!0),!e||!e._skipRendering){var a=this._engine;if(this._activeCamera=e,!this.activeCamera)throw new Error("Active camera not set");if(a.setViewport(this.activeCamera.viewport),this.resetCachedMaterial(),this._renderId++,!this.prePass&&i){var s=!0;e._renderingMultiview&&e.outputRenderTarget&&(s=e.outputRenderTarget.skipInitialClear,this.autoClear&&(this._defaultFrameBufferCleared=!1,e.outputRenderTarget.skipInitialClear=!1)),this._bindFrameBuffer(this._activeCamera),e._renderingMultiview&&e.outputRenderTarget&&(e.outputRenderTarget.skipInitialClear=s)}this.updateTransformMatrix(),this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera),this._evaluateActiveMeshes();for(var l=0;l<this._softwareSkinnedMeshes.length;l++){var c=this._softwareSkinnedMeshes.data[l];c.applySkeleton(c.skeleton)}this.onBeforeRenderTargetsRenderObservable.notifyObservers(this),this._renderTargets.concatWithNoDuplicate(this._materialsRenderTargets),e.customRenderTargets&&e.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(var h=0,d=this._gatherActiveCameraRenderTargetsStage;h<d.length;h++)d[h].action(this._renderTargets);var p=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){rr.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(var f=0;f<this._renderTargets.length;f++){var _=this._renderTargets.data[f];if(_._shouldRender()){this._renderId++;var m=_.activeCamera&&_.activeCamera!==this.activeCamera;_.render(m,this.dumpNextRenderTargets),p=!0}}rr.EndPerformanceCounter("Render targets",this._renderTargets.length>0),this._renderId++}for(var g=0,v=this._cameraDrawRenderTargetStage;g<v.length;g++)p=v[g].action(this.activeCamera)||p;this._intermediateRendering=!1}this._engine.currentRenderPassId=null!==(o=null!==(n=null===(r=e.outputRenderTarget)||void 0===r?void 0:r.renderPassId)&&void 0!==n?n:e.renderPassId)&&void 0!==o?o:u.RENDERPASS_MAIN,p&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame();for(var y=0,b=this._beforeCameraDrawStage;y<b.length;y++)b[y].action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),a.snapshotRendering&&a.snapshotRenderingMode===u.SNAPSHOTRENDERING_FAST&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(var T=0,E=this._afterCameraDrawStage;T<E.length;T++)E[T].action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){var S=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,S)}for(var x=0,A=this._afterCameraPostProcessStage;x<A.length;x++)A[x].action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}},t.prototype._processSubCameras=function(e,t){if(void 0===t&&(t=!0),e.cameraRigMode===u.RIG_MODE_NONE||e._renderingMultiview)return e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),void this.onAfterRenderCameraObservable.notifyObservers(e);if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(var i=0;i<e._rigCameras.length;i++)this._renderForCamera(e._rigCameras[i],e)}this._activeCamera=e,this.updateTransformMatrix(),this.onAfterRenderCameraObservable.notifyObservers(e)},t.prototype._checkIntersections=function(){for(var e=0;e<this._meshesForIntersections.length;e++){var t=this._meshesForIntersections.data[e];if(t.actionManager)for(var i=function(e){var i=t.actionManager.actions[e];if(i.trigger===u.ACTION_OnIntersectionEnterTrigger||i.trigger===u.ACTION_OnIntersectionExitTrigger){var r=i.getTriggerParameter(),n=r.mesh?r.mesh:r,o=n.intersectsMesh(t,r.usePreciseIntersection),a=t._intersectionsInProgress.indexOf(n);o&&-1===a?i.trigger===u.ACTION_OnIntersectionEnterTrigger?(i._executeCurrent(te.CreateNew(t,void 0,n)),t._intersectionsInProgress.push(n)):i.trigger===u.ACTION_OnIntersectionExitTrigger&&t._intersectionsInProgress.push(n):!o&&a>-1&&(i.trigger===u.ACTION_OnIntersectionExitTrigger&&i._executeCurrent(te.CreateNew(t,void 0,n)),t.actionManager.hasSpecificTrigger(u.ACTION_OnIntersectionExitTrigger,(function(e){var t=e.mesh?e.mesh:e;return n===t}))&&i.trigger!==u.ACTION_OnIntersectionExitTrigger||t._intersectionsInProgress.splice(a,1))}},r=0;t.actionManager&&r<t.actionManager.actions.length;r++)i(r)}},t.prototype._advancePhysicsEngineStep=function(e){},t.prototype._animate=function(e){},t.prototype.animate=function(){if(this._engine.isDeterministicLockStep()){var e=Math.max(t.MinDeltaTime,Math.min(this._engine.getDeltaTime(),t.MaxDeltaTime))+this._timeAccumulator,i=this._engine.getTimeStep(),r=1e3/i/1e3,n=0,o=this._engine.getLockstepMaxSteps(),a=Math.floor(e/i);for(a=Math.min(a,o);e>0&&n<a;)this.onBeforeStepObservable.notifyObservers(this),this._animationRatio=i*r,this._animate(i),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(i),this.onAfterStepObservable.notifyObservers(this),this._currentStepId++,n++,e-=i;this._timeAccumulator=e<0?0:e}else e=this.useConstantAnimationDeltaTime?16:Math.max(t.MinDeltaTime,Math.min(this._engine.getDeltaTime(),t.MaxDeltaTime)),this._animationRatio=.06*e,this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(e)},t.prototype._clear=function(){(this.autoClearDepthAndStencil||this.autoClear)&&this._engine.clear(this.clearColor,this.autoClear||this.forceWireframe||this.forcePointsCloud,this.autoClearDepthAndStencil,this.autoClearDepthAndStencil)},t.prototype._checkCameraRenderTarget=function(e){var t;if((null==e?void 0:e.outputRenderTarget)&&!(null==e?void 0:e.isRigCamera)&&(e.outputRenderTarget._cleared=!1),null===(t=null==e?void 0:e.rigCameras)||void 0===t?void 0:t.length)for(var i=0;i<e.rigCameras.length;++i){var r=e.rigCameras[i].outputRenderTarget;r&&(r._cleared=!1)}},t.prototype.resetDrawCache=function(e){if(this.meshes)for(var t=0,i=this.meshes;t<i.length;t++)i[t].resetDrawCache(e)},t.prototype.render=function(e,t){var i,r,n;if(void 0===e&&(e=!0),void 0===t&&(t=!1),!this.isDisposed){this.onReadyObservable.hasObservers()&&null===this._executeWhenReadyTimeoutId&&this._checkIsReady(),this._frameId++,this._defaultFrameBufferCleared=!1,this._checkCameraRenderTarget(this.activeCamera),(null===(i=this.activeCameras)||void 0===i?void 0:i.length)&&this.activeCameras.forEach(this._checkCameraRenderTarget),this._registerTransientComponents(),this._activeParticles.fetchNewFrame(),this._totalVertices.fetchNewFrame(),this._activeIndices.fetchNewFrame(),this._activeBones.fetchNewFrame(),this._meshesForIntersections.reset(),this.resetCachedMaterial(),this.onBeforeAnimationsObservable.notifyObservers(this),this.actionManager&&this.actionManager.processTrigger(u.ACTION_OnEveryFrameTrigger),t||this.animate();for(var o=0,a=this._beforeCameraUpdateStage;o<a.length;o++)a[o].action();if(e)if(this.activeCameras&&this.activeCameras.length>0)for(var s=0;s<this.activeCameras.length;s++){var l=this.activeCameras[s];if(l.update(),l.cameraRigMode!==u.RIG_MODE_NONE)for(var c=0;c<l._rigCameras.length;c++)l._rigCameras[c].update()}else if(this.activeCamera&&(this.activeCamera.update(),this.activeCamera.cameraRigMode!==u.RIG_MODE_NONE))for(c=0;c<this.activeCamera._rigCameras.length;c++)this.activeCamera._rigCameras[c].update();this.onBeforeRenderObservable.notifyObservers(this);var h=this.getEngine();this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);var d=(null===(r=this.activeCameras)||void 0===r?void 0:r.length)?this.activeCameras[0]:this.activeCamera;if(this.renderTargetsEnabled){rr.StartPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!0;for(var p=0;p<this.customRenderTargets.length;p++){var f=this.customRenderTargets[p];if(f._shouldRender()){if(this._renderId++,this.activeCamera=f.activeCamera||this.activeCamera,!this.activeCamera)throw new Error("Active camera not set");h.setViewport(this.activeCamera.viewport),this.updateTransformMatrix(),f.render(d!==this.activeCamera,this.dumpNextRenderTargets)}}rr.EndPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=null!==(n=null==d?void 0:d.renderPassId)&&void 0!==n?n:u.RENDERPASS_MAIN,this.activeCamera=d,this._activeCamera&&this._activeCamera.cameraRigMode!==u.RIG_MODE_CUSTOM&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(var _=0,m=this._beforeClearStage;_<m.length;_++)m[_].action();this._clearFrameBuffer(this.activeCamera);for(var g=0,v=this._gatherRenderTargetsStage;g<v.length;g++)v[g].action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(s=0;s<this.activeCameras.length;s++)this._processSubCameras(this.activeCameras[s],s>0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}this._checkIntersections();for(var y=0,b=this._afterRenderStage;y<b.length;y++)b[y].action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(c=0;c<this._toBeDisposed.length;c++){var T=this._toBeDisposed[c];T&&T.dispose()}this._toBeDisposed.length=0}this.dumpNextRenderTargets&&(this.dumpNextRenderTargets=!1),this._activeBones.addCount(0,!0),this._activeIndices.addCount(0,!0),this._activeParticles.addCount(0,!0),this._engine.restoreDefaultFramebuffer()}},t.prototype.freezeMaterials=function(){for(var e=0;e<this.materials.length;e++)this.materials[e].freeze()},t.prototype.unfreezeMaterials=function(){for(var e=0;e<this.materials.length;e++)this.materials[e].unfreeze()},t.prototype.dispose=function(){if(!this.isDisposed){this.beforeRender=null,this.afterRender=null,this.metadata=null,this.skeletons.length=0,this.morphTargetManagers.length=0,this._transientComponents.length=0,this._isReadyForMeshStage.clear(),this._beforeEvaluateActiveMeshStage.clear(),this._evaluateSubMeshStage.clear(),this._preActiveMeshStage.clear(),this._cameraDrawRenderTargetStage.clear(),this._beforeCameraDrawStage.clear(),this._beforeRenderTargetDrawStage.clear(),this._beforeRenderingGroupDrawStage.clear(),this._beforeRenderingMeshStage.clear(),this._afterRenderingMeshStage.clear(),this._afterRenderingGroupDrawStage.clear(),this._afterCameraDrawStage.clear(),this._afterRenderTargetDrawStage.clear(),this._afterRenderStage.clear(),this._beforeCameraUpdateStage.clear(),this._beforeClearStage.clear(),this._gatherRenderTargetsStage.clear(),this._gatherActiveCameraRenderTargetsStage.clear(),this._pointerMoveStage.clear(),this._pointerDownStage.clear(),this._pointerUpStage.clear(),this.importedMeshesFiles=[],this.stopAllAnimations&&(this._activeAnimatables.forEach((function(e){e.onAnimationEndObservable.clear(),e.onAnimationEnd=null})),this.stopAllAnimations()),this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this.activeCameras=null,this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._materialsRenderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed.length=0;for(var e=0,t=this._activeRequests.slice();e<t.length;e++)t[e].abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(e){ae.Error("An error occurred while calling onDisposeObservable!",e)}if(this.detachControl(),this._engine.getInputElement())for(var i=0;i<this.cameras.length;i++)this.cameras[i].detachControl();this._disposeList(this.animationGroups),this._disposeList(this.lights),this._disposeList(this.meshes,(function(e){return e.dispose(!0)})),this._disposeList(this.transformNodes,(function(e){return e.dispose(!0)}));var r=this.cameras;this._disposeList(r),this._defaultMaterial&&this._defaultMaterial.dispose(),this._disposeList(this.multiMaterials),this._disposeList(this.materials),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);var n=this._engine.scenes.indexOf(this);n>-1&&this._engine.scenes.splice(n,1),M._LastCreatedScene===this&&(this._engine.scenes.length>0?M._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:M._LastCreatedScene=null),(n=this._engine._virtualScenes.indexOf(this))>-1&&this._engine._virtualScenes.splice(n,1),this._engine.wipeCaches(!0),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onAfterRenderCameraObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this._isDisposed=!0}},t.prototype._disposeList=function(e,t){t=null!=t?t:function(e){return e.dispose()};for(var i=0,r=e.slice(0);i<r.length;i++)t(r[i]);e.length=0},Object.defineProperty(t.prototype,"isDisposed",{get:function(){return this._isDisposed},enumerable:!1,configurable:!0}),t.prototype.clearCachedVertexData=function(){for(var e=0;e<this.meshes.length;e++){var t=this.meshes[e].geometry;t&&t.clearCachedData()}},t.prototype.cleanCachedTextureBuffer=function(){for(var e=0,t=this.textures;e<t.length;e++){var i=t[e];i._buffer&&(i._buffer=null)}},t.prototype.getWorldExtends=function(e){var t=new V(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),i=new V(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return e=e||function(){return!0},this.meshes.filter(e).forEach((function(e){if(e.computeWorldMatrix(!0),e.subMeshes&&0!==e.subMeshes.length&&!e.infiniteDistance){var r=e.getBoundingInfo(),n=r.boundingBox.minimumWorld,o=r.boundingBox.maximumWorld;V.CheckExtends(n,t,i),V.CheckExtends(o,t,i)}})),{min:t,max:i}},t.prototype.createPickingRay=function(e,t,i,r,n){throw void 0===n&&(n=!1),He("Ray")},t.prototype.createPickingRayToRef=function(e,t,i,r,n,o,a){throw void 0===o&&(o=!1),void 0===a&&(a=!1),He("Ray")},t.prototype.createPickingRayInCameraSpace=function(e,t,i){throw He("Ray")},t.prototype.createPickingRayInCameraSpaceToRef=function(e,t,i,r){throw He("Ray")},Object.defineProperty(t.prototype,"_pickingAvailable",{get:function(){return!1},enumerable:!1,configurable:!0}),t.prototype.pick=function(e,t,i,r,n,o){var a=He("Ray",!0);return a&&ae.Warn(a),new Fr},t.prototype.pickWithBoundingInfo=function(e,t,i,r,n){var o=He("Ray",!0);return o&&ae.Warn(o),new Fr},t.prototype.pickWithRay=function(e,t,i,r){throw He("Ray")},t.prototype.multiPick=function(e,t,i,r,n){throw He("Ray")},t.prototype.multiPickWithRay=function(e,t,i){throw He("Ray")},t.prototype.setPointerOverMesh=function(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)},t.prototype.getPointerOverMesh=function(){return this._inputManager.getPointerOverMesh()},t.prototype._rebuildGeometries=function(){for(var e=0,t=this.geometries;e<t.length;e++)t[e]._rebuild();for(var i=0,r=this.meshes;i<r.length;i++)r[i]._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(var n=0,o=this._components;n<o.length;n++)o[n].rebuild();for(var a=0,s=this.particleSystems;a<s.length;a++)s[a].rebuild();if(this.spriteManagers)for(var l=0,c=this.spriteManagers;l<c.length;l++)c[l].rebuild()},t.prototype._rebuildTextures=function(){for(var e=0,t=this.textures;e<t.length;e++)t[e]._rebuild(!0);this.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag)},t.prototype._getByTags=function(e,t,i){if(void 0===t)return e;var r=[];for(var n in e){var o=e[n];je&&je.MatchesQuery(o,t)&&(!i||i(o))&&r.push(o)}return r},t.prototype.getMeshesByTags=function(e,t){return this._getByTags(this.meshes,e,t)},t.prototype.getCamerasByTags=function(e,t){return this._getByTags(this.cameras,e,t)},t.prototype.getLightsByTags=function(e,t){return this._getByTags(this.lights,e,t)},t.prototype.getMaterialByTags=function(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))},t.prototype.getTransformNodesByTags=function(e,t){return this._getByTags(this.transformNodes,e,t)},t.prototype.setRenderingOrder=function(e,t,i,r){void 0===t&&(t=null),void 0===i&&(i=null),void 0===r&&(r=null),this._renderingManager.setRenderingOrder(e,t,i,r)},t.prototype.setRenderingAutoClearDepthStencil=function(e,t,i,r){void 0===i&&(i=!0),void 0===r&&(r=!0),this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,r)},t.prototype.getAutoClearDepthStencilSetup=function(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)},t.prototype._forceBlockMaterialDirtyMechanism=function(e){this._blockMaterialDirtyMechanism=e},Object.defineProperty(t.prototype,"blockMaterialDirtyMechanism",{get:function(){return this._blockMaterialDirtyMechanism},set:function(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(u.MATERIAL_AllDirtyFlag))},enumerable:!1,configurable:!0}),t.prototype.markAllMaterialsAsDirty=function(e,t){if(!this._blockMaterialDirtyMechanism)for(var i=0,r=this.materials;i<r.length;i++){var n=r[i];t&&!t(n)||n.markAsDirty(e)}},t.prototype._loadFile=function(e,t,i,r,n,o,a){var s=this,l=Vi(e,t,i,r?this.offlineProvider:void 0,n,o,a);return this._activeRequests.push(l),l.onCompleteObservable.add((function(e){s._activeRequests.splice(s._activeRequests.indexOf(e),1)})),l},t.prototype._loadFileAsync=function(e,t,i,r,n){var o=this;return new Promise((function(a,s){o._loadFile(e,(function(e){a(e)}),t,i,r,(function(e,t){s(t)}),n)}))},t.prototype._requestFile=function(e,t,i,r,n,o,a){var s=this,l=ki(e,t,i,r?this.offlineProvider:void 0,n,o,a);return this._activeRequests.push(l),l.onCompleteObservable.add((function(e){s._activeRequests.splice(s._activeRequests.indexOf(e),1)})),l},t.prototype._requestFileAsync=function(e,t,i,r,n){var o=this;return new Promise((function(a,s){o._requestFile(e,(function(e){a(e)}),t,i,r,(function(e){s(e)}),n)}))},t.prototype._readFile=function(e,t,i,r,n){var o=this,a=Ui(e,t,i,r,n);return this._activeRequests.push(a),a.onCompleteObservable.add((function(e){o._activeRequests.splice(o._activeRequests.indexOf(e),1)})),a},t.prototype._readFileAsync=function(e,t,i){var r=this;return new Promise((function(n,o){r._readFile(e,(function(e){n(e)}),t,i,(function(e){o(e)}))}))},t.prototype.getPerfCollector=function(){throw He("performanceViewerSceneExtension")},t.prototype.setActiveCameraByID=function(e){return this.setActiveCameraById(e)},t.prototype.getMaterialByID=function(e){return this.getMaterialById(e)},t.prototype.getLastMaterialByID=function(e){return this.getLastMaterialById(e)},t.prototype.getTextureByUniqueID=function(e){return this.getTextureByUniqueId(e)},t.prototype.getCameraByID=function(e){return this.getCameraById(e)},t.prototype.getCameraByUniqueID=function(e){return this.getCameraByUniqueId(e)},t.prototype.getBoneByID=function(e){return this.getBoneById(e)},t.prototype.getLightByID=function(e){return this.getLightById(e)},t.prototype.getLightByUniqueID=function(e){return this.getLightByUniqueId(e)},t.prototype.getParticleSystemByID=function(e){return this.getParticleSystemById(e)},t.prototype.getGeometryByID=function(e){return this.getGeometryById(e)},t.prototype.getMeshByID=function(e){return this.getMeshById(e)},t.prototype.getMeshByUniqueID=function(e){return this.getMeshByUniqueId(e)},t.prototype.getLastMeshByID=function(e){return this.getLastMeshById(e)},t.prototype.getMeshesByID=function(e){return this.getMeshesById(e)},t.prototype.getTransformNodeByID=function(e){return this.getTransformNodeById(e)},t.prototype.getTransformNodeByUniqueID=function(e){return this.getTransformNodeByUniqueId(e)},t.prototype.getTransformNodesByID=function(e){return this.getTransformNodesById(e)},t.prototype.getNodeByID=function(e){return this.getNodeById(e)},t.prototype.getLastEntryByID=function(e){return this.getLastEntryById(e)},t.prototype.getLastSkeletonByID=function(e){return this.getLastSkeletonById(e)},t.FOGMODE_NONE=u.FOGMODE_NONE,t.FOGMODE_EXP=u.FOGMODE_EXP,t.FOGMODE_EXP2=u.FOGMODE_EXP2,t.FOGMODE_LINEAR=u.FOGMODE_LINEAR,t.MinDeltaTime=1,t.MaxDeltaTime=1e3,t}(c);a("BABYLON.Scene",pn),function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"}(dn||(dn={}));var fn,_n=function(){function e(){}return e.X=new V(1,0,0),e.Y=new V(0,1,0),e.Z=new V(0,0,1),e}();!function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(fn||(fn={}));var mn=function(e){function t(t,i,r,n,o,a,s){void 0===r&&(r=null),void 0===n&&(n=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null);var l,c=this;return(c=e.call(this,t,i.getScene(),!1)||this).name=t,c.children=[],c.animations=[],c._index=null,c._scalingDeterminant=1,c._needToDecompose=!0,c._needToCompose=!1,c._linkedTransformNode=null,c._waitingTransformNodeId=null,c._skeleton=i,c._localMatrix=null!==(l=null==n?void 0:n.clone())&&void 0!==l?l:z.Identity(),c._restMatrix=null!=o?o:c._localMatrix.clone(),c._bindMatrix=null!=a?a:c._localMatrix.clone(),c._index=s,c._absoluteMatrix=new z,c._absoluteBindMatrix=new z,c._absoluteInverseBindMatrix=new z,c._finalMatrix=new z,i.bones.push(c),c.setParent(r,!1),c._updateAbsoluteBindMatrices(),c}return m(t,e),Object.defineProperty(t.prototype,"_matrix",{get:function(){return this._compose(),this._localMatrix},set:function(e){(e.updateFlag!==this._localMatrix.updateFlag||this._needToCompose)&&(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"Bone"},t.prototype.getSkeleton=function(){return this._skeleton},Object.defineProperty(t.prototype,"parent",{get:function(){return this._parentNode},set:function(e){this.setParent(e)},enumerable:!1,configurable:!0}),t.prototype.getParent=function(){return this.parent},t.prototype.getChildren=function(){return this.children},t.prototype.getIndex=function(){return null===this._index?this.getSkeleton().bones.indexOf(this):this._index},t.prototype.setParent=function(e,t){if(void 0===t&&(t=!0),this.parent!==e){if(this.parent){var i=this.parent.children.indexOf(this);-1!==i&&this.parent.children.splice(i,1)}this._parentNode=e,this.parent&&this.parent.children.push(this),t&&this._updateAbsoluteBindMatrices(),this.markAsDirty()}},t.prototype.getLocalMatrix=function(){return this._compose(),this._localMatrix},t.prototype.getBindMatrix=function(){return this._bindMatrix},t.prototype.getBaseMatrix=function(){return this.getBindMatrix()},t.prototype.getRestMatrix=function(){return this._restMatrix},t.prototype.getRestPose=function(){return this.getRestMatrix()},t.prototype.setRestMatrix=function(e){this._restMatrix.copyFrom(e)},t.prototype.setRestPose=function(e){this.setRestMatrix(e)},t.prototype.getBindPose=function(){return this.getBindMatrix()},t.prototype.setBindMatrix=function(e){this.updateMatrix(e)},t.prototype.setBindPose=function(e){this.setBindMatrix(e)},t.prototype.getFinalMatrix=function(){return this._finalMatrix},t.prototype.getWorldMatrix=function(){return this.getFinalMatrix()},t.prototype.returnToRest=function(){var e;if(this._linkedTransformNode){var t=H.Vector3[0],i=H.Quaternion[0],r=H.Vector3[1];this.getRestMatrix().decompose(t,i,r),this._linkedTransformNode.position.copyFrom(r),this._linkedTransformNode.rotationQuaternion=null!==(e=this._linkedTransformNode.rotationQuaternion)&&void 0!==e?e:G.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(i),this._linkedTransformNode.scaling.copyFrom(t)}else this._matrix=this._restMatrix},t.prototype.getAbsoluteInverseBindMatrix=function(){return this._absoluteInverseBindMatrix},t.prototype.getInvertedAbsoluteTransform=function(){return this.getAbsoluteInverseBindMatrix()},t.prototype.getAbsoluteMatrix=function(){return this._absoluteMatrix},t.prototype.getAbsoluteTransform=function(){return this._absoluteMatrix},t.prototype.linkTransformNode=function(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++},t.prototype.getTransformNode=function(){return this._linkedTransformNode},Object.defineProperty(t.prototype,"position",{get:function(){return this._decompose(),this._localPosition},set:function(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rotation",{get:function(){return this.getRotation()},set:function(e){this.setRotation(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rotationQuaternion",{get:function(){return this._decompose(),this._localRotation},set:function(e){this.setRotationQuaternion(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scaling",{get:function(){return this.getScale()},set:function(e){this.setScale(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"animationPropertiesOverride",{get:function(){return this._skeleton.animationPropertiesOverride},enumerable:!1,configurable:!0}),t.prototype._decompose=function(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=V.Zero(),this._localRotation=G.Zero(),this._localPosition=V.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))},t.prototype._compose=function(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,z.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)):this._needToCompose=!1)},t.prototype.updateMatrix=function(e,t,i){void 0===t&&(t=!0),void 0===i&&(i=!0),this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?this._matrix=e:this.markAsDirty()},t.prototype._updateAbsoluteBindMatrices=function(e,t){if(void 0===t&&(t=!0),e||(e=this._bindMatrix),this.parent?e.multiplyToRef(this.parent._absoluteBindMatrix,this._absoluteBindMatrix):this._absoluteBindMatrix.copyFrom(e),this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix),t)for(var i=0;i<this.children.length;i++)this.children[i]._updateAbsoluteBindMatrices();this._scalingDeterminant=this._absoluteBindMatrix.determinant()<0?-1:1},t.prototype.markAsDirty=function(){return this._currentRenderId++,this._childUpdateId++,this._skeleton._markAsDirty(),this},t.prototype._markAsDirtyAndCompose=function(){this.markAsDirty(),this._needToCompose=!0},t.prototype._markAsDirtyAndDecompose=function(){this.markAsDirty(),this._needToDecompose=!0},t.prototype._updatePosition=function(e,i,r,n){void 0===i&&(i=dn.LOCAL),void 0===n&&(n=!0);var o=this.getLocalMatrix();if(i==dn.LOCAL)n?(o.addAtIndex(12,e.x),o.addAtIndex(13,e.y),o.addAtIndex(14,e.z)):o.setTranslationFromFloats(e.x,e.y,e.z);else{var a=null;r&&(a=r.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();var s=t._TmpMats[0],l=t._TmpVecs[0];this.parent?r&&a?(s.copyFrom(this.parent.getAbsoluteMatrix()),s.multiplyToRef(a,s)):s.copyFrom(this.parent.getAbsoluteMatrix()):z.IdentityToRef(s),n&&s.setTranslationFromFloats(0,0,0),s.invert(),V.TransformCoordinatesToRef(e,s,l),n?(o.addAtIndex(12,l.x),o.addAtIndex(13,l.y),o.addAtIndex(14,l.z)):o.setTranslationFromFloats(l.x,l.y,l.z)}this._markAsDirtyAndDecompose()},t.prototype.translate=function(e,t,i){void 0===t&&(t=dn.LOCAL),this._updatePosition(e,t,i,!0)},t.prototype.setPosition=function(e,t,i){void 0===t&&(t=dn.LOCAL),this._updatePosition(e,t,i,!1)},t.prototype.setAbsolutePosition=function(e,t){this.setPosition(e,dn.WORLD,t)},t.prototype.scale=function(e,i,r,n){void 0===n&&(n=!1);var o=this.getLocalMatrix(),a=t._TmpMats[0];z.ScalingToRef(e,i,r,a),a.multiplyToRef(o,o),a.invert();for(var s=0,l=this.children;s<l.length;s++){var c=(d=l[s]).getLocalMatrix();c.multiplyToRef(a,c),c.multiplyAtIndex(12,e),c.multiplyAtIndex(13,i),c.multiplyAtIndex(14,r),d._markAsDirtyAndDecompose()}if(this._markAsDirtyAndDecompose(),n)for(var u=0,h=this.children;u<h.length;u++){var d;(d=h[u]).scale(e,i,r,n)}},t.prototype.setScale=function(e){this._decompose(),this._localScaling.copyFrom(e),this._markAsDirtyAndCompose()},t.prototype.getScale=function(){return this._decompose(),this._localScaling},t.prototype.getScaleToRef=function(e){this._decompose(),e.copyFrom(this._localScaling)},t.prototype.setYawPitchRoll=function(e,i,r,n,o){if(void 0===n&&(n=dn.LOCAL),n===dn.LOCAL){var a=t._TmpQuat;return G.RotationYawPitchRollToRef(e,i,r,a),void this.setRotationQuaternion(a,n,o)}var s=t._TmpMats[0];if(this._getAbsoluteInverseMatrixUnscaledToRef(s,o)){var l=t._TmpMats[1];z.RotationYawPitchRollToRef(e,i,r,l),s.multiplyToRef(l,l),this._rotateWithMatrix(l,n,o)}},t.prototype.rotate=function(e,i,r,n){void 0===r&&(r=dn.LOCAL);var o=t._TmpMats[0];o.setTranslationFromFloats(0,0,0),z.RotationAxisToRef(e,i,o),this._rotateWithMatrix(o,r,n)},t.prototype.setAxisAngle=function(e,i,r,n){if(void 0===r&&(r=dn.LOCAL),r===dn.LOCAL){var o=t._TmpQuat;return G.RotationAxisToRef(e,i,o),void this.setRotationQuaternion(o,r,n)}var a=t._TmpMats[0];if(this._getAbsoluteInverseMatrixUnscaledToRef(a,n)){var s=t._TmpMats[1];z.RotationAxisToRef(e,i,s),a.multiplyToRef(s,s),this._rotateWithMatrix(s,r,n)}},t.prototype.setRotation=function(e,t,i){void 0===t&&(t=dn.LOCAL),this.setYawPitchRoll(e.y,e.x,e.z,t,i)},t.prototype.setRotationQuaternion=function(e,i,r){if(void 0===i&&(i=dn.LOCAL),i===dn.LOCAL)return this._decompose(),this._localRotation.copyFrom(e),void this._markAsDirtyAndCompose();var n=t._TmpMats[0];if(this._getAbsoluteInverseMatrixUnscaledToRef(n,r)){var o=t._TmpMats[1];z.FromQuaternionToRef(e,o),n.multiplyToRef(o,o),this._rotateWithMatrix(o,i,r)}},t.prototype.setRotationMatrix=function(e,i,r){if(void 0===i&&(i=dn.LOCAL),i===dn.LOCAL){var n=t._TmpQuat;return G.FromRotationMatrixToRef(e,n),void this.setRotationQuaternion(n,i,r)}var o=t._TmpMats[0];if(this._getAbsoluteInverseMatrixUnscaledToRef(o,r)){var a=t._TmpMats[1];a.copyFrom(e),o.multiplyToRef(e,a),this._rotateWithMatrix(a,i,r)}},t.prototype._rotateWithMatrix=function(e,i,r){void 0===i&&(i=dn.LOCAL);var n=this.getLocalMatrix(),o=n.m[12],a=n.m[13],s=n.m[14],l=this.getParent(),c=t._TmpMats[3],u=t._TmpMats[4];l&&i==dn.WORLD?(r?(c.copyFrom(r.getWorldMatrix()),l.getAbsoluteMatrix().multiplyToRef(c,c)):c.copyFrom(l.getAbsoluteMatrix()),u.copyFrom(c),u.invert(),n.multiplyToRef(c,n),n.multiplyToRef(e,n),n.multiplyToRef(u,n)):i==dn.WORLD&&r?(c.copyFrom(r.getWorldMatrix()),u.copyFrom(c),u.invert(),n.multiplyToRef(c,n),n.multiplyToRef(e,n),n.multiplyToRef(u,n)):n.multiplyToRef(e,n),n.setTranslationFromFloats(o,a,s),this.computeAbsoluteMatrices(),this._markAsDirtyAndDecompose()},t.prototype._getAbsoluteInverseMatrixUnscaledToRef=function(e,i){var r=t._TmpMats[2];return e.copyFrom(this.getAbsoluteMatrix()),i?(e.multiplyToRef(i.getWorldMatrix(),e),z.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,r)):z.IdentityToRef(r),e.invert(),!isNaN(e.m[0])&&(r.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyToRef(r,e),!0)},t.prototype.getPosition=function(e,t){void 0===e&&(e=dn.LOCAL),void 0===t&&(t=null);var i=V.Zero();return this.getPositionToRef(e,t,i),i},t.prototype.getPositionToRef=function(e,i,r){if(void 0===e&&(e=dn.LOCAL),e==dn.LOCAL){var n=this.getLocalMatrix();r.x=n.m[12],r.y=n.m[13],r.z=n.m[14]}else{var o=null;i&&(o=i.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();var a=t._TmpMats[0];i&&o?(a.copyFrom(this.getAbsoluteMatrix()),a.multiplyToRef(o,a)):a=this.getAbsoluteMatrix(),r.x=a.m[12],r.y=a.m[13],r.z=a.m[14]}},t.prototype.getAbsolutePosition=function(e){void 0===e&&(e=null);var t=V.Zero();return this.getPositionToRef(dn.WORLD,e,t),t},t.prototype.getAbsolutePositionToRef=function(e,t){this.getPositionToRef(dn.WORLD,e,t)},t.prototype.computeAbsoluteMatrices=function(){if(this._compose(),this.parent)this._localMatrix.multiplyToRef(this.parent._absoluteMatrix,this._absoluteMatrix);else{this._absoluteMatrix.copyFrom(this._localMatrix);var e=this._skeleton.getPoseMatrix();e&&this._absoluteMatrix.multiplyToRef(e,this._absoluteMatrix)}for(var t=this.children,i=t.length,r=0;r<i;r++)t[r].computeAbsoluteMatrices()},t.prototype.computeAbsoluteTransforms=function(){this.computeAbsoluteMatrices()},t.prototype.getDirection=function(e,t){void 0===t&&(t=null);var i=V.Zero();return this.getDirectionToRef(e,t,i),i},t.prototype.getDirectionToRef=function(e,i,r){void 0===i&&(i=null);var n=null;i&&(n=i.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();var o=t._TmpMats[0];o.copyFrom(this.getAbsoluteMatrix()),i&&n&&o.multiplyToRef(n,o),V.TransformNormalToRef(e,o,r),r.normalize()},t.prototype.getRotation=function(e,t){void 0===e&&(e=dn.LOCAL),void 0===t&&(t=null);var i=V.Zero();return this.getRotationToRef(e,t,i),i},t.prototype.getRotationToRef=function(e,i,r){void 0===e&&(e=dn.LOCAL),void 0===i&&(i=null);var n=t._TmpQuat;this.getRotationQuaternionToRef(e,i,n),n.toEulerAnglesToRef(r)},t.prototype.getRotationQuaternion=function(e,t){void 0===e&&(e=dn.LOCAL),void 0===t&&(t=null);var i=G.Identity();return this.getRotationQuaternionToRef(e,t,i),i},t.prototype.getRotationQuaternionToRef=function(e,i,r){if(void 0===e&&(e=dn.LOCAL),void 0===i&&(i=null),e==dn.LOCAL)this._decompose(),r.copyFrom(this._localRotation);else{var n=t._TmpMats[0],o=this.getAbsoluteMatrix();i?o.multiplyToRef(i.getWorldMatrix(),n):n.copyFrom(o),n.multiplyAtIndex(0,this._scalingDeterminant),n.multiplyAtIndex(1,this._scalingDeterminant),n.multiplyAtIndex(2,this._scalingDeterminant),n.decompose(void 0,r,void 0)}},t.prototype.getRotationMatrix=function(e,t){void 0===e&&(e=dn.LOCAL);var i=z.Identity();return this.getRotationMatrixToRef(e,t,i),i},t.prototype.getRotationMatrixToRef=function(e,i,r){if(void 0===e&&(e=dn.LOCAL),e==dn.LOCAL)this.getLocalMatrix().getRotationMatrixToRef(r);else{var n=t._TmpMats[0],o=this.getAbsoluteMatrix();i?o.multiplyToRef(i.getWorldMatrix(),n):n.copyFrom(o),n.multiplyAtIndex(0,this._scalingDeterminant),n.multiplyAtIndex(1,this._scalingDeterminant),n.multiplyAtIndex(2,this._scalingDeterminant),n.getRotationMatrixToRef(r)}},t.prototype.getAbsolutePositionFromLocal=function(e,t){void 0===t&&(t=null);var i=V.Zero();return this.getAbsolutePositionFromLocalToRef(e,t,i),i},t.prototype.getAbsolutePositionFromLocalToRef=function(e,i,r){void 0===i&&(i=null);var n=null;i&&(n=i.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();var o=t._TmpMats[0];o.copyFrom(this.getAbsoluteMatrix()),i&&n&&o.multiplyToRef(n,o),V.TransformCoordinatesToRef(e,o,r)},t.prototype.getLocalPositionFromAbsolute=function(e,t){void 0===t&&(t=null);var i=V.Zero();return this.getLocalPositionFromAbsoluteToRef(e,t,i),i},t.prototype.getLocalPositionFromAbsoluteToRef=function(e,i,r){void 0===i&&(i=null);var n=null;i&&(n=i.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();var o=t._TmpMats[0];o.copyFrom(this.getAbsoluteMatrix()),i&&n&&o.multiplyToRef(n,o),o.invert(),V.TransformCoordinatesToRef(e,o,r)},t.prototype.setCurrentPoseAsRest=function(){this.setRestMatrix(this.getLocalMatrix())},t._TmpVecs=C.BuildArray(2,V.Zero),t._TmpQuat=G.Identity(),t._TmpMats=C.BuildArray(5,z.Identity),t}(qe),gn=function(){function e(e,t,i,r,n,o,a,s,l,c,u){void 0===i&&(i=0),void 0===r&&(r=100),void 0===n&&(n=!1),void 0===o&&(o=1),void 0===c&&(c=!1),void 0===u&&(u=0),this.target=t,this.fromFrame=i,this.toFrame=r,this.loopAnimation=n,this.onAnimationEnd=a,this.onAnimationLoop=l,this.isAdditive=c,this.playOrder=u,this._localDelayOffset=null,this._pausedDelay=null,this._manualJumpDelay=null,this._runtimeAnimations=new Array,this._paused=!1,this._speedRatio=1,this._weight=-1,this._syncRoot=null,this._frameToSyncFromJump=null,this._goToFrame=null,this.disposeOnEnd=!0,this.animationStarted=!1,this.onAnimationEndObservable=new f,this.onAnimationLoopObservable=new f,this._scene=e,s&&this.appendAnimations(t,s),this._speedRatio=o,e._activeAnimatables.push(this)}return Object.defineProperty(e.prototype,"syncRoot",{get:function(){return this._syncRoot},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"masterFrame",{get:function(){return 0===this._runtimeAnimations.length?0:this._runtimeAnimations[0].currentFrame},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"weight",{get:function(){return this._weight},set:function(e){this._weight=-1!==e?Math.min(Math.max(e,0),1):-1},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"speedRatio",{get:function(){return this._speedRatio},set:function(e){for(var t=0;t<this._runtimeAnimations.length;t++)this._runtimeAnimations[t]._prepareForSpeedRatioChange(e);this._speedRatio=e,null!==this._goToFrame&&this.goToFrame(this._goToFrame)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"elapsedTime",{get:function(){return null===this._localDelayOffset?0:this._scene._animationTime-this._localDelayOffset},enumerable:!1,configurable:!0}),e.prototype.syncWith=function(e){if(this._syncRoot=e,e){var t=this._scene._activeAnimatables.indexOf(this);t>-1&&(this._scene._activeAnimatables.splice(t,1),this._scene._activeAnimatables.push(this))}return this},e.prototype.getAnimations=function(){return this._runtimeAnimations},e.prototype.appendAnimations=function(e,t){for(var i=this,r=0;r<t.length;r++){var n=t[r],o=new lt(e,n,this._scene,this);o._onLoop=function(){i.onAnimationLoopObservable.notifyObservers(i),i.onAnimationLoop&&i.onAnimationLoop()},this._runtimeAnimations.push(o)}},e.prototype.getAnimationByTargetProperty=function(e){for(var t=this._runtimeAnimations,i=0;i<t.length;i++)if(t[i].animation.targetProperty===e)return t[i].animation;return null},e.prototype.getRuntimeAnimationByTargetProperty=function(e){for(var t=this._runtimeAnimations,i=0;i<t.length;i++)if(t[i].animation.targetProperty===e)return t[i];return null},e.prototype.reset=function(){for(var e=this._runtimeAnimations,t=0;t<e.length;t++)e[t].reset(!0);this._localDelayOffset=null,this._pausedDelay=null},e.prototype.enableBlending=function(e){for(var t=this._runtimeAnimations,i=0;i<t.length;i++)t[i].animation.enableBlending=!0,t[i].animation.blendingSpeed=e},e.prototype.disableBlending=function(){for(var e=this._runtimeAnimations,t=0;t<e.length;t++)e[t].animation.enableBlending=!1},e.prototype.goToFrame=function(e){var t,i=this._runtimeAnimations;if(i[0]){var r=i[0].animation.framePerSecond;this._frameToSyncFromJump=null!==(t=this._frameToSyncFromJump)&&void 0!==t?t:i[0].currentFrame;var n=0===this.speedRatio?0:(e-this._frameToSyncFromJump)/r*1e3/this.speedRatio;this._manualJumpDelay=-n}for(var o=0;o<i.length;o++)i[o].goToFrame(e);this._goToFrame=e},Object.defineProperty(e.prototype,"paused",{get:function(){return this._paused},enumerable:!1,configurable:!0}),e.prototype.pause=function(){this._paused||(this._paused=!0)},e.prototype.restart=function(){this._paused=!1},e.prototype._raiseOnAnimationEnd=function(){this.onAnimationEnd&&this.onAnimationEnd(),this.onAnimationEndObservable.notifyObservers(this)},e.prototype.stop=function(e,t,i){if(void 0===i&&(i=!1),e||t){var r=this._scene._activeAnimatables.indexOf(this);if(r>-1){for(var n=(a=this._runtimeAnimations).length-1;n>=0;n--){var o=a[n];e&&o.animation.name!=e||t&&!t(o.target)||(o.dispose(),a.splice(n,1))}0==a.length&&(i||this._scene._activeAnimatables.splice(r,1),this._raiseOnAnimationEnd())}}else if((n=this._scene._activeAnimatables.indexOf(this))>-1){i||this._scene._activeAnimatables.splice(n,1);for(var a=this._runtimeAnimations,s=0;s<a.length;s++)a[s].dispose();this._runtimeAnimations.length=0,this._raiseOnAnimationEnd()}},e.prototype.waitAsync=function(){var e=this;return new Promise((function(t){e.onAnimationEndObservable.add((function(){t(e)}),void 0,void 0,e,!0)}))},e.prototype._animate=function(e){if(this._paused)return this.animationStarted=!1,null===this._pausedDelay&&(this._pausedDelay=e),!0;if(null===this._localDelayOffset?(this._localDelayOffset=e,this._pausedDelay=null):null!==this._pausedDelay&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),null!==this._manualJumpDelay&&(this._localDelayOffset+=this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._goToFrame=null,0===this._weight)return!0;var t,i=!1,r=this._runtimeAnimations;for(t=0;t<r.length;t++){var n=r[t].animate(e-this._localDelayOffset,this.fromFrame,this.toFrame,this.loopAnimation,this._speedRatio,this._weight);i=i||n}if(this.animationStarted=i,!i){if(this.disposeOnEnd)for(t=this._scene._activeAnimatables.indexOf(this),this._scene._activeAnimatables.splice(t,1),t=0;t<r.length;t++)r[t].dispose();this._raiseOnAnimationEnd(),this.disposeOnEnd&&(this.onAnimationEnd=null,this.onAnimationLoop=null,this.onAnimationLoopObservable.clear(),this.onAnimationEndObservable.clear())}return i},e}();pn.prototype._animate=function(e){if(this.animationsEnabled){var t=_t.Now;if(!this._animationTimeLast){if(this._pendingData.length>0)return;this._animationTimeLast=t}this.deltaTime=void 0!==e?e:this.useConstantAnimationDeltaTime?16:(t-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=t;var i=this._activeAnimatables;if(0!==i.length){this._animationTime+=this.deltaTime;for(var r=this._animationTime,n=0;n<i.length;n++){var o=i[n];!o._animate(r)&&o.disposeOnEnd&&n--}this._processLateAnimationBindings()}}},pn.prototype.sortActiveAnimatables=function(){this._activeAnimatables.sort((function(e,t){return e.playOrder-t.playOrder}))},pn.prototype.beginWeightedAnimation=function(e,t,i,r,n,o,a,s,l,c,u){void 0===r&&(r=1),void 0===o&&(o=1),void 0===u&&(u=!1);var h=this.beginAnimation(e,t,i,n,o,a,s,!1,l,c,u);return h.weight=r,h},pn.prototype.beginAnimation=function(e,t,i,r,n,o,a,s,l,c,u){void 0===n&&(n=1),void 0===s&&(s=!0),void 0===u&&(u=!1),t>i&&n>0&&(n*=-1),s&&this.stopAnimation(e,void 0,l),a||(a=new gn(this,e,t,i,r,n,o,void 0,c,u));var h=!l||l(e);if(e.animations&&h&&a.appendAnimations(e,e.animations),e.getAnimatables)for(var d=e.getAnimatables(),p=0;p<d.length;p++)this.beginAnimation(d[p],t,i,r,n,o,a,s,l,c);return a.reset(),a},pn.prototype.beginHierarchyAnimation=function(e,t,i,r,n,o,a,s,l,c,u,h){void 0===o&&(o=1),void 0===l&&(l=!0),void 0===h&&(h=!1);var d=e.getDescendants(t),p=[];p.push(this.beginAnimation(e,i,r,n,o,a,s,l,c,void 0,h));for(var f=0,_=d;f<_.length;f++){var m=_[f];p.push(this.beginAnimation(m,i,r,n,o,a,s,l,c,void 0,h))}return p},pn.prototype.beginDirectAnimation=function(e,t,i,r,n,o,a,s,l){if(void 0===l&&(l=!1),void 0===o&&(o=1),i>r&&o>0)o*=-1;else if(r>i&&o<0){var c=r;r=i,i=c}return new gn(this,e,i,r,n,o,a,t,s,l)},pn.prototype.beginDirectHierarchyAnimation=function(e,t,i,r,n,o,a,s,l,c){void 0===c&&(c=!1);var u=e.getDescendants(t),h=[];h.push(this.beginDirectAnimation(e,i,r,n,o,a,s,l,c));for(var d=0,p=u;d<p.length;d++){var f=p[d];h.push(this.beginDirectAnimation(f,i,r,n,o,a,s,l,c))}return h},pn.prototype.getAnimatableByTarget=function(e){for(var t=0;t<this._activeAnimatables.length;t++)if(this._activeAnimatables[t].target===e)return this._activeAnimatables[t];return null},pn.prototype.getAllAnimatablesByTarget=function(e){for(var t=[],i=0;i<this._activeAnimatables.length;i++)this._activeAnimatables[i].target===e&&t.push(this._activeAnimatables[i]);return t},pn.prototype.stopAnimation=function(e,t,i){for(var r=0,n=this.getAllAnimatablesByTarget(e);r<n.length;r++)n[r].stop(t,i)},pn.prototype.stopAllAnimations=function(){if(this._activeAnimatables){for(var e=0;e<this._activeAnimatables.length;e++)this._activeAnimatables[e].stop(void 0,void 0,!0);this._activeAnimatables.length=0}for(var t=0,i=this.animationGroups;t<i.length;t++)i[t].stop()},pn.prototype._registerTargetForLateAnimationBinding=function(e,t){var i=e.target;this._registeredForLateAnimationBindings.pushNoDuplicate(i),i._lateAnimationHolders||(i._lateAnimationHolders={}),i._lateAnimationHolders[e.targetPath]||(i._lateAnimationHolders[e.targetPath]={totalWeight:0,totalAdditiveWeight:0,animations:[],additiveAnimations:[],originalValue:t}),e.isAdditive?(i._lateAnimationHolders[e.targetPath].additiveAnimations.push(e),i._lateAnimationHolders[e.targetPath].totalAdditiveWeight+=e.weight):(i._lateAnimationHolders[e.targetPath].animations.push(e),i._lateAnimationHolders[e.targetPath].totalWeight+=e.weight)},pn.prototype._processLateAnimationBindingsForMatrices=function(e){if(0===e.totalWeight&&0===e.totalAdditiveWeight)return e.originalValue;var t=1,i=H.Vector3[0],r=H.Vector3[1],n=H.Quaternion[0],o=0,a=e.animations[0],s=e.originalValue,l=1,c=!1;if(e.totalWeight<1)l=1-e.totalWeight,s.decompose(r,n,i);else{if(o=1,t=e.totalWeight,1==(l=a.weight/t)){if(!e.totalAdditiveWeight)return a.currentValue;c=!0}a.currentValue.decompose(r,n,i)}if(!c){r.scaleInPlace(l),i.scaleInPlace(l),n.scaleInPlace(l);for(var u=o;u<e.animations.length;u++)if(0!==(f=e.animations[u]).weight){l=f.weight/t;var h=H.Vector3[2],d=H.Vector3[3],p=H.Quaternion[1];f.currentValue.decompose(d,p,h),d.scaleAndAddToRef(l,r),p.scaleAndAddToRef(G.Dot(n,p)>0?l:-l,n),h.scaleAndAddToRef(l,i)}n.normalize()}for(u=0;u<e.additiveAnimations.length;u++){var f;0!==(f=e.additiveAnimations[u]).weight&&(h=H.Vector3[2],d=H.Vector3[3],p=H.Quaternion[1],f.currentValue.decompose(d,p,h),d.multiplyToRef(r,d),V.LerpToRef(r,d,f.weight,r),n.multiplyToRef(p,p),G.SlerpToRef(n,p,f.weight,n),h.scaleAndAddToRef(f.weight,i))}var _=a?a._animationState.workValue:H.Matrix[0].clone();return z.ComposeToRef(r,n,i,_),_},pn.prototype._processLateAnimationBindingsForQuaternions=function(e,t){if(0===e.totalWeight&&0===e.totalAdditiveWeight)return t;var i=e.animations[0],r=e.originalValue,n=t;if(0===e.totalWeight&&e.totalAdditiveWeight>0)n.copyFrom(r);else if(1===e.animations.length){if(G.SlerpToRef(r,i.currentValue,Math.min(1,e.totalWeight),n),0===e.totalAdditiveWeight)return n}else if(e.animations.length>1){var o=1,a=void 0,s=void 0;if(e.totalWeight<1){var l=1-e.totalWeight;s=[],(a=[]).push(r),s.push(l)}else{if(2===e.animations.length&&(G.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;a=[],s=[],o=e.totalWeight}for(var c=0;c<e.animations.length;c++){var u=e.animations[c];a.push(u.currentValue),s.push(u.weight/o)}for(var h=0,d=0;d<a.length;)d?(h+=s[d],G.SlerpToRef(n,a[d],s[d]/h,n),d++):(G.SlerpToRef(a[d],a[d+1],s[d+1]/(s[d]+s[d+1]),t),n=t,h=s[d]+s[d+1],d+=2)}for(c=0;c<e.additiveAnimations.length;c++)0!==(u=e.additiveAnimations[c]).weight&&(n.multiplyToRef(u.currentValue,H.Quaternion[0]),G.SlerpToRef(n,H.Quaternion[0],u.weight,n));return n},pn.prototype._processLateAnimationBindings=function(){if(this._registeredForLateAnimationBindings.length){for(var e=0;e<this._registeredForLateAnimationBindings.length;e++){var t=this._registeredForLateAnimationBindings.data[e];for(var i in t._lateAnimationHolders){var r=t._lateAnimationHolders[i],n=r.animations[0],o=r.originalValue;if(null!=o){var a=at.AllowMatrixDecomposeForInterpolation&&o.m,s=t[i];if(a)s=this._processLateAnimationBindingsForMatrices(r);else if(void 0!==o.w)s=this._processLateAnimationBindingsForQuaternions(r,s||G.Identity());else{var l=0,c=1,u=n&&n._animationState.loopMode===at.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT;r.totalWeight<1?s=u?o.clone?o.clone():o:n&&o.scale?o.scale(1-r.totalWeight):n?o*(1-r.totalWeight):o.clone?o.clone():o:n&&(c=r.totalWeight,s=1!=(p=n.weight/c)?n.currentValue.scale?n.currentValue.scale(p):n.currentValue*p:n.currentValue,u&&(s.addToRef?s.addToRef(o,s):s+=o),l=1);for(var h=l;h<r.animations.length;h++)(p=(d=r.animations[h]).weight/c)&&(d.currentValue.scaleAndAddToRef?d.currentValue.scaleAndAddToRef(p,s):s+=d.currentValue*p);for(h=0;h<r.additiveAnimations.length;h++){var d,p;(p=(d=r.additiveAnimations[h]).weight)&&(d.currentValue.scaleAndAddToRef?d.currentValue.scaleAndAddToRef(p,s):s+=d.currentValue*p)}}t[i]=s}}t._lateAnimationHolders={}}this._registeredForLateAnimationBindings.reset()}},mn.prototype.copyAnimationRange=function(e,t,i,r,n){void 0===r&&(r=!1),void 0===n&&(n=null),0===this.animations.length&&(this.animations.push(new at(this.name,"_matrix",e.animations[0].framePerSecond,at.ANIMATIONTYPE_MATRIX,0)),this.animations[0].setKeys([]));var o=e.animations[0].getRange(t);if(!o)return!1;for(var a,s,l,c=o.from,u=o.to,h=e.animations[0].getKeys(),d=e.length,p=e.getParent(),f=this.getParent(),_=r&&p&&d&&this.length&&d!==this.length,m=_&&f&&p?f.length/p.length:1,g=r&&!f&&n&&(1!==n.x||1!==n.y||1!==n.z),v=this.animations[0].getKeys(),y=0,b=h.length;y<b;y++)(a=h[y]).frame>=c&&a.frame<=u&&(r?(l=a.value.clone(),_?(s=l.getTranslation(),l.setTranslation(s.scaleInPlace(m))):g&&n?(s=l.getTranslation(),l.setTranslation(s.multiplyInPlace(n))):l=a.value):l=a.value,v.push({frame:a.frame+i,value:l}));return this.animations[0].createRange(t,c+i,u+i),!0};var vn,yn=function(){this.enableBlending=!1,this.blendingSpeed=.01,this.loopMode=at.ANIMATIONLOOPMODE_CYCLE};!function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(vn||(vn={}));var bn,Tn=function(){function e(){}return e.Interpolate=function(e,t,i,r,n){for(var o=1-3*r+3*t,a=3*r-6*t,s=3*t,l=e,c=0;c<5;c++){var u=l*l;l-=1/(3*o*u+2*a*l+s)*(o*(u*l)+a*u+s*l-e),l=Math.min(1,Math.max(0,l))}return 3*Math.pow(1-l,2)*l*i+3*(1-l)*Math.pow(l,2)*n+Math.pow(l,3)},e}(),En=function(){function e(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}return e.prototype.degrees=function(){return 180*this._radians/Math.PI},e.prototype.radians=function(){return this._radians},e.BetweenTwoPoints=function(t,i){var r=i.subtract(t);return new e(Math.atan2(r.y,r.x))},e.BetweenTwoVectors=function(t,i){var r=t.lengthSquared()*i.lengthSquared();if(0===r)return new e(Math.PI/2);r=Math.sqrt(r);var n=t.dot(i)/r;return n=j.Clamp(n,-1,1),new e(Math.acos(n))},e.FromRadians=function(t){return new e(t)},e.FromDegrees=function(t){return new e(t*Math.PI/180)},e}(),Sn=function(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;var r=Math.pow(t.x,2)+Math.pow(t.y,2),n=(Math.pow(e.x,2)+Math.pow(e.y,2)-r)/2,o=(r-Math.pow(i.x,2)-Math.pow(i.y,2))/2,a=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new U((n*(t.y-i.y)-o*(e.y-t.y))/a,((e.x-t.x)*o-(t.x-i.x)*n)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=En.BetweenTwoPoints(this.centerPoint,this.startPoint);var s=this.startAngle.degrees(),l=En.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),c=En.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();l-s>180&&(l-=360),l-s<-180&&(l+=360),c-l>180&&(c-=360),c-l<-180&&(c+=360),this.orientation=l-s<0?vn.CW:vn.CCW,this.angle=En.FromDegrees(this.orientation===vn.CW?s-c:c-s)},xn=function(){function e(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new U(e,t))}return e.prototype.addLineTo=function(e,t){if(this.closed)return this;var i=new U(e,t),r=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(r).length(),this},e.prototype.addArcTo=function(e,t,i,r,n){if(void 0===n&&(n=36),this.closed)return this;var o=this._points[this._points.length-1],a=new U(e,t),s=new U(i,r),l=new Sn(o,a,s),c=l.angle.radians()/n;l.orientation===vn.CW&&(c*=-1);for(var u=l.startAngle.radians()+c,h=0;h<n;h++){var d=Math.cos(u)*l.radius+l.centerPoint.x,p=Math.sin(u)*l.radius+l.centerPoint.y;this.addLineTo(d,p),u+=c}return this},e.prototype.addQuadraticCurveTo=function(e,t,i,r,n){if(void 0===n&&(n=36),this.closed)return this;for(var o=function(e,t,i,r){return(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r},a=this._points[this._points.length-1],s=0;s<=n;s++){var l=s/n,c=o(l,a.x,e,i),u=o(l,a.y,t,r);this.addLineTo(c,u)}return this},e.prototype.addBezierCurveTo=function(e,t,i,r,n,o,a){if(void 0===a&&(a=36),this.closed)return this;for(var s=function(e,t,i,r,n){return(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*n},l=this._points[this._points.length-1],c=0;c<=a;c++){var u=c/a,h=s(u,l.x,e,i,n),d=s(u,l.y,t,r,o);this.addLineTo(h,d)}return this},e.prototype.isPointInside=function(e){for(var t=!1,i=this._points.length,r=i-1,n=0;n<i;r=n++){var o=this._points[r],a=this._points[n],s=a.x-o.x,l=a.y-o.y;if(Math.abs(l)>Number.EPSILON){if(l<0&&(o=this._points[n],s=-s,a=this._points[r],l=-l),e.y<o.y||e.y>a.y)continue;if(e.y===o.y&&e.x===o.x)return!0;var c=l*(e.x-o.x)-s*(e.y-o.y);if(0===c)return!0;if(c<0)continue;t=!t}else{if(e.y!==o.y)continue;if(a.x<=e.x&&e.x<=o.x||o.x<=e.x&&e.x<=a.x)return!0}}return t},e.prototype.close=function(){return this.closed=!0,this},e.prototype.length=function(){var e=this._length;if(this.closed){var t=this._points[this._points.length-1];e+=this._points[0].subtract(t).length()}return e},e.prototype.area=function(){for(var e=this._points.length,t=0,i=e-1,r=0;r<e;i=r++)t+=this._points[i].x*this._points[r].y-this._points[r].x*this._points[i].y;return.5*t},e.prototype.getPoints=function(){return this._points},e.prototype.getPointAtLengthPosition=function(e){if(e<0||e>1)return U.Zero();for(var t=e*this.length(),i=0,r=0;r<this._points.length;r++){var n=(r+1)%this._points.length,o=this._points[r],a=this._points[n].subtract(o),s=a.length()+i;if(t>=i&&t<=s){var l=a.normalize(),c=t-i;return new U(o.x+l.x*c,o.y+l.y*c)}i=s}return U.Zero()},e.StartingAt=function(t,i){return new e(t,i)},e}(),An=function(){function e(e,t,i,r){void 0===t&&(t=null),void 0===r&&(r=!1),this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array,this._pointAtData={id:0,point:V.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:z.Identity()};for(var n=0;n<e.length;n++)this._curve[n]=e[n].clone();this._raw=i||!1,this._alignTangentsWithPath=r,this._compute(t,r)}return e.prototype.getCurve=function(){return this._curve},e.prototype.getPoints=function(){return this._curve},e.prototype.length=function(){return this._distances[this._distances.length-1]},e.prototype.getTangents=function(){return this._tangents},e.prototype.getNormals=function(){return this._normals},e.prototype.getBinormals=function(){return this._binormals},e.prototype.getDistances=function(){return this._distances},e.prototype.getPointAt=function(e){return this._updatePointAtData(e).point},e.prototype.getTangentAt=function(e,t){return void 0===t&&(t=!1),this._updatePointAtData(e,t),t?V.TransformCoordinates(V.Forward(),this._pointAtData.interpolationMatrix):this._tangents[this._pointAtData.previousPointArrayIndex]},e.prototype.getNormalAt=function(e,t){return void 0===t&&(t=!1),this._updatePointAtData(e,t),t?V.TransformCoordinates(V.Right(),this._pointAtData.interpolationMatrix):this._normals[this._pointAtData.previousPointArrayIndex]},e.prototype.getBinormalAt=function(e,t){return void 0===t&&(t=!1),this._updatePointAtData(e,t),t?V.TransformCoordinates(V.UpReadOnly,this._pointAtData.interpolationMatrix):this._binormals[this._pointAtData.previousPointArrayIndex]},e.prototype.getDistanceAt=function(e){return this.length()*e},e.prototype.getPreviousPointIndexAt=function(e){return this._updatePointAtData(e),this._pointAtData.previousPointArrayIndex},e.prototype.getSubPositionAt=function(e){return this._updatePointAtData(e),this._pointAtData.subPosition},e.prototype.getClosestPositionTo=function(e){for(var t=Number.MAX_VALUE,i=0,r=0;r<this._curve.length-1;r++){var n=this._curve[r+0],o=this._curve[r+1].subtract(n).normalize(),a=this._distances[r+1]-this._distances[r+0],s=Math.min(Math.max(V.Dot(o,e.subtract(n).normalize()),0)*V.Distance(n,e)/a,1),l=V.Distance(n.add(o.scale(s*a)),e);l<t&&(t=l,i=(this._distances[r+0]+a*s)/this.length())}return i},e.prototype.slice=function(t,i){if(void 0===t&&(t=0),void 0===i&&(i=1),t<0&&(t=1- -1*t%1),i<0&&(i=1- -1*i%1),t>i){var r=t;t=i,i=r}var n=this.getCurve(),o=this.getPointAt(t),a=this.getPreviousPointIndexAt(t),s=this.getPointAt(i),l=this.getPreviousPointIndexAt(i)+1,c=[];return 0!==t&&(a++,c.push(o)),c.push.apply(c,n.slice(a,l)),1===i&&1!==t||c.push(s),new e(c,this.getNormalAt(t),this._raw,this._alignTangentsWithPath)},e.prototype.update=function(e,t,i){void 0===t&&(t=null),void 0===i&&(i=!1);for(var r=0;r<e.length;r++)this._curve[r].x=e[r].x,this._curve[r].y=e[r].y,this._curve[r].z=e[r].z;return this._compute(t,i),this},e.prototype._compute=function(e,t){void 0===t&&(t=!1);var i=this._curve.length;if(!(i<2)){this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var r,n,o,a,s,l=this._tangents[0],c=this._normalVector(l,e);this._normals[0]=c,this._raw||this._normals[0].normalize(),this._binormals[0]=V.Cross(l,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var u=1;u<i;u++)r=this._getLastNonNullVector(u),u<i-1&&(n=this._getFirstNonNullVector(u),this._tangents[u]=t?n:r.add(n),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+this._curve[u].subtract(this._curve[u-1]).length(),o=this._tangents[u],s=this._binormals[u-1],this._normals[u]=V.Cross(s,o),this._raw||(0===this._normals[u].length()?(a=this._normals[u-1],this._normals[u]=a.clone()):this._normals[u].normalize()),this._binormals[u]=V.Cross(o,this._normals[u]),this._raw||this._binormals[u].normalize();this._pointAtData.id=NaN}},e.prototype._getFirstNonNullVector=function(e){for(var t=1,i=this._curve[e+t].subtract(this._curve[e]);0===i.length()&&e+t+1<this._curve.length;)t++,i=this._curve[e+t].subtract(this._curve[e]);return i},e.prototype._getLastNonNullVector=function(e){for(var t=1,i=this._curve[e].subtract(this._curve[e-t]);0===i.length()&&e>t+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i},e.prototype._normalVector=function(e,t){var i,r=e.length();if(0===r&&(r=1),null==t){var n;n=j.WithinEpsilon(Math.abs(e.y)/r,1,A)?j.WithinEpsilon(Math.abs(e.x)/r,1,A)?j.WithinEpsilon(Math.abs(e.z)/r,1,A)?V.Zero():new V(0,0,1):new V(1,0,0):new V(0,-1,0),i=V.Cross(e,n)}else i=V.Cross(e,t),V.CrossToRef(i,e,i);return i.normalize(),i},e.prototype._updatePointAtData=function(e,t){if(void 0===t&&(t=!1),this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;var i=this.getPoints();if(e<=0)return this._setPointAtData(0,0,i[0],0,t);if(e>=1)return this._setPointAtData(1,1,i[i.length-1],i.length-1,t);for(var r,n=i[0],o=0,a=e*this.length(),s=1;s<i.length;s++){r=i[s];var l=V.Distance(n,r);if((o+=l)===a)return this._setPointAtData(e,1,r,s,t);if(o>a){var c=(o-a)/l,u=n.subtract(r),h=r.add(u.scaleInPlace(c));return this._setPointAtData(e,1-c,h,s-1,t)}n=r}return this._pointAtData},e.prototype._setPointAtData=function(e,t,i,r,n){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=r,this._pointAtData.interpolateReady=n,n&&this._updateInterpolationMatrix(),this._pointAtData},e.prototype._updateInterpolationMatrix=function(){this._pointAtData.interpolationMatrix=z.Identity();var e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){var t=e+1,i=this._tangents[e].clone(),r=this._normals[e].clone(),n=this._binormals[e].clone(),o=this._tangents[t].clone(),a=this._normals[t].clone(),s=this._binormals[t].clone(),l=G.RotationQuaternionFromAxis(r,n,i),c=G.RotationQuaternionFromAxis(a,s,o);G.Slerp(l,c,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}},e}(),Cn=function(){function e(e){this._length=0,this._points=e,this._length=this._computeLength(e)}return e.CreateQuadraticBezier=function(t,i,r,n){n=n>2?n:3;for(var o=[],a=function(e,t,i,r){return(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r},s=0;s<=n;s++)o.push(new V(a(s/n,t.x,i.x,r.x),a(s/n,t.y,i.y,r.y),a(s/n,t.z,i.z,r.z)));return new e(o)},e.CreateCubicBezier=function(t,i,r,n,o){o=o>3?o:4;for(var a=[],s=function(e,t,i,r,n){return(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*n},l=0;l<=o;l++)a.push(new V(s(l/o,t.x,i.x,r.x,n.x),s(l/o,t.y,i.y,r.y,n.y),s(l/o,t.z,i.z,r.z,n.z)));return new e(a)},e.CreateHermiteSpline=function(t,i,r,n,o){for(var a=[],s=1/o,l=0;l<=o;l++)a.push(V.Hermite(t,i,r,n,l*s));return new e(a)},e.CreateCatmullRomSpline=function(t,i,r){var n=[],o=1/i,a=0;if(r){for(var s=t.length,l=0;l<s;l++){a=0;for(var c=0;c<i;c++)n.push(V.CatmullRom(t[l%s],t[(l+1)%s],t[(l+2)%s],t[(l+3)%s],a)),a+=o}n.push(n[0])}else{var u=[];for(u.push(t[0].clone()),Array.prototype.push.apply(u,t),u.push(t[t.length-1].clone()),l=0;l<u.length-3;l++)for(a=0,c=0;c<i;c++)n.push(V.CatmullRom(u[l],u[l+1],u[l+2],u[l+3],a)),a+=o;l--,n.push(V.CatmullRom(u[l],u[l+1],u[l+2],u[l+3],a))}return new e(n)},e.ArcThru3Points=function(t,i,r,n,o,a){void 0===n&&(n=32),void 0===o&&(o=!1),void 0===a&&(a=!1);var s=[],l=i.subtract(t),c=r.subtract(i),u=t.subtract(r),h=V.Cross(l,c),d=h.length();if(d<Math.pow(10,-8))return new e(s);var p=l.lengthSquared(),f=c.lengthSquared(),_=u.lengthSquared(),m=h.lengthSquared(),g=.5*l.length()*c.length()*u.length()/d,v=-.5*f*V.Dot(l,u)/m,y=-.5*_*V.Dot(l,c)/m,b=-.5*p*V.Dot(c,u)/m,T=t.scale(v).add(i.scale(y)).add(r.scale(b)),E=t.subtract(T).normalize(),S=V.Cross(h,E).normalize();if(a){for(var x=2*Math.PI/n,A=0;A<=2*Math.PI;A+=x)s.push(T.add(E.scale(g*Math.cos(A)).add(S.scale(g*Math.sin(A)))));s.push(t)}else{x=1/n,A=0;var C=V.Zero();do{C=T.add(E.scale(g*Math.cos(A)).add(S.scale(g*Math.sin(A)))),s.push(C),A+=x}while(!C.equalsWithEpsilon(r,g*x*1.1));s.push(r),o&&s.push(t)}return new e(s)},e.prototype.getPoints=function(){return this._points},e.prototype.length=function(){return this._length},e.prototype.continue=function(t){for(var i=this._points[this._points.length-1],r=this._points.slice(),n=t.getPoints(),o=1;o<n.length;o++)r.push(n[o].subtract(n[0]).add(i));return new e(r)},e.prototype._computeLength=function(e){for(var t=0,i=1;i<e.length;i++)t+=e[i].subtract(e[i-1]).length();return t},e}(),Rn=function(){function e(){this._easingMode=e.EASINGMODE_EASEIN}return e.prototype.setEasingMode=function(e){var t=Math.min(Math.max(e,0),2);this._easingMode=t},e.prototype.getEasingMode=function(){return this._easingMode},e.prototype.easeInCore=function(e){throw new Error("You must implement this method")},e.prototype.ease=function(t){switch(this._easingMode){case e.EASINGMODE_EASEIN:return this.easeInCore(t);case e.EASINGMODE_EASEOUT:return 1-this.easeInCore(1-t)}return t>=.5?.5*(1-this.easeInCore(2*(1-t)))+.5:.5*this.easeInCore(2*t)},e.EASINGMODE_EASEIN=0,e.EASINGMODE_EASEOUT=1,e.EASINGMODE_EASEINOUT=2,e}(),Pn=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.prototype.easeInCore=function(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)},t}(Rn),In=function(e){function t(t){void 0===t&&(t=1);var i=e.call(this)||this;return i.amplitude=t,i}return m(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)},t}(Rn),Mn=function(e){function t(t,i){void 0===t&&(t=3),void 0===i&&(i=2);var r=e.call(this)||this;return r.bounces=t,r.bounciness=i,r}return m(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.bounces),i=this.bounciness;i<=1&&(i=1.001);var r=Math.pow(i,t),n=1-i,o=(1-r)/n+.5*r,a=e*o,s=Math.log(-a*(1-i)+1)/Math.log(i),l=Math.floor(s),c=l+1,u=(1-Math.pow(i,l))/(n*o),h=.5*(u+(1-Math.pow(i,c))/(n*o)),d=e-h,p=h-u;return-Math.pow(1/i,t-l)/(p*p)*(d-p)*(d+p)},t}(Rn),On=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.prototype.easeInCore=function(e){return e*e*e},t}(Rn),Dn=function(e){function t(t,i){void 0===t&&(t=3),void 0===i&&(i=3);var r=e.call(this)||this;return r.oscillations=t,r.springiness=i,r}return m(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.oscillations),i=Math.max(0,this.springiness);return(0==i?e:(Math.exp(i*e)-1)/(Math.exp(i)-1))*Math.sin((6.283185307179586*t+1.5707963267948966)*e)},t}(Rn),Nn=function(e){function t(t){void 0===t&&(t=2);var i=e.call(this)||this;return i.exponent=t,i}return m(t,e),t.prototype.easeInCore=function(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)},t}(Rn),Fn=function(e){function t(t){void 0===t&&(t=2);var i=e.call(this)||this;return i.power=t,i}return m(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.power);return Math.pow(e,t)},t}(Rn),Ln=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.prototype.easeInCore=function(e){return e*e},t}(Rn),wn=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.prototype.easeInCore=function(e){return e*e*e*e},t}(Rn),Bn=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.prototype.easeInCore=function(e){return e*e*e*e*e},t}(Rn),Un=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.prototype.easeInCore=function(e){return 1-Math.sin(1.5707963267948966*(1-e))},t}(Rn),Vn=function(e){function t(t,i,r,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=1),void 0===n&&(n=1);var o=e.call(this)||this;return o.x1=t,o.y1=i,o.x2=r,o.y2=n,o}return m(t,e),t.prototype.easeInCore=function(e){return Tn.Interpolate(e,this.x1,this.y1,this.x2,this.y2)},t}(Rn),kn=function(){function e(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}return e.prototype._clone=function(){return new e(this.frame,this.action,this.onlyOnce)},e}(),Gn=function(){function e(){}return e.prototype.getClassName=function(){return"TargetedAnimation"},e.prototype.serialize=function(){var e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e},e}(),zn=function(){function e(e,t,i,r){void 0===t&&(t=null),void 0===i&&(i=-1),void 0===r&&(r=0),this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._parentContainer=null,this.onAnimationEndObservable=new f,this.onAnimationLoopObservable=new f,this.onAnimationGroupLoopObservable=new f,this.onAnimationGroupEndObservable=new f,this.onAnimationGroupPauseObservable=new f,this.onAnimationGroupPlayObservable=new f,this.metadata=null,this._mask=null,this._animationLoopFlags=[],this._scene=t||M.LastCreatedScene,this._weight=i,this._playOrder=r,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}return Object.defineProperty(e.prototype,"mask",{get:function(){return this._mask},set:function(e){this._mask!==e&&(this._mask=e,this.syncWithMask(!0))},enumerable:!1,configurable:!0}),e.prototype.syncWithMask=function(e){if(void 0===e&&(e=!1),this.mask||e){this._numActiveAnimatables=0;for(var t=0;t<this._animatables.length;++t){var i=this._animatables[t];!this.mask||this.mask.disabled||this.mask.retainsTarget(i.target.name)?(this._numActiveAnimatables++,i.paused&&i.restart()):i.paused||i.pause()}}else this._numActiveAnimatables=this._targetedAnimations.length},e.prototype.removeUnmaskedAnimations=function(){if(this.mask&&!this.mask.disabled){for(var e=0;e<this._animatables.length;++e){var t=this._animatables[e];this.mask.retainsTarget(t.target.name)||(t.stop(),this._animatables.splice(e,1),--e)}for(var i=0;i<this._targetedAnimations.length;i++){var r=this._targetedAnimations[i];this.mask.retainsTarget(r.target.name)||(this._targetedAnimations.splice(i,1),--i)}}},Object.defineProperty(e.prototype,"from",{get:function(){return this._from},set:function(e){if(this._from!==e){this._from=e;for(var t=0;t<this._animatables.length;t++)this._animatables[t].fromFrame=this._from}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"to",{get:function(){return this._to},set:function(e){if(this._to!==e){this._to=e;for(var t=0;t<this._animatables.length;t++)this._animatables[t].toFrame=this._to}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isStarted",{get:function(){return this._isStarted},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isPlaying",{get:function(){return this._isStarted&&!this._isPaused},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"speedRatio",{get:function(){return this._speedRatio},set:function(e){if(this._speedRatio!==e){this._speedRatio=e;for(var t=0;t<this._animatables.length;t++)this._animatables[t].speedRatio=this._speedRatio}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"loopAnimation",{get:function(){return this._loopAnimation},set:function(e){if(this._loopAnimation!==e){this._loopAnimation=e;for(var t=0;t<this._animatables.length;t++)this._animatables[t].loopAnimation=this._loopAnimation}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isAdditive",{get:function(){return this._isAdditive},set:function(e){if(this._isAdditive!==e){this._isAdditive=e;for(var t=0;t<this._animatables.length;t++)this._animatables[t].isAdditive=this._isAdditive}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"weight",{get:function(){return this._weight},set:function(e){this._weight!==e&&(this._weight=e,this.setWeightForAllAnimatables(this._weight))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"targetedAnimations",{get:function(){return this._targetedAnimations},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"animatables",{get:function(){return this._animatables},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"children",{get:function(){return this._targetedAnimations},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"playOrder",{get:function(){return this._playOrder},set:function(e){if(this._playOrder!==e&&(this._playOrder=e,this._animatables.length>0)){for(var t=0;t<this._animatables.length;t++)this._animatables[t].playOrder=this._playOrder;this._scene.sortActiveAnimatables()}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"enableBlending",{get:function(){return this._enableBlending},set:function(e){if(this._enableBlending!==e&&(this._enableBlending=e,null!==e))for(var t=0;t<this._targetedAnimations.length;++t)this._targetedAnimations[t].animation.enableBlending=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"blendingSpeed",{get:function(){return this._blendingSpeed},set:function(e){if(this._blendingSpeed!==e&&(this._blendingSpeed=e,null!==e))for(var t=0;t<this._targetedAnimations.length;++t)this._targetedAnimations[t].animation.blendingSpeed=e},enumerable:!1,configurable:!0}),e.prototype.getLength=function(e,t){return e=null!=e?e:this._from,((t=null!=t?t:this._to)-e)/(this.targetedAnimations[0].animation.framePerSecond*this._speedRatio)},e.MergeAnimationGroups=function(t,i,r,n){if(void 0===i&&(i=!0),void 0===r&&(r=!1),0===t.length)return null;n=null!=n?n:t[0].weight;var o=Number.MAX_VALUE,a=-Number.MAX_VALUE;if(r)for(var s=0,l=t;s<l.length;s++)(d=l[s]).from<o&&(o=d.from),d.to>a&&(a=d.to);for(var c=new e(t[0].name+"_merged",t[0]._scene,n),u=0,h=t;u<h.length;u++){var d=h[u];r&&d.normalize(o,a);for(var p=0,f=d.targetedAnimations;p<f.length;p++){var _=f[p];c.addTargetedAnimation(_.animation,_.target)}i&&d.dispose()}return c},e.prototype.addTargetedAnimation=function(e,t){var i=new Gn;i.animation=e,i.target=t;var r=e.getKeys();return this._from>r[0].frame&&(this._from=r[0].frame),this._to<r[r.length-1].frame&&(this._to=r[r.length-1].frame),null!==this._enableBlending&&(e.enableBlending=this._enableBlending),null!==this._blendingSpeed&&(e.blendingSpeed=this._blendingSpeed),this._targetedAnimations.push(i),i},e.prototype.removeTargetedAnimation=function(e){for(var t=this._targetedAnimations.length-1;t>-1;t--)this._targetedAnimations[t].animation===e&&this._targetedAnimations.splice(t,1)},e.prototype.normalize=function(e,t){void 0===e&&(e=null),void 0===t&&(t=null),null==e&&(e=this._from),null==t&&(t=this._to);for(var i=0;i<this._targetedAnimations.length;i++){var r=this._targetedAnimations[i].animation.getKeys(),n=r[0],o=r[r.length-1];if(n.frame>e){var a={frame:e,value:n.value,inTangent:n.inTangent,outTangent:n.outTangent,interpolation:n.interpolation};r.splice(0,0,a)}o.frame<t&&(a={frame:t,value:o.value,inTangent:o.inTangent,outTangent:o.outTangent,interpolation:o.interpolation},r.push(a))}return this._from=e,this._to=t,this},e.prototype._processLoop=function(e,t,i){var r=this;e.onAnimationLoop=function(){r.onAnimationLoopObservable.notifyObservers(t),r._animationLoopFlags[i]||(r._animationLoopFlags[i]=!0,r._animationLoopCount++,r._animationLoopCount===r._numActiveAnimatables&&(r.onAnimationGroupLoopObservable.notifyObservers(r),r._animationLoopCount=0,r._animationLoopFlags.length=0))}},e.prototype.start=function(e,t,i,r,n){var o=this;if(void 0===e&&(e=!1),void 0===t&&(t=1),this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(var a=function(a){var l=s._targetedAnimations[a],c=s._scene.beginDirectAnimation(l.target,[l.animation],void 0!==i?i:s._from,void 0!==r?r:s._to,e,t,void 0,void 0,void 0!==n?n:s._isAdditive);c.weight=s._weight,c.playOrder=s._playOrder,c.onAnimationEnd=function(){o.onAnimationEndObservable.notifyObservers(l),o._checkAnimationGroupEnded(c)},s._processLoop(c,l,a),s._animatables.push(c)},s=this,l=0;l<this._targetedAnimations.length;l++)a(l);return this.syncWithMask(),this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this},e.prototype.pause=function(){if(!this._isStarted)return this;this._isPaused=!0;for(var e=0;e<this._animatables.length;e++)this._animatables[e].pause();return this.onAnimationGroupPauseObservable.notifyObservers(this),this},e.prototype.play=function(e){return this.isStarted&&this._animatables.length===this._targetedAnimations.length?(void 0!==e&&(this.loopAnimation=e),this.restart()):(this.stop(),this.start(e,this._speedRatio)),this._isPaused=!1,this},e.prototype.reset=function(){if(!this._isStarted)return this.play(),this.goToFrame(0),this.stop(),this;for(var e=0;e<this._animatables.length;e++)this._animatables[e].reset();return this},e.prototype.restart=function(){if(!this._isStarted)return this;for(var e=0;e<this._animatables.length;e++)this._animatables[e].restart();return this.syncWithMask(),this.onAnimationGroupPlayObservable.notifyObservers(this),this},e.prototype.stop=function(){if(!this._isStarted)return this;for(var e=this._animatables.slice(),t=0;t<e.length;t++)e[t].stop(void 0,void 0,!0);var i=0;for(t=0;t<this._scene._activeAnimatables.length;t++){var r=this._scene._activeAnimatables[t];r._runtimeAnimations.length>0&&(this._scene._activeAnimatables[i++]=r)}return this._scene._activeAnimatables.length=i,this._isStarted=!1,this},e.prototype.setWeightForAllAnimatables=function(e){for(var t=0;t<this._animatables.length;t++)this._animatables[t].weight=e;return this},e.prototype.syncAllAnimationsWith=function(e){for(var t=0;t<this._animatables.length;t++)this._animatables[t].syncWith(e);return this},e.prototype.goToFrame=function(e){if(!this._isStarted)return this;for(var t=0;t<this._animatables.length;t++)this._animatables[t].goToFrame(e);return this},e.prototype.dispose=function(){this._targetedAnimations.length=0,this._animatables.length=0;var e=this._scene.animationGroups.indexOf(this);if(e>-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){var t=this._parentContainer.animationGroups.indexOf(this);t>-1&&this._parentContainer.animationGroups.splice(t,1),this._parentContainer=null}this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear(),this.onAnimationGroupLoopObservable.clear()},e.prototype._checkAnimationGroupEnded=function(e){var t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),0===this._animatables.length&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))},e.prototype.clone=function(t,i,r){void 0===r&&(r=!1);var n=new e(t||this.name,this._scene,this._weight,this._playOrder);n._from=this.from,n._to=this.to,n._speedRatio=this.speedRatio,n._loopAnimation=this.loopAnimation,n._isAdditive=this.isAdditive,n._enableBlending=this.enableBlending,n._blendingSpeed=this.blendingSpeed,n.metadata=this.metadata,n.mask=this.mask;for(var o=0,a=this._targetedAnimations;o<a.length;o++){var s=a[o];n.addTargetedAnimation(r?s.animation.clone():s.animation,i?i(s.target):s.target)}return n},e.prototype.serialize=function(){var e={};e.name=this.name,e.from=this.from,e.to=this.to,e.speedRatio=this.speedRatio,e.loopAnimation=this.loopAnimation,e.isAdditive=this.isAdditive,e.weight=this.weight,e.playOrder=this.playOrder,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,e.targetedAnimations=[];for(var t=0;t<this.targetedAnimations.length;t++){var i=this.targetedAnimations[t];e.targetedAnimations[t]=i.serialize()}return je&&je.HasTags(this)&&(e.tags=je.GetTags(this)),this.metadata&&(e.metadata=this.metadata),e},e.Parse=function(t,i){for(var r=new e(t.name,i,t.weight,t.playOrder),n=0;n<t.targetedAnimations.length;n++){var o=t.targetedAnimations[n],a=at.Parse(o.animation),s=o.targetId;if("influence"===o.animation.property){var l=i.getMorphTargetById(s);l&&r.addTargetedAnimation(a,l)}else{var c=i.getNodeById(s);null!=c&&r.addTargetedAnimation(a,c)}}return je&&je.AddTagsTo(r,t.tags),null!==t.from&&null!==t.to&&r.normalize(t.from,t.to),void 0!==t.speedRatio&&(r._speedRatio=t.speedRatio),void 0!==t.loopAnimation&&(r._loopAnimation=t.loopAnimation),void 0!==t.isAdditive&&(r._isAdditive=t.isAdditive),void 0!==t.weight&&(r._weight=t.weight),void 0!==t.playOrder&&(r._playOrder=t.playOrder),void 0!==t.enableBlending&&(r._enableBlending=t.enableBlending),void 0!==t.blendingSpeed&&(r._blendingSpeed=t.blendingSpeed),void 0!==t.metadata&&(r.metadata=t.metadata),r},e.MakeAnimationAdditive=function(e,t,i,r,n){var o;void 0===r&&(r=!1);var a=e;(o="object"==typeof t?t:{referenceFrame:t,range:i,cloneOriginalAnimationGroup:r,clonedAnimationName:n}).cloneOriginalAnimationGroup&&(a=e.clone(o.clonedAnimationGroupName||a.name));for(var s=a.targetedAnimations,l=0;l<s.length;l++)(d=s[l]).animation=at.MakeAnimationAdditive(d.animation,o);if(a.isAdditive=!0,o.clipKeys){var c=Number.MAX_VALUE,u=-Number.MAX_VALUE,h=a.targetedAnimations;for(l=0;l<h.length;l++){var d,p=(d=h[l]).animation.getKeys();c>p[0].frame&&(c=p[0].frame),u<p[p.length-1].frame&&(u=p[p.length-1].frame)}a._from=c,a._to=u}return a},e.ClipKeys=function(t,i,r,n,o){var a=t.clone(n||t.name);return e.ClipKeysInPlace(a,i,r,o)},e.ClipKeysInPlace=function(t,i,r,n){return e.ClipInPlace(t,i,r,n,!1)},e.ClipFrames=function(t,i,r,n,o){var a=t.clone(n||t.name);return e.ClipFramesInPlace(a,i,r,o)},e.ClipFramesInPlace=function(t,i,r,n){return e.ClipInPlace(t,i,r,n,!0)},e.ClipInPlace=function(e,t,i,r,n){void 0===n&&(n=!1);for(var o=Number.MAX_VALUE,a=-Number.MAX_VALUE,s=e.targetedAnimations,l=0;l<s.length;l++){var c=s[l],u=r?c.animation:c.animation.clone();n&&(u.createKeyForFrame(t),u.createKeyForFrame(i));for(var h=u.getKeys(),d=[],p=Number.MAX_VALUE,f=0;f<h.length;f++){var _=h[f];if(!n&&f>=t&&f<=i||n&&_.frame>=t&&_.frame<=i){var m={frame:_.frame,value:_.value.clone?_.value.clone():_.value,inTangent:_.inTangent,outTangent:_.outTangent,interpolation:_.interpolation,lockedTangent:_.lockedTangent};p===Number.MAX_VALUE&&(p=m.frame),m.frame-=p,d.push(m)}}0!==d.length?(o>d[0].frame&&(o=d[0].frame),a<d[d.length-1].frame&&(a=d[d.length-1].frame),u.setKeys(d,!0),c.animation=u):(s.splice(l,1),l--)}return e._from=o,e._to=a,e},e.prototype.getClassName=function(){return"AnimationGroup"},e.prototype.toString=function(e){var t="Name: "+this.name;return t+=", type: "+this.getClassName(),e&&(t+=", from: "+this._from,t+=", to: "+this._to,t+=", isStarted: "+this._isStarted,t+=", speedRatio: "+this._speedRatio,t+=", targetedAnimations length: "+this._targetedAnimations.length,t+=", animatables length: "+this._animatables),t},e}(),Wn=function(){function e(e){this._path=e,this._onchange=new Array,this.value=0,this.animations=[]}return e.prototype.getPoint=function(){var e=this._path.getPointAtLengthPosition(this.value);return new V(e.x,0,e.y)},e.prototype.moveAhead=function(e){return void 0===e&&(e=.002),this.move(e),this},e.prototype.moveBack=function(e){return void 0===e&&(e=.002),this.move(-e),this},e.prototype.move=function(e){if(Math.abs(e)>1)throw"step size should be less than 1.";return this.value+=e,this._ensureLimits(),this._raiseOnChange(),this},e.prototype._ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},e.prototype._raiseOnChange=function(){var e=this;return this._onchange.forEach((function(t){return t(e)})),this},e.prototype.onchange=function(e){return this._onchange.push(e),this},e}();!function(e){e[e.Include=0]="Include",e[e.Exclude=1]="Exclude"}(bn||(bn={}));var Hn=function(){function e(e,t){void 0===t&&(t=bn.Include),this.mode=t,this.disabled=!1,this._targetNames=new Set,e&&this.addTargetName(e)}return e.prototype.addTargetName=function(e){if(Array.isArray(e))for(var t=0,i=e;t<i.length;t++){var r=i[t];this._targetNames.add(r)}else this._targetNames.add(e)},e.prototype.removeTargetName=function(e){if(Array.isArray(e))for(var t=0,i=e;t<i.length;t++){var r=i[t];this._targetNames.delete(r)}else this._targetNames.delete(e)},e.prototype.hasTarget=function(e){return this._targetNames.has(e)},e.prototype.retainsTarget=function(e){return this._targetNames.has(e)===(this.mode===bn.Include)},e}();function Xn(e,t,i){try{var r=e.next();r.done?t(r):r.value?r.value.then((function(){r.value=void 0,t(r)}),i):t(r)}catch(e){i(e)}}function jn(e){var t;return void 0===e&&(e=25),function(i,r,n){var o=performance.now();void 0===t||o-t>e?(t=o,setTimeout((function(){Xn(i,r,n)}),0)):Xn(i,r,n)}}function Yn(e,t,i,r,n){var o=function(){var a,s=function(e){e.done?i(e.value):void 0===a?a=!0:o()};do{a=void 0,n&&n.aborted?r(new Error("Aborted")):t(e,s,r),void 0===a&&(a=!1)}while(a)};o()}function Kn(e,t){var i;return Yn(e,Xn,(function(e){return i=e}),(function(e){throw e}),t),i}function Qn(e,t,i){return new Promise((function(r,n){Yn(e,t,r,n,i)}))}function qn(e,t){return function(){for(var i=[],r=0;r<arguments.length;r++)i[r]=arguments[r];return Kn(e.apply(void 0,i),t)}}function Zn(e,t,i){return function(){for(var r=[],n=0;n<arguments.length;n++)r[n]=arguments[n];return Qn(e.apply(void 0,r),t,i)}}var Jn=function(){function e(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}return e.prototype.toGlobal=function(t,i){return new e(this.x*t,this.y*i,this.width*t,this.height*i)},e.prototype.toGlobalToRef=function(e,t,i){return i.x=this.x*e,i.y=this.y*t,i.width=this.width*e,i.height=this.height*t,this},e.prototype.clone=function(){return new e(this.x,this.y,this.width,this.height)},e}(),$n=function(e){function t(i,r,n,o){void 0===o&&(o=!0);var a=e.call(this,i,n,!1)||this;return a._position=V.Zero(),a._upVector=V.Up(),a.oblique=null,a._orthoLeft=null,a._orthoRight=null,a._orthoBottom=null,a._orthoTop=null,a.fov=.8,a.projectionPlaneTilt=0,a.minZ=1,a.maxZ=1e4,a.inertia=.9,a._mode=t.PERSPECTIVE_CAMERA,a.isIntermediate=!1,a.viewport=new Jn(0,0,1,1),a.layerMask=268435455,a.fovMode=t.FOVMODE_VERTICAL_FIXED,a.cameraRigMode=t.RIG_MODE_NONE,a.customRenderTargets=[],a.outputRenderTarget=null,a.onViewMatrixChangedObservable=new f,a.onProjectionMatrixChangedObservable=new f,a.onAfterCheckInputsObservable=new f,a.onRestoreStateObservable=new f,a.isRigCamera=!1,a._hasMoved=!1,a._rigCameras=new Array,a._skipRendering=!1,a._projectionMatrix=new z,a._postProcesses=new Array,a._activeMeshes=new ar(256),a._globalPosition=V.Zero(),a._computedViewMatrix=z.Identity(),a._doNotComputeProjectionMatrix=!1,a._transformMatrix=z.Zero(),a._refreshFrustumPlanes=!0,a._absoluteRotation=G.Identity(),a._isCamera=!0,a._isLeftCamera=!1,a._isRightCamera=!1,a.getScene().addCamera(a),o&&!a.getScene().activeCamera&&(a.getScene().activeCamera=a),a.position=r,a.renderPassId=a.getScene().getEngine().createRenderPassId("Camera ".concat(i)),a}return m(t,e),Object.defineProperty(t.prototype,"position",{get:function(){return this._position},set:function(e){this._position=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"upVector",{get:function(){return this._upVector},set:function(e){this._upVector=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"screenArea",{get:function(){var e,i,r,n,o=0,a=0;if(this.mode===t.PERSPECTIVE_CAMERA)this.fovMode===t.FOVMODE_VERTICAL_FIXED?(a=2*this.minZ*Math.tan(this.fov/2),o=this.getEngine().getAspectRatio(this)*a):a=(o=2*this.minZ*Math.tan(this.fov/2))/this.getEngine().getAspectRatio(this);else{var s=this.getEngine().getRenderWidth()/2,l=this.getEngine().getRenderHeight()/2;o=(null!==(e=this.orthoRight)&&void 0!==e?e:s)-(null!==(i=this.orthoLeft)&&void 0!==i?i:-s),a=(null!==(r=this.orthoTop)&&void 0!==r?r:l)-(null!==(n=this.orthoBottom)&&void 0!==n?n:-l)}return o*a},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"orthoLeft",{get:function(){return this._orthoLeft},set:function(e){this._orthoLeft=e;for(var t=0,i=this._rigCameras;t<i.length;t++)i[t].orthoLeft=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"orthoRight",{get:function(){return this._orthoRight},set:function(e){this._orthoRight=e;for(var t=0,i=this._rigCameras;t<i.length;t++)i[t].orthoRight=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"orthoBottom",{get:function(){return this._orthoBottom},set:function(e){this._orthoBottom=e;for(var t=0,i=this._rigCameras;t<i.length;t++)i[t].orthoBottom=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"orthoTop",{get:function(){return this._orthoTop},set:function(e){this._orthoTop=e;for(var t=0,i=this._rigCameras;t<i.length;t++)i[t].orthoTop=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"mode",{get:function(){return this._mode},set:function(e){this._mode=e;for(var t=0,i=this._rigCameras;t<i.length;t++)i[t].mode=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hasMoved",{get:function(){return this._hasMoved},enumerable:!1,configurable:!0}),t.prototype.storeState=function(){return this._stateStored=!0,this._storedFov=this.fov,this},t.prototype._restoreStateValues=function(){return!!this._stateStored&&(this.fov=this._storedFov,!0)},t.prototype.restoreState=function(){return!!this._restoreStateValues()&&(this.onRestoreStateObservable.notifyObservers(this),!0)},t.prototype.getClassName=function(){return"Camera"},t.prototype.toString=function(e){var t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(var i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t},t.prototype.applyVerticalCorrection=function(){var e=this.absoluteRotation.toEulerAngles();this.projectionPlaneTilt=this._scene.useRightHandedSystem?-e.x:e.x},Object.defineProperty(t.prototype,"globalPosition",{get:function(){return this._globalPosition},enumerable:!1,configurable:!0}),t.prototype.getActiveMeshes=function(){return this._activeMeshes},t.prototype.isActiveMesh=function(e){return-1!==this._activeMeshes.indexOf(e)},t.prototype.isReady=function(t){if(void 0===t&&(t=!1),t)for(var i=0,r=this._postProcesses;i<r.length;i++){var n=r[i];if(n&&!n.isReady())return!1}return e.prototype.isReady.call(this,t)},t.prototype._initCache=function(){e.prototype._initCache.call(this),this._cache.position=new V(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.upVector=new V(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.mode=void 0,this._cache.minZ=void 0,this._cache.maxZ=void 0,this._cache.fov=void 0,this._cache.fovMode=void 0,this._cache.aspectRatio=void 0,this._cache.orthoLeft=void 0,this._cache.orthoRight=void 0,this._cache.orthoBottom=void 0,this._cache.orthoTop=void 0,this._cache.obliqueAngle=void 0,this._cache.obliqueLength=void 0,this._cache.obliqueOffset=void 0,this._cache.renderWidth=void 0,this._cache.renderHeight=void 0},t.prototype._updateCache=function(t){t||e.prototype._updateCache.call(this),this._cache.position.copyFrom(this.position),this._cache.upVector.copyFrom(this.upVector)},t.prototype._isSynchronized=function(){return this._isSynchronizedViewMatrix()&&this._isSynchronizedProjectionMatrix()},t.prototype._isSynchronizedViewMatrix=function(){return!!e.prototype._isSynchronized.call(this)&&this._cache.position.equals(this.position)&&this._cache.upVector.equals(this.upVector)&&this.isSynchronizedWithParent()},t.prototype._isSynchronizedProjectionMatrix=function(){var e=this._cache.mode===this.mode&&this._cache.minZ===this.minZ&&this._cache.maxZ===this.maxZ;if(!e)return!1;var i=this.getEngine();return this.mode===t.PERSPECTIVE_CAMERA?e=this._cache.fov===this.fov&&this._cache.fovMode===this.fovMode&&this._cache.aspectRatio===i.getAspectRatio(this)&&this._cache.projectionPlaneTilt===this.projectionPlaneTilt:(e=this._cache.orthoLeft===this.orthoLeft&&this._cache.orthoRight===this.orthoRight&&this._cache.orthoBottom===this.orthoBottom&&this._cache.orthoTop===this.orthoTop&&this._cache.renderWidth===i.getRenderWidth()&&this._cache.renderHeight===i.getRenderHeight(),this.oblique&&(e=e&&this._cache.obliqueAngle===this.oblique.angle&&this._cache.obliqueLength===this.oblique.length&&this._cache.obliqueOffset===this.oblique.offset)),e},t.prototype.attachControl=function(e,t){},t.prototype.detachControl=function(e){},t.prototype.update=function(){this._hasMoved=!1,this._checkInputs(),this.cameraRigMode!==t.RIG_MODE_NONE&&this._updateRigCameras(),this.getViewMatrix(),this.getProjectionMatrix()},t.prototype._checkInputs=function(){this.onAfterCheckInputsObservable.notifyObservers(this)},Object.defineProperty(t.prototype,"rigCameras",{get:function(){return this._rigCameras},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rigPostProcess",{get:function(){return this._rigPostProcess},enumerable:!1,configurable:!0}),t.prototype._getFirstPostProcess=function(){for(var e=0;e<this._postProcesses.length;e++)if(null!==this._postProcesses[e])return this._postProcesses[e];return null},t.prototype._cascadePostProcessesToRigCams=function(){var e=this._getFirstPostProcess();e&&e.markTextureDirty();for(var t=0,i=this._rigCameras.length;t<i;t++){var r=this._rigCameras[t],n=r._rigPostProcess;n?("pass"===n.getEffectName()&&(r.isIntermediate=0===this._postProcesses.length),r._postProcesses=this._postProcesses.slice(0).concat(n),n.markTextureDirty()):r._postProcesses=this._postProcesses.slice(0)}},t.prototype.attachPostProcess=function(e,t){return void 0===t&&(t=null),!e.isReusable()&&this._postProcesses.indexOf(e)>-1?(ae.Error("You're trying to reuse a post process not defined as reusable."),0):(null==t||t<0?this._postProcesses.push(e):null===this._postProcesses[t]?this._postProcesses[t]=e:this._postProcesses.splice(t,0,e),this._cascadePostProcessesToRigCams(),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._postProcesses.indexOf(e))},t.prototype.detachPostProcess=function(e){var t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses[t]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()},t.prototype.getWorldMatrix=function(){return this._isSynchronizedViewMatrix()||this.getViewMatrix(),this._worldMatrix},t.prototype._getViewMatrix=function(){return z.Identity()},t.prototype.getViewMatrix=function(e){return!e&&this._isSynchronizedViewMatrix()||(this._hasMoved=!0,this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix)),this._computedViewMatrix},t.prototype.freezeProjectionMatrix=function(e){this._doNotComputeProjectionMatrix=!0,void 0!==e&&(this._projectionMatrix=e)},t.prototype.unfreezeProjectionMatrix=function(){this._doNotComputeProjectionMatrix=!1},t.prototype.getProjectionMatrix=function(e){var i,r,n,o,a,s,l,c,u,h,d,p,f,_,m,g,v,y,b;if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;var T=this.getEngine(),E=this.getScene(),S=T.useReverseDepthBuffer;if(this.mode===t.PERSPECTIVE_CAMERA)this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=T.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1),(E.useRightHandedSystem?z.PerspectiveFovRHToRef:z.PerspectiveFovLHToRef)(this.fov,T.getAspectRatio(this),S?this.maxZ:this.minZ,S?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===t.FOVMODE_VERTICAL_FIXED,T.isNDCHalfZRange,this.projectionPlaneTilt,S);else{var x=T.getRenderWidth()/2,A=T.getRenderHeight()/2;E.useRightHandedSystem?this.oblique?z.ObliqueOffCenterRHToRef(null!==(i=this.orthoLeft)&&void 0!==i?i:-x,null!==(r=this.orthoRight)&&void 0!==r?r:x,null!==(n=this.orthoBottom)&&void 0!==n?n:-A,null!==(o=this.orthoTop)&&void 0!==o?o:A,S?this.maxZ:this.minZ,S?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,T.isNDCHalfZRange):z.OrthoOffCenterRHToRef(null!==(a=this.orthoLeft)&&void 0!==a?a:-x,null!==(s=this.orthoRight)&&void 0!==s?s:x,null!==(l=this.orthoBottom)&&void 0!==l?l:-A,null!==(c=this.orthoTop)&&void 0!==c?c:A,S?this.maxZ:this.minZ,S?this.minZ:this.maxZ,this._projectionMatrix,T.isNDCHalfZRange):this.oblique?z.ObliqueOffCenterLHToRef(null!==(u=this.orthoLeft)&&void 0!==u?u:-x,null!==(h=this.orthoRight)&&void 0!==h?h:x,null!==(d=this.orthoBottom)&&void 0!==d?d:-A,null!==(p=this.orthoTop)&&void 0!==p?p:A,S?this.maxZ:this.minZ,S?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,T.isNDCHalfZRange):z.OrthoOffCenterLHToRef(null!==(f=this.orthoLeft)&&void 0!==f?f:-x,null!==(_=this.orthoRight)&&void 0!==_?_:x,null!==(m=this.orthoBottom)&&void 0!==m?m:-A,null!==(g=this.orthoTop)&&void 0!==g?g:A,S?this.maxZ:this.minZ,S?this.minZ:this.maxZ,this._projectionMatrix,T.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=null===(v=this.oblique)||void 0===v?void 0:v.angle,this._cache.obliqueLength=null===(y=this.oblique)||void 0===y?void 0:y.length,this._cache.obliqueOffset=null===(b=this.oblique)||void 0===b?void 0:b.offset,this._cache.renderWidth=T.getRenderWidth(),this._cache.renderHeight=T.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix},t.prototype.getTransformationMatrix=function(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix},t.prototype._computeObliqueDistance=function(e){return(this.radius||(this.target?V.Distance(this.position,this.target):this.position.length()))+e},t.prototype._updateFrustumPlanes=function(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?ln.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=ln.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)},t.prototype.isInFrustum=function(e,t){if(void 0===t&&(t=!1),this._updateFrustumPlanes(),t&&this.rigCameras.length>0){var i=!1;return this.rigCameras.forEach((function(t){t._updateFrustumPlanes(),i=i||e.isInFrustum(t._frustumPlanes)})),i}return e.isInFrustum(this._frustumPlanes)},t.prototype.isCompletelyInFrustum=function(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)},t.prototype.getForwardRay=function(e,t,i){throw void 0===e&&(e=100),He("Ray")},t.prototype.getForwardRayToRef=function(e,t,i,r){throw void 0===t&&(t=100),He("Ray")},t.prototype.dispose=function(i,r){for(void 0===r&&(r=!1),this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){var n=this._rigCameras.pop();n&&n.dispose()}if(this._parentContainer){var o=this._parentContainer.cameras.indexOf(this);o>-1&&this._parentContainer.cameras.splice(o,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==t.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else for(var a=this._postProcesses.length;--a>=0;){var s=this._postProcesses[a];s&&s.dispose(this)}for(var l=this.customRenderTargets.length;--l>=0;)this.customRenderTargets[l].dispose();this.customRenderTargets.length=0,this._activeMeshes.dispose(),this.getScene().getEngine().releaseRenderPassId(this.renderPassId),e.prototype.dispose.call(this,i,r)},Object.defineProperty(t.prototype,"isLeftCamera",{get:function(){return this._isLeftCamera},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isRightCamera",{get:function(){return this._isRightCamera},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"leftCamera",{get:function(){return this._rigCameras.length<1?null:this._rigCameras[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rightCamera",{get:function(){return this._rigCameras.length<2?null:this._rigCameras[1]},enumerable:!1,configurable:!0}),t.prototype.getLeftTarget=function(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()},t.prototype.getRightTarget=function(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()},t.prototype.setCameraRigMode=function(e,i){if(this.cameraRigMode!==e){for(;this._rigCameras.length>0;){var r=this._rigCameras.pop();r&&r.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=i.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=rr.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==t.RIG_MODE_NONE){var n=this.createRigCamera(this.name+"_L",0);n&&(n._isLeftCamera=!0);var o=this.createRigCamera(this.name+"_R",1);o&&(o._isRightCamera=!0),n&&o&&(this._rigCameras.push(n),this._rigCameras.push(o))}this._setRigMode(i),this._cascadePostProcessesToRigCams(),this.update()}},t.prototype._setRigMode=function(e){},t.prototype._getVRProjectionMatrix=function(){return z.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix},t.prototype.setCameraRigParameter=function(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=rr.ToRadians(t/.0637))},t.prototype.createRigCamera=function(e,t){return null},t.prototype._updateRigCameras=function(){for(var e=0;e<this._rigCameras.length;e++)this._rigCameras[e].minZ=this.minZ,this._rigCameras[e].maxZ=this.maxZ,this._rigCameras[e].fov=this.fov,this._rigCameras[e].upVector.copyFrom(this.upVector);this.cameraRigMode===t.RIG_MODE_STEREOSCOPIC_ANAGLYPH&&(this._rigCameras[0].viewport=this._rigCameras[1].viewport=this.viewport)},t.prototype._setupInputs=function(){},t.prototype.serialize=function(){var e=Ke.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getClassName(),this.parent&&this.parent._serializeAsParent(e),this.inputs&&this.inputs.serialize(e),Ke.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e},t.prototype.clone=function(e,i){void 0===i&&(i=null);var r=Ke.Clone(t.GetConstructorFromName(this.getClassName(),e,this.getScene(),this.interaxialDistance,this.isStereoscopicSideBySide),this);return r.name=e,r.parent=i,this.onClonedObservable.notifyObservers(r),r},t.prototype.getDirection=function(e){var t=V.Zero();return this.getDirectionToRef(e,t),t},Object.defineProperty(t.prototype,"absoluteRotation",{get:function(){return this.getWorldMatrix().decompose(void 0,this._absoluteRotation),this._absoluteRotation},enumerable:!1,configurable:!0}),t.prototype.getDirectionToRef=function(e,t){V.TransformNormalToRef(e,this.getWorldMatrix(),t)},t.GetConstructorFromName=function(e,i,r,n,o){return void 0===n&&(n=0),void 0===o&&(o=!0),qe.Construct(e,i,r,{interaxial_distance:n,isStereoscopicSideBySide:o})||function(){return t._CreateDefaultParsedCamera(i,r)}},t.prototype.computeWorldMatrix=function(){return this.getWorldMatrix()},t.Parse=function(e,i){var r=e.type,n=t.GetConstructorFromName(r,e.name,i,e.interaxial_distance,e.isStereoscopicSideBySide),o=Ke.Parse(n,e,i);if(void 0!==e.parentId&&(o._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(o._waitingParentInstanceIndex=e.parentInstanceIndex),o.inputs&&(o.inputs.parse(e),o._setupInputs()),e.upVector&&(o.upVector=V.FromArray(e.upVector)),o.setPosition&&(o.position.copyFromFloats(0,0,0),o.setPosition(V.FromArray(e.position))),e.target&&o.setTarget&&o.setTarget(V.FromArray(e.target)),e.cameraRigMode){var a=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};o.setCameraRigMode(e.cameraRigMode,a)}if(e.animations){for(var l=0;l<e.animations.length;l++){var c=e.animations[l],u=s("BABYLON.Animation");u&&o.animations.push(u.Parse(c))}qe.ParseAnimationRanges(o,e,i)}return e.autoAnimate&&i.beginAnimation(o,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),void 0!==e.isEnabled&&o.setEnabled(e.isEnabled),o},t.prototype._calculateHandednessMultiplier=function(){var e=this.getScene().useRightHandedSystem?-1:1;return this.parent&&this.parent._getWorldMatrixDeterminant()<0&&(e*=-1),e},t._CreateDefaultParsedCamera=function(e,t){throw He("UniversalCamera")},t.PERSPECTIVE_CAMERA=u.PERSPECTIVE_CAMERA,t.ORTHOGRAPHIC_CAMERA=u.ORTHOGRAPHIC_CAMERA,t.FOVMODE_VERTICAL_FIXED=u.FOVMODE_VERTICAL_FIXED,t.FOVMODE_HORIZONTAL_FIXED=u.FOVMODE_HORIZONTAL_FIXED,t.RIG_MODE_NONE=u.RIG_MODE_NONE,t.RIG_MODE_STEREOSCOPIC_ANAGLYPH=u.RIG_MODE_STEREOSCOPIC_ANAGLYPH,t.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=u.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL,t.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=u.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,t.RIG_MODE_STEREOSCOPIC_OVERUNDER=u.RIG_MODE_STEREOSCOPIC_OVERUNDER,t.RIG_MODE_STEREOSCOPIC_INTERLACED=u.RIG_MODE_STEREOSCOPIC_INTERLACED,t.RIG_MODE_VR=u.RIG_MODE_VR,t.RIG_MODE_CUSTOM=u.RIG_MODE_CUSTOM,t.ForceAttachControlToAlwaysPreventDefault=!1,v([Fe("position")],t.prototype,"_position",void 0),v([Fe("upVector")],t.prototype,"_upVector",void 0),v([Ie()],t.prototype,"orthoLeft",null),v([Ie()],t.prototype,"orthoRight",null),v([Ie()],t.prototype,"orthoBottom",null),v([Ie()],t.prototype,"orthoTop",null),v([Ie()],t.prototype,"fov",void 0),v([Ie()],t.prototype,"projectionPlaneTilt",void 0),v([Ie()],t.prototype,"minZ",void 0),v([Ie()],t.prototype,"maxZ",void 0),v([Ie()],t.prototype,"inertia",void 0),v([Ie()],t.prototype,"mode",null),v([Ie()],t.prototype,"layerMask",void 0),v([Ie()],t.prototype,"fovMode",void 0),v([Ie()],t.prototype,"cameraRigMode",void 0),v([Ie()],t.prototype,"interaxialDistance",void 0),v([Ie()],t.prototype,"isStereoscopicSideBySide",void 0),t}(qe),eo=function(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0},to=function(){function e(e,t,i){this.vectors=C.BuildArray(8,V.Zero),this.center=V.Zero(),this.centerWorld=V.Zero(),this.extendSize=V.Zero(),this.extendSizeWorld=V.Zero(),this.directions=C.BuildArray(3,V.Zero),this.vectorsWorld=C.BuildArray(8,V.Zero),this.minimumWorld=V.Zero(),this.maximumWorld=V.Zero(),this.minimum=V.Zero(),this.maximum=V.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}return e.prototype.reConstruct=function(e,t,i){var r=e.x,n=e.y,o=e.z,a=t.x,s=t.y,l=t.z,c=this.vectors;this.minimum.copyFromFloats(r,n,o),this.maximum.copyFromFloats(a,s,l),c[0].copyFromFloats(r,n,o),c[1].copyFromFloats(a,s,l),c[2].copyFromFloats(a,n,o),c[3].copyFromFloats(r,s,o),c[4].copyFromFloats(r,n,l),c[5].copyFromFloats(a,s,o),c[6].copyFromFloats(r,s,l),c[7].copyFromFloats(a,n,l),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||z.IdentityReadOnly,this._update(this._worldMatrix)},e.prototype.scale=function(t){var i=e._TmpVector3,r=this.maximum.subtractToRef(this.minimum,i[0]),n=r.length();r.normalizeFromLength(n);var o=n*t,a=r.scaleInPlace(.5*o),s=this.center.subtractToRef(a,i[1]),l=this.center.addToRef(a,i[2]);return this.reConstruct(s,l,this._worldMatrix),this},e.prototype.getWorldMatrix=function(){return this._worldMatrix},e.prototype._update=function(e){var t=this.minimumWorld,i=this.maximumWorld,r=this.directions,n=this.vectorsWorld,o=this.vectors;if(e.isIdentity()){for(t.copyFrom(this.minimum),i.copyFrom(this.maximum),a=0;a<8;++a)n[a].copyFrom(o[a]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(var a=0;a<8;++a){var s=n[a];V.TransformCoordinatesToRef(o[a],e,s),t.minimizeInPlace(s),i.maximizeInPlace(s)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}V.FromArrayToRef(e.m,0,r[0]),V.FromArrayToRef(e.m,4,r[1]),V.FromArrayToRef(e.m,8,r[2]),this._worldMatrix=e},e.prototype.isInFrustum=function(t){return e.IsInFrustum(this.vectorsWorld,t)},e.prototype.isCompletelyInFrustum=function(t){return e.IsCompletelyInFrustum(this.vectorsWorld,t)},e.prototype.intersectsPoint=function(e){var t=this.minimumWorld,i=this.maximumWorld,r=t.x,n=t.y,o=t.z,a=i.x,s=i.y,l=i.z,c=e.x,u=e.y,h=e.z,d=-A;return!(a-c<d||d>c-r||s-u<d||d>u-n||l-h<d||d>h-o)},e.prototype.intersectsSphere=function(t){return e.IntersectsSphere(this.minimumWorld,this.maximumWorld,t.centerWorld,t.radiusWorld)},e.prototype.intersectsMinMax=function(e,t){var i=this.minimumWorld,r=this.maximumWorld,n=i.x,o=i.y,a=i.z,s=r.x,l=r.y,c=r.z,u=e.x,h=e.y,d=e.z,p=t.x,f=t.y,_=t.z;return!(s<u||n>p||l<h||o>f||c<d||a>_)},e.prototype.dispose=function(){var e,t;null===(e=this._drawWrapperFront)||void 0===e||e.dispose(),null===(t=this._drawWrapperBack)||void 0===t||t.dispose()},e.Intersects=function(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)},e.IntersectsSphere=function(t,i,r,n){var o=e._TmpVector3[0];return V.ClampToRef(r,t,i,o),V.DistanceSquared(r,o)<=n*n},e.IsCompletelyInFrustum=function(e,t){for(var i=0;i<6;++i)for(var r=t[i],n=0;n<8;++n)if(r.dotCoordinate(e[n])<0)return!1;return!0},e.IsInFrustum=function(e,t){for(var i=0;i<6;++i){for(var r=!0,n=t[i],o=0;o<8;++o)if(n.dotCoordinate(e[o])>=0){r=!1;break}if(r)return!1}return!0},e._TmpVector3=C.BuildArray(3,V.Zero),e}(),io=function(){function e(e,t,i){this.center=V.Zero(),this.centerWorld=V.Zero(),this.minimum=V.Zero(),this.maximum=V.Zero(),this.reConstruct(e,t,i)}return e.prototype.reConstruct=function(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);var r=V.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*r,this._update(i||z.IdentityReadOnly)},e.prototype.scale=function(t){var i=this.radius*t,r=e._TmpVector3,n=r[0].setAll(i),o=this.center.subtractToRef(n,r[1]),a=this.center.addToRef(n,r[2]);return this.reConstruct(o,a,this._worldMatrix),this},e.prototype.getWorldMatrix=function(){return this._worldMatrix},e.prototype._update=function(t){if(t.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{V.TransformCoordinatesToRef(this.center,t,this.centerWorld);var i=e._TmpVector3[0];V.TransformNormalFromFloatsToRef(1,1,1,t,i),this.radiusWorld=Math.max(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z))*this.radius}},e.prototype.isInFrustum=function(e){for(var t=this.centerWorld,i=this.radiusWorld,r=0;r<6;r++)if(e[r].dotCoordinate(t)<=-i)return!1;return!0},e.prototype.isCenterInFrustum=function(e){for(var t=this.centerWorld,i=0;i<6;i++)if(e[i].dotCoordinate(t)<0)return!1;return!0},e.prototype.intersectsPoint=function(e){var t=V.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld<t)},e.Intersects=function(e,t){var i=V.DistanceSquared(e.centerWorld,t.centerWorld),r=e.radiusWorld+t.radiusWorld;return!(r*r<i)},e.CreateFromCenterAndRadius=function(t,i,r){this._TmpVector3[0].copyFrom(t),this._TmpVector3[1].copyFromFloats(0,0,i),this._TmpVector3[2].copyFrom(t),this._TmpVector3[0].addInPlace(this._TmpVector3[1]),this._TmpVector3[2].subtractInPlace(this._TmpVector3[1]);var n=new e(this._TmpVector3[0],this._TmpVector3[2]);return n._worldMatrix=r||z.Identity(),n},e._TmpVector3=C.BuildArray(3,V.Zero),e}(),ro={min:0,max:0},no={min:0,max:0},oo=function(e,t,i){var r=V.Dot(t.centerWorld,e),n=Math.abs(V.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(V.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(V.Dot(t.directions[2],e))*t.extendSize.z;i.min=r-n,i.max=r+n},ao=function(e,t,i){return oo(e,t,ro),oo(e,i,no),!(ro.min>no.max||no.min>ro.max)},so=function(){function e(e,t,i){this._isLocked=!1,this.boundingBox=new to(e,t,i),this.boundingSphere=new io(e,t,i)}return e.prototype.reConstruct=function(e,t,i){this.boundingBox.reConstruct(e,t,i),this.boundingSphere.reConstruct(e,t,i)},Object.defineProperty(e.prototype,"minimum",{get:function(){return this.boundingBox.minimum},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maximum",{get:function(){return this.boundingBox.maximum},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isLocked",{get:function(){return this._isLocked},set:function(e){this._isLocked=e},enumerable:!1,configurable:!0}),e.prototype.update=function(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))},e.prototype.centerOn=function(t,i){var r=e._TmpVector3[0].copyFrom(t).subtractInPlace(i),n=e._TmpVector3[1].copyFrom(t).addInPlace(i);return this.boundingBox.reConstruct(r,n,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(r,n,this.boundingBox.getWorldMatrix()),this},e.prototype.encapsulate=function(e){var t=V.Minimize(this.minimum,e),i=V.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this},e.prototype.encapsulateBoundingInfo=function(e){var t=H.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);var i=H.Vector3[0];return V.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),V.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this},e.prototype.scale=function(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this},e.prototype.isInFrustum=function(e,t){return void 0===t&&(t=u.MESHES_CULLINGSTRATEGY_STANDARD),!(t!==u.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION&&t!==u.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY||!this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(!(t!==u.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY&&t!==u.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY)||this.boundingBox.isInFrustum(e))},Object.defineProperty(e.prototype,"diagonalLength",{get:function(){var t=this.boundingBox;return t.maximumWorld.subtractToRef(t.minimumWorld,e._TmpVector3[0]).length()},enumerable:!1,configurable:!0}),e.prototype.isCompletelyInFrustum=function(e){return this.boundingBox.isCompletelyInFrustum(e)},e.prototype._checkCollision=function(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)},e.prototype.intersectsPoint=function(e){return!!this.boundingSphere.centerWorld&&!!this.boundingSphere.intersectsPoint(e)&&!!this.boundingBox.intersectsPoint(e)},e.prototype.intersects=function(e,t){if(!io.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!to.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;var i=this.boundingBox,r=e.boundingBox;return!!(ao(i.directions[0],i,r)&&ao(i.directions[1],i,r)&&ao(i.directions[2],i,r)&&ao(r.directions[0],i,r)&&ao(r.directions[1],i,r)&&ao(r.directions[2],i,r)&&ao(V.Cross(i.directions[0],r.directions[0]),i,r)&&ao(V.Cross(i.directions[0],r.directions[1]),i,r)&&ao(V.Cross(i.directions[0],r.directions[2]),i,r)&&ao(V.Cross(i.directions[1],r.directions[0]),i,r)&&ao(V.Cross(i.directions[1],r.directions[1]),i,r)&&ao(V.Cross(i.directions[1],r.directions[2]),i,r)&&ao(V.Cross(i.directions[2],r.directions[0]),i,r)&&ao(V.Cross(i.directions[2],r.directions[1]),i,r)&&ao(V.Cross(i.directions[2],r.directions[2]),i,r))},e._TmpVector3=C.BuildArray(2,V.Zero),e}(),lo=function(){function e(){}return e.extractMinAndMaxIndexed=function(e,t,i,r,n,o){for(var a=i;a<i+r;a++){var s=3*t[a],l=e[s],c=e[s+1],u=e[s+2];n.minimizeInPlaceFromFloats(l,c,u),o.maximizeInPlaceFromFloats(l,c,u)}},e.extractMinAndMax=function(e,t,i,r,n,o){for(var a=t,s=t*r;a<t+i;a++,s+=r){var l=e[s],c=e[s+1],u=e[s+2];n.minimizeInPlaceFromFloats(l,c,u),o.maximizeInPlaceFromFloats(l,c,u)}},v([ze.filter((function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var i=e[0],r=e[1];return!Array.isArray(i)&&!Array.isArray(r)}))],e,"extractMinAndMaxIndexed",null),v([ze.filter((function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var i=e[0];return!Array.isArray(i)}))],e,"extractMinAndMax",null),e}();function co(e,t,i,r,n){void 0===n&&(n=null);var o=new V(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new V(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return lo.extractMinAndMaxIndexed(e,t,i,r,o,a),n&&(o.x-=o.x*n.x+n.y,o.y-=o.y*n.x+n.y,o.z-=o.z*n.x+n.y,a.x+=a.x*n.x+n.y,a.y+=a.y*n.x+n.y,a.z+=a.z*n.x+n.y),{minimum:o,maximum:a}}function uo(e,t,i,r,n){void 0===r&&(r=null);var o=new V(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new V(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return n||(n=3),lo.extractMinAndMax(e,t,i,n,o,a),r&&(o.x-=o.x*r.x+r.y,o.y-=o.y*r.x+r.y,o.z-=o.z*r.x+r.y,a.x+=a.x*r.x+r.y,a.y+=a.y*r.x+r.y,a.z+=a.z*r.x+r.y),{minimum:o,maximum:a}}var ho=function(){function e(e,t){void 0===t&&(t=!0),this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!0,this._wasPreviouslyUsingInstances=null,this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}return e.GetEffect=function(e){return void 0===e.getPipelineContext?e.effect:e},e.prototype.setEffect=function(e,t,i){var r;void 0===i&&(i=!0),this.effect=e,void 0!==t&&(this.defines=t),i&&(null===(r=this.drawContext)||void 0===r||r.reset())},e.prototype.dispose=function(){var e;null===(e=this.drawContext)||void 0===e||e.dispose()},e}(),po=function(){function e(e,t,i,r,n,o,a,s,l){void 0===s&&(s=!0),void 0===l&&(l=!0),this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=r,this.indexCount=n,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=o,this._renderingMesh=a||o,l&&o.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=o.subMeshes.length-1,s&&(this.refreshBoundingInfo(),o.computeWorldMatrix(!0))}return Object.defineProperty(e.prototype,"materialDefines",{get:function(){var e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:null===(e=this._getDrawWrapper())||void 0===e?void 0:e.defines},set:function(e){var t;(null!==(t=this._mainDrawWrapperOverride)&&void 0!==t?t:this._getDrawWrapper(void 0,!0)).defines=e},enumerable:!1,configurable:!0}),e.prototype._getDrawWrapper=function(e,t){void 0===t&&(t=!1),e=null!=e?e:this._engine.currentRenderPassId;var i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new ho(this._mesh.getScene().getEngine())),i},e.prototype._removeDrawWrapper=function(e,t){var i;void 0===t&&(t=!0),t&&(null===(i=this._drawWrappers[e])||void 0===i||i.dispose()),this._drawWrappers[e]=void 0},Object.defineProperty(e.prototype,"effect",{get:function(){var e,t;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:null!==(t=null===(e=this._getDrawWrapper())||void 0===e?void 0:e.effect)&&void 0!==t?t:null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"_drawWrapper",{get:function(){var e;return null!==(e=this._mainDrawWrapperOverride)&&void 0!==e?e:this._getDrawWrapper(void 0,!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"_drawWrapperOverride",{get:function(){return this._mainDrawWrapperOverride},enumerable:!1,configurable:!0}),e.prototype._setMainDrawWrapperOverride=function(e){this._mainDrawWrapperOverride=e},e.prototype.setEffect=function(e,t,i,r){void 0===t&&(t=null),void 0===r&&(r=!0);var n=this._drawWrapper;n.setEffect(e,t,r),void 0!==i&&(n.materialContext=i),e||(n.defines=null,n.materialContext=void 0)},e.prototype.resetDrawCache=function(e){if(this._drawWrappers){if(void 0!==e)return void this._removeDrawWrapper(e);for(var t=0,i=this._drawWrappers;t<i.length;t++){var r=i[t];null==r||r.dispose()}}this._drawWrappers=[]},e.AddToMesh=function(t,i,r,n,o,a,s,l){return void 0===l&&(l=!0),new e(t,i,r,n,o,a,s,l)},Object.defineProperty(e.prototype,"IsGlobal",{get:function(){return 0===this.verticesStart&&this.verticesCount===this._mesh.getTotalVertices()&&0===this.indexStart&&this.indexCount===this._mesh.getTotalIndices()},enumerable:!1,configurable:!0}),e.prototype.getBoundingInfo=function(){return this.IsGlobal||this._mesh.hasThinInstances?this._mesh.getBoundingInfo():this._boundingInfo},e.prototype.setBoundingInfo=function(e){return this._boundingInfo=e,this},e.prototype.getMesh=function(){return this._mesh},e.prototype.getRenderingMesh=function(){return this._renderingMesh},e.prototype.getReplacementMesh=function(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null},e.prototype.getEffectiveMesh=function(){return(this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null)||this._renderingMesh},e.prototype.getMaterial=function(e){var t;void 0===e&&(e=!0);var i=null!==(t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId))&&void 0!==t?t:this._renderingMesh.material;if(!i)return e?this._mesh.getScene().defaultMaterial:null;if(this._isMultiMaterial(i)){var r=i.getSubMaterial(this.materialIndex);return this._currentMaterial!==r&&(this._currentMaterial=r,this.resetDrawCache()),r}return i},e.prototype._isMultiMaterial=function(e){return void 0!==e.getSubMaterial},e.prototype.refreshBoundingInfo=function(e){if(void 0===e&&(e=null),this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(Nr.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;var t,i=this._renderingMesh.getIndices();if(0===this.indexStart&&this.indexCount===i.length){var r=this._renderingMesh.getBoundingInfo();t={minimum:r.minimum.clone(),maximum:r.maximum.clone()}}else t=co(e,i,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(t.minimum,t.maximum):this._boundingInfo=new so(t.minimum,t.maximum),this},e.prototype._checkCollision=function(e){return this.getBoundingInfo()._checkCollision(e)},e.prototype.updateBoundingInfo=function(e){var t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this},e.prototype.isInFrustum=function(e){var t=this.getBoundingInfo();return!!t&&t.isInFrustum(e,this._mesh.cullingStrategy)},e.prototype.isCompletelyInFrustum=function(e){var t=this.getBoundingInfo();return!!t&&t.isCompletelyInFrustum(e)},e.prototype.render=function(e){return this._renderingMesh.render(this,e,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this},e.prototype._getLinesIndexBuffer=function(e,t){if(!this._linesIndexBuffer){for(var i=[],r=this.indexStart;r<this.indexStart+this.indexCount;r+=3)i.push(e[r],e[r+1],e[r+1],e[r+2],e[r+2],e[r]);this._linesIndexBuffer=t.createIndexBuffer(i),this._linesIndexCount=i.length}return this._linesIndexBuffer},e.prototype.canIntersects=function(e){var t=this.getBoundingInfo();return!!t&&e.intersectsBox(t.boundingBox)},e.prototype.intersects=function(e,t,i,r,n){var o=this.getMaterial();if(!o)return null;var a=3,s=!1;switch(o.fillMode){case u.MATERIAL_PointListDrawMode:case u.MATERIAL_LineLoopDrawMode:case u.MATERIAL_LineStripDrawMode:case u.MATERIAL_TriangleFanDrawMode:return null;case u.MATERIAL_TriangleStripDrawMode:a=1,s=!0}return o.fillMode===u.MATERIAL_LineListDrawMode?i.length?this._intersectLines(e,t,i,this._mesh.intersectionThreshold,r):this._intersectUnIndexedLines(e,t,i,this._mesh.intersectionThreshold,r):!i.length&&this._mesh._unIndexed?this._intersectUnIndexedTriangles(e,t,i,r,n):this._intersectTriangles(e,t,i,a,s,r,n)},e.prototype._intersectLines=function(e,t,i,r,n){for(var o=null,a=this.indexStart;a<this.indexStart+this.indexCount;a+=2){var s=t[i[a]],l=t[i[a+1]],c=e.intersectionSegment(s,l,r);if(!(c<0)&&(n||!o||c<o.distance)&&((o=new eo(null,null,c)).faceId=a/2,n))break}return o},e.prototype._intersectUnIndexedLines=function(e,t,i,r,n){for(var o=null,a=this.verticesStart;a<this.verticesStart+this.verticesCount;a+=2){var s=t[a],l=t[a+1],c=e.intersectionSegment(s,l,r);if(!(c<0)&&(n||!o||c<o.distance)&&((o=new eo(null,null,c)).faceId=a/2,n))break}return o},e.prototype._intersectTriangles=function(e,t,i,r,n,o,a){for(var s=null,l=-1,c=this.indexStart;c<this.indexStart+this.indexCount-(3-r);c+=r){l++;var u=i[c],h=i[c+1],d=i[c+2];if(n&&4294967295===d)c+=2;else{var p=t[u],f=t[h],_=t[d];if(p&&f&&_&&(!a||a(p,f,_,e,u,h,d))){var m=e.intersectsTriangle(p,f,_);if(m){if(m.distance<0)continue;if((o||!s||m.distance<s.distance)&&((s=m).faceId=l,o))break}}}}return s},e.prototype._intersectUnIndexedTriangles=function(e,t,i,r,n){for(var o=null,a=this.verticesStart;a<this.verticesStart+this.verticesCount;a+=3){var s=t[a],l=t[a+1],c=t[a+2];if(!n||n(s,l,c,e,-1,-1,-1)){var u=e.intersectsTriangle(s,l,c);if(u){if(u.distance<0)continue;if((r||!o||u.distance<o.distance)&&((o=u).faceId=a/3,r))break}}}return o},e.prototype._rebuild=function(){this._linesIndexBuffer&&(this._linesIndexBuffer=null)},e.prototype.clone=function(t,i){var r=new e(this.materialIndex,this.verticesStart,this.verticesCount,this.indexStart,this.indexCount,t,i,!1);if(!this.IsGlobal){var n=this.getBoundingInfo();if(!n)return r;r._boundingInfo=new so(n.minimum,n.maximum)}return r},e.prototype.dispose=function(){this._linesIndexBuffer&&(this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null);var e=this._mesh.subMeshes.indexOf(this);this._mesh.subMeshes.splice(e,1),this.resetDrawCache()},e.prototype.getClassName=function(){return"SubMesh"},e.CreateFromIndices=function(t,i,r,n,o,a){void 0===a&&(a=!0);for(var s=Number.MAX_VALUE,l=-Number.MAX_VALUE,c=(o||n).getIndices(),u=i;u<i+r;u++){var h=c[u];h<s&&(s=h),h>l&&(l=h)}return new e(t,s,l-s+1,i,r,n,o,a)},e}(),fo=function(){},_o=function(){function e(){this.uniqueId=0,this.metadata={},this._applyTo=qn(this._applyToCoroutine.bind(this)),this.uniqueId=e._UniqueIDGenerator,e._UniqueIDGenerator++}return e.prototype.set=function(e,t){switch(e.length||ae.Warn("Setting vertex data kind '".concat(t,"' with an empty array")),t){case Nr.PositionKind:this.positions=e;break;case Nr.NormalKind:this.normals=e;break;case Nr.TangentKind:this.tangents=e;break;case Nr.UVKind:this.uvs=e;break;case Nr.UV2Kind:this.uvs2=e;break;case Nr.UV3Kind:this.uvs3=e;break;case Nr.UV4Kind:this.uvs4=e;break;case Nr.UV5Kind:this.uvs5=e;break;case Nr.UV6Kind:this.uvs6=e;break;case Nr.ColorKind:this.colors=e;break;case Nr.MatricesIndicesKind:this.matricesIndices=e;break;case Nr.MatricesWeightsKind:this.matricesWeights=e;break;case Nr.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case Nr.MatricesWeightsExtraKind:this.matricesWeightsExtra=e}},e.prototype.applyToMesh=function(e,t){return this._applyTo(e,t,!1),this},e.prototype.applyToGeometry=function(e,t){return this._applyTo(e,t,!1),this},e.prototype.updateMesh=function(e){return this._update(e),this},e.prototype.updateGeometry=function(e){return this._update(e),this},e.prototype._applyToCoroutine=function(e,t,i){var r,n,o,a;return void 0===t&&(t=!1),b(this,(function(s){switch(s.label){case 0:return this.positions?(e.setVerticesData(Nr.PositionKind,this.positions,t),i?[4]:[3,2]):[3,2];case 1:s.sent(),s.label=2;case 2:return this.normals?(e.setVerticesData(Nr.NormalKind,this.normals,t),i?[4]:[3,4]):[3,4];case 3:s.sent(),s.label=4;case 4:return this.tangents?(e.setVerticesData(Nr.TangentKind,this.tangents,t),i?[4]:[3,6]):[3,6];case 5:s.sent(),s.label=6;case 6:return this.uvs?(e.setVerticesData(Nr.UVKind,this.uvs,t),i?[4]:[3,8]):[3,8];case 7:s.sent(),s.label=8;case 8:return this.uvs2?(e.setVerticesData(Nr.UV2Kind,this.uvs2,t),i?[4]:[3,10]):[3,10];case 9:s.sent(),s.label=10;case 10:return this.uvs3?(e.setVerticesData(Nr.UV3Kind,this.uvs3,t),i?[4]:[3,12]):[3,12];case 11:s.sent(),s.label=12;case 12:return this.uvs4?(e.setVerticesData(Nr.UV4Kind,this.uvs4,t),i?[4]:[3,14]):[3,14];case 13:s.sent(),s.label=14;case 14:return this.uvs5?(e.setVerticesData(Nr.UV5Kind,this.uvs5,t),i?[4]:[3,16]):[3,16];case 15:s.sent(),s.label=16;case 16:return this.uvs6?(e.setVerticesData(Nr.UV6Kind,this.uvs6,t),i?[4]:[3,18]):[3,18];case 17:s.sent(),s.label=18;case 18:return this.colors?(e.setVerticesData(Nr.ColorKind,this.colors,t),this.hasVertexAlpha&&void 0!==e.hasVertexAlpha&&(e.hasVertexAlpha=!0),i?[4]:[3,20]):[3,20];case 19:s.sent(),s.label=20;case 20:return this.matricesIndices?(e.setVerticesData(Nr.MatricesIndicesKind,this.matricesIndices,t),i?[4]:[3,22]):[3,22];case 21:s.sent(),s.label=22;case 22:return this.matricesWeights?(e.setVerticesData(Nr.MatricesWeightsKind,this.matricesWeights,t),i?[4]:[3,24]):[3,24];case 23:s.sent(),s.label=24;case 24:return this.matricesIndicesExtra?(e.setVerticesData(Nr.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i?[4]:[3,26]):[3,26];case 25:s.sent(),s.label=26;case 26:return this.matricesWeightsExtra?(e.setVerticesData(Nr.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i?[4]:[3,28]):[3,28];case 27:s.sent(),s.label=28;case 28:return this.indices?(e.setIndices(this.indices,null,t),i?[4]:[3,30]):[3,31];case 29:s.sent(),s.label=30;case 30:return[3,32];case 31:e.setIndices([],null),s.label=32;case 32:if(e.subMeshes&&this.materialInfos&&this.materialInfos.length>1)for((r=e).subMeshes=[],n=0,o=this.materialInfos;n<o.length;n++)a=o[n],new po(a.materialIndex,a.verticesStart,a.verticesCount,a.indexStart,a.indexCount,r);return[2,this]}}))},e.prototype._update=function(e,t,i){return this.positions&&e.updateVerticesData(Nr.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(Nr.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(Nr.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(Nr.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(Nr.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(Nr.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(Nr.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(Nr.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(Nr.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(Nr.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(Nr.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(Nr.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(Nr.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(Nr.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this},e._TransformVector3Coordinates=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=e.length);for(var n=H.Vector3[0],o=H.Vector3[1],a=i;a<i+r;a+=3)V.FromArrayToRef(e,a,n),V.TransformCoordinatesToRef(n,t,o),e[a]=o.x,e[a+1]=o.y,e[a+2]=o.z},e._TransformVector3Normals=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=e.length);for(var n=H.Vector3[0],o=H.Vector3[1],a=i;a<i+r;a+=3)V.FromArrayToRef(e,a,n),V.TransformNormalToRef(n,t,o),e[a]=o.x,e[a+1]=o.y,e[a+2]=o.z},e._TransformVector4Normals=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=e.length);for(var n=H.Vector4[0],o=H.Vector4[1],a=i;a<i+r;a+=4)k.FromArrayToRef(e,a,n),k.TransformNormalToRef(n,t,o),e[a]=o.x,e[a+1]=o.y,e[a+2]=o.z,e[a+3]=o.w},e._FlipFaces=function(e,t,i){void 0===t&&(t=0),void 0===i&&(i=e.length);for(var r=t;r<t+i;r+=3){var n=e[r+1];e[r+1]=e[r+2],e[r+2]=n}},e.prototype.transform=function(t){var i=t.determinant()<0;return this.positions&&e._TransformVector3Coordinates(this.positions,t),this.normals&&e._TransformVector3Normals(this.normals,t),this.tangents&&e._TransformVector4Normals(this.tangents,t),i&&this.indices&&e._FlipFaces(this.indices),this},e.prototype.splitBasedOnMaterialID=function(){if(!this.materialInfos||this.materialInfos.length<2)return[this];for(var t=[],i=0,r=this.materialInfos;i<r.length;i++){var n=r[i],o=new e;if(this.positions&&(o.positions=this.positions.slice(3*n.verticesStart,3*(n.verticesCount+n.verticesStart))),this.normals&&(o.normals=this.normals.slice(3*n.verticesStart,3*(n.verticesCount+n.verticesStart))),this.tangents&&(o.tangents=this.tangents.slice(4*n.verticesStart,4*(n.verticesCount+n.verticesStart))),this.colors&&(o.colors=this.colors.slice(4*n.verticesStart,4*(n.verticesCount+n.verticesStart))),this.uvs&&(o.uvs=this.uvs.slice(2*n.verticesStart,2*(n.verticesCount+n.verticesStart))),this.uvs2&&(o.uvs2=this.uvs2.slice(2*n.verticesStart,2*(n.verticesCount+n.verticesStart))),this.uvs3&&(o.uvs3=this.uvs3.slice(2*n.verticesStart,2*(n.verticesCount+n.verticesStart))),this.uvs4&&(o.uvs4=this.uvs4.slice(2*n.verticesStart,2*(n.verticesCount+n.verticesStart))),this.uvs5&&(o.uvs5=this.uvs5.slice(2*n.verticesStart,2*(n.verticesCount+n.verticesStart))),this.uvs6&&(o.uvs6=this.uvs6.slice(2*n.verticesStart,2*(n.verticesCount+n.verticesStart))),this.matricesIndices&&(o.matricesIndices=this.matricesIndices.slice(4*n.verticesStart,4*(n.verticesCount+n.verticesStart))),this.matricesIndicesExtra&&(o.matricesIndicesExtra=this.matricesIndicesExtra.slice(4*n.verticesStart,4*(n.verticesCount+n.verticesStart))),this.matricesWeights&&(o.matricesWeights=this.matricesWeights.slice(4*n.verticesStart,4*(n.verticesCount+n.verticesStart))),this.matricesWeightsExtra&&(o.matricesWeightsExtra=this.matricesWeightsExtra.slice(4*n.verticesStart,4*(n.verticesCount+n.verticesStart))),this.indices){o.indices=[];for(var a=n.indexStart;a<n.indexStart+n.indexCount;a++)o.indices.push(this.indices[a]-n.verticesStart)}var s=new fo;s.indexStart=0,s.indexCount=o.indices?o.indices.length:0,s.materialIndex=n.materialIndex,s.verticesStart=0,s.verticesCount=(o.positions?o.positions.length:0)/3,o.materialInfos=[s],t.push(o)}return t},e.prototype.merge=function(e,t,i,r,n){void 0===t&&(t=!1),void 0===i&&(i=!1),void 0===r&&(r=!1),void 0===n&&(n=!1);var o=Array.isArray(e)?e.map((function(e){return{vertexData:e}})):[{vertexData:e}];return Kn(this._mergeCoroutine(void 0,o,t,!1,i,r,n))},e.prototype._mergeCoroutine=function(t,i,r,n,o,a,s){var l,c,u,h,d,p,f,_,m,g,v,y,T,E,S,x,A,C,R,P,I,M,O,D,N,F,L,w,B,U,V,k,G,z,W,H,X,j,Y,K,Q,q;return void 0===r&&(r=!1),void 0===a&&(a=!1),void 0===s&&(s=!1),b(this,(function(b){switch(b.label){case 0:if(this._validate(),l=i.map((function(e){return e.vertexData})),c=this,s)for(u=0,h=l;u<h.length;u++)(H=h[u])&&(H._validate(),!this.normals&&H.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&H.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&H.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&H.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&H.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&H.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&H.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&H.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&H.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&H.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&H.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&H.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&H.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(d=0,p=l;d<p.length;d++)if(H=p[d])if(s)this.normals&&!H.normals&&(H.normals=new Float32Array(H.positions.length)),this.tangents&&!H.tangents&&(H.tangents=new Float32Array(H.positions.length/3*4)),this.uvs&&!H.uvs&&(H.uvs=new Float32Array(H.positions.length/3*2)),this.uvs2&&!H.uvs2&&(H.uvs2=new Float32Array(H.positions.length/3*2)),this.uvs3&&!H.uvs3&&(H.uvs3=new Float32Array(H.positions.length/3*2)),this.uvs4&&!H.uvs4&&(H.uvs4=new Float32Array(H.positions.length/3*2)),this.uvs5&&!H.uvs5&&(H.uvs5=new Float32Array(H.positions.length/3*2)),this.uvs6&&!H.uvs6&&(H.uvs6=new Float32Array(H.positions.length/3*2)),this.colors&&!H.colors&&(H.colors=new Float32Array(H.positions.length/3*4),H.colors.fill(1)),this.matricesIndices&&!H.matricesIndices&&(H.matricesIndices=new Float32Array(H.positions.length/3*4)),this.matricesWeights&&!H.matricesWeights&&(H.matricesWeights=new Float32Array(H.positions.length/3*4)),this.matricesIndicesExtra&&!H.matricesIndicesExtra&&(H.matricesIndicesExtra=new Float32Array(H.positions.length/3*4)),this.matricesWeightsExtra&&!H.matricesWeightsExtra&&(H.matricesWeightsExtra=new Float32Array(H.positions.length/3*4));else if(H._validate(),!this.normals!=!H.normals||!this.tangents!=!H.tangents||!this.uvs!=!H.uvs||!this.uvs2!=!H.uvs2||!this.uvs3!=!H.uvs3||!this.uvs4!=!H.uvs4||!this.uvs5!=!H.uvs5||!this.uvs6!=!H.uvs6||!this.colors!=!H.colors||!this.matricesIndices!=!H.matricesIndices||!this.matricesWeights!=!H.matricesWeights||!this.matricesIndicesExtra!=!H.matricesIndicesExtra||!this.matricesWeightsExtra!=!H.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes");if(a){for(f=0,_=0,m=0,g=[],v=null,y=[],T=0,E=this.splitBasedOnMaterialID();T<E.length;T++)P=E[T],y.push({vertexData:P,transform:t});for(S=0,x=i;S<x.length;S++)if((A=x[S]).vertexData)for(C=0,R=A.vertexData.splitBasedOnMaterialID();C<R.length;C++)P=R[C],y.push({vertexData:P,transform:A.transform});for(y.sort((function(e,t){var i=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,r=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return i>r?1:i===r?0:-1})),I=0,M=y;I<M.length;I++)O=M[I],D=O.vertexData,f=D.materialInfos?D.materialInfos[0].materialIndex:0,v&&v.materialIndex===f?(v.indexCount+=D.indices.length,v.verticesCount+=D.positions.length/3):((N=new fo).materialIndex=f,N.indexStart=_,N.indexCount=D.indices.length,N.verticesStart=m,N.verticesCount=D.positions.length/3,g.push(N),v=N),_+=D.indices.length,m+=D.positions.length/3;F=y.splice(0,1)[0],c=F.vertexData,t=F.transform,l=y.map((function(e){return e.vertexData})),i=y,this.materialInfos=g}if(L=l.reduce((function(e,t){var i,r;return e+(null!==(r=null===(i=t.indices)||void 0===i?void 0:i.length)&&void 0!==r?r:0)}),null!==(K=null===(Y=c.indices)||void 0===Y?void 0:Y.length)&&void 0!==K?K:0),w=o||l.some((function(e){return e.indices===c.indices})),B=w?null===(Q=c.indices)||void 0===Q?void 0:Q.slice():c.indices,!(L>0))return[3,4];U=null!==(q=null==B?void 0:B.length)&&void 0!==q?q:0,B||(B=new Array(L)),B.length!==L&&(Array.isArray(B)?B.length=L:((V=r||B instanceof Uint32Array?new Uint32Array(L):new Uint16Array(L)).set(B),B=V),t&&t.determinant()<0&&e._FlipFaces(B,0,U)),k=c.positions?c.positions.length/3:0,G=0,z=i,b.label=1;case 1:if(!(G<z.length))return[3,4];if(W=z[G],H=W.vertexData,X=W.transform,!H.indices)return[3,3];for(j=0;j<H.indices.length;j++)B[U+j]=H.indices[j]+k;return X&&X.determinant()<0&&e._FlipFaces(B,U,H.indices.length),k+=H.positions.length/3,U+=H.indices.length,n?[4]:[3,3];case 2:b.sent(),b.label=3;case 3:return G++,[3,1];case 4:return this.indices=B,this.positions=e._MergeElement(Nr.PositionKind,c.positions,t,i.map((function(e){return[e.vertexData.positions,e.transform]}))),n?[4]:[3,6];case 5:b.sent(),b.label=6;case 6:return c.normals?(this.normals=e._MergeElement(Nr.NormalKind,c.normals,t,i.map((function(e){return[e.vertexData.normals,e.transform]}))),n?[4]:[3,8]):[3,8];case 7:b.sent(),b.label=8;case 8:return c.tangents?(this.tangents=e._MergeElement(Nr.TangentKind,c.tangents,t,i.map((function(e){return[e.vertexData.tangents,e.transform]}))),n?[4]:[3,10]):[3,10];case 9:b.sent(),b.label=10;case 10:return c.uvs?(this.uvs=e._MergeElement(Nr.UVKind,c.uvs,t,i.map((function(e){return[e.vertexData.uvs,e.transform]}))),n?[4]:[3,12]):[3,12];case 11:b.sent(),b.label=12;case 12:return c.uvs2?(this.uvs2=e._MergeElement(Nr.UV2Kind,c.uvs2,t,i.map((function(e){return[e.vertexData.uvs2,e.transform]}))),n?[4]:[3,14]):[3,14];case 13:b.sent(),b.label=14;case 14:return c.uvs3?(this.uvs3=e._MergeElement(Nr.UV3Kind,c.uvs3,t,i.map((function(e){return[e.vertexData.uvs3,e.transform]}))),n?[4]:[3,16]):[3,16];case 15:b.sent(),b.label=16;case 16:return c.uvs4?(this.uvs4=e._MergeElement(Nr.UV4Kind,c.uvs4,t,i.map((function(e){return[e.vertexData.uvs4,e.transform]}))),n?[4]:[3,18]):[3,18];case 17:b.sent(),b.label=18;case 18:return c.uvs5?(this.uvs5=e._MergeElement(Nr.UV5Kind,c.uvs5,t,i.map((function(e){return[e.vertexData.uvs5,e.transform]}))),n?[4]:[3,20]):[3,20];case 19:b.sent(),b.label=20;case 20:return c.uvs6?(this.uvs6=e._MergeElement(Nr.UV6Kind,c.uvs6,t,i.map((function(e){return[e.vertexData.uvs6,e.transform]}))),n?[4]:[3,22]):[3,22];case 21:b.sent(),b.label=22;case 22:return c.colors?(this.colors=e._MergeElement(Nr.ColorKind,c.colors,t,i.map((function(e){return[e.vertexData.colors,e.transform]}))),(void 0!==c.hasVertexAlpha||i.some((function(e){return void 0!==e.vertexData.hasVertexAlpha})))&&(this.hasVertexAlpha=c.hasVertexAlpha||i.some((function(e){return e.vertexData.hasVertexAlpha}))),n?[4]:[3,24]):[3,24];case 23:b.sent(),b.label=24;case 24:return c.matricesIndices?(this.matricesIndices=e._MergeElement(Nr.MatricesIndicesKind,c.matricesIndices,t,i.map((function(e){return[e.vertexData.matricesIndices,e.transform]}))),n?[4]:[3,26]):[3,26];case 25:b.sent(),b.label=26;case 26:return c.matricesWeights?(this.matricesWeights=e._MergeElement(Nr.MatricesWeightsKind,c.matricesWeights,t,i.map((function(e){return[e.vertexData.matricesWeights,e.transform]}))),n?[4]:[3,28]):[3,28];case 27:b.sent(),b.label=28;case 28:return c.matricesIndicesExtra?(this.matricesIndicesExtra=e._MergeElement(Nr.MatricesIndicesExtraKind,c.matricesIndicesExtra,t,i.map((function(e){return[e.vertexData.matricesIndicesExtra,e.transform]}))),n?[4]:[3,30]):[3,30];case 29:b.sent(),b.label=30;case 30:return c.matricesWeightsExtra&&(this.matricesWeightsExtra=e._MergeElement(Nr.MatricesWeightsExtraKind,c.matricesWeightsExtra,t,i.map((function(e){return[e.vertexData.matricesWeightsExtra,e.transform]})))),[2,this]}}))},e._MergeElement=function(t,i,r,n){var o=n.filter((function(e){return null!==e[0]&&void 0!==e[0]}));if(!i&&0==o.length)return i;if(!i)return this._MergeElement(t,o[0][0],o[0][1],o.slice(1));var a=o.reduce((function(e,t){return e+t[0].length}),i.length),s=t===Nr.PositionKind?e._TransformVector3Coordinates:t===Nr.NormalKind?e._TransformVector3Normals:t===Nr.TangentKind?e._TransformVector4Normals:function(){};if(i instanceof Float32Array){var l=new Float32Array(a);l.set(i),r&&s(l,r,0,i.length);for(var c=i.length,u=0,h=o;u<h.length;u++){var d=h[u],p=d[0],f=d[1];l.set(p,c),f&&s(l,f,c,p.length),c+=p.length}return l}for(var _=new Array(a),m=0;m<i.length;m++)_[m]=i[m];r&&s(_,r,0,i.length),c=i.length;for(var g=0,v=o;g<v.length;g++){var y=v[g],b=(p=y[0],y[1]);for(m=0;m<p.length;m++)_[c+m]=p[m];b&&s(_,b,c,p.length),c+=p.length}return _},e.prototype._validate=function(){if(!this.positions)throw new bt("Positions are required",yt.MeshInvalidPositionsError);var e=function(e,t){var i=Nr.DeduceStride(e);if(t.length%i!=0)throw new Error("The "+e+"s array count must be a multiple of "+i);return t.length/i},t=e(Nr.PositionKind,this.positions),i=function(i,r){var n=e(i,r);if(n!==t)throw new Error("The "+i+"s element count ("+n+") does not match the positions count ("+t+")")};this.normals&&i(Nr.NormalKind,this.normals),this.tangents&&i(Nr.TangentKind,this.tangents),this.uvs&&i(Nr.UVKind,this.uvs),this.uvs2&&i(Nr.UV2Kind,this.uvs2),this.uvs3&&i(Nr.UV3Kind,this.uvs3),this.uvs4&&i(Nr.UV4Kind,this.uvs4),this.uvs5&&i(Nr.UV5Kind,this.uvs5),this.uvs6&&i(Nr.UV6Kind,this.uvs6),this.colors&&i(Nr.ColorKind,this.colors),this.matricesIndices&&i(Nr.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(Nr.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(Nr.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(Nr.MatricesWeightsExtraKind,this.matricesWeightsExtra)},e.prototype.clone=function(){var t=this.serialize();return e.Parse(t)},e.prototype.serialize=function(){var e={};if(this.positions&&(e.positions=Array.from(this.positions)),this.normals&&(e.normals=Array.from(this.normals)),this.tangents&&(e.tangents=Array.from(this.tangents)),this.uvs&&(e.uvs=Array.from(this.uvs)),this.uvs2&&(e.uvs2=Array.from(this.uvs2)),this.uvs3&&(e.uvs3=Array.from(this.uvs3)),this.uvs4&&(e.uvs4=Array.from(this.uvs4)),this.uvs5&&(e.uvs5=Array.from(this.uvs5)),this.uvs6&&(e.uvs6=Array.from(this.uvs6)),this.colors&&(e.colors=Array.from(this.colors),e.hasVertexAlpha=this.hasVertexAlpha),this.matricesIndices&&(e.matricesIndices=Array.from(this.matricesIndices),e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=Array.from(this.indices),this.materialInfos){e.materialInfos=[];for(var t=0,i=this.materialInfos;t<i.length;t++){var r=i[t],n={indexStart:r.indexStart,indexCount:r.indexCount,materialIndex:r.materialIndex,verticesStart:r.verticesStart,verticesCount:r.verticesCount};e.materialInfos.push(n)}}return e},e.ExtractFromMesh=function(t,i,r){return e._ExtractFrom(t,i,r)},e.ExtractFromGeometry=function(t,i,r){return e._ExtractFrom(t,i,r)},e._ExtractFrom=function(t,i,r){var n=new e;return t.isVerticesDataPresent(Nr.PositionKind)&&(n.positions=t.getVerticesData(Nr.PositionKind,i,r)),t.isVerticesDataPresent(Nr.NormalKind)&&(n.normals=t.getVerticesData(Nr.NormalKind,i,r)),t.isVerticesDataPresent(Nr.TangentKind)&&(n.tangents=t.getVerticesData(Nr.TangentKind,i,r)),t.isVerticesDataPresent(Nr.UVKind)&&(n.uvs=t.getVerticesData(Nr.UVKind,i,r)),t.isVerticesDataPresent(Nr.UV2Kind)&&(n.uvs2=t.getVerticesData(Nr.UV2Kind,i,r)),t.isVerticesDataPresent(Nr.UV3Kind)&&(n.uvs3=t.getVerticesData(Nr.UV3Kind,i,r)),t.isVerticesDataPresent(Nr.UV4Kind)&&(n.uvs4=t.getVerticesData(Nr.UV4Kind,i,r)),t.isVerticesDataPresent(Nr.UV5Kind)&&(n.uvs5=t.getVerticesData(Nr.UV5Kind,i,r)),t.isVerticesDataPresent(Nr.UV6Kind)&&(n.uvs6=t.getVerticesData(Nr.UV6Kind,i,r)),t.isVerticesDataPresent(Nr.ColorKind)&&(n.colors=t.getVerticesData(Nr.ColorKind,i,r)),t.isVerticesDataPresent(Nr.MatricesIndicesKind)&&(n.matricesIndices=t.getVerticesData(Nr.MatricesIndicesKind,i,r)),t.isVerticesDataPresent(Nr.MatricesWeightsKind)&&(n.matricesWeights=t.getVerticesData(Nr.MatricesWeightsKind,i,r)),t.isVerticesDataPresent(Nr.MatricesIndicesExtraKind)&&(n.matricesIndicesExtra=t.getVerticesData(Nr.MatricesIndicesExtraKind,i,r)),t.isVerticesDataPresent(Nr.MatricesWeightsExtraKind)&&(n.matricesWeightsExtra=t.getVerticesData(Nr.MatricesWeightsExtraKind,i,r)),n.indices=t.getIndices(i,r),n},e.CreateRibbon=function(e){throw He("ribbonBuilder")},e.CreateBox=function(e){throw He("boxBuilder")},e.CreateTiledBox=function(e){throw He("tiledBoxBuilder")},e.CreateTiledPlane=function(e){throw He("tiledPlaneBuilder")},e.CreateSphere=function(e){throw He("sphereBuilder")},e.CreateCylinder=function(e){throw He("cylinderBuilder")},e.CreateTorus=function(e){throw He("torusBuilder")},e.CreateLineSystem=function(e){throw He("linesBuilder")},e.CreateDashedLines=function(e){throw He("linesBuilder")},e.CreateGround=function(e){throw He("groundBuilder")},e.CreateTiledGround=function(e){throw He("groundBuilder")},e.CreateGroundFromHeightMap=function(e){throw He("groundBuilder")},e.CreatePlane=function(e){throw He("planeBuilder")},e.CreateDisc=function(e){throw He("discBuilder")},e.CreatePolygon=function(e,t,i,r,n,o,a){throw He("polygonBuilder")},e.CreateIcoSphere=function(e){throw He("icoSphereBuilder")},e.CreatePolyhedron=function(e){throw He("polyhedronBuilder")},e.CreateCapsule=function(e){throw void 0===e&&(e={orientation:V.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}),He("capsuleBuilder")},e.CreateTorusKnot=function(e){throw He("torusKnotBuilder")},e.ComputeNormals=function(e,t,i,r){var n=0,o=0,a=0,s=0,l=0,c=0,u=0,h=0,d=0,p=0,f=0,_=0,m=0,g=0,v=0,y=0,b=0,T=0,E=0,S=0,x=!1,A=!1,C=!1,R=!1,P=1,I=0,M=null;r&&(x=!!r.facetNormals,A=!!r.facetPositions,C=!!r.facetPartitioning,P=!0===r.useRightHandedSystem?-1:1,I=r.ratio||0,R=!!r.depthSort,M=r.distanceTo,R&&void 0===M&&(M=V.Zero()));var O=0,D=0,N=0,F=0;for(C&&r&&r.bbSize&&(O=r.subDiv.X*I/r.bbSize.x,D=r.subDiv.Y*I/r.bbSize.y,N=r.subDiv.Z*I/r.bbSize.z,F=r.subDiv.max*r.subDiv.max,r.facetPartitioning.length=0),n=0;n<e.length;n++)i[n]=0;var L=t.length/3|0;for(n=0;n<L;n++){if(m=1+(_=3*t[3*n]),g=_+2,y=1+(v=3*t[3*n+1]),b=v+2,E=1+(T=3*t[3*n+2]),S=T+2,o=e[_]-e[v],a=e[m]-e[y],s=e[g]-e[b],l=e[T]-e[v],c=e[E]-e[y],h=P*(a*(u=e[S]-e[b])-s*c),d=P*(s*l-o*u),p=P*(o*c-a*l),h/=f=0===(f=Math.sqrt(h*h+d*d+p*p))?1:f,d/=f,p/=f,x&&r&&(r.facetNormals[n].x=h,r.facetNormals[n].y=d,r.facetNormals[n].z=p),A&&r&&(r.facetPositions[n].x=(e[_]+e[v]+e[T])/3,r.facetPositions[n].y=(e[m]+e[y]+e[E])/3,r.facetPositions[n].z=(e[g]+e[b]+e[S])/3),C&&r){var w=Math.floor((r.facetPositions[n].x-r.bInfo.minimum.x*I)*O),B=Math.floor((r.facetPositions[n].y-r.bInfo.minimum.y*I)*D),U=Math.floor((r.facetPositions[n].z-r.bInfo.minimum.z*I)*N),k=Math.floor((e[_]-r.bInfo.minimum.x*I)*O),G=Math.floor((e[m]-r.bInfo.minimum.y*I)*D),z=Math.floor((e[g]-r.bInfo.minimum.z*I)*N),W=Math.floor((e[v]-r.bInfo.minimum.x*I)*O),H=Math.floor((e[y]-r.bInfo.minimum.y*I)*D),X=Math.floor((e[b]-r.bInfo.minimum.z*I)*N),j=Math.floor((e[T]-r.bInfo.minimum.x*I)*O),Y=Math.floor((e[E]-r.bInfo.minimum.y*I)*D),K=Math.floor((e[S]-r.bInfo.minimum.z*I)*N),Q=k+r.subDiv.max*G+F*z,q=W+r.subDiv.max*H+F*X,Z=j+r.subDiv.max*Y+F*K,J=w+r.subDiv.max*B+F*U;r.facetPartitioning[J]=r.facetPartitioning[J]?r.facetPartitioning[J]:new Array,r.facetPartitioning[Q]=r.facetPartitioning[Q]?r.facetPartitioning[Q]:new Array,r.facetPartitioning[q]=r.facetPartitioning[q]?r.facetPartitioning[q]:new Array,r.facetPartitioning[Z]=r.facetPartitioning[Z]?r.facetPartitioning[Z]:new Array,r.facetPartitioning[Q].push(n),q!=Q&&r.facetPartitioning[q].push(n),Z!=q&&Z!=Q&&r.facetPartitioning[Z].push(n),J!=Q&&J!=q&&J!=Z&&r.facetPartitioning[J].push(n)}if(R&&r&&r.facetPositions){var $=r.depthSortedFacets[n];$.ind=3*n,$.sqDistance=V.DistanceSquared(r.facetPositions[n],M)}i[_]+=h,i[m]+=d,i[g]+=p,i[v]+=h,i[y]+=d,i[b]+=p,i[T]+=h,i[E]+=d,i[S]+=p}for(n=0;n<i.length/3;n++)h=i[3*n],d=i[3*n+1],p=i[3*n+2],h/=f=0===(f=Math.sqrt(h*h+d*d+p*p))?1:f,d/=f,p/=f,i[3*n]=h,i[3*n+1]=d,i[3*n+2]=p},e._ComputeSides=function(t,i,r,n,o,a,s){var l,c,u=r.length,h=n.length;switch(t=t||e.DEFAULTSIDE){case e.FRONTSIDE:break;case e.BACKSIDE:for(l=0;l<u;l+=3){var d=r[l];r[l]=r[l+2],r[l+2]=d}for(c=0;c<h;c++)n[c]=-n[c];break;case e.DOUBLESIDE:for(var p=i.length,f=p/3,_=0;_<p;_++)i[p+_]=i[_];for(l=0;l<u;l+=3)r[l+u]=r[l+2]+f,r[l+1+u]=r[l+1]+f,r[l+2+u]=r[l]+f;for(c=0;c<h;c++)n[h+c]=-n[c];var m=o.length,g=0;for(g=0;g<m;g++)o[g+m]=o[g];for(a=a||new k(0,0,1,1),s=s||new k(0,0,1,1),g=0,l=0;l<m/2;l++)o[g]=a.x+(a.z-a.x)*o[g],o[g+1]=a.y+(a.w-a.y)*o[g+1],o[g+m]=s.x+(s.z-s.x)*o[g+m],o[g+m+1]=s.y+(s.w-s.y)*o[g+m+1],g+=2}},e.Parse=function(t){var i=new e,r=t.positions;r&&i.set(r,Nr.PositionKind);var n=t.normals;n&&i.set(n,Nr.NormalKind);var o=t.tangents;o&&i.set(o,Nr.TangentKind);var a=t.uvs;a&&i.set(a,Nr.UVKind);var s=t.uvs2;s&&i.set(s,Nr.UV2Kind);var l=t.uvs3;l&&i.set(l,Nr.UV3Kind);var c=t.uvs4;c&&i.set(c,Nr.UV4Kind);var u=t.uvs5;u&&i.set(u,Nr.UV5Kind);var h=t.uvs6;h&&i.set(h,Nr.UV6Kind);var d=t.colors;d&&(i.set(J.CheckColors4(d,r.length/3),Nr.ColorKind),void 0!==t.hasVertexAlpha&&(i.hasVertexAlpha=t.hasVertexAlpha));var p=t.matricesIndices;p&&i.set(p,Nr.MatricesIndicesKind);var f=t.matricesWeights;f&&i.set(f,Nr.MatricesWeightsKind);var _=t.indices;_&&(i.indices=_);var m=t.materialInfos;if(m){i.materialInfos=[];for(var g=0,v=m;g<v.length;g++){var y=v[g],b=new fo;b.indexCount=y.indexCount,b.indexStart=y.indexStart,b.verticesCount=y.verticesCount,b.verticesStart=y.verticesStart,b.materialIndex=y.materialIndex,i.materialInfos.push(b)}}return i},e.ImportVertexData=function(t,i){var r=e.Parse(t);i.setAllVerticesData(r,t.updatable)},e.FRONTSIDE=0,e.BACKSIDE=1,e.DOUBLESIDE=2,e.DEFAULTSIDE=0,e._UniqueIDGenerator=0,v([ze.filter((function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var i=e[0];return!Array.isArray(i)}))],e,"_TransformVector3Coordinates",null),v([ze.filter((function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var i=e[0];return!Array.isArray(i)}))],e,"_TransformVector3Normals",null),v([ze.filter((function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var i=e[0];return!Array.isArray(i)}))],e,"_TransformVector4Normals",null),v([ze.filter((function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var i=e[0];return!Array.isArray(i)}))],e,"_FlipFaces",null),e}(),mo=function(){function e(){}return Object.defineProperty(e,"ForceFullSceneLoadingForIncremental",{get:function(){return e._ForceFullSceneLoadingForIncremental},set:function(t){e._ForceFullSceneLoadingForIncremental=t},enumerable:!1,configurable:!0}),Object.defineProperty(e,"ShowLoadingScreen",{get:function(){return e._ShowLoadingScreen},set:function(t){e._ShowLoadingScreen=t},enumerable:!1,configurable:!0}),Object.defineProperty(e,"loggingLevel",{get:function(){return e._LoggingLevel},set:function(t){e._LoggingLevel=t},enumerable:!1,configurable:!0}),Object.defineProperty(e,"CleanBoneMatrixWeights",{get:function(){return e._CleanBoneMatrixWeights},set:function(t){e._CleanBoneMatrixWeights=t},enumerable:!1,configurable:!0}),e._ForceFullSceneLoadingForIncremental=!1,e._ShowLoadingScreen=!0,e._CleanBoneMatrixWeights=!1,e._LoggingLevel=u.SCENELOADER_NO_LOGGING,e}(),go=function(){function e(){}return e.UseOpenGLOrientationForUV=!1,e}(),vo=function(){function e(e,t,i,r,n){void 0===r&&(r=!1),void 0===n&&(n=null),this.delayLoadState=u.DELAYLOADSTATE_NONE,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||M.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=r,i?this.setAllVerticesData(i,r):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),n&&(this.applyToMesh(n),n.computeWorldMatrix(!0)))}return Object.defineProperty(e.prototype,"boundingBias",{get:function(){return this._boundingBias},set:function(e){this._boundingBias?this._boundingBias.copyFrom(e):this._boundingBias=e.clone(),this._updateBoundingInfo(!0,null)},enumerable:!1,configurable:!0}),e.CreateGeometryForMesh=function(t){var i=new e(e.RandomId(),t.getScene());return i.applyToMesh(t),i},Object.defineProperty(e.prototype,"meshes",{get:function(){return this._meshes},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"extend",{get:function(){return this._extend},enumerable:!1,configurable:!0}),e.prototype.getScene=function(){return this._scene},e.prototype.getEngine=function(){return this._engine},e.prototype.isReady=function(){return this.delayLoadState===u.DELAYLOADSTATE_LOADED||this.delayLoadState===u.DELAYLOADSTATE_NONE},Object.defineProperty(e.prototype,"doNotSerialize",{get:function(){for(var e=0;e<this._meshes.length;e++)if(!this._meshes[e].doNotSerialize)return!1;return!0},enumerable:!1,configurable:!0}),e.prototype._rebuild=function(){this._vertexArrayObjects&&(this._vertexArrayObjects={}),0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer"));var e=new Set;for(var t in this._vertexBuffers)e.add(this._vertexBuffers[t].getWrapperBuffer());e.forEach((function(e){e._rebuild()}))},e.prototype.setAllVerticesData=function(e,t){e.applyToGeometry(this,t),this._notifyUpdate()},e.prototype.setVerticesData=function(e,t,i,r){void 0===i&&(i=!1),i&&Array.isArray(t)&&(t=new Float32Array(t));var n=new Nr(this._engine,t,e,{updatable:i,postponeInternalCreation:0===this._meshes.length,stride:r,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(n)},e.prototype.removeVerticesData=function(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()},e.prototype.setVerticesBuffer=function(e,t,i){void 0===t&&(t=null),void 0===i&&(i=!0);var r=e.getKind();this._vertexBuffers[r]&&i&&this._vertexBuffers[r].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[r]=e;var n=this._meshes,o=n.length;if(r===Nr.PositionKind){this._totalVertices=null!=t?t:e._maxVerticesCount,this._updateExtend(e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();for(var a=this._extend&&this._extend.minimum||new V(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),s=this._extend&&this._extend.maximum||new V(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),l=0;l<o;l++){var c=n[l];c.buildBoundingInfo(a,s),c._createGlobalSubMesh(c.isUnIndexed),c.computeWorldMatrix(!0),c.synchronizeInstances()}}this._notifyUpdate(r)},e.prototype.updateVerticesDataDirectly=function(e,t,i,r){void 0===r&&(r=!1);var n=this.getVertexBuffer(e);n&&(n.updateDirectly(t,i,r),this._notifyUpdate(e))},e.prototype.updateVerticesData=function(e,t,i){void 0===i&&(i=!1);var r=this.getVertexBuffer(e);r&&(r.update(t),e===Nr.PositionKind&&this._updateBoundingInfo(i,t),this._notifyUpdate(e))},e.prototype._updateBoundingInfo=function(e,t){if(e&&this._updateExtend(t),this._resetPointsArrayCache(),e)for(var i=0,r=this._meshes;i<r.length;i++){var n=r[i];n.hasBoundingInfo?n.getBoundingInfo().reConstruct(this._extend.minimum,this._extend.maximum):n.buildBoundingInfo(this._extend.minimum,this._extend.maximum);for(var o=0,a=n.subMeshes;o<a.length;o++)a[o].refreshBoundingInfo()}},e.prototype._bind=function(e,t,i,r){if(e){void 0===t&&(t=this._indexBuffer);var n=this.getVertexBuffers();if(n)if(t==this._indexBuffer&&(this._vertexArrayObjects||r)){var o=r||this._vertexArrayObjects,a=this._engine;o[e.key]||(o[e.key]=a.recordVertexArrayObject(n,t,e,i)),a.bindVertexArrayObject(o[e.key],t)}else this._engine.bindBuffers(n,t,e,i)}},e.prototype.getTotalVertices=function(){return this.isReady()?this._totalVertices:0},e.prototype.getVerticesData=function(e,t,i){var r=this.getVertexBuffer(e);return r?r.getFloatData(this._totalVertices,i||t&&1!==this._meshes.length):null},e.prototype.isVertexBufferUpdatable=function(e){var t=this._vertexBuffers[e];return!!t&&t.isUpdatable()},e.prototype.getVertexBuffer=function(e){return this.isReady()?this._vertexBuffers[e]:null},e.prototype.getVertexBuffers=function(){return this.isReady()?this._vertexBuffers:null},e.prototype.isVerticesDataPresent=function(e){return this._vertexBuffers?void 0!==this._vertexBuffers[e]:!!this._delayInfo&&-1!==this._delayInfo.indexOf(e)},e.prototype.getVerticesDataKinds=function(){var e,t=[];if(!this._vertexBuffers&&this._delayInfo)for(e in this._delayInfo)t.push(e);else for(e in this._vertexBuffers)t.push(e);return t},e.prototype.updateIndices=function(e,t,i){if(void 0===i&&(i=!1),this._indexBuffer)if(this._indexBufferIsUpdatable){var r=e.length!==this._indices.length;if(i||(this._indices=e.slice()),this._engine.updateDynamicIndexBuffer(this._indexBuffer,e,t),r)for(var n=0,o=this._meshes;n<o.length;n++)o[n]._createGlobalSubMesh(!0)}else this.setIndices(e,null,!0)},e.prototype.setIndexBuffer=function(e,t,i){this._indices=[],this._indexBufferIsUpdatable=!1,this._indexBuffer=e,this._totalVertices=t,this._totalIndices=i,e.is32Bits||(e.is32Bits=this._totalIndices>65535);for(var r=0,n=this._meshes;r<n.length;r++){var o=n[r];o._createGlobalSubMesh(!0),o.synchronizeInstances()}this._notifyUpdate()},e.prototype.setIndices=function(e,t,i){void 0===t&&(t=null),void 0===i&&(i=!1),this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),null!=t&&(this._totalVertices=t);for(var r=0,n=this._meshes;r<n.length;r++){var o=n[r];o._createGlobalSubMesh(!0),o.synchronizeInstances()}this._notifyUpdate()},e.prototype.getTotalIndices=function(){return this.isReady()?void 0!==this._totalIndices?this._totalIndices:this._indices.length:0},e.prototype.getIndices=function(e,t){if(!this.isReady())return null;var i=this._indices;return t||e&&1!==this._meshes.length?i.slice():i},e.prototype.getIndexBuffer=function(){return this.isReady()?this._indexBuffer:null},e.prototype._releaseVertexArrayObject=function(e){void 0===e&&(e=null),e&&this._vertexArrayObjects&&this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])},e.prototype.releaseForMesh=function(e,t){var i=this._meshes,r=i.indexOf(e);-1!==r&&(i.splice(r,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,0===i.length&&t&&this.dispose())},e.prototype.applyToMesh=function(e){if(e._geometry!==this){var t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();var i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):this._boundingInfo&&e.setBoundingInfo(this._boundingInfo)}},e.prototype._updateExtend=function(e){if(void 0===e&&(e=null),this.useBoundingInfoFromGeometry&&this._boundingInfo)this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()};else{if(!e&&!(e=this.getVerticesData(Nr.PositionKind)))return;this._extend=uo(e,0,this._totalVertices,this.boundingBias,3)}},e.prototype._applyToMesh=function(e){var t=this._meshes.length;for(var i in this._vertexBuffers)1===t&&this._vertexBuffers[i].create(),i===Nr.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());1===t&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer")),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()},e.prototype._notifyUpdate=function(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(var t=0,i=this._meshes;t<i.length;t++)i[t]._markSubMeshesAsAttributesDirty()},e.prototype.load=function(e,t){this.delayLoadState!==u.DELAYLOADSTATE_LOADING&&(this.isReady()?t&&t():(this.delayLoadState=u.DELAYLOADSTATE_LOADING,this._queueLoad(e,t)))},e.prototype._queueLoad=function(e,t){var i=this;this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,(function(r){if(i._delayLoadingFunction){i._delayLoadingFunction(JSON.parse(r),i),i.delayLoadState=u.DELAYLOADSTATE_LOADED,i._delayInfo=[],e.removePendingData(i);for(var n=i._meshes,o=n.length,a=0;a<o;a++)i._applyToMesh(n[a]);t&&t()}}),void 0,!0))},e.prototype.toLeftHanded=function(){var e=this.getIndices(!1);if(null!=e&&e.length>0){for(var t=0;t<e.length;t+=3){var i=e[t+0];e[t+0]=e[t+2],e[t+2]=i}this.setIndices(e)}var r=this.getVerticesData(Nr.PositionKind,!1);if(null!=r&&r.length>0){for(t=0;t<r.length;t+=3)r[t+2]=-r[t+2];this.setVerticesData(Nr.PositionKind,r,!1)}var n=this.getVerticesData(Nr.NormalKind,!1);if(null!=n&&n.length>0){for(t=0;t<n.length;t+=3)n[t+2]=-n[t+2];this.setVerticesData(Nr.NormalKind,n,!1)}},e.prototype._resetPointsArrayCache=function(){this._positions=null},e.prototype._generatePointsArray=function(){if(this._positions)return!0;var e=this.getVerticesData(Nr.PositionKind);if(!e||0===e.length)return!1;for(var t=3*this._positionsCache.length,i=this._positionsCache.length;t<e.length;t+=3,++i)this._positionsCache[i]=V.FromArray(e,t);for(t=0,i=0;t<e.length;t+=3,++i)this._positionsCache[i].set(e[0+t],e[1+t],e[2+t]);return this._positionsCache.length=e.length/3,this._positions=this._positionsCache,!0},e.prototype.isDisposed=function(){return this._isDisposed},e.prototype._disposeVertexArrayObjects=function(){if(this._vertexArrayObjects){for(var e in this._vertexArrayObjects)this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e]);this._vertexArrayObjects={};for(var t=this._meshes,i=t.length,r=0;r<i;r++)t[r]._invalidateInstanceVertexArrayObject()}},e.prototype.dispose=function(){var e,t=this._meshes,i=t.length;for(e=0;e<i;e++)this.releaseForMesh(t[e]);for(var r in this._meshes.length=0,this._disposeVertexArrayObjects(),this._vertexBuffers)this._vertexBuffers[r].dispose();if(this._vertexBuffers={},this._totalVertices=0,this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null,this._indices=[],this.delayLoadState=u.DELAYLOADSTATE_NONE,this.delayLoadingFile=null,this._delayLoadingFunction=null,this._delayInfo=[],this._boundingInfo=null,this._scene.removeGeometry(this),this._parentContainer){var n=this._parentContainer.geometries.indexOf(this);n>-1&&this._parentContainer.geometries.splice(n,1),this._parentContainer=null}this._isDisposed=!0},e.prototype.copy=function(t){var i=new _o;i.indices=[];var r=this.getIndices();if(r)for(var n=0;n<r.length;n++)i.indices.push(r[n]);var o,a=!1,s=!1;for(o in this._vertexBuffers){var l=this.getVerticesData(o);if(l&&(l instanceof Float32Array?i.set(new Float32Array(l),o):i.set(l.slice(0),o),!s)){var c=this.getVertexBuffer(o);c&&(s=!(a=c.isUpdatable()))}}var u=new e(t,this._scene,i,a);for(o in u.delayLoadState=this.delayLoadState,u.delayLoadingFile=this.delayLoadingFile,u._delayLoadingFunction=this._delayLoadingFunction,this._delayInfo)u._delayInfo=u._delayInfo||[],u._delayInfo.push(o);return u._boundingInfo=new so(this._extend.minimum,this._extend.maximum),u},e.prototype.serialize=function(){var e={};return e.id=this.id,e.uniqueId=this.uniqueId,e.updatable=this._updatable,je&&je.HasTags(this)&&(e.tags=je.GetTags(this)),e},e.prototype._toNumberArray=function(e){return Array.isArray(e)?e:Array.prototype.slice.call(e)},e.prototype.clearCachedData=function(){for(var e in this._indices=[],this._resetPointsArrayCache(),this._vertexBuffers)Object.prototype.hasOwnProperty.call(this._vertexBuffers,e)&&(this._vertexBuffers[e]._buffer._data=null)},e.prototype.serializeVerticeData=function(){var e=this.serialize();return this.isVerticesDataPresent(Nr.PositionKind)&&(e.positions=this._toNumberArray(this.getVerticesData(Nr.PositionKind)),this.isVertexBufferUpdatable(Nr.PositionKind)&&(e.positions._updatable=!0)),this.isVerticesDataPresent(Nr.NormalKind)&&(e.normals=this._toNumberArray(this.getVerticesData(Nr.NormalKind)),this.isVertexBufferUpdatable(Nr.NormalKind)&&(e.normals._updatable=!0)),this.isVerticesDataPresent(Nr.TangentKind)&&(e.tangents=this._toNumberArray(this.getVerticesData(Nr.TangentKind)),this.isVertexBufferUpdatable(Nr.TangentKind)&&(e.tangents._updatable=!0)),this.isVerticesDataPresent(Nr.UVKind)&&(e.uvs=this._toNumberArray(this.getVerticesData(Nr.UVKind)),this.isVertexBufferUpdatable(Nr.UVKind)&&(e.uvs._updatable=!0)),this.isVerticesDataPresent(Nr.UV2Kind)&&(e.uvs2=this._toNumberArray(this.getVerticesData(Nr.UV2Kind)),this.isVertexBufferUpdatable(Nr.UV2Kind)&&(e.uvs2._updatable=!0)),this.isVerticesDataPresent(Nr.UV3Kind)&&(e.uvs3=this._toNumberArray(this.getVerticesData(Nr.UV3Kind)),this.isVertexBufferUpdatable(Nr.UV3Kind)&&(e.uvs3._updatable=!0)),this.isVerticesDataPresent(Nr.UV4Kind)&&(e.uvs4=this._toNumberArray(this.getVerticesData(Nr.UV4Kind)),this.isVertexBufferUpdatable(Nr.UV4Kind)&&(e.uvs4._updatable=!0)),this.isVerticesDataPresent(Nr.UV5Kind)&&(e.uvs5=this._toNumberArray(this.getVerticesData(Nr.UV5Kind)),this.isVertexBufferUpdatable(Nr.UV5Kind)&&(e.uvs5._updatable=!0)),this.isVerticesDataPresent(Nr.UV6Kind)&&(e.uvs6=this._toNumberArray(this.getVerticesData(Nr.UV6Kind)),this.isVertexBufferUpdatable(Nr.UV6Kind)&&(e.uvs6._updatable=!0)),this.isVerticesDataPresent(Nr.ColorKind)&&(e.colors=this._toNumberArray(this.getVerticesData(Nr.ColorKind)),this.isVertexBufferUpdatable(Nr.ColorKind)&&(e.colors._updatable=!0)),this.isVerticesDataPresent(Nr.MatricesIndicesKind)&&(e.matricesIndices=this._toNumberArray(this.getVerticesData(Nr.MatricesIndicesKind)),e.matricesIndices._isExpanded=!0,this.isVertexBufferUpdatable(Nr.MatricesIndicesKind)&&(e.matricesIndices._updatable=!0)),this.isVerticesDataPresent(Nr.MatricesWeightsKind)&&(e.matricesWeights=this._toNumberArray(this.getVerticesData(Nr.MatricesWeightsKind)),this.isVertexBufferUpdatable(Nr.MatricesWeightsKind)&&(e.matricesWeights._updatable=!0)),e.indices=this._toNumberArray(this.getIndices()),e},e.ExtractFromMesh=function(e,t){var i=e._geometry;return i?i.copy(t):null},e.RandomId=function(){return rr.RandomId()},e._GetGeometryByLoadedUniqueId=function(e,t){for(var i=0;i<t.geometries.length;i++)if(t.geometries[i]._loadedUniqueId===e)return t.geometries[i];return null},e._ImportGeometry=function(t,i){var r=i.getScene(),n=t.geometryUniqueId,o=t.geometryId;if(n||o){var a=n?this._GetGeometryByLoadedUniqueId(n,r):r.getGeometryById(o);a&&a.applyToMesh(i)}else if(t instanceof ArrayBuffer){var s=i._binaryInfo;if(s.positionsAttrDesc&&s.positionsAttrDesc.count>0){var l=new Float32Array(t,s.positionsAttrDesc.offset,s.positionsAttrDesc.count);i.setVerticesData(Nr.PositionKind,l,!1)}if(s.normalsAttrDesc&&s.normalsAttrDesc.count>0){var c=new Float32Array(t,s.normalsAttrDesc.offset,s.normalsAttrDesc.count);i.setVerticesData(Nr.NormalKind,c,!1)}if(s.tangetsAttrDesc&&s.tangetsAttrDesc.count>0){var u=new Float32Array(t,s.tangetsAttrDesc.offset,s.tangetsAttrDesc.count);i.setVerticesData(Nr.TangentKind,u,!1)}if(s.uvsAttrDesc&&s.uvsAttrDesc.count>0){var h=new Float32Array(t,s.uvsAttrDesc.offset,s.uvsAttrDesc.count);if(go.UseOpenGLOrientationForUV)for(var d=1;d<h.length;d+=2)h[d]=1-h[d];i.setVerticesData(Nr.UVKind,h,!1)}if(s.uvs2AttrDesc&&s.uvs2AttrDesc.count>0){var p=new Float32Array(t,s.uvs2AttrDesc.offset,s.uvs2AttrDesc.count);if(go.UseOpenGLOrientationForUV)for(d=1;d<p.length;d+=2)p[d]=1-p[d];i.setVerticesData(Nr.UV2Kind,p,!1)}if(s.uvs3AttrDesc&&s.uvs3AttrDesc.count>0){var f=new Float32Array(t,s.uvs3AttrDesc.offset,s.uvs3AttrDesc.count);if(go.UseOpenGLOrientationForUV)for(d=1;d<f.length;d+=2)f[d]=1-f[d];i.setVerticesData(Nr.UV3Kind,f,!1)}if(s.uvs4AttrDesc&&s.uvs4AttrDesc.count>0){var _=new Float32Array(t,s.uvs4AttrDesc.offset,s.uvs4AttrDesc.count);if(go.UseOpenGLOrientationForUV)for(d=1;d<_.length;d+=2)_[d]=1-_[d];i.setVerticesData(Nr.UV4Kind,_,!1)}if(s.uvs5AttrDesc&&s.uvs5AttrDesc.count>0){var m=new Float32Array(t,s.uvs5AttrDesc.offset,s.uvs5AttrDesc.count);if(go.UseOpenGLOrientationForUV)for(d=1;d<m.length;d+=2)m[d]=1-m[d];i.setVerticesData(Nr.UV5Kind,m,!1)}if(s.uvs6AttrDesc&&s.uvs6AttrDesc.count>0){var g=new Float32Array(t,s.uvs6AttrDesc.offset,s.uvs6AttrDesc.count);if(go.UseOpenGLOrientationForUV)for(d=1;d<g.length;d+=2)g[d]=1-g[d];i.setVerticesData(Nr.UV6Kind,g,!1)}if(s.colorsAttrDesc&&s.colorsAttrDesc.count>0){var v=new Float32Array(t,s.colorsAttrDesc.offset,s.colorsAttrDesc.count);i.setVerticesData(Nr.ColorKind,v,!1,s.colorsAttrDesc.stride)}if(s.matricesIndicesAttrDesc&&s.matricesIndicesAttrDesc.count>0){for(var y=new Int32Array(t,s.matricesIndicesAttrDesc.offset,s.matricesIndicesAttrDesc.count),b=[],T=0;T<y.length;T++)d=y[T],b.push(255&d),b.push((65280&d)>>8),b.push((16711680&d)>>16),b.push(d>>24&255);i.setVerticesData(Nr.MatricesIndicesKind,b,!1)}if(s.matricesIndicesExtraAttrDesc&&s.matricesIndicesExtraAttrDesc.count>0){for(y=new Int32Array(t,s.matricesIndicesExtraAttrDesc.offset,s.matricesIndicesExtraAttrDesc.count),b=[],T=0;T<y.length;T++)d=y[T],b.push(255&d),b.push((65280&d)>>8),b.push((16711680&d)>>16),b.push(d>>24&255);i.setVerticesData(Nr.MatricesIndicesExtraKind,b,!1)}if(s.matricesWeightsAttrDesc&&s.matricesWeightsAttrDesc.count>0){var E=new Float32Array(t,s.matricesWeightsAttrDesc.offset,s.matricesWeightsAttrDesc.count);i.setVerticesData(Nr.MatricesWeightsKind,E,!1)}if(s.indicesAttrDesc&&s.indicesAttrDesc.count>0){var S=new Int32Array(t,s.indicesAttrDesc.offset,s.indicesAttrDesc.count);i.setIndices(S,null)}if(s.subMeshesAttrDesc&&s.subMeshesAttrDesc.count>0){var x=new Int32Array(t,s.subMeshesAttrDesc.offset,5*s.subMeshesAttrDesc.count);for(i.subMeshes=[],T=0;T<s.subMeshesAttrDesc.count;T++){var A=x[5*T+0],C=x[5*T+1],R=x[5*T+2],P=x[5*T+3],I=x[5*T+4];po.AddToMesh(A,C,R,P,I,i)}}}else if(t.positions&&t.normals&&t.indices){if(i.setVerticesData(Nr.PositionKind,t.positions,t.positions._updatable),i.setVerticesData(Nr.NormalKind,t.normals,t.normals._updatable),t.tangents&&i.setVerticesData(Nr.TangentKind,t.tangents,t.tangents._updatable),t.uvs&&i.setVerticesData(Nr.UVKind,t.uvs,t.uvs._updatable),t.uvs2&&i.setVerticesData(Nr.UV2Kind,t.uvs2,t.uvs2._updatable),t.uvs3&&i.setVerticesData(Nr.UV3Kind,t.uvs3,t.uvs3._updatable),t.uvs4&&i.setVerticesData(Nr.UV4Kind,t.uvs4,t.uvs4._updatable),t.uvs5&&i.setVerticesData(Nr.UV5Kind,t.uvs5,t.uvs5._updatable),t.uvs6&&i.setVerticesData(Nr.UV6Kind,t.uvs6,t.uvs6._updatable),t.colors&&i.setVerticesData(Nr.ColorKind,J.CheckColors4(t.colors,t.positions.length/3),t.colors._updatable),t.matricesIndices)if(t.matricesIndices._isExpanded)delete t.matricesIndices._isExpanded,i.setVerticesData(Nr.MatricesIndicesKind,t.matricesIndices,t.matricesIndices._updatable);else{for(b=[],T=0;T<t.matricesIndices.length;T++){var M=t.matricesIndices[T];b.push(255&M),b.push((65280&M)>>8),b.push((16711680&M)>>16),b.push(M>>24&255)}i.setVerticesData(Nr.MatricesIndicesKind,b,t.matricesIndices._updatable)}if(t.matricesIndicesExtra)if(t.matricesIndicesExtra._isExpanded)delete t.matricesIndices._isExpanded,i.setVerticesData(Nr.MatricesIndicesExtraKind,t.matricesIndicesExtra,t.matricesIndicesExtra._updatable);else{for(b=[],T=0;T<t.matricesIndicesExtra.length;T++)M=t.matricesIndicesExtra[T],b.push(255&M),b.push((65280&M)>>8),b.push((16711680&M)>>16),b.push(M>>24&255);i.setVerticesData(Nr.MatricesIndicesExtraKind,b,t.matricesIndicesExtra._updatable)}t.matricesWeights&&(e._CleanMatricesWeights(t,i),i.setVerticesData(Nr.MatricesWeightsKind,t.matricesWeights,t.matricesWeights._updatable)),t.matricesWeightsExtra&&i.setVerticesData(Nr.MatricesWeightsExtraKind,t.matricesWeightsExtra,t.matricesWeights._updatable),i.setIndices(t.indices,null)}if(t.subMeshes){i.subMeshes=[];for(var O=0;O<t.subMeshes.length;O++){var D=t.subMeshes[O];po.AddToMesh(D.materialIndex,D.verticesStart,D.verticesCount,D.indexStart,D.indexCount,i)}}i._shouldGenerateFlatShading&&(i.convertToFlatShadedMesh(),i._shouldGenerateFlatShading=!1),i.computeWorldMatrix(!0),r.onMeshImportedObservable.notifyObservers(i)},e._CleanMatricesWeights=function(e,t){var i=.001;if(mo.CleanBoneMatrixWeights){var r=0;if(e.skeletonId>-1){var n=t.getScene().getLastSkeletonById(e.skeletonId);if(n){r=n.bones.length;for(var o=t.getVerticesData(Nr.MatricesIndicesKind),a=t.getVerticesData(Nr.MatricesIndicesExtraKind),s=e.matricesWeights,l=e.matricesWeightsExtra,c=e.numBoneInfluencer,u=s.length,h=0;h<u;h+=4){for(var d=0,p=-1,f=0;f<4;f++)d+=_=s[h+f],_<i&&p<0&&(p=f);if(l)for(f=0;f<4;f++){var _;d+=_=l[h+f],_<i&&p<0&&(p=f+4)}if((p<0||p>c-1)&&(p=c-1),d>i){var m=1/d;for(f=0;f<4;f++)s[h+f]*=m;if(l)for(f=0;f<4;f++)l[h+f]*=m}else p>=4?(l[h+p-4]=1-d,a[h+p-4]=r):(s[h+p]=1-d,o[h+p]=r)}t.setVerticesData(Nr.MatricesIndicesKind,o),e.matricesWeightsExtra&&t.setVerticesData(Nr.MatricesIndicesExtraKind,a)}}}},e.Parse=function(t,i,r){var n=new e(t.id,i,void 0,t.updatable);return n._loadedUniqueId=t.uniqueId,je&&je.AddTagsTo(n,t.tags),t.delayLoadingFile?(n.delayLoadState=u.DELAYLOADSTATE_NOTLOADED,n.delayLoadingFile=r+t.delayLoadingFile,n._boundingInfo=new so(V.FromArray(t.boundingBoxMinimum),V.FromArray(t.boundingBoxMaximum)),n._delayInfo=[],t.hasUVs&&n._delayInfo.push(Nr.UVKind),t.hasUVs2&&n._delayInfo.push(Nr.UV2Kind),t.hasUVs3&&n._delayInfo.push(Nr.UV3Kind),t.hasUVs4&&n._delayInfo.push(Nr.UV4Kind),t.hasUVs5&&n._delayInfo.push(Nr.UV5Kind),t.hasUVs6&&n._delayInfo.push(Nr.UV6Kind),t.hasColors&&n._delayInfo.push(Nr.ColorKind),t.hasMatricesIndices&&n._delayInfo.push(Nr.MatricesIndicesKind),t.hasMatricesWeights&&n._delayInfo.push(Nr.MatricesWeightsKind),n._delayLoadingFunction=_o.ImportVertexData):_o.ImportVertexData(t,n),i.pushGeometry(n,!0),n},e}(),yo=function(){function e(e){void 0===e&&(e=30),this._enabled=!0,this._rollingFrameTime=new bo(e)}return e.prototype.sampleFrame=function(e){if(void 0===e&&(e=_t.Now),this._enabled){if(null!=this._lastFrameTimeMs){var t=e-this._lastFrameTimeMs;this._rollingFrameTime.add(t)}this._lastFrameTimeMs=e}},Object.defineProperty(e.prototype,"averageFrameTime",{get:function(){return this._rollingFrameTime.average},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"averageFrameTimeVariance",{get:function(){return this._rollingFrameTime.variance},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"instantaneousFrameTime",{get:function(){return this._rollingFrameTime.history(0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"averageFPS",{get:function(){return 1e3/this._rollingFrameTime.average},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"instantaneousFPS",{get:function(){var e=this._rollingFrameTime.history(0);return 0===e?0:1e3/e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isSaturated",{get:function(){return this._rollingFrameTime.isSaturated()},enumerable:!1,configurable:!0}),e.prototype.enable=function(){this._enabled=!0},e.prototype.disable=function(){this._enabled=!1,this._lastFrameTimeMs=null},Object.defineProperty(e.prototype,"isEnabled",{get:function(){return this._enabled},enumerable:!1,configurable:!0}),e.prototype.reset=function(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()},e}(),bo=function(){function e(e){this._samples=new Array(e),this.reset()}return e.prototype.add=function(e){var t;if(this.isSaturated()){var i=this._samples[this._pos];t=i-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(i-this.average)}else this._sampleCount++;t=e-this.average,this.average+=t/this._sampleCount,this._m2+=t*(e-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=e,this._pos++,this._pos%=this._samples.length},e.prototype.history=function(e){if(e>=this._sampleCount||e>=this._samples.length)return 0;var t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]},e.prototype.isSaturated=function(){return this._sampleCount>=this._samples.length},e.prototype.reset=function(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0},e.prototype._wrapPosition=function(e){var t=this._samples.length;return(e%t+t)%t},e}();function To(e,t,i,r){switch(void 0===i&&(i=!1),e){case u.TEXTURETYPE_BYTE:var n=(ArrayBuffer,new Int8Array(t));return r&&n.set(new Int8Array(r)),n;case u.TEXTURETYPE_UNSIGNED_BYTE:var o=(ArrayBuffer,new Uint8Array(t));return r&&o.set(new Uint8Array(r)),o;case u.TEXTURETYPE_SHORT:var a=t instanceof ArrayBuffer?new Int16Array(t):new Int16Array(i?t/2:t);return r&&a.set(new Int16Array(r)),a;case u.TEXTURETYPE_UNSIGNED_SHORT:case u.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:case u.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:case u.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:case u.TEXTURETYPE_HALF_FLOAT:var s=t instanceof ArrayBuffer?new Uint16Array(t):new Uint16Array(i?t/2:t);return r&&s.set(new Uint16Array(r)),s;case u.TEXTURETYPE_INT:var l=t instanceof ArrayBuffer?new Int32Array(t):new Int32Array(i?t/4:t);return r&&l.set(new Int32Array(r)),l;case u.TEXTURETYPE_UNSIGNED_INTEGER:case u.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:case u.TEXTURETYPE_UNSIGNED_INT_24_8:case u.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:case u.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:case u.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:var c=t instanceof ArrayBuffer?new Uint32Array(t):new Uint32Array(i?t/4:t);return r&&c.set(new Uint32Array(r)),c;case u.TEXTURETYPE_FLOAT:var h=t instanceof ArrayBuffer?new Float32Array(t):new Float32Array(i?t/4:t);return r&&h.set(new Float32Array(r)),h}var d=(ArrayBuffer,new Uint8Array(t));return r&&d.set(new Uint8Array(r)),d}function Eo(e,t,i){e._onCanvasFocus=function(){e.onCanvasFocusObservable.notifyObservers(e)},e._onCanvasBlur=function(){e.onCanvasBlurObservable.notifyObservers(e)},e._onCanvasContextMenu=function(t){e.disableContextMenu&&t.preventDefault()},t.addEventListener("focus",e._onCanvasFocus),t.addEventListener("blur",e._onCanvasBlur),t.addEventListener("contextmenu",e._onCanvasContextMenu),e._onBlur=function(){e.disablePerformanceMonitorInBackground&&e.performanceMonitor.disable(),e._windowIsBackground=!0},e._onFocus=function(){e.disablePerformanceMonitorInBackground&&e.performanceMonitor.enable(),e._windowIsBackground=!1},e._onCanvasPointerOut=function(i){document.elementFromPoint(i.clientX,i.clientY)!==t&&e.onCanvasPointerOutObservable.notifyObservers(i)};var r=e.getHostWindow();r&&"function"==typeof r.addEventListener&&(r.addEventListener("blur",e._onBlur),r.addEventListener("focus",e._onFocus)),t.addEventListener("pointerout",e._onCanvasPointerOut),i.doNotHandleTouchAction||function(e){e&&e.setAttribute&&(e.setAttribute("touch-action","none"),e.style.touchAction="none",e.style.webkitTapHighlightColor="transparent")}(t),!Mi.audioEngine&&i.audioEngine&&Mi.AudioEngineFactory&&(Mi.audioEngine=Mi.AudioEngineFactory(e.getRenderingCanvas(),e.getAudioContext(),e.getAudioDestination())),ht()&&(e._onFullscreenChange=function(){e.isFullscreen=!!document.fullscreenElement,e.isFullscreen&&e._pointerLockRequested&&t&&Io(t)},document.addEventListener("fullscreenchange",e._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",e._onFullscreenChange,!1),e._onPointerLockChange=function(){e.isPointerLock=document.pointerLockElement===t},document.addEventListener("pointerlockchange",e._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",e._onPointerLockChange,!1)),e.enableOfflineSupport=void 0!==Mi.OfflineProviderFactory,e._deterministicLockstep=!!i.deterministicLockstep,e._lockstepMaxSteps=i.lockstepMaxSteps||0,e._timeStep=i.timeStep||1/60}function So(e,t){1===M.Instances.length&&Mi.audioEngine&&(Mi.audioEngine.dispose(),Mi.audioEngine=null);var i=e.getHostWindow();i&&"function"==typeof i.removeEventListener&&(i.removeEventListener("blur",e._onBlur),i.removeEventListener("focus",e._onFocus)),t&&(t.removeEventListener("focus",e._onCanvasFocus),t.removeEventListener("blur",e._onCanvasBlur),t.removeEventListener("pointerout",e._onCanvasPointerOut),t.removeEventListener("contextmenu",e._onCanvasContextMenu)),ht()&&(document.removeEventListener("fullscreenchange",e._onFullscreenChange),document.removeEventListener("mozfullscreenchange",e._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",e._onFullscreenChange),document.removeEventListener("msfullscreenchange",e._onFullscreenChange),document.removeEventListener("pointerlockchange",e._onPointerLockChange),document.removeEventListener("mspointerlockchange",e._onPointerLockChange),document.removeEventListener("mozpointerlockchange",e._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",e._onPointerLockChange))}function xo(e){var t=document.createElement("span");t.innerHTML="Hg",t.setAttribute("style","font: ".concat(e," !important"));var i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";var r=document.createElement("div");r.style.whiteSpace="nowrap",r.appendChild(t),r.appendChild(i),document.body.appendChild(r);var n=0,o=0;try{o=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",n=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(r)}return{ascent:n,height:o,descent:o-n}}function Ao(e,t,i){return new Promise((function(r,n){var o=new Image;o.onload=function(){o.decode().then((function(){e.createImageBitmap(o,i).then((function(e){r(e)}))}))},o.onerror=function(){n("Error loading image ".concat(o.src))},o.src=t}))}function Co(e,t,i,r){var n=e.createCanvas(i,r).getContext("2d");if(!n)throw new Error("Unable to get 2d context for resizeImageBitmap");return n.drawImage(t,0,0),n.getImageData(0,0,i,r).data}function Ro(e){var t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}function Po(){var e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}function Io(e){if(e.requestPointerLock){var t=e.requestPointerLock();t instanceof Promise?t.then((function(){e.focus()})).catch((function(){})):e.focus()}}function Mo(){document.exitPointerLock&&document.exitPointerLock()}Er.prototype.setAlphaMode=function(e,t){if(void 0===t&&(t=!1),this._alphaMode!==e){switch(e){case u.ALPHA_DISABLE:this._alphaState.alphaBlend=!1;break;case u.ALPHA_PREMULTIPLIED:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case u.ALPHA_PREMULTIPLIED_PORTERDUFF:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case u.ALPHA_COMBINE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case u.ALPHA_ONEONE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case u.ALPHA_ADD:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case u.ALPHA_SUBTRACT:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case u.ALPHA_MULTIPLY:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case u.ALPHA_MAXIMIZED:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case u.ALPHA_INTERPOLATE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR,this._gl.ONE_MINUS_CONSTANT_COLOR,this._gl.CONSTANT_ALPHA,this._gl.ONE_MINUS_CONSTANT_ALPHA),this._alphaState.alphaBlend=!0;break;case u.ALPHA_SCREENMODE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case u.ALPHA_ONEONE_ONEONE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case u.ALPHA_ALPHATOCOLOR:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case u.ALPHA_REVERSEONEMINUS:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE_MINUS_DST_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case u.ALPHA_SRC_DSTONEMINUSSRCALPHA:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case u.ALPHA_ONEONE_ONEZERO:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case u.ALPHA_EXCLUSION:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case u.ALPHA_LAYER_ACCUMULATE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0}t||(this.depthCullingState.depthMask=e===u.ALPHA_DISABLE),this._alphaMode=e}else if(!t){var i=e===u.ALPHA_DISABLE;this.depthCullingState.depthMask!==i&&(this.depthCullingState.depthMask=i)}},Er.prototype._readTexturePixelsSync=function(e,t,i,r,n,o,a,s,l,c){var u,h;void 0===r&&(r=-1),void 0===n&&(n=0),void 0===o&&(o=null),void 0===a&&(a=!0),void 0===s&&(s=!1),void 0===l&&(l=0),void 0===c&&(c=0);var d=this._gl;if(!d)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){var p=d.createFramebuffer();if(!p)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=p}d.bindFramebuffer(d.FRAMEBUFFER,this._dummyFramebuffer),r>-1?d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_CUBE_MAP_POSITIVE_X+r,null===(u=e._hardwareTexture)||void 0===u?void 0:u.underlyingResource,n):d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_2D,null===(h=e._hardwareTexture)||void 0===h?void 0:h.underlyingResource,n);var f=void 0!==e.type?this._getWebGLTextureType(e.type):d.UNSIGNED_BYTE;return s?o||(o=To(e.type,4*t*i)):f===d.UNSIGNED_BYTE?(o||(o=new Uint8Array(4*t*i)),f=d.UNSIGNED_BYTE):(o||(o=new Float32Array(4*t*i)),f=d.FLOAT),a&&this.flushFramebuffer(),d.readPixels(l,c,t,i,d.RGBA,f,o),d.bindFramebuffer(d.FRAMEBUFFER,this._currentFramebuffer),o},Er.prototype._readTexturePixels=function(e,t,i,r,n,o,a,s,l,c){return void 0===r&&(r=-1),void 0===n&&(n=0),void 0===o&&(o=null),void 0===a&&(a=!0),void 0===s&&(s=!1),void 0===l&&(l=0),void 0===c&&(c=0),Promise.resolve(this._readTexturePixelsSync(e,t,i,r,n,o,a,s,l,c))},Er.prototype.updateDynamicIndexBuffer=function(e,t,i){var r;void 0===i&&(i=0),this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),r=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,r,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},Er.prototype.updateDynamicVertexBuffer=function(e,t,i,r){this.bindArrayBuffer(e),void 0===i&&(i=0);var n=t.byteLength||t.length;void 0===r||r>=n&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+r)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,r):new Uint8Array(t.buffer,t.byteOffset+i,r),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()},Mi.prototype.displayLoadingUI=function(){if(ct()){var e=this.loadingScreen;e&&e.displayLoadingUI()}},Mi.prototype.hideLoadingUI=function(){if(ct()){var e=this._loadingScreen;e&&e.hideLoadingUI()}},Object.defineProperty(Mi.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=Mi.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(e){this._loadingScreen=e},enumerable:!0,configurable:!0}),Object.defineProperty(Mi.prototype,"loadingUIText",{set:function(e){this.loadingScreen.loadingUIText=e},enumerable:!0,configurable:!0}),Object.defineProperty(Mi.prototype,"loadingUIBackgroundColor",{set:function(e){this.loadingScreen.loadingUIBackgroundColor=e},enumerable:!0,configurable:!0}),Mi.prototype.getInputElement=function(){return this._renderingCanvas},Mi.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null},Mi.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null},Mi.prototype.getAspectRatio=function(e,t){void 0===t&&(t=!1);var i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)},Mi.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)},Mi.prototype._verifyPointerLock=function(){var e;null===(e=this._onPointerLockChange)||void 0===e||e.call(this)},Mi.prototype.getInputElement=function(){return this._renderingCanvas},Mi.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc},Mi.prototype.setDepthFunction=function(e){this._depthCullingState.depthFunc=e},Mi.prototype.setDepthFunctionToGreater=function(){this.setDepthFunction(u.GREATER)},Mi.prototype.setDepthFunctionToGreaterOrEqual=function(){this.setDepthFunction(u.GEQUAL)},Mi.prototype.setDepthFunctionToLess=function(){this.setDepthFunction(u.LESS)},Mi.prototype.setDepthFunctionToLessOrEqual=function(){this.setDepthFunction(u.LEQUAL)},Mi.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask},Mi.prototype.setDepthWrite=function(e){this._depthCullingState.depthMask=e},Mi.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest},Mi.prototype.setStencilBuffer=function(e){this._stencilState.stencilTest=e},Mi.prototype.getStencilMask=function(){return this._stencilState.stencilMask},Mi.prototype.setStencilMask=function(e){this._stencilState.stencilMask=e},Mi.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc},Mi.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef},Mi.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask},Mi.prototype.setStencilFunction=function(e){this._stencilState.stencilFunc=e},Mi.prototype.setStencilFunctionReference=function(e){this._stencilState.stencilFuncRef=e},Mi.prototype.setStencilFunctionMask=function(e){this._stencilState.stencilFuncMask=e},Mi.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail},Mi.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail},Mi.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass},Mi.prototype.setStencilOperationFail=function(e){this._stencilState.stencilOpStencilFail=e},Mi.prototype.setStencilOperationDepthFail=function(e){this._stencilState.stencilOpDepthFail=e},Mi.prototype.setStencilOperationPass=function(e){this._stencilState.stencilOpStencilDepthPass=e},Mi.prototype.cacheStencilState=function(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()},Mi.prototype.restoreStencilState=function(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)},Mi.prototype.setAlphaConstants=function(e,t,i,r){this._alphaState.setAlphaBlendConstants(e,t,i,r)},Mi.prototype.getAlphaMode=function(){return this._alphaMode},Mi.prototype.getAlphaEquation=function(){return this._alphaEquation},Mi.prototype.getRenderPassNames=function(){return this._renderPassNames},Mi.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]},Mi.prototype.createRenderPassId=function(e){var t=++Mi._RenderPassIdCounter;return this._renderPassNames[t]=null!=e?e:"NONAME",t},Mi.prototype.releaseRenderPassId=function(e){this._renderPassNames[e]=void 0;for(var t=0;t<this.scenes.length;++t)for(var i=this.scenes[t],r=0;r<i.meshes.length;++r){var n=i.meshes[r];if(n.subMeshes)for(var o=0;o<n.subMeshes.length;++o)n.subMeshes[o]._removeDrawWrapper(e)}},Mi.prototype.createDepthStencilTexture=function(e,t,i){if(t.isCube){var r=e.width||e;return this._createDepthStencilCubeTexture(r,t)}return this._createDepthStencilTexture(e,t,i)},Mi.AudioEngineFactory=function(e,t,i){return new Oo(e,t,i)};var Oo=function(){function e(e,t,i){void 0===e&&(e=null),void 0===t&&(t=null),void 0===i&&(i=null);var r=this;if(this._audioContext=null,this._audioContextInitialized=!1,this._muteButton=null,this._audioDestination=null,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.isMP3supported=!1,this.isOGGsupported=!1,this.unlocked=!1,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new f,this.onAudioLockedObservable=new f,this._tryToRun=!1,this._onResize=function(){r._moveButtonToTopLeft()},ct()){void 0!==window.AudioContext&&(this.canUseWebAudio=!0);var n=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{n&&n.canPlayType&&(n.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||n.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch(e){}try{n&&n.canPlayType&&n.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(e){}}}return Object.defineProperty(e.prototype,"audioContext",{get:function(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext},enumerable:!1,configurable:!0}),e.prototype.lock=function(){this._triggerSuspendedState()},e.prototype.unlock=function(){var e,t,i=this;if("running"===(null===(e=this._audioContext)||void 0===e?void 0:e.state))return this._hideMuteButton(),void(this.unlocked||(this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)));this._tryToRun?null===(t=this._audioContext)||void 0===t||t.suspend().then((function(){i._tryToRun=!1,i._triggerRunningState()})):this._triggerRunningState()},e.prototype._resumeAudioContext=function(){var e;return(null===(e=this._audioContext)||void 0===e?void 0:e.resume)?this._audioContext.resume():Promise.resolve()},e.prototype._initializeAudioContext=function(){try{this.canUseWebAudio&&(this._audioContext||(this._audioContext=new AudioContext),this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this._audioDestination||(this._audioDestination=this._audioContext.destination),this.masterGain.connect(this._audioDestination),this._audioContextInitialized=!0,"running"===this._audioContext.state&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,ae.Error("Web Audio: "+e.message)}},e.prototype._triggerRunningState=function(){var e=this;this._tryToRun||(this._tryToRun=!0,this._resumeAudioContext().then((function(){e._tryToRun=!1,e._muteButton&&e._hideMuteButton(),e.unlocked=!0,e.onAudioUnlockedObservable.notifyObservers(e)})).catch((function(){e._tryToRun=!1,e.unlocked=!1})))},e.prototype._triggerSuspendedState=function(){this.unlocked=!1,this.onAudioLockedObservable.notifyObservers(this),this._displayMuteButton()},e.prototype._displayMuteButton=function(){var e=this;if(!this.useCustomUnlockedButton&&!this._muteButton){this._muteButton=document.createElement("BUTTON"),this._muteButton.className="babylonUnmuteIcon",this._muteButton.id="babylonUnmuteIconBtn",this._muteButton.title="Unmute";var t=".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E":"https://cdn.babylonjs.com/Assets/audio.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }",i=document.createElement("style");i.appendChild(document.createTextNode(t)),document.getElementsByTagName("head")[0].appendChild(i),document.body.appendChild(this._muteButton),this._moveButtonToTopLeft(),this._muteButton.addEventListener("touchend",(function(){e._triggerRunningState()}),!0),this._muteButton.addEventListener("click",(function(){e.unlock()}),!0),window.addEventListener("resize",this._onResize)}},e.prototype._moveButtonToTopLeft=function(){this._hostElement&&this._muteButton&&(this._muteButton.style.top=this._hostElement.offsetTop+20+"px",this._muteButton.style.left=this._hostElement.offsetLeft+20+"px")},e.prototype._hideMuteButton=function(){this._muteButton&&(document.body.removeChild(this._muteButton),this._muteButton=null)},e.prototype.dispose=function(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&this._audioContext&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1,this._hideMuteButton(),window.removeEventListener("resize",this._onResize),this.onAudioUnlockedObservable.clear(),this.onAudioLockedObservable.clear()},e.prototype.getGlobalVolume=function(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1},e.prototype.setGlobalVolume=function(e){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=e)},e.prototype.connectToAnalyser=function(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&this._audioContext&&(this._connectedAnalyser=e,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))},e}(),Do=function(e){function t(t,i,r,n){void 0===n&&(n=!1);var o=e.call(this,t,i,r,n)||this;if(o.customAnimationFrameRequester=null,o._performanceMonitor=new yo,o._drawCalls=new an,!t)return o;if(o._features.supportRenderPasses=!0,r=o._creationOptions,t.getContext){var a=t;o._sharedInit(a)}return o}return m(t,e),Object.defineProperty(t,"NpmPackage",{get:function(){return Mi.NpmPackage},enumerable:!1,configurable:!0}),Object.defineProperty(t,"Version",{get:function(){return Mi.Version},enumerable:!1,configurable:!0}),Object.defineProperty(t,"Instances",{get:function(){return M.Instances},enumerable:!1,configurable:!0}),Object.defineProperty(t,"LastCreatedEngine",{get:function(){return M.LastCreatedEngine},enumerable:!1,configurable:!0}),Object.defineProperty(t,"LastCreatedScene",{get:function(){return M.LastCreatedScene},enumerable:!1,configurable:!0}),t.MarkAllMaterialsAsDirty=function(e,i){for(var r=0;r<t.Instances.length;r++)for(var n=t.Instances[r],o=0;o<n.scenes.length;o++)n.scenes[o].markAllMaterialsAsDirty(e,i)},t.DefaultLoadingScreenFactory=function(e){return Mi.DefaultLoadingScreenFactory(e)},Object.defineProperty(t.prototype,"_supportsHardwareTextureRescaling",{get:function(){return!!t._RescalePostProcessFactory},enumerable:!1,configurable:!0}),t.prototype._measureFps=function(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0},Object.defineProperty(t.prototype,"performanceMonitor",{get:function(){return this._performanceMonitor},enumerable:!1,configurable:!0}),t.prototype._initGLContext=function(){e.prototype._initGLContext.call(this),this._rescalePostProcess=null},t.prototype._sharedInit=function(t){e.prototype._sharedInit.call(this,t),Eo(this,t,this._creationOptions)},t.prototype.resizeImageBitmap=function(e,t,i){return Co(this,e,t,i)},t.prototype._createImageBitmapFromSource=function(e,t){return Ao(this,e,t)},t.prototype.switchFullscreen=function(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)},t.prototype.enterFullscreen=function(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&Ro(this._renderingCanvas))},t.prototype.exitFullscreen=function(){this.isFullscreen&&Po()},t.prototype.generateMipMapsForCubemap=function(e,t){if(void 0===t&&(t=!0),e.generateMipMaps){var i=this._gl;this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,e,!0),i.generateMipmap(i.TEXTURE_CUBE_MAP),t&&this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)}},t.prototype.setDitheringState=function(e){e?this._gl.enable(this._gl.DITHER):this._gl.disable(this._gl.DITHER)},t.prototype.setRasterizerState=function(e){e?this._gl.disable(this._gl.RASTERIZER_DISCARD):this._gl.enable(this._gl.RASTERIZER_DISCARD)},t.prototype.setDirectViewport=function(e,t,i,r){var n=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,r),n},t.prototype.scissorClear=function(e,t,i,r,n){this.enableScissor(e,t,i,r),this.clear(n,!0,!0,!0),this.disableScissor()},t.prototype.enableScissor=function(e,t,i,r){var n=this._gl;n.enable(n.SCISSOR_TEST),n.scissor(e,t,i,r)},t.prototype.disableScissor=function(){var e=this._gl;e.disable(e.SCISSOR_TEST)},t.prototype._loadFileAsync=function(e,t,i){var r=this;return new Promise((function(n,o){r._loadFile(e,(function(e){n(e)}),void 0,t,i,(function(e,t){o(t)}))}))},t.prototype.getVertexShaderSource=function(e){var t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null},t.prototype.getFragmentShaderSource=function(e){var t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null},t.prototype.setDepthStencilTexture=function(e,t,i,r){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,r):this._setTexture(e,null,void 0,void 0,r))},t.prototype.setTextureFromPostProcess=function(e,t,i){var r,n=null;t&&(t._forcedOutputTexture?n=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(n=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,null!==(r=null==n?void 0:n.texture)&&void 0!==r?r:null,i)},t.prototype.setTextureFromPostProcessOutput=function(e,t,i){var r,n;this._bindTexture(e,null!==(n=null===(r=null==t?void 0:t._outputTexture)||void 0===r?void 0:r.texture)&&void 0!==n?n:null,i)},Object.defineProperty(t.prototype,"framebufferDimensionsObject",{set:function(e){this._framebufferDimensionsObject=e,this._framebufferDimensionsObject&&this.onResizeObservable.notifyObservers(this)},enumerable:!1,configurable:!0}),t.prototype._rebuildBuffers=function(){for(var t=0,i=this.scenes;t<i.length;t++)(o=i[t]).resetCachedMaterial(),o._rebuildGeometries();for(var r=0,n=this._virtualScenes;r<n.length;r++){var o;(o=n[r]).resetCachedMaterial(),o._rebuildGeometries()}e.prototype._rebuildBuffers.call(this)},t.prototype.getFontOffset=function(e){return xo(e)},t.prototype._renderFrame=function(){for(var e=0;e<this._activeRenderLoops.length;e++)(0,this._activeRenderLoops[e])()},t.prototype._cancelFrame=function(){if(this.customAnimationFrameRequester){if(0!==this._frameHandler){this._frameHandler=0;var t=this.customAnimationFrameRequester.cancelAnimationFrame;t&&t(this.customAnimationFrameRequester.requestID)}}else e.prototype._cancelFrame.call(this)},t.prototype._renderLoop=function(){if(this._frameHandler=0,!this._contextWasLost){var e=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&0===this._frameHandler&&(this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))},t.prototype._renderViews=function(){return!1},t.prototype.enterPointerlock=function(){this._renderingCanvas&&Io(this._renderingCanvas)},t.prototype.exitPointerlock=function(){Mo()},t.prototype.beginFrame=function(){this._measureFps(),e.prototype.beginFrame.call(this)},t.prototype._deletePipelineContext=function(t){var i=t;i&&i.program&&i.transformFeedback&&(this.deleteTransformFeedback(i.transformFeedback),i.transformFeedback=null),e.prototype._deletePipelineContext.call(this,t)},t.prototype.createShaderProgram=function(t,i,r,n,o,a){void 0===a&&(a=null),o=o||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);var s=e.prototype.createShaderProgram.call(this,t,i,r,n,o,a);return this.onAfterShaderCompilationObservable.notifyObservers(this),s},t.prototype._createShaderProgram=function(e,t,i,r,n){void 0===n&&(n=null);var o=r.createProgram();if(e.program=o,!o)throw new Error("Unable to create program");if(r.attachShader(o,t),r.attachShader(o,i),this.webGLVersion>1&&n){var a=this.createTransformFeedback();this.bindTransformFeedback(a),this.setTranformFeedbackVaryings(o,n),e.transformFeedback=a}return r.linkProgram(o),this.webGLVersion>1&&n&&this.bindTransformFeedback(null),e.context=r,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),o},t.prototype._releaseTexture=function(t){e.prototype._releaseTexture.call(this,t)},t.prototype._releaseRenderTargetWrapper=function(t){e.prototype._releaseRenderTargetWrapper.call(this,t),this.scenes.forEach((function(e){e.postProcesses.forEach((function(e){e._outputTexture===t&&(e._outputTexture=null)})),e.cameras.forEach((function(e){e._postProcesses.forEach((function(e){e&&e._outputTexture===t&&(e._outputTexture=null)}))}))}))},t.prototype._rescaleTexture=function(e,i,r,n,o){var a=this;this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);var s=this.createRenderTargetTexture({width:i.width,height:i.height},{generateMipMaps:!1,type:u.TEXTURETYPE_UNSIGNED_INT,samplingMode:u.TEXTURE_BILINEAR_SAMPLINGMODE,generateDepthBuffer:!1,generateStencilBuffer:!1});!this._rescalePostProcess&&t._RescalePostProcessFactory&&(this._rescalePostProcess=t._RescalePostProcessFactory(this)),this._rescalePostProcess&&(this._rescalePostProcess.externalTextureSamplerBinding=!0,this._rescalePostProcess.getEffect().executeWhenCompiled((function(){a._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};var t=r;t||(t=a.scenes[a.scenes.length-1]),t.postProcessManager.directRender([a._rescalePostProcess],s,!0),a._bindTextureDirectly(a._gl.TEXTURE_2D,i,!0),a._gl.copyTexImage2D(a._gl.TEXTURE_2D,0,n,0,0,i.width,i.height,0),a.unBindFramebuffer(s),s.dispose(),o&&o()})))},t.prototype.wrapWebGLTexture=function(e,t,i,r,n){void 0===t&&(t=!1),void 0===i&&(i=u.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===r&&(r=0),void 0===n&&(n=0);var o=new br(e,this._gl),a=new Pi(this,Ti.Unknown,!0);return a._hardwareTexture=o,a.baseWidth=r,a.baseHeight=n,a.width=r,a.height=n,a.isReady=!0,a.useMipMaps=t,this.updateTextureSamplingMode(i,a),a},t.prototype._uploadImageToTexture=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0);var n=this._gl,o=this._getWebGLTextureType(e.type),a=this._getInternalFormat(e.format),s=this._getRGBABufferInternalSizedFormat(e.type,a),l=e.isCube?n.TEXTURE_CUBE_MAP:n.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);var c=n.TEXTURE_2D;e.isCube&&(c=n.TEXTURE_CUBE_MAP_POSITIVE_X+i),n.texImage2D(c,r,s,a,o,t),this._bindTextureDirectly(l,null,!0)},t.prototype.updateTextureComparisonFunction=function(e,t){if(1!==this.webGLVersion){var i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,u.LEQUAL),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),0===t?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,u.LEQUAL),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}else ae.Error("WebGL 1 does not support texture comparison.")},t.prototype.createInstancesBuffer=function(e){var t=this._gl.createBuffer();if(!t)throw new Error("Unable to create instance buffer");var i=new yr(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i},t.prototype.deleteInstancesBuffer=function(e){this._gl.deleteBuffer(e)},t.prototype._clientWaitAsync=function(e,t,i){void 0===t&&(t=0),void 0===i&&(i=10);var r=this._gl;return new Promise((function(n,o){var a=function(){var s=r.clientWaitSync(e,t,0);s!=r.WAIT_FAILED?s!=r.TIMEOUT_EXPIRED?n():setTimeout(a,i):o()};a()}))},t.prototype._readPixelsAsync=function(e,t,i,r,n,o,a){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");var s=this._gl,l=s.createBuffer();s.bindBuffer(s.PIXEL_PACK_BUFFER,l),s.bufferData(s.PIXEL_PACK_BUFFER,a.byteLength,s.STREAM_READ),s.readPixels(e,t,i,r,n,o,0),s.bindBuffer(s.PIXEL_PACK_BUFFER,null);var c=s.fenceSync(s.SYNC_GPU_COMMANDS_COMPLETE,0);return c?(s.flush(),this._clientWaitAsync(c,0,10).then((function(){return s.deleteSync(c),s.bindBuffer(s.PIXEL_PACK_BUFFER,l),s.getBufferSubData(s.PIXEL_PACK_BUFFER,0,a),s.bindBuffer(s.PIXEL_PACK_BUFFER,null),s.deleteBuffer(l),a}))):null},t.prototype.dispose=function(){this._rescalePostProcess&&this._rescalePostProcess.dispose(),So(this,this._renderingCanvas),e.prototype.dispose.call(this)},t.ALPHA_DISABLE=u.ALPHA_DISABLE,t.ALPHA_ADD=u.ALPHA_ADD,t.ALPHA_COMBINE=u.ALPHA_COMBINE,t.ALPHA_SUBTRACT=u.ALPHA_SUBTRACT,t.ALPHA_MULTIPLY=u.ALPHA_MULTIPLY,t.ALPHA_MAXIMIZED=u.ALPHA_MAXIMIZED,t.ALPHA_ONEONE=u.ALPHA_ONEONE,t.ALPHA_PREMULTIPLIED=u.ALPHA_PREMULTIPLIED,t.ALPHA_PREMULTIPLIED_PORTERDUFF=u.ALPHA_PREMULTIPLIED_PORTERDUFF,t.ALPHA_INTERPOLATE=u.ALPHA_INTERPOLATE,t.ALPHA_SCREENMODE=u.ALPHA_SCREENMODE,t.DELAYLOADSTATE_NONE=u.DELAYLOADSTATE_NONE,t.DELAYLOADSTATE_LOADED=u.DELAYLOADSTATE_LOADED,t.DELAYLOADSTATE_LOADING=u.DELAYLOADSTATE_LOADING,t.DELAYLOADSTATE_NOTLOADED=u.DELAYLOADSTATE_NOTLOADED,t.NEVER=u.NEVER,t.ALWAYS=u.ALWAYS,t.LESS=u.LESS,t.EQUAL=u.EQUAL,t.LEQUAL=u.LEQUAL,t.GREATER=u.GREATER,t.GEQUAL=u.GEQUAL,t.NOTEQUAL=u.NOTEQUAL,t.KEEP=u.KEEP,t.REPLACE=u.REPLACE,t.INCR=u.INCR,t.DECR=u.DECR,t.INVERT=u.INVERT,t.INCR_WRAP=u.INCR_WRAP,t.DECR_WRAP=u.DECR_WRAP,t.TEXTURE_CLAMP_ADDRESSMODE=u.TEXTURE_CLAMP_ADDRESSMODE,t.TEXTURE_WRAP_ADDRESSMODE=u.TEXTURE_WRAP_ADDRESSMODE,t.TEXTURE_MIRROR_ADDRESSMODE=u.TEXTURE_MIRROR_ADDRESSMODE,t.TEXTUREFORMAT_ALPHA=u.TEXTUREFORMAT_ALPHA,t.TEXTUREFORMAT_LUMINANCE=u.TEXTUREFORMAT_LUMINANCE,t.TEXTUREFORMAT_LUMINANCE_ALPHA=u.TEXTUREFORMAT_LUMINANCE_ALPHA,t.TEXTUREFORMAT_RGB=u.TEXTUREFORMAT_RGB,t.TEXTUREFORMAT_RGBA=u.TEXTUREFORMAT_RGBA,t.TEXTUREFORMAT_RED=u.TEXTUREFORMAT_RED,t.TEXTUREFORMAT_R=u.TEXTUREFORMAT_R,t.TEXTUREFORMAT_RG=u.TEXTUREFORMAT_RG,t.TEXTUREFORMAT_RED_INTEGER=u.TEXTUREFORMAT_RED_INTEGER,t.TEXTUREFORMAT_R_INTEGER=u.TEXTUREFORMAT_R_INTEGER,t.TEXTUREFORMAT_RG_INTEGER=u.TEXTUREFORMAT_RG_INTEGER,t.TEXTUREFORMAT_RGB_INTEGER=u.TEXTUREFORMAT_RGB_INTEGER,t.TEXTUREFORMAT_RGBA_INTEGER=u.TEXTUREFORMAT_RGBA_INTEGER,t.TEXTURETYPE_UNSIGNED_BYTE=u.TEXTURETYPE_UNSIGNED_BYTE,t.TEXTURETYPE_UNSIGNED_INT=u.TEXTURETYPE_UNSIGNED_INT,t.TEXTURETYPE_FLOAT=u.TEXTURETYPE_FLOAT,t.TEXTURETYPE_HALF_FLOAT=u.TEXTURETYPE_HALF_FLOAT,t.TEXTURETYPE_BYTE=u.TEXTURETYPE_BYTE,t.TEXTURETYPE_SHORT=u.TEXTURETYPE_SHORT,t.TEXTURETYPE_UNSIGNED_SHORT=u.TEXTURETYPE_UNSIGNED_SHORT,t.TEXTURETYPE_INT=u.TEXTURETYPE_INT,t.TEXTURETYPE_UNSIGNED_INTEGER=u.TEXTURETYPE_UNSIGNED_INTEGER,t.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=u.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4,t.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=u.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1,t.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=u.TEXTURETYPE_UNSIGNED_SHORT_5_6_5,t.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=u.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV,t.TEXTURETYPE_UNSIGNED_INT_24_8=u.TEXTURETYPE_UNSIGNED_INT_24_8,t.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=u.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV,t.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=u.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV,t.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=u.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV,t.TEXTURE_NEAREST_SAMPLINGMODE=u.TEXTURE_NEAREST_SAMPLINGMODE,t.TEXTURE_BILINEAR_SAMPLINGMODE=u.TEXTURE_BILINEAR_SAMPLINGMODE,t.TEXTURE_TRILINEAR_SAMPLINGMODE=u.TEXTURE_TRILINEAR_SAMPLINGMODE,t.TEXTURE_NEAREST_NEAREST_MIPLINEAR=u.TEXTURE_NEAREST_NEAREST_MIPLINEAR,t.TEXTURE_LINEAR_LINEAR_MIPNEAREST=u.TEXTURE_LINEAR_LINEAR_MIPNEAREST,t.TEXTURE_LINEAR_LINEAR_MIPLINEAR=u.TEXTURE_LINEAR_LINEAR_MIPLINEAR,t.TEXTURE_NEAREST_NEAREST_MIPNEAREST=u.TEXTURE_NEAREST_NEAREST_MIPNEAREST,t.TEXTURE_NEAREST_LINEAR_MIPNEAREST=u.TEXTURE_NEAREST_LINEAR_MIPNEAREST,t.TEXTURE_NEAREST_LINEAR_MIPLINEAR=u.TEXTURE_NEAREST_LINEAR_MIPLINEAR,t.TEXTURE_NEAREST_LINEAR=u.TEXTURE_NEAREST_LINEAR,t.TEXTURE_NEAREST_NEAREST=u.TEXTURE_NEAREST_NEAREST,t.TEXTURE_LINEAR_NEAREST_MIPNEAREST=u.TEXTURE_LINEAR_NEAREST_MIPNEAREST,t.TEXTURE_LINEAR_NEAREST_MIPLINEAR=u.TEXTURE_LINEAR_NEAREST_MIPLINEAR,t.TEXTURE_LINEAR_LINEAR=u.TEXTURE_LINEAR_LINEAR,t.TEXTURE_LINEAR_NEAREST=u.TEXTURE_LINEAR_NEAREST,t.TEXTURE_EXPLICIT_MODE=u.TEXTURE_EXPLICIT_MODE,t.TEXTURE_SPHERICAL_MODE=u.TEXTURE_SPHERICAL_MODE,t.TEXTURE_PLANAR_MODE=u.TEXTURE_PLANAR_MODE,t.TEXTURE_CUBIC_MODE=u.TEXTURE_CUBIC_MODE,t.TEXTURE_PROJECTION_MODE=u.TEXTURE_PROJECTION_MODE,t.TEXTURE_SKYBOX_MODE=u.TEXTURE_SKYBOX_MODE,t.TEXTURE_INVCUBIC_MODE=u.TEXTURE_INVCUBIC_MODE,t.TEXTURE_EQUIRECTANGULAR_MODE=u.TEXTURE_EQUIRECTANGULAR_MODE,t.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=u.TEXTURE_FIXED_EQUIRECTANGULAR_MODE,t.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=u.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE,t.SCALEMODE_FLOOR=u.SCALEMODE_FLOOR,t.SCALEMODE_NEAREST=u.SCALEMODE_NEAREST,t.SCALEMODE_CEILING=u.SCALEMODE_CEILING,t}(Er),No=z.Compose(V.One(),G.FromEulerAngles(0,Math.PI,0),V.Zero()),Fo=function(e){function t(i,r,n){void 0===r&&(r=null),void 0===n&&(n=!0);var o=e.call(this,i,r,!1)||this;return o._forward=new V(0,0,1),o._up=new V(0,1,0),o._right=new V(1,0,0),o._position=V.Zero(),o._rotation=V.Zero(),o._rotationQuaternion=null,o._scaling=V.One(),o._transformToBoneReferal=null,o._isAbsoluteSynced=!1,o._billboardMode=t.BILLBOARDMODE_NONE,o._preserveParentRotationForBillboard=!1,o.scalingDeterminant=1,o._infiniteDistance=!1,o.ignoreNonUniformScaling=!1,o.reIntegrateRotationIntoRotationQuaternion=!1,o._poseMatrix=null,o._localMatrix=z.Zero(),o._usePivotMatrix=!1,o._absolutePosition=V.Zero(),o._absoluteScaling=V.Zero(),o._absoluteRotationQuaternion=G.Identity(),o._pivotMatrix=z.Identity(),o._postMultiplyPivotMatrix=!1,o._isWorldMatrixFrozen=!1,o._indexInSceneTransformNodesArray=-1,o.onAfterWorldMatrixUpdateObservable=new f,o._nonUniformScaling=!1,n&&o.getScene().addTransformNode(o),o}return m(t,e),Object.defineProperty(t.prototype,"billboardMode",{get:function(){return this._billboardMode},set:function(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=!!(this._billboardMode&t.BILLBOARDMODE_USE_POSITION),this._computeUseBillboardPath())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"preserveParentRotationForBillboard",{get:function(){return this._preserveParentRotationForBillboard},set:function(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())},enumerable:!1,configurable:!0}),t.prototype._computeUseBillboardPath=function(){this._cache.useBillboardPath=this._billboardMode!==t.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard},Object.defineProperty(t.prototype,"infiniteDistance",{get:function(){return this._infiniteDistance},set:function(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"TransformNode"},Object.defineProperty(t.prototype,"position",{get:function(){return this._position},set:function(e){this._position=e,this._isDirty=!0},enumerable:!1,configurable:!0}),t.prototype.isUsingPivotMatrix=function(){return this._usePivotMatrix},t.prototype.isUsingPostMultiplyPivotMatrix=function(){return this._postMultiplyPivotMatrix},Object.defineProperty(t.prototype,"rotation",{get:function(){return this._rotation},set:function(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scaling",{get:function(){return this._scaling},set:function(e){this._scaling=e,this._isDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rotationQuaternion",{get:function(){return this._rotationQuaternion},set:function(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"forward",{get:function(){return V.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"up",{get:function(){return V.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return V.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem?-1:1,0,0,this.getWorldMatrix(),this._right),this._right.normalize()},enumerable:!1,configurable:!0}),t.prototype.updatePoseMatrix=function(e){return this._poseMatrix?(this._poseMatrix.copyFrom(e),this):(this._poseMatrix=e.clone(),this)},t.prototype.getPoseMatrix=function(){return this._poseMatrix||(this._poseMatrix=z.Identity()),this._poseMatrix},t.prototype._isSynchronized=function(){var e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==t.BILLBOARDMODE_NONE||e.pivotMatrixUpdated||this._infiniteDistance||this._position._isDirty||this._scaling._isDirty||this._rotationQuaternion&&this._rotationQuaternion._isDirty||this._rotation._isDirty)},t.prototype._initCache=function(){e.prototype._initCache.call(this);var t=this._cache;t.localMatrixUpdated=!1,t.billboardMode=-1,t.infiniteDistance=!1,t.useBillboardPosition=!1,t.useBillboardPath=!1},Object.defineProperty(t.prototype,"absolutePosition",{get:function(){return this.getAbsolutePosition()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"absoluteScaling",{get:function(){return this._syncAbsoluteScalingAndRotation(),this._absoluteScaling},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"absoluteRotationQuaternion",{get:function(){return this._syncAbsoluteScalingAndRotation(),this._absoluteRotationQuaternion},enumerable:!1,configurable:!0}),t.prototype.setPreTransformMatrix=function(e){return this.setPivotMatrix(e,!1)},t.prototype.setPivotMatrix=function(e,t){return void 0===t&&(t=!0),this._pivotMatrix.copyFrom(e),this._usePivotMatrix=!this._pivotMatrix.isIdentity(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=t,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=z.Invert(this._pivotMatrix)),this},t.prototype.getPivotMatrix=function(){return this._pivotMatrix},t.prototype.instantiateHierarchy=function(e,t,i){void 0===e&&(e=null);var r=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);r&&i&&i(this,r);for(var n=0,o=this.getChildTransformNodes(!0);n<o.length;n++)o[n].instantiateHierarchy(r,t,i);return r},t.prototype.freezeWorldMatrix=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||G.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this},t.prototype.unfreezeWorldMatrix=function(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this},Object.defineProperty(t.prototype,"isWorldMatrixFrozen",{get:function(){return this._isWorldMatrixFrozen},enumerable:!1,configurable:!0}),t.prototype.getAbsolutePosition=function(){return this.computeWorldMatrix(),this._absolutePosition},t.prototype.setAbsolutePosition=function(e){if(!e)return this;var t,i,r;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],r=arguments[2]}else t=e.x,i=e.y,r=e.z;if(this.parent){var n=H.Matrix[0];this.parent.getWorldMatrix().invertToRef(n),V.TransformCoordinatesFromFloatsToRef(t,i,r,n,this.position)}else this.position.x=t,this.position.y=i,this.position.z=r;return this._absolutePosition.copyFrom(e),this},t.prototype.setPositionWithLocalVector=function(e){return this.computeWorldMatrix(),this.position=V.TransformNormal(e,this._localMatrix),this},t.prototype.getPositionExpressedInLocalSpace=function(){this.computeWorldMatrix();var e=H.Matrix[0];return this._localMatrix.invertToRef(e),V.TransformNormal(this.position,e)},t.prototype.locallyTranslate=function(e){return this.computeWorldMatrix(!0),this.position=V.TransformCoordinates(e,this._localMatrix),this},t.prototype.lookAt=function(e,i,r,n,o){void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=0),void 0===o&&(o=dn.LOCAL);var a=t._LookAtVectorCache,s=o===dn.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(s,a),this.setDirection(a,i,r,n),o===dn.WORLD&&this.parent)if(this.rotationQuaternion){var l=H.Matrix[0];this.rotationQuaternion.toRotationMatrix(l);var c=H.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(c),c.invert(),l.multiplyToRef(c,l),this.rotationQuaternion.fromRotationMatrix(l)}else{var u=H.Quaternion[0];G.FromEulerVectorToRef(this.rotation,u),l=H.Matrix[0],u.toRotationMatrix(l),c=H.Matrix[1],this.parent.getWorldMatrix().getRotationMatrixToRef(c),c.invert(),l.multiplyToRef(c,l),u.fromRotationMatrix(l),u.toEulerAnglesToRef(this.rotation)}return this},t.prototype.getDirection=function(e){var t=V.Zero();return this.getDirectionToRef(e,t),t},t.prototype.getDirectionToRef=function(e,t){return V.TransformNormalToRef(e,this.getWorldMatrix(),t),this},t.prototype.setDirection=function(e,t,i,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0);var n=-Math.atan2(e.z,e.x)+Math.PI/2,o=Math.sqrt(e.x*e.x+e.z*e.z),a=-Math.atan2(e.y,o);return this.rotationQuaternion?G.RotationYawPitchRollToRef(n+t,a+i,r,this.rotationQuaternion):(this.rotation.x=a+i,this.rotation.y=n+t,this.rotation.z=r),this},t.prototype.setPivotPoint=function(e,t){void 0===t&&(t=dn.LOCAL),0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);var i=this.getWorldMatrix();if(t==dn.WORLD){var r=H.Matrix[0];i.invertToRef(r),e=V.TransformCoordinates(e,r)}return this.setPivotMatrix(z.Translation(-e.x,-e.y,-e.z),!0)},t.prototype.getPivotPoint=function(){var e=V.Zero();return this.getPivotPointToRef(e),e},t.prototype.getPivotPointToRef=function(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this},t.prototype.getAbsolutePivotPoint=function(){var e=V.Zero();return this.getAbsolutePivotPointToRef(e),e},t.prototype.getAbsolutePivotPointToRef=function(e){return this.getPivotPointToRef(e),V.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this},t.prototype.markAsDirty=function(t){if(this._isDirty)return this;if(this._children)for(var i=0,r=this._children;i<r.length;i++)r[i].markAsDirty(t);return e.prototype.markAsDirty.call(this,t)},t.prototype.setParent=function(e,i,r){if(void 0===i&&(i=!1),void 0===r&&(r=!1),!e&&!this.parent)return this;var n=H.Quaternion[0],o=H.Vector3[0],a=H.Vector3[1],s=H.Matrix[1];z.IdentityToRef(s);var l=H.Matrix[0];this.computeWorldMatrix(!0);var c=this.rotationQuaternion;return c||(c=t._TmpRotation,G.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,c)),z.ComposeToRef(this.scaling,c,this.position,l),this.parent&&l.multiplyToRef(this.parent.computeWorldMatrix(!0),l),e&&(e.computeWorldMatrix(!0).invertToRef(s),l.multiplyToRef(s,l)),l.decompose(a,n,o,i?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(n):n.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(a),this.position.copyFrom(o),this.parent=e,r&&this.setPivotMatrix(z.Identity()),this},Object.defineProperty(t.prototype,"nonUniformScaling",{get:function(){return this._nonUniformScaling},enumerable:!1,configurable:!0}),t.prototype._updateNonUniformScalingState=function(e){return this._nonUniformScaling!==e&&(this._nonUniformScaling=e,!0)},t.prototype.attachToBone=function(e,t){return this._currentParentWhenAttachingToBone=this.parent,this._transformToBoneReferal=t,this.parent=e,e.getSkeleton().prepare(!0),e.getFinalMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this},t.prototype.detachFromBone=function(e){return void 0===e&&(e=!1),this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,this.parent=e?this._currentParentWhenAttachingToBone:null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)},t.prototype.rotate=function(e,i,r){var n;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),r&&r!==dn.LOCAL){if(this.parent){var o=this.parent.getWorldMatrix(),a=H.Matrix[0];o.invertToRef(a),e=V.TransformNormal(e,a),o.determinant()<0&&(i*=-1)}(n=G.RotationAxisToRef(e,i,t._RotationAxisCache)).multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else n=G.RotationAxisToRef(e,i,t._RotationAxisCache),this.rotationQuaternion.multiplyToRef(n,this.rotationQuaternion);return this},t.prototype.rotateAround=function(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=G.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));var r=H.Vector3[0],n=H.Vector3[1],o=H.Vector3[2],a=H.Quaternion[0],s=H.Matrix[0],l=H.Matrix[1],c=H.Matrix[2],u=H.Matrix[3];return e.subtractToRef(this.position,r),z.TranslationToRef(r.x,r.y,r.z,s),z.TranslationToRef(-r.x,-r.y,-r.z,l),z.RotationAxisToRef(t,i,c),l.multiplyToRef(c,u),u.multiplyToRef(s,u),u.decompose(n,a,o),this.position.addInPlace(o),a.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this},t.prototype.translate=function(e,t,i){var r=e.scale(t);if(i&&i!==dn.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(r));else{var n=this.getPositionExpressedInLocalSpace().add(r);this.setPositionWithLocalVector(n)}return this},t.prototype.addRotation=function(e,t,i){var r;this.rotationQuaternion?r=this.rotationQuaternion:(r=H.Quaternion[1],G.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,r));var n=H.Quaternion[0];return G.RotationYawPitchRollToRef(t,e,i,n),r.multiplyInPlace(n),this.rotationQuaternion||r.toEulerAnglesToRef(this.rotation),this},t.prototype._getEffectiveParent=function(){return this.parent},t.prototype.isWorldMatrixCameraDependent=function(){return this._infiniteDistance&&!this.parent||this._billboardMode!==t.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard},t.prototype.computeWorldMatrix=function(e,i){if(void 0===e&&(e=!1),void 0===i&&(i=null),this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;var r=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===r||this.isSynchronized()))return this._currentRenderId=r,this._worldMatrix;i=i||this.getScene().activeCamera,this._updateCache();var n=this._cache;n.pivotMatrixUpdated=!1,n.billboardMode=this.billboardMode,n.infiniteDistance=this.infiniteDistance,n.parent=this._parentNode,this._currentRenderId=r,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;var o,a=this._getEffectiveParent(),s=t._TmpScaling,l=this._position;if(this._infiniteDistance&&!this.parent&&i){var c=i.getWorldMatrix(),u=new V(c.m[12],c.m[13],c.m[14]);(l=t._TmpTranslation).copyFromFloats(this._position.x+u.x,this._position.y+u.y,this._position.z+u.z)}if(s.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,o=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&(E=this.rotation.lengthSquared())&&(this._rotationQuaternion.multiplyInPlace(G.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(o=t._TmpRotation,G.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,o)),this._usePivotMatrix){var h=H.Matrix[1];z.ScalingToRef(s.x,s.y,s.z,h);var d=H.Matrix[0];o.toRotationMatrix(d),this._pivotMatrix.multiplyToRef(h,H.Matrix[4]),H.Matrix[4].multiplyToRef(d,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(l.x,l.y,l.z)}else z.ComposeToRef(s,o,l,this._localMatrix);if(a&&a.getWorldMatrix){if(e&&a.computeWorldMatrix(e),n.useBillboardPath){this._transformToBoneReferal?((m=this.parent).getSkeleton().prepare(),m.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),H.Matrix[7])):H.Matrix[7].copyFrom(a.getWorldMatrix());var p=H.Vector3[5],f=H.Vector3[6],_=H.Quaternion[0];H.Matrix[7].decompose(f,_,p),z.ScalingToRef(f.x,f.y,f.z,H.Matrix[7]),H.Matrix[7].setTranslation(p),t.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(_,p),this._localMatrix.setTranslation(p)),this._localMatrix.multiplyToRef(H.Matrix[7],this._worldMatrix)}else{var m;this._transformToBoneReferal?((m=this.parent).getSkeleton().prepare(),this._localMatrix.multiplyToRef(m.getFinalMatrix(),H.Matrix[6]),H.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)):this._localMatrix.multiplyToRef(a.getWorldMatrix(),this._worldMatrix)}this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(n.useBillboardPath&&i&&this.billboardMode&&!n.useBillboardPosition){var g=H.Vector3[0];if(this._worldMatrix.getTranslationToRef(g),H.Matrix[1].copyFrom(i.getViewMatrix()),this._scene.useRightHandedSystem&&H.Matrix[1].multiplyToRef(No,H.Matrix[1]),H.Matrix[1].setTranslationFromFloats(0,0,0),H.Matrix[1].invertToRef(H.Matrix[0]),(this.billboardMode&t.BILLBOARDMODE_ALL)!==t.BILLBOARDMODE_ALL){H.Matrix[0].decompose(void 0,H.Quaternion[0],void 0);var v=H.Vector3[1];H.Quaternion[0].toEulerAnglesToRef(v),(this.billboardMode&t.BILLBOARDMODE_X)!==t.BILLBOARDMODE_X&&(v.x=0),(this.billboardMode&t.BILLBOARDMODE_Y)!==t.BILLBOARDMODE_Y&&(v.y=0),(this.billboardMode&t.BILLBOARDMODE_Z)!==t.BILLBOARDMODE_Z&&(v.z=0),z.RotationYawPitchRollToRef(v.y,v.x,v.z,H.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(H.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(H.Vector3[0])}else if(n.useBillboardPath&&i&&n.useBillboardPosition){g=H.Vector3[0],this._worldMatrix.getTranslationToRef(g);var y=i.globalPosition;this._worldMatrix.invertToRef(H.Matrix[1]);var b=H.Vector3[1];V.TransformCoordinatesToRef(y,H.Matrix[1],b),b.normalize();var T=-Math.atan2(b.z,b.x)+Math.PI/2,E=Math.sqrt(b.x*b.x+b.z*b.z),S=-Math.atan2(b.y,E);G.RotationYawPitchRollToRef(T,S,0,H.Quaternion[0]),(this.billboardMode&t.BILLBOARDMODE_ALL)!==t.BILLBOARDMODE_ALL?(v=H.Vector3[1],H.Quaternion[0].toEulerAnglesToRef(v),(this.billboardMode&t.BILLBOARDMODE_X)!==t.BILLBOARDMODE_X&&(v.x=0),(this.billboardMode&t.BILLBOARDMODE_Y)!==t.BILLBOARDMODE_Y&&(v.y=0),(this.billboardMode&t.BILLBOARDMODE_Z)!==t.BILLBOARDMODE_Z&&(v.z=0),z.RotationYawPitchRollToRef(v.y,v.x,v.z,H.Matrix[0])):z.FromQuaternionToRef(H.Quaternion[0],H.Matrix[0]),this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(H.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(H.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):a&&a._nonUniformScaling?this._updateNonUniformScalingState(a._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=z.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix},t.prototype.resetLocalMatrix=function(e){if(void 0===e&&(e=!0),this.computeWorldMatrix(),e)for(var t=this.getChildren(),i=0;i<t.length;++i){var r=t[i];if(r){r.computeWorldMatrix();var n=H.Matrix[0];r._localMatrix.multiplyToRef(this._localMatrix,n);var o=H.Quaternion[0];n.decompose(r.scaling,o,r.position),r.rotationQuaternion?r.rotationQuaternion.copyFrom(o):o.toEulerAnglesToRef(r.rotation)}}this.scaling.copyFromFloats(1,1,1),this.position.copyFromFloats(0,0,0),this.rotation.copyFromFloats(0,0,0),this.rotationQuaternion&&(this.rotationQuaternion=G.Identity()),this._worldMatrix=z.Identity()},t.prototype._afterComputeWorldMatrix=function(){},t.prototype.registerAfterWorldMatrixUpdate=function(e){return this.onAfterWorldMatrixUpdateObservable.add(e),this},t.prototype.unregisterAfterWorldMatrixUpdate=function(e){return this.onAfterWorldMatrixUpdateObservable.removeCallback(e),this},t.prototype.getPositionInCameraSpace=function(e){return void 0===e&&(e=null),e||(e=this.getScene().activeCamera),V.TransformCoordinates(this.getAbsolutePosition(),e.getViewMatrix())},t.prototype.getDistanceToCamera=function(e){return void 0===e&&(e=null),e||(e=this.getScene().activeCamera),this.getAbsolutePosition().subtract(e.globalPosition).length()},t.prototype.clone=function(e,i,r){var n=this,o=Ke.Clone((function(){return new t(e,n.getScene())}),this);if(o.name=e,o.id=e,i&&(o.parent=i),!r)for(var a=this.getDescendants(!0),s=0;s<a.length;s++){var l=a[s];l.clone&&l.clone(e+"."+l.name,o)}return o},t.prototype.serialize=function(e){var t=Ke.Serialize(this,e);return t.type=this.getClassName(),t.uniqueId=this.uniqueId,this.parent&&this.parent._serializeAsParent(t),t.localMatrix=this.getPivotMatrix().asArray(),t.isEnabled=this.isEnabled(),Ke.AppendSerializedAnimations(this,t),t.ranges=this.serializeAnimationRanges(),t},t.Parse=function(e,i,r){var n=Ke.Parse((function(){return new t(e.name,i)}),e,i,r);if(e.localMatrix?n.setPreTransformMatrix(z.FromArray(e.localMatrix)):e.pivotMatrix&&n.setPivotMatrix(z.FromArray(e.pivotMatrix)),n.setEnabled(e.isEnabled),n._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(n._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(n._waitingParentInstanceIndex=e.parentInstanceIndex),e.animations){for(var o=0;o<e.animations.length;o++){var a=e.animations[o],l=s("BABYLON.Animation");l&&n.animations.push(l.Parse(a))}qe.ParseAnimationRanges(n,e,i)}return e.autoAnimate&&i.beginAnimation(n,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),n},t.prototype.getChildTransformNodes=function(e,i){var r=[];return this._getDescendants(r,e,(function(e){return(!i||i(e))&&e instanceof t})),r},t.prototype.dispose=function(t,i){if(void 0===i&&(i=!1),this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){var r=this._parentContainer.transformNodes.indexOf(this);r>-1&&this._parentContainer.transformNodes.splice(r,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),t)for(var n=0,o=this.getChildTransformNodes(!0);n<o.length;n++){var a=o[n];a.parent=null,a.computeWorldMatrix(!0)}e.prototype.dispose.call(this,t,i)},t.prototype.normalizeToUnitCube=function(e,t,i){void 0===e&&(e=!0),void 0===t&&(t=!1);var r=null,n=null;t&&(this.rotationQuaternion?(n=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(r=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));var o=this.getHierarchyBoundingVectors(e,i),a=o.max.subtract(o.min),s=Math.max(a.x,a.y,a.z);if(0===s)return this;var l=1/s;return this.scaling.scaleInPlace(l),t&&(this.rotationQuaternion&&n?this.rotationQuaternion.copyFrom(n):this.rotation&&r&&this.rotation.copyFrom(r)),this},t.prototype._syncAbsoluteScalingAndRotation=function(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)},t.BILLBOARDMODE_NONE=0,t.BILLBOARDMODE_X=1,t.BILLBOARDMODE_Y=2,t.BILLBOARDMODE_Z=4,t.BILLBOARDMODE_ALL=7,t.BILLBOARDMODE_USE_POSITION=128,t.BillboardUseParentOrientation=!1,t._TmpRotation=G.Zero(),t._TmpScaling=V.Zero(),t._TmpTranslation=V.Zero(),t._LookAtVectorCache=new V(0,0,0),t._RotationAxisCache=new G,v([Fe("position")],t.prototype,"_position",void 0),v([Fe("rotation")],t.prototype,"_rotation",void 0),v([Ve("rotationQuaternion")],t.prototype,"_rotationQuaternion",void 0),v([Fe("scaling")],t.prototype,"_scaling",void 0),v([Ie("billboardMode")],t.prototype,"_billboardMode",void 0),v([Ie()],t.prototype,"scalingDeterminant",void 0),v([Ie("infiniteDistance")],t.prototype,"_infiniteDistance",void 0),v([Ie()],t.prototype,"ignoreNonUniformScaling",void 0),v([Ie()],t.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0),t}(qe),Lo=function(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new V(0,0,0),this._diffPositionForCollisions=new V(0,0,0),this._collisionResponse=!0},wo=function(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=V.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1},Bo=function(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new wo,this._visibility=1,this._skeleton=null,this._layerMask=268435455,this._computeBonesUsingShaders=!0,this._isActive=!1,this._onlyForInstances=!1,this._isActiveIntermediate=!1,this._onlyForInstancesIntermediate=!1,this._actAsRegularMesh=!1,this._currentLOD=null,this._currentLODIsUpToDate=!1,this._collisionRetryCount=3,this._morphTargetManager=null,this._renderingGroupId=0,this._bakedVertexAnimationManager=null,this._material=null,this._positions=null,this._pointerOverDisableMeshTesting=!1,this._meshCollisionData=new Lo,this._enableDistantPicking=!1,this._rawBoundingInfo=null},Uo=function(e){function t(i,r){void 0===r&&(r=null);var n=e.call(this,i,r,!1)||this;switch(n._internalAbstractMeshDataInfo=new Bo,n._waitingMaterialId=null,n.cullingStrategy=t.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,n.onCollideObservable=new f,n.onCollisionPositionChangeObservable=new f,n.onMaterialChangedObservable=new f,n.definedFacingForward=!0,n._occlusionQuery=null,n._renderingGroup=null,n.alphaIndex=Number.MAX_VALUE,n.isVisible=!0,n.isPickable=!0,n.isNearPickable=!1,n.isNearGrabbable=!1,n.showSubMeshesBoundingBox=!1,n.isBlocker=!1,n.enablePointerMoveEvents=!1,n.outlineColor=Z.Red(),n.outlineWidth=.02,n.overlayColor=Z.Red(),n.overlayAlpha=.5,n.useOctreeForRenderingSelection=!0,n.useOctreeForPicking=!0,n.useOctreeForCollisions=!0,n.alwaysSelectAsActiveMesh=!1,n.doNotSyncBoundingInfo=!1,n.actionManager=null,n.ellipsoid=new V(.5,1,.5),n.ellipsoidOffset=new V(0,0,0),n.edgesWidth=1,n.edgesColor=new J(1,0,0,1),n._edgesRenderer=null,n._masterMesh=null,n._boundingInfo=null,n._boundingInfoIsDirty=!0,n._renderId=0,n._intersectionsInProgress=new Array,n._unIndexed=!1,n._lightSources=new Array,n._waitingData={lods:null,actions:null,freezeWorldMatrix:null},n._bonesTransformMatrices=null,n._transformMatrixTexture=null,n.onRebuildObservable=new f,n._onCollisionPositionChange=function(e,t,i){void 0===i&&(i=null),t.subtractToRef(n._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,n._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),n._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>Do.CollisionsEpsilon&&n.position.addInPlace(n._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),i&&n.onCollideObservable.notifyObservers(i),n.onCollisionPositionChangeObservable.notifyObservers(n.position)},(r=n.getScene()).addMesh(n),n._resyncLightSources(),n._uniformBuffer=new Or(n.getScene().getEngine(),void 0,void 0,i,!n.getScene().getEngine().isWebGPU),n._buildUniformLayout(),r.performancePriority){case Kr.Aggressive:n.doNotSyncBoundingInfo=!0;case Kr.Intermediate:n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1}return n}return m(t,e),Object.defineProperty(t,"BILLBOARDMODE_NONE",{get:function(){return Fo.BILLBOARDMODE_NONE},enumerable:!1,configurable:!0}),Object.defineProperty(t,"BILLBOARDMODE_X",{get:function(){return Fo.BILLBOARDMODE_X},enumerable:!1,configurable:!0}),Object.defineProperty(t,"BILLBOARDMODE_Y",{get:function(){return Fo.BILLBOARDMODE_Y},enumerable:!1,configurable:!0}),Object.defineProperty(t,"BILLBOARDMODE_Z",{get:function(){return Fo.BILLBOARDMODE_Z},enumerable:!1,configurable:!0}),Object.defineProperty(t,"BILLBOARDMODE_ALL",{get:function(){return Fo.BILLBOARDMODE_ALL},enumerable:!1,configurable:!0}),Object.defineProperty(t,"BILLBOARDMODE_USE_POSITION",{get:function(){return Fo.BILLBOARDMODE_USE_POSITION},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"facetNb",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetNb},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"partitioningSubdivisions",{get:function(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions},set:function(e){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"partitioningBBoxRatio",{get:function(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio},set:function(e){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"mustDepthSortFacets",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort},set:function(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"facetDepthSortFrom",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom},set:function(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"collisionRetryCount",{get:function(){return this._internalAbstractMeshDataInfo._collisionRetryCount},set:function(e){this._internalAbstractMeshDataInfo._collisionRetryCount=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isFacetDataEnabled",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"morphTargetManager",{get:function(){return this._internalAbstractMeshDataInfo._morphTargetManager},set:function(e){this._internalAbstractMeshDataInfo._morphTargetManager!==e&&(this._internalAbstractMeshDataInfo._morphTargetManager=e,this._syncGeometryWithMorphTargetManager())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"bakedVertexAnimationManager",{get:function(){return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager},set:function(e){this._internalAbstractMeshDataInfo._bakedVertexAnimationManager!==e&&(this._internalAbstractMeshDataInfo._bakedVertexAnimationManager=e,this._markSubMeshesAsAttributesDirty())},enumerable:!1,configurable:!0}),t.prototype._syncGeometryWithMorphTargetManager=function(){},t.prototype._updateNonUniformScalingState=function(t){return!!e.prototype._updateNonUniformScalingState.call(this,t)&&(this._markSubMeshesAsMiscDirty(),!0)},Object.defineProperty(t.prototype,"rawBoundingInfo",{get:function(){return this._internalAbstractMeshDataInfo._rawBoundingInfo},set:function(e){this._internalAbstractMeshDataInfo._rawBoundingInfo=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onCollide",{set:function(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onCollisionPositionChange",{set:function(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"visibility",{get:function(){return this._internalAbstractMeshDataInfo._visibility},set:function(e){if(this._internalAbstractMeshDataInfo._visibility!==e){var t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(1===t&&1!==e||1!==t&&1===e)&&this._markSubMeshesAsDirty((function(e){e.markAsMiscDirty(),e.markAsPrePassDirty()}))}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"pointerOverDisableMeshTesting",{get:function(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting},set:function(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"renderingGroupId",{get:function(){return this._internalAbstractMeshDataInfo._renderingGroupId},set:function(e){this._internalAbstractMeshDataInfo._renderingGroupId=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"material",{get:function(){return this._internalAbstractMeshDataInfo._material},set:function(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(),this._unBindEffect()))},enumerable:!1,configurable:!0}),t.prototype.getMaterialForRenderPass=function(e){var t;return null===(t=this._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===t?void 0:t[e]},t.prototype.setMaterialForRenderPass=function(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t},Object.defineProperty(t.prototype,"receiveShadows",{get:function(){return this._internalAbstractMeshDataInfo._receiveShadows},set:function(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hasVertexAlpha",{get:function(){return this._internalAbstractMeshDataInfo._hasVertexAlpha},set:function(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"useVertexColors",{get:function(){return this._internalAbstractMeshDataInfo._useVertexColors},set:function(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"computeBonesUsingShaders",{get:function(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders},set:function(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"numBoneInfluencers",{get:function(){return this._internalAbstractMeshDataInfo._numBoneInfluencers},set:function(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"applyFog",{get:function(){return this._internalAbstractMeshDataInfo._applyFog},set:function(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"enableDistantPicking",{get:function(){return this._internalAbstractMeshDataInfo._enableDistantPicking},set:function(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"layerMask",{get:function(){return this._internalAbstractMeshDataInfo._layerMask},set:function(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"collisionMask",{get:function(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask},set:function(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"collisionResponse",{get:function(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse},set:function(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"collisionGroup",{get:function(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup},set:function(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"surroundingMeshes",{get:function(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes},set:function(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"lightSources",{get:function(){return this._lightSources},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_positions",{get:function(){return null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"skeleton",{get:function(){return this._internalAbstractMeshDataInfo._skeleton},set:function(e){var t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()},enumerable:!1,configurable:!0}),t.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()},t.prototype.transferToEffect=function(e){var t=this._uniformBuffer;t.updateMatrix("world",e),t.updateFloat("visibility",this._internalAbstractMeshDataInfo._visibility),t.update()},t.prototype.getMeshUniformBuffer=function(){return this._uniformBuffer},t.prototype.getClassName=function(){return"AbstractMesh"},t.prototype.toString=function(e){var t="Name: "+this.name+", isInstance: "+("InstancedMesh"!==this.getClassName()?"YES":"NO");t+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0);var i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],t+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t},t.prototype._getEffectiveParent=function(){return this._masterMesh&&this.billboardMode!==Fo.BILLBOARDMODE_NONE?this._masterMesh:e.prototype._getEffectiveParent.call(this)},t.prototype._getActionManagerForTrigger=function(e,t){if(void 0===t&&(t=!0),this.actionManager&&(t||this.actionManager.isRecursive)){if(!e)return this.actionManager;if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}return this.parent?this.parent._getActionManagerForTrigger(e,!1):null},t.prototype._rebuild=function(e){if(void 0===e&&(e=!1),this.onRebuildObservable.notifyObservers(this),null!==this._occlusionQuery&&(this._occlusionQuery=null),this.subMeshes){for(var t=0,i=this.subMeshes;t<i.length;t++)i[t]._rebuild();this.resetDrawCache()}},t.prototype._resyncLightSources=function(){this._lightSources.length=0;for(var e=0,t=this.getScene().lights;e<t.length;e++){var i=t[e];i.isEnabled()&&i.canAffectMesh(this)&&this._lightSources.push(i)}this._markSubMeshesAsLightDirty()},t.prototype._resyncLightSource=function(e){var t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e),r=!1;if(-1===i){if(!t)return;this._lightSources.push(e)}else{if(t)return;r=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(r)},t.prototype._unBindEffect=function(){for(var e=0,t=this.subMeshes;e<t.length;e++)t[e].setEffect(null)},t.prototype._removeLightSource=function(e,t){var i=this._lightSources.indexOf(e);-1!==i&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))},t.prototype._markSubMeshesAsDirty=function(e){if(this.subMeshes)for(var t=0,i=this.subMeshes;t<i.length;t++)for(var r=i[t],n=0;n<r._drawWrappers.length;++n){var o=r._drawWrappers[n];o&&o.defines&&o.defines.markAllAsDirty&&e(o.defines)}},t.prototype._markSubMeshesAsLightDirty=function(e){void 0===e&&(e=!1),this._markSubMeshesAsDirty((function(t){return t.markAsLightDirty(e)}))},t.prototype._markSubMeshesAsAttributesDirty=function(){this._markSubMeshesAsDirty((function(e){return e.markAsAttributesDirty()}))},t.prototype._markSubMeshesAsMiscDirty=function(){this._markSubMeshesAsDirty((function(e){return e.markAsMiscDirty()}))},t.prototype.markAsDirty=function(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this},t.prototype.resetDrawCache=function(e){if(this.subMeshes)for(var t=0,i=this.subMeshes;t<i.length;t++)i[t].resetDrawCache(e)},Object.defineProperty(t.prototype,"isBlocked",{get:function(){return!1},enumerable:!1,configurable:!0}),t.prototype.getLOD=function(e){return this},t.prototype.getTotalVertices=function(){return 0},t.prototype.getTotalIndices=function(){return 0},t.prototype.getIndices=function(){return null},t.prototype.getVerticesData=function(e){return null},t.prototype.setVerticesData=function(e,t,i,r){return this},t.prototype.updateVerticesData=function(e,t,i,r){return this},t.prototype.setIndices=function(e,t){return this},t.prototype.isVerticesDataPresent=function(e){return!1},t.prototype.getBoundingInfo=function(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)},t.prototype.getRawBoundingInfo=function(){var e;return null!==(e=this.rawBoundingInfo)&&void 0!==e?e:this.getBoundingInfo()},t.prototype.setBoundingInfo=function(e){return this._boundingInfo=e,this},Object.defineProperty(t.prototype,"hasBoundingInfo",{get:function(){return null!==this._boundingInfo},enumerable:!1,configurable:!0}),t.prototype.buildBoundingInfo=function(e,t,i){return this._boundingInfo=new so(e,t,i),this._boundingInfo},t.prototype.normalizeToUnitCube=function(t,i,r){return void 0===t&&(t=!0),void 0===i&&(i=!1),e.prototype.normalizeToUnitCube.call(this,t,i,r)},Object.defineProperty(t.prototype,"useBones",{get:function(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(Nr.MatricesIndicesKind)&&this.isVerticesDataPresent(Nr.MatricesWeightsKind)},enumerable:!1,configurable:!0}),t.prototype._preActivate=function(){},t.prototype._preActivateForIntermediateRendering=function(e){},t.prototype._activate=function(e,t){return this._renderId=e,!0},t.prototype._postActivate=function(){},t.prototype._freeze=function(){},t.prototype._unFreeze=function(){},t.prototype.getWorldMatrix=function(){return this._masterMesh&&this.billboardMode===Fo.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():e.prototype.getWorldMatrix.call(this)},t.prototype._getWorldMatrixDeterminant=function(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():e.prototype._getWorldMatrixDeterminant.call(this)},Object.defineProperty(t.prototype,"isAnInstance",{get:function(){return!1},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hasInstances",{get:function(){return!1},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hasThinInstances",{get:function(){return!1},enumerable:!1,configurable:!0}),t.prototype.movePOV=function(e,t,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this},t.prototype.calcMovePOV=function(e,t,i){var r=new z;(this.rotationQuaternion?this.rotationQuaternion:G.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(r);var n=V.Zero(),o=this.definedFacingForward?-1:1;return V.TransformCoordinatesFromFloatsToRef(e*o,t,i*o,r,n),n},t.prototype.rotatePOV=function(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this},t.prototype.calcRotatePOV=function(e,t,i){var r=this.definedFacingForward?1:-1;return new V(e*r,t,i*r)},t.prototype.refreshBoundingInfo=function(e,t){return void 0===e&&(e=!1),void 0===t&&(t=!1),this._boundingInfo&&this._boundingInfo.isLocked||this._refreshBoundingInfo(this._getPositionData(e,t),null),this},t.prototype._refreshBoundingInfo=function(e,t){if(e){var i=uo(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new so(i.minimum,i.maximum)}if(this.subMeshes)for(var r=0;r<this.subMeshes.length;r++)this.subMeshes[r].refreshBoundingInfo(e);this._updateBoundingInfo()},t.prototype._getData=function(e,t,i,r){if(void 0===e&&(e=!1),void 0===t&&(t=!1),void 0===r&&(r=Nr.PositionKind),(i=null!=i?i:this.getVerticesData(r).slice())&&t&&this.morphTargetManager)for(var n=0,o=0,a=0;a<i.length;a++){for(var s=i[a],l=0;l<this.morphTargetManager.numTargets;l++){var c=this.morphTargetManager.getTarget(l),u=c.influence;if(0!==u){var h=null;switch(r){case Nr.PositionKind:h=c.getPositions();break;case Nr.NormalKind:h=c.getNormals();break;case Nr.TangentKind:h=c.getTangents();break;case Nr.UVKind:h=c.getUVs()}h&&(s+=(h[a]-i[a])*u)}}if(i[a]=s,n++,r===Nr.PositionKind&&this._positions&&3===n){n=0;var d=3*o;this._positions[o++].copyFromFloats(i[d],i[d+1],i[d+2])}}if(i&&e&&this.skeleton){var p=this.getVerticesData(Nr.MatricesIndicesKind),f=this.getVerticesData(Nr.MatricesWeightsKind);if(f&&p){var _=this.numBoneInfluencers>4,m=_?this.getVerticesData(Nr.MatricesIndicesExtraKind):null,g=_?this.getVerticesData(Nr.MatricesWeightsExtraKind):null,v=this.skeleton.getTransformMatrices(this),y=H.Vector3[0],b=H.Matrix[0],T=H.Matrix[1],E=0;for(d=0;d<i.length;d+=3,E+=4){b.reset();var S=void 0,x=void 0;for(S=0;S<4;S++)(x=f[E+S])>0&&(z.FromFloat32ArrayToRefScaled(v,Math.floor(16*p[E+S]),x,T),b.addToSelf(T));if(_)for(S=0;S<4;S++)(x=g[E+S])>0&&(z.FromFloat32ArrayToRefScaled(v,Math.floor(16*m[E+S]),x,T),b.addToSelf(T));r===Nr.NormalKind?V.TransformNormalFromFloatsToRef(i[d],i[d+1],i[d+2],b,y):V.TransformCoordinatesFromFloatsToRef(i[d],i[d+1],i[d+2],b,y),y.toArray(i,d),r===Nr.PositionKind&&this._positions&&this._positions[d/3].copyFrom(y)}}}return i},t.prototype.getNormalsData=function(e,t){return void 0===e&&(e=!1),void 0===t&&(t=!1),this._getData(e,t,null,Nr.NormalKind)},t.prototype.getPositionData=function(e,t,i){return void 0===e&&(e=!1),void 0===t&&(t=!1),this._getData(e,t,i,Nr.PositionKind)},t.prototype._getPositionData=function(e,t){var i,r=this.getVerticesData(Nr.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),r&&(e&&this.skeleton||t&&this.morphTargetManager)){if(r=r.slice(),this._generatePointsArray(),this._positions){var n=this._positions;this._internalAbstractMeshDataInfo._positions=new Array(n.length);for(var o=0;o<n.length;o++)this._internalAbstractMeshDataInfo._positions[o]=(null===(i=n[o])||void 0===i?void 0:i.clone())||new V}return this.getPositionData(e,t,r)}return r},t.prototype._updateBoundingInfo=function(){return this._boundingInfo?this._boundingInfo.update(this.worldMatrixFromCache):this._boundingInfo=new so(V.Zero(),V.Zero(),this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this},t.prototype._updateSubMeshesBoundingInfo=function(e){if(!this.subMeshes)return this;for(var t=this.subMeshes.length,i=0;i<t;i++){var r=this.subMeshes[i];(t>1||!r.IsGlobal)&&r.updateBoundingInfo(e)}return this},t.prototype._afterComputeWorldMatrix=function(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)},t.prototype.isInFrustum=function(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)},t.prototype.isCompletelyInFrustum=function(e){return this.getBoundingInfo().isCompletelyInFrustum(e)},t.prototype.intersectsMesh=function(e,t,i){void 0===t&&(t=!1);var r=this.getBoundingInfo(),n=e.getBoundingInfo();if(r.intersects(n,t))return!0;if(i)for(var o=0,a=this.getChildMeshes();o<a.length;o++)if(a[o].intersectsMesh(e,t,!0))return!0;return!1},t.prototype.intersectsPoint=function(e){return this.getBoundingInfo().intersectsPoint(e)},Object.defineProperty(t.prototype,"checkCollisions",{get:function(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions},set:function(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"collider",{get:function(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider},enumerable:!1,configurable:!0}),t.prototype.moveWithCollisions=function(e){this.getAbsolutePosition().addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);var t=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=t.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,t.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this},t.prototype._collideForSubMesh=function(e,t,i){var r;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,o=e.verticesStart+e.verticesCount,a=n;a<o;a++)e._lastColliderWorldVertices.push(V.TransformCoordinates(this._positions[a],t))}return i._collide(e._trianglePlanes,e._lastColliderWorldVertices,this.getIndices(),e.indexStart,e.indexStart+e.indexCount,e.verticesStart,!!e.getMaterial(),this,this._shouldConvertRHS(),(null===(r=e.getMaterial())||void 0===r?void 0:r.fillMode)===u.MATERIAL_TriangleStripDrawMode),this},t.prototype._processCollisionsForSubMeshes=function(e,t){for(var i=this._scene.getCollidingSubMeshCandidates(this,e),r=i.length,n=0;n<r;n++){var o=i.data[n];r>1&&!o._checkCollision(e)||this._collideForSubMesh(o,t,e)}return this},t.prototype._shouldConvertRHS=function(){return!1},t.prototype._checkCollision=function(e){if(!this.getBoundingInfo()._checkCollision(e))return this;var t=H.Matrix[0],i=H.Matrix[1];return z.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this},t.prototype._generatePointsArray=function(){return!1},t.prototype.intersects=function(e,t,i,r,n,o){void 0===r&&(r=!1),void 0===o&&(o=!1);var a=new Fr,s=this.getClassName(),l="InstancedLinesMesh"===s||"LinesMesh"===s||"GreasedLineMesh"===s?this.intersectionThreshold:0,c=this.getBoundingInfo();if(!this.subMeshes)return a;if(!(o||e.intersectsSphere(c.boundingSphere,l)&&e.intersectsBox(c.boundingBox,l)))return a;if(r)return a.hit=!o,a.pickedMesh=o?null:this,a.distance=o?0:V.Distance(e.origin,c.boundingSphere.center),a.subMeshId=0,a;if(!this._generatePointsArray())return a;for(var h=null,d=this._scene.getIntersectingSubMeshCandidates(this,e),p=d.length,f=!1,_=0;_<p;_++){var m=(g=d.data[_]).getMaterial();if(m&&(m.fillMode==u.MATERIAL_TriangleStripDrawMode||m.fillMode==u.MATERIAL_TriangleFillMode||m.fillMode==u.MATERIAL_WireFrameFillMode||m.fillMode==u.MATERIAL_PointFillMode||m.fillMode==u.MATERIAL_LineListDrawMode)){f=!0;break}}if(!f)return a.hit=!0,a.pickedMesh=this,a.distance=V.Distance(e.origin,c.boundingSphere.center),a.subMeshId=-1,a;for(_=0;_<p;_++){var g=d.data[_];if(!(p>1)||o||g.canIntersects(e)){var v=g.intersects(e,this._positions,this.getIndices(),t,i);if(v&&(t||!h||v.distance<h.distance)&&((h=v).subMeshId=_,t))break}}if(h){var y=null!=n?n:this.getWorldMatrix(),b=H.Vector3[0],T=H.Vector3[1];V.TransformCoordinatesToRef(e.origin,y,b),e.direction.scaleToRef(h.distance,T);var E=V.TransformNormal(T,y).addInPlace(b);return a.hit=!0,a.distance=V.Distance(b,E),a.pickedPoint=E,a.pickedMesh=this,a.bu=h.bu||0,a.bv=h.bv||0,a.subMeshFaceId=h.faceId,a.faceId=h.faceId+d.data[h.subMeshId].indexStart/(-1!==this.getClassName().indexOf("LinesMesh")?2:3),a.subMeshId=h.subMeshId,a}return a},t.prototype.clone=function(e,t,i){return null},t.prototype.releaseSubMeshes=function(){if(this.subMeshes)for(;this.subMeshes.length;)this.subMeshes[0].dispose();else this.subMeshes=[];return this},t.prototype.dispose=function(t,i){var r,n=this;void 0===i&&(i=!1);var o=this.getScene();for(this._scene.useMaterialMeshMap&&this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),o.freeActiveMeshes(),o.freeRenderingGroups(),o.renderingManager.maintainStateBetweenFrames&&o.renderingManager.restoreDispachedFlags(),void 0!==this.actionManager&&null!==this.actionManager&&(this._scene.meshes.some((function(e){return e!==n&&e.actionManager===n.actionManager}))||this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),r=0;r<this._intersectionsInProgress.length;r++){var a=this._intersectionsInProgress[r],s=a._intersectionsInProgress.indexOf(this);a._intersectionsInProgress.splice(s,1)}this._intersectionsInProgress.length=0,o.lights.forEach((function(e){var t=e.includedOnlyMeshes.indexOf(n);-1!==t&&e.includedOnlyMeshes.splice(t,1),-1!==(t=e.excludedMeshes.indexOf(n))&&e.excludedMeshes.splice(t,1);var i=e.getShadowGenerators();if(i)for(var r=i.values(),o=r.next();!0!==o.done;o=r.next()){var a=o.value.getShadowMap();a&&a.renderList&&-1!==(t=a.renderList.indexOf(n))&&a.renderList.splice(t,1)}})),"InstancedMesh"===this.getClassName()&&"InstancedLinesMesh"===this.getClassName()||this.releaseSubMeshes();var l=o.getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,l.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),l.wipeCaches(),o.removeMesh(this),this._parentContainer){var c=this._parentContainer.meshes.indexOf(this);c>-1&&this._parentContainer.meshes.splice(c,1),this._parentContainer=null}if(i&&this.material&&("MultiMaterial"===this.material.getClassName()?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!t)for(r=0;r<o.particleSystems.length;r++)o.particleSystems[r].emitter===this&&(o.particleSystems[r].dispose(),r--);this._internalAbstractMeshDataInfo._facetData.facetDataEnabled&&this.disableFacetData(),this._uniformBuffer.dispose(),this.onAfterWorldMatrixUpdateObservable.clear(),this.onCollideObservable.clear(),this.onCollisionPositionChangeObservable.clear(),this.onRebuildObservable.clear(),e.prototype.dispose.call(this,t,i)},t.prototype.addChild=function(e,t){return void 0===t&&(t=!1),e.setParent(this,t),this},t.prototype.removeChild=function(e,t){return void 0===t&&(t=!1),e.setParent(null,t),this},t.prototype._initFacetData=function(){var e=this._internalAbstractMeshDataInfo._facetData;e.facetNormals||(e.facetNormals=[]),e.facetPositions||(e.facetPositions=[]),e.facetPartitioning||(e.facetPartitioning=new Array),e.facetNb=this.getIndices().length/3|0,e.partitioningSubdivisions=e.partitioningSubdivisions?e.partitioningSubdivisions:10,e.partitioningBBoxRatio=e.partitioningBBoxRatio?e.partitioningBBoxRatio:1.01;for(var t=0;t<e.facetNb;t++)e.facetNormals[t]=V.Zero(),e.facetPositions[t]=V.Zero();return e.facetDataEnabled=!0,this},t.prototype.updateFacetData=function(){var e=this._internalAbstractMeshDataInfo._facetData;e.facetDataEnabled||this._initFacetData();var t=this.getVerticesData(Nr.PositionKind),i=this.getIndices(),r=this.getVerticesData(Nr.NormalKind),n=this.getBoundingInfo();if(e.facetDepthSort&&!e.facetDepthSortEnabled){if(e.facetDepthSortEnabled=!0,i instanceof Uint16Array)e.depthSortedIndices=new Uint16Array(i);else if(i instanceof Uint32Array)e.depthSortedIndices=new Uint32Array(i);else{for(var o=!1,a=0;a<i.length;a++)if(i[a]>65535){o=!0;break}e.depthSortedIndices=o?new Uint32Array(i):new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){var s=this.getScene().activeCamera;e.facetDepthSortFrom=s?s.position:V.Zero()}e.depthSortedFacets=[];for(var l=0;l<e.facetNb;l++){var c={ind:3*l,sqDistance:0};e.depthSortedFacets.push(c)}e.invertedMatrix=z.Identity(),e.facetDepthSortOrigin=V.Zero()}e.bbSize.x=n.maximum.x-n.minimum.x>A?n.maximum.x-n.minimum.x:A,e.bbSize.y=n.maximum.y-n.minimum.y>A?n.maximum.y-n.minimum.y:A,e.bbSize.z=n.maximum.z-n.minimum.z>A?n.maximum.z-n.minimum.z:A;var u=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(u=u>e.bbSize.z?u:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/u),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/u),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/u),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=n,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),V.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,r&&_o.ComputeNormals(t,i,r,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);var h=e.depthSortedIndices.length/3|0;for(l=0;l<h;l++){var d=e.depthSortedFacets[l].ind;e.depthSortedIndices[3*l]=i[d],e.depthSortedIndices[3*l+1]=i[d+1],e.depthSortedIndices[3*l+2]=i[d+2]}this.updateIndices(e.depthSortedIndices,void 0,!0)}return this},t.prototype.getFacetLocalNormals=function(){var e=this._internalAbstractMeshDataInfo._facetData;return e.facetNormals||this.updateFacetData(),e.facetNormals},t.prototype.getFacetLocalPositions=function(){var e=this._internalAbstractMeshDataInfo._facetData;return e.facetPositions||this.updateFacetData(),e.facetPositions},t.prototype.getFacetLocalPartitioning=function(){var e=this._internalAbstractMeshDataInfo._facetData;return e.facetPartitioning||this.updateFacetData(),e.facetPartitioning},t.prototype.getFacetPosition=function(e){var t=V.Zero();return this.getFacetPositionToRef(e,t),t},t.prototype.getFacetPositionToRef=function(e,t){var i=this.getFacetLocalPositions()[e],r=this.getWorldMatrix();return V.TransformCoordinatesToRef(i,r,t),this},t.prototype.getFacetNormal=function(e){var t=V.Zero();return this.getFacetNormalToRef(e,t),t},t.prototype.getFacetNormalToRef=function(e,t){var i=this.getFacetLocalNormals()[e];return V.TransformNormalToRef(i,this.getWorldMatrix(),t),this},t.prototype.getFacetsAtLocalCoordinates=function(e,t,i){var r=this.getBoundingInfo(),n=this._internalAbstractMeshDataInfo._facetData,o=Math.floor((e-r.minimum.x*n.partitioningBBoxRatio)*n.subDiv.X*n.partitioningBBoxRatio/n.bbSize.x),a=Math.floor((t-r.minimum.y*n.partitioningBBoxRatio)*n.subDiv.Y*n.partitioningBBoxRatio/n.bbSize.y),s=Math.floor((i-r.minimum.z*n.partitioningBBoxRatio)*n.subDiv.Z*n.partitioningBBoxRatio/n.bbSize.z);return o<0||o>n.subDiv.max||a<0||a>n.subDiv.max||s<0||s>n.subDiv.max?null:n.facetPartitioning[o+n.subDiv.max*a+n.subDiv.max*n.subDiv.max*s]},t.prototype.getClosestFacetAtCoordinates=function(e,t,i,r,n,o){void 0===n&&(n=!1),void 0===o&&(o=!0);var a=this.getWorldMatrix(),s=H.Matrix[5];a.invertToRef(s);var l=H.Vector3[8];V.TransformCoordinatesFromFloatsToRef(e,t,i,s,l);var c=this.getClosestFacetAtLocalCoordinates(l.x,l.y,l.z,r,n,o);return r&&V.TransformCoordinatesFromFloatsToRef(r.x,r.y,r.z,a,r),c},t.prototype.getClosestFacetAtLocalCoordinates=function(e,t,i,r,n,o){void 0===n&&(n=!1),void 0===o&&(o=!0);var a=null,s=0,l=0,c=0,u=0,h=0,d=0,p=0,f=0,_=this.getFacetLocalPositions(),m=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;for(var v,y,b,T=Number.MAX_VALUE,E=T,S=0;S<g.length;S++)y=m[v=g[S]],u=(e-(b=_[v]).x)*y.x+(t-b.y)*y.y+(i-b.z)*y.z,(!n||n&&o&&u>=0||n&&!o&&u<=0)&&(u=y.x*b.x+y.y*b.y+y.z*b.z,h=-(y.x*e+y.y*t+y.z*i-u)/(y.x*y.x+y.y*y.y+y.z*y.z),(E=(s=(d=e+y.x*h)-e)*s+(l=(p=t+y.y*h)-t)*l+(c=(f=i+y.z*h)-i)*c)<T&&(T=E,a=v,r&&(r.x=d,r.y=p,r.z=f)));return a},t.prototype.getFacetDataParameters=function(){return this._internalAbstractMeshDataInfo._facetData.facetParameters},t.prototype.disableFacetData=function(){var e=this._internalAbstractMeshDataInfo._facetData;return e.facetDataEnabled&&(e.facetDataEnabled=!1,e.facetPositions=[],e.facetNormals=[],e.facetPartitioning=new Array,e.facetParameters=null,e.depthSortedIndices=new Uint32Array(0)),this},t.prototype.updateIndices=function(e,t,i){return void 0===i&&(i=!1),this},t.prototype.createNormals=function(e){var t,i=this.getVerticesData(Nr.PositionKind),r=this.getIndices();return t=this.isVerticesDataPresent(Nr.NormalKind)?this.getVerticesData(Nr.NormalKind):[],_o.ComputeNormals(i,r,t,{useRightHandedSystem:this.getScene().useRightHandedSystem}),this.setVerticesData(Nr.NormalKind,t,e),this},t.prototype.alignWithNormal=function(e,t){t||(t=_n.Y);var i=H.Vector3[0],r=H.Vector3[1];return V.CrossToRef(t,e,r),V.CrossToRef(e,r,i),this.rotationQuaternion?G.RotationQuaternionFromAxisToRef(i,e,r,this.rotationQuaternion):V.RotationFromAxisToRef(i,e,r,this.rotation),this},t.prototype._checkOcclusionQuery=function(){return!1},t.prototype.disableEdgesRendering=function(){throw He("EdgesRenderer")},t.prototype.enableEdgesRendering=function(e,t,i){throw He("EdgesRenderer")},t.prototype.getConnectedParticleSystems=function(){var e=this;return this._scene.particleSystems.filter((function(t){return t.emitter===e}))},t.OCCLUSION_TYPE_NONE=0,t.OCCLUSION_TYPE_OPTIMISTIC=1,t.OCCLUSION_TYPE_STRICT=2,t.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,t.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,t.CULLINGSTRATEGY_STANDARD=u.MESHES_CULLINGSTRATEGY_STANDARD,t.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=u.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,t.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=u.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION,t.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=u.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY,t}(Fo);a("BABYLON.AbstractMesh",Uo);var Vo,ko=function(){function e(){this.reset()}return e.prototype.reset=function(){this.enabled=!1,this.mask=255,this.func=u.ALWAYS,this.funcRef=1,this.funcMask=255,this.opStencilFail=u.KEEP,this.opDepthFail=u.KEEP,this.opStencilDepthPass=u.REPLACE},Object.defineProperty(e.prototype,"func",{get:function(){return this._func},set:function(e){this._func=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"funcRef",{get:function(){return this._funcRef},set:function(e){this._funcRef=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"funcMask",{get:function(){return this._funcMask},set:function(e){this._funcMask=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"opStencilFail",{get:function(){return this._opStencilFail},set:function(e){this._opStencilFail=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"opDepthFail",{get:function(){return this._opDepthFail},set:function(e){this._opDepthFail=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"opStencilDepthPass",{get:function(){return this._opStencilDepthPass},set:function(e){this._opStencilDepthPass=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"mask",{get:function(){return this._mask},set:function(e){this._mask=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"enabled",{get:function(){return this._enabled},set:function(e){this._enabled=e},enumerable:!1,configurable:!0}),e.prototype.getClassName=function(){return"MaterialStencilState"},e.prototype.copyTo=function(e){Ke.Clone((function(){return e}),this)},e.prototype.serialize=function(){return Ke.Serialize(this)},e.prototype.parse=function(e,t,i){var r=this;Ke.Parse((function(){return r}),e,t,i)},v([Ie()],e.prototype,"func",null),v([Ie()],e.prototype,"funcRef",null),v([Ie()],e.prototype,"funcMask",null),v([Ie()],e.prototype,"opStencilFail",null),v([Ie()],e.prototype,"opDepthFail",null),v([Ie()],e.prototype,"opStencilDepthPass",null),v([Ie()],e.prototype,"mask",null),v([Ie()],e.prototype,"enabled",null),e}();function Go(e){-1===e.indexOf("vClipPlane")&&e.push("vClipPlane"),-1===e.indexOf("vClipPlane2")&&e.push("vClipPlane2"),-1===e.indexOf("vClipPlane3")&&e.push("vClipPlane3"),-1===e.indexOf("vClipPlane4")&&e.push("vClipPlane4"),-1===e.indexOf("vClipPlane5")&&e.push("vClipPlane5"),-1===e.indexOf("vClipPlane6")&&e.push("vClipPlane6")}function zo(e,t,i){var r,n,o,a,s,l,c=!!(null!==(r=e.clipPlane)&&void 0!==r?r:t.clipPlane),u=!!(null!==(n=e.clipPlane2)&&void 0!==n?n:t.clipPlane2),h=!!(null!==(o=e.clipPlane3)&&void 0!==o?o:t.clipPlane3),d=!!(null!==(a=e.clipPlane4)&&void 0!==a?a:t.clipPlane4),p=!!(null!==(s=e.clipPlane5)&&void 0!==s?s:t.clipPlane5),f=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);c&&i.push("#define CLIPPLANE"),u&&i.push("#define CLIPPLANE2"),h&&i.push("#define CLIPPLANE3"),d&&i.push("#define CLIPPLANE4"),p&&i.push("#define CLIPPLANE5"),f&&i.push("#define CLIPPLANE6")}function Wo(e,t,i){var r,n,o,a,s,l,c=!1,u=!!(null!==(r=e.clipPlane)&&void 0!==r?r:t.clipPlane),h=!!(null!==(n=e.clipPlane2)&&void 0!==n?n:t.clipPlane2),d=!!(null!==(o=e.clipPlane3)&&void 0!==o?o:t.clipPlane3),p=!!(null!==(a=e.clipPlane4)&&void 0!==a?a:t.clipPlane4),f=!!(null!==(s=e.clipPlane5)&&void 0!==s?s:t.clipPlane5),_=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);return i.CLIPPLANE!==u&&(i.CLIPPLANE=u,c=!0),i.CLIPPLANE2!==h&&(i.CLIPPLANE2=h,c=!0),i.CLIPPLANE3!==d&&(i.CLIPPLANE3=d,c=!0),i.CLIPPLANE4!==p&&(i.CLIPPLANE4=p,c=!0),i.CLIPPLANE5!==f&&(i.CLIPPLANE5=f,c=!0),i.CLIPPLANE6!==_&&(i.CLIPPLANE6=_,c=!0),c}function Ho(e,t,i){var r,n,o,a,s,l,c=null!==(r=t.clipPlane)&&void 0!==r?r:i.clipPlane;Xo(e,"vClipPlane",c),Xo(e,"vClipPlane2",c=null!==(n=t.clipPlane2)&&void 0!==n?n:i.clipPlane2),Xo(e,"vClipPlane3",c=null!==(o=t.clipPlane3)&&void 0!==o?o:i.clipPlane3),Xo(e,"vClipPlane4",c=null!==(a=t.clipPlane4)&&void 0!==a?a:i.clipPlane4),Xo(e,"vClipPlane5",c=null!==(s=t.clipPlane5)&&void 0!==s?s:i.clipPlane5),Xo(e,"vClipPlane6",c=null!==(l=t.clipPlane6)&&void 0!==l?l:i.clipPlane6)}function Xo(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}!function(e){e[e.Created=1]="Created",e[e.Disposed=2]="Disposed",e[e.GetDefineNames=4]="GetDefineNames",e[e.PrepareUniformBuffer=8]="PrepareUniformBuffer",e[e.IsReadyForSubMesh=16]="IsReadyForSubMesh",e[e.PrepareDefines=32]="PrepareDefines",e[e.BindForSubMesh=64]="BindForSubMesh",e[e.PrepareEffect=128]="PrepareEffect",e[e.GetAnimatables=256]="GetAnimatables",e[e.GetActiveTextures=512]="GetActiveTextures",e[e.HasTexture=1024]="HasTexture",e[e.FillRenderTargetTextures=2048]="FillRenderTargetTextures",e[e.HasRenderTargetTextures=4096]="HasRenderTargetTextures",e[e.HardBindForSubMesh=8192]="HardBindForSubMesh"}(Vo||(Vo={}));var jo=Z.Black(),Yo={NUM_MORPH_INFLUENCERS:0};function Ko(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){var r=i.activeCamera;r.mode===u.ORTHOGRAPHIC_CAMERA&&ae.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(r.maxZ+1)/Math.LN2))}}function Qo(e,t,i,r){void 0===r&&(r=!1),i&&e.fogEnabled&&(!t||t.applyFog)&&e.fogMode!==u.FOGMODE_NONE&&(i.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),r?(e.fogColor.toLinearSpaceToRef(jo,e.getEngine().useExactSrgbConversions),i.setColor3("vFogColor",jo)):i.setColor3("vFogColor",e.fogColor))}function qo(e,t,i){Yo.NUM_MORPH_INFLUENCERS=i,Zo(e,t,Yo)}function Zo(e,t,i){var r=i.NUM_MORPH_INFLUENCERS;if(r>0&&M.LastCreatedEngine){var n=M.LastCreatedEngine.getCaps().maxVertexAttribs,o=t.morphTargetManager;if(null==o?void 0:o.isUsingTextureForTargets)return;for(var a=o&&o.supportsNormals&&i.NORMAL,s=o&&o.supportsTangents&&i.TANGENT,l=o&&o.supportsUVs&&i.UV1,c=0;c<r;c++)e.push(u.PositionKind+c),a&&e.push(u.NormalKind+c),s&&e.push(u.TangentKind+c),l&&e.push(u.UVKind+"_"+c),e.length>n&&ae.Error("Cannot add more vertex attributes for mesh "+t.name)}}function Jo(e,t){void 0===t&&(t=!1),e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"),t&&(e.push("previousWorld0"),e.push("previousWorld1"),e.push("previousWorld2"),e.push("previousWorld3"))}function $o(e,t){var i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)}function ea(e,t){t.bindToEffect(e,"Scene")}function ta(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}function ia(e,t,i){var r=e.getTextureMatrix();t.updateMatrix(i+"Matrix",r)}function ra(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}function na(e,t,i){var r;if(t&&e&&(e.computeBonesUsingShaders&&t._bonesComputationForcedToCPU&&(e.computeBonesUsingShaders=!1),e.useBones&&e.computeBonesUsingShaders&&e.skeleton)){var n=e.skeleton;if(n.isUsingTextureForMatrices&&t.getUniformIndex("boneTextureWidth")>-1){var o=n.getTransformMatrixTexture(e);t.setTexture("boneSampler",o),t.setFloat("boneTextureWidth",4*(n.bones.length+1))}else{var a=n.getTransformMatrices(e);a&&(t.setMatrices("mBones",a),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(u.PREPASS_VELOCITY_TEXTURE_TYPE)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=a.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),r=a,i.previousBones[e.uniqueId].set(r)))}}}function oa(e,t,i){e.transferToEffect(t,i+"")}function aa(e,t,i,r,n,o){void 0===o&&(o=!0),e._bindLight(t,i,r,n,o)}function sa(e,t,i,r,n){void 0===n&&(n=4);for(var o=Math.min(t.lightSources.length,n),a=0;a<o;a++)aa(t.lightSources[a],a,e,i,"boolean"==typeof r?r:r.SPECULARTERM,t.receiveShadows)}function la(e,t,i,r){i.NUM_BONE_INFLUENCERS>0&&(r.addCPUSkinningFallback(0,t),e.push(u.MatricesIndicesKind),e.push(u.MatricesWeightsKind),i.NUM_BONE_INFLUENCERS>4&&(e.push(u.MatricesIndicesExtraKind),e.push(u.MatricesWeightsExtraKind)))}function ca(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&Jo(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push(u.ColorInstanceKind)}function ua(e,t,i,r){void 0===i&&(i=4),void 0===r&&(r=0);for(var n=0,o=0;o<i&&e["LIGHT"+o];o++)o>0&&(n=r+o,t.addFallback(n,"LIGHT"+o)),e.SHADOWS||(e["SHADOW"+o]&&t.addFallback(r,"SHADOW"+o),e["SHADOWPCF"+o]&&t.addFallback(r,"SHADOWPCF"+o),e["SHADOWPCSS"+o]&&t.addFallback(r,"SHADOWPCSS"+o),e["SHADOWPOISSON"+o]&&t.addFallback(r,"SHADOWPOISSON"+o),e["SHADOWESM"+o]&&t.addFallback(r,"SHADOWESM"+o),e["SHADOWCLOSEESM"+o]&&t.addFallback(r,"SHADOWCLOSEESM"+o));return n++}function ha(e,t){return t.fogEnabled&&e.applyFog&&t.fogMode!==u.FOGMODE_NONE}function da(e,t,i,r,n,o,a,s){void 0===s&&(s=!1),a._areMiscDirty&&(a.LOGARITHMICDEPTH=i,a.POINTSIZE=r,a.FOG=n&&ha(e,t),a.NONUNIFORMSCALING=e.nonUniformScaling,a.ALPHATEST=o,a.DECAL_AFTER_DETAIL=s)}function pa(e,t,i,r,n,o){if(void 0===n&&(n=4),void 0===o&&(o=!1),!i._areLightsDirty)return i._needNormals;var a=0,s={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!o)for(var l=0,c=t.lightSources;l<c.length&&(fa(e,t,c[l],a,i,r,s),++a!==n);l++);i.SPECULARTERM=s.specularEnabled,i.SHADOWS=s.shadowEnabled;for(var u=a;u<n;u++)void 0!==i["LIGHT"+u]&&(i["LIGHT"+u]=!1,i["HEMILIGHT"+u]=!1,i["POINTLIGHT"+u]=!1,i["DIRLIGHT"+u]=!1,i["SPOTLIGHT"+u]=!1,i["SHADOW"+u]=!1,i["SHADOWCSM"+u]=!1,i["SHADOWCSMDEBUG"+u]=!1,i["SHADOWCSMNUM_CASCADES"+u]=!1,i["SHADOWCSMUSESHADOWMAXZ"+u]=!1,i["SHADOWCSMNOBLEND"+u]=!1,i["SHADOWCSM_RIGHTHANDED"+u]=!1,i["SHADOWPCF"+u]=!1,i["SHADOWPCSS"+u]=!1,i["SHADOWPOISSON"+u]=!1,i["SHADOWESM"+u]=!1,i["SHADOWCLOSEESM"+u]=!1,i["SHADOWCUBE"+u]=!1,i["SHADOWLOWQUALITY"+u]=!1,i["SHADOWMEDIUMQUALITY"+u]=!1);var h=e.getEngine().getCaps();return void 0===i.SHADOWFLOAT&&(s.needRebuild=!0),i.SHADOWFLOAT=s.shadowEnabled&&(h.textureFloatRender&&h.textureFloatLinearFiltering||h.textureHalfFloatRender&&h.textureHalfFloatLinearFiltering),i.LIGHTMAPEXCLUDED=s.lightmapMode,s.needRebuild&&i.rebuild(),s.needNormals}function fa(e,t,i,r,n,o,a){var s;switch(a.needNormals=!0,void 0===n["LIGHT"+r]&&(a.needRebuild=!0),n["LIGHT"+r]=!0,n["SPOTLIGHT"+r]=!1,n["HEMILIGHT"+r]=!1,n["POINTLIGHT"+r]=!1,n["DIRLIGHT"+r]=!1,i.prepareLightSpecificDefines(n,r),n["LIGHT_FALLOFF_PHYSICAL"+r]=!1,n["LIGHT_FALLOFF_GLTF"+r]=!1,n["LIGHT_FALLOFF_STANDARD"+r]=!1,i.falloffType){case un.FALLOFF_GLTF:n["LIGHT_FALLOFF_GLTF"+r]=!0;break;case un.FALLOFF_PHYSICAL:n["LIGHT_FALLOFF_PHYSICAL"+r]=!0;break;case un.FALLOFF_STANDARD:n["LIGHT_FALLOFF_STANDARD"+r]=!0}if(o&&!i.specular.equalsFloats(0,0,0)&&(a.specularEnabled=!0),n["SHADOW"+r]=!1,n["SHADOWCSM"+r]=!1,n["SHADOWCSMDEBUG"+r]=!1,n["SHADOWCSMNUM_CASCADES"+r]=!1,n["SHADOWCSMUSESHADOWMAXZ"+r]=!1,n["SHADOWCSMNOBLEND"+r]=!1,n["SHADOWCSM_RIGHTHANDED"+r]=!1,n["SHADOWPCF"+r]=!1,n["SHADOWPCSS"+r]=!1,n["SHADOWPOISSON"+r]=!1,n["SHADOWESM"+r]=!1,n["SHADOWCLOSEESM"+r]=!1,n["SHADOWCUBE"+r]=!1,n["SHADOWLOWQUALITY"+r]=!1,n["SHADOWMEDIUMQUALITY"+r]=!1,t&&t.receiveShadows&&e.shadowsEnabled&&i.shadowEnabled){var l=null!==(s=i.getShadowGenerator(e.activeCamera))&&void 0!==s?s:i.getShadowGenerator();if(l){var c=l.getShadowMap();c&&c.renderList&&c.renderList.length>0&&(a.shadowEnabled=!0,l.prepareDefines(n,r))}}i.lightmapMode!=un.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,n["LIGHTMAPEXCLUDED"+r]=!0,n["LIGHTMAPNOSPECULAR"+r]=i.lightmapMode==un.LIGHTMAP_SHADOWSONLY):(n["LIGHTMAPEXCLUDED"+r]=!1,n["LIGHTMAPNOSPECULAR"+r]=!1)}function _a(e,t,i,r,n,o,a){void 0===o&&(o=null),void 0===a&&(a=!1);var s=Sa(e,r);!1!==o&&(s=Wo(i,e,r)),r.DEPTHPREPASS!==!t.getColorWrite()&&(r.DEPTHPREPASS=!r.DEPTHPREPASS,s=!0),r.INSTANCES!==n&&(r.INSTANCES=n,s=!0),r.THIN_INSTANCES!==a&&(r.THIN_INSTANCES=a,s=!0),s&&r.markAsUnprocessed()}function ma(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;var i=void 0!==t.BONETEXTURE;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!i&&void 0;var r=e.getScene().prePassRenderer;if(r&&r.enabled){var n=-1===r.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=n}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}function ga(e,t){var i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.NUM_MORPH_INFLUENCERS=i.numMaxInfluencers||i.numInfluencers,t.MORPHTARGETS=t.NUM_MORPH_INFLUENCERS>0,t.MORPHTARGETS_TEXTURE=i.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}function va(e,t){var i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!(!i||!i.isEnabled)}function ya(e,t,i,r,n,o,a){if(void 0===n&&(n=!1),void 0===o&&(o=!0),void 0===a&&(a=!0),!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent(u.NormalKind),t._needNormals&&e.isVerticesDataPresent(u.TangentKind)&&(t.TANGENT=!0);for(var s=1;s<=u.MAX_SUPPORTED_UV_SETS;++s)t["UV"+s]=!!t._needUVs&&e.isVerticesDataPresent("uv".concat(1===s?"":s));if(i){var l=e.useVertexColors&&e.isVerticesDataPresent(u.ColorKind);t.VERTEXCOLOR=l,t.VERTEXALPHA=e.hasVertexAlpha&&l&&o}return e.isVerticesDataPresent(u.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),r&&ma(e,t),n&&ga(e,t),a&&va(e,t),!0}function ba(e,t){if(e.activeCamera){var i=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}function Ta(e,t,i){var r=t.ORDER_INDEPENDENT_TRANSPARENCY,n=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,r===t.ORDER_INDEPENDENT_TRANSPARENCY&&n===t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS||t.markAsUnprocessed()}function Ea(e,t,i){var r=t.PREPASS;if(t._arePrePassDirty){var n=[{type:u.PREPASS_POSITION_TEXTURE_TYPE,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:u.PREPASS_VELOCITY_TEXTURE_TYPE,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:u.PREPASS_REFLECTIVITY_TEXTURE_TYPE,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:u.PREPASS_IRRADIANCE_TEXTURE_TYPE,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:u.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:u.PREPASS_DEPTH_TEXTURE_TYPE,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:u.PREPASS_NORMAL_TEXTURE_TYPE,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace;for(var o=0;o<n.length;o++){var a=e.prePassRenderer.getIndex(n[o].type);-1!==a?(t[n[o].define]=!0,t[n[o].index]=a):t[n[o].define]=!1}}else for(t.PREPASS=!1,o=0;o<n.length;o++)t[n[o].define]=!1;t.PREPASS!=r&&(t.markAsUnprocessed(),t.markAsImageProcessingDirty())}}function Sa(e,t){var i=!1;if(e.activeCamera){var r=t.CAMERA_ORTHOGRAPHIC?1:0,n=t.CAMERA_PERSPECTIVE?1:0,o=e.activeCamera.mode===u.ORTHOGRAPHIC_CAMERA?1:0,a=e.activeCamera.mode===u.PERSPECTIVE_CAMERA?1:0;(r^o||n^a)&&(t.CAMERA_ORTHOGRAPHIC=1===o,t.CAMERA_PERSPECTIVE=1===a,i=!0)}return i}function xa(e,t,i,r,n,o){void 0===n&&(n=null),void 0===o&&(o=!1),n&&n.push("Light"+e),o||(t.push("vLightData"+e,"vLightDiffuse"+e,"vLightSpecular"+e,"vLightDirection"+e,"vLightFalloff"+e,"vLightGround"+e,"lightMatrix"+e,"shadowsInfo"+e,"depthValues"+e),i.push("shadowSampler"+e),i.push("depthSampler"+e),t.push("viewFrustumZ"+e,"cascadeBlendFactor"+e,"lightSizeUVCorrection"+e,"depthCorrection"+e,"penumbraDarkness"+e,"frustumLengths"+e),r&&(i.push("projectionLightSampler"+e),t.push("textureProjectionMatrix"+e)))}function Aa(e,t,i,r){var n;void 0===r&&(r=4);var o=null;if(e.uniformsNames){var a=e;n=a.uniformsNames,o=a.uniformBuffersNames,t=a.samplers,i=a.defines,r=a.maxSimultaneousLights||0}else n=e,t||(t=[]);for(var s=0;s<r&&i["LIGHT"+s];s++)xa(s,n,t,i["PROJECTEDLIGHTTEXTURE"+s],o);i.NUM_MORPH_INFLUENCERS&&(n.push("morphTargetInfluences"),n.push("morphTargetCount")),i.BAKED_VERTEX_ANIMATION_TEXTURE&&(n.push("bakedVertexAnimationSettings"),n.push("bakedVertexAnimationTextureSizeInverted"),n.push("bakedVertexAnimationTime"),t.push("bakedVertexAnimationTexture"))}var Ca=function(){function e(t,i,r){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!0,this.metadata=null,this.reservedDataStore=null,this.checkReadyOnEveryCall=!1,this.checkReadyOnlyOnce=!1,this.state="",this._alpha=1,this._backFaceCulling=!0,this._cullBackFaces=!0,this._blockDirtyMechanism=!1,this.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new f,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=u.ALPHA_COMBINE,this._needDepthPrePass=!1,this.disableDepthWrite=!1,this.disableColorWrite=!1,this.forceDepthWrite=!1,this.depthFunction=0,this.separateCullingPass=!1,this._fogEnabled=!0,this.pointSize=1,this.zOffset=0,this.zOffsetUnits=0,this.stencil=new ko,this._useUBO=!1,this._fillMode=e.TriangleFillMode,this._cachedDepthWriteState=!1,this._cachedColorWriteState=!1,this._cachedDepthFunctionState=0,this._indexInSceneMaterialArray=-1,this.meshMap=null,this._parentContainer=null,this._uniformBufferLayoutBuilt=!1,this._eventInfo={},this._callbackPluginEventGeneric=function(){},this._callbackPluginEventIsReadyForSubMesh=function(){},this._callbackPluginEventPrepareDefines=function(){},this._callbackPluginEventPrepareDefinesBeforeAttributes=function(){},this._callbackPluginEventHardBindForSubMesh=function(){},this._callbackPluginEventBindForSubMesh=function(){},this._callbackPluginEventHasRenderTargetTextures=function(){},this._callbackPluginEventFillRenderTargetTextures=function(){},this._forceAlphaTest=!1,this._transparencyMode=null,this.name=t;var n=i||M.LastCreatedScene;n&&(this._scene=n,this._dirtyCallbacks={},this._dirtyCallbacks[u.MATERIAL_TextureDirtyFlag]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[u.MATERIAL_LightDirtyFlag]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[u.MATERIAL_FresnelDirtyFlag]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[u.MATERIAL_AttributesDirtyFlag]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[u.MATERIAL_MiscDirtyFlag]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[u.MATERIAL_PrePassDirtyFlag]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[u.MATERIAL_AllDirtyFlag]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=t||rr.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new ho(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=e.ClockWiseSideOrientation:this.sideOrientation=e.CounterClockWiseSideOrientation,this._uniformBuffer=new Or(this._scene.getEngine(),void 0,void 0,t),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,r||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),e.OnEventObservable.notifyObservers(this,Vo.Created))}return Object.defineProperty(e.prototype,"canRenderToMRT",{get:function(){return!1},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"alpha",{get:function(){return this._alpha},set:function(t){if(this._alpha!==t){var i=this._alpha;this._alpha=t,1!==i&&1!==t||this.markAsDirty(e.MiscDirtyFlag+e.PrePassDirtyFlag)}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"backFaceCulling",{get:function(){return this._backFaceCulling},set:function(t){this._backFaceCulling!==t&&(this._backFaceCulling=t,this.markAsDirty(e.TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"cullBackFaces",{get:function(){return this._cullBackFaces},set:function(t){this._cullBackFaces!==t&&(this._cullBackFaces=t,this.markAsDirty(e.TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"blockDirtyMechanism",{get:function(){return this._blockDirtyMechanism},set:function(e){this._blockDirtyMechanism!==e&&(this._blockDirtyMechanism=e,e||this.markDirty())},enumerable:!1,configurable:!0}),e.prototype.atomicMaterialsUpdate=function(e){this.blockDirtyMechanism=!0;try{e(this)}finally{this.blockDirtyMechanism=!1}},Object.defineProperty(e.prototype,"hasRenderTargetTextures",{get:function(){return this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._eventInfo.hasRenderTargetTextures},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onBindObservable",{get:function(){return this._onBindObservable||(this._onBindObservable=new f),this._onBindObservable},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onBind",{set:function(e){this._onBindObserver&&this.onBindObservable.remove(this._onBindObserver),this._onBindObserver=this.onBindObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onUnBindObservable",{get:function(){return this._onUnBindObservable||(this._onUnBindObservable=new f),this._onUnBindObservable},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onEffectCreatedObservable",{get:function(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new f),this._onEffectCreatedObservable},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"alphaMode",{get:function(){return this._alphaMode},set:function(t){this._alphaMode!==t&&(this._alphaMode=t,this.markAsDirty(e.TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"needDepthPrePass",{get:function(){return this._needDepthPrePass},set:function(e){this._needDepthPrePass!==e&&(this._needDepthPrePass=e,this._needDepthPrePass&&(this.checkReadyOnEveryCall=!0))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isPrePassCapable",{get:function(){return!1},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"fogEnabled",{get:function(){return this._fogEnabled},set:function(t){this._fogEnabled!==t&&(this._fogEnabled=t,this.markAsDirty(e.MiscDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"wireframe",{get:function(){switch(this._fillMode){case e.WireFrameFillMode:case e.LineListDrawMode:case e.LineLoopDrawMode:case e.LineStripDrawMode:return!0}return this._scene.forceWireframe},set:function(t){this.fillMode=t?e.WireFrameFillMode:e.TriangleFillMode},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"pointsCloud",{get:function(){switch(this._fillMode){case e.PointFillMode:case e.PointListDrawMode:return!0}return this._scene.forcePointsCloud},set:function(t){this.fillMode=t?e.PointFillMode:e.TriangleFillMode},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"fillMode",{get:function(){return this._fillMode},set:function(t){this._fillMode!==t&&(this._fillMode=t,this.markAsDirty(e.MiscDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useLogarithmicDepth",{get:function(){return this._useLogarithmicDepth},set:function(e){var t=this.getScene().getEngine().getCaps().fragmentDepthSupported;e&&!t&&ae.Warn("Logarithmic depth has been requested for a material on a device that doesn't support it."),this._useLogarithmicDepth=e&&t,this._markAllSubMeshesAsMiscDirty()},enumerable:!1,configurable:!0}),e.prototype._getDrawWrapper=function(){return this._drawWrapper},e.prototype._setDrawWrapper=function(e){this._drawWrapper=e},e.prototype.toString=function(e){return"Name: "+this.name},e.prototype.getClassName=function(){return"Material"},Object.defineProperty(e.prototype,"_isMaterial",{get:function(){return!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isFrozen",{get:function(){return this.checkReadyOnlyOnce},enumerable:!1,configurable:!0}),e.prototype.freeze=function(){this.markDirty(),this.checkReadyOnlyOnce=!0},e.prototype.unfreeze=function(){this.markDirty(),this.checkReadyOnlyOnce=!1},e.prototype.isReady=function(e,t){return!0},e.prototype.isReadyForSubMesh=function(e,t,i){var r=t.materialDefines;return!!r&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)},e.prototype.getEffect=function(){return this._drawWrapper.effect},e.prototype.getScene=function(){return this._scene},Object.defineProperty(e.prototype,"transparencyMode",{get:function(){return this._transparencyMode},set:function(t){this._transparencyMode!==t&&(this._transparencyMode=t,this._forceAlphaTest=t===e.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"_disableAlphaBlending",{get:function(){return this._transparencyMode===e.MATERIAL_OPAQUE||this._transparencyMode===e.MATERIAL_ALPHATEST},enumerable:!1,configurable:!0}),e.prototype.needAlphaBlending=function(){return!this._disableAlphaBlending&&this.alpha<1},e.prototype.needAlphaBlendingForMesh=function(e){return e.visibility<1||!this._disableAlphaBlending&&(e.hasVertexAlpha||this.needAlphaBlending())},e.prototype.needAlphaTesting=function(){return!!this._forceAlphaTest},e.prototype._shouldTurnAlphaTestOn=function(e){return!this.needAlphaBlendingForMesh(e)&&this.needAlphaTesting()},e.prototype.getAlphaTestTexture=function(){return null},e.prototype.markDirty=function(t){void 0===t&&(t=!1);for(var i=0,r=this.getScene().meshes;i<r.length;i++){var n=r[i];if(n.subMeshes)for(var o=0,a=n.subMeshes;o<a.length;o++){var s=a[o];if(s.getMaterial()===this)for(var l=0,c=s._drawWrappers;l<c.length;l++){var u=c[l];u&&this._materialContext===u.materialContext&&(u._wasPreviouslyReady=!1,u._wasPreviouslyUsingInstances=null,u._forceRebindOnNextCall=t)}}}t&&this.markAsDirty(e.AllDirtyFlag)},e.prototype._preBind=function(t,i){void 0===i&&(i=null);var r=this._scene.getEngine(),n=(null==i?this.sideOrientation:i)===e.ClockWiseSideOrientation;return r.enableEffect(t||this._getDrawWrapper()),r.setState(this.backFaceCulling,this.zOffset,!1,n,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),n},e.prototype.bind=function(e,t){},e.prototype.buildUniformLayout=function(){var e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(Vo.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0},e.prototype.bindForSubMesh=function(e,t,i){var r=i._drawWrapper;this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),r._forceRebindOnNextCall=!1},e.prototype.bindOnlyWorldMatrix=function(e){},e.prototype.bindView=function(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())},e.prototype.bindViewProjection=function(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))},e.prototype.bindEyePosition=function(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)},e.prototype._afterBind=function(e,t,i){if(void 0===t&&(t=null),this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,ea(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),this._scene._cachedVisibility=e?e.visibility:1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){var r=this._scene.getEngine();this._cachedDepthWriteState=r.getDepthWrite(),r.setDepthWrite(!1)}this.disableColorWrite&&(r=this._scene.getEngine(),this._cachedColorWriteState=r.getColorWrite(),r.setColorWrite(!1)),0!==this.depthFunction&&(r=this._scene.getEngine(),this._cachedDepthFunctionState=r.getDepthFunction()||0,r.setDepthFunction(this.depthFunction))},e.prototype.unbind=function(){this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)},e.prototype.getAnimatables=function(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(Vo.GetAnimatables,this._eventInfo),this._eventInfo.animatables},e.prototype.getActiveTextures=function(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(Vo.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures},e.prototype.hasTexture=function(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(Vo.HasTexture,this._eventInfo),this._eventInfo.hasTexture},e.prototype.clone=function(e){return null},e.prototype._clonePlugins=function(t,i){var r={};if(this._serializePlugins(r),e._ParsePlugins(r,t,this._scene,i),this.pluginManager)for(var n=0,o=this.pluginManager._plugins;n<o.length;n++){var a=o[n],s=t.pluginManager.getPlugin(a.name);s&&a.copyTo(s)}},e.prototype.getBindedMeshes=function(){var e=this;if(this.meshMap){var t=[];for(var i in this.meshMap){var r=this.meshMap[i];r&&t.push(r)}return t}return this._scene.meshes.filter((function(t){return t.material===e}))},e.prototype.forceCompilation=function(e,t,i,r){var n=this,o=g({clipPlane:!1,useInstances:!1},i),a=this.getScene(),s=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;var l=function(){if(n._scene&&n._scene.getEngine()){var i=a.clipPlane;if(o.clipPlane&&(a.clipPlane=new sn(0,0,0,1)),n._storeEffectOnSubMeshes){var c=!0,u=null;if(e.subMeshes){var h=new po(0,0,0,0,0,e,void 0,!1,!1);h.materialDefines&&(h.materialDefines._renderId=-1),n.isReadyForSubMesh(e,h,o.useInstances)||(h.effect&&h.effect.getCompilationError()&&h.effect.allFallbacksProcessed()?u=h.effect.getCompilationError():(c=!1,setTimeout(l,16)))}c&&(n.allowShaderHotSwapping=s,u&&r&&r(u),t&&t(n))}else n.isReady()?(n.allowShaderHotSwapping=s,t&&t(n)):setTimeout(l,16);o.clipPlane&&(a.clipPlane=i)}};l()},e.prototype.forceCompilationAsync=function(e,t){var i=this;return new Promise((function(r,n){i.forceCompilation(e,(function(){r()}),t,(function(e){n(e)}))}))},e.prototype.markAsDirty=function(t){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(e._DirtyCallbackArray.length=0,t&e.TextureDirtyFlag&&e._DirtyCallbackArray.push(e._TextureDirtyCallBack),t&e.LightDirtyFlag&&e._DirtyCallbackArray.push(e._LightsDirtyCallBack),t&e.FresnelDirtyFlag&&e._DirtyCallbackArray.push(e._FresnelDirtyCallBack),t&e.AttributesDirtyFlag&&e._DirtyCallbackArray.push(e._AttributeDirtyCallBack),t&e.MiscDirtyFlag&&e._DirtyCallbackArray.push(e._MiscDirtyCallBack),t&e.PrePassDirtyFlag&&e._DirtyCallbackArray.push(e._PrePassDirtyCallBack),e._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(e._RunDirtyCallBacks),this.getScene().resetCachedMaterial())},e.prototype.resetDrawCache=function(){for(var e=0,t=this.getScene().meshes;e<t.length;e++){var i=t[e];if(i.subMeshes)for(var r=0,n=i.subMeshes;r<n.length;r++){var o=n[r];o.getMaterial()===this&&o.resetDrawCache()}}},e.prototype._markAllSubMeshesAsDirty=function(e){if(!this.getScene().blockMaterialDirtyMechanism&&!this._blockDirtyMechanism)for(var t=0,i=this.getScene().meshes;t<i.length;t++){var r=i[t];if(r.subMeshes)for(var n=0,o=r.subMeshes;n<o.length;n++){var a=o[n];if(a.getMaterial(!1)===this)for(var s=0,l=a._drawWrappers;s<l.length;s++){var c=l[s];c&&c.defines&&c.defines.markAllAsDirty&&this._materialContext===c.materialContext&&e(c.defines)}}}},e.prototype._markScenePrePassDirty=function(){if(!this.getScene().blockMaterialDirtyMechanism&&!this._blockDirtyMechanism){var e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}},e.prototype._markAllSubMeshesAsAllDirty=function(){this._markAllSubMeshesAsDirty(e._AllDirtyCallBack)},e.prototype._markAllSubMeshesAsImageProcessingDirty=function(){this._markAllSubMeshesAsDirty(e._ImageProcessingDirtyCallBack)},e.prototype._markAllSubMeshesAsTexturesDirty=function(){this._markAllSubMeshesAsDirty(e._TextureDirtyCallBack)},e.prototype._markAllSubMeshesAsFresnelDirty=function(){this._markAllSubMeshesAsDirty(e._FresnelDirtyCallBack)},e.prototype._markAllSubMeshesAsFresnelAndMiscDirty=function(){this._markAllSubMeshesAsDirty(e._FresnelAndMiscDirtyCallBack)},e.prototype._markAllSubMeshesAsLightsDirty=function(){this._markAllSubMeshesAsDirty(e._LightsDirtyCallBack)},e.prototype._markAllSubMeshesAsAttributesDirty=function(){this._markAllSubMeshesAsDirty(e._AttributeDirtyCallBack)},e.prototype._markAllSubMeshesAsMiscDirty=function(){this._markAllSubMeshesAsDirty(e._MiscDirtyCallBack)},e.prototype._markAllSubMeshesAsPrePassDirty=function(){this._markAllSubMeshesAsDirty(e._MiscDirtyCallBack)},e.prototype._markAllSubMeshesAsTexturesAndMiscDirty=function(){this._markAllSubMeshesAsDirty(e._TextureAndMiscDirtyCallBack)},e.prototype._checkScenePerformancePriority=function(){var e=this;if(this._scene.performancePriority!==Kr.BackwardCompatible){this.checkReadyOnlyOnce=!0;var t=this._scene.onScenePerformancePriorityChangedObservable.addOnce((function(){e.checkReadyOnlyOnce=!1}));this.onDisposeObservable.add((function(){e._scene.onScenePerformancePriorityChangedObservable.remove(t)}))}},e.prototype.setPrePassRenderer=function(e){return!1},e.prototype.dispose=function(e,t,i){var r=this.getScene();if(r.stopAnimation(this),r.freeProcessedMaterials(),r.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(Vo.Disposed,this._eventInfo),this._parentContainer){var n=this._parentContainer.materials.indexOf(this);n>-1&&this._parentContainer.materials.splice(n,1),this._parentContainer=null}if(!0!==i)if(this.meshMap)for(var o in this.meshMap)(l=this.meshMap[o])&&(l.material=null,this.releaseVertexArrayObject(l,e));else for(var a=0,s=r.meshes;a<s.length;a++){var l;(l=s[a]).material!==this||l.sourceMesh||(l.material=null,this.releaseVertexArrayObject(l,e))}this._uniformBuffer.dispose(),e&&this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})},e.prototype.releaseVertexArrayObject=function(e,t){var i=e.geometry;if(i)if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(var r=0,n=e.subMeshes;r<n.length;r++){var o=n[r];i._releaseVertexArrayObject(o.effect),t&&o.effect&&o.effect.dispose()}}else i._releaseVertexArrayObject(this._drawWrapper.effect)},e.prototype.serialize=function(){var e=Ke.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,this._serializePlugins(e),e},e.prototype._serializePlugins=function(e){if(e.plugins={},this.pluginManager)for(var t=0,i=this.pluginManager._plugins;t<i.length;t++){var r=i[t];e.plugins[r.getClassName()]=r.serialize()}},e.Parse=function(e,t,i){if(e.customType){if("BABYLON.PBRMaterial"===e.customType&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return ae.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null}else e.customType="BABYLON.StandardMaterial";var r=rr.Instantiate(e.customType).Parse(e,t,i);return r._loadedUniqueId=e.uniqueId,r},e._ParsePlugins=function(e,t,i,r){var n;if(e.plugins)for(var o in e.plugins){var a=e.plugins[o],s=null===(n=t.pluginManager)||void 0===n?void 0:n.getPlugin(a.name);if(!s){var l=rr.Instantiate("BABYLON."+o);l&&(s=new l(t))}null==s||s.parse(a,i,r)}},e.TriangleFillMode=u.MATERIAL_TriangleFillMode,e.WireFrameFillMode=u.MATERIAL_WireFrameFillMode,e.PointFillMode=u.MATERIAL_PointFillMode,e.PointListDrawMode=u.MATERIAL_PointListDrawMode,e.LineListDrawMode=u.MATERIAL_LineListDrawMode,e.LineLoopDrawMode=u.MATERIAL_LineLoopDrawMode,e.LineStripDrawMode=u.MATERIAL_LineStripDrawMode,e.TriangleStripDrawMode=u.MATERIAL_TriangleStripDrawMode,e.TriangleFanDrawMode=u.MATERIAL_TriangleFanDrawMode,e.ClockWiseSideOrientation=u.MATERIAL_ClockWiseSideOrientation,e.CounterClockWiseSideOrientation=u.MATERIAL_CounterClockWiseSideOrientation,e.TextureDirtyFlag=u.MATERIAL_TextureDirtyFlag,e.LightDirtyFlag=u.MATERIAL_LightDirtyFlag,e.FresnelDirtyFlag=u.MATERIAL_FresnelDirtyFlag,e.AttributesDirtyFlag=u.MATERIAL_AttributesDirtyFlag,e.MiscDirtyFlag=u.MATERIAL_MiscDirtyFlag,e.PrePassDirtyFlag=u.MATERIAL_PrePassDirtyFlag,e.AllDirtyFlag=u.MATERIAL_AllDirtyFlag,e.MATERIAL_OPAQUE=0,e.MATERIAL_ALPHATEST=1,e.MATERIAL_ALPHABLEND=2,e.MATERIAL_ALPHATESTANDBLEND=3,e.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,e.MATERIAL_NORMALBLENDMETHOD_RNM=1,e.OnEventObservable=new f,e._AllDirtyCallBack=function(e){return e.markAllAsDirty()},e._ImageProcessingDirtyCallBack=function(e){return e.markAsImageProcessingDirty()},e._TextureDirtyCallBack=function(e){return e.markAsTexturesDirty()},e._FresnelDirtyCallBack=function(e){return e.markAsFresnelDirty()},e._MiscDirtyCallBack=function(e){return e.markAsMiscDirty()},e._PrePassDirtyCallBack=function(e){return e.markAsPrePassDirty()},e._LightsDirtyCallBack=function(e){return e.markAsLightDirty()},e._AttributeDirtyCallBack=function(e){return e.markAsAttributesDirty()},e._FresnelAndMiscDirtyCallBack=function(t){e._FresnelDirtyCallBack(t),e._MiscDirtyCallBack(t)},e._TextureAndMiscDirtyCallBack=function(t){e._TextureDirtyCallBack(t),e._MiscDirtyCallBack(t)},e._DirtyCallbackArray=[],e._RunDirtyCallBacks=function(t){for(var i=0,r=e._DirtyCallbackArray;i<r.length;i++)(0,r[i])(t)},v([Ie()],e.prototype,"id",void 0),v([Ie()],e.prototype,"uniqueId",void 0),v([Ie()],e.prototype,"name",void 0),v([Ie()],e.prototype,"metadata",void 0),v([Ie()],e.prototype,"checkReadyOnEveryCall",void 0),v([Ie()],e.prototype,"checkReadyOnlyOnce",void 0),v([Ie()],e.prototype,"state",void 0),v([Ie("alpha")],e.prototype,"_alpha",void 0),v([Ie("backFaceCulling")],e.prototype,"_backFaceCulling",void 0),v([Ie("cullBackFaces")],e.prototype,"_cullBackFaces",void 0),v([Ie()],e.prototype,"sideOrientation",void 0),v([Ie("alphaMode")],e.prototype,"_alphaMode",void 0),v([Ie()],e.prototype,"_needDepthPrePass",void 0),v([Ie()],e.prototype,"disableDepthWrite",void 0),v([Ie()],e.prototype,"disableColorWrite",void 0),v([Ie()],e.prototype,"forceDepthWrite",void 0),v([Ie()],e.prototype,"depthFunction",void 0),v([Ie()],e.prototype,"separateCullingPass",void 0),v([Ie("fogEnabled")],e.prototype,"_fogEnabled",void 0),v([Ie()],e.prototype,"pointSize",void 0),v([Ie()],e.prototype,"zOffset",void 0),v([Ie()],e.prototype,"zOffsetUnits",void 0),v([Ie()],e.prototype,"pointsCloud",null),v([Ie()],e.prototype,"fillMode",null),v([Ie()],e.prototype,"useLogarithmicDepth",null),v([Ie()],e.prototype,"transparencyMode",null),e}(),Ra=function(e){function t(t,i){var r=e.call(this,t,i,!0)||this;return r._waitingSubMaterialsUniqueIds=[],r.getScene().addMultiMaterial(r),r.subMaterials=[],r._storeEffectOnSubMeshes=!0,r}return m(t,e),Object.defineProperty(t.prototype,"subMaterials",{get:function(){return this._subMaterials},set:function(e){this._subMaterials=e,this._hookArray(e)},enumerable:!1,configurable:!0}),t.prototype.getChildren=function(){return this.subMaterials},t.prototype._hookArray=function(e){var t=this,i=e.push;e.push=function(){for(var r=[],n=0;n<arguments.length;n++)r[n]=arguments[n];var o=i.apply(e,r);return t._markAllSubMeshesAsTexturesDirty(),o};var r=e.splice;e.splice=function(i,n){var o=r.apply(e,[i,n]);return t._markAllSubMeshesAsTexturesDirty(),o}},t.prototype.getSubMaterial=function(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]},t.prototype.getActiveTextures=function(){var t;return(t=e.prototype.getActiveTextures.call(this)).concat.apply(t,this.subMaterials.map((function(e){return e?e.getActiveTextures():[]})))},t.prototype.hasTexture=function(t){var i;if(e.prototype.hasTexture.call(this,t))return!0;for(var r=0;r<this.subMaterials.length;r++)if(null===(i=this.subMaterials[r])||void 0===i?void 0:i.hasTexture(t))return!0;return!1},t.prototype.getClassName=function(){return"MultiMaterial"},t.prototype.isReadyForSubMesh=function(e,t,i){for(var r=0;r<this.subMaterials.length;r++){var n=this.subMaterials[r];if(n){if(n._storeEffectOnSubMeshes){if(!n.isReadyForSubMesh(e,t,i))return!1;continue}if(!n.isReady(e))return!1}}return!0},t.prototype.clone=function(e,i){for(var r=new t(e,this.getScene()),n=0;n<this.subMaterials.length;n++){var o,a=this.subMaterials[n];o=i&&a?a.clone(e+"-"+a.name):this.subMaterials[n],r.subMaterials.push(o)}return r},t.prototype.serialize=function(){var e={};e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,je&&(e.tags=je.GetTags(this)),e.materialsUniqueIds=[],e.materials=[];for(var t=0;t<this.subMaterials.length;t++){var i=this.subMaterials[t];i?(e.materialsUniqueIds.push(i.uniqueId),e.materials.push(i.id)):(e.materialsUniqueIds.push(null),e.materials.push(null))}return e},t.prototype.dispose=function(t,i,r){var n=this.getScene();if(n){if(r)for(var o=0;o<this.subMaterials.length;o++){var a=this.subMaterials[o];a&&a.dispose(t,i)}var s=n.multiMaterials.indexOf(this);s>=0&&n.multiMaterials.splice(s,1),e.prototype.dispose.call(this,t,i)}},t.ParseMultiMaterial=function(e,i){var r=new t(e.name,i);return r.id=e.id,r._loadedUniqueId=e.uniqueId,je&&je.AddTagsTo(r,e.tags),e.materialsUniqueIds?r._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach((function(e){return r.subMaterials.push(i.getLastMaterialById(e))})),r},t}(Ca);a("BABYLON.MultiMaterial",Ra);var Pa=function(e,t){this.distanceOrScreenCoverage=e,this.mesh=t},Ia=function(){},Ma=function(){this.visibleInstances={},this.batchCache=new Oa,this.batchCacheReplacementModeInFrozenMode=new Oa,this.instancesBufferSize=2048},Oa=function(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]},Da=function(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null},Na=function(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=new Array,this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null},Fa=function(e){function t(i,r,n,o,a,s){void 0===r&&(r=null),void 0===n&&(n=null),void 0===o&&(o=null),void 0===s&&(s=!0);var l=e.call(this,i,r)||this;if(l._internalMeshDataInfo=new Na,l.delayLoadState=u.DELAYLOADSTATE_NONE,l.instances=[],l._creationDataStorage=null,l._geometry=null,l._instanceDataStorage=new Ma,l._thinInstanceDataStorage=new Da,l._shouldGenerateFlatShading=!1,l._originalBuilderSideOrientation=t.DEFAULTSIDE,l.overrideMaterialSideOrientation=null,l.ignoreCameraMaxZ=!1,r=l.getScene(),l._onBeforeDraw=function(e,t,i){e&&i&&(l._uniformBuffer?l.transferToEffect(t):i.bindOnlyWorldMatrix(t))},o){if(o._geometry&&o._geometry.applyToMesh(l),ye.DeepCopy(o,l,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),l._internalMeshDataInfo._source=o,r.useClonedMeshMap&&(o._internalMeshDataInfo.meshMap||(o._internalMeshDataInfo.meshMap={}),o._internalMeshDataInfo.meshMap[l.uniqueId]=l),l._originalBuilderSideOrientation=o._originalBuilderSideOrientation,l._creationDataStorage=o._creationDataStorage,o._ranges){var c=o._ranges;for(var h in c)Object.prototype.hasOwnProperty.call(c,h)&&c[h]&&l.createAnimationRange(h,c[h].from,c[h].to)}if(o.metadata&&o.metadata.clone?l.metadata=o.metadata.clone():l.metadata=o.metadata,l._internalMetadata=o._internalMetadata,je&&je.HasTags(o)&&je.AddTagsTo(l,je.GetTags(o,!0)),l.setEnabled(o.isEnabled(!1)),l.parent=o.parent,l.setPivotMatrix(o.getPivotMatrix(),l._postMultiplyPivotMatrix),l.id=i+"."+o.id,l.material=o.material,!a)for(var d=o.getDescendants(!0),p=0;p<d.length;p++){var _=d[p];_.clone&&_.clone(i+"."+_.name,l)}if(o.morphTargetManager&&(l.morphTargetManager=o.morphTargetManager),r.getPhysicsEngine){var m=r.getPhysicsEngine();if(s&&m)if(1===m.getPluginVersion()){var g=m.getImpostorForPhysicsObject(o);g&&(l.physicsImpostor=g.clone(l))}else 2===m.getPluginVersion()&&o.physicsBody&&o.physicsBody.clone(l)}for(p=0;p<r.particleSystems.length;p++){var v=r.particleSystems[p];v.emitter===o&&v.clone(v.name,l)}l.skeleton=o.skeleton,l.refreshBoundingInfo(!0,!0),l.computeWorldMatrix(!0)}return null!==n&&(l.parent=n),l._instanceDataStorage.hardwareInstancedRendering=l.getEngine().getCaps().instancedArrays,l._internalMeshDataInfo._onMeshReadyObserverAdded=function(e){e.unregisterOnNextCall=!0,l.isReady(!0)?l.onMeshReadyObservable.notifyObservers(l):l._internalMeshDataInfo._checkReadinessObserver||(l._internalMeshDataInfo._checkReadinessObserver=l._scene.onBeforeRenderObservable.add((function(){l.isReady(!0)&&(l._scene.onBeforeRenderObservable.remove(l._internalMeshDataInfo._checkReadinessObserver),l._internalMeshDataInfo._checkReadinessObserver=null,l.onMeshReadyObservable.notifyObservers(l))})))},l.onMeshReadyObservable=new f(l._internalMeshDataInfo._onMeshReadyObserverAdded),o&&o.onClonedObservable.notifyObservers(l),l}return m(t,e),t._GetDefaultSideOrientation=function(e){return e||t.FRONTSIDE},Object.defineProperty(t.prototype,"useLODScreenCoverage",{get:function(){return this._internalMeshDataInfo._useLODScreenCoverage},set:function(e){this._internalMeshDataInfo._useLODScreenCoverage=e,this._sortLODLevels()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"computeBonesUsingShaders",{get:function(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders},set:function(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(e&&this._internalMeshDataInfo._sourcePositions&&(this.setVerticesData(Nr.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(Nr.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onBeforeRenderObservable",{get:function(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new f),this._internalMeshDataInfo._onBeforeRenderObservable},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onBeforeBindObservable",{get:function(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new f),this._internalMeshDataInfo._onBeforeBindObservable},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onAfterRenderObservable",{get:function(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new f),this._internalMeshDataInfo._onAfterRenderObservable},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onBetweenPassObservable",{get:function(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new f),this._internalMeshDataInfo._onBetweenPassObservable},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onBeforeDrawObservable",{get:function(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new f),this._internalMeshDataInfo._onBeforeDrawObservable},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onBeforeDraw",{set:function(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hasInstances",{get:function(){return this.instances.length>0},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hasThinInstances",{get:function(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"forcedInstanceCount",{get:function(){return this._internalMeshDataInfo._forcedInstanceCount},set:function(e){this._internalMeshDataInfo._forcedInstanceCount=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"overrideRenderingFillMode",{get:function(){return this._internalMeshDataInfo._overrideRenderingFillMode},set:function(e){this._internalMeshDataInfo._overrideRenderingFillMode=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"source",{get:function(){return this._internalMeshDataInfo._source},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cloneMeshMap",{get:function(){return this._internalMeshDataInfo.meshMap},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isUnIndexed",{get:function(){return this._unIndexed},set:function(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"worldMatrixInstancedBuffer",{get:function(){return this._instanceDataStorage.instancesData},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"previousWorldMatrixInstancedBuffer",{get:function(){return this._instanceDataStorage.instancesPreviousData},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"manualUpdateOfWorldMatrixInstancedBuffer",{get:function(){return this._instanceDataStorage.manualUpdate},set:function(e){this._instanceDataStorage.manualUpdate=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"manualUpdateOfPreviousWorldMatrixInstancedBuffer",{get:function(){return this._instanceDataStorage.previousManualUpdate},set:function(e){this._instanceDataStorage.previousManualUpdate=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"forceWorldMatrixInstancedBufferUpdate",{get:function(){return this._instanceDataStorage.forceMatrixUpdates},set:function(e){this._instanceDataStorage.forceMatrixUpdates=e},enumerable:!1,configurable:!0}),t.prototype.instantiateHierarchy=function(e,t,i){void 0===e&&(e=null);var r=0===this.getTotalVertices()||t&&t.doNotInstantiate&&(!0===t.doNotInstantiate||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));r.parent=e||this.parent,r.position=this.position.clone(),r.scaling=this.scaling.clone(),this.rotationQuaternion?r.rotationQuaternion=this.rotationQuaternion.clone():r.rotation=this.rotation.clone(),i&&i(this,r);for(var n=0,o=this.getChildTransformNodes(!0);n<o.length;n++){var a=o[n];"InstancedMesh"===a.getClassName()&&"Mesh"===r.getClassName()&&a.sourceMesh===this?a.instantiateHierarchy(r,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:r},i):a.instantiateHierarchy(r,t,i)}return r},t.prototype.getClassName=function(){return"Mesh"},Object.defineProperty(t.prototype,"_isMesh",{get:function(){return!0},enumerable:!1,configurable:!0}),t.prototype.toString=function(t){var i=e.prototype.toString.call(this,t);if(i+=", n vertices: "+this.getTotalVertices(),i+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(var r=0;r<this.animations.length;r++)i+=", animation[0]: "+this.animations[r].toString(t);if(t)if(this._geometry){var n=this.getIndices(),o=this.getVerticesData(Nr.PositionKind);o&&n&&(i+=", flat shading: "+(o.length/3===n.length?"YES":"NO"))}else i+=", flat shading: UNKNOWN";return i},t.prototype._unBindEffect=function(){e.prototype._unBindEffect.call(this);for(var t=0,i=this.instances;t<i.length;t++)i[t]._unBindEffect()},Object.defineProperty(t.prototype,"hasLODLevels",{get:function(){return this._internalMeshDataInfo._LODLevels.length>0},enumerable:!1,configurable:!0}),t.prototype.getLODLevels=function(){return this._internalMeshDataInfo._LODLevels},t.prototype._sortLODLevels=function(){var e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort((function(t,i){return t.distanceOrScreenCoverage<i.distanceOrScreenCoverage?e:t.distanceOrScreenCoverage>i.distanceOrScreenCoverage?-e:0}))},t.prototype.addLODLevel=function(e,t){if(t&&t._masterMesh)return ae.Warn("You cannot use a mesh as LOD level twice"),this;var i=new Pa(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this},t.prototype.getLODLevelAtDistance=function(e){for(var t=this._internalMeshDataInfo,i=0;i<t._LODLevels.length;i++){var r=t._LODLevels[i];if(r.distanceOrScreenCoverage===e)return r.mesh}return null},t.prototype.removeLODLevel=function(e){for(var t=this._internalMeshDataInfo,i=0;i<t._LODLevels.length;i++)t._LODLevels[i].mesh===e&&(t._LODLevels.splice(i,1),e&&(e._masterMesh=null));return this._sortLODLevels(),this},t.prototype.getLOD=function(e,t){var i=this._internalMeshDataInfo;if(!i._LODLevels||0===i._LODLevels.length)return this;var r=t||this.getBoundingInfo().boundingSphere,n=e.mode===$n.ORTHOGRAPHIC_CAMERA?e.minZ:r.centerWorld.subtract(e.globalPosition).length(),o=n,a=1;if(i._useLODScreenCoverage){var s=e.screenArea,l=r.radiusWorld*e.minZ/n;o=(l=l*l*Math.PI)/s,a=-1}if(a*i._LODLevels[i._LODLevels.length-1].distanceOrScreenCoverage>a*o)return this.onLODLevelSelection&&this.onLODLevelSelection(o,this,this),this;for(var c=0;c<i._LODLevels.length;c++){var h=i._LODLevels[c];if(a*h.distanceOrScreenCoverage<a*o){if(h.mesh){if(h.mesh.delayLoadState===u.DELAYLOADSTATE_NOTLOADED)return h.mesh._checkDelayState(),this;if(h.mesh.delayLoadState===u.DELAYLOADSTATE_LOADING)return this;h.mesh._preActivate(),h.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)}return this.onLODLevelSelection&&this.onLODLevelSelection(o,this,h.mesh),h.mesh}}return this.onLODLevelSelection&&this.onLODLevelSelection(o,this,this),this},Object.defineProperty(t.prototype,"geometry",{get:function(){return this._geometry},enumerable:!1,configurable:!0}),t.prototype.getTotalVertices=function(){return null===this._geometry||void 0===this._geometry?0:this._geometry.getTotalVertices()},t.prototype.getVerticesData=function(e,t,i,r){var n,o;if(!this._geometry)return null;var a=r||null===(o=null===(n=this._userInstancedBuffersStorage)||void 0===n?void 0:n.vertexBuffers[e])||void 0===o?void 0:o.getFloatData(this.instances.length+1,i||t&&1!==this._geometry.meshes.length);return a||(a=this._geometry.getVerticesData(e,t,i)),a},t.prototype.getVertexBuffer=function(e,t){var i,r;return this._geometry?null!==(r=t||null===(i=this._userInstancedBuffersStorage)||void 0===i?void 0:i.vertexBuffers[e])&&void 0!==r?r:this._geometry.getVertexBuffer(e):null},t.prototype.isVerticesDataPresent=function(e,t){var i;return this._geometry?!t&&void 0!==(null===(i=this._userInstancedBuffersStorage)||void 0===i?void 0:i.vertexBuffers[e])||this._geometry.isVerticesDataPresent(e):!!this._delayInfo&&-1!==this._delayInfo.indexOf(e)},t.prototype.isVertexBufferUpdatable=function(e,t){var i;if(!this._geometry)return!!this._delayInfo&&-1!==this._delayInfo.indexOf(e);if(!t){var r=null===(i=this._userInstancedBuffersStorage)||void 0===i?void 0:i.vertexBuffers[e];if(r)return r.isUpdatable()}return this._geometry.isVertexBufferUpdatable(e)},t.prototype.getVerticesDataKinds=function(e){if(!this._geometry){var t=[];return this._delayInfo&&this._delayInfo.forEach((function(e){t.push(e)})),t}var i=this._geometry.getVerticesDataKinds();if(!e&&this._userInstancedBuffersStorage)for(var r in this._userInstancedBuffersStorage.vertexBuffers)-1===i.indexOf(r)&&i.push(r);return i},t.prototype.getTotalIndices=function(){return this._geometry?this._geometry.getTotalIndices():0},t.prototype.getIndices=function(e,t){return this._geometry?this._geometry.getIndices(e,t):[]},Object.defineProperty(t.prototype,"isBlocked",{get:function(){return null!==this._masterMesh&&void 0!==this._masterMesh},enumerable:!1,configurable:!0}),t.prototype.isReady=function(t,i){var r,n,o,a,s,l,c;if(void 0===t&&(t=!1),void 0===i&&(i=!1),this.delayLoadState===u.DELAYLOADSTATE_LOADING)return!1;if(!e.prototype.isReady.call(this,t))return!1;if(!this.subMeshes||0===this.subMeshes.length)return!0;if(!t)return!0;var h=this.getEngine(),d=this.getScene(),p=i||h.getCaps().instancedArrays&&(this.instances.length>0||this.hasThinInstances);this.computeWorldMatrix();var f=this.material||d.defaultMaterial;if(f)if(f._storeEffectOnSubMeshes)for(var _=0,m=this.subMeshes;_<m.length;_++){var g=(I=m[_]).getMaterial();if(g)if(g._storeEffectOnSubMeshes){if(!g.isReadyForSubMesh(this,I,p))return!1}else if(!g.isReady(this,p))return!1}else if(!f.isReady(this,p))return!1;for(var v=h.currentRenderPassId,y=0,b=this.lightSources;y<b.length;y++){var T=b[y].getShadowGenerators();if(T)for(var E=T.values(),S=E.next();!0!==S.done;S=E.next()){var x=S.value;if(x&&(!(null===(r=x.getShadowMap())||void 0===r?void 0:r.renderList)||(null===(n=x.getShadowMap())||void 0===n?void 0:n.renderList)&&-1!==(null===(a=null===(o=x.getShadowMap())||void 0===o?void 0:o.renderList)||void 0===a?void 0:a.indexOf(this)))){for(var A=null!==(s=x.getShadowMap().renderPassIds)&&void 0!==s?s:[h.currentRenderPassId],C=0;C<A.length;++C){h.currentRenderPassId=A[C];for(var R=0,P=this.subMeshes;R<P.length;R++){var I=P[R];if(!x.isReady(I,p,null!==(c=null===(l=I.getMaterial())||void 0===l?void 0:l.needAlphaBlendingForMesh(this))&&void 0!==c&&c))return h.currentRenderPassId=v,!1}}h.currentRenderPassId=v}}}for(var M=0,O=this._internalMeshDataInfo._LODLevels;M<O.length;M++){var D=O[M];if(D.mesh&&!D.mesh.isReady(p))return!1}return!0},Object.defineProperty(t.prototype,"areNormalsFrozen",{get:function(){return this._internalMeshDataInfo._areNormalsFrozen},enumerable:!1,configurable:!0}),t.prototype.freezeNormals=function(){return this._internalMeshDataInfo._areNormalsFrozen=!0,this},t.prototype.unfreezeNormals=function(){return this._internalMeshDataInfo._areNormalsFrozen=!1,this},Object.defineProperty(t.prototype,"overridenInstanceCount",{set:function(e){this._instanceDataStorage.overridenInstanceCount=e},enumerable:!1,configurable:!0}),t.prototype._preActivate=function(){var e=this._internalMeshDataInfo,t=this.getScene().getRenderId();return e._preActivateId===t||(e._preActivateId=t,this._instanceDataStorage.visibleInstances=null),this},t.prototype._preActivateForIntermediateRendering=function(e){return this._instanceDataStorage.visibleInstances&&(this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId=e),this},t.prototype._registerInstanceForRenderId=function(e,t){return this._instanceDataStorage.visibleInstances||(this._instanceDataStorage.visibleInstances={defaultRenderId:t,selfDefaultRenderId:this._renderId}),this._instanceDataStorage.visibleInstances[t]||(void 0!==this._instanceDataStorage.previousRenderId&&this._instanceDataStorage.isFrozen&&(this._instanceDataStorage.visibleInstances[this._instanceDataStorage.previousRenderId]=null),this._instanceDataStorage.previousRenderId=t,this._instanceDataStorage.visibleInstances[t]=new Array),this._instanceDataStorage.visibleInstances[t].push(e),this},t.prototype._afterComputeWorldMatrix=function(){e.prototype._afterComputeWorldMatrix.call(this),this.hasThinInstances&&(this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1))},t.prototype._postActivate=function(){this.edgesShareWithInstances&&this.edgesRenderer&&this.edgesRenderer.isEnabled&&this._renderingGroup&&(this._renderingGroup._edgesRenderers.pushNoDuplicate(this.edgesRenderer),this.edgesRenderer.customInstances.push(this.getWorldMatrix()))},t.prototype.refreshBoundingInfo=function(e,t){if(void 0===e&&(e=!1),void 0===t&&(t=!1),this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;var i=this.geometry?this.geometry.boundingBias:null;return this._refreshBoundingInfo(this._getPositionData(e,t),i),this},t.prototype._createGlobalSubMesh=function(e){var t=this.getTotalVertices();if(!t||!this.getIndices())return null;if(this.subMeshes&&this.subMeshes.length>0){var i=this.getIndices();if(!i)return null;var r=i.length,n=!1;if(e)n=!0;else for(var o=0,a=this.subMeshes;o<a.length;o++){var s=a[o];if(s.indexStart+s.indexCount>r){n=!0;break}if(s.verticesStart+s.verticesCount>t){n=!0;break}}if(!n)return this.subMeshes[0]}return this.releaseSubMeshes(),new po(0,0,t,0,this.getTotalIndices(),this)},t.prototype.subdivide=function(e){if(!(e<1)){for(var t=this.getTotalIndices(),i=t/e|0,r=0;i%3!=0;)i++;this.releaseSubMeshes();for(var n=0;n<e&&!(r>=t);n++)po.CreateFromIndices(0,r,n===e-1?t-r:i,this,void 0,!1),r+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}},t.prototype.setVerticesData=function(e,t,i,r){if(void 0===i&&(i=!1),this._geometry)this._geometry.setVerticesData(e,t,i,r);else{var n=new _o;n.set(t,e);var o=this.getScene();new vo(vo.RandomId(),o,n,i,this)}return this},t.prototype.removeVerticesData=function(e){this._geometry&&this._geometry.removeVerticesData(e)},t.prototype.markVerticesDataAsUpdatable=function(e,t){void 0===t&&(t=!0);var i=this.getVertexBuffer(e);i&&i.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)},t.prototype.setVerticesBuffer=function(e,t){return void 0===t&&(t=!0),this._geometry||(this._geometry=vo.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this},t.prototype.updateVerticesData=function(e,t,i,r){return this._geometry?(r?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this},t.prototype.updateMeshPositions=function(e,t){void 0===t&&(t=!0);var i=this.getVerticesData(Nr.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(Nr.PositionKind,i,!1,!1),t){var r=this.getIndices(),n=this.getVerticesData(Nr.NormalKind);if(!n)return this;_o.ComputeNormals(i,r,n),this.updateVerticesData(Nr.NormalKind,n,!1,!1)}return this},t.prototype.makeGeometryUnique=function(){if(!this._geometry)return this;if(1===this._geometry.meshes.length)return this;var e=this._geometry,t=this._geometry.copy(vo.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this},t.prototype.setIndexBuffer=function(e,t,i){var r=this._geometry;r||(r=new vo(vo.RandomId(),this.getScene(),void 0,void 0,this)),r.setIndexBuffer(e,t,i)},t.prototype.setIndices=function(e,t,i){if(void 0===t&&(t=null),void 0===i&&(i=!1),this._geometry)this._geometry.setIndices(e,t,i);else{var r=new _o;r.indices=e;var n=this.getScene();new vo(vo.RandomId(),n,r,i,this)}return this},t.prototype.updateIndices=function(e,t,i){return void 0===i&&(i=!1),this._geometry?(this._geometry.updateIndices(e,t,i),this):this},t.prototype.toLeftHanded=function(){return this._geometry?(this._geometry.toLeftHanded(),this):this},t.prototype._bind=function(e,t,i,r){if(void 0===r&&(r=!0),!this._geometry)return this;var n,o=this.getScene().getEngine();if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t),this._unIndexed)n=null;else switch(this._getRenderingFillMode(i)){case Ca.PointFillMode:n=null;break;case Ca.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),o);break;default:case Ca.TriangleFillMode:n=this._geometry.getIndexBuffer()}return r&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(t,n,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,n),this},t.prototype._draw=function(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);var r=this.getScene().getEngine();return this._unIndexed||t==Ca.PointFillMode?r.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==Ca.WireFrameFillMode?r.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):r.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),this},t.prototype.registerBeforeRender=function(e){return this.onBeforeRenderObservable.add(e),this},t.prototype.unregisterBeforeRender=function(e){return this.onBeforeRenderObservable.removeCallback(e),this},t.prototype.registerAfterRender=function(e){return this.onAfterRenderObservable.add(e),this},t.prototype.unregisterAfterRender=function(e){return this.onAfterRenderObservable.removeCallback(e),this},t.prototype._getInstancesRenderList=function(e,t){if(void 0===t&&(t=!1),this._instanceDataStorage.isFrozen){if(t)return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;if(this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch}var i=this.getScene(),r=i._isInIntermediateRendering(),n=r?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,o=this._instanceDataStorage.batchCache;if(o.mustReturn=!1,o.renderSelf[e]=t||!n&&this.isEnabled()&&this.isVisible,o.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){var a=this._instanceDataStorage.visibleInstances,s=i.getRenderId(),l=r?a.intermediateDefaultRenderId:a.defaultRenderId;o.visibleInstances[e]=a[s],!o.visibleInstances[e]&&l&&(o.visibleInstances[e]=a[l])}return o.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==o.visibleInstances[e]&&void 0!==o.visibleInstances[e],this._instanceDataStorage.previousBatch=o,o},t.prototype._renderWithInstances=function(e,i,r,n,o){for(var a,s=r.visibleInstances[e._id],l=s?s.length:0,c=this._instanceDataStorage,u=c.instancesBufferSize,h=c.instancesBuffer,d=c.instancesPreviousBuffer,p=16*(l+1)*4;c.instancesBufferSize<p;)c.instancesBufferSize*=2;c.instancesData&&u==c.instancesBufferSize||(c.instancesData=new Float32Array(c.instancesBufferSize/4)),(this._scene.needsPreviousWorldMatrices&&!c.instancesPreviousData||u!=c.instancesBufferSize)&&(c.instancesPreviousData=new Float32Array(c.instancesBufferSize/4));var f=0,_=0,m=r.renderSelf[e._id],g=!h||u!==c.instancesBufferSize||this._scene.needsPreviousWorldMatrices&&!c.instancesPreviousBuffer;if(this._instanceDataStorage.manualUpdate||c.isFrozen&&!g)_=(m?1:0)+l;else{var v=this.getWorldMatrix();if(m&&(this._scene.needsPreviousWorldMatrices&&(c.masterMeshPreviousWorldMatrix?(c.masterMeshPreviousWorldMatrix.copyToArray(c.instancesPreviousData,f),c.masterMeshPreviousWorldMatrix.copyFrom(v)):(c.masterMeshPreviousWorldMatrix=v.clone(),c.masterMeshPreviousWorldMatrix.copyToArray(c.instancesPreviousData,f))),v.copyToArray(c.instancesData,f),f+=16,_++),s){if(t.INSTANCEDMESH_SORT_TRANSPARENT&&this._scene.activeCamera&&(null===(a=e.getMaterial())||void 0===a?void 0:a.needAlphaBlendingForMesh(e.getRenderingMesh()))){for(var y=this._scene.activeCamera.globalPosition,b=0;b<s.length;b++){var T=s[b];T._distanceToCamera=V.Distance(T.getBoundingInfo().boundingSphere.centerWorld,y)}s.sort((function(e,t){return e._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera<t._distanceToCamera?1:0}))}for(b=0;b<s.length;b++){var E=s[b],S=E.getWorldMatrix();S.copyToArray(c.instancesData,f),this._scene.needsPreviousWorldMatrices&&(E._previousWorldMatrix?(E._previousWorldMatrix.copyToArray(c.instancesPreviousData,f),E._previousWorldMatrix.copyFrom(S)):(E._previousWorldMatrix=S.clone(),E._previousWorldMatrix.copyToArray(c.instancesPreviousData,f))),f+=16,_++}}}return g?(h&&h.dispose(),d&&d.dispose(),h=new Dr(o,c.instancesData,!0,16,!1,!0),c.instancesBuffer=h,this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}),this._userInstancedBuffersStorage.vertexBuffers.world0=h.createVertexBuffer("world0",0,4),this._userInstancedBuffersStorage.vertexBuffers.world1=h.createVertexBuffer("world1",4,4),this._userInstancedBuffersStorage.vertexBuffers.world2=h.createVertexBuffer("world2",8,4),this._userInstancedBuffersStorage.vertexBuffers.world3=h.createVertexBuffer("world3",12,4),this._scene.needsPreviousWorldMatrices&&(d=new Dr(o,c.instancesPreviousData,!0,16,!1,!0),c.instancesPreviousBuffer=d,this._userInstancedBuffersStorage.vertexBuffers.previousWorld0=d.createVertexBuffer("previousWorld0",0,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld1=d.createVertexBuffer("previousWorld1",4,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld2=d.createVertexBuffer("previousWorld2",8,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld3=d.createVertexBuffer("previousWorld3",12,4)),this._invalidateInstanceVertexArrayObject()):this._instanceDataStorage.isFrozen&&!this._instanceDataStorage.forceMatrixUpdates||(h.updateDirectly(c.instancesData,0,_),!this._scene.needsPreviousWorldMatrices||this._instanceDataStorage.manualUpdate&&!this._instanceDataStorage.previousManualUpdate||d.updateDirectly(c.instancesPreviousData,0,_)),this._processInstancedBuffers(s,m),this.getScene()._activeIndices.addCount(e.indexCount*_,!1),o._currentDrawContext&&(o._currentDrawContext.useInstancing=!0),this._bind(e,n,i),this._draw(e,i,_),!this._scene.needsPreviousWorldMatrices||g||!this._instanceDataStorage.manualUpdate||this._instanceDataStorage.isFrozen&&!this._instanceDataStorage.forceMatrixUpdates||this._instanceDataStorage.previousManualUpdate||d.updateDirectly(c.instancesData,0,_),o.unbindInstanceAttributes(),this},t.prototype._renderWithThinInstances=function(e,t,i,r){var n,o,a=null!==(o=null===(n=this._thinInstanceDataStorage)||void 0===n?void 0:n.instancesCount)&&void 0!==o?o:0;this.getScene()._activeIndices.addCount(e.indexCount*a,!1),r._currentDrawContext&&(r._currentDrawContext.useInstancing=!0),this._bind(e,i,t),this._draw(e,t,a),this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&this._thinInstanceDataStorage.matrixData&&(this._thinInstanceDataStorage.previousMatrixBuffer?this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData,0,a):this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",this._thinInstanceDataStorage.matrixData,!1)),r.unbindInstanceAttributes()},t.prototype._processInstancedBuffers=function(e,t){},t.prototype._processRendering=function(e,t,i,r,n,o,a,s){var l=this.getScene(),c=l.getEngine();if(r=this._getRenderingFillMode(r),o&&t.getRenderingMesh().hasThinInstances)return this._renderWithThinInstances(t,r,i,c),this;if(o)this._renderWithInstances(t,r,n,i,c);else{c._currentDrawContext&&(c._currentDrawContext.useInstancing=!1);var u=0;n.renderSelf[t._id]&&(a&&a(!1,e.getWorldMatrix(),s),u++,this._draw(t,r,this._instanceDataStorage.overridenInstanceCount));var h=n.visibleInstances[t._id];if(h){var d=h.length;u+=d;for(var p=0;p<d;p++){var f=h[p].getWorldMatrix();a&&a(!0,f,s),this._draw(t,r)}}l._activeIndices.addCount(t.indexCount*u,!1)}return this},t.prototype._rebuild=function(t){if(void 0===t&&(t=!1),this._instanceDataStorage.instancesBuffer&&(t&&this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null),this._userInstancedBuffersStorage){for(var i in this._userInstancedBuffersStorage.vertexBuffers){var r=this._userInstancedBuffersStorage.vertexBuffers[i];r&&(t&&r.dispose(),this._userInstancedBuffersStorage.vertexBuffers[i]=null)}this._userInstancedBuffersStorage.vertexArrayObjects&&(this._userInstancedBuffersStorage.vertexArrayObjects={})}this._internalMeshDataInfo._effectiveMaterial=null,e.prototype._rebuild.call(this,t)},t.prototype._freeze=function(){if(this.subMeshes){for(var e=0;e<this.subMeshes.length;e++)this._getInstancesRenderList(e);this._internalMeshDataInfo._effectiveMaterial=null,this._instanceDataStorage.isFrozen=!0}},t.prototype._unFreeze=function(){this._instanceDataStorage.isFrozen=!1,this._instanceDataStorage.previousBatch=null},t.prototype.renderWithRenderPassId=function(e,t,i,r,n){void 0===n&&(n=!0);var o=this._scene.getEngine(),a=o.currentRenderPassId;if(void 0!==e&&(o.currentRenderPassId=e),r)(!n||n&&r.isInFrustum(this._scene._frustumPlanes))&&this.render(r,!!t,i);else for(var s=0;s<this.subMeshes.length;s++){var l=this.subMeshes[s];(!n||n&&l.isInFrustum(this._scene._frustumPlanes))&&this.render(l,!!t,i)}return void 0!==e&&(o.currentRenderPassId=a),this},t.prototype.render=function(e,t,i){var r,n,o,a,s=this.getScene();this._internalAbstractMeshDataInfo._isActiveIntermediate?this._internalAbstractMeshDataInfo._isActiveIntermediate=!1:this._internalAbstractMeshDataInfo._isActive=!1;var l=null!==(n=null===(r=s.activeCameras)||void 0===r?void 0:r.length)&&void 0!==n?n:0;if((l>1&&s.activeCamera===s.activeCameras[0]||l<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;var c=this._getInstancesRenderList(e._id,!!i);if(c.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;var u=s.getEngine(),h=0,d=null;this.ignoreCameraMaxZ&&s.activeCamera&&!s._isInIntermediateRendering()&&(h=s.activeCamera.maxZ,d=s.activeCamera,s.activeCamera.maxZ=0,s.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);var p,f=e.getRenderingMesh(),_=c.hardwareInstancedRendering[e._id]||f.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,m=this._instanceDataStorage,g=e.getMaterial();if(!g)return d&&(d.maxZ=h,s.updateTransformMatrix(!0)),this;if(m.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===g){if(g._storeEffectOnSubMeshes&&!(null===(o=e._drawWrapper)||void 0===o?void 0:o._wasPreviouslyReady)||!g._storeEffectOnSubMeshes&&!g._getDrawWrapper()._wasPreviouslyReady)return d&&(d.maxZ=h,s.updateTransformMatrix(!0)),this}else{if(g._storeEffectOnSubMeshes){if(!g.isReadyForSubMesh(this,e,_))return d&&(d.maxZ=h,s.updateTransformMatrix(!0)),this}else if(!g.isReady(this,_))return d&&(d.maxZ=h,s.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=g}t&&u.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode);for(var v=null!==(a=null==(p=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper())?void 0:p.effect)&&void 0!==a?a:null,y=0,b=s._beforeRenderingMeshStage;y<b.length;y++)b[y].action(this,e,c,v);if(!p||!v)return d&&(d.maxZ=h,s.updateTransformMatrix(!0)),this;var T,E=i||this;if(m.isFrozen||!this._internalMeshDataInfo._effectiveMaterial.backFaceCulling&&null===this.overrideMaterialSideOrientation&&!this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)T=m.sideOrientation;else{var S=E._getWorldMatrixDeterminant();null==(T=this.overrideMaterialSideOrientation)&&(T=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),S<0&&(T=T===Ca.ClockWiseSideOrientation?Ca.CounterClockWiseSideOrientation:Ca.ClockWiseSideOrientation),m.sideOrientation=T}var x=this._internalMeshDataInfo._effectiveMaterial._preBind(p,T);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&u.setDepthWrite(!0);var A=this._internalMeshDataInfo._effectiveMaterial,C=A.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),_||this._bind(e,v,C,!1);var R=E.getWorldMatrix();A._storeEffectOnSubMeshes?A.bindForSubMesh(R,this,e):A.bind(R,this),!A.backFaceCulling&&A.separateCullingPass&&(u.setState(!0,A.zOffset,!1,!x,A.cullBackFaces,A.stencil,A.zOffsetUnits),this._processRendering(this,e,v,C,c,_,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),u.setState(!0,A.zOffset,!1,x,A.cullBackFaces,A.stencil,A.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,v,C,c,_,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(var P=0,I=s._afterRenderingMeshStage;P<I.length;P++)I[P].action(this,e,c,v);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),d&&(d.maxZ=h,s.updateTransformMatrix(!0)),s.performancePriority!==Kr.Aggressive||m.isFrozen||this._freeze(),this},t.prototype.cleanMatrixWeights=function(){this.isVerticesDataPresent(Nr.MatricesWeightsKind)&&(this.isVerticesDataPresent(Nr.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())},t.prototype._normalizeSkinFourWeights=function(){for(var e=this.getVerticesData(Nr.MatricesWeightsKind),t=e.length,i=0;i<t;i+=4){var r=e[i]+e[i+1]+e[i+2]+e[i+3];if(0===r)e[i]=1;else{var n=1/r;e[i]*=n,e[i+1]*=n,e[i+2]*=n,e[i+3]*=n}}this.setVerticesData(Nr.MatricesWeightsKind,e)},t.prototype._normalizeSkinWeightsAndExtra=function(){for(var e=this.getVerticesData(Nr.MatricesWeightsExtraKind),t=this.getVerticesData(Nr.MatricesWeightsKind),i=t.length,r=0;r<i;r+=4){var n=t[r]+t[r+1]+t[r+2]+t[r+3];if(0===(n+=e[r]+e[r+1]+e[r+2]+e[r+3]))t[r]=1;else{var o=1/n;t[r]*=o,t[r+1]*=o,t[r+2]*=o,t[r+3]*=o,e[r]*=o,e[r+1]*=o,e[r+2]*=o,e[r+3]*=o}}this.setVerticesData(Nr.MatricesWeightsKind,t),this.setVerticesData(Nr.MatricesWeightsKind,e)},t.prototype.validateSkinning=function(){var e=this.getVerticesData(Nr.MatricesWeightsExtraKind),t=this.getVerticesData(Nr.MatricesWeightsKind);if(null===t||null==this.skeleton)return{skinned:!1,valid:!0,report:"not skinned"};for(var i=t.length,r=0,n=0,o=0,a=0,s=null===e?4:8,l=[],c=0;c<=s;c++)l[c]=0;for(c=0;c<i;c+=4){for(var u=t[c],h=u,d=0===h?0:1,p=1;p<s;p++){var f=p<4?t[c+p]:e[c+p-4];f>u&&r++,0!==f&&d++,h+=f,u=f}if(l[d]++,d>o&&(o=d),0===h)n++;else{var _=1/h,m=0;for(p=0;p<s;p++)m+=p<4?Math.abs(t[c+p]-t[c+p]*_):Math.abs(e[c+p-4]-e[c+p-4]*_);m>.001&&a++}}var g=this.skeleton.bones.length,v=this.getVerticesData(Nr.MatricesIndicesKind),y=this.getVerticesData(Nr.MatricesIndicesExtraKind),b=0;for(c=0;c<i;c+=4)for(p=0;p<s;p++){var T=p<4?v[c+p]:y[c+p-4];(T>=g||T<0)&&b++}return{skinned:!0,valid:0===n&&0===a&&0===b,report:"Number of Weights = "+i/4+"\nMaximum influences = "+o+"\nMissing Weights = "+n+"\nNot Sorted = "+r+"\nNot Normalized = "+a+"\nWeightCounts = ["+l+"]\nNumber of bones = "+g+"\nBad Bone Indices = "+b}},t.prototype._checkDelayState=function(){var e=this.getScene();return this._geometry?this._geometry.load(e):this.delayLoadState===u.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=u.DELAYLOADSTATE_LOADING,this._queueLoad(e)),this},t.prototype._queueLoad=function(e){var t=this;e.addPendingData(this);var i=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return rr.LoadFile(this.delayLoadingFile,(function(i){i instanceof ArrayBuffer?t._delayLoadingFunction(i,t):t._delayLoadingFunction(JSON.parse(i),t),t.instances.forEach((function(e){e.refreshBoundingInfo(),e._syncSubMeshes()})),t.delayLoadState=u.DELAYLOADSTATE_LOADED,e.removePendingData(t)}),(function(){}),e.offlineProvider,i),this},t.prototype.isInFrustum=function(t){return this.delayLoadState!==u.DELAYLOADSTATE_LOADING&&!!e.prototype.isInFrustum.call(this,t)&&(this._checkDelayState(),!0)},t.prototype.setMaterialById=function(e){var t,i=this.getScene().materials;for(t=i.length-1;t>-1;t--)if(i[t].id===e)return this.material=i[t],this;var r=this.getScene().multiMaterials;for(t=r.length-1;t>-1;t--)if(r[t].id===e)return this.material=r[t],this;return this},t.prototype.getAnimatables=function(){var e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e},t.prototype.bakeTransformIntoVertices=function(e){if(!this.isVerticesDataPresent(Nr.PositionKind))return this;var t=this.subMeshes.splice(0);this._resetPointsArrayCache();var i,r=this.getVerticesData(Nr.PositionKind),n=V.Zero();for(i=0;i<r.length;i+=3)V.TransformCoordinatesFromFloatsToRef(r[i],r[i+1],r[i+2],e,n).toArray(r,i);if(this.setVerticesData(Nr.PositionKind,r,this.getVertexBuffer(Nr.PositionKind).isUpdatable()),this.isVerticesDataPresent(Nr.NormalKind)){for(r=this.getVerticesData(Nr.NormalKind),i=0;i<r.length;i+=3)V.TransformNormalFromFloatsToRef(r[i],r[i+1],r[i+2],e,n).normalize().toArray(r,i);this.setVerticesData(Nr.NormalKind,r,this.getVertexBuffer(Nr.NormalKind).isUpdatable())}if(this.isVerticesDataPresent(Nr.TangentKind)){for(r=this.getVerticesData(Nr.TangentKind),i=0;i<r.length;i+=4)V.TransformNormalFromFloatsToRef(r[i],r[i+1],r[i+2],e,n).normalize().toArray(r,i);this.setVerticesData(Nr.TangentKind,r,this.getVertexBuffer(Nr.TangentKind).isUpdatable())}return e.determinant()<0&&this.flipFaces(),this.releaseSubMeshes(),this.subMeshes=t,this},t.prototype.bakeCurrentTransformIntoVertices=function(e){return void 0===e&&(e=!0),this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),this.resetLocalMatrix(e),this},Object.defineProperty(t.prototype,"_positions",{get:function(){return this._internalAbstractMeshDataInfo._positions?this._internalAbstractMeshDataInfo._positions:this._geometry?this._geometry._positions:null},enumerable:!1,configurable:!0}),t.prototype._resetPointsArrayCache=function(){return this._geometry&&this._geometry._resetPointsArrayCache(),this},t.prototype._generatePointsArray=function(){return!!this._geometry&&this._geometry._generatePointsArray()},t.prototype.clone=function(e,i,r,n){return void 0===e&&(e=""),void 0===i&&(i=null),void 0===n&&(n=!0),new t(e,this.getScene(),i,this,r,n)},t.prototype.dispose=function(t,i){void 0===i&&(i=!1),this.morphTargetManager=null,this._geometry&&this._geometry.releaseForMesh(this,!0);var r=this._internalMeshDataInfo;if(r._onBeforeDrawObservable&&r._onBeforeDrawObservable.clear(),r._onBeforeBindObservable&&r._onBeforeBindObservable.clear(),r._onBeforeRenderObservable&&r._onBeforeRenderObservable.clear(),r._onAfterRenderObservable&&r._onAfterRenderObservable.clear(),r._onBetweenPassObservable&&r._onBetweenPassObservable.clear(),this._scene.useClonedMeshMap){if(r.meshMap)for(var n in r.meshMap)(s=r.meshMap[n])&&(s._internalMeshDataInfo._source=null,r.meshMap[n]=void 0);r._source&&r._source._internalMeshDataInfo.meshMap&&(r._source._internalMeshDataInfo.meshMap[this.uniqueId]=void 0)}else for(var o=0,a=this.getScene().meshes;o<a.length;o++){var s;(s=a[o])._internalMeshDataInfo&&s._internalMeshDataInfo._source&&s._internalMeshDataInfo._source===this&&(s._internalMeshDataInfo._source=null)}r._source=null,this._instanceDataStorage.visibleInstances={},this._disposeInstanceSpecificData(),this._disposeThinInstanceSpecificData(),this._internalMeshDataInfo._checkReadinessObserver&&this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),e.prototype.dispose.call(this,t,i)},t.prototype._disposeInstanceSpecificData=function(){},t.prototype._disposeThinInstanceSpecificData=function(){},t.prototype._invalidateInstanceVertexArrayObject=function(){},t.prototype.applyDisplacementMap=function(e,t,i,r,n,o,a,s){var l=this;void 0===a&&(a=!1);var c=this.getScene();return rr.LoadImage(e,(function(e){var s=e.width,c=e.height,u=l.getEngine().createCanvas(s,c).getContext("2d");u.drawImage(e,0,0);var h=u.getImageData(0,0,s,c).data;l.applyDisplacementMapFromBuffer(h,s,c,t,i,n,o,a),r&&r(l)}),s||function(){},c.offlineProvider),this},t.prototype.applyDisplacementMapFromBuffer=function(e,t,i,r,n,o,a,s){if(void 0===s&&(s=!1),!this.isVerticesDataPresent(Nr.PositionKind)||!this.isVerticesDataPresent(Nr.NormalKind)||!this.isVerticesDataPresent(Nr.UVKind))return ae.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;var l=this.getVerticesData(Nr.PositionKind,!0,!0),c=this.getVerticesData(Nr.NormalKind),u=this.getVerticesData(Nr.UVKind),h=V.Zero(),d=V.Zero(),p=U.Zero();o=o||U.Zero(),a=a||new U(1,1);for(var f=0;f<l.length;f+=3){V.FromArrayToRef(l,f,h),V.FromArrayToRef(c,f,d),U.FromArrayToRef(u,f/3*2,p);var _=4*((Math.abs(p.x*a.x+o.x%1)*(t-1)%t|0)+(Math.abs(p.y*a.y+o.y%1)*(i-1)%i|0)*t),m=e[_]/255*.3+e[_+1]/255*.59+e[_+2]/255*.11;d.normalize(),d.scaleInPlace(r+(n-r)*m),(h=h.add(d)).toArray(l,f)}return _o.ComputeNormals(l,this.getIndices(),c),s?(this.setVerticesData(Nr.PositionKind,l),this.setVerticesData(Nr.NormalKind,c),this.setVerticesData(Nr.UVKind,u)):(this.updateVerticesData(Nr.PositionKind,l),this.updateVerticesData(Nr.NormalKind,c)),this},t.prototype._getFlattenedNormals=function(e,t){for(var i=new Float32Array(3*e.length),r=0,n=this.overrideMaterialSideOrientation===(this._scene.useRightHandedSystem?u.MATERIAL_CounterClockWiseSideOrientation:u.MATERIAL_ClockWiseSideOrientation),o=0;o<e.length;o+=3){var a=V.FromArray(t,3*e[o]),s=V.FromArray(t,3*e[o+1]),l=V.FromArray(t,3*e[o+2]),c=a.subtract(s),h=l.subtract(s),d=V.Normalize(V.Cross(c,h));n&&d.scaleInPlace(-1);for(var p=0;p<3;p++)i[r++]=d.x,i[r++]=d.y,i[r++]=d.z}return i},t.prototype._convertToUnIndexedMesh=function(e){void 0===e&&(e=!1);for(var t=this.getVerticesDataKinds(),i=this.getIndices(),r={},n=function(e,t){for(var r=new Float32Array(i.length*t),n=0,o=0;o<i.length;o++)for(var a=0;a<t;a++)r[n++]=e[i[o]*t+a];return r},o=this.geometry?this.subMeshes.slice(0):[],a=0,s=t;a<s.length;a++)r[u=s[a]]=this.getVerticesData(u);for(var l=0,c=t;l<c.length;l++){var u=c[l],h=this.getVertexBuffer(u),d=h.getStrideSize();if(e&&u===Nr.NormalKind){var p=this._getFlattenedNormals(i,r[Nr.PositionKind]);this.setVerticesData(Nr.NormalKind,p,h.isUpdatable(),d)}else this.setVerticesData(u,n(r[u],d),h.isUpdatable(),d)}if(this.morphTargetManager){for(var f=0;f<this.morphTargetManager.numTargets;f++){var _=this.morphTargetManager.getTarget(f),m=_.getPositions();_.setPositions(n(m,3)),(p=_.getNormals())&&_.setNormals(e?this._getFlattenedNormals(i,m):n(p,3));var g=_.getTangents();g&&_.setTangents(n(g,3));var v=_.getUVs();v&&_.setUVs(n(v,2))}this.morphTargetManager.synchronize()}for(var y=0;y<i.length;y++)i[y]=y;this.setIndices(i),this._unIndexed=!0,this.releaseSubMeshes();for(var b=0,T=o;b<T.length;b++){var E=T[b];po.AddToMesh(E.materialIndex,E.indexStart,E.indexCount,E.indexStart,E.indexCount,this)}return this.synchronizeInstances(),this},t.prototype.convertToFlatShadedMesh=function(){return this._convertToUnIndexedMesh(!0)},t.prototype.convertToUnIndexedMesh=function(){return this._convertToUnIndexedMesh()},t.prototype.flipFaces=function(e){void 0===e&&(e=!1);var t,i=_o.ExtractFromMesh(this);if(e&&this.isVerticesDataPresent(Nr.NormalKind)&&i.normals)for(t=0;t<i.normals.length;t++)i.normals[t]*=-1;if(i.indices){var r=void 0;for(t=0;t<i.indices.length;t+=3)r=i.indices[t+1],i.indices[t+1]=i.indices[t+2],i.indices[t+2]=r}return i.applyToMesh(this,this.isVertexBufferUpdatable(Nr.PositionKind)),this},t.prototype.increaseVertices=function(e){void 0===e&&(e=1);var t=_o.ExtractFromMesh(this),i=t.indices&&!Array.isArray(t.indices)&&Array.from?Array.from(t.indices):t.indices,r=t.positions&&!Array.isArray(t.positions)&&Array.from?Array.from(t.positions):t.positions,n=t.uvs&&!Array.isArray(t.uvs)&&Array.from?Array.from(t.uvs):t.uvs,o=t.normals&&!Array.isArray(t.normals)&&Array.from?Array.from(t.normals):t.normals;if(i&&r){t.indices=i,t.positions=r,n&&(t.uvs=n),o&&(t.normals=o);for(var a=e+1,s=new Array,l=0;l<a+1;l++)s[l]=new Array;var c=void 0,u=void 0,h=new V(0,0,0),d=new V(0,0,0),p=new U(0,0),f=new Array,_=new Array,m=new Array,g=void 0,v=r.length,y=void 0;n&&(y=n.length);var b=void 0;for(o&&(b=o.length),l=0;l<i.length;l+=3){_[0]=i[l],_[1]=i[l+1],_[2]=i[l+2];for(var T=0;T<3;T++)if(c=_[T],u=_[(T+1)%3],void 0===m[c]&&void 0===m[u]?(m[c]=new Array,m[u]=new Array):(void 0===m[c]&&(m[c]=new Array),void 0===m[u]&&(m[u]=new Array)),void 0===m[c][u]&&void 0===m[u][c]){m[c][u]=[],h.x=(r[3*u]-r[3*c])/a,h.y=(r[3*u+1]-r[3*c+1])/a,h.z=(r[3*u+2]-r[3*c+2])/a,o&&(d.x=(o[3*u]-o[3*c])/a,d.y=(o[3*u+1]-o[3*c+1])/a,d.z=(o[3*u+2]-o[3*c+2])/a),n&&(p.x=(n[2*u]-n[2*c])/a,p.y=(n[2*u+1]-n[2*c+1])/a),m[c][u].push(c);for(var E=1;E<a;E++)m[c][u].push(r.length/3),r[v++]=r[3*c]+E*h.x,r[v++]=r[3*c+1]+E*h.y,r[v++]=r[3*c+2]+E*h.z,o&&(o[b++]=o[3*c]+E*d.x,o[b++]=o[3*c+1]+E*d.y,o[b++]=o[3*c+2]+E*d.z),n&&(n[y++]=n[2*c]+E*p.x,n[y++]=n[2*c+1]+E*p.y);m[c][u].push(u),m[u][c]=new Array,g=m[c][u].length;for(var S=0;S<g;S++)m[u][c][S]=m[c][u][g-1-S]}for(s[0][0]=i[l],s[1][0]=m[i[l]][i[l+1]][1],s[1][1]=m[i[l]][i[l+2]][1],E=2;E<a;E++)for(s[E][0]=m[i[l]][i[l+1]][E],s[E][E]=m[i[l]][i[l+2]][E],h.x=(r[3*s[E][E]]-r[3*s[E][0]])/E,h.y=(r[3*s[E][E]+1]-r[3*s[E][0]+1])/E,h.z=(r[3*s[E][E]+2]-r[3*s[E][0]+2])/E,o&&(d.x=(o[3*s[E][E]]-o[3*s[E][0]])/E,d.y=(o[3*s[E][E]+1]-o[3*s[E][0]+1])/E,d.z=(o[3*s[E][E]+2]-o[3*s[E][0]+2])/E),n&&(p.x=(n[2*s[E][E]]-n[2*s[E][0]])/E,p.y=(n[2*s[E][E]+1]-n[2*s[E][0]+1])/E),T=1;T<E;T++)s[E][T]=r.length/3,r[v++]=r[3*s[E][0]]+T*h.x,r[v++]=r[3*s[E][0]+1]+T*h.y,r[v++]=r[3*s[E][0]+2]+T*h.z,o&&(o[b++]=o[3*s[E][0]]+T*d.x,o[b++]=o[3*s[E][0]+1]+T*d.y,o[b++]=o[3*s[E][0]+2]+T*d.z),n&&(n[y++]=n[2*s[E][0]]+T*p.x,n[y++]=n[2*s[E][0]+1]+T*p.y);for(s[a]=m[i[l+1]][i[l+2]],f.push(s[0][0],s[1][0],s[1][1]),E=1;E<a;E++){for(T=void 0,T=0;T<E;T++)f.push(s[E][T],s[E+1][T],s[E+1][T+1]),f.push(s[E][T],s[E+1][T+1],s[E][T+1]);f.push(s[E][T],s[E+1][T],s[E+1][T+1])}}t.indices=f,t.applyToMesh(this,this.isVertexBufferUpdatable(Nr.PositionKind))}else ae.Warn("Couldn't increase number of vertices : VertexData must contain at least indices and positions")},t.prototype.forceSharedVertices=function(){var e=_o.ExtractFromMesh(this),t=e.uvs,i=e.indices,r=e.positions,n=e.colors,o=e.matricesIndices,a=e.matricesWeights,s=e.matricesIndicesExtra,l=e.matricesWeightsExtra;if(void 0===i||void 0===r||null===i||null===r)ae.Warn("VertexData contains empty entries");else{for(var c=new Array,u=new Array,h=new Array,d=new Array,p=new Array,f=new Array,_=new Array,m=new Array,g=new Array,v=0,y={},b=void 0,T=void 0,E=0;E<i.length;E+=3){T=[i[E],i[E+1],i[E+2]],g=[];for(var S=0;S<3;S++){g[S]="";for(var x=0;x<3;x++)Math.abs(r[3*T[S]+x])<1e-8&&(r[3*T[S]+x]=0),g[S]+=r[3*T[S]+x]+"|"}if(g[0]!=g[1]&&g[0]!=g[2]&&g[1]!=g[2])for(S=0;S<3;S++){if(void 0===(b=y[g[S]])){for(y[g[S]]=v,b=v++,x=0;x<3;x++)c.push(r[3*T[S]+x]);if(null!=n)for(x=0;x<4;x++)d.push(n[4*T[S]+x]);if(null!=t)for(x=0;x<2;x++)h.push(t[2*T[S]+x]);if(null!=o)for(x=0;x<4;x++)p.push(o[4*T[S]+x]);if(null!=a)for(x=0;x<4;x++)f.push(a[4*T[S]+x]);if(null!=s)for(x=0;x<4;x++)_.push(s[4*T[S]+x]);if(null!=l)for(x=0;x<4;x++)m.push(l[4*T[S]+x])}u.push(b)}}var A=new Array;_o.ComputeNormals(c,u,A),e.positions=c,e.indices=u,e.normals=A,null!=t&&(e.uvs=h),null!=n&&(e.colors=d),null!=o&&(e.matricesIndices=p),null!=a&&(e.matricesWeights=f),null!=s&&(e.matricesIndicesExtra=_),null!=a&&(e.matricesWeightsExtra=m),e.applyToMesh(this,this.isVertexBufferUpdatable(Nr.PositionKind))}},t._instancedMeshFactory=function(e,t){throw He("InstancedMesh")},t._PhysicsImpostorParser=function(e,t,i){throw He("PhysicsImpostor")},t.prototype.createInstance=function(e){return t._instancedMeshFactory(e,this)},t.prototype.synchronizeInstances=function(){for(var e=0;e<this.instances.length;e++)this.instances[e]._syncSubMeshes();return this},t.prototype.optimizeIndices=function(e){var t=this,i=this.getIndices(),r=this.getVerticesData(Nr.PositionKind);if(!r||!i)return this;for(var n=[],o=0;o<r.length;o+=3)n.push(V.FromArray(r,o));var a=[];return or.SyncAsyncForLoop(n.length,40,(function(e){for(var t=n.length-1-e,i=n[t],r=0;r<t;++r){var o=n[r];if(i.equals(o)){a[t]=r;break}}}),(function(){for(var r=0;r<i.length;++r)i[r]=a[i[r]]||i[r];var n=t.subMeshes.slice(0);t.setIndices(i),t.subMeshes=n,e&&e(t)})),this},t.prototype.serialize=function(e){void 0===e&&(e={}),e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,e.type=this.getClassName(),je&&je.HasTags(this)&&(e.tags=je.GetTags(this)),e.position=this.position.asArray(),this.rotationQuaternion?e.rotationQuaternion=this.rotationQuaternion.asArray():this.rotation&&(e.rotation=this.rotation.asArray()),e.scaling=this.scaling.asArray(),this._postMultiplyPivotMatrix?e.pivotMatrix=this.getPivotMatrix().asArray():e.localMatrix=this.getPivotMatrix().asArray(),e.isEnabled=this.isEnabled(!1),e.isVisible=this.isVisible,e.infiniteDistance=this.infiniteDistance,e.pickable=this.isPickable,e.receiveShadows=this.receiveShadows,e.billboardMode=this.billboardMode,e.visibility=this.visibility,e.alwaysSelectAsActiveMesh=this.alwaysSelectAsActiveMesh,e.checkCollisions=this.checkCollisions,e.ellipsoid=this.ellipsoid.asArray(),e.ellipsoidOffset=this.ellipsoidOffset.asArray(),e.doNotSyncBoundingInfo=this.doNotSyncBoundingInfo,e.isBlocker=this.isBlocker,e.overrideMaterialSideOrientation=this.overrideMaterialSideOrientation,this.parent&&this.parent._serializeAsParent(e),e.isUnIndexed=this.isUnIndexed;var t=this._geometry;if(t&&this.subMeshes){e.geometryUniqueId=t.uniqueId,e.geometryId=t.id,e.subMeshes=[];for(var i=0;i<this.subMeshes.length;i++){var r=this.subMeshes[i];e.subMeshes.push({materialIndex:r.materialIndex,verticesStart:r.verticesStart,verticesCount:r.verticesCount,indexStart:r.indexStart,indexCount:r.indexCount})}}this.material?this.material.doNotSerialize||(e.materialUniqueId=this.material.uniqueId,e.materialId=this.material.id):(this.material=null,e.materialUniqueId=this._scene.defaultMaterial.uniqueId,e.materialId=this._scene.defaultMaterial.id),this.morphTargetManager&&(e.morphTargetManagerId=this.morphTargetManager.uniqueId),this.skeleton&&(e.skeletonId=this.skeleton.id,e.numBoneInfluencers=this.numBoneInfluencers),this.getScene()._getComponent(Vr.NAME_PHYSICSENGINE)&&(a=this.getPhysicsImpostor())&&(e.physicsMass=a.getParam("mass"),e.physicsFriction=a.getParam("friction"),e.physicsRestitution=a.getParam("mass"),e.physicsImpostor=a.type),this.metadata&&(e.metadata=this.metadata),e.instances=[];for(var n=0;n<this.instances.length;n++){var o=this.instances[n];if(!o.doNotSerialize){var a,s={name:o.name,id:o.id,isEnabled:o.isEnabled(!1),isVisible:o.isVisible,isPickable:o.isPickable,checkCollisions:o.checkCollisions,position:o.position.asArray(),scaling:o.scaling.asArray()};o.parent&&o.parent._serializeAsParent(s),o.rotationQuaternion?s.rotationQuaternion=o.rotationQuaternion.asArray():o.rotation&&(s.rotation=o.rotation.asArray()),this.getScene()._getComponent(Vr.NAME_PHYSICSENGINE)&&(a=o.getPhysicsImpostor())&&(s.physicsMass=a.getParam("mass"),s.physicsFriction=a.getParam("friction"),s.physicsRestitution=a.getParam("mass"),s.physicsImpostor=a.type),o.metadata&&(s.metadata=o.metadata),o.actionManager&&(s.actions=o.actionManager.serialize(o.name)),e.instances.push(s),Ke.AppendSerializedAnimations(o,s),s.ranges=o.serializeAnimationRanges()}}if(this._thinInstanceDataStorage.instancesCount&&this._thinInstanceDataStorage.matrixData&&(e.thinInstances={instancesCount:this._thinInstanceDataStorage.instancesCount,matrixData:Array.from(this._thinInstanceDataStorage.matrixData),matrixBufferSize:this._thinInstanceDataStorage.matrixBufferSize,enablePicking:this.thinInstanceEnablePicking},this._userThinInstanceBuffersStorage)){var l={data:{},sizes:{},strides:{}};for(var c in this._userThinInstanceBuffersStorage.data)l.data[c]=Array.from(this._userThinInstanceBuffersStorage.data[c]),l.sizes[c]=this._userThinInstanceBuffersStorage.sizes[c],l.strides[c]=this._userThinInstanceBuffersStorage.strides[c];e.thinInstances.userThinInstance=l}return Ke.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.layerMask=this.layerMask,e.alphaIndex=this.alphaIndex,e.hasVertexAlpha=this.hasVertexAlpha,e.overlayAlpha=this.overlayAlpha,e.overlayColor=this.overlayColor.asArray(),e.renderOverlay=this.renderOverlay,e.applyFog=this.applyFog,this.actionManager&&(e.actions=this.actionManager.serialize(this.name)),e},t.prototype._syncGeometryWithMorphTargetManager=function(){if(this.geometry){this._markSubMeshesAsAttributesDirty();var e=this._internalAbstractMeshDataInfo._morphTargetManager;if(e&&e.vertexCount){if(e.vertexCount!==this.getTotalVertices())return ae.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count."),void(this.morphTargetManager=null);if(e.isUsingTextureForTargets)return;for(var t=0;t<e.numInfluencers;t++){var i=e.getActiveTarget(t),r=i.getPositions();if(!r)return void ae.Error("Invalid morph target. Target must have positions.");this.geometry.setVerticesData(Nr.PositionKind+t,r,!1,3);var n=i.getNormals();n&&this.geometry.setVerticesData(Nr.NormalKind+t,n,!1,3);var o=i.getTangents();o&&this.geometry.setVerticesData(Nr.TangentKind+t,o,!1,3);var a=i.getUVs();a&&this.geometry.setVerticesData(Nr.UVKind+"_"+t,a,!1,2)}}else for(t=0;this.geometry.isVerticesDataPresent(Nr.PositionKind+t);)this.geometry.removeVerticesData(Nr.PositionKind+t),this.geometry.isVerticesDataPresent(Nr.NormalKind+t)&&this.geometry.removeVerticesData(Nr.NormalKind+t),this.geometry.isVerticesDataPresent(Nr.TangentKind+t)&&this.geometry.removeVerticesData(Nr.TangentKind+t),this.geometry.isVerticesDataPresent(Nr.UVKind+t)&&this.geometry.removeVerticesData(Nr.UVKind+"_"+t),t++}},t.Parse=function(e,i,r){var n;if((n=e.type&&"LinesMesh"===e.type?t._LinesMeshParser(e,i):e.type&&"GroundMesh"===e.type?t._GroundMeshParser(e,i):e.type&&"GoldbergMesh"===e.type?t._GoldbergMeshParser(e,i):e.type&&"GreasedLineMesh"===e.type?t._GreasedLineMeshParser(e,i):e.type&&"TrailMesh"===e.type?t._TrailMeshParser(e,i):new t(e.name,i)).id=e.id,n._waitingParsedUniqueId=e.uniqueId,je&&je.AddTagsTo(n,e.tags),n.position=V.FromArray(e.position),void 0!==e.metadata&&(n.metadata=e.metadata),e.rotationQuaternion?n.rotationQuaternion=G.FromArray(e.rotationQuaternion):e.rotation&&(n.rotation=V.FromArray(e.rotation)),n.scaling=V.FromArray(e.scaling),e.localMatrix?n.setPreTransformMatrix(z.FromArray(e.localMatrix)):e.pivotMatrix&&n.setPivotMatrix(z.FromArray(e.pivotMatrix)),n.setEnabled(e.isEnabled),n.isVisible=e.isVisible,n.infiniteDistance=e.infiniteDistance,n.alwaysSelectAsActiveMesh=!!e.alwaysSelectAsActiveMesh,n.showBoundingBox=e.showBoundingBox,n.showSubMeshesBoundingBox=e.showSubMeshesBoundingBox,void 0!==e.applyFog&&(n.applyFog=e.applyFog),void 0!==e.pickable&&(n.isPickable=e.pickable),void 0!==e.alphaIndex&&(n.alphaIndex=e.alphaIndex),n.receiveShadows=e.receiveShadows,void 0!==e.billboardMode&&(n.billboardMode=e.billboardMode),void 0!==e.visibility&&(n.visibility=e.visibility),n.checkCollisions=e.checkCollisions,n.doNotSyncBoundingInfo=!!e.doNotSyncBoundingInfo,e.ellipsoid&&(n.ellipsoid=V.FromArray(e.ellipsoid)),e.ellipsoidOffset&&(n.ellipsoidOffset=V.FromArray(e.ellipsoidOffset)),void 0!==e.overrideMaterialSideOrientation&&(n.overrideMaterialSideOrientation=e.overrideMaterialSideOrientation),void 0!==e.isBlocker&&(n.isBlocker=e.isBlocker),n._shouldGenerateFlatShading=e.useFlatShading,e.freezeWorldMatrix&&(n._waitingData.freezeWorldMatrix=e.freezeWorldMatrix),void 0!==e.parentId&&(n._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(n._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.actions&&(n._waitingData.actions=e.actions),void 0!==e.overlayAlpha&&(n.overlayAlpha=e.overlayAlpha),void 0!==e.overlayColor&&(n.overlayColor=Z.FromArray(e.overlayColor)),void 0!==e.renderOverlay&&(n.renderOverlay=e.renderOverlay),n.isUnIndexed=!!e.isUnIndexed,n.hasVertexAlpha=e.hasVertexAlpha,e.delayLoadingFile?(n.delayLoadState=u.DELAYLOADSTATE_NOTLOADED,n.delayLoadingFile=r+e.delayLoadingFile,n.buildBoundingInfo(V.FromArray(e.boundingBoxMinimum),V.FromArray(e.boundingBoxMaximum)),e._binaryInfo&&(n._binaryInfo=e._binaryInfo),n._delayInfo=[],e.hasUVs&&n._delayInfo.push(Nr.UVKind),e.hasUVs2&&n._delayInfo.push(Nr.UV2Kind),e.hasUVs3&&n._delayInfo.push(Nr.UV3Kind),e.hasUVs4&&n._delayInfo.push(Nr.UV4Kind),e.hasUVs5&&n._delayInfo.push(Nr.UV5Kind),e.hasUVs6&&n._delayInfo.push(Nr.UV6Kind),e.hasColors&&n._delayInfo.push(Nr.ColorKind),e.hasMatricesIndices&&n._delayInfo.push(Nr.MatricesIndicesKind),e.hasMatricesWeights&&n._delayInfo.push(Nr.MatricesWeightsKind),n._delayLoadingFunction=vo._ImportGeometry,mo.ForceFullSceneLoadingForIncremental&&n._checkDelayState()):vo._ImportGeometry(e,n),e.materialUniqueId?n._waitingMaterialId=e.materialUniqueId:e.materialId&&(n._waitingMaterialId=e.materialId),e.morphTargetManagerId>-1&&(n.morphTargetManager=i.getMorphTargetManagerById(e.morphTargetManagerId)),void 0!==e.skeletonId&&null!==e.skeletonId&&(n.skeleton=i.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(n.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(var o=0;o<e.animations.length;o++){var a=e.animations[o];(d=s("BABYLON.Animation"))&&n.animations.push(d.Parse(a))}qe.ParseAnimationRanges(n,e,i)}if(e.autoAnimate&&i.beginAnimation(n,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.layerMask&&!isNaN(e.layerMask)?n.layerMask=Math.abs(parseInt(e.layerMask)):n.layerMask=268435455,e.physicsImpostor&&t._PhysicsImpostorParser(i,n,e),e.lodMeshIds&&(n._waitingData.lods={ids:e.lodMeshIds,distances:e.lodDistances?e.lodDistances:null,coverages:e.lodCoverages?e.lodCoverages:null}),e.instances)for(var l=0;l<e.instances.length;l++){var c=e.instances[l],h=n.createInstance(c.name);if(c.id&&(h.id=c.id),je&&(c.tags?je.AddTagsTo(h,c.tags):je.AddTagsTo(h,e.tags)),h.position=V.FromArray(c.position),void 0!==c.metadata&&(h.metadata=c.metadata),void 0!==c.parentId&&(h._waitingParentId=c.parentId),void 0!==c.parentInstanceIndex&&(h._waitingParentInstanceIndex=c.parentInstanceIndex),void 0!==c.isEnabled&&null!==c.isEnabled&&h.setEnabled(c.isEnabled),void 0!==c.isVisible&&null!==c.isVisible&&(h.isVisible=c.isVisible),void 0!==c.isPickable&&null!==c.isPickable&&(h.isPickable=c.isPickable),c.rotationQuaternion?h.rotationQuaternion=G.FromArray(c.rotationQuaternion):c.rotation&&(h.rotation=V.FromArray(c.rotation)),h.scaling=V.FromArray(c.scaling),null!=c.checkCollisions&&null!=c.checkCollisions&&(h.checkCollisions=c.checkCollisions),null!=c.pickable&&null!=c.pickable&&(h.isPickable=c.pickable),null!=c.showBoundingBox&&null!=c.showBoundingBox&&(h.showBoundingBox=c.showBoundingBox),null!=c.showSubMeshesBoundingBox&&null!=c.showSubMeshesBoundingBox&&(h.showSubMeshesBoundingBox=c.showSubMeshesBoundingBox),null!=c.alphaIndex&&null!=c.showSubMeshesBoundingBox&&(h.alphaIndex=c.alphaIndex),c.physicsImpostor&&t._PhysicsImpostorParser(i,h,c),void 0!==c.actions&&(h._waitingData.actions=c.actions),c.animations){for(o=0;o<c.animations.length;o++){var d;a=c.animations[o],(d=s("BABYLON.Animation"))&&h.animations.push(d.Parse(a))}qe.ParseAnimationRanges(h,c,i),c.autoAnimate&&i.beginAnimation(h,c.autoAnimateFrom,c.autoAnimateTo,c.autoAnimateLoop,c.autoAnimateSpeed||1)}}if(e.thinInstances){var p=e.thinInstances;if(n.thinInstanceEnablePicking=!!p.enablePicking,p.matrixData?(n.thinInstanceSetBuffer("matrix",new Float32Array(p.matrixData),16,!1),n._thinInstanceDataStorage.matrixBufferSize=p.matrixBufferSize,n._thinInstanceDataStorage.instancesCount=p.instancesCount):n._thinInstanceDataStorage.matrixBufferSize=p.matrixBufferSize,e.thinInstances.userThinInstance){var f=e.thinInstances.userThinInstance;for(var _ in f.data)n.thinInstanceSetBuffer(_,new Float32Array(f.data[_]),f.strides[_],!1),n._userThinInstanceBuffersStorage.sizes[_]=f.sizes[_]}}return n},t.prototype.setPositionsForCPUSkinning=function(){var e=this._internalMeshDataInfo;if(!e._sourcePositions){var t=this.getVerticesData(Nr.PositionKind);if(!t)return e._sourcePositions;e._sourcePositions=new Float32Array(t),this.isVertexBufferUpdatable(Nr.PositionKind)||this.setVerticesData(Nr.PositionKind,t,!0)}return e._sourcePositions},t.prototype.setNormalsForCPUSkinning=function(){var e=this._internalMeshDataInfo;if(!e._sourceNormals){var t=this.getVerticesData(Nr.NormalKind);if(!t)return e._sourceNormals;e._sourceNormals=new Float32Array(t),this.isVertexBufferUpdatable(Nr.NormalKind)||this.setVerticesData(Nr.NormalKind,t,!0)}return e._sourceNormals},t.prototype.applySkeleton=function(e){if(!this.geometry)return this;if(this.geometry._softwareSkinningFrameId==this.getScene().getFrameId())return this;if(this.geometry._softwareSkinningFrameId=this.getScene().getFrameId(),!this.isVerticesDataPresent(Nr.PositionKind))return this;if(!this.isVerticesDataPresent(Nr.MatricesIndicesKind))return this;if(!this.isVerticesDataPresent(Nr.MatricesWeightsKind))return this;var t=this.isVerticesDataPresent(Nr.NormalKind),i=this._internalMeshDataInfo;if(!i._sourcePositions){var r=this.subMeshes.slice();this.setPositionsForCPUSkinning(),this.subMeshes=r}t&&!i._sourceNormals&&this.setNormalsForCPUSkinning();var n=this.getVerticesData(Nr.PositionKind);if(!n)return this;n instanceof Float32Array||(n=new Float32Array(n));var o=this.getVerticesData(Nr.NormalKind);if(t){if(!o)return this;o instanceof Float32Array||(o=new Float32Array(o))}var a=this.getVerticesData(Nr.MatricesIndicesKind),s=this.getVerticesData(Nr.MatricesWeightsKind);if(!s||!a)return this;for(var l,c=this.numBoneInfluencers>4,u=c?this.getVerticesData(Nr.MatricesIndicesExtraKind):null,h=c?this.getVerticesData(Nr.MatricesWeightsExtraKind):null,d=e.getTransformMatrices(this),p=V.Zero(),f=new z,_=new z,m=0,g=0;g<n.length;g+=3,m+=4){var v=void 0;for(l=0;l<4;l++)(v=s[m+l])>0&&(z.FromFloat32ArrayToRefScaled(d,Math.floor(16*a[m+l]),v,_),f.addToSelf(_));if(c)for(l=0;l<4;l++)(v=h[m+l])>0&&(z.FromFloat32ArrayToRefScaled(d,Math.floor(16*u[m+l]),v,_),f.addToSelf(_));V.TransformCoordinatesFromFloatsToRef(i._sourcePositions[g],i._sourcePositions[g+1],i._sourcePositions[g+2],f,p),p.toArray(n,g),t&&(V.TransformNormalFromFloatsToRef(i._sourceNormals[g],i._sourceNormals[g+1],i._sourceNormals[g+2],f,p),p.toArray(o,g)),f.reset()}return this.updateVerticesData(Nr.PositionKind,n),t&&this.updateVerticesData(Nr.NormalKind,o),this},t.MinMax=function(e){var t=null,i=null;return e.forEach((function(e){var r=e.getBoundingInfo().boundingBox;t&&i?(t.minimizeInPlace(r.minimumWorld),i.maximizeInPlace(r.maximumWorld)):(t=r.minimumWorld,i=r.maximumWorld)})),t&&i?{min:t,max:i}:{min:V.Zero(),max:V.Zero()}},t.Center=function(e){var i=e instanceof Array?t.MinMax(e):e;return V.Center(i.min,i.max)},t.MergeMeshes=function(e,i,r,n,o,a){return void 0===i&&(i=!0),Kn(t._MergeMeshesCoroutine(e,i,r,n,o,a,!1))},t.MergeMeshesAsync=function(e,i,r,n,o,a){return void 0===i&&(i=!0),Qn(t._MergeMeshesCoroutine(e,i,r,n,o,a,!0),jn())},t._MergeMeshesCoroutine=function(e,i,r,n,o,a,s){var l,c,u,h,d,p,f,_,m,g,v,y,T,E,S,x,A,C,R,P,I,M,O,D,N,F;return void 0===i&&(i=!0),b(this,(function(b){switch(b.label){case 0:if(0===(e=e.filter(Boolean)).length)return[2,null];if(!r)for(c=0,l=0;l<e.length;l++)if((c+=e[l].getTotalVertices())>=65536)return ae.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),[2,null];for(a&&(o=!1),u=new Array,h=new Array,d=new Array,p=e[0].overrideMaterialSideOrientation,l=0;l<e.length;l++){if((f=e[l]).isAnInstance)return ae.Warn("Cannot merge instance meshes."),[2,null];if(p!==f.overrideMaterialSideOrientation)return ae.Warn("Cannot merge meshes with different overrideMaterialSideOrientation values."),[2,null];if(o&&d.push(f.getTotalIndices()),a)if(f.material)if((_=f.material)instanceof Ra){for(m=0;m<_.subMaterials.length;m++)u.indexOf(_.subMaterials[m])<0&&u.push(_.subMaterials[m]);for(N=0;N<f.subMeshes.length;N++)h.push(u.indexOf(_.subMaterials[f.subMeshes[N].materialIndex])),d.push(f.subMeshes[N].indexCount)}else for(u.indexOf(_)<0&&u.push(_),N=0;N<f.subMeshes.length;N++)h.push(u.indexOf(_)),d.push(f.subMeshes[N].indexCount);else for(N=0;N<f.subMeshes.length;N++)h.push(0),d.push(f.subMeshes[N].indexCount)}return g=e[0],v=function(e){var t=e.computeWorldMatrix(!0);return{vertexData:_o.ExtractFromMesh(e,!1,!1),transform:t}},F=v(g),y=F.vertexData,T=F.transform,s?[4]:[3,2];case 1:b.sent(),b.label=2;case 2:E=new Array(e.length-1),S=1,b.label=3;case 3:return S<e.length?(E[S-1]=v(e[S]),s?[4]:[3,5]):[3,6];case 4:b.sent(),b.label=5;case 5:return S++,[3,3];case 6:x=y._mergeCoroutine(T,E,r,s,!i),A=x.next(),b.label=7;case 7:return A.done?[3,10]:s?[4]:[3,9];case 8:b.sent(),b.label=9;case 9:return A=x.next(),[3,7];case 10:C=A.value,n||(n=new t(g.name+"_merged",g.getScene())),R=C._applyToCoroutine(n,void 0,s),P=R.next(),b.label=11;case 11:return P.done?[3,14]:s?[4]:[3,13];case 12:b.sent(),b.label=13;case 13:return P=R.next(),[3,11];case 14:if(n.checkCollisions=g.checkCollisions,n.overrideMaterialSideOrientation=g.overrideMaterialSideOrientation,i)for(l=0;l<e.length;l++)e[l].dispose();if(o||a){for(n.releaseSubMeshes(),l=0,I=0;l<d.length;)po.CreateFromIndices(0,I,d[l],n,void 0,!1),I+=d[l],l++;for(M=0,O=n.subMeshes;M<O.length;M++)O[M].refreshBoundingInfo();n.computeWorldMatrix(!0)}if(a){for((D=new Ra(g.name+"_merged",g.getScene())).subMaterials=u,N=0;N<n.subMeshes.length;N++)n.subMeshes[N].materialIndex=h[N];n.material=D}else n.material=g.material;return[2,n]}}))},t.prototype.addInstance=function(e){e._indexInSourceMeshInstanceArray=this.instances.length,this.instances.push(e)},t.prototype.removeInstance=function(e){var t=e._indexInSourceMeshInstanceArray;if(-1!=t){if(t!==this.instances.length-1){var i=this.instances[this.instances.length-1];this.instances[t]=i,i._indexInSourceMeshInstanceArray=t}e._indexInSourceMeshInstanceArray=-1,this.instances.pop()}},t.prototype._shouldConvertRHS=function(){return this.overrideMaterialSideOrientation===Ca.CounterClockWiseSideOrientation},t.prototype._getRenderingFillMode=function(e){var t,i=this.getScene();return i.forcePointsCloud?Ca.PointFillMode:i.forceWireframe?Ca.WireFrameFillMode:null!==(t=this.overrideRenderingFillMode)&&void 0!==t?t:e},t.prototype.setMaterialByID=function(e){return this.setMaterialById(e)},t.CreateRibbon=function(e,t,i,r,n,o,a,s,l){throw new Error("Import MeshBuilder to populate this function")},t.CreateDisc=function(e,t,i,r,n,o){throw new Error("Import MeshBuilder to populate this function")},t.CreateBox=function(e,t,i,r,n){throw new Error("Import MeshBuilder to populate this function")},t.CreateSphere=function(e,t,i,r,n,o){throw new Error("Import MeshBuilder to populate this function")},t.CreateHemisphere=function(e,t,i,r){throw new Error("Import MeshBuilder to populate this function")},t.CreateCylinder=function(e,t,i,r,n,o,a,s,l){throw new Error("Import MeshBuilder to populate this function")},t.CreateTorus=function(e,t,i,r,n,o,a){throw new Error("Import MeshBuilder to populate this function")},t.CreateTorusKnot=function(e,t,i,r,n,o,a,s,l,c){throw new Error("Import MeshBuilder to populate this function")},t.CreateLines=function(e,t,i,r,n){throw new Error("Import MeshBuilder to populate this function")},t.CreateDashedLines=function(e,t,i,r,n,o,a,s){throw new Error("Import MeshBuilder to populate this function")},t.CreatePolygon=function(e,t,i,r,n,o,a){throw new Error("Import MeshBuilder to populate this function")},t.ExtrudePolygon=function(e,t,i,r,n,o,a,s){throw new Error("Import MeshBuilder to populate this function")},t.ExtrudeShape=function(e,t,i,r,n,o,a,s,l,c){throw new Error("Import MeshBuilder to populate this function")},t.ExtrudeShapeCustom=function(e,t,i,r,n,o,a,s,l,c,u,h){throw new Error("Import MeshBuilder to populate this function")},t.CreateLathe=function(e,t,i,r,n,o,a){throw new Error("Import MeshBuilder to populate this function")},t.CreatePlane=function(e,t,i,r,n){throw new Error("Import MeshBuilder to populate this function")},t.CreateGround=function(e,t,i,r,n,o){throw new Error("Import MeshBuilder to populate this function")},t.CreateTiledGround=function(e,t,i,r,n,o,a,s,l){throw new Error("Import MeshBuilder to populate this function")},t.CreateGroundFromHeightMap=function(e,t,i,r,n,o,a,s,l,c,u){throw new Error("Import MeshBuilder to populate this function")},t.CreateTube=function(e,t,i,r,n,o,a,s,l,c){throw new Error("Import MeshBuilder to populate this function")},t.CreatePolyhedron=function(e,t,i){throw new Error("Import MeshBuilder to populate this function")},t.CreateIcoSphere=function(e,t,i){throw new Error("Import MeshBuilder to populate this function")},t.CreateDecal=function(e,t,i,r,n,o){throw new Error("Import MeshBuilder to populate this function")},t.CreateCapsule=function(e,t,i){throw new Error("Import MeshBuilder to populate this function")},t.ExtendToGoldberg=function(e){throw new Error("Import MeshBuilder to populate this function")},t.FRONTSIDE=_o.FRONTSIDE,t.BACKSIDE=_o.BACKSIDE,t.DOUBLESIDE=_o.DOUBLESIDE,t.DEFAULTSIDE=_o.DEFAULTSIDE,t.NO_CAP=0,t.CAP_START=1,t.CAP_END=2,t.CAP_ALL=3,t.NO_FLIP=0,t.FLIP_TILE=1,t.ROTATE_TILE=2,t.FLIP_ROW=3,t.ROTATE_ROW=4,t.FLIP_N_ROTATE_TILE=5,t.FLIP_N_ROTATE_ROW=6,t.CENTER=0,t.LEFT=1,t.RIGHT=2,t.TOP=3,t.BOTTOM=4,t.INSTANCEDMESH_SORT_TRANSPARENT=!1,t._GroundMeshParser=function(e,t){throw He("GroundMesh")},t._GoldbergMeshParser=function(e,t){throw He("GoldbergMesh")},t._LinesMeshParser=function(e,t){throw He("LinesMesh")},t._GreasedLineMeshParser=function(e,t){throw He("GreasedLineMesh")},t._GreasedLineRibbonMeshParser=function(e,t){throw He("GreasedLineRibbonMesh")},t._TrailMeshParser=function(e,t){throw He("TrailMesh")},t}(Uo);a("BABYLON.Mesh",Fa),Fa._instancedMeshFactory=function(e,t){var i=new La(e,t);if(t.instancedBuffers)for(var r in i.instancedBuffers={},t.instancedBuffers)i.instancedBuffers[r]=t.instancedBuffers[r];return i};var La=function(e){function t(t,i){var r=e.call(this,t,i.getScene())||this;r._indexInSourceMeshInstanceArray=-1,r._distanceToCamera=0,i.addInstance(r),r._sourceMesh=i,r._unIndexed=i._unIndexed,r.position.copyFrom(i.position),r.rotation.copyFrom(i.rotation),r.scaling.copyFrom(i.scaling),i.rotationQuaternion&&(r.rotationQuaternion=i.rotationQuaternion.clone()),r.animations=i.animations.slice();for(var n=0,o=i.getAnimationRanges();n<o.length;n++){var a=o[n];null!=a&&r.createAnimationRange(a.name,a.from,a.to)}return r.infiniteDistance=i.infiniteDistance,r.setPivotMatrix(i.getPivotMatrix()),r.refreshBoundingInfo(!0,!0),r._syncSubMeshes(),r}return m(t,e),t.prototype.getClassName=function(){return"InstancedMesh"},Object.defineProperty(t.prototype,"lightSources",{get:function(){return this._sourceMesh._lightSources},enumerable:!1,configurable:!0}),t.prototype._resyncLightSources=function(){},t.prototype._resyncLightSource=function(){},t.prototype._removeLightSource=function(){},Object.defineProperty(t.prototype,"receiveShadows",{get:function(){return this._sourceMesh.receiveShadows},set:function(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.receiveShadows)!==e&&rr.Warn("Setting receiveShadows on an instanced mesh has no effect")},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"material",{get:function(){return this._sourceMesh.material},set:function(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.material)!==e&&rr.Warn("Setting material on an instanced mesh has no effect")},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"visibility",{get:function(){return this._sourceMesh.visibility},set:function(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.visibility)!==e&&rr.Warn("Setting visibility on an instanced mesh has no effect")},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"skeleton",{get:function(){return this._sourceMesh.skeleton},set:function(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.skeleton)!==e&&rr.Warn("Setting skeleton on an instanced mesh has no effect")},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"renderingGroupId",{get:function(){return this._sourceMesh.renderingGroupId},set:function(e){this._sourceMesh&&e!==this._sourceMesh.renderingGroupId&&ae.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")},enumerable:!1,configurable:!0}),t.prototype.getTotalVertices=function(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0},t.prototype.getTotalIndices=function(){return this._sourceMesh.getTotalIndices()},Object.defineProperty(t.prototype,"sourceMesh",{get:function(){return this._sourceMesh},enumerable:!1,configurable:!0}),t.prototype.createInstance=function(e){return this._sourceMesh.createInstance(e)},t.prototype.isReady=function(e){return void 0===e&&(e=!1),this._sourceMesh.isReady(e,!0)},t.prototype.getVerticesData=function(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)},t.prototype.setVerticesData=function(e,t,i,r){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,r),this.sourceMesh},t.prototype.updateVerticesData=function(e,t,i,r){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,r),this.sourceMesh},t.prototype.setIndices=function(e,t){return void 0===t&&(t=null),this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh},t.prototype.isVerticesDataPresent=function(e){return this._sourceMesh.isVerticesDataPresent(e)},t.prototype.getIndices=function(){return this._sourceMesh.getIndices()},Object.defineProperty(t.prototype,"_positions",{get:function(){return this._sourceMesh._positions},enumerable:!1,configurable:!0}),t.prototype.refreshBoundingInfo=function(e,t){if(void 0===e&&(e=!1),void 0===t&&(t=!1),this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;var i=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e,t),i),this},t.prototype._preActivate=function(){return this._currentLOD&&this._currentLOD._preActivate(),this},t.prototype._activate=function(t,i){if(e.prototype._activate.call(this,t,i),this._sourceMesh.subMeshes||ae.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){if(this._currentLOD._getWorldMatrixDeterminant()>=0!=this._getWorldMatrixDeterminant()>=0)return this._internalAbstractMeshDataInfo._actAsRegularMesh=!0,!0;if(this._internalAbstractMeshDataInfo._actAsRegularMesh=!1,this._currentLOD._registerInstanceForRenderId(this,t),i){if(!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!0,!0}else if(!this._currentLOD._internalAbstractMeshDataInfo._isActive)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances=!0,!0}return!1},t.prototype._postActivate=function(){this._sourceMesh.edgesShareWithInstances&&this._sourceMesh._edgesRenderer&&this._sourceMesh._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup?(this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer),this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix())):this._edgesRenderer&&this._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup&&this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer)},t.prototype.getWorldMatrix=function(){if(this._currentLOD&&this._currentLOD.billboardMode!==Fo.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new z);var t=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,H.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(H.Vector3[7]),this._currentLOD._masterMesh=t,this._billboardWorldMatrix}return e.prototype.getWorldMatrix.call(this)},Object.defineProperty(t.prototype,"isAnInstance",{get:function(){return!0},enumerable:!1,configurable:!0}),t.prototype.getLOD=function(e){if(!e)return this;var t=this.sourceMesh.getLODLevels();if(t&&0!==t.length){var i=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,i.boundingSphere)}else this._currentLOD=this.sourceMesh;return this._currentLOD},t.prototype._preActivateForIntermediateRendering=function(e){return this.sourceMesh._preActivateForIntermediateRendering(e)},t.prototype._syncSubMeshes=function(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(var e=0;e<this._sourceMesh.subMeshes.length;e++)this._sourceMesh.subMeshes[e].clone(this,this._sourceMesh);return this},t.prototype._generatePointsArray=function(){return this._sourceMesh._generatePointsArray()},t.prototype._updateBoundingInfo=function(){return this.hasBoundingInfo?this.getBoundingInfo().update(this.worldMatrixFromCache):this.buildBoundingInfo(this.absolutePosition,this.absolutePosition,this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this},t.prototype.clone=function(e,t,i,r){void 0===t&&(t=null);var n=(r||this._sourceMesh).createInstance(e);if(ye.DeepCopy(this,n,["name","subMeshes","uniqueId","parent","lightSources","receiveShadows","material","visibility","skeleton","sourceMesh","isAnInstance","facetNb","isFacetDataEnabled","isBlocked","useBones","hasInstances","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","hasBoundingInfo"],[]),this.refreshBoundingInfo(),t&&(n.parent=t),!i)for(var o=0;o<this.getScene().meshes.length;o++){var a=this.getScene().meshes[o];a.parent===this&&a.clone(a.name,n)}return n.computeWorldMatrix(!0),this.onClonedObservable.notifyObservers(n),n},t.prototype.dispose=function(t,i){void 0===i&&(i=!1),this._sourceMesh.removeInstance(this),e.prototype.dispose.call(this,t,i)},t.prototype._serializeAsParent=function(t){e.prototype._serializeAsParent.call(this,t),t.parentId=this._sourceMesh.uniqueId,t.parentInstanceIndex=this._indexInSourceMeshInstanceArray},t.prototype.instantiateHierarchy=function(e,t,i){void 0===e&&(e=null);var r=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0,t&&t.newSourcedMesh);r&&i&&i(this,r);for(var n=0,o=this.getChildTransformNodes(!0);n<o.length;n++)o[n].instantiateHierarchy(r,t,i);return r},t}(Uo);Fa.prototype.registerInstancedBuffer=function(e,t){var i,r;if(null===(r=null===(i=this._userInstancedBuffersStorage)||void 0===i?void 0:i.vertexBuffers[e])||void 0===r||r.dispose(),!this.instancedBuffers){this.instancedBuffers={};for(var n=0,o=this.instances;n<o.length;n++)o[n].instancedBuffers={}}this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}),this.instancedBuffers[e]=null,this._userInstancedBuffersStorage.strides[e]=t,this._userInstancedBuffersStorage.sizes[e]=32*t,this._userInstancedBuffersStorage.data[e]=new Float32Array(this._userInstancedBuffersStorage.sizes[e]),this._userInstancedBuffersStorage.vertexBuffers[e]=new Nr(this.getEngine(),this._userInstancedBuffersStorage.data[e],e,!0,!1,t,!0);for(var a=0,s=this.instances;a<s.length;a++)s[a].instancedBuffers[e]=null;this._invalidateInstanceVertexArrayObject(),this._markSubMeshesAsAttributesDirty()},Fa.prototype._processInstancedBuffers=function(e,t){var i=e?e.length:0;for(var r in this.instancedBuffers){for(var n=this._userInstancedBuffersStorage.sizes[r],o=this._userInstancedBuffersStorage.strides[r],a=(i+1)*o;n<a;)n*=2;this._userInstancedBuffersStorage.data[r].length!=n&&(this._userInstancedBuffersStorage.data[r]=new Float32Array(n),this._userInstancedBuffersStorage.sizes[r]=n,this._userInstancedBuffersStorage.vertexBuffers[r]&&(this._userInstancedBuffersStorage.vertexBuffers[r].dispose(),this._userInstancedBuffersStorage.vertexBuffers[r]=null));var s=this._userInstancedBuffersStorage.data[r],l=0;t&&((u=this.instancedBuffers[r]).toArray?u.toArray(s,l):u.copyToArray?u.copyToArray(s,l):s[l]=u,l+=o);for(var c=0;c<i;c++){var u;(u=e[c].instancedBuffers[r]).toArray?u.toArray(s,l):u.copyToArray?u.copyToArray(s,l):s[l]=u,l+=o}this._userInstancedBuffersStorage.vertexBuffers[r]?this._userInstancedBuffersStorage.vertexBuffers[r].updateDirectly(s,0):(this._userInstancedBuffersStorage.vertexBuffers[r]=new Nr(this.getEngine(),this._userInstancedBuffersStorage.data[r],r,!0,!1,o,!0),this._invalidateInstanceVertexArrayObject())}},Fa.prototype._invalidateInstanceVertexArrayObject=function(){if(this._userInstancedBuffersStorage&&void 0!==this._userInstancedBuffersStorage.vertexArrayObjects){for(var e in this._userInstancedBuffersStorage.vertexArrayObjects)this.getEngine().releaseVertexArrayObject(this._userInstancedBuffersStorage.vertexArrayObjects[e]);this._userInstancedBuffersStorage.vertexArrayObjects={}}},Fa.prototype._disposeInstanceSpecificData=function(){for(this._instanceDataStorage.instancesBuffer&&(this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null);this.instances.length;)this.instances[0].dispose();for(var e in this.instancedBuffers)this._userInstancedBuffersStorage.vertexBuffers[e]&&this._userInstancedBuffersStorage.vertexBuffers[e].dispose();this._invalidateInstanceVertexArrayObject(),this.instancedBuffers={}},a("BABYLON.InstancedMesh",La);var wa=function(e){function t(i,r){var n=e.call(this,i,r,!1)||this;return n.diffuse=new Z(1,1,1),n.specular=new Z(1,1,1),n.falloffType=t.FALLOFF_DEFAULT,n.intensity=1,n._range=Number.MAX_VALUE,n._inverseSquaredRange=0,n._photometricScale=1,n._intensityMode=t.INTENSITYMODE_AUTOMATIC,n._radius=1e-5,n.renderPriority=0,n._shadowEnabled=!0,n._excludeWithLayerMask=0,n._includeOnlyWithLayerMask=0,n._lightmapMode=0,n._shadowGenerators=null,n._excludedMeshesIds=new Array,n._includedOnlyMeshesIds=new Array,n._isLight=!0,n.getScene().addLight(n),n._uniformBuffer=new Or(n.getScene().getEngine(),void 0,void 0,i),n._buildUniformLayout(),n.includedOnlyMeshes=[],n.excludedMeshes=[],n._resyncMeshes(),n}return m(t,e),Object.defineProperty(t.prototype,"range",{get:function(){return this._range},set:function(e){this._range=e,this._inverseSquaredRange=1/(this.range*this.range)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"intensityMode",{get:function(){return this._intensityMode},set:function(e){this._intensityMode=e,this._computePhotometricScale()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"radius",{get:function(){return this._radius},set:function(e){this._radius=e,this._computePhotometricScale()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"shadowEnabled",{get:function(){return this._shadowEnabled},set:function(e){this._shadowEnabled!==e&&(this._shadowEnabled=e,this._markMeshesAsLightDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"includedOnlyMeshes",{get:function(){return this._includedOnlyMeshes},set:function(e){this._includedOnlyMeshes=e,this._hookArrayForIncludedOnly(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"excludedMeshes",{get:function(){return this._excludedMeshes},set:function(e){this._excludedMeshes=e,this._hookArrayForExcluded(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"excludeWithLayerMask",{get:function(){return this._excludeWithLayerMask},set:function(e){this._excludeWithLayerMask=e,this._resyncMeshes()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"includeOnlyWithLayerMask",{get:function(){return this._includeOnlyWithLayerMask},set:function(e){this._includeOnlyWithLayerMask=e,this._resyncMeshes()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"lightmapMode",{get:function(){return this._lightmapMode},set:function(e){this._lightmapMode!==e&&(this._lightmapMode=e,this._markMeshesAsLightDirty())},enumerable:!1,configurable:!0}),t.prototype.getViewMatrix=function(e){return null},t.prototype.getProjectionMatrix=function(e,t){return null},t.prototype.transferTexturesToEffect=function(e,t){return this},t.prototype._bindLight=function(e,t,i,r,n){var o;void 0===n&&(n=!0);var a=e.toString(),s=!1;if(this._uniformBuffer.bindToEffect(i,"Light"+a),this._renderId!==t.getRenderId()||this._lastUseSpecular!==r||!this._uniformBuffer.useUbo){this._renderId=t.getRenderId(),this._lastUseSpecular=r;var l=this.getScaledIntensity();this.transferToEffect(i,a),this.diffuse.scaleToRef(l,$.Color3[0]),this._uniformBuffer.updateColor4("vLightDiffuse",$.Color3[0],this.range,a),r&&(this.specular.scaleToRef(l,$.Color3[1]),this._uniformBuffer.updateColor4("vLightSpecular",$.Color3[1],this.radius,a)),s=!0}if(this.transferTexturesToEffect(i,a),t.shadowsEnabled&&this.shadowEnabled&&n){var c=null!==(o=this.getShadowGenerator(t.activeCamera))&&void 0!==o?o:this.getShadowGenerator();c&&(c.bindShadowLight(a,i),s=!0)}s?this._uniformBuffer.update():this._uniformBuffer.bindUniformBuffer()},t.prototype.getClassName=function(){return"Light"},t.prototype.toString=function(e){var t="Name: "+this.name;if(t+=", type: "+["Point","Directional","Spot","Hemispheric"][this.getTypeID()],this.animations)for(var i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t},t.prototype._syncParentEnabledState=function(){e.prototype._syncParentEnabledState.call(this),this.isDisposed()||this._resyncMeshes()},t.prototype.setEnabled=function(t){e.prototype.setEnabled.call(this,t),this._resyncMeshes()},t.prototype.getShadowGenerator=function(e){var t;return void 0===e&&(e=null),null===this._shadowGenerators?null:null!==(t=this._shadowGenerators.get(e))&&void 0!==t?t:null},t.prototype.getShadowGenerators=function(){return this._shadowGenerators},t.prototype.getAbsolutePosition=function(){return V.Zero()},t.prototype.canAffectMesh=function(e){return!(e&&(this.includedOnlyMeshes&&this.includedOnlyMeshes.length>0&&-1===this.includedOnlyMeshes.indexOf(e)||this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)||!(0===this.includeOnlyWithLayerMask||this.includeOnlyWithLayerMask&e.layerMask)||0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask))},t.prototype.dispose=function(t,i){if(void 0===i&&(i=!1),this._shadowGenerators){for(var r=this._shadowGenerators.values(),n=r.next();!0!==n.done;n=r.next())n.value.dispose();this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){var o=this._parentContainer.lights.indexOf(this);o>-1&&this._parentContainer.lights.splice(o,1),this._parentContainer=null}for(var a=0,s=this.getScene().meshes;a<s.length;a++)s[a]._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),e.prototype.dispose.call(this,t,i)},t.prototype.getTypeID=function(){return 0},t.prototype.getScaledIntensity=function(){return this._photometricScale*this.intensity},t.prototype.clone=function(e,i){void 0===i&&(i=null);var r=t.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!r)return null;var n=Ke.Clone(r,this);return e&&(n.name=e),i&&(n.parent=i),n.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(n),n},t.prototype.serialize=function(){var e=Ke.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getTypeID(),this.parent&&this.parent._serializeAsParent(e),this.excludedMeshes.length>0&&(e.excludedMeshesIds=[],this.excludedMeshes.forEach((function(t){e.excludedMeshesIds.push(t.id)}))),this.includedOnlyMeshes.length>0&&(e.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach((function(t){e.includedOnlyMeshesIds.push(t.id)}))),Ke.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e},t.GetConstructorFromName=function(e,t,i){return qe.Construct("Light_Type_"+e,t,i)||null},t.Parse=function(e,i){var r=t.GetConstructorFromName(e.type,e.name,i);if(!r)return null;var n=Ke.Parse(r,e,i);if(e.excludedMeshesIds&&(n._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(n._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(n._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(n._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(n.falloffType=e.falloffType),void 0!==e.lightmapMode&&(n.lightmapMode=e.lightmapMode),e.animations){for(var o=0;o<e.animations.length;o++){var a=e.animations[o],l=s("BABYLON.Animation");l&&n.animations.push(l.Parse(a))}qe.ParseAnimationRanges(n,e,i)}return e.autoAnimate&&i.beginAnimation(n,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),void 0!==e.isEnabled&&n.setEnabled(e.isEnabled),n},t.prototype._hookArrayForExcluded=function(e){var t=this,i=e.push;e.push=function(){for(var r=[],n=0;n<arguments.length;n++)r[n]=arguments[n];for(var o=i.apply(e,r),a=0,s=r;a<s.length;a++)s[a]._resyncLightSource(t);return o};var r=e.splice;e.splice=function(i,n){for(var o=r.apply(e,[i,n]),a=0,s=o;a<s.length;a++)s[a]._resyncLightSource(t);return o};for(var n=0,o=e;n<o.length;n++)o[n]._resyncLightSource(this)},t.prototype._hookArrayForIncludedOnly=function(e){var t=this,i=e.push;e.push=function(){for(var r=[],n=0;n<arguments.length;n++)r[n]=arguments[n];var o=i.apply(e,r);return t._resyncMeshes(),o};var r=e.splice;e.splice=function(i,n){var o=r.apply(e,[i,n]);return t._resyncMeshes(),o},this._resyncMeshes()},t.prototype._resyncMeshes=function(){for(var e=0,t=this.getScene().meshes;e<t.length;e++)t[e]._resyncLightSource(this)},t.prototype._markMeshesAsLightDirty=function(){for(var e=0,t=this.getScene().meshes;e<t.length;e++){var i=t[e];-1!==i.lightSources.indexOf(this)&&i._markSubMeshesAsLightDirty()}},t.prototype._computePhotometricScale=function(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()},t.prototype._getPhotometricScale=function(){var e=0,i=this.getTypeID(),r=this.intensityMode;switch(r===t.INTENSITYMODE_AUTOMATIC&&(r=i===t.LIGHTTYPEID_DIRECTIONALLIGHT?t.INTENSITYMODE_ILLUMINANCE:t.INTENSITYMODE_LUMINOUSINTENSITY),i){case t.LIGHTTYPEID_POINTLIGHT:case t.LIGHTTYPEID_SPOTLIGHT:switch(r){case t.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case t.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case t.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case t.LIGHTTYPEID_DIRECTIONALLIGHT:switch(r){case t.INTENSITYMODE_ILLUMINANCE:e=1;break;case t.INTENSITYMODE_LUMINANCE:var n=this.radius;n=Math.max(n,.001),e=2*Math.PI*(1-Math.cos(n))}break;case t.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e},t.prototype._reorderLightsInScene=function(){var e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()},t.FALLOFF_DEFAULT=un.FALLOFF_DEFAULT,t.FALLOFF_PHYSICAL=un.FALLOFF_PHYSICAL,t.FALLOFF_GLTF=un.FALLOFF_GLTF,t.FALLOFF_STANDARD=un.FALLOFF_STANDARD,t.LIGHTMAP_DEFAULT=un.LIGHTMAP_DEFAULT,t.LIGHTMAP_SPECULAR=un.LIGHTMAP_SPECULAR,t.LIGHTMAP_SHADOWSONLY=un.LIGHTMAP_SHADOWSONLY,t.INTENSITYMODE_AUTOMATIC=un.INTENSITYMODE_AUTOMATIC,t.INTENSITYMODE_LUMINOUSPOWER=un.INTENSITYMODE_LUMINOUSPOWER,t.INTENSITYMODE_LUMINOUSINTENSITY=un.INTENSITYMODE_LUMINOUSINTENSITY,t.INTENSITYMODE_ILLUMINANCE=un.INTENSITYMODE_ILLUMINANCE,t.INTENSITYMODE_LUMINANCE=un.INTENSITYMODE_LUMINANCE,t.LIGHTTYPEID_POINTLIGHT=un.LIGHTTYPEID_POINTLIGHT,t.LIGHTTYPEID_DIRECTIONALLIGHT=un.LIGHTTYPEID_DIRECTIONALLIGHT,t.LIGHTTYPEID_SPOTLIGHT=un.LIGHTTYPEID_SPOTLIGHT,t.LIGHTTYPEID_HEMISPHERICLIGHT=un.LIGHTTYPEID_HEMISPHERICLIGHT,v([Oe()],t.prototype,"diffuse",void 0),v([Oe()],t.prototype,"specular",void 0),v([Ie()],t.prototype,"falloffType",void 0),v([Ie()],t.prototype,"intensity",void 0),v([Ie()],t.prototype,"range",null),v([Ie()],t.prototype,"intensityMode",null),v([Ie()],t.prototype,"radius",null),v([Ie()],t.prototype,"_renderPriority",void 0),v([Pe("_reorderLightsInScene")],t.prototype,"renderPriority",void 0),v([Ie("shadowEnabled")],t.prototype,"_shadowEnabled",void 0),v([Ie("excludeWithLayerMask")],t.prototype,"_excludeWithLayerMask",void 0),v([Ie("includeOnlyWithLayerMask")],t.prototype,"_includeOnlyWithLayerMask",void 0),v([Ie("lightmapMode")],t.prototype,"_lightmapMode",void 0),t}(qe),Ba=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t}(c),Ua=function(){function e(){this.rootNodes=[],this.skeletons=[],this.animationGroups=[]}return e.prototype.dispose=function(){this.rootNodes.slice(0).forEach((function(e){e.dispose()})),this.rootNodes.length=0,this.skeletons.slice(0).forEach((function(e){e.dispose()})),this.skeletons.length=0,this.animationGroups.slice(0).forEach((function(e){e.dispose()})),this.animationGroups.length=0},e}(),Va=function(e){function t(t){var i=e.call(this)||this;return i._wasAddedToScene=!1,(t=t||M.LastCreatedScene)?(i.scene=t,i.sounds=[],i.effectLayers=[],i.layers=[],i.lensFlareSystems=[],i.proceduralTextures=[],i.reflectionProbes=[],t.onDisposeObservable.add((function(){i._wasAddedToScene||i.dispose()})),i._onContextRestoredObserver=t.getEngine().onContextRestoredObservable.add((function(){for(var e=0,t=i.geometries;e<t.length;e++)t[e]._rebuild();for(var r=0,n=i.meshes;r<n.length;r++)n[r]._rebuild();for(var o=0,a=i.particleSystems;o<a.length;o++)a[o].rebuild();for(var s=0,l=i.textures;s<l.length;s++)l[s]._rebuild()})),i):i}return m(t,e),t.prototype._topologicalSort=function(e){for(var t=new Map,i=0,r=e;i<r.length;i++){var n=r[i];t.set(n.uniqueId,n)}for(var o={dependsOn:new Map,dependedBy:new Map},a=0,s=e;a<s.length;a++){var l=(n=s[a]).uniqueId;o.dependsOn.set(l,new Set),o.dependedBy.set(l,new Set)}for(var c=0,u=e;c<u.length;c++){l=(n=u[c]).uniqueId;var h=o.dependsOn.get(l);if(n instanceof La){var d=n.sourceMesh;t.has(d.uniqueId)&&(h.add(d.uniqueId),o.dependedBy.get(d.uniqueId).add(l))}for(var p=o.dependedBy.get(l),f=0,_=n.getDescendants();f<_.length;f++){var m=_[f].uniqueId;t.has(m)&&(p.add(m),o.dependsOn.get(m).add(l))}}for(var g=[],v=[],y=0,b=e;y<b.length;y++)l=(n=b[y]).uniqueId,0===o.dependsOn.get(l).size&&(v.push(n),t.delete(l));for(var T=v;T.length>0;){var E=T.shift();g.push(E);for(var S=o.dependedBy.get(E.uniqueId),x=0,A=Array.from(S.values());x<A.length;x++){var C=A[x],R=o.dependsOn.get(C);R.delete(E.uniqueId),0===R.size&&t.get(C)&&(T.push(t.get(C)),t.delete(C))}}return t.size>0&&(ae.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach((function(e){return ae.Error(e.name)}))),g},t.prototype._addNodeAndDescendantsToList=function(e,t,i,r){if(i&&(!r||r(i))&&!t.has(i.uniqueId)){e.push(i),t.add(i.uniqueId);for(var n=0,o=i.getDescendants(!0);n<o.length;n++){var a=o[n];this._addNodeAndDescendantsToList(e,t,a,r)}}},t.prototype._isNodeInContainer=function(e){return e instanceof Uo&&-1!==this.meshes.indexOf(e)||e instanceof Fo&&-1!==this.transformNodes.indexOf(e)||e instanceof wa&&-1!==this.lights.indexOf(e)||e instanceof $n&&-1!==this.cameras.indexOf(e)},t.prototype._isValidHierarchy=function(){for(var e=0,t=this.meshes;e<t.length;e++)if((l=t[e]).parent&&!this._isNodeInContainer(l.parent))return ae.Warn("Node ".concat(l.name," has a parent that is not in the container.")),!1;for(var i=0,r=this.transformNodes;i<r.length;i++)if((l=r[i]).parent&&!this._isNodeInContainer(l.parent))return ae.Warn("Node ".concat(l.name," has a parent that is not in the container.")),!1;for(var n=0,o=this.lights;n<o.length;n++)if((l=o[n]).parent&&!this._isNodeInContainer(l.parent))return ae.Warn("Node ".concat(l.name," has a parent that is not in the container.")),!1;for(var a=0,s=this.cameras;a<s.length;a++){var l;if((l=s[a]).parent&&!this._isNodeInContainer(l.parent))return ae.Warn("Node ".concat(l.name," has a parent that is not in the container.")),!1}return!0},t.prototype.instantiateModelsToScene=function(e,t,i){var r=this;void 0===t&&(t=!1),this._isValidHierarchy()||rr.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");for(var n={},o={},a=new Ua,s=[],l=[],c=g({doNotInstantiate:!0},i),u=[],h=new Set,d=0,p=this.transformNodes;d<p.length;d++){var f=p[d];null===f.parent&&this._addNodeAndDescendantsToList(u,h,f,c.predicate)}for(var _=0,m=this.meshes;_<m.length;_++){var v=m[_];null===v.parent&&this._addNodeAndDescendantsToList(u,h,v,c.predicate)}var y=this._topologicalSort(u),b=function(i,s){if(function(t,i){if(n[t.uniqueId]=i.uniqueId,o[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof Fa){var r=i;if(r.morphTargetManager){var a=t.morphTargetManager;r.morphTargetManager=a.clone();for(var s=0;s<a.numTargets;s++){var l=a.getTarget(s),c=r.morphTargetManager.getTarget(s);n[l.uniqueId]=c.uniqueId,o[c.uniqueId]=c}}}}(i,s),i.parent){var c=n[i.parent.uniqueId],u=o[c];s.parent=u||i.parent}if(s.position&&i.position&&s.position.copyFrom(i.position),s.rotationQuaternion&&i.rotationQuaternion&&s.rotationQuaternion.copyFrom(i.rotationQuaternion),s.rotation&&i.rotation&&s.rotation.copyFrom(i.rotation),s.scaling&&i.scaling&&s.scaling.copyFrom(i.scaling),s.material){var h=s;if(h.material)if(t){var d=i.material;if(-1===l.indexOf(d)){var p=d.clone(e?e(d.name):"Clone of "+d.name);if(l.push(d),n[d.uniqueId]=p.uniqueId,o[p.uniqueId]=p,"MultiMaterial"===d.getClassName()){for(var f=d,_=0,m=f.subMaterials;_<m.length;_++){var g=m[_];g&&(p=g.clone(e?e(g.name):"Clone of "+g.name),l.push(g),n[g.uniqueId]=p.uniqueId,o[p.uniqueId]=p)}f.subMaterials=f.subMaterials.map((function(e){return e&&o[n[e.uniqueId]]}))}}"InstancedMesh"!==h.getClassName()&&(h.material=o[n[d.uniqueId]])}else"MultiMaterial"===h.material.getClassName()?-1===r.scene.multiMaterials.indexOf(h.material)&&r.scene.addMultiMaterial(h.material):-1===r.scene.materials.indexOf(h.material)&&r.scene.addMaterial(h.material)}null===s.parent&&a.rootNodes.push(s)};return y.forEach((function(e){if("InstancedMesh"===e.getClassName()){var t=e,i=t.sourceMesh,r=n[i.uniqueId],a=("number"==typeof r?o[r]:i).createInstance(t.name);b(t,a)}else{var s=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||!e.getTotalVertices||0===e.getTotalVertices()?s=!1:c.doNotInstantiate&&(s="function"==typeof c.doNotInstantiate?!c.doNotInstantiate(e):!c.doNotInstantiate);var l=s?e.createInstance("instance of ".concat(e.name)):e.clone("Clone of ".concat(e.name),null,!0);if(!l)throw new Error("Could not clone or instantiate node on Asset Container ".concat(e.name));b(e,l)}})),this.skeletons.forEach((function(t){if(!c.predicate||c.predicate(t)){for(var i=t.clone(e?e(t.name):"Clone of "+t.name),l=0,u=r.meshes;l<u.length;l++){var h=u[l];if(h.skeleton===t&&!h.isAnInstance){var d=o[n[h.uniqueId]];if(!d||d.isAnInstance)continue;if(d.skeleton=i,-1!==s.indexOf(i))continue;s.push(i);for(var p=0,f=i.bones;p<f.length;p++){var _=f[p];_._linkedTransformNode&&(_._linkedTransformNode=o[n[_._linkedTransformNode.uniqueId]])}}}a.skeletons.push(i)}})),this.animationGroups.forEach((function(t){if(!c.predicate||c.predicate(t)){var i=t.clone(e?e(t.name):"Clone of "+t.name,(function(e){return o[n[e.uniqueId]]||e}));a.animationGroups.push(i)}})),a},t.prototype.addAllToScene=function(){if(!this._wasAddedToScene){this._isValidHierarchy()||rr.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture);for(var e=0,t=this.scene._serializableComponents;e<t.length;e++)t[e].addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}},t.prototype.addToScene=function(e){var t=this;void 0===e&&(e=null);var i=[];this.cameras.forEach((function(r){e&&!e(r)||(t.scene.addCamera(r),i.push(r))})),this.lights.forEach((function(r){e&&!e(r)||(t.scene.addLight(r),i.push(r))})),this.meshes.forEach((function(r){e&&!e(r)||(t.scene.addMesh(r),i.push(r))})),this.skeletons.forEach((function(i){e&&!e(i)||t.scene.addSkeleton(i)})),this.animations.forEach((function(i){e&&!e(i)||t.scene.addAnimation(i)})),this.animationGroups.forEach((function(i){e&&!e(i)||t.scene.addAnimationGroup(i)})),this.multiMaterials.forEach((function(i){e&&!e(i)||t.scene.addMultiMaterial(i)})),this.materials.forEach((function(i){e&&!e(i)||t.scene.addMaterial(i)})),this.morphTargetManagers.forEach((function(i){e&&!e(i)||t.scene.addMorphTargetManager(i)})),this.geometries.forEach((function(i){e&&!e(i)||t.scene.addGeometry(i)})),this.transformNodes.forEach((function(r){e&&!e(r)||(t.scene.addTransformNode(r),i.push(r))})),this.actionManagers.forEach((function(i){e&&!e(i)||t.scene.addActionManager(i)})),this.textures.forEach((function(i){e&&!e(i)||t.scene.addTexture(i)})),this.reflectionProbes.forEach((function(i){e&&!e(i)||t.scene.addReflectionProbe(i)}));for(var r=0,n=i;r<n.length;r++){var o=n[r];o.parent&&-1===this.scene.getNodes().indexOf(o.parent)&&(o.setParent?o.setParent(null):o.parent=null)}},t.prototype.removeAllFromScene=function(){this._isValidHierarchy()||rr.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!1,this.removeFromScene(null),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(var e=0,t=this.scene._serializableComponents;e<t.length;e++)t[e].removeFromContainer(this)},t.prototype.removeFromScene=function(e){var t=this;void 0===e&&(e=null),this.cameras.forEach((function(i){e&&!e(i)||t.scene.removeCamera(i)})),this.lights.forEach((function(i){e&&!e(i)||t.scene.removeLight(i)})),this.meshes.forEach((function(i){e&&!e(i)||t.scene.removeMesh(i,!0)})),this.skeletons.forEach((function(i){e&&!e(i)||t.scene.removeSkeleton(i)})),this.animations.forEach((function(i){e&&!e(i)||t.scene.removeAnimation(i)})),this.animationGroups.forEach((function(i){e&&!e(i)||t.scene.removeAnimationGroup(i)})),this.multiMaterials.forEach((function(i){e&&!e(i)||t.scene.removeMultiMaterial(i)})),this.materials.forEach((function(i){e&&!e(i)||t.scene.removeMaterial(i)})),this.morphTargetManagers.forEach((function(i){e&&!e(i)||t.scene.removeMorphTargetManager(i)})),this.geometries.forEach((function(i){e&&!e(i)||t.scene.removeGeometry(i)})),this.transformNodes.forEach((function(i){e&&!e(i)||t.scene.removeTransformNode(i)})),this.actionManagers.forEach((function(i){e&&!e(i)||t.scene.removeActionManager(i)})),this.textures.forEach((function(i){e&&!e(i)||t.scene.removeTexture(i)})),this.reflectionProbes.forEach((function(i){e&&!e(i)||t.scene.removeReflectionProbe(i)}))},t.prototype.dispose=function(){this.cameras.slice(0).forEach((function(e){e.dispose()})),this.cameras.length=0,this.lights.slice(0).forEach((function(e){e.dispose()})),this.lights.length=0,this.meshes.slice(0).forEach((function(e){e.dispose()})),this.meshes.length=0,this.skeletons.slice(0).forEach((function(e){e.dispose()})),this.skeletons.length=0,this.animationGroups.slice(0).forEach((function(e){e.dispose()})),this.animationGroups.length=0,this.multiMaterials.slice(0).forEach((function(e){e.dispose()})),this.multiMaterials.length=0,this.materials.slice(0).forEach((function(e){e.dispose()})),this.materials.length=0,this.geometries.slice(0).forEach((function(e){e.dispose()})),this.geometries.length=0,this.transformNodes.slice(0).forEach((function(e){e.dispose()})),this.transformNodes.length=0,this.actionManagers.slice(0).forEach((function(e){e.dispose()})),this.actionManagers.length=0,this.textures.slice(0).forEach((function(e){e.dispose()})),this.textures.length=0,this.reflectionProbes.slice(0).forEach((function(e){e.dispose()})),this.reflectionProbes.length=0,this.morphTargetManagers.slice(0).forEach((function(e){e.dispose()})),this.morphTargetManagers.length=0,this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(var e=0,t=this.scene._serializableComponents;e<t.length;e++)t[e].removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)},t.prototype._moveAssets=function(e,t,i){if(e&&t)for(var r=0,n=e;r<n.length;r++){var o=n[r],a=!0;if(i)for(var s=0,l=i;s<l.length;s++)if(o===l[s]){a=!1;break}a&&(t.push(o),o._parentContainer=this)}},t.prototype.moveAllFromScene=function(e){for(var t in this._wasAddedToScene=!1,void 0===e&&(e=new Ba),this)Object.prototype.hasOwnProperty.call(this,t)&&(this[t]=this[t]||("_environmentTexture"===t?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()},t.prototype.createRootMesh=function(){var e=new Fa("assetContainerRootMesh",this.scene);return this.meshes.forEach((function(t){t.parent||e.addChild(t)})),this.meshes.unshift(e),e},t.prototype.mergeAnimationsTo=function(e,t,i){if(void 0===e&&(e=M.LastCreatedScene),void 0===i&&(i=null),!e)return ae.Error("No scene available to merge animations to"),[];var r=i||function(t){var i=null,r=t.animations.length?t.animations[0].targetProperty:"",n=t.name.split(".").join("").split("_primitive")[0];switch(r){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(n);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(n);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(n)}return i};this.getNodes().forEach((function(e){var t=r(e);if(null!==t){for(var i=function(e){for(var i=0,r=t.animations.filter((function(t){return t.targetProperty===e.targetProperty}));i<r.length;i++){var n=r[i],o=t.animations.indexOf(n,0);o>-1&&t.animations.splice(o,1)}},n=0,o=e.animations;n<o.length;n++)i(o[n]);t.animations=t.animations.concat(e.animations)}}));var n=[];return this.animationGroups.slice().forEach((function(e){n.push(e.clone(e.name,r)),e.animatables.forEach((function(e){e.stop()}))})),t.forEach((function(t){var i=r(t.target);i&&(e.beginAnimation(i,t.fromFrame,t.toFrame,t.loopAnimation,t.speedRatio,t.onAnimationEnd?t.onAnimationEnd:void 0,void 0,!0,void 0,t.onAnimationLoop?t.onAnimationLoop:void 0),e.stopAnimation(t.target))})),n},t.prototype.populateRootNodes=function(){var e=this;this.rootNodes.length=0,this.meshes.forEach((function(t){t.parent||-1!==e.rootNodes.indexOf(t)||e.rootNodes.push(t)})),this.transformNodes.forEach((function(t){t.parent||-1!==e.rootNodes.indexOf(t)||e.rootNodes.push(t)})),this.lights.forEach((function(t){t.parent||-1!==e.rootNodes.indexOf(t)||e.rootNodes.push(t)})),this.cameras.forEach((function(t){t.parent||-1!==e.rootNodes.indexOf(t)||e.rootNodes.push(t)}))},t.prototype.addAllAssetsToContainer=function(e){if(e){var t=[],i=new Set;for(t.push(e);t.length>0;){var r=t.pop();if(r instanceof Fa?(r.geometry&&-1===this.geometries.indexOf(r.geometry)&&this.geometries.push(r.geometry),this.meshes.push(r)):r instanceof Fo?this.transformNodes.push(r):r instanceof wa?this.lights.push(r):r instanceof $n&&this.cameras.push(r),r instanceof Uo){if(r.material&&-1===this.materials.indexOf(r.material)){this.materials.push(r.material);for(var n=0,o=r.material.getActiveTextures();n<o.length;n++){var a=o[n];-1===this.textures.indexOf(a)&&this.textures.push(a)}}r.skeleton&&-1===this.skeletons.indexOf(r.skeleton)&&this.skeletons.push(r.skeleton),r.morphTargetManager&&-1===this.morphTargetManagers.indexOf(r.morphTargetManager)&&this.morphTargetManagers.push(r.morphTargetManager)}for(var s=0,l=r.getChildren();s<l.length;s++){var c=l[s];i.has(c)||t.push(c)}i.add(r)}this.populateRootNodes()}},t}(c),ka=function(){function e(e){this.SMOOTHING=.75,this.FFT_SIZE=512,this.BARGRAPHAMPLITUDE=256,this.DEBUGCANVASPOS={x:20,y:20},this.DEBUGCANVASSIZE={width:320,height:200},(e=e||M.LastCreatedScene)&&(this._scene=e,Do.audioEngine?(this._audioEngine=Do.audioEngine,this._audioEngine.canUseWebAudio&&this._audioEngine.audioContext&&(this._webAudioAnalyser=this._audioEngine.audioContext.createAnalyser(),this._webAudioAnalyser.minDecibels=-140,this._webAudioAnalyser.maxDecibels=0,this._byteFreqs=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._byteTime=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._floatFreqs=new Float32Array(this._webAudioAnalyser.frequencyBinCount))):rr.Warn("No audio engine initialized, failed to create an audio analyser"))}return e.prototype.getFrequencyBinCount=function(){return this._audioEngine.canUseWebAudio?this._webAudioAnalyser.frequencyBinCount:0},e.prototype.getByteFrequencyData=function(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs)),this._byteFreqs},e.prototype.getByteTimeDomainData=function(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteTimeDomainData(this._byteTime)),this._byteTime},e.prototype.getFloatFrequencyData=function(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs)),this._floatFreqs},e.prototype.drawDebugCanvas=function(){var e=this;if(this._audioEngine.canUseWebAudio&&(this._debugCanvas||(this._debugCanvas=document.createElement("canvas"),this._debugCanvas.width=this.DEBUGCANVASSIZE.width,this._debugCanvas.height=this.DEBUGCANVASSIZE.height,this._debugCanvas.style.position="absolute",this._debugCanvas.style.top=this.DEBUGCANVASPOS.y+"px",this._debugCanvas.style.left=this.DEBUGCANVASPOS.x+"px",this._debugCanvasContext=this._debugCanvas.getContext("2d"),document.body.appendChild(this._debugCanvas),this._registerFunc=function(){e.drawDebugCanvas()},this._scene.registerBeforeRender(this._registerFunc)),this._registerFunc&&this._debugCanvasContext)){var t=this.getByteFrequencyData();this._debugCanvasContext.fillStyle="rgb(0, 0, 0)",this._debugCanvasContext.fillRect(0,0,this.DEBUGCANVASSIZE.width,this.DEBUGCANVASSIZE.height);for(var i=0;i<this.getFrequencyBinCount();i++){var r=t[i]/this.BARGRAPHAMPLITUDE,n=this.DEBUGCANVASSIZE.height*r,o=this.DEBUGCANVASSIZE.height-n-1,a=this.DEBUGCANVASSIZE.width/this.getFrequencyBinCount(),s=i/this.getFrequencyBinCount()*360;this._debugCanvasContext.fillStyle="hsl("+s+", 100%, 50%)",this._debugCanvasContext.fillRect(i*a,o,a,n)}}},e.prototype.stopDebugCanvas=function(){this._debugCanvas&&(this._registerFunc&&(this._scene.unregisterBeforeRender(this._registerFunc),this._registerFunc=null),document.body.removeChild(this._debugCanvas),this._debugCanvas=null,this._debugCanvasContext=null)},e.prototype.connectAudioNodes=function(e,t){this._audioEngine.canUseWebAudio&&(e.connect(this._webAudioAnalyser),this._webAudioAnalyser.connect(t))},e.prototype.dispose=function(){this._audioEngine.canUseWebAudio&&this._webAudioAnalyser.disconnect()},e}(),Ga=function(){function e(t,i,r,n,o){void 0===n&&(n=null);var a,s,l,c,u,h=this;if(this.autoplay=!1,this._loop=!1,this.useCustomAttenuation=!1,this.isPlaying=!1,this.isPaused=!1,this.refDistance=1,this.rolloffFactor=1,this.maxDistance=100,this.distanceModel="linear",this.metadata=null,this.onEndedObservable=new f,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=V.Zero(),this._localDirection=new V(1,0,0),this._volume=1,this._isReadyToPlay=!1,this._isDirectional=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._coneOuterGain=0,this._isOutputConnected=!1,this._urlType="Unknown",this.name=t,r=r||M.LastCreatedScene)if(this._scene=r,e._SceneComponentInitialization(r),this._readyToPlayCallback=n,this._customAttenuationFunction=function(e,t,i,r,n){return t<i?e*(1-t/i):0},o&&(this.autoplay=o.autoplay||!1,this._loop=o.loop||!1,void 0!==o.volume&&(this._volume=o.volume),this._spatialSound=null!==(a=o.spatialSound)&&void 0!==a&&a,this.maxDistance=null!==(s=o.maxDistance)&&void 0!==s?s:100,this.useCustomAttenuation=null!==(l=o.useCustomAttenuation)&&void 0!==l&&l,this.rolloffFactor=o.rolloffFactor||1,this.refDistance=o.refDistance||1,this.distanceModel=o.distanceModel||"linear",this._playbackRate=o.playbackRate||1,this._streaming=null!==(c=o.streaming)&&void 0!==c&&c,this._length=o.length,this._offset=o.offset),(null===(u=Do.audioEngine)||void 0===u?void 0:u.canUseWebAudio)&&Do.audioEngine.audioContext){this._soundGain=Do.audioEngine.audioContext.createGain(),this._soundGain.gain.value=this._volume,this._inputAudioNode=this._soundGain,this._outputAudioNode=this._soundGain,this._spatialSound&&this._createSpatialParameters(),this._scene.mainSoundTrack.addSound(this);var d=!0;if(i)try{"string"==typeof i?(this._urlType="String",this._url=i):i instanceof ArrayBuffer?this._urlType="ArrayBuffer":i instanceof HTMLMediaElement?this._urlType="MediaElement":i instanceof MediaStream?this._urlType="MediaStream":i instanceof AudioBuffer?this._urlType="AudioBuffer":Array.isArray(i)&&(this._urlType="Array");var p=[],_=!1;switch(this._urlType){case"MediaElement":this._streaming=!0,this._isReadyToPlay=!0,this._streamingSource=Do.audioEngine.audioContext.createMediaElementSource(i),this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback();break;case"MediaStream":this._streaming=!0,this._isReadyToPlay=!0,this._streamingSource=Do.audioEngine.audioContext.createMediaStreamSource(i),this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback();break;case"ArrayBuffer":i.byteLength>0&&(_=!0,this._soundLoaded(i));break;case"AudioBuffer":this._audioBufferLoaded(i);break;case"String":p.push(i);case"Array":0===p.length&&(p=i);for(var m=function(e){var t=p[e];if(_=o&&o.skipCodecCheck||-1!==t.indexOf(".mp3",t.length-4)&&Do.audioEngine.isMP3supported||-1!==t.indexOf(".ogg",t.length-4)&&Do.audioEngine.isOGGsupported||-1!==t.indexOf(".wav",t.length-4)||-1!==t.indexOf(".m4a",t.length-4)||-1!==t.indexOf(".mp4",t.length-4)||-1!==t.indexOf("blob:"))return g._streaming?(g._htmlAudioElement=new Audio(t),g._htmlAudioElement.controls=!1,g._htmlAudioElement.loop=g.loop,rr.SetCorsBehavior(t,g._htmlAudioElement),g._htmlAudioElement.preload="auto",g._htmlAudioElement.addEventListener("canplaythrough",(function(){h._isReadyToPlay=!0,h.autoplay&&h.play(0,h._offset,h._length),h._readyToPlayCallback&&h._readyToPlayCallback()})),document.body.appendChild(g._htmlAudioElement),g._htmlAudioElement.load()):g._scene._loadFile(t,(function(e){h._soundLoaded(e)}),void 0,!0,!0,(function(e){e&&ae.Error("XHR "+e.status+" error on: "+t+"."),ae.Error("Sound creation aborted."),h._scene.mainSoundTrack.removeSound(h)})),"break"},g=this,v=0;v<p.length&&"break"!==m(v);v++);break;default:d=!1}d?_||(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout((function(){h._readyToPlayCallback&&h._readyToPlayCallback()}),1e3)):ae.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){ae.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),Do.audioEngine&&!Do.audioEngine.WarnedWebAudioUnsupported&&(ae.Error("Web Audio is not supported by your browser."),Do.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout((function(){h._readyToPlayCallback&&h._readyToPlayCallback()}),1e3)}return Object.defineProperty(e.prototype,"loop",{get:function(){return this._loop},set:function(e){e!==this._loop&&(this._loop=e,this.updateOptions({loop:e}))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentTime",{get:function(){var e;if(this._htmlAudioElement)return this._htmlAudioElement.currentTime;if((null===(e=Do.audioEngine)||void 0===e?void 0:e.audioContext)&&(this.isPlaying||this.isPaused)){var t=this.isPaused?0:Do.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+t}return 0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"spatialSound",{get:function(){return this._spatialSound},set:function(e){if(e!=this._spatialSound){var t=this.isPlaying;this.pause(),e?(this._spatialSound=e,this._updateSpatialParameters()):this._disableSpatialSound(),t&&this.play()}},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){var e;(null===(e=Do.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&(this.isPlaying&&this.stop(),this._isReadyToPlay=!1,-1===this.soundTrackId?this._scene.mainSoundTrack.removeSound(this):this._scene.soundTracks&&this._scene.soundTracks[this.soundTrackId].removeSound(this),this._soundGain&&(this._soundGain.disconnect(),this._soundGain=null),this._soundPanner&&(this._soundPanner.disconnect(),this._soundPanner=null),this._soundSource&&(this._soundSource.disconnect(),this._soundSource=null),this._audioBuffer=null,this._htmlAudioElement&&(this._htmlAudioElement.pause(),this._htmlAudioElement.src="",document.body.removeChild(this._htmlAudioElement)),this._streamingSource&&this._streamingSource.disconnect(),this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._connectedTransformNode=null),this._clearTimeoutsAndObservers())},e.prototype.isReady=function(){return this._isReadyToPlay},e.prototype.getClassName=function(){return"Sound"},e.prototype._audioBufferLoaded=function(e){var t;(null===(t=Do.audioEngine)||void 0===t?void 0:t.audioContext)&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())},e.prototype._soundLoaded=function(e){var t,i=this;(null===(t=Do.audioEngine)||void 0===t?void 0:t.audioContext)&&Do.audioEngine.audioContext.decodeAudioData(e,(function(e){i._audioBufferLoaded(e)}),(function(e){ae.Error("Error while decoding audio data for: "+i.name+" / Error: "+e)}))},e.prototype.setAudioBuffer=function(e){var t;(null===(t=Do.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&(this._audioBuffer=e,this._isReadyToPlay=!0)},e.prototype.updateOptions=function(e){var t,i,r,n,o,a,s,l,c,u,h;e&&(this.loop=null!==(t=e.loop)&&void 0!==t?t:this.loop,this.maxDistance=null!==(i=e.maxDistance)&&void 0!==i?i:this.maxDistance,this.useCustomAttenuation=null!==(r=e.useCustomAttenuation)&&void 0!==r?r:this.useCustomAttenuation,this.rolloffFactor=null!==(n=e.rolloffFactor)&&void 0!==n?n:this.rolloffFactor,this.refDistance=null!==(o=e.refDistance)&&void 0!==o?o:this.refDistance,this.distanceModel=null!==(a=e.distanceModel)&&void 0!==a?a:this.distanceModel,this._playbackRate=null!==(s=e.playbackRate)&&void 0!==s?s:this._playbackRate,this._length=null!==(l=e.length)&&void 0!==l?l:void 0,this.spatialSound=null!==(c=e.spatialSound)&&void 0!==c?c:this._spatialSound,this._setOffset(null!==(u=e.offset)&&void 0!==u?u:void 0),this.setVolume(null!==(h=e.volume)&&void 0!==h?h:this._volume),this._updateSpatialParameters(),this.isPlaying&&(this._streaming&&this._htmlAudioElement?(this._htmlAudioElement.playbackRate=this._playbackRate,this._htmlAudioElement.loop!==this.loop&&(this._htmlAudioElement.loop=this.loop)):this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.loop!==this.loop&&(this._soundSource.loop=this.loop),void 0!==this._offset&&this._soundSource.loopStart!==this._offset&&(this._soundSource.loopStart=this._offset),void 0!==this._length&&this._length!==this._soundSource.loopEnd&&(this._soundSource.loopEnd=(0|this._offset)+this._length))))},e.prototype._createSpatialParameters=function(){var e,t;(null===(e=Do.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&Do.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=null!==(t=this._soundPanner)&&void 0!==t?t:Do.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))},e.prototype._disableSpatialSound=function(){var e;this._spatialSound&&(this._inputAudioNode=this._soundGain,null===(e=this._soundPanner)||void 0===e||e.disconnect(),this._soundPanner=null,this._spatialSound=!1)},e.prototype._updateSpatialParameters=function(){this._spatialSound&&(this._soundPanner?this.useCustomAttenuation?(this._soundPanner.distanceModel="linear",this._soundPanner.maxDistance=Number.MAX_VALUE,this._soundPanner.refDistance=1,this._soundPanner.rolloffFactor=1,this._soundPanner.panningModel=this._panningModel):(this._soundPanner.distanceModel=this.distanceModel,this._soundPanner.maxDistance=this.maxDistance,this._soundPanner.refDistance=this.refDistance,this._soundPanner.rolloffFactor=this.rolloffFactor,this._soundPanner.panningModel=this._panningModel):this._createSpatialParameters())},e.prototype.switchPanningModelToHRTF=function(){this._panningModel="HRTF",this._switchPanningModel()},e.prototype.switchPanningModelToEqualPower=function(){this._panningModel="equalpower",this._switchPanningModel()},e.prototype._switchPanningModel=function(){var e;(null===(e=Do.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)},e.prototype.connectToSoundTrackAudioNode=function(e){var t;(null===(t=Do.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)},e.prototype.setDirectionalCone=function(e,t,i){t<e?ae.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle."):(this._coneInnerAngle=e,this._coneOuterAngle=t,this._coneOuterGain=i,this._isDirectional=!0,this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length)))},Object.defineProperty(e.prototype,"directionalConeInnerAngle",{get:function(){return this._coneInnerAngle},set:function(e){var t;if(e!=this._coneInnerAngle){if(this._coneOuterAngle<e)return void ae.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneInnerAngle=e,(null===(t=Do.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle)}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"directionalConeOuterAngle",{get:function(){return this._coneOuterAngle},set:function(e){var t;if(e!=this._coneOuterAngle){if(e<this._coneInnerAngle)return void ae.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneOuterAngle=e,(null===(t=Do.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.coneOuterAngle=this._coneOuterAngle)}},enumerable:!1,configurable:!0}),e.prototype.setPosition=function(e){var t;e.equals(this._position)||(this._position.copyFrom(e),(null===(t=Do.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&!isNaN(this._position.x)&&!isNaN(this._position.y)&&!isNaN(this._position.z)&&(this._soundPanner.positionX.value=this._position.x,this._soundPanner.positionY.value=this._position.y,this._soundPanner.positionZ.value=this._position.z))},e.prototype.setLocalDirectionToMesh=function(e){var t;this._localDirection=e,(null===(t=Do.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._connectedTransformNode&&this.isPlaying&&this._updateDirection()},e.prototype._updateDirection=function(){if(this._connectedTransformNode&&this._soundPanner){var e=this._connectedTransformNode.getWorldMatrix(),t=V.TransformNormal(this._localDirection,e);t.normalize(),this._soundPanner.orientationX.value=t.x,this._soundPanner.orientationY.value=t.y,this._soundPanner.orientationZ.value=t.z}},e.prototype.updateDistanceFromListener=function(){var e;if((null===(e=Do.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&this._connectedTransformNode&&this.useCustomAttenuation&&this._soundGain&&this._scene.activeCamera){var t=this._scene.audioListenerPositionProvider?this._connectedTransformNode.position.subtract(this._scene.audioListenerPositionProvider()).length():this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera);this._soundGain.gain.value=this._customAttenuationFunction(this._volume,t,this.maxDistance,this.refDistance,this.rolloffFactor)}},e.prototype.setAttenuationFunction=function(e){this._customAttenuationFunction=e},e.prototype.play=function(e,t,i){var r,n,o,a,s=this;if(this._isReadyToPlay&&this._scene.audioEnabled&&(null===(r=Do.audioEngine)||void 0===r?void 0:r.audioContext))try{this._clearTimeoutsAndObservers();var l=e?(null===(n=Do.audioEngine)||void 0===n?void 0:n.audioContext.currentTime)+e:null===(o=Do.audioEngine)||void 0===o?void 0:o.audioContext.currentTime;if(this._soundSource&&this._streamingSource||this._spatialSound&&this._soundPanner&&(isNaN(this._position.x)||isNaN(this._position.y)||isNaN(this._position.z)||(this._soundPanner.positionX.value=this._position.x,this._soundPanner.positionY.value=this._position.y,this._soundPanner.positionZ.value=this._position.z),this._isDirectional&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle,this._soundPanner.coneOuterAngle=this._coneOuterAngle,this._soundPanner.coneOuterGain=this._coneOuterGain,this._connectedTransformNode?this._updateDirection():this._soundPanner.setOrientation(this._localDirection.x,this._localDirection.y,this._localDirection.z))),this._streaming){if(this._streamingSource||(this._streamingSource=Do.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement),this._htmlAudioElement.onended=function(){s._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){var c=function(){var e,t;if(null===(e=Do.audioEngine)||void 0===e?void 0:e.unlocked){var i=s._htmlAudioElement.play();void 0!==i&&i.catch((function(){var e,t;null===(e=Do.audioEngine)||void 0===e||e.lock(),(s.loop||s.autoplay)&&(s._audioUnlockedObserver=null===(t=Do.audioEngine)||void 0===t?void 0:t.onAudioUnlockedObservable.addOnce((function(){c()})))}))}else(s.loop||s.autoplay)&&(s._audioUnlockedObserver=null===(t=Do.audioEngine)||void 0===t?void 0:t.onAudioUnlockedObservable.addOnce((function(){c()})))};c()}}else{var u=function(){var r,n,o,a;if(null===(r=Do.audioEngine)||void 0===r?void 0:r.audioContext){if(i=i||s._length,void 0!==t&&s._setOffset(t),s._soundSource){var c=s._soundSource;c.onended=function(){c.disconnect()}}if(s._soundSource=null===(n=Do.audioEngine)||void 0===n?void 0:n.audioContext.createBufferSource(),s._soundSource&&s._inputAudioNode){s._soundSource.buffer=s._audioBuffer,s._soundSource.connect(s._inputAudioNode),s._soundSource.loop=s.loop,void 0!==t&&(s._soundSource.loopStart=t),void 0!==i&&(s._soundSource.loopEnd=(0|t)+i),s._soundSource.playbackRate.value=s._playbackRate,s._soundSource.onended=function(){s._onended()},l=e?(null===(o=Do.audioEngine)||void 0===o?void 0:o.audioContext.currentTime)+e:Do.audioEngine.audioContext.currentTime;var u=((s.isPaused?s.currentTime:0)+(null!==(a=s._offset)&&void 0!==a?a:0))%s._soundSource.buffer.duration;s._soundSource.start(l,u,s.loop?void 0:i)}}};"suspended"===(null===(a=Do.audioEngine)||void 0===a?void 0:a.audioContext.state)?this._tryToPlayTimeout=setTimeout((function(){var e;"suspended"===(null===(e=Do.audioEngine)||void 0===e?void 0:e.audioContext.state)?(Do.audioEngine.lock(),(s.loop||s.autoplay)&&(s._audioUnlockedObserver=Do.audioEngine.onAudioUnlockedObservable.addOnce((function(){u()})))):u()}),500):u()}this._startTime=l,this.isPlaying=!0,this.isPaused=!1}catch(e){ae.Error("Error while trying to play audio: "+this.name+", "+e.message)}},e.prototype._onended=function(){this.isPlaying=!1,this._startTime=0,this._currentTime=0,this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)},e.prototype.stop=function(e){var t,i=this;if(this.isPlaying)if(this._clearTimeoutsAndObservers(),this._streaming)this._htmlAudioElement?(this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if((null===(t=Do.audioEngine)||void 0===t?void 0:t.audioContext)&&this._soundSource){var r=e?Do.audioEngine.audioContext.currentTime+e:void 0;this._soundSource.onended=function(){i.isPlaying=!1,i.isPaused=!1,i._startTime=0,i._currentTime=0,i._soundSource&&(i._soundSource.onended=function(){}),i._onended()},this._soundSource.stop(r)}else this.isPlaying=!1;else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)},e.prototype.pause=function(){var e;this.isPlaying&&(this._clearTimeoutsAndObservers(),this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):(null===(e=Do.audioEngine)||void 0===e?void 0:e.audioContext)&&this._soundSource&&(this._soundSource.onended=function(){},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=Do.audioEngine.audioContext.currentTime-this._startTime))},e.prototype.setVolume=function(e,t){var i;(null===(i=Do.audioEngine)||void 0===i?void 0:i.canUseWebAudio)&&this._soundGain&&(t&&Do.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(Do.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,Do.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,Do.audioEngine.audioContext.currentTime+t)):this._soundGain.gain.value=e),this._volume=e},e.prototype.setPlaybackRate=function(e){this._playbackRate=e,this.isPlaying&&(this._streaming&&this._htmlAudioElement?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate))},e.prototype.getPlaybackRate=function(){return this._playbackRate},e.prototype.getVolume=function(){return this._volume},e.prototype.attachToMesh=function(e){var t=this;this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedTransformNode=e,this._spatialSound||(this._spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length))),this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode),this._registerFunc=function(e){return t._onRegisterAfterWorldMatrixUpdate(e)},this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc)},e.prototype.detachFromMesh=function(){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedTransformNode=null)},e.prototype._onRegisterAfterWorldMatrixUpdate=function(e){var t;if(e.getBoundingInfo){var i=e.getBoundingInfo();this.setPosition(i.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);(null===(t=Do.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._isDirectional&&this.isPlaying&&this._updateDirection()},e.prototype.clone=function(){var t=this;if(this._streaming)return null;var i=function(){t._isReadyToPlay?(n._audioBuffer=t.getAudioBuffer(),n._isReadyToPlay=!0,n.autoplay&&n.play(0,t._offset,t._length)):setTimeout(i,300)},r={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},n=new e(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,r);return this.useCustomAttenuation&&n.setAttenuationFunction(this._customAttenuationFunction),n.setPosition(this._position),n.setPlaybackRate(this._playbackRate),i(),n},e.prototype.getAudioBuffer=function(){return this._audioBuffer},e.prototype.getSoundSource=function(){return this._soundSource},e.prototype.getSoundGain=function(){return this._soundGain},e.prototype.serialize=function(){var e={name:this.name,url:this._url,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId,metadata:this.metadata};return this._spatialSound&&(this._connectedTransformNode&&(e.connectedMeshId=this._connectedTransformNode.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e},e.Parse=function(t,i,r,n){var o,a=t.name;o=t.url?r+t.url:r+a;var s,l={autoplay:t.autoplay,loop:t.loop,volume:t.volume,spatialSound:t.spatialSound,maxDistance:t.maxDistance,rolloffFactor:t.rolloffFactor,refDistance:t.refDistance,distanceModel:t.distanceModel,playbackRate:t.playbackRate};if(n){var c=function(){n._isReadyToPlay?(s._audioBuffer=n.getAudioBuffer(),s._isReadyToPlay=!0,s.autoplay&&s.play(0,s._offset,s._length)):setTimeout(c,300)};s=new e(a,new ArrayBuffer(0),i,null,l),c()}else s=new e(a,o,i,(function(){i.removePendingData(s)}),l),i.addPendingData(s);if(t.position){var u=V.FromArray(t.position);s.setPosition(u)}if(t.isDirectional&&(s.setDirectionalCone(t.coneInnerAngle||360,t.coneOuterAngle||360,t.coneOuterGain||0),t.localDirectionToMesh)){var h=V.FromArray(t.localDirectionToMesh);s.setLocalDirectionToMesh(h)}if(t.connectedMeshId){var d=i.getMeshById(t.connectedMeshId);d&&s.attachToMesh(d)}return t.metadata&&(s.metadata=t.metadata),s},e.prototype._setOffset=function(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)},e.prototype._clearTimeoutsAndObservers=function(){var e;this._tryToPlayTimeout&&(clearTimeout(this._tryToPlayTimeout),this._tryToPlayTimeout=null),this._audioUnlockedObserver&&(null===(e=Do.audioEngine)||void 0===e||e.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)},e._SceneComponentInitialization=function(e){throw He("AudioSceneComponent")},e}();a("BABYLON.Sound",Ga);var za=function(){function e(e,t){void 0===t&&(t={}),this.id=-1,this._isInitialized=!1,(e=e||M.LastCreatedScene)&&(this._scene=e,this.soundCollection=[],this._options=t,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1))}return e.prototype._initializeSoundTrackAudioGraph=function(){var e;(null===(e=Do.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&Do.audioEngine.audioContext&&(this._outputAudioNode=Do.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(Do.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)},e.prototype.dispose=function(){if(Do.audioEngine&&Do.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}},e.prototype.addSound=function(e){var t;this._isInitialized||this._initializeSoundTrackAudioGraph(),(null===(t=Do.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),void 0!==e.soundTrackId&&(-1===e.soundTrackId?this._scene.mainSoundTrack.removeSound(e):this._scene.soundTracks&&this._scene.soundTracks[e.soundTrackId].removeSound(e)),this.soundCollection.push(e),e.soundTrackId=this.id},e.prototype.removeSound=function(e){var t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)},e.prototype.setVolume=function(e){var t;(null===(t=Do.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)},e.prototype.switchPanningModelToHRTF=function(){var e;if(null===(e=Do.audioEngine)||void 0===e?void 0:e.canUseWebAudio)for(var t=0;t<this.soundCollection.length;t++)this.soundCollection[t].switchPanningModelToHRTF()},e.prototype.switchPanningModelToEqualPower=function(){var e;if(null===(e=Do.audioEngine)||void 0===e?void 0:e.canUseWebAudio)for(var t=0;t<this.soundCollection.length;t++)this.soundCollection[t].switchPanningModelToEqualPower()},e.prototype.connectToAnalyser=function(e){var t;this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser=e,(null===(t=Do.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._outputAudioNode.disconnect(),this._connectedAnalyser.connectAudioNodes(this._outputAudioNode,Do.audioEngine.masterGain))},e}();c.AddParser(Vr.NAME_AUDIO,(function(e,t,i,r){var n,o,a=[];if(i.sounds=i.sounds||[],void 0!==e.sounds&&null!==e.sounds)for(var s=0,l=e.sounds.length;s<l;s++){var c=e.sounds[s];(null===(n=Do.audioEngine)||void 0===n?void 0:n.canUseWebAudio)?(c.url||(c.url=c.name),a[c.url]?i.sounds.push(Ga.Parse(c,t,r,a[c.url])):(o=Ga.Parse(c,t,r),a[c.url]=o,i.sounds.push(o))):i.sounds.push(new Ga(c.name,null,t))}a=[]})),Object.defineProperty(pn.prototype,"mainSoundTrack",{get:function(){var e=this._getComponent(Vr.NAME_AUDIO);return e||(e=new Wa(this),this._addComponent(e)),this._mainSoundTrack||(this._mainSoundTrack=new za(this,{mainTrack:!0})),this._mainSoundTrack},enumerable:!0,configurable:!0}),pn.prototype.getSoundByName=function(e){var t;for(t=0;t<this.mainSoundTrack.soundCollection.length;t++)if(this.mainSoundTrack.soundCollection[t].name===e)return this.mainSoundTrack.soundCollection[t];if(this.soundTracks)for(var i=0;i<this.soundTracks.length;i++)for(t=0;t<this.soundTracks[i].soundCollection.length;t++)if(this.soundTracks[i].soundCollection[t].name===e)return this.soundTracks[i].soundCollection[t];return null},Object.defineProperty(pn.prototype,"audioEnabled",{get:function(){var e=this._getComponent(Vr.NAME_AUDIO);return e||(e=new Wa(this),this._addComponent(e)),e.audioEnabled},set:function(e){var t=this._getComponent(Vr.NAME_AUDIO);t||(t=new Wa(this),this._addComponent(t)),e?t.enableAudio():t.disableAudio()},enumerable:!0,configurable:!0}),Object.defineProperty(pn.prototype,"headphone",{get:function(){var e=this._getComponent(Vr.NAME_AUDIO);return e||(e=new Wa(this),this._addComponent(e)),e.headphone},set:function(e){var t=this._getComponent(Vr.NAME_AUDIO);t||(t=new Wa(this),this._addComponent(t)),e?t.switchAudioModeForHeadphones():t.switchAudioModeForNormalSpeakers()},enumerable:!0,configurable:!0}),Object.defineProperty(pn.prototype,"audioListenerPositionProvider",{get:function(){var e=this._getComponent(Vr.NAME_AUDIO);return e||(e=new Wa(this),this._addComponent(e)),e.audioListenerPositionProvider},set:function(e){var t=this._getComponent(Vr.NAME_AUDIO);if(t||(t=new Wa(this),this._addComponent(t)),e&&"function"!=typeof e)throw new Error("The value passed to [Scene.audioListenerPositionProvider] must be a function that returns a Vector3");t.audioListenerPositionProvider=e},enumerable:!0,configurable:!0}),Object.defineProperty(pn.prototype,"audioListenerRotationProvider",{get:function(){var e=this._getComponent(Vr.NAME_AUDIO);return e||(e=new Wa(this),this._addComponent(e)),e.audioListenerRotationProvider},set:function(e){var t=this._getComponent(Vr.NAME_AUDIO);if(t||(t=new Wa(this),this._addComponent(t)),e&&"function"!=typeof e)throw new Error("The value passed to [Scene.audioListenerRotationProvider] must be a function that returns a Vector3");t.audioListenerRotationProvider=e},enumerable:!0,configurable:!0}),Object.defineProperty(pn.prototype,"audioPositioningRefreshRate",{get:function(){var e=this._getComponent(Vr.NAME_AUDIO);return e||(e=new Wa(this),this._addComponent(e)),e.audioPositioningRefreshRate},set:function(e){var t=this._getComponent(Vr.NAME_AUDIO);t||(t=new Wa(this),this._addComponent(t)),t.audioPositioningRefreshRate=e},enumerable:!0,configurable:!0});var Wa=function(){function e(e){this.name=Vr.NAME_AUDIO,this._audioEnabled=!0,this._headphone=!1,this.audioPositioningRefreshRate=500,this.audioListenerPositionProvider=null,this.audioListenerRotationProvider=null,this._cachedCameraDirection=new V,this._cachedCameraPosition=new V,this._lastCheck=0,this._invertMatrixTemp=new z,this._cameraDirectionTemp=new V,(e=e||M.LastCreatedScene)&&(this.scene=e,e.soundTracks=[],e.sounds=[])}return Object.defineProperty(e.prototype,"audioEnabled",{get:function(){return this._audioEnabled},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"headphone",{get:function(){return this._headphone},enumerable:!1,configurable:!0}),e.prototype.register=function(){this.scene._afterRenderStage.registerStep(Vr.STEP_AFTERRENDER_AUDIO,this,this._afterRender)},e.prototype.rebuild=function(){},e.prototype.serialize=function(e){if(e.sounds=[],this.scene.soundTracks)for(var t=0;t<this.scene.soundTracks.length;t++)for(var i=this.scene.soundTracks[t],r=0;r<i.soundCollection.length;r++)e.sounds.push(i.soundCollection[r].serialize())},e.prototype.addFromContainer=function(e){var t=this;e.sounds&&e.sounds.forEach((function(e){e.play(),e.autoplay=!0,t.scene.mainSoundTrack.addSound(e)}))},e.prototype.removeFromContainer=function(e,t){var i=this;void 0===t&&(t=!1),e.sounds&&e.sounds.forEach((function(e){e.stop(),e.autoplay=!1,i.scene.mainSoundTrack.removeSound(e),t&&e.dispose()}))},e.prototype.dispose=function(){var e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(var t=0;t<e.soundTracks.length;t++)e.soundTracks[t].dispose()},e.prototype.disableAudio=function(){var e,t=this.scene;for(this._audioEnabled=!1,Do.audioEngine&&Do.audioEngine.audioContext&&Do.audioEngine.audioContext.suspend(),e=0;e<t.mainSoundTrack.soundCollection.length;e++)t.mainSoundTrack.soundCollection[e].pause();if(t.soundTracks)for(e=0;e<t.soundTracks.length;e++)for(var i=0;i<t.soundTracks[e].soundCollection.length;i++)t.soundTracks[e].soundCollection[i].pause()},e.prototype.enableAudio=function(){var e,t=this.scene;for(this._audioEnabled=!0,Do.audioEngine&&Do.audioEngine.audioContext&&Do.audioEngine.audioContext.resume(),e=0;e<t.mainSoundTrack.soundCollection.length;e++)t.mainSoundTrack.soundCollection[e].isPaused&&t.mainSoundTrack.soundCollection[e].play();if(t.soundTracks)for(e=0;e<t.soundTracks.length;e++)for(var i=0;i<t.soundTracks[e].soundCollection.length;i++)t.soundTracks[e].soundCollection[i].isPaused&&t.soundTracks[e].soundCollection[i].play()},e.prototype.switchAudioModeForHeadphones=function(){var e=this.scene;if(this._headphone=!0,e.mainSoundTrack.switchPanningModelToHRTF(),e.soundTracks)for(var t=0;t<e.soundTracks.length;t++)e.soundTracks[t].switchPanningModelToHRTF()},e.prototype.switchAudioModeForNormalSpeakers=function(){var e=this.scene;if(this._headphone=!1,e.mainSoundTrack.switchPanningModelToEqualPower(),e.soundTracks)for(var t=0;t<e.soundTracks.length;t++)e.soundTracks[t].switchPanningModelToEqualPower()},e.prototype._afterRender=function(){var t=_t.Now;if(!(this._lastCheck&&t-this._lastCheck<this.audioPositioningRefreshRate)){this._lastCheck=t;var i=this.scene;if(this._audioEnabled&&i._mainSoundTrack&&i.soundTracks&&(0!==i._mainSoundTrack.soundCollection.length||1!==i.soundTracks.length)){var r=Do.audioEngine;if(r&&r.audioContext){var n=i.activeCamera;if(i.activeCameras&&i.activeCameras.length>0&&(n=i.activeCameras[0]),this.audioListenerPositionProvider){var o=this.audioListenerPositionProvider();r.audioContext.listener.setPosition(o.x||0,o.y||0,o.z||0)}else n?this._cachedCameraPosition.equals(n.globalPosition)||(this._cachedCameraPosition.copyFrom(n.globalPosition),r.audioContext.listener.setPosition(n.globalPosition.x,n.globalPosition.y,n.globalPosition.z)):r.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){var a=this.audioListenerRotationProvider();r.audioContext.listener.setOrientation(a.x||0,a.y||0,a.z||0,0,1,0)}else n?(n.rigCameras&&n.rigCameras.length>0&&(n=n.rigCameras[0]),n.getViewMatrix().invertToRef(this._invertMatrixTemp),V.TransformNormalToRef(e._CameraDirection,this._invertMatrixTemp,this._cameraDirectionTemp),this._cameraDirectionTemp.normalize(),isNaN(this._cameraDirectionTemp.x)||isNaN(this._cameraDirectionTemp.y)||isNaN(this._cameraDirectionTemp.z)||this._cachedCameraDirection.equals(this._cameraDirectionTemp)||(this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp),r.audioContext.listener.setOrientation(this._cameraDirectionTemp.x,this._cameraDirectionTemp.y,this._cameraDirectionTemp.z,0,1,0))):r.audioContext.listener.setOrientation(0,0,0,0,1,0);var s=void 0;for(s=0;s<i.mainSoundTrack.soundCollection.length;s++)(c=i.mainSoundTrack.soundCollection[s]).useCustomAttenuation&&c.updateDistanceFromListener();if(i.soundTracks)for(s=0;s<i.soundTracks.length;s++)for(var l=0;l<i.soundTracks[s].soundCollection.length;l++){var c;(c=i.soundTracks[s].soundCollection[l]).useCustomAttenuation&&c.updateDistanceFromListener()}}}}},e._CameraDirection=new V(0,0,-1),e}();Ga._SceneComponentInitialization=function(e){var t=e._getComponent(Vr.NAME_AUDIO);t||(t=new Wa(e),e._addComponent(t))};var Ha=function(){function e(e,t,i){var r=this;if(this.loop=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._volume=1,this.isPlaying=!1,this.isPaused=!1,this._sounds=[],this._weights=[],t.length!==i.length)throw new Error("Sounds length does not equal weights length");this.loop=e,this._weights=i;for(var n=0,o=0,a=i;o<a.length;o++)n+=a[o];for(var s=n>0?1/n:0,l=0;l<this._weights.length;l++)this._weights[l]*=s;this._sounds=t;for(var c=0,u=this._sounds;c<u.length;c++)u[c].onEndedObservable.add((function(){r._onended()}))}return Object.defineProperty(e.prototype,"directionalConeInnerAngle",{get:function(){return this._coneInnerAngle},set:function(e){if(e!==this._coneInnerAngle){if(this._coneOuterAngle<e)return void ae.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneInnerAngle=e;for(var t=0,i=this._sounds;t<i.length;t++)i[t].directionalConeInnerAngle=e}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"directionalConeOuterAngle",{get:function(){return this._coneOuterAngle},set:function(e){if(e!==this._coneOuterAngle){if(e<this._coneInnerAngle)return void ae.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneOuterAngle=e;for(var t=0,i=this._sounds;t<i.length;t++)i[t].directionalConeOuterAngle=e}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"volume",{get:function(){return this._volume},set:function(e){if(e!==this._volume)for(var t=0,i=this._sounds;t<i.length;t++)i[t].setVolume(e)},enumerable:!1,configurable:!0}),e.prototype._onended=function(){void 0!==this._currentIndex&&(this._sounds[this._currentIndex].autoplay=!1),this.loop&&this.isPlaying?this.play():this.isPlaying=!1},e.prototype.pause=function(){this.isPaused=!0,void 0!==this._currentIndex&&this._sounds[this._currentIndex].pause()},e.prototype.stop=function(){this.isPlaying=!1,void 0!==this._currentIndex&&this._sounds[this._currentIndex].stop()},e.prototype.play=function(e){if(!this.isPaused){this.stop();for(var t=Math.random(),i=0,r=0;r<this._weights.length;r++)if(t<=(i+=this._weights[r])){this._currentIndex=r;break}}var n=this._sounds[this._currentIndex];n.isReady()?n.play(0,this.isPaused?void 0:e):n.autoplay=!0,this.isPlaying=!0,this.isPaused=!1},e}(),Xa=function(){function e(e){this._texture=null,this._isEnabled=!0,this.isEnabled=!0,this.time=0,(e=e||M.LastCreatedScene)&&(this._scene=e,this.animationParameters=new k(0,0,0,30))}return e.prototype._markSubMeshesAsAttributesDirty=function(){for(var e=0,t=this._scene.meshes;e<t.length;e++){var i=t[e];i.bakedVertexAnimationManager===this&&i._markSubMeshesAsAttributesDirty()}},e.prototype.bind=function(e,t){if(void 0===t&&(t=!1),this._texture&&this._isEnabled){var i=this._texture.getSize();e.setFloat2("bakedVertexAnimationTextureSizeInverted",1/i.width,1/i.height),e.setFloat("bakedVertexAnimationTime",this.time),t||e.setVector4("bakedVertexAnimationSettings",this.animationParameters),e.setTexture("bakedVertexAnimationTexture",this._texture)}},e.prototype.clone=function(){var t=new e(this._scene);return this.copyTo(t),t},e.prototype.setAnimationParameters=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=30),this.animationParameters=new k(e,t,i,r)},e.prototype.dispose=function(e){var t;e&&(null===(t=this._texture)||void 0===t||t.dispose())},e.prototype.getClassName=function(){return"BakedVertexAnimationManager"},e.prototype.copyTo=function(e){Ke.Clone((function(){return e}),this)},e.prototype.serialize=function(){return Ke.Serialize(this)},e.prototype.parse=function(e,t,i){var r=this;Ke.Parse((function(){return r}),e,t,i)},v([Me(),Pe("_markSubMeshesAsAttributesDirty")],e.prototype,"texture",void 0),v([Ie(),Pe("_markSubMeshesAsAttributesDirty")],e.prototype,"isEnabled",void 0),v([Ie()],e.prototype,"animationParameters",void 0),v([Ie()],e.prototype,"time",void 0),e}(),ja=function(){function e(t){this._wrapU=u.TEXTURE_WRAP_ADDRESSMODE,this._wrapV=u.TEXTURE_WRAP_ADDRESSMODE,this.wrapR=u.TEXTURE_WRAP_ADDRESSMODE,this.anisotropicFilteringLevel=4,this.delayLoadState=u.DELAYLOADSTATE_NONE,this._texture=null,this._engine=null,this._cachedSize=Ze.Zero(),this._cachedBaseSize=Ze.Zero(),this._initialSamplingMode=u.TEXTURE_BILINEAR_SAMPLINGMODE,this._texture=e._IsRenderTargetWrapper(t)?t.texture:t,this._texture&&(this._engine=this._texture.getEngine())}return Object.defineProperty(e.prototype,"wrapU",{get:function(){return this._wrapU},set:function(e){this._wrapU=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"wrapV",{get:function(){return this._wrapV},set:function(e){this._wrapV=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"coordinatesMode",{get:function(){return 0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isCube",{get:function(){return!!this._texture&&this._texture.isCube},set:function(e){this._texture&&(this._texture.isCube=e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"is3D",{get:function(){return!!this._texture&&this._texture.is3D},set:function(e){this._texture&&(this._texture.is3D=e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"is2DArray",{get:function(){return!!this._texture&&this._texture.is2DArray},set:function(e){this._texture&&(this._texture.is2DArray=e)},enumerable:!1,configurable:!0}),e.prototype.getClassName=function(){return"ThinTexture"},e._IsRenderTargetWrapper=function(e){return void 0!==(null==e?void 0:e.shareDepth)},e.prototype.isReady=function(){return this.delayLoadState===u.DELAYLOADSTATE_NOTLOADED?(this.delayLoad(),!1):!!this._texture&&this._texture.isReady},e.prototype.delayLoad=function(){},e.prototype.getInternalTexture=function(){return this._texture},e.prototype.getSize=function(){if(this._texture){if(this._texture.width)return this._cachedSize.width=this._texture.width,this._cachedSize.height=this._texture.height,this._cachedSize;if(this._texture._size)return this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size,this._cachedSize}return this._cachedSize},e.prototype.getBaseSize=function(){return this.isReady()&&this._texture?this._texture._size?(this._cachedBaseSize.width=this._texture._size,this._cachedBaseSize.height=this._texture._size,this._cachedBaseSize):(this._cachedBaseSize.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight,this._cachedBaseSize):(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,this._cachedBaseSize)},Object.defineProperty(e.prototype,"samplingMode",{get:function(){return this._texture?this._texture.samplingMode:this._initialSamplingMode},enumerable:!1,configurable:!0}),e.prototype.updateSamplingMode=function(e){this._texture&&this._engine&&this._engine.updateTextureSamplingMode(e,this._texture)},e.prototype.releaseInternalTexture=function(){this._texture&&(this._texture.dispose(),this._texture=null)},e.prototype.dispose=function(){this._texture&&(this.releaseInternalTexture(),this._engine=null)},e}(),Ya=function(e){function t(i,r){void 0===r&&(r=null);var n=e.call(this,null)||this;return n.metadata=null,n.reservedDataStore=null,n._hasAlpha=!1,n._getAlphaFromRGB=!1,n.level=1,n._coordinatesIndex=0,n.optimizeUVAllocation=!0,n._coordinatesMode=u.TEXTURE_EXPLICIT_MODE,n.wrapR=u.TEXTURE_WRAP_ADDRESSMODE,n.anisotropicFilteringLevel=t.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,n._isCube=!1,n._gammaSpace=!0,n.invertZ=!1,n.lodLevelInAlpha=!1,n.isRenderTarget=!1,n._prefiltered=!1,n._forceSerialize=!1,n.animations=[],n.onDisposeObservable=new f,n._onDisposeObserver=null,n._scene=null,n._uid=null,n._parentContainer=null,n._loadingError=!1,i?t._IsScene(i)?n._scene=i:n._engine=i:n._scene=M.LastCreatedScene,n._scene&&(n.uniqueId=n._scene.getUniqueId(),n._scene.addTexture(n),n._engine=n._scene.getEngine()),n._texture=r,n._uid=null,n}return m(t,e),Object.defineProperty(t.prototype,"hasAlpha",{get:function(){return this._hasAlpha},set:function(e){var t=this;this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(e){return e.hasTexture(t)})))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"getAlphaFromRGB",{get:function(){return this._getAlphaFromRGB},set:function(e){var t=this;this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(e){return e.hasTexture(t)})))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"coordinatesIndex",{get:function(){return this._coordinatesIndex},set:function(e){var t=this;this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(e){return e.hasTexture(t)})))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"coordinatesMode",{get:function(){return this._coordinatesMode},set:function(e){var t=this;this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(e){return e.hasTexture(t)})))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"wrapU",{get:function(){return this._wrapU},set:function(e){this._wrapU=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"wrapV",{get:function(){return this._wrapV},set:function(e){this._wrapV=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isCube",{get:function(){return this._texture?this._texture.isCube:this._isCube},set:function(e){this._texture?this._texture.isCube=e:this._isCube=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"is3D",{get:function(){return!!this._texture&&this._texture.is3D},set:function(e){this._texture&&(this._texture.is3D=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"is2DArray",{get:function(){return!!this._texture&&this._texture.is2DArray},set:function(e){this._texture&&(this._texture.is2DArray=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"gammaSpace",{get:function(){return this._texture?(null===this._texture._gammaSpace&&(this._texture._gammaSpace=this._gammaSpace),this._texture._gammaSpace&&!this._texture._useSRGBBuffer):this._gammaSpace},set:function(e){var t,i=this;if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(e){return e.hasTexture(i)}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isRGBD",{get:function(){return null!=this._texture&&this._texture._isRGBD},set:function(e){var t,i=this;e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(e){return e.hasTexture(i)})))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"noMipmap",{get:function(){return!1},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"lodGenerationOffset",{get:function(){return this._texture?this._texture._lodGenerationOffset:0},set:function(e){this._texture&&(this._texture._lodGenerationOffset=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"lodGenerationScale",{get:function(){return this._texture?this._texture._lodGenerationScale:0},set:function(e){this._texture&&(this._texture._lodGenerationScale=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"linearSpecularLOD",{get:function(){return!!this._texture&&this._texture._linearSpecularLOD},set:function(e){this._texture&&(this._texture._linearSpecularLOD=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"irradianceTexture",{get:function(){return this._texture?this._texture._irradianceTexture:null},set:function(e){this._texture&&(this._texture._irradianceTexture=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"uid",{get:function(){return this._uid||(this._uid=Qi()),this._uid},enumerable:!1,configurable:!0}),t.prototype.toString=function(){return this.name},t.prototype.getClassName=function(){return"BaseTexture"},Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isBlocking",{get:function(){return!0},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"loadingError",{get:function(){return this._loadingError},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"errorObject",{get:function(){return this._errorObject},enumerable:!1,configurable:!0}),t.prototype.getScene=function(){return this._scene},t.prototype._getEngine=function(){return this._engine},t.prototype.getTextureMatrix=function(){return z.IdentityReadOnly},t.prototype.getReflectionTextureMatrix=function(){return z.IdentityReadOnly},t.prototype.getRefractionTextureMatrix=function(){return this.getReflectionTextureMatrix()},t.prototype.isReadyOrNotBlocking=function(){return!this.isBlocking||this.isReady()||this.loadingError},t.prototype.scale=function(e){},Object.defineProperty(t.prototype,"canRescale",{get:function(){return!1},enumerable:!1,configurable:!0}),t.prototype._getFromCache=function(e,t,i,r,n,o){var a=this._getEngine();if(!a)return null;for(var s=a._getUseSRGBBuffer(!!n,t),l=a.getLoadedTexturesCache(),c=0;c<l.length;c++){var u=l[c];if(!(void 0!==n&&s!==u._useSRGBBuffer||void 0!==r&&r!==u.invertY||u.url!==e||u.generateMipMaps!==!t||i&&i!==u.samplingMode||void 0!==o&&o!==u.isCube))return u.incrementReferences(),u}return null},t.prototype._rebuild=function(e){void 0===e&&(e=!1)},t.prototype.clone=function(){return null},Object.defineProperty(t.prototype,"textureType",{get:function(){return this._texture&&void 0!==this._texture.type?this._texture.type:u.TEXTURETYPE_UNSIGNED_INT},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"textureFormat",{get:function(){return this._texture&&void 0!==this._texture.format?this._texture.format:u.TEXTUREFORMAT_RGBA},enumerable:!1,configurable:!0}),t.prototype._markAllSubMeshesAsTexturesDirty=function(){var e=this.getScene();e&&e.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag)},t.prototype.readPixels=function(e,t,i,r,n,o,a,s,l){if(void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=null),void 0===r&&(r=!0),void 0===n&&(n=!1),void 0===o&&(o=0),void 0===a&&(a=0),void 0===s&&(s=Number.MAX_VALUE),void 0===l&&(l=Number.MAX_VALUE),!this._texture)return null;var c=this._getEngine();if(!c)return null;var u=this.getSize(),h=u.width,d=u.height;0!==t&&(h/=Math.pow(2,t),d/=Math.pow(2,t),h=Math.round(h),d=Math.round(d)),s=Math.min(h,s),l=Math.min(d,l);try{return this._texture.isCube?c._readTexturePixels(this._texture,s,l,e,t,i,r,n,o,a):c._readTexturePixels(this._texture,s,l,-1,t,i,r,n,o,a)}catch(e){return null}},t.prototype._readPixelsSync=function(e,t,i,r,n){if(void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=null),void 0===r&&(r=!0),void 0===n&&(n=!1),!this._texture)return null;var o=this.getSize(),a=o.width,s=o.height,l=this._getEngine();if(!l)return null;0!=t&&(a/=Math.pow(2,t),s/=Math.pow(2,t),a=Math.round(a),s=Math.round(s));try{return this._texture.isCube?l._readTexturePixelsSync(this._texture,a,s,e,t,i,r,n):l._readTexturePixelsSync(this._texture,a,s,-1,t,i,r,n)}catch(e){return null}},Object.defineProperty(t.prototype,"_lodTextureHigh",{get:function(){return this._texture?this._texture._lodTextureHigh:null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_lodTextureMid",{get:function(){return this._texture?this._texture._lodTextureMid:null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_lodTextureLow",{get:function(){return this._texture?this._texture._lodTextureLow:null},enumerable:!1,configurable:!0}),t.prototype.dispose=function(){if(this._scene){this._scene.stopAnimation&&this._scene.stopAnimation(this),this._scene.removePendingData(this);var t=this._scene.textures.indexOf(this);if(t>=0&&this._scene.textures.splice(t,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){var i=this._parentContainer.textures.indexOf(this);i>-1&&this._parentContainer.textures.splice(i,1),this._parentContainer=null}}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null,e.prototype.dispose.call(this)},t.prototype.serialize=function(e){if(void 0===e&&(e=!1),!this.name&&!e)return null;var t=Ke.Serialize(this);return Ke.AppendSerializedAnimations(this,t),t},t.WhenAllReady=function(e,t){var i=e.length;if(0!==i)for(var r=0;r<e.length;r++){var n=e[r];if(n.isReady())0==--i&&t();else{var o=n.onLoadObservable;o?o.addOnce((function(){0==--i&&t()})):0==--i&&t()}}else t()},t._IsScene=function(e){return"Scene"===e.getClassName()},t.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,v([Ie()],t.prototype,"uniqueId",void 0),v([Ie()],t.prototype,"name",void 0),v([Ie()],t.prototype,"metadata",void 0),v([Ie("hasAlpha")],t.prototype,"_hasAlpha",void 0),v([Ie("getAlphaFromRGB")],t.prototype,"_getAlphaFromRGB",void 0),v([Ie()],t.prototype,"level",void 0),v([Ie("coordinatesIndex")],t.prototype,"_coordinatesIndex",void 0),v([Ie()],t.prototype,"optimizeUVAllocation",void 0),v([Ie("coordinatesMode")],t.prototype,"_coordinatesMode",void 0),v([Ie()],t.prototype,"wrapU",null),v([Ie()],t.prototype,"wrapV",null),v([Ie()],t.prototype,"wrapR",void 0),v([Ie()],t.prototype,"anisotropicFilteringLevel",void 0),v([Ie()],t.prototype,"isCube",null),v([Ie()],t.prototype,"is3D",null),v([Ie()],t.prototype,"is2DArray",null),v([Ie()],t.prototype,"gammaSpace",null),v([Ie()],t.prototype,"invertZ",void 0),v([Ie()],t.prototype,"lodLevelInAlpha",void 0),v([Ie()],t.prototype,"lodGenerationOffset",null),v([Ie()],t.prototype,"lodGenerationScale",null),v([Ie()],t.prototype,"linearSpecularLOD",null),v([Me()],t.prototype,"irradianceTexture",null),v([Ie()],t.prototype,"isRenderTarget",void 0),t}(ja);function Ka(e,t,i){void 0===i&&(i=!1);var r=t.width,n=t.height;if(e instanceof Float32Array){for(var o=e.byteLength/e.BYTES_PER_ELEMENT,a=new Uint8Array(o);--o>=0;){var s=e[o];s<0?s=0:s>1&&(s=1),a[o]=255*s}e=a}var l=document.createElement("canvas");l.width=r,l.height=n;var c=l.getContext("2d");if(!c)return null;var u=c.createImageData(r,n);if(u.data.set(e),c.putImageData(u,0,0),i){var h=document.createElement("canvas");h.width=r,h.height=n;var d=h.getContext("2d");return d?(d.translate(0,n),d.scale(1,-1),d.drawImage(l,0,0),h.toDataURL("image/png")):null}return l.toDataURL("image/png")}function Qa(e,t,i){void 0===t&&(t=0),void 0===i&&(i=0);var r=e.getInternalTexture();if(!r)return null;var n=e._readPixelsSync(t,i);return n?Ka(n,e.getSize(),r.invertY):null}function qa(e,t,i){return void 0===t&&(t=0),void 0===i&&(i=0),y(this,void 0,void 0,(function(){var r,n;return b(this,(function(o){switch(o.label){case 0:return(r=e.getInternalTexture())?[4,e.readPixels(t,i)]:[2,null];case 1:return(n=o.sent())?[2,Ka(n,e.getSize(),r.invertY)]:[2,null]}}))}))}var Za={GenerateBase64StringFromPixelData:Ka,GenerateBase64StringFromTexture:Qa,GenerateBase64StringFromTextureAsync:qa},Ja=function(e){function t(i,r,n,o,a,s,l,c,h,d,p,_,m,g){void 0===a&&(a=t.TRILINEAR_SAMPLINGMODE),void 0===s&&(s=null),void 0===l&&(l=null),void 0===c&&(c=null),void 0===h&&(h=!1);var v,y,b,T,E,S,x,A,C,R,P,I=this;(I=e.call(this,r)||this).url=null,I.uOffset=0,I.vOffset=0,I.uScale=1,I.vScale=1,I.uAng=0,I.vAng=0,I.wAng=0,I.uRotationCenter=.5,I.vRotationCenter=.5,I.wRotationCenter=.5,I.homogeneousRotationInUVTransform=!1,I.inspectableCustomProperties=null,I._noMipmap=!1,I._invertY=!1,I._rowGenerationMatrix=null,I._cachedTextureMatrix=null,I._projectionModeMatrix=null,I._t0=null,I._t1=null,I._t2=null,I._cachedUOffset=-1,I._cachedVOffset=-1,I._cachedUScale=0,I._cachedVScale=0,I._cachedUAng=-1,I._cachedVAng=-1,I._cachedWAng=-1,I._cachedReflectionProjectionMatrixId=-1,I._cachedURotationCenter=-1,I._cachedVRotationCenter=-1,I._cachedWRotationCenter=-1,I._cachedHomogeneousRotationInUVTransform=!1,I._cachedIdentity3x2=!0,I._cachedReflectionTextureMatrix=null,I._cachedReflectionUOffset=-1,I._cachedReflectionVOffset=-1,I._cachedReflectionUScale=0,I._cachedReflectionVScale=0,I._cachedReflectionCoordinatesMode=-1,I._buffer=null,I._deleteBuffer=!1,I._format=null,I._delayedOnLoad=null,I._delayedOnError=null,I.onLoadObservable=new f,I._isBlocking=!0,I.name=i||"",I.url=i;var M=!1,O=null,D=!0;"object"==typeof n&&null!==n?(P=null!==(v=n.noMipmap)&&void 0!==v&&v,o=null!==(y=n.invertY)&&void 0!==y?y:!go.UseOpenGLOrientationForUV,a=null!==(b=n.samplingMode)&&void 0!==b?b:t.TRILINEAR_SAMPLINGMODE,s=null!==(T=n.onLoad)&&void 0!==T?T:null,l=null!==(E=n.onError)&&void 0!==E?E:null,c=null!==(S=n.buffer)&&void 0!==S?S:null,h=null!==(x=n.deleteBuffer)&&void 0!==x&&x,d=n.format,p=n.mimeType,_=n.loaderOptions,m=n.creationFlags,M=null!==(A=n.useSRGBBuffer)&&void 0!==A&&A,O=null!==(C=n.internalTexture)&&void 0!==C?C:null,D=null!==(R=n.gammaSpace)&&void 0!==R?R:D):P=!!n,I._gammaSpace=D,I._noMipmap=P,I._invertY=void 0===o?!go.UseOpenGLOrientationForUV:o,I._initialSamplingMode=a,I._buffer=c,I._deleteBuffer=h,I._mimeType=p,I._loaderOptions=_,I._creationFlags=m,I._useSRGBBuffer=M,I._forcedExtension=g,d&&(I._format=d);var N=I.getScene(),F=I._getEngine();if(!F)return I;F.onBeforeTextureInitObservable.notifyObservers(I);var L=function(){I._texture&&(I._texture._invertVScale&&(I.vScale*=-1,I.vOffset+=1),null!==I._texture._cachedWrapU&&(I.wrapU=I._texture._cachedWrapU,I._texture._cachedWrapU=null),null!==I._texture._cachedWrapV&&(I.wrapV=I._texture._cachedWrapV,I._texture._cachedWrapV=null),null!==I._texture._cachedWrapR&&(I.wrapR=I._texture._cachedWrapR,I._texture._cachedWrapR=null)),I.onLoadObservable.hasObservers()&&I.onLoadObservable.notifyObservers(I),s&&s(),!I.isBlocking&&N&&N.resetCachedMaterial()},w=function(e,i){I._loadingError=!0,I._errorObject={message:e,exception:i},l&&l(e,i),t.OnTextureLoadErrorObservable.notifyObservers(I)};if(!I.url&&!O)return I._delayedOnLoad=L,I._delayedOnError=w,I;if(I._texture=null!=O?O:I._getFromCache(I.url,P,a,I._invertY,M,I.isCube),I._texture)if(I._texture.isReady)si.SetImmediate((function(){return L()}));else{var B=I._texture.onLoadedObservable.add(L);I._texture.onErrorObservable.add((function(e){var t;w(e.message,e.exception),null===(t=I._texture)||void 0===t||t.onLoadedObservable.remove(B)}))}else if(N&&N.useDelayedTextureLoading)I.delayLoadState=u.DELAYLOADSTATE_NOTLOADED,I._delayedOnLoad=L,I._delayedOnError=w;else{try{I._texture=F.createTexture(I.url,P,I._invertY,N,a,L,w,I._buffer,void 0,I._format,I._forcedExtension,p,_,m,M)}catch(e){throw w("error loading",e),e}h&&(I._buffer=null)}return I}return m(t,e),t._CreateVideoTexture=function(e,i,r,n,o,a,s,l,c){throw void 0===n&&(n=!1),void 0===o&&(o=!1),void 0===a&&(a=t.TRILINEAR_SAMPLINGMODE),void 0===s&&(s={}),void 0===c&&(c=u.TEXTUREFORMAT_RGBA),He("VideoTexture")},Object.defineProperty(t.prototype,"noMipmap",{get:function(){return this._noMipmap},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"mimeType",{get:function(){return this._mimeType},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isBlocking",{get:function(){return this._isBlocking},set:function(e){this._isBlocking=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"invertY",{get:function(){return this._invertY},enumerable:!1,configurable:!0}),t.prototype.updateURL=function(e,t,i,r){var n=this;void 0===t&&(t=null),this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(e){return e.hasTexture(n)}))),this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=r,this.delayLoadState=u.DELAYLOADSTATE_NOTLOADED,i&&(this._delayedOnLoad=i),this.delayLoad()},t.prototype.delayLoad=function(){if(this.delayLoadState===u.DELAYLOADSTATE_NOTLOADED){var e=this.getScene();e&&(this.delayLoadState=u.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?si.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null)}},t.prototype._prepareRowForTextureGeneration=function(e,t,i,r){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,V.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,r),r.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,r.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,r.z+=this.wRotationCenter},t.prototype.getTextureMatrix=function(e){var t=this;if(void 0===e&&(e=1),this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,this._cachedTextureMatrix&&this._rowGenerationMatrix||(this._cachedTextureMatrix=z.Zero(),this._rowGenerationMatrix=new z,this._t0=V.Zero(),this._t1=V.Zero(),this._t2=V.Zero()),z.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(z.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,H.Matrix[0]),z.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,H.Matrix[1]),z.ScalingToRef(this._cachedUScale,this._cachedVScale,0,H.Matrix[2]),z.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,H.Matrix[3]),H.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(H.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(H.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(H.Matrix[3],this._cachedTextureMatrix),this._cachedTextureMatrix.setRowFromFloats(2,this._cachedTextureMatrix.m[12],this._cachedTextureMatrix.m[13],this._cachedTextureMatrix.m[14],1)):(this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),z.FromValuesToRef(this._t1.x,this._t1.y,this._t1.z,0,this._t2.x,this._t2.y,this._t2.z,0,this._t0.x,this._t0.y,this._t0.z,0,0,0,0,1,this._cachedTextureMatrix));var i=this.getScene();if(!i)return this._cachedTextureMatrix;var r=this._cachedIdentity3x2;return this._cachedIdentity3x2=this._cachedTextureMatrix.isIdentityAs3x2(),this.optimizeUVAllocation&&r!==this._cachedIdentity3x2&&i.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(e){return e.hasTexture(t)})),this._cachedTextureMatrix},t.prototype.getReflectionTextureMatrix=function(){var e=this,i=this.getScene();if(!i)return this._cachedReflectionTextureMatrix;if(this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode){if(this.coordinatesMode!==t.PROJECTION_MODE)return this._cachedReflectionTextureMatrix;if(this._cachedReflectionProjectionMatrixId===i.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=z.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=z.Zero());var r=this._cachedReflectionCoordinatesMode!==this.coordinatesMode;switch(this._cachedReflectionUOffset=this.uOffset,this._cachedReflectionVOffset=this.vOffset,this._cachedReflectionUScale=this.uScale,this._cachedReflectionVScale=this.vScale,this._cachedReflectionCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case t.PLANAR_MODE:z.IdentityToRef(this._cachedReflectionTextureMatrix),this._cachedReflectionTextureMatrix[0]=this.uScale,this._cachedReflectionTextureMatrix[5]=this.vScale,this._cachedReflectionTextureMatrix[12]=this.uOffset,this._cachedReflectionTextureMatrix[13]=this.vOffset;break;case t.PROJECTION_MODE:z.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);var n=i.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=n.updateFlag,n.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break;default:z.IdentityToRef(this._cachedReflectionTextureMatrix)}return r&&i.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(t){return t.hasTexture(e)})),this._cachedReflectionTextureMatrix},t.prototype.clone=function(){var e=this,i={noMipmap:this._noMipmap,invertY:this._invertY,samplingMode:this.samplingMode,onLoad:void 0,onError:void 0,buffer:this._texture?this._texture._buffer:void 0,deleteBuffer:this._deleteBuffer,format:this.textureFormat,mimeType:this.mimeType,loaderOptions:this._loaderOptions,creationFlags:this._creationFlags,useSRGBBuffer:this._useSRGBBuffer};return Ke.Clone((function(){return new t(e._texture?e._texture.url:null,e.getScene(),i)}),this)},t.prototype.serialize=function(){var i,r,n=this.name;t.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");var o=e.prototype.serialize.call(this,t._SerializeInternalTextureUniqueId);return o?((t.SerializeBuffers||t.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(o.base64String=this._buffer,o.name=o.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?o.base64String="data:image/png;base64,"+xt(this._buffer):(t.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(o.base64String=!this._engine||this._engine._features.supportSyncTextureRead?Qa(this):qa(this))),o.invertY=this._invertY,o.samplingMode=this.samplingMode,o._creationFlags=this._creationFlags,o._useSRGBBuffer=this._useSRGBBuffer,t._SerializeInternalTextureUniqueId&&(o.internalTextureUniqueId=null!==(r=null===(i=this._texture)||void 0===i?void 0:i.uniqueId)&&void 0!==r?r:void 0),o.noMipmap=this._noMipmap,this.name=n,o):null},t.prototype.getClassName=function(){return"Texture"},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null},t.Parse=function(e,i,r){if(e.customType){var n=Ki.Instantiate(e.customType).Parse(e,i,r);return e.samplingMode&&n.updateSamplingMode&&n._samplingMode&&n._samplingMode!==e.samplingMode&&n.updateSamplingMode(e.samplingMode),n}if(e.isCube&&!e.isRenderTarget)return t._CubeTextureParser(e,i,r);var o,a=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!a)return null;if(a)for(var l=0,c=i.getEngine().getLoadedTexturesCache();l<c.length;l++){var u=c[l];if(u.uniqueId===e.internalTextureUniqueId){o=u;break}}var h=function(t){var i;if(t&&t._texture&&(t._texture._cachedWrapU=null,t._texture._cachedWrapV=null,t._texture._cachedWrapR=null),e.samplingMode){var r=e.samplingMode;t&&t.samplingMode!==r&&t.updateSamplingMode(r)}if(t&&e.animations)for(var n=0;n<e.animations.length;n++){var l=e.animations[n],c=s("BABYLON.Animation");c&&t.animations.push(c.Parse(l))}a&&!o&&(null===(i=null==t?void 0:t._texture)||void 0===i||i._setUniqueId(e.internalTextureUniqueId))},d=Ke.Parse((function(){var n,a,s,l,c=!0;if(e.noMipmap&&(c=!1),e.mirrorPlane){var u=t._CreateMirror(e.name,e.renderTargetSize,i,c);return u._waitingRenderList=e.renderList,u.mirrorPlane=sn.FromArray(e.mirrorPlane),h(u),u}if(e.isRenderTarget){var d=null;if(e.isCube){if(i.reflectionProbes)for(var p=0;p<i.reflectionProbes.length;p++){var f=i.reflectionProbes[p];if(f.name===e.name)return f.cubeTexture}}else(d=t._CreateRenderTargetTexture(e.name,e.renderTargetSize,i,c,null!==(n=e._creationFlags)&&void 0!==n?n:0))._waitingRenderList=e.renderList;return h(d),d}if(e.isVideo){var _=t._CreateVideoTexture(r+(e.url||e.name),r+(e.src||e.url),i,c,e.invertY,e.samplingMode,e.settings||{});return h(_),_}if(e.base64String&&!o)(l=t.CreateFromBase64String(e.base64String,e.base64String,i,!c,e.invertY,e.samplingMode,(function(){h(l)}),null!==(a=e._creationFlags)&&void 0!==a?a:0,null!==(s=e._useSRGBBuffer)&&void 0!==s&&s)).name=e.name;else{var m=void 0;m=e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?e.name:r+e.name,e.url&&(e.url.startsWith("data:")||t.UseSerializedUrlIfAny)&&(m=e.url);var g={noMipmap:!c,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:function(){h(l)},internalTexture:o};l=new t(m,i,g)}return l}),e,i);return d},t.CreateFromBase64String=function(e,i,r,n,o,a,s,l,c,h,d){return void 0===a&&(a=t.TRILINEAR_SAMPLINGMODE),void 0===s&&(s=null),void 0===l&&(l=null),void 0===c&&(c=u.TEXTUREFORMAT_RGBA),new t("data:"+i,r,n,o,a,s,l,e,!1,c,void 0,void 0,h,d)},t.LoadFromDataString=function(e,i,r,n,o,a,s,l,c,h,d,p){return void 0===n&&(n=!1),void 0===a&&(a=!0),void 0===s&&(s=t.TRILINEAR_SAMPLINGMODE),void 0===l&&(l=null),void 0===c&&(c=null),void 0===h&&(h=u.TEXTUREFORMAT_RGBA),"data:"!==e.substr(0,5)&&(e="data:"+e),new t(e,r,o,a,s,l,c,i,n,h,void 0,void 0,d,p)},t.SerializeBuffers=!0,t.ForceSerializeBuffers=!1,t.OnTextureLoadErrorObservable=new f,t._SerializeInternalTextureUniqueId=!1,t._CubeTextureParser=function(e,t,i){throw He("CubeTexture")},t._CreateMirror=function(e,t,i,r){throw He("MirrorTexture")},t._CreateRenderTargetTexture=function(e,t,i,r,n){throw He("RenderTargetTexture")},t.NEAREST_SAMPLINGMODE=u.TEXTURE_NEAREST_SAMPLINGMODE,t.NEAREST_NEAREST_MIPLINEAR=u.TEXTURE_NEAREST_NEAREST_MIPLINEAR,t.BILINEAR_SAMPLINGMODE=u.TEXTURE_BILINEAR_SAMPLINGMODE,t.LINEAR_LINEAR_MIPNEAREST=u.TEXTURE_LINEAR_LINEAR_MIPNEAREST,t.TRILINEAR_SAMPLINGMODE=u.TEXTURE_TRILINEAR_SAMPLINGMODE,t.LINEAR_LINEAR_MIPLINEAR=u.TEXTURE_LINEAR_LINEAR_MIPLINEAR,t.NEAREST_NEAREST_MIPNEAREST=u.TEXTURE_NEAREST_NEAREST_MIPNEAREST,t.NEAREST_LINEAR_MIPNEAREST=u.TEXTURE_NEAREST_LINEAR_MIPNEAREST,t.NEAREST_LINEAR_MIPLINEAR=u.TEXTURE_NEAREST_LINEAR_MIPLINEAR,t.NEAREST_LINEAR=u.TEXTURE_NEAREST_LINEAR,t.NEAREST_NEAREST=u.TEXTURE_NEAREST_NEAREST,t.LINEAR_NEAREST_MIPNEAREST=u.TEXTURE_LINEAR_NEAREST_MIPNEAREST,t.LINEAR_NEAREST_MIPLINEAR=u.TEXTURE_LINEAR_NEAREST_MIPLINEAR,t.LINEAR_LINEAR=u.TEXTURE_LINEAR_LINEAR,t.LINEAR_NEAREST=u.TEXTURE_LINEAR_NEAREST,t.EXPLICIT_MODE=u.TEXTURE_EXPLICIT_MODE,t.SPHERICAL_MODE=u.TEXTURE_SPHERICAL_MODE,t.PLANAR_MODE=u.TEXTURE_PLANAR_MODE,t.CUBIC_MODE=u.TEXTURE_CUBIC_MODE,t.PROJECTION_MODE=u.TEXTURE_PROJECTION_MODE,t.SKYBOX_MODE=u.TEXTURE_SKYBOX_MODE,t.INVCUBIC_MODE=u.TEXTURE_INVCUBIC_MODE,t.EQUIRECTANGULAR_MODE=u.TEXTURE_EQUIRECTANGULAR_MODE,t.FIXED_EQUIRECTANGULAR_MODE=u.TEXTURE_FIXED_EQUIRECTANGULAR_MODE,t.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=u.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE,t.CLAMP_ADDRESSMODE=u.TEXTURE_CLAMP_ADDRESSMODE,t.WRAP_ADDRESSMODE=u.TEXTURE_WRAP_ADDRESSMODE,t.MIRROR_ADDRESSMODE=u.TEXTURE_MIRROR_ADDRESSMODE,t.UseSerializedUrlIfAny=!1,v([Ie()],t.prototype,"url",void 0),v([Ie()],t.prototype,"uOffset",void 0),v([Ie()],t.prototype,"vOffset",void 0),v([Ie()],t.prototype,"uScale",void 0),v([Ie()],t.prototype,"vScale",void 0),v([Ie()],t.prototype,"uAng",void 0),v([Ie()],t.prototype,"vAng",void 0),v([Ie()],t.prototype,"wAng",void 0),v([Ie()],t.prototype,"uRotationCenter",void 0),v([Ie()],t.prototype,"vRotationCenter",void 0),v([Ie()],t.prototype,"wRotationCenter",void 0),v([Ie()],t.prototype,"homogeneousRotationInUVTransform",void 0),v([Ie()],t.prototype,"isBlocking",null),t}(Ya);function $a(e,t,i,r){var n,o=1;r===u.TEXTURETYPE_FLOAT?n=new Float32Array(t*i*4):r===u.TEXTURETYPE_HALF_FLOAT?(n=new Uint16Array(t*i*4),o=15360):n=r===u.TEXTURETYPE_UNSIGNED_INTEGER?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(var a=0;a<t;a++)for(var s=0;s<i;s++){var l=3*(s*t+a),c=4*(s*t+a);n[c+0]=e[l+0],n[c+1]=e[l+1],n[c+2]=e[l+2],n[c+3]=o}return n}function es(e){return function(t,i,r,n,o,a,s,l,c,h){void 0===c&&(c=null),void 0===h&&(h=u.TEXTURETYPE_UNSIGNED_INT);var d=e?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,p=e?Ti.Raw3D:Ti.Raw2DArray,f=new Pi(this,p);f.baseWidth=i,f.baseHeight=r,f.baseDepth=n,f.width=i,f.height=r,f.depth=n,f.format=o,f.type=h,f.generateMipMaps=a,f.samplingMode=l,e?f.is3D=!0:f.is2DArray=!0,this._doNotHandleContextLost||(f._bufferView=t),e?this.updateRawTexture3D(f,t,o,s,c,h):this.updateRawTexture2DArray(f,t,o,s,c,h),this._bindTextureDirectly(d,f,!0);var _=this._getSamplingParameters(l,a);return this._gl.texParameteri(d,this._gl.TEXTURE_MAG_FILTER,_.mag),this._gl.texParameteri(d,this._gl.TEXTURE_MIN_FILTER,_.min),a&&this._gl.generateMipmap(d),this._bindTextureDirectly(d,null),this._internalTexturesCache.push(f),f}}function ts(e){return function(t,i,r,n,o,a){void 0===o&&(o=null),void 0===a&&(a=u.TEXTURETYPE_UNSIGNED_INT);var s=e?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,l=this._getWebGLTextureType(a),c=this._getInternalFormat(r),h=this._getRGBABufferInternalSizedFormat(a,r);this._bindTextureDirectly(s,t,!0),this._unpackFlipY(void 0===n||!!n),this._doNotHandleContextLost||(t._bufferView=i,t.format=r,t.invertY=n,t._compression=o),t.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),o&&i?this._gl.compressedTexImage3D(s,0,this.getCaps().s3tc[o],t.width,t.height,t.depth,0,i):this._gl.texImage3D(s,0,h,t.width,t.height,t.depth,0,c,l,i),t.generateMipMaps&&this._gl.generateMipmap(s),this._bindTextureDirectly(s,null),t.isReady=!0}}a("BABYLON.Texture",Ja),Ke._TextureParser=Ja.Parse,Er.prototype.updateRawTexture=function(e,t,i,r,n,o,a){if(void 0===n&&(n=null),void 0===o&&(o=u.TEXTURETYPE_UNSIGNED_INT),void 0===a&&(a=!1),e){var s=this._getRGBABufferInternalSizedFormat(o,i,a),l=this._getInternalFormat(i),c=this._getWebGLTextureType(o);this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===r||!!r),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.type=o,e.invertY=r,e._compression=n),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),n&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[n],e.width,e.height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,e.width,e.height,0,l,c,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}},Er.prototype.createRawTexture=function(e,t,i,r,n,o,a,s,l,c,h){void 0===s&&(s=null),void 0===l&&(l=u.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=0),void 0===h&&(h=!1);var d=new Pi(this,Ti.Raw);d.baseWidth=t,d.baseHeight=i,d.width=t,d.height=i,d.format=r,d.generateMipMaps=n,d.samplingMode=a,d.invertY=o,d._compression=s,d.type=l,d._useSRGBBuffer=this._getUseSRGBBuffer(h,!n),this._doNotHandleContextLost||(d._bufferView=e),this.updateRawTexture(d,e,r,o,s,l,d._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,d,!0);var p=this._getSamplingParameters(a,n);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,p.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,p.min),n&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(d),d},Er.prototype.createRawCubeTexture=function(e,t,i,r,n,o,a,s){void 0===s&&(s=null);var l=this._gl,c=new Pi(this,Ti.CubeRaw);c.isCube=!0,c.format=i,c.type=r,this._doNotHandleContextLost||(c._bufferViewArray=e);var h=this._getWebGLTextureType(r),d=this._getInternalFormat(i);d===l.RGB&&(d=l.RGBA),h!==l.FLOAT||this._caps.textureFloatLinearFiltering?h!==this._gl.HALF_FLOAT_OES||this._caps.textureHalfFloatLinearFiltering?h!==l.FLOAT||this._caps.textureFloatRender?h!==l.HALF_FLOAT||this._caps.colorBufferFloat||(n=!1,ae.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(n=!1,ae.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(n=!1,a=u.TEXTURE_NEAREST_SAMPLINGMODE,ae.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(n=!1,a=u.TEXTURE_NEAREST_SAMPLINGMODE,ae.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."));var p=t,f=p;if(c.width=p,c.height=f,c.invertY=o,c._compression=s,!this.needPOTTextures||Zi(c.width)&&Zi(c.height)||(n=!1),e)this.updateRawCubeTexture(c,e,i,r,o,s);else{var _=this._getRGBABufferInternalSizedFormat(r);this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,c,!0);for(var m=0;m<6;m++)s?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+m,0,this.getCaps().s3tc[s],c.width,c.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+m,0,_,c.width,c.height,0,d,h,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,c,!0),e&&n&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);var g=this._getSamplingParameters(a,n);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,g.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,g.min),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,null),c.generateMipMaps=n,c.samplingMode=a,c.isReady=!0,c},Er.prototype.updateRawCubeTexture=function(e,t,i,r,n,o,a){void 0===o&&(o=null),void 0===a&&(a=0),e._bufferViewArray=t,e.format=i,e.type=r,e.invertY=n,e._compression=o;var s=this._gl,l=this._getWebGLTextureType(r),c=this._getInternalFormat(i),u=this._getRGBABufferInternalSizedFormat(r),h=!1;c===s.RGB&&(c=s.RGBA,h=!0),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(void 0===n||!!n),e.width%4!=0&&s.pixelStorei(s.UNPACK_ALIGNMENT,1);for(var d=0;d<6;d++){var p=t[d];o?s.compressedTexImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+d,a,this.getCaps().s3tc[o],e.width,e.height,0,p):(h&&(p=$a(p,e.width,e.height,r)),s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+d,a,u,e.width,e.height,0,c,l,p))}(!this.needPOTTextures||Zi(e.width)&&Zi(e.height))&&e.generateMipMaps&&0===a&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),e.isReady=!0},Er.prototype.createRawCubeTextureFromUrl=function(e,t,i,r,n,o,a,s,l,c,h,d){var p=this;void 0===l&&(l=null),void 0===c&&(c=null),void 0===h&&(h=u.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===d&&(d=!1);var f=this._gl,_=this.createRawCubeTexture(null,i,r,n,!o,d,h,null);return null==t||t.addPendingData(_),_.url=e,_.isReady=!1,this._internalTexturesCache.push(_),this._loadFile(e,(function(e){!function(e){var i=_.width,o=a(e);if(o){if(s){var c=p._getWebGLTextureType(n),u=p._getInternalFormat(r),h=p._getRGBABufferInternalSizedFormat(n),m=!1;u===f.RGB&&(u=f.RGBA,m=!0),p._bindTextureDirectly(f.TEXTURE_CUBE_MAP,_,!0),p._unpackFlipY(!1);for(var g=s(o),v=0;v<g.length;v++)for(var y=i>>v,b=0;b<6;b++){var T=g[v][b];m&&(T=$a(T,y,y,n)),f.texImage2D(b,v,h,y,y,0,u,c,T)}p._bindTextureDirectly(f.TEXTURE_CUBE_MAP,null)}else p.updateRawCubeTexture(_,o,r,n,d);_.isReady=!0,null==t||t.removePendingData(_),_.onLoadedObservable.notifyObservers(_),_.onLoadedObservable.clear(),l&&l()}}(e)}),void 0,null==t?void 0:t.offlineProvider,!0,(function(e,i){null==t||t.removePendingData(_),c&&e&&c(e.status+" "+e.statusText,i)})),_},Er.prototype.createRawTexture2DArray=es(!1),Er.prototype.createRawTexture3D=es(!0),Er.prototype.updateRawTexture2DArray=ts(!1),Er.prototype.updateRawTexture3D=ts(!0);var is=function(e){function t(t,i,r,n,o,a,s,l,c,h,d){void 0===a&&(a=!0),void 0===s&&(s=!1),void 0===l&&(l=u.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===c&&(c=u.TEXTURETYPE_UNSIGNED_INT);var p=e.call(this,null,o,!a,s,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,h)||this;return p.format=n,p._engine?(p._engine._caps.textureFloatLinearFiltering||c!==u.TEXTURETYPE_FLOAT||(l=u.TEXTURE_NEAREST_SAMPLINGMODE),p._engine._caps.textureHalfFloatLinearFiltering||c!==u.TEXTURETYPE_HALF_FLOAT||(l=u.TEXTURE_NEAREST_SAMPLINGMODE),p._texture=p._engine.createRawTexture(t,i,r,n,a,s,l,null,c,null!=h?h:0,null!=d&&d),p.wrapU=Ja.CLAMP_ADDRESSMODE,p.wrapV=Ja.CLAMP_ADDRESSMODE,p):p}return m(t,e),t.prototype.update=function(e){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer)},t.CreateLuminanceTexture=function(e,i,r,n,o,a,s){return void 0===o&&(o=!0),void 0===a&&(a=!1),void 0===s&&(s=u.TEXTURE_TRILINEAR_SAMPLINGMODE),new t(e,i,r,u.TEXTUREFORMAT_LUMINANCE,n,o,a,s)},t.CreateLuminanceAlphaTexture=function(e,i,r,n,o,a,s){return void 0===o&&(o=!0),void 0===a&&(a=!1),void 0===s&&(s=u.TEXTURE_TRILINEAR_SAMPLINGMODE),new t(e,i,r,u.TEXTUREFORMAT_LUMINANCE_ALPHA,n,o,a,s)},t.CreateAlphaTexture=function(e,i,r,n,o,a,s){return void 0===o&&(o=!0),void 0===a&&(a=!1),void 0===s&&(s=u.TEXTURE_TRILINEAR_SAMPLINGMODE),new t(e,i,r,u.TEXTUREFORMAT_ALPHA,n,o,a,s)},t.CreateRGBTexture=function(e,i,r,n,o,a,s,l,c,h){return void 0===o&&(o=!0),void 0===a&&(a=!1),void 0===s&&(s=u.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===l&&(l=u.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=0),void 0===h&&(h=!1),new t(e,i,r,u.TEXTUREFORMAT_RGB,n,o,a,s,l,c,h)},t.CreateRGBATexture=function(e,i,r,n,o,a,s,l,c,h){return void 0===o&&(o=!0),void 0===a&&(a=!1),void 0===s&&(s=u.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===l&&(l=u.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=0),void 0===h&&(h=!1),new t(e,i,r,u.TEXTUREFORMAT_RGBA,n,o,a,s,l,c,h)},t.CreateRGBAStorageTexture=function(e,i,r,n,o,a,s,l,c){return void 0===o&&(o=!0),void 0===a&&(a=!1),void 0===s&&(s=u.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===l&&(l=u.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=!1),new t(e,i,r,u.TEXTUREFORMAT_RGBA,n,o,a,s,l,u.TEXTURE_CREATIONFLAG_STORAGE,c)},t.CreateRTexture=function(e,i,r,n,o,a,s,l){return void 0===o&&(o=!0),void 0===a&&(a=!1),void 0===s&&(s=Ja.TRILINEAR_SAMPLINGMODE),void 0===l&&(l=u.TEXTURETYPE_FLOAT),new t(e,i,r,u.TEXTUREFORMAT_R,n,o,a,s,l)},t.CreateRStorageTexture=function(e,i,r,n,o,a,s,l){return void 0===o&&(o=!0),void 0===a&&(a=!1),void 0===s&&(s=Ja.TRILINEAR_SAMPLINGMODE),void 0===l&&(l=u.TEXTURETYPE_FLOAT),new t(e,i,r,u.TEXTUREFORMAT_R,n,o,a,s,l,u.TEXTURE_CREATIONFLAG_STORAGE)},t}(Ja),rs=function(){function e(e,t,i){this.name=e,this.id=t,this.bones=[],this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=z.Identity(),this._currentRenderId=-1,this._ranges={},this._absoluteTransformIsDirty=!0,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._parentContainer=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new f,this.bones=[],this._scene=i||M.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;var r=this._scene.getEngine().getCaps();this._canUseTextureForBones=r.textureFloat&&r.maxVertexTextureImageUnits>0}return Object.defineProperty(e.prototype,"useTextureToStoreBoneMatrices",{get:function(){return this._useTextureToStoreBoneMatrices},set:function(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"animationPropertiesOverride",{get:function(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride},set:function(e){this._animationPropertiesOverride=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isUsingTextureForMatrices",{get:function(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"uniqueId",{get:function(){return this._uniqueId},enumerable:!1,configurable:!0}),e.prototype.getClassName=function(){return"Skeleton"},e.prototype.getChildren=function(){return this.bones.filter((function(e){return!e.getParent()}))},e.prototype.getTransformMatrices=function(e){if(this.needInitialSkinMatrix){if(!e)throw new Error("getTransformMatrices: When using the needInitialSkinMatrix flag, a mesh must be provided");return e._bonesTransformMatrices||this.prepare(!0),e._bonesTransformMatrices}return this._transformMatrices&&!this._isDirty||this.prepare(!this._transformMatrices),this._transformMatrices},e.prototype.getTransformMatrixTexture=function(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture},e.prototype.getScene=function(){return this._scene},e.prototype.toString=function(e){var t="Name: ".concat(this.name,", nBones: ").concat(this.bones.length);if(t+=", nAnimationRanges: ".concat(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";var i=!0;for(var r in this._ranges)i&&(t+=", ",i=!1),t+=r;t+="}"}return t},e.prototype.getBoneIndexByName=function(e){for(var t=0,i=this.bones.length;t<i;t++)if(this.bones[t].name===e)return t;return-1},e.prototype.createAnimationRange=function(e,t,i){if(!this._ranges[e]){this._ranges[e]=new Se(e,t,i);for(var r=0,n=this.bones.length;r<n;r++)this.bones[r].animations[0]&&this.bones[r].animations[0].createRange(e,t,i)}},e.prototype.deleteAnimationRange=function(e,t){void 0===t&&(t=!0);for(var i=0,r=this.bones.length;i<r;i++)this.bones[i].animations[0]&&this.bones[i].animations[0].deleteRange(e,t);this._ranges[e]=null},e.prototype.getAnimationRange=function(e){return this._ranges[e]||null},e.prototype.getAnimationRanges=function(){var e,t=[];for(e in this._ranges)t.push(this._ranges[e]);return t},e.prototype.copyAnimationRange=function(e,t,i){if(void 0===i&&(i=!1),this._ranges[t]||!e.getAnimationRange(t))return!1;var r,n,o=!0,a=this._getHighestAnimationFrame()+1,s={},l=e.bones;for(n=0,r=l.length;n<r;n++)s[l[n].name]=l[n];this.bones.length!==l.length&&(ae.Warn("copyAnimationRange: this rig has ".concat(this.bones.length," bones, while source as ").concat(l.length)),o=!1);var c=i&&this.dimensionsAtRest&&e.dimensionsAtRest?this.dimensionsAtRest.divide(e.dimensionsAtRest):null;for(n=0,r=this.bones.length;n<r;n++){var u=this.bones[n].name,h=s[u];h?o=o&&this.bones[n].copyAnimationRange(h,t,a,i,c):(ae.Warn("copyAnimationRange: not same rig, missing source bone "+u),o=!1)}var d=e.getAnimationRange(t);return d&&(this._ranges[t]=new Se(t,d.from+a,d.to+a)),o},e.prototype.returnToRest=function(){for(var e=0,t=this.bones;e<t.length;e++){var i=t[e];-1!==i._index&&i.returnToRest()}},e.prototype._getHighestAnimationFrame=function(){for(var e=0,t=0,i=this.bones.length;t<i;t++)if(this.bones[t].animations[0]){var r=this.bones[t].animations[0].getHighestFrame();e<r&&(e=r)}return e},e.prototype.beginAnimation=function(e,t,i,r){var n=this.getAnimationRange(e);return n?this._scene.beginAnimation(this,n.from,n.to,t,i,r):null},e.MakeAnimationAdditive=function(e,t,i){void 0===t&&(t=0);var r=e.getAnimationRange(i);if(!r)return null;for(var n=e._scene.getAllAnimatablesByTarget(e),o=null,a=0;a<n.length;a++){var s=n[a];if(s.fromFrame===(null==r?void 0:r.from)&&s.toFrame===(null==r?void 0:r.to)){o=s;break}}var l=e.getAnimatables();for(a=0;a<l.length;a++){var c=l[a].animations;if(c)for(var u=0;u<c.length;u++)at.MakeAnimationAdditive(c[u],t,i)}return o&&(o.isAdditive=!0),e},e.prototype._markAsDirty=function(){this._isDirty=!0,this._absoluteTransformIsDirty=!0},e.prototype._registerMeshWithPoseMatrix=function(e){this._meshesWithPoseMatrix.push(e)},e.prototype._unregisterMeshWithPoseMatrix=function(e){var t=this._meshesWithPoseMatrix.indexOf(e);t>-1&&this._meshesWithPoseMatrix.splice(t,1)},e.prototype._computeTransformMatrices=function(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(var i=0;i<this.bones.length;i++){var r=this.bones[i];r._childUpdateId++;var n=r.getParent();if(n?r.getLocalMatrix().multiplyToRef(n.getFinalMatrix(),r.getFinalMatrix()):t?r.getLocalMatrix().multiplyToRef(t,r.getFinalMatrix()):r.getFinalMatrix().copyFrom(r.getLocalMatrix()),-1!==r._index){var o=null===r._index?i:r._index;r.getAbsoluteInverseBindMatrix().multiplyToArray(r.getFinalMatrix(),e,16*o)}}this._identity.copyToArray(e,16*this.bones.length)},e.prototype.prepare=function(e){if(void 0===e&&(e=!1),!e){var t=this.getScene().getRenderId();if(this._currentRenderId===t)return;this._currentRenderId=t}if(this._numBonesWithLinkedTransformNode>0)for(var i=0,r=this.bones;i<r.length;i++)if((p=r[i])._linkedTransformNode){var n=p._linkedTransformNode;p.position=n.position,n.rotationQuaternion?p.rotationQuaternion=n.rotationQuaternion:p.rotation=n.rotation,p.scaling=n.scaling}if(this.needInitialSkinMatrix)for(var o=0,a=this._meshesWithPoseMatrix;o<a.length;o++){var s=a[o],l=s.getPoseMatrix(),c=this._isDirty;if(s._bonesTransformMatrices&&s._bonesTransformMatrices.length===16*(this.bones.length+1)||(s._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),c=!0),c){if(this._synchronizedWithMesh!==s){this._synchronizedWithMesh=s;for(var h=0,d=this.bones;h<d.length;h++){var p;(p=d[h]).getParent()||(p.getBindMatrix().multiplyToRef(l,H.Matrix[1]),p._updateAbsoluteBindMatrices(H.Matrix[1]))}if(this.isUsingTextureForMatrices){var f=4*(this.bones.length+1);s._transformMatrixTexture&&s._transformMatrixTexture.getSize().width===f||(s._transformMatrixTexture&&s._transformMatrixTexture.dispose(),s._transformMatrixTexture=is.CreateRGBATexture(s._bonesTransformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,u.TEXTURE_NEAREST_SAMPLINGMODE,u.TEXTURETYPE_FLOAT))}}this._computeTransformMatrices(s._bonesTransformMatrices,l),this.isUsingTextureForMatrices&&s._transformMatrixTexture&&s._transformMatrixTexture.update(s._bonesTransformMatrices)}}else{if(!this._isDirty)return;this._transformMatrices&&this._transformMatrices.length===16*(this.bones.length+1)||(this._transformMatrices=new Float32Array(16*(this.bones.length+1)),this.isUsingTextureForMatrices&&(this._transformMatrixTexture&&this._transformMatrixTexture.dispose(),this._transformMatrixTexture=is.CreateRGBATexture(this._transformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,u.TEXTURE_NEAREST_SAMPLINGMODE,u.TEXTURETYPE_FLOAT))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1},e.prototype.getAnimatables=function(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(var e=0;e<this.bones.length;e++)this._animatables.push(this.bones[e])}return this._animatables},e.prototype.clone=function(t,i){var r=new e(t,i||t,this._scene);r.needInitialSkinMatrix=this.needInitialSkinMatrix;for(var n=0;n<this.bones.length;n++){var o=this.bones[n],a=null,s=o.getParent();if(s){var l=this.bones.indexOf(s);a=r.bones[l]}var c=new mn(o.name,r,a,o.getBindMatrix().clone(),o.getRestMatrix().clone());c._index=o._index,o._linkedTransformNode&&c.linkTransformNode(o._linkedTransformNode),ye.DeepCopy(o.animations,c.animations)}if(this._ranges)for(var u in r._ranges={},this._ranges){var h=this._ranges[u];h&&(r._ranges[u]=h.clone())}return this._isDirty=!0,r.prepare(!0),r},e.prototype.enableBlending=function(e){void 0===e&&(e=.01),this.bones.forEach((function(t){t.animations.forEach((function(t){t.enableBlending=!0,t.blendingSpeed=e}))}))},e.prototype.dispose=function(){if(this._meshesWithPoseMatrix.length=0,this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._parentContainer){var e=this._parentContainer.skeletons.indexOf(this);e>-1&&this._parentContainer.skeletons.splice(e,1),this._parentContainer=null}this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null)},e.prototype.serialize=function(){var e,t={};t.name=this.name,t.id=this.id,this.dimensionsAtRest&&(t.dimensionsAtRest=this.dimensionsAtRest.asArray()),t.bones=[],t.needInitialSkinMatrix=this.needInitialSkinMatrix;for(var i=0;i<this.bones.length;i++){var r=this.bones[i],n=r.getParent(),o={parentBoneIndex:n?this.bones.indexOf(n):-1,index:r.getIndex(),name:r.name,id:r.id,matrix:r.getBindMatrix().asArray(),rest:r.getRestMatrix().asArray(),linkedTransformNodeId:null===(e=r.getTransformNode())||void 0===e?void 0:e.id};for(var a in t.bones.push(o),r.length&&(o.length=r.length),r.metadata&&(o.metadata=r.metadata),r.animations&&r.animations.length>0&&(o.animation=r.animations[0].serialize()),t.ranges=[],this._ranges){var s=this._ranges[a];if(s){var l={};l.name=a,l.from=s.from,l.to=s.to,t.ranges.push(l)}}}return t},e.Parse=function(t,i){var r,n=new e(t.name,t.id,i);for(t.dimensionsAtRest&&(n.dimensionsAtRest=V.FromArray(t.dimensionsAtRest)),n.needInitialSkinMatrix=t.needInitialSkinMatrix,r=0;r<t.bones.length;r++){var o=t.bones[r],a=t.bones[r].index,s=null;o.parentBoneIndex>-1&&(s=n.bones[o.parentBoneIndex]);var l=o.rest?z.FromArray(o.rest):null,c=new mn(o.name,n,s,z.FromArray(o.matrix),l,null,a);void 0!==o.id&&null!==o.id&&(c.id=o.id),o.length&&(c.length=o.length),o.metadata&&(c.metadata=o.metadata),o.animation&&c.animations.push(at.Parse(o.animation)),void 0!==o.linkedTransformNodeId&&null!==o.linkedTransformNodeId&&(n._hasWaitingData=!0,c._waitingTransformNodeId=o.linkedTransformNodeId)}if(t.ranges)for(r=0;r<t.ranges.length;r++){var u=t.ranges[r];n.createAnimationRange(u.name,u.from,u.to)}return n},e.prototype.computeAbsoluteMatrices=function(e){void 0===e&&(e=!1),(this._absoluteTransformIsDirty||e)&&(this.bones[0].computeAbsoluteMatrices(),this._absoluteTransformIsDirty=!1)},e.prototype.computeAbsoluteTransforms=function(e){void 0===e&&(e=!1),this.computeAbsoluteMatrices(e)},e.prototype.getPoseMatrix=function(){var e=null;return this._meshesWithPoseMatrix.length>0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e},e.prototype.sortBones=function(){for(var e=[],t=new Array(this.bones.length),i=0;i<this.bones.length;i++)this._sortBones(i,e,t);this.bones=e},e.prototype._sortBones=function(e,t,i){if(!i[e]){i[e]=!0;var r=this.bones[e];if(r){void 0===r._index&&(r._index=e);var n=r.getParent();n&&this._sortBones(this.bones.indexOf(n),t,i),t.push(r)}}},e.prototype.setCurrentPoseAsRest=function(){this.bones.forEach((function(e){e.setCurrentPoseAsRest()}))},e}(),ns=function(){function e(e,t){this._scene=e,t instanceof rs?(this._skeleton=t,this._mesh=null):(this._mesh=t,this._skeleton=t.skeleton)}return e.prototype.bakeVertexData=function(e){return y(this,void 0,void 0,(function(){var t,i,r,n,o,a,s,l;return b(this,(function(c){switch(c.label){case 0:if(!this._skeleton)throw new Error("No skeleton provided.");if(t=this._skeleton.bones.length,i=e.reduce((function(e,t){return e+t.to-t.from+1}),0),isNaN(i))throw new Error("Invalid animation ranges.");r=0,n=new Float32Array(4*(t+1)*4*i),this._scene.stopAnimation(this._skeleton),this._skeleton.returnToRest(),o=0,a=e,c.label=1;case 1:if(!(o<a.length))return[3,6];s=a[o],l=s.from,c.label=2;case 2:return l<=s.to?[4,this._executeAnimationFrame(n,l,r++)]:[3,5];case 3:c.sent(),c.label=4;case 4:return l++,[3,2];case 5:return o++,[3,1];case 6:return[2,n]}}))}))},e.prototype._executeAnimationFrame=function(e,t,i){return y(this,void 0,void 0,(function(){var r=this;return b(this,(function(n){return[2,new Promise((function(n,o){r._scene.beginAnimation(r._skeleton,t,t,!1,1,(function(){var t=r._skeleton.getTransformMatrices(r._mesh);e.set(t,i*t.length),n()}))}))]}))}))},e.prototype.textureFromBakedVertexData=function(e){if(!this._skeleton)throw new Error("No skeleton provided.");var t=this._skeleton.bones.length,i=is.CreateRGBATexture(e,4*(t+1),e.length/(4*(t+1)*4),this._scene,!1,!1,Ja.NEAREST_NEAREST,u.TEXTURETYPE_FLOAT);return i.name="VAT"+this._skeleton.name,i},e.prototype.serializeBakedVertexDataToObject=function(e){if(!this._skeleton)throw new Error("No skeleton provided.");var t=this._skeleton.bones.length,i=4*(t+1),r=e.length/(4*(t+1)*4);return{vertexData:xt(e),width:i,height:r}},e.prototype.loadBakedVertexDataFromObject=function(e){return new Float32Array(Ct(e.vertexData))},e.prototype.serializeBakedVertexDataToJSON=function(e){return JSON.stringify(this.serializeBakedVertexDataToObject(e))},e.prototype.loadBakedVertexDataFromJSON=function(e){return this.loadBakedVertexDataFromObject(JSON.parse(e))},e}(),os=function(){function e(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this.targetAlpha=null,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}return Object.defineProperty(e.prototype,"name",{get:function(){return"AutoRotation"},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"zoomStopsAnimation",{get:function(){return this._zoomStopsAnimation},set:function(e){this._zoomStopsAnimation=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"idleRotationSpeed",{get:function(){return this._idleRotationSpeed},set:function(e){this._idleRotationSpeed=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"idleRotationWaitTime",{get:function(){return this._idleRotationWaitTime},set:function(e){this._idleRotationWaitTime=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"idleRotationSpinupTime",{get:function(){return this._idleRotationSpinupTime},set:function(e){this._idleRotationSpinupTime=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"rotationInProgress",{get:function(){return Math.abs(this._cameraRotationSpeed)>0},enumerable:!1,configurable:!0}),e.prototype.init=function(){},e.prototype.attach=function(e){var t=this;this._attachedCamera=e;var i=this._attachedCamera.getScene();this._onPrePointerObservableObserver=i.onPrePointerObservable.add((function(e){e.type!==Gr.POINTERDOWN?e.type===Gr.POINTERUP&&(t._isPointerDown=!1):t._isPointerDown=!0})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((function(){if(!t._reachTargetAlpha()){var e=_t.Now,i=0;null!=t._lastFrameTime&&(i=e-t._lastFrameTime),t._lastFrameTime=e,t._applyUserInteraction();var r=e-t._lastInteractionTime-t._idleRotationWaitTime,n=Math.max(Math.min(r/t._idleRotationSpinupTime,1),0);t._cameraRotationSpeed=t._idleRotationSpeed*n,t._attachedCamera&&(t._attachedCamera.alpha-=t._cameraRotationSpeed*(i/1e3))}}))},e.prototype.detach=function(){if(this._attachedCamera){var e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}},e.prototype.resetLastInteractionTime=function(e){this._lastInteractionTime=null!=e?e:_t.Now},e.prototype._reachTargetAlpha=function(){return!(!this._attachedCamera||!this.targetAlpha)&&Math.abs(this._attachedCamera.alpha-this.targetAlpha)<A},e.prototype._userIsZooming=function(){return!!this._attachedCamera&&0!==this._attachedCamera.inertialRadiusOffset},e.prototype._shouldAnimationStopForInteraction=function(){if(!this._attachedCamera)return!1;var e=!1;return this._lastFrameRadius===this._attachedCamera.radius&&0!==this._attachedCamera.inertialRadiusOffset&&(e=!0),this._lastFrameRadius=this._attachedCamera.radius,this._zoomStopsAnimation?e:this._userIsZooming()},e.prototype._applyUserInteraction=function(){this._userIsMoving()&&!this._shouldAnimationStopForInteraction()&&(this._lastInteractionTime=_t.Now)},e.prototype._userIsMoving=function(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)},e}(),as=function(){function e(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=new Array}return Object.defineProperty(e.prototype,"name",{get:function(){return"Bouncing"},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"autoTransitionRange",{get:function(){return this._autoTransitionRange},set:function(e){var t=this;if(this._autoTransitionRange!==e){this._autoTransitionRange=e;var i=this._attachedCamera;i&&(e?this._onMeshTargetChangedObserver=i.onMeshTargetChangedObservable.add((function(e){if(e&&(e.computeWorldMatrix(!0),e.getBoundingInfo)){var i=e.getBoundingInfo().diagonalLength;t.lowerRadiusTransitionRange=.05*i,t.upperRadiusTransitionRange=.05*i}})):this._onMeshTargetChangedObserver&&i.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}},enumerable:!1,configurable:!0}),e.prototype.init=function(){},e.prototype.attach=function(e){var t=this;this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((function(){t._attachedCamera&&(t._isRadiusAtLimit(t._attachedCamera.lowerRadiusLimit)&&t._applyBoundRadiusAnimation(t.lowerRadiusTransitionRange),t._isRadiusAtLimit(t._attachedCamera.upperRadiusLimit)&&t._applyBoundRadiusAnimation(t.upperRadiusTransitionRange))}))},e.prototype.detach=function(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)},e.prototype._isRadiusAtLimit=function(e){return!!this._attachedCamera&&this._attachedCamera.radius===e&&!this._radiusIsAnimating},e.prototype._applyBoundRadiusAnimation=function(t){var i=this;if(this._attachedCamera){this._radiusBounceTransition||(e.EasingFunction.setEasingMode(e.EasingMode),this._radiusBounceTransition=at.CreateAnimation("radius",at.ANIMATIONTYPE_FLOAT,60,e.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;var r=at.TransitionTo("radius",this._attachedCamera.radius+t,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,(function(){return i._clearAnimationLocks()}));r&&this._animatables.push(r)}},e.prototype._clearAnimationLocks=function(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)},e.prototype.stopAllAnimations=function(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()},e.EasingFunction=new In(.3),e.EasingMode=Rn.EASINGMODE_EASEOUT,e}(),ss=function(){function e(){this.onTargetFramingAnimationEndObservable=new f,this._mode=e.FitFrustumSidesMode,this._radiusScale=1,this._positionScale=.5,this._defaultElevation=.3,this._elevationReturnTime=1500,this._elevationReturnWaitTime=1e3,this._zoomStopsAnimation=!1,this._framingTime=1500,this.autoCorrectCameraLimitsAndSensibility=!0,this._isPointerDown=!1,this._lastInteractionTime=-1/0,this._animatables=new Array,this._betaIsAnimating=!1}return Object.defineProperty(e.prototype,"name",{get:function(){return"Framing"},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"mode",{get:function(){return this._mode},set:function(e){this._mode=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"radiusScale",{get:function(){return this._radiusScale},set:function(e){this._radiusScale=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"positionScale",{get:function(){return this._positionScale},set:function(e){this._positionScale=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"defaultElevation",{get:function(){return this._defaultElevation},set:function(e){this._defaultElevation=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"elevationReturnTime",{get:function(){return this._elevationReturnTime},set:function(e){this._elevationReturnTime=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"elevationReturnWaitTime",{get:function(){return this._elevationReturnWaitTime},set:function(e){this._elevationReturnWaitTime=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"zoomStopsAnimation",{get:function(){return this._zoomStopsAnimation},set:function(e){this._zoomStopsAnimation=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"framingTime",{get:function(){return this._framingTime},set:function(e){this._framingTime=e},enumerable:!1,configurable:!0}),e.prototype.init=function(){},e.prototype.attach=function(t){var i=this;this._attachedCamera=t;var r=this._attachedCamera.getScene();e.EasingFunction.setEasingMode(e.EasingMode),this._onPrePointerObservableObserver=r.onPrePointerObservable.add((function(e){e.type!==Gr.POINTERDOWN?e.type===Gr.POINTERUP&&(i._isPointerDown=!1):i._isPointerDown=!0})),this._onMeshTargetChangedObserver=t.onMeshTargetChangedObservable.add((function(e){e&&e.getBoundingInfo&&i.zoomOnMesh(e,void 0,(function(){i.onTargetFramingAnimationEndObservable.notifyObservers()}))})),this._onAfterCheckInputsObserver=t.onAfterCheckInputsObservable.add((function(){i._applyUserInteraction(),i._maintainCameraAboveGround()}))},e.prototype.detach=function(){if(this._attachedCamera){var e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}},e.prototype.zoomOnMesh=function(e,t,i){void 0===t&&(t=!1),void 0===i&&(i=null),e.computeWorldMatrix(!0);var r=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(r.minimumWorld,r.maximumWorld,t,i)},e.prototype.zoomOnMeshHierarchy=function(e,t,i){void 0===t&&(t=!1),void 0===i&&(i=null),e.computeWorldMatrix(!0);var r=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(r.min,r.max,t,i)},e.prototype.zoomOnMeshesHierarchy=function(e,t,i){void 0===t&&(t=!1),void 0===i&&(i=null);for(var r=new V(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new V(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),o=0;o<e.length;o++){var a=e[o].getHierarchyBoundingVectors(!0);V.CheckExtends(a.min,r,n),V.CheckExtends(a.max,r,n)}this.zoomOnBoundingInfo(r,n,t,i)},e.prototype.zoomOnBoundingInfo=function(t,i,r,n){var o,a=this;if(void 0===r&&(r=!1),void 0===n&&(n=null),!this._attachedCamera)return!1;var s=t.y,l=s+(i.y-s)*this._positionScale,c=i.subtract(t).scale(.5);if(r)o=new V(0,l,0);else{var u=t.add(c);o=new V(u.x,l,u.z)}this._vectorTransition||(this._vectorTransition=at.CreateAnimation("target",at.ANIMATIONTYPE_VECTOR3,60,e.EasingFunction)),this._betaIsAnimating=!0;var h=at.TransitionTo("target",o,this._attachedCamera,this._attachedCamera.getScene(),60,this._vectorTransition,this._framingTime);h&&this._animatables.push(h);var d=0;if(this._mode===e.FitFrustumSidesMode){var p=this._calculateLowerRadiusFromModelBoundingSphere(t,i);this.autoCorrectCameraLimitsAndSensibility&&(this._attachedCamera.lowerRadiusLimit=c.length()+this._attachedCamera.minZ),d=p}else this._mode===e.IgnoreBoundsSizeMode&&(d=this._calculateLowerRadiusFromModelBoundingSphere(t,i),this.autoCorrectCameraLimitsAndSensibility&&null===this._attachedCamera.lowerRadiusLimit&&(this._attachedCamera.lowerRadiusLimit=this._attachedCamera.minZ));if(this.autoCorrectCameraLimitsAndSensibility){var f=i.subtract(t).length();this._attachedCamera.panningSensibility=5e3/f,this._attachedCamera.wheelPrecision=100/d}return this._radiusTransition||(this._radiusTransition=at.CreateAnimation("radius",at.ANIMATIONTYPE_FLOAT,60,e.EasingFunction)),(h=at.TransitionTo("radius",d,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusTransition,this._framingTime,(function(){a.stopAllAnimations(),n&&n(),a._attachedCamera&&a._attachedCamera.useInputToRestoreState&&a._attachedCamera.storeState()})))&&this._animatables.push(h),!0},e.prototype._calculateLowerRadiusFromModelBoundingSphere=function(t,i){var r=this._attachedCamera;if(!r)return 0;var n=r._calculateLowerRadiusFromModelBoundingSphere(t,i,this._radiusScale);return r.lowerRadiusLimit&&this._mode===e.IgnoreBoundsSizeMode&&(n=n<r.lowerRadiusLimit?r.lowerRadiusLimit:n),r.upperRadiusLimit&&(n=n>r.upperRadiusLimit?r.upperRadiusLimit:n),n},e.prototype._maintainCameraAboveGround=function(){var t=this;if(!(this._elevationReturnTime<0)){var i=_t.Now-this._lastInteractionTime,r=.5*Math.PI-this._defaultElevation,n=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>n&&i>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=at.CreateAnimation("beta",at.ANIMATIONTYPE_FLOAT,60,e.EasingFunction));var o=at.TransitionTo("beta",r,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,(function(){t._clearAnimationLocks(),t.stopAllAnimations()}));o&&this._animatables.push(o)}}},e.prototype._clearAnimationLocks=function(){this._betaIsAnimating=!1},e.prototype._applyUserInteraction=function(){this.isUserIsMoving&&(this._lastInteractionTime=_t.Now,this.stopAllAnimations(),this._clearAnimationLocks())},e.prototype.stopAllAnimations=function(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()},Object.defineProperty(e.prototype,"isUserIsMoving",{get:function(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)},enumerable:!1,configurable:!0}),e.EasingFunction=new Nn,e.EasingMode=Rn.EASINGMODE_EASEINOUT,e.IgnoreBoundsSizeMode=0,e.FitFrustumSidesMode=1,e}(),ls=function(e,t,i,r){void 0===t&&(t=new V),void 0===i&&(i=0),void 0===r&&(r=!1),this.direction=e,this.rotatedDirection=t,this.diff=i,this.ignore=r},cs=function(){function e(e){this._ui=e,this.name="AttachToBoxBehavior",this.distanceAwayFromFace=.15,this.distanceAwayFromBottomOfFace=.15,this._faceVectors=[new ls(V.Up()),new ls(V.Down()),new ls(V.Left()),new ls(V.Right()),new ls(V.Forward()),new ls(V.Forward().scaleInPlace(-1))],this._tmpMatrix=new z,this._tmpVector=new V,this._zeroVector=V.Zero(),this._lookAtTmpMatrix=new z}return e.prototype.init=function(){},e.prototype._closestFace=function(e){var t=this;return this._faceVectors.forEach((function(i){t._target.rotationQuaternion||(t._target.rotationQuaternion=G.RotationYawPitchRoll(t._target.rotation.y,t._target.rotation.x,t._target.rotation.z)),t._target.rotationQuaternion.toRotationMatrix(t._tmpMatrix),V.TransformCoordinatesToRef(i.direction,t._tmpMatrix,i.rotatedDirection),i.diff=V.GetAngleBetweenVectors(i.rotatedDirection,e,V.Cross(i.rotatedDirection,e))})),this._faceVectors.reduce((function(e,t){return e.ignore?t:t.ignore||e.diff<t.diff?e:t}),this._faceVectors[0])},e.prototype._lookAtToRef=function(e,t,i){void 0===t&&(t=new V(0,1,0)),z.LookAtLHToRef(this._zeroVector,e,t,this._lookAtTmpMatrix),this._lookAtTmpMatrix.invert(),G.FromRotationMatrixToRef(this._lookAtTmpMatrix,i)},e.prototype.attach=function(e){var t=this;this._target=e,this._scene=this._target.getScene(),this._onRenderObserver=this._scene.onBeforeRenderObservable.add((function(){if(t._scene.activeCamera){var i=t._scene.activeCamera.position;t._scene.activeCamera.devicePosition&&(i=t._scene.activeCamera.devicePosition);var r=t._closestFace(i.subtract(e.position));t._scene.activeCamera.leftCamera?t._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(t._tmpMatrix):t._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(t._tmpMatrix),V.TransformCoordinatesToRef(V.Up(),t._tmpMatrix,t._tmpVector),t._faceVectors.forEach((function(e){r.direction.x&&e.direction.x&&(e.ignore=!0),r.direction.y&&e.direction.y&&(e.ignore=!0),r.direction.z&&e.direction.z&&(e.ignore=!0)}));var n=t._closestFace(t._tmpVector);t._faceVectors.forEach((function(e){e.ignore=!1})),t._ui.position.copyFrom(e.position),r.direction.x&&(r.rotatedDirection.scaleToRef(e.scaling.x/2+t.distanceAwayFromFace,t._tmpVector),t._ui.position.addInPlace(t._tmpVector)),r.direction.y&&(r.rotatedDirection.scaleToRef(e.scaling.y/2+t.distanceAwayFromFace,t._tmpVector),t._ui.position.addInPlace(t._tmpVector)),r.direction.z&&(r.rotatedDirection.scaleToRef(e.scaling.z/2+t.distanceAwayFromFace,t._tmpVector),t._ui.position.addInPlace(t._tmpVector)),t._ui.rotationQuaternion||(t._ui.rotationQuaternion=G.RotationYawPitchRoll(t._ui.rotation.y,t._ui.rotation.x,t._ui.rotation.z)),r.rotatedDirection.scaleToRef(-1,t._tmpVector),t._lookAtToRef(t._tmpVector,n.rotatedDirection,t._ui.rotationQuaternion),n.direction.x&&t._ui.up.scaleToRef(t.distanceAwayFromBottomOfFace-e.scaling.x/2,t._tmpVector),n.direction.y&&t._ui.up.scaleToRef(t.distanceAwayFromBottomOfFace-e.scaling.y/2,t._tmpVector),n.direction.z&&t._ui.up.scaleToRef(t.distanceAwayFromBottomOfFace-e.scaling.z/2,t._tmpVector),t._ui.position.addInPlace(t._tmpVector)}}))},e.prototype.detach=function(){this._scene.onBeforeRenderObservable.remove(this._onRenderObserver)},e}(),us=function(){function e(){var e=this;this.fadeInDelay=0,this.fadeOutDelay=0,this.fadeInTime=300,this.fadeOutTime=300,this._millisecondsPerFrame=1e3/60,this._hovered=!1,this._hoverValue=0,this._ownerNode=null,this._delay=0,this._time=300,this._update=function(){if(e._ownerNode){if(e._hoverValue+=e._hovered?e._millisecondsPerFrame:-e._millisecondsPerFrame,e._setAllVisibility(e._ownerNode,(e._hoverValue-e._delay)/e._time),e._ownerNode.visibility>1){if(e._setAllVisibility(e._ownerNode,1),e._hoverValue>e._time)return e._hoverValue=e._time,void e._detachObserver()}else if(e._ownerNode.visibility<0&&(e._setAllVisibility(e._ownerNode,0),e._hoverValue<0))return e._hoverValue=0,void e._detachObserver();e._attachObserver()}}}return Object.defineProperty(e.prototype,"delay",{get:function(){return this.fadeInDelay},set:function(e){this.fadeInDelay=e,this.fadeOutDelay=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"name",{get:function(){return"FadeInOut"},enumerable:!1,configurable:!0}),e.prototype.init=function(){},e.prototype.attach=function(e){this._ownerNode=e,this._setAllVisibility(this._ownerNode,0)},e.prototype.detach=function(){this._ownerNode=null},e.prototype.fadeIn=function(e){void 0===e&&(e=!0),this._delay=e?this.fadeInDelay:this.fadeOutDelay,this._time=e?this.fadeInTime:this.fadeOutTime,this._detachObserver(),this._ownerNode&&(e&&this._ownerNode.visibility>=1||!e&&this._ownerNode.visibility<=0)||(this._hovered=e,this._hovered||(this._delay*=-1),this._ownerNode.visibility>=1?this._hoverValue=this._time:this._ownerNode.visibility<=0&&(this._hoverValue=0),this._update())},e.prototype.fadeOut=function(){this.fadeIn(!1)},e.prototype._setAllVisibility=function(e,t){var i=this;e.visibility=t,e.getChildMeshes().forEach((function(e){i._setAllVisibility(e,t)}))},e.prototype._attachObserver=function(){var e;this._onBeforeRenderObserver||(this._onBeforeRenderObserver=null===(e=this._ownerNode)||void 0===e?void 0:e.getScene().onBeforeRenderObservable.add(this._update))},e.prototype._detachObserver=function(){var e;this._onBeforeRenderObserver&&(null===(e=this._ownerNode)||void 0===e||e.getScene().onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=null)},e}(),hs=function(){function e(e,t,i,r){void 0===i&&(i=Number.MAX_VALUE),void 0===r&&(r=A),this.origin=e,this.direction=t,this.length=i,this.epsilon=r}return e.prototype.clone=function(){return new e(this.origin.clone(),this.direction.clone(),this.length)},e.prototype.intersectsBoxMinMax=function(t,i,r){void 0===r&&(r=0);var n,o,a,s,l=e._TmpVector3[0].copyFromFloats(t.x-r,t.y-r,t.z-r),c=e._TmpVector3[1].copyFromFloats(i.x+r,i.y+r,i.z+r),u=0,h=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<l.x||this.origin.x>c.x)return!1}else if(n=1/this.direction.x,o=(l.x-this.origin.x)*n,(a=(c.x-this.origin.x)*n)==-1/0&&(a=1/0),o>a&&(s=o,o=a,a=s),(u=Math.max(o,u))>(h=Math.min(a,h)))return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<l.y||this.origin.y>c.y)return!1}else if(n=1/this.direction.y,o=(l.y-this.origin.y)*n,(a=(c.y-this.origin.y)*n)==-1/0&&(a=1/0),o>a&&(s=o,o=a,a=s),(u=Math.max(o,u))>(h=Math.min(a,h)))return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<l.z||this.origin.z>c.z)return!1}else if(n=1/this.direction.z,o=(l.z-this.origin.z)*n,(a=(c.z-this.origin.z)*n)==-1/0&&(a=1/0),o>a&&(s=o,o=a,a=s),(u=Math.max(o,u))>(h=Math.min(a,h)))return!1;return!0},e.prototype.intersectsBox=function(e,t){return void 0===t&&(t=0),this.intersectsBoxMinMax(e.minimum,e.maximum,t)},e.prototype.intersectsSphere=function(e,t){void 0===t&&(t=0);var i=e.center.x-this.origin.x,r=e.center.y-this.origin.y,n=e.center.z-this.origin.z,o=i*i+r*r+n*n,a=e.radius+t,s=a*a;if(o<=s)return!0;var l=i*this.direction.x+r*this.direction.y+n*this.direction.z;return!(l<0)&&o-l*l<=s},e.prototype.intersectsTriangle=function(t,i,r){var n=e._TmpVector3[0],o=e._TmpVector3[1],a=e._TmpVector3[2],s=e._TmpVector3[3],l=e._TmpVector3[4];i.subtractToRef(t,n),r.subtractToRef(t,o),V.CrossToRef(this.direction,o,a);var c=V.Dot(n,a);if(0===c)return null;var u=1/c;this.origin.subtractToRef(t,s);var h=V.Dot(s,a)*u;if(h<-this.epsilon||h>1+this.epsilon)return null;V.CrossToRef(s,n,l);var d=V.Dot(this.direction,l)*u;if(d<-this.epsilon||h+d>1+this.epsilon)return null;var p=V.Dot(o,l)*u;return p>this.length?null:new eo(1-h-d,h,p)},e.prototype.intersectsPlane=function(e){var t,i=V.Dot(e.normal,this.direction);if(Math.abs(i)<9.99999997475243e-7)return null;var r=V.Dot(e.normal,this.origin);return(t=(-e.d-r)/i)<0?t<-9.99999997475243e-7?null:0:t},e.prototype.intersectsAxis=function(e,t){switch(void 0===t&&(t=0),e){case"y":return(i=(this.origin.y-t)/this.direction.y)>0?null:new V(this.origin.x+this.direction.x*-i,t,this.origin.z+this.direction.z*-i);case"x":return(i=(this.origin.x-t)/this.direction.x)>0?null:new V(t,this.origin.y+this.direction.y*-i,this.origin.z+this.direction.z*-i);case"z":var i;return(i=(this.origin.z-t)/this.direction.z)>0?null:new V(this.origin.x+this.direction.x*-i,this.origin.y+this.direction.y*-i,t);default:return null}},e.prototype.intersectsMesh=function(t,i,r,n,o,a){void 0===n&&(n=!1),void 0===a&&(a=!1);var s=H.Matrix[0];return t.getWorldMatrix().invertToRef(s),this._tmpRay?e.TransformToRef(this,s,this._tmpRay):this._tmpRay=e.Transform(this,s),t.intersects(this._tmpRay,i,r,n,o,a)},e.prototype.intersectsMeshes=function(e,t,i){i?i.length=0:i=[];for(var r=0;r<e.length;r++){var n=this.intersectsMesh(e[r],t);n.hit&&i.push(n)}return i.sort(this._comparePickingInfo),i},e.prototype._comparePickingInfo=function(e,t){return e.distance<t.distance?-1:e.distance>t.distance?1:0},e.prototype.intersectionSegment=function(t,i,r){var n=this.origin,o=H.Vector3[0],a=H.Vector3[1],s=H.Vector3[2],l=H.Vector3[3];i.subtractToRef(t,o),this.direction.scaleToRef(e._Rayl,s),n.addToRef(s,a),t.subtractToRef(n,l);var c,u,h=V.Dot(o,o),d=V.Dot(o,s),p=V.Dot(s,s),f=V.Dot(o,l),_=V.Dot(s,l),m=h*p-d*d,g=m,v=m;m<e._Smallnum?(c=0,g=1,u=_,v=p):(u=h*_-d*f,(c=d*_-p*f)<0?(c=0,u=_,v=p):c>g&&(c=g,u=_+d,v=p)),u<0?(u=0,-f<0?c=0:-f>h?c=g:(c=-f,g=h)):u>v&&(u=v,-f+d<0?c=0:-f+d>h?c=g:(c=-f+d,g=h));var y=Math.abs(c)<e._Smallnum?0:c/g,b=Math.abs(u)<e._Smallnum?0:u/v,T=H.Vector3[4];s.scaleToRef(b,T);var E=H.Vector3[5];o.scaleToRef(y,E),E.addInPlace(l);var S=H.Vector3[6];return E.subtractToRef(T,S),b>0&&b<=this.length&&S.lengthSquared()<r*r?E.length():-1},e.prototype.update=function(t,i,r,n,o,a,s,l){if(void 0===l&&(l=!1),l){e._RayDistant||(e._RayDistant=e.Zero()),e._RayDistant.unprojectRayToRef(t,i,r,n,z.IdentityReadOnly,a,s);var c=H.Matrix[0];o.invertToRef(c),e.TransformToRef(e._RayDistant,c,this)}else this.unprojectRayToRef(t,i,r,n,o,a,s);return this},e.Zero=function(){return new e(V.Zero(),V.Zero())},e.CreateNew=function(t,i,r,n,o,a,s){return e.Zero().update(t,i,r,n,o,a,s)},e.CreateNewFromTo=function(t,i,r){void 0===r&&(r=z.IdentityReadOnly);var n=new e(new V(0,0,0),new V(0,0,0));return e.CreateFromToToRef(t,i,n,r)},e.CreateFromToToRef=function(t,i,r,n){void 0===n&&(n=z.IdentityReadOnly),r.origin.copyFrom(t);var o=i.subtractToRef(t,r.direction),a=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return r.length=a,r.direction.normalize(),e.TransformToRef(r,n,r)},e.Transform=function(t,i){var r=new e(new V(0,0,0),new V(0,0,0));return e.TransformToRef(t,i,r),r},e.TransformToRef=function(e,t,i){V.TransformCoordinatesToRef(e.origin,t,i.origin),V.TransformNormalToRef(e.direction,t,i.direction),i.length=e.length,i.epsilon=e.epsilon;var r=i.direction,n=r.length();if(0!==n&&1!==n){var o=1/n;r.x*=o,r.y*=o,r.z*=o,i.length*=n}return i},e.prototype.unprojectRayToRef=function(e,t,i,r,n,o,a){var s=H.Matrix[0];n.multiplyToRef(o,s),s.multiplyToRef(a,s),s.invert();var l=M.LastCreatedEngine,c=H.Vector3[0];c.x=e/i*2-1,c.y=-(t/r*2-1),c.z=(null==l?void 0:l.useReverseDepthBuffer)?1:(null==l?void 0:l.isNDCHalfZRange)?0:-1;var u=H.Vector3[1].copyFromFloats(c.x,c.y,1-1e-8),h=H.Vector3[2],d=H.Vector3[3];V._UnprojectFromInvertedMatrixToRef(c,s,h),V._UnprojectFromInvertedMatrixToRef(u,s,d),this.origin.copyFrom(h),d.subtractToRef(h,this.direction),this.direction.normalize()},e._TmpVector3=C.BuildArray(6,V.Zero),e._RayDistant=e.Zero(),e._Smallnum=1e-8,e._Rayl=1e9,e}();pn.prototype.createPickingRay=function(e,t,i,r,n){void 0===n&&(n=!1);var o=hs.Zero();return this.createPickingRayToRef(e,t,i,o,r,n),o},pn.prototype.createPickingRayToRef=function(e,t,i,r,n,o,a){void 0===o&&(o=!1),void 0===a&&(a=!1);var s=this.getEngine();if(!n&&!(n=this.activeCamera))return this;var l=n.viewport,c=s.getRenderHeight(),u=l.toGlobal(s.getRenderWidth(),c),h=u.x,d=u.y,p=u.width,f=u.height,_=1/s.getHardwareScalingLevel();return e=e*_-h,t=t*_-(c-d-f),r.update(e,t,p,f,i||z.IdentityReadOnly,o?z.IdentityReadOnly:n.getViewMatrix(),n.getProjectionMatrix(),a),this},pn.prototype.createPickingRayInCameraSpace=function(e,t,i){var r=hs.Zero();return this.createPickingRayInCameraSpaceToRef(e,t,r,i),r},pn.prototype.createPickingRayInCameraSpaceToRef=function(e,t,i,r){if(!Fr)return this;var n=this.getEngine();if(!r&&!(r=this.activeCamera))throw new Error("Active camera not set");var o=r.viewport,a=n.getRenderHeight(),s=o.toGlobal(n.getRenderWidth(),a),l=s.x,c=s.y,u=s.width,h=s.height,d=z.Identity(),p=1/n.getHardwareScalingLevel();return e=e*p-l,t=t*p-(a-c-h),i.update(e,t,u,h,d,d,r.getProjectionMatrix()),this},pn.prototype._internalPickForMesh=function(e,t,i,r,n,o,a,s){var l=t(r,i.enableDistantPicking),c=i.intersects(l,n,a,o,r,s);return c&&c.hit?!n&&null!=e&&c.distance>=e.distance?null:c:null},pn.prototype._internalPick=function(e,t,i,r,n){for(var o=null,a=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),s=this.cameraToUseForPointers||this.activeCamera,l=0;l<this.meshes.length;l++){var c=this.meshes[l];if(t){if(!t(c))continue}else if(!c.isEnabled()||!c.isVisible||!c.isPickable)continue;var u,h=a&&c.isWorldMatrixCameraDependent(),d=c.computeWorldMatrix(h,s);if(c.hasThinInstances&&c.thinInstanceEnablePicking){if(u=this._internalPickForMesh(o,e,c,d,!0,!0,n)){if(r)return u;for(var p=H.Matrix[1],f=c.thinInstanceGetWorldMatrices(),_=0;_<f.length;_++){f[_].multiplyToRef(d,p);var m=this._internalPickForMesh(o,e,c,p,i,r,n,!0);if(m&&((o=m).thinInstanceIndex=_,i))return o}}}else if((u=this._internalPickForMesh(o,e,c,d,i,r,n))&&(o=u,i))return o}return o||new Fr},pn.prototype._internalMultiPick=function(e,t,i){if(!Fr)return null;for(var r=[],n=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),o=this.cameraToUseForPointers||this.activeCamera,a=0;a<this.meshes.length;a++){var s=this.meshes[a];if(t){if(!t(s))continue}else if(!s.isEnabled()||!s.isVisible||!s.isPickable)continue;var l,c=n&&s.isWorldMatrixCameraDependent(),u=s.computeWorldMatrix(c,o);if(s.hasThinInstances&&s.thinInstanceEnablePicking){if(l=this._internalPickForMesh(null,e,s,u,!0,!0,i))for(var h=H.Matrix[1],d=s.thinInstanceGetWorldMatrices(),p=0;p<d.length;p++){d[p].multiplyToRef(u,h);var f=this._internalPickForMesh(null,e,s,h,!1,!1,i,!0);f&&(f.thinInstanceIndex=p,r.push(f))}}else(l=this._internalPickForMesh(null,e,s,u,!1,!1,i))&&r.push(l)}return r},pn.prototype.pickWithBoundingInfo=function(e,t,i,r,n){var o=this;if(!Fr)return null;var a=this._internalPick((function(i){return o._tempPickingRay||(o._tempPickingRay=hs.Zero()),o.createPickingRayToRef(e,t,i,o._tempPickingRay,n||null),o._tempPickingRay}),i,r,!0);return a&&(a.ray=this.createPickingRay(e,t,z.Identity(),n||null)),a},Object.defineProperty(pn.prototype,"_pickingAvailable",{get:function(){return!0},enumerable:!1,configurable:!1}),pn.prototype.pick=function(e,t,i,r,n,o,a){var s=this;void 0===a&&(a=!1);var l=this._internalPick((function(i,r){return s._tempPickingRay||(s._tempPickingRay=hs.Zero()),s.createPickingRayToRef(e,t,i,s._tempPickingRay,n||null,!1,r),s._tempPickingRay}),i,r,!1,o);return l&&(l.ray=this.createPickingRay(e,t,z.Identity(),n||null)),l},pn.prototype.pickWithRay=function(e,t,i,r){var n=this,o=this._internalPick((function(t){return n._pickWithRayInverseMatrix||(n._pickWithRayInverseMatrix=z.Identity()),t.invertToRef(n._pickWithRayInverseMatrix),n._cachedRayForTransform||(n._cachedRayForTransform=hs.Zero()),hs.TransformToRef(e,n._pickWithRayInverseMatrix,n._cachedRayForTransform),n._cachedRayForTransform}),t,i,!1,r);return o&&(o.ray=e),o},pn.prototype.multiPick=function(e,t,i,r,n){var o=this;return this._internalMultiPick((function(i){return o.createPickingRay(e,t,i,r||null)}),i,n)},pn.prototype.multiPickWithRay=function(e,t,i){var r=this;return this._internalMultiPick((function(t){return r._pickWithRayInverseMatrix||(r._pickWithRayInverseMatrix=z.Identity()),t.invertToRef(r._pickWithRayInverseMatrix),r._cachedRayForTransform||(r._cachedRayForTransform=hs.Zero()),hs.TransformToRef(e,r._pickWithRayInverseMatrix,r._cachedRayForTransform),r._cachedRayForTransform}),t,i)},$n.prototype.getForwardRay=function(e,t,i){return void 0===e&&(e=100),this.getForwardRayToRef(new hs(V.Zero(),V.Zero(),e),e,t,i)},$n.prototype.getForwardRayToRef=function(e,t,i,r){void 0===t&&(t=100),i||(i=this.getWorldMatrix()),e.length=t,r?e.origin.copyFrom(r):e.origin.copyFrom(this.position);var n=H.Vector3[2];n.set(0,0,this._scene.useRightHandedSystem?-1:1);var o=H.Vector3[3];return V.TransformNormalToRef(n,i,o),V.NormalizeToRef(o,e.direction),e};var ds=function(){function e(){}return e._RemoveAndStorePivotPoint=function(t){t&&0===e._PivotCached&&(t.getPivotPointToRef(e._OldPivotPoint),e._PivotPostMultiplyPivotMatrix=t._postMultiplyPivotMatrix,e._OldPivotPoint.equalsToFloats(0,0,0)||(t.setPivotMatrix(z.IdentityReadOnly),e._OldPivotPoint.subtractToRef(t.getPivotPoint(),e._PivotTranslation),e._PivotTmpVector.copyFromFloats(1,1,1),e._PivotTmpVector.subtractInPlace(t.scaling),e._PivotTmpVector.multiplyInPlace(e._PivotTranslation),t.position.addInPlace(e._PivotTmpVector))),e._PivotCached++},e._RestorePivotPoint=function(t){t&&!e._OldPivotPoint.equalsToFloats(0,0,0)&&1===e._PivotCached&&(t.setPivotPoint(e._OldPivotPoint),t._postMultiplyPivotMatrix=e._PivotPostMultiplyPivotMatrix,e._PivotTmpVector.copyFromFloats(1,1,1),e._PivotTmpVector.subtractInPlace(t.scaling),e._PivotTmpVector.multiplyInPlace(e._PivotTranslation),t.position.subtractInPlace(e._PivotTmpVector)),this._PivotCached--},e._PivotCached=0,e._OldPivotPoint=new V,e._PivotTranslation=new V,e._PivotTmpVector=new V,e._PivotPostMultiplyPivotMatrix=!1,e}();function ps(e){var t=[],i=[],r=[],n=[],o=e.width||e.size||1,a=e.height||e.size||1,s=0===e.sideOrientation?0:e.sideOrientation||_o.DEFAULTSIDE,l=o/2,c=a/2;i.push(-l,-c,0),r.push(0,0,-1),n.push(0,go.UseOpenGLOrientationForUV?1:0),i.push(l,-c,0),r.push(0,0,-1),n.push(1,go.UseOpenGLOrientationForUV?1:0),i.push(l,c,0),r.push(0,0,-1),n.push(1,go.UseOpenGLOrientationForUV?0:1),i.push(-l,c,0),r.push(0,0,-1),n.push(0,go.UseOpenGLOrientationForUV?0:1),t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),_o._ComputeSides(s,i,t,r,n,e.frontUVs,e.backUVs);var u=new _o;return u.indices=t,u.positions=i,u.normals=r,u.uvs=n,u}function fs(e,t,i){void 0===t&&(t={}),void 0===i&&(i=null);var r=new Fa(e,i);return t.sideOrientation=Fa._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,ps(t).applyToMesh(r,t.updatable),t.sourcePlane&&(r.translate(t.sourcePlane.normal,-t.sourcePlane.d),r.setDirection(t.sourcePlane.normal.scale(-1))),r}var _s={CreatePlane:fs};_o.CreatePlane=ps,Fa.CreatePlane=function(e,t,i,r,n){return fs(e,{size:t,width:t,height:t,sideOrientation:n,updatable:r},i)};var ms,gs=function(){function e(e){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this._activeDragButton=-1,this.maxDragAngle=0,this.dragButtons=[0,1,2],this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerId=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new f,this.onDragStartObservable=new f,this.onDragEndObservable=new f,this.onEnabledObservable=new f,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=function(e){return!0},this._tmpVector=new V(0,0,0),this._alternatePickedPoint=new V(0,0,0),this._worldDragAxis=new V(0,0,0),this._targetPosition=new V(0,0,0),this._attachedToElement=!1,this._startDragRay=new hs(new V,new V),this._lastPointerRay={},this._dragDelta=new V,this._pointA=new V(0,0,0),this._pointC=new V(0,0,0),this._localAxis=new V(0,0,0),this._lookAt=new V(0,0,0),this._options=e||{};var t=0;if(this._options.dragAxis&&t++,this._options.dragPlaneNormal&&t++,t>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}return Object.defineProperty(e.prototype,"currentDraggingPointerID",{get:function(){return this.currentDraggingPointerId},set:function(e){this.currentDraggingPointerId=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"enabled",{get:function(){return this._enabled},set:function(e){e!=this._enabled&&this.onEnabledObservable.notifyObservers(e),this._enabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"options",{get:function(){return this._options},set:function(e){this._options=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"name",{get:function(){return"PointerDrag"},enumerable:!1,configurable:!0}),e.prototype.init=function(){},e.prototype.attach=function(t,i){var r=this;this._scene=t.getScene(),t.isNearGrabbable=!0,this.attachedNode=t,e._PlaneScene||(this._debugMode?e._PlaneScene=this._scene:(e._PlaneScene=new pn(this._scene.getEngine(),{virtual:!0}),e._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce((function(){e._PlaneScene.dispose(),e._PlaneScene=null})))),this._dragPlane=fs("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:Fa.DOUBLESIDE},e._PlaneScene),this.lastDragPosition=new V(0,0,0);var n=i||function(e){return r.attachedNode==e||e.isDescendantOf(r.attachedNode)};this._pointerObserver=this._scene.onPointerObservable.add((function(t){if(r.enabled){if(t.type==Gr.POINTERDOWN)r.startAndReleaseDragOnPointerEvents&&!r.dragging&&t.pickInfo&&t.pickInfo.hit&&t.pickInfo.pickedMesh&&t.pickInfo.pickedPoint&&t.pickInfo.ray&&n(t.pickInfo.pickedMesh)&&-1===r._activeDragButton&&-1!==r.dragButtons.indexOf(t.event.button)&&(r._activeDragButton=t.event.button,r._activePointerInfo=t,r._startDrag(t.event.pointerId,t.pickInfo.ray,t.pickInfo.pickedPoint));else if(t.type==Gr.POINTERUP)!r.startAndReleaseDragOnPointerEvents||r.currentDraggingPointerId!=t.event.pointerId||r._activeDragButton!==t.event.button&&-1!==r._activeDragButton||r.releaseDrag();else if(t.type==Gr.POINTERMOVE){var i=t.event.pointerId;if(r.currentDraggingPointerId===e._AnyMouseId&&i!==e._AnyMouseId){var o=t.event;("mouse"===o.pointerType||!r._scene.getEngine().hostInformation.isMobile&&o instanceof MouseEvent)&&(r._lastPointerRay[r.currentDraggingPointerId]&&(r._lastPointerRay[i]=r._lastPointerRay[r.currentDraggingPointerId],delete r._lastPointerRay[r.currentDraggingPointerId]),r.currentDraggingPointerId=i)}r._lastPointerRay[i]||(r._lastPointerRay[i]=new hs(new V,new V)),t.pickInfo&&t.pickInfo.ray&&(r._lastPointerRay[i].origin.copyFrom(t.pickInfo.ray.origin),r._lastPointerRay[i].direction.copyFrom(t.pickInfo.ray.direction),r.currentDraggingPointerId==i&&r.dragging&&r._moveDrag(t.pickInfo.ray))}}else r._attachedToElement&&r.releaseDrag()})),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add((function(){if(r._moving&&r.moveAttached){var e=!1;ds._RemoveAndStorePivotPoint(r.attachedNode),r._targetPosition.subtractToRef(r.attachedNode.absolutePosition,r._tmpVector),r._tmpVector.scaleInPlace(r.dragDeltaRatio),r.attachedNode.getAbsolutePosition().addToRef(r._tmpVector,r._tmpVector),r.validateDrag(r._tmpVector)&&(r.attachedNode.setAbsolutePosition(r._tmpVector),e=!0),ds._RestorePivotPoint(r.attachedNode),e&&r.attachedNode.computeWorldMatrix()}}))},e.prototype.releaseDrag=function(){if(this.dragging&&(this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo})),this.currentDraggingPointerId=-1,this._activeDragButton=-1,this._activePointerInfo=null,this._moving=!1,this.detachCameraControls&&this._attachedToElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera){if("ArcRotateCamera"===this._scene.activeCamera.getClassName()){var e=this._scene.activeCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._scene.activeCamera.attachControl(!this._scene.activeCamera.inputs||this._scene.activeCamera.inputs.noPreventDefault);this._attachedToElement=!1}},e.prototype.startDrag=function(t,i,r){void 0===t&&(t=e._AnyMouseId),this._startDrag(t,i,r);var n=this._lastPointerRay[t];t===e._AnyMouseId&&(n=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),n&&this._moveDrag(n)},e.prototype._startDrag=function(e,t,i){if(this._scene.activeCamera&&!this.dragging&&this.attachedNode){ds._RemoveAndStorePivotPoint(this.attachedNode),t?(this._startDragRay.direction.copyFrom(t.direction),this._startDragRay.origin.copyFrom(t.origin)):(this._startDragRay.origin.copyFrom(this._scene.activeCamera.position),this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector),this._tmpVector.subtractToRef(this._scene.activeCamera.position,this._startDragRay.direction)),this._updateDragPlanePosition(this._startDragRay,i||this._tmpVector);var r=this._pickWithRayOnDragPlane(this._startDragRay);r?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(r),this.onDragStartObservable.notifyObservers({dragPlanePoint:r,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)):this.releaseDrag(),ds._RestorePivotPoint(this.attachedNode)}},e.prototype._moveDrag=function(e){this._moving=!0;var t=this._pickWithRayOnDragPlane(e);if(t){ds._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);var i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?V.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=V.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(i,this._dragDelta)):(i=this._dragDelta.length(),t.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:i,delta:this._dragDelta,dragPlanePoint:t,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this.lastDragPosition.copyFrom(t),ds._RestorePivotPoint(this.attachedNode)}},e.prototype._pickWithRayOnDragPlane=function(e){if(!e)return null;var t=Math.acos(V.Dot(this._dragPlane.forward,e.direction));if(t>Math.PI/2&&(t=Math.PI-t),this.maxDragAngle>0&&t>this.maxDragAngle){if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(e.direction),this.attachedNode.absolutePosition.subtractToRef(e.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*V.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);var i=V.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-i,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}return null}var r=this._dragPlane.forward,n=this._dragPlane.position,o=e.direction.dot(r);if(Math.abs(o)<A)return null;n.subtractToRef(e.origin,H.Vector3[0]);var a=H.Vector3[0].dot(r)/o;return a<0?null:(e.direction.scaleToRef(a,H.Vector3[0]),e.origin.add(H.Vector3[0]))},e.prototype._updateDragPlanePosition=function(e,t){this._pointA.copyFrom(t),this._options.dragAxis?(this.useObjectOrientationForDragging?V.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragAxis),e.origin.subtractToRef(this._pointA,this._pointC),this._pointC.normalize(),Math.abs(V.Dot(this._localAxis,this._pointC))>.999?Math.abs(V.Dot(V.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(V.Right()):this._lookAt.copyFrom(V.UpReadOnly):(V.CrossToRef(this._localAxis,this._pointC,this._lookAt),V.CrossToRef(this._localAxis,this._lookAt,this._lookAt),this._lookAt.normalize()),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrientationForDragging?V.TransformCoordinatesToRef(this._options.dragPlaneNormal,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(e.origin)),this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition()),this._dragPlane.computeWorldMatrix(!0)},e.prototype.detach=function(){this._lastPointerRay={},this.attachedNode&&(this.attachedNode.isNearGrabbable=!1),this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this._dragPlane&&this._dragPlane.dispose(),this.releaseDrag()},e._AnyMouseId=-2,e}(),vs=function(){function e(){this._startDistance=0,this._initialScale=new V(0,0,0),this._targetScale=new V(0,0,0),this._sceneRenderObserver=null,this._dragBehaviorA=new gs({}),this._dragBehaviorA.moveAttached=!1,this._dragBehaviorB=new gs({}),this._dragBehaviorB.moveAttached=!1}return Object.defineProperty(e.prototype,"name",{get:function(){return"MultiPointerScale"},enumerable:!1,configurable:!0}),e.prototype.init=function(){},e.prototype._getCurrentDistance=function(){return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length()},e.prototype.attach=function(e){var t=this;this._ownerNode=e,this._dragBehaviorA.onDragStartObservable.add((function(){t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging&&(t._dragBehaviorA.currentDraggingPointerId==t._dragBehaviorB.currentDraggingPointerId?t._dragBehaviorA.releaseDrag():(t._initialScale.copyFrom(e.scaling),t._startDistance=t._getCurrentDistance()))})),this._dragBehaviorB.onDragStartObservable.add((function(){t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging&&(t._dragBehaviorA.currentDraggingPointerId==t._dragBehaviorB.currentDraggingPointerId?t._dragBehaviorB.releaseDrag():(t._initialScale.copyFrom(e.scaling),t._startDistance=t._getCurrentDistance()))})),[this._dragBehaviorA,this._dragBehaviorB].forEach((function(e){e.onDragObservable.add((function(){if(t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging){var e=t._getCurrentDistance()/t._startDistance;t._initialScale.scaleToRef(e,t._targetScale)}}))})),e.addBehavior(this._dragBehaviorA),e.addBehavior(this._dragBehaviorB),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add((function(){if(t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging){var i=t._targetScale.subtract(e.scaling).scaleInPlace(.1);i.length()>.01&&e.scaling.addInPlace(i)}}))},e.prototype.detach=function(){var e=this;this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),[this._dragBehaviorA,this._dragBehaviorB].forEach((function(t){t.onDragStartObservable.clear(),t.onDragObservable.clear(),e._ownerNode.removeBehavior(t)}))},e}(),ys=function(){function e(){this._attachedToElement=!1,this._virtualMeshesInfo={},this._tmpVector=new V,this._tmpQuaternion=new G,this._dragType={NONE:0,DRAG:1,DRAG_WITH_CONTROLLER:2,NEAR_DRAG:3},this._moving=!1,this._dragging=this._dragType.NONE,this.draggableMeshes=null,this.zDragFactor=3,this.currentDraggingPointerIds=[],this.detachCameraControls=!0,this.onDragStartObservable=new f,this.onDragObservable=new f,this.onDragEndObservable=new f,this.allowMultiPointer=!0}return Object.defineProperty(e.prototype,"currentDraggingPointerId",{get:function(){return void 0!==this.currentDraggingPointerIds[0]?this.currentDraggingPointerIds[0]:-1},set:function(e){this.currentDraggingPointerIds[0]=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentDraggingPointerID",{get:function(){return this.currentDraggingPointerId},set:function(e){this.currentDraggingPointerId=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"name",{get:function(){return"BaseSixDofDrag"},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isMoving",{get:function(){return this._moving},enumerable:!1,configurable:!0}),e.prototype.init=function(){},Object.defineProperty(e.prototype,"_pointerCamera",{get:function(){return this._scene.cameraToUseForPointers?this._scene.cameraToUseForPointers:this._scene.activeCamera},enumerable:!1,configurable:!0}),e.prototype._createVirtualMeshInfo=function(){var t=new Uo("",e._virtualScene);t.rotationQuaternion=new G;var i=new Uo("",e._virtualScene);i.rotationQuaternion=new G;var r=new Uo("",e._virtualScene);return r.rotationQuaternion=new G,{dragging:!1,moving:!1,dragMesh:t,originMesh:i,pivotMesh:r,startingPivotPosition:new V,startingPivotOrientation:new G,startingPosition:new V,startingOrientation:new G,lastOriginPosition:new V,lastDragPosition:new V}},e.prototype._resetVirtualMeshesPosition=function(){for(var e=0;e<this.currentDraggingPointerIds.length;e++)this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].pivotMesh.position.copyFrom(this._ownerNode.getAbsolutePivotPoint()),this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].pivotMesh.rotationQuaternion.copyFrom(this._ownerNode.rotationQuaternion),this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].startingPivotPosition.copyFrom(this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].pivotMesh.position),this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].startingPivotOrientation.copyFrom(this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].pivotMesh.rotationQuaternion),this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].startingPosition.copyFrom(this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].dragMesh.position),this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].startingOrientation.copyFrom(this._virtualMeshesInfo[this.currentDraggingPointerIds[e]].dragMesh.rotationQuaternion)},e.prototype._pointerUpdate2D=function(e,t,i){!this._pointerCamera||this._pointerCamera.cameraRigMode!=$n.RIG_MODE_NONE||this._pointerCamera._isLeftCamera||this._pointerCamera._isRightCamera||(e.origin.copyFrom(this._pointerCamera.globalPosition),i=0);var r=this._virtualMeshesInfo[t],n=H.Vector3[0];e.origin.subtractToRef(r.lastOriginPosition,n),r.lastOriginPosition.copyFrom(e.origin);var o=-V.Dot(n,e.direction);r.originMesh.addChild(r.dragMesh),r.originMesh.addChild(r.pivotMesh),this._applyZOffset(r.dragMesh,o,i),this._applyZOffset(r.pivotMesh,o,i),r.originMesh.position.copyFrom(e.origin);var a=H.Vector3[0];e.origin.addToRef(e.direction,a),r.originMesh.lookAt(a),r.originMesh.removeChild(r.dragMesh),r.originMesh.removeChild(r.pivotMesh)},e.prototype._pointerUpdateXR=function(e,t,i,r){var n=this._virtualMeshesInfo[i];if(n.originMesh.position.copyFrom(e.position),this._dragging===this._dragType.NEAR_DRAG&&t?n.originMesh.rotationQuaternion.copyFrom(t.rotationQuaternion):n.originMesh.rotationQuaternion.copyFrom(e.rotationQuaternion),n.pivotMesh.computeWorldMatrix(!0),n.dragMesh.computeWorldMatrix(!0),0!==r){var o=H.Vector3[0],a=H.Vector3[1];o.copyFrom(this._pointerCamera.getForwardRay().direction),n.originMesh.position.subtractToRef(n.lastOriginPosition,a),n.lastOriginPosition.copyFrom(n.originMesh.position);var s=a.length();a.normalize();var l=H.Vector3[2],c=H.Vector3[3];n.dragMesh.absolutePosition.subtractToRef(this._pointerCamera.globalPosition,l),n.dragMesh.absolutePosition.subtractToRef(n.originMesh.position,c);var u=c.length();l.normalize(),c.normalize();var h=Math.abs(V.Dot(a,c))*V.Dot(a,o)*r*s*u;h<0&&.01-u>h&&(h=Math.min(.01-u,0)),c.scaleInPlace(h),c.addToRef(n.pivotMesh.absolutePosition,this._tmpVector),n.pivotMesh.setAbsolutePosition(this._tmpVector),c.addToRef(n.dragMesh.absolutePosition,this._tmpVector),n.dragMesh.setAbsolutePosition(this._tmpVector)}},e.prototype.attach=function(t){var i=this;this._ownerNode=t,this._scene=this._ownerNode.getScene(),e._virtualScene||(e._virtualScene=new pn(this._scene.getEngine(),{virtual:!0}),e._virtualScene.detachControl()),this._pointerObserver=this._scene.onPointerObservable.add((function(e){var t=e.event.pointerId;i._virtualMeshesInfo[t]||(i._virtualMeshesInfo[t]=i._createVirtualMeshInfo());var r,n=i._virtualMeshesInfo[t],o="xr-near"===e.event.pointerType||"xr"===e.event.pointerType;if(e.type==Gr.POINTERDOWN){if(!n.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&(!o||e.pickInfo.aimTransform)&&(r=e.pickInfo.pickedMesh,i._ownerNode===r||r.isDescendantOf(i._ownerNode)&&(!i.draggableMeshes||-1!==i.draggableMeshes.indexOf(r)))){if((!i.allowMultiPointer||o)&&i.currentDraggingPointerIds.length>0)return;!i._pointerCamera||i._pointerCamera.cameraRigMode!==$n.RIG_MODE_NONE||i._pointerCamera._isLeftCamera||i._pointerCamera._isRightCamera||e.pickInfo.ray.origin.copyFrom(i._pointerCamera.globalPosition),i._ownerNode.computeWorldMatrix(!0);var a=i._virtualMeshesInfo[t];o?(i._dragging=e.pickInfo.originMesh?i._dragType.NEAR_DRAG:i._dragType.DRAG_WITH_CONTROLLER,a.originMesh.position.copyFrom(e.pickInfo.aimTransform.position),i._dragging===i._dragType.NEAR_DRAG&&e.pickInfo.gripTransform?a.originMesh.rotationQuaternion.copyFrom(e.pickInfo.gripTransform.rotationQuaternion):a.originMesh.rotationQuaternion.copyFrom(e.pickInfo.aimTransform.rotationQuaternion)):(i._dragging=i._dragType.DRAG,a.originMesh.position.copyFrom(e.pickInfo.ray.origin)),a.lastOriginPosition.copyFrom(a.originMesh.position),a.dragMesh.position.copyFrom(e.pickInfo.pickedPoint),a.lastDragPosition.copyFrom(e.pickInfo.pickedPoint),a.pivotMesh.position.copyFrom(i._ownerNode.getAbsolutePivotPoint()),a.pivotMesh.rotationQuaternion.copyFrom(i._ownerNode.absoluteRotationQuaternion),a.startingPosition.copyFrom(a.dragMesh.position),a.startingPivotPosition.copyFrom(a.pivotMesh.position),a.startingOrientation.copyFrom(a.dragMesh.rotationQuaternion),a.startingPivotOrientation.copyFrom(a.pivotMesh.rotationQuaternion),o?(a.originMesh.addChild(a.dragMesh),a.originMesh.addChild(a.pivotMesh)):a.originMesh.lookAt(a.dragMesh.position),a.dragging=!0,-1===i.currentDraggingPointerIds.indexOf(t)&&i.currentDraggingPointerIds.push(t),i.detachCameraControls&&i._pointerCamera&&!i._pointerCamera.leftCamera&&(i._pointerCamera.inputs&&i._pointerCamera.inputs.attachedToElement?(i._pointerCamera.detachControl(),i._attachedToElement=!0):i.allowMultiPointer&&0!==i.currentDraggingPointerIds.length||(i._attachedToElement=!1)),i._targetDragStart(a.pivotMesh.position,a.pivotMesh.rotationQuaternion,t),i.onDragStartObservable.notifyObservers({position:a.pivotMesh.position})}}else if(e.type==Gr.POINTERUP||e.type==Gr.POINTERDOUBLETAP){var s=i.currentDraggingPointerIds.indexOf(t);n.dragging=!1,-1!==s&&(i.currentDraggingPointerIds.splice(s,1),0===i.currentDraggingPointerIds.length&&(i._moving=!1,i._dragging=i._dragType.NONE,i.detachCameraControls&&i._attachedToElement&&i._pointerCamera&&!i._pointerCamera.leftCamera&&(i._reattachCameraControls(),i._attachedToElement=!1)),n.originMesh.removeChild(n.dragMesh),n.originMesh.removeChild(n.pivotMesh),i._targetDragEnd(t),i.onDragEndObservable.notifyObservers({}))}else if(e.type==Gr.POINTERMOVE&&-1!==(s=i.currentDraggingPointerIds.indexOf(t))&&n.dragging&&e.pickInfo&&(e.pickInfo.ray||e.pickInfo.aimTransform)){var l=i.zDragFactor;(i.currentDraggingPointerIds.length>1||e.pickInfo.originMesh)&&(l=0),i._ownerNode.computeWorldMatrix(!0),o?i._pointerUpdateXR(e.pickInfo.aimTransform,e.pickInfo.gripTransform,t,l):i._pointerUpdate2D(e.pickInfo.ray,t,l),i._tmpQuaternion.copyFrom(n.startingPivotOrientation),i._tmpQuaternion.x=-i._tmpQuaternion.x,i._tmpQuaternion.y=-i._tmpQuaternion.y,i._tmpQuaternion.z=-i._tmpQuaternion.z,n.pivotMesh.absoluteRotationQuaternion.multiplyToRef(i._tmpQuaternion,i._tmpQuaternion),n.pivotMesh.absolutePosition.subtractToRef(n.startingPivotPosition,i._tmpVector),i.onDragObservable.notifyObservers({delta:i._tmpVector,position:n.pivotMesh.position,pickInfo:e.pickInfo}),i._targetDrag(i._tmpVector,i._tmpQuaternion,t),n.lastDragPosition.copyFrom(n.dragMesh.absolutePosition),i._moving=!0}}))},e.prototype._applyZOffset=function(e,t,i){e.position.z-=e.position.z<1?t*i:t*i*e.position.z,e.position.z<0&&(e.position.z=0)},e.prototype._targetDragStart=function(e,t,i){},e.prototype._targetDrag=function(e,t,i){},e.prototype._targetDragEnd=function(e){},e.prototype._reattachCameraControls=function(){if(this._pointerCamera)if("ArcRotateCamera"===this._pointerCamera.getClassName()){var e=this._pointerCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._pointerCamera.attachControl(!this._pointerCamera.inputs||this._pointerCamera.inputs.noPreventDefault)},e.prototype.detach=function(){for(var e in this._scene&&(this.detachCameraControls&&this._attachedToElement&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._reattachCameraControls(),this._attachedToElement=!1),this._scene.onPointerObservable.remove(this._pointerObserver)),this._virtualMeshesInfo)this._virtualMeshesInfo[e].originMesh.dispose(),this._virtualMeshesInfo[e].dragMesh.dispose();this.onDragEndObservable.clear(),this.onDragObservable.clear(),this.onDragStartObservable.clear()},e}(),bs=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._sceneRenderObserver=null,t._targetPosition=new V(0,0,0),t._targetOrientation=new G,t._targetScaling=new V(1,1,1),t._startingPosition=new V(0,0,0),t._startingOrientation=new G,t._startingScaling=new V(1,1,1),t.onPositionChangedObservable=new f,t.dragDeltaRatio=.2,t.rotateDraggedObject=!0,t.rotateAroundYOnly=!1,t.rotateWithMotionController=!0,t.disableMovement=!1,t.faceCameraOnDragStart=!1,t}return m(t,e),Object.defineProperty(t.prototype,"name",{get:function(){return"SixDofDrag"},enumerable:!1,configurable:!0}),t.prototype.attach=function(t){var i=this;e.prototype.attach.call(this,t),t.isNearGrabbable=!0,t.getChildMeshes().forEach((function(e){e.isNearGrabbable=!0})),this._virtualTransformNode=new Fo("virtual_sixDof",ys._virtualScene),this._virtualTransformNode.rotationQuaternion=G.Identity(),this._sceneRenderObserver=t.getScene().onBeforeRenderObservable.add((function(){if(1===i.currentDraggingPointerIds.length&&i._moving&&!i.disableMovement){var e=H.Vector3[0];e.copyFrom(i._targetPosition).subtractInPlace(t.absolutePosition).scaleInPlace(i.dragDeltaRatio);var r=H.Vector3[1];if(r.copyFrom(e),t.parent){var n=H.Matrix[0];t.parent.absoluteRotationQuaternion.toRotationMatrix(n),n.invert(),V.TransformNormalToRef(e,n,r)}if(t.position.addInPlace(r),i.onPositionChangedObservable.notifyObservers({position:t.absolutePosition}),!t.parent||t.parent.scaling&&!t.parent.scaling.isNonUniformWithinEpsilon(.001)){var o=H.Quaternion[0];if(o.copyFrom(i._targetOrientation),t.parent){var a=H.Quaternion[0];a.copyFrom(t.parent.absoluteRotationQuaternion),a.invertInPlace(),a.multiplyToRef(i._targetOrientation,o)}G.SlerpToRef(t.rotationQuaternion,o,i.dragDeltaRatio,t.rotationQuaternion)}}}))},t.prototype._getPositionOffsetAround=function(e,t,i){var r=H.Matrix[0],n=H.Matrix[1],o=H.Matrix[2],a=H.Matrix[3],s=H.Matrix[4];return z.TranslationToRef(e.x,e.y,e.z,r),z.TranslationToRef(-e.x,-e.y,-e.z,n),z.FromQuaternionToRef(i,o),z.ScalingToRef(t,t,t,a),n.multiplyToRef(o,s),s.multiplyToRef(a,s),s.multiplyToRef(r,s),s.getTranslation()},t.prototype._onePointerPositionUpdated=function(e,t){H.Vector3[0].setAll(0),this._dragging===this._dragType.DRAG?this.rotateDraggedObject&&(this.rotateAroundYOnly?G.RotationYawPitchRollToRef(t.toEulerAngles().y,0,0,H.Quaternion[0]):H.Quaternion[0].copyFrom(t),H.Quaternion[0].multiplyToRef(this._startingOrientation,this._targetOrientation)):(this._dragging===this._dragType.NEAR_DRAG||this._dragging===this._dragType.DRAG_WITH_CONTROLLER&&this.rotateWithMotionController)&&t.multiplyToRef(this._startingOrientation,this._targetOrientation),this._targetPosition.copyFrom(this._startingPosition).addInPlace(e)},t.prototype._twoPointersPositionUpdated=function(){var e=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].startingPosition,t=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].startingPosition,i=H.Vector3[0];e.addToRef(t,i),i.scaleInPlace(.5);var r=H.Vector3[1];t.subtractToRef(e,r);var n=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].dragMesh.absolutePosition,o=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].dragMesh.absolutePosition,a=H.Vector3[2];n.addToRef(o,a),a.scaleInPlace(.5);var s=H.Vector3[3];o.subtractToRef(n,s);var l=s.length()/r.length(),c=a.subtract(i),u=G.FromEulerAngles(0,V.GetAngleBetweenVectorsOnPlane(r.normalize(),s.normalize(),V.UpReadOnly),0),h=this._ownerNode.parent;this._ownerNode.setParent(null);var d=this._getPositionOffsetAround(i.subtract(this._virtualTransformNode.getAbsolutePivotPoint()),l,u);this._virtualTransformNode.rotationQuaternion.multiplyToRef(u,this._ownerNode.rotationQuaternion),this._virtualTransformNode.scaling.scaleToRef(l,this._ownerNode.scaling),this._virtualTransformNode.position.addToRef(c.addInPlace(d),this._ownerNode.position),this.onPositionChangedObservable.notifyObservers({position:this._ownerNode.position}),this._ownerNode.setParent(h)},t.prototype._targetDragStart=function(){var e=this.currentDraggingPointerIds.length;this._ownerNode.rotationQuaternion||(this._ownerNode.rotationQuaternion=G.RotationYawPitchRoll(this._ownerNode.rotation.y,this._ownerNode.rotation.x,this._ownerNode.rotation.z));var t=this._ownerNode.getAbsolutePivotPoint();if(1===e){if(this._targetPosition.copyFrom(this._ownerNode.absolutePosition),this._targetOrientation.copyFrom(this._ownerNode.absoluteRotationQuaternion),this._targetScaling.copyFrom(this._ownerNode.absoluteScaling),this.faceCameraOnDragStart&&this._scene.activeCamera){var i=H.Vector3[0];this._scene.activeCamera.position.subtractToRef(t,i),i.normalize();var r=H.Quaternion[0];this._scene.useRightHandedSystem?G.FromLookDirectionRHToRef(i,new V(0,1,0),r):G.FromLookDirectionLHToRef(i,new V(0,1,0),r),r.normalize(),G.RotationYawPitchRollToRef(r.toEulerAngles().y,0,0,H.Quaternion[0]),this._targetOrientation.copyFrom(H.Quaternion[0])}this._startingPosition.copyFrom(this._targetPosition),this._startingOrientation.copyFrom(this._targetOrientation),this._startingScaling.copyFrom(this._targetScaling)}else 2===e&&(this._virtualTransformNode.setPivotPoint(new V(0,0,0),dn.LOCAL),this._virtualTransformNode.position.copyFrom(this._ownerNode.absolutePosition),this._virtualTransformNode.scaling.copyFrom(this._ownerNode.absoluteScaling),this._virtualTransformNode.rotationQuaternion.copyFrom(this._ownerNode.absoluteRotationQuaternion),this._virtualTransformNode.setPivotPoint(t,dn.WORLD),this._resetVirtualMeshesPosition())},t.prototype._targetDrag=function(e,t){1===this.currentDraggingPointerIds.length?this._onePointerPositionUpdated(e,t):2===this.currentDraggingPointerIds.length&&this._twoPointersPositionUpdated()},t.prototype._targetDragEnd=function(){if(1===this.currentDraggingPointerIds.length){this._resetVirtualMeshesPosition();var e=this.faceCameraOnDragStart;this.faceCameraOnDragStart=!1,this._targetDragStart(),this.faceCameraOnDragStart=e}},t.prototype.detach=function(){e.prototype.detach.call(this),this._ownerNode&&this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),this._virtualTransformNode&&this._virtualTransformNode.dispose()},t}(ys),Ts=function(){function e(){this._attachPointLocalOffset=new V,this._workingPosition=new V,this._workingQuaternion=new G,this._lastTick=-1,this._hit=!1,this.hitNormalOffset=.05,this.meshes=[],this.interpolatePose=!0,this.lerpTime=250,this.keepOrientationVertical=!0,this.enabled=!0,this.maxStickingDistance=.8}return Object.defineProperty(e.prototype,"name",{get:function(){return"SurfaceMagnetism"},enumerable:!1,configurable:!0}),e.prototype.init=function(){},e.prototype.attach=function(e,t){this._attachedMesh=e,this._scene=t||e.getScene(),this._attachedMesh.rotationQuaternion||(this._attachedMesh.rotationQuaternion=G.RotationYawPitchRoll(this._attachedMesh.rotation.y,this._attachedMesh.rotation.x,this._attachedMesh.rotation.z)),this.updateAttachPoint(),this._workingPosition.copyFrom(this._attachedMesh.position),this._workingQuaternion.copyFrom(this._attachedMesh.rotationQuaternion),this._addObservables()},e.prototype.detach=function(){this._attachedMesh=null,this._removeObservables()},e.prototype._getTargetPose=function(e){if(!this._attachedMesh)return null;if(e&&e.hit){var t=e.getNormal(!0,!0),i=e.pickedPoint;if(!t||!i)return null;t.normalize();var r=H.Vector3[0];return r.copyFrom(t),r.scaleInPlace(this.hitNormalOffset),r.addInPlace(i),this._attachedMesh.parent&&(H.Matrix[0].copyFrom(this._attachedMesh.parent.getWorldMatrix()).invert(),V.TransformNormalToRef(r,H.Matrix[0],r)),{position:r,quaternion:G.RotationYawPitchRoll(-Math.atan2(t.x,-t.z),this.keepOrientationVertical?0:Math.atan2(t.y,Math.sqrt(t.z*t.z+t.x*t.x)),0)}}return null},e.prototype.updateAttachPoint=function(){this._getAttachPointOffsetToRef(this._attachPointLocalOffset)},e.prototype.findAndUpdateTarget=function(e){if(this._hit=!1,!e.ray)return!1;var t=e.ray.intersectsMeshes(this.meshes)[0];if(this._attachedMesh&&t&&t.hit&&t.pickedMesh){var i=this._getTargetPose(t);i&&V.Distance(this._attachedMesh.position,i.position)<this.maxStickingDistance&&(this._workingPosition.copyFrom(i.position),this._workingQuaternion.copyFrom(i.quaternion),this._hit=!0)}return this._hit},e.prototype._getAttachPointOffsetToRef=function(e){if(this._attachedMesh){var t=H.Quaternion[0];t.copyFrom(this._attachedMesh.rotationQuaternion),this._attachedMesh.rotationQuaternion.copyFromFloats(0,0,0,1),this._attachedMesh.computeWorldMatrix();var i=this._attachedMesh.getHierarchyBoundingVectors(),r=H.Vector3[0];i.max.addToRef(i.min,r),r.scaleInPlace(.5),r.z=i.max.z;var n=H.Matrix[0];this._attachedMesh.getWorldMatrix().invertToRef(n),V.TransformCoordinatesToRef(r,n,e),this._attachedMesh.rotationQuaternion.copyFrom(t)}else e.setAll(0)},e.prototype._updateTransformToGoal=function(e){if(this._attachedMesh&&this._hit){var t=this._attachedMesh.parent;this._attachedMesh.setParent(null);var i=H.Vector3[0];if(V.TransformNormalToRef(this._attachPointLocalOffset,this._attachedMesh.getWorldMatrix(),i),!this.interpolatePose)return this._attachedMesh.position.copyFrom(this._workingPosition).subtractInPlace(i),void this._attachedMesh.rotationQuaternion.copyFrom(this._workingQuaternion);var r=new V;V.SmoothToRef(this._attachedMesh.position,this._workingPosition,e,this.lerpTime,r),this._attachedMesh.position.copyFrom(r);var n=new G;n.copyFrom(this._attachedMesh.rotationQuaternion),G.SmoothToRef(n,this._workingQuaternion,e,this.lerpTime,this._attachedMesh.rotationQuaternion),this._attachedMesh.setParent(t)}},e.prototype._addObservables=function(){var e=this;this._pointerObserver=this._scene.onPointerObservable.add((function(t){e.enabled&&t.type==Gr.POINTERMOVE&&t.pickInfo&&e.findAndUpdateTarget(t.pickInfo)})),this._lastTick=Date.now(),this._onBeforeRender=this._scene.onBeforeRenderObservable.add((function(){var t=Date.now();e._updateTransformToGoal(t-e._lastTick),e._lastTick=t}))},e.prototype._removeObservables=function(){this._scene.onPointerObservable.remove(this._pointerObserver),this._scene.onBeforeRenderObservable.remove(this._onBeforeRender),this._pointerObserver=null,this._onBeforeRender=null},e}(),Es=function(){function e(){this._tmpQuaternion=new G,this._tmpVectors=[new V,new V,new V,new V,new V,new V,new V],this._tmpMatrix=new z,this._tmpInvertView=new z,this._tmpForward=new V,this._tmpNodeForward=new V,this._tmpPosition=new V,this._workingPosition=new V,this._workingQuaternion=new G,this._lastTick=-1,this._recenterNextUpdate=!0,this.interpolatePose=!0,this.lerpTime=500,this.ignoreCameraPitchAndRoll=!1,this.pitchOffset=15,this.maxViewVerticalDegrees=30,this.maxViewHorizontalDegrees=30,this.orientToCameraDeadzoneDegrees=60,this.ignoreDistanceClamp=!1,this.ignoreAngleClamp=!1,this.verticalMaxDistance=0,this.defaultDistance=.8,this.maximumDistance=2,this.minimumDistance=.3,this.useFixedVerticalOffset=!1,this.fixedVerticalOffset=0,this._enabled=!0}return Object.defineProperty(e.prototype,"followedCamera",{get:function(){return this._followedCamera||this._scene.activeCamera},set:function(e){this._followedCamera=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"name",{get:function(){return"Follow"},enumerable:!1,configurable:!0}),e.prototype.init=function(){},e.prototype.attach=function(e,t){this._scene=e.getScene(),this.attachedNode=e,t&&(this.followedCamera=t),this._addObservables()},e.prototype.detach=function(){this.attachedNode=null,this._removeObservables()},e.prototype.recenter=function(){this._recenterNextUpdate=!0},e.prototype._angleBetweenVectorAndPlane=function(e,t){return this._tmpVectors[0].copyFrom(e),e=this._tmpVectors[0],this._tmpVectors[1].copyFrom(t),t=this._tmpVectors[1],e.normalize(),t.normalize(),Math.PI/2-Math.acos(V.Dot(e,t))},e.prototype._length2D=function(e){return Math.sqrt(e.x*e.x+e.z*e.z)},e.prototype._distanceClamp=function(e,t){void 0===t&&(t=!1);var i=this.minimumDistance,r=this.maximumDistance,n=this.defaultDistance,o=this._tmpVectors[0];o.copyFrom(e);var a=o.length();if(o.normalizeFromLength(a),this.ignoreCameraPitchAndRoll){i=this._length2D(o)*i,r=this._length2D(o)*r;var s=this._length2D(e);o.scaleInPlace(a/s),a=s}var l;return l=t?n:j.Clamp(a,i,r),e.copyFrom(o).scaleInPlace(l),a!==l},e.prototype._applyVerticalClamp=function(e){0!==this.verticalMaxDistance&&(e.y=j.Clamp(e.y,-this.verticalMaxDistance,this.verticalMaxDistance))},e.prototype._toOrientationQuatToRef=function(e,t){G.RotationYawPitchRollToRef(Math.atan2(e.x,e.z),Math.atan2(e.y,Math.sqrt(e.z*e.z+e.x*e.x)),0,t)},e.prototype._applyPitchOffset=function(e){var t=this._tmpVectors[0],i=this._tmpVectors[1];t.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),i.copyFromFloats(1,0,0),V.TransformNormalToRef(t,e,t),t.y=0,t.normalize(),V.TransformNormalToRef(i,e,i),G.RotationAxisToRef(i,this.pitchOffset*Math.PI/180,this._tmpQuaternion),t.rotateByQuaternionToRef(this._tmpQuaternion,t),this._toOrientationQuatToRef(t,this._tmpQuaternion),this._tmpQuaternion.toRotationMatrix(this._tmpMatrix),e.copyFrom(this._tmpMatrix)},e.prototype._angularClamp=function(e,t){var i=this._tmpVectors[5];i.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1);var r=this._tmpVectors[6];r.copyFromFloats(1,0,0),V.TransformNormalToRef(i,e,i),V.TransformNormalToRef(r,e,r);var n=V.UpReadOnly;if(t.length()<A)return!1;var o=!1,a=this._tmpQuaternion;if(this.ignoreCameraPitchAndRoll){var s=V.GetAngleBetweenVectorsOnPlane(t,i,r);G.RotationAxisToRef(r,s,a),t.rotateByQuaternionToRef(a,t)}else{var l=-V.GetAngleBetweenVectorsOnPlane(t,i,r),c=this.maxViewVerticalDegrees*Math.PI/180*.5;l<-c?(G.RotationAxisToRef(r,-l-c,a),t.rotateByQuaternionToRef(a,t),o=!0):l>c&&(G.RotationAxisToRef(r,-l+c,a),t.rotateByQuaternionToRef(a,t),o=!0)}var u=this._angleBetweenVectorAndPlane(t,r)*(this._scene.useRightHandedSystem?-1:1),h=this.maxViewHorizontalDegrees*Math.PI/180*.5;return u<-h?(G.RotationAxisToRef(n,-u-h,a),t.rotateByQuaternionToRef(a,t),o=!0):u>h&&(G.RotationAxisToRef(n,-u+h,a),t.rotateByQuaternionToRef(a,t),o=!0),o},e.prototype._orientationClamp=function(e,t){var i,r=this._tmpVectors[0];r.copyFrom(e).scaleInPlace(-1).normalize();var n=this._tmpVectors[1],o=this._tmpVectors[2];n.copyFromFloats(0,1,0),V.CrossToRef(r,n,o);var a=o.length();a<A||(o.normalizeFromLength(a),V.CrossToRef(o,r,n),(null===(i=this.attachedNode)||void 0===i?void 0:i.getScene().useRightHandedSystem)?G.FromLookDirectionRHToRef(r,n,t):G.FromLookDirectionLHToRef(r,n,t))},e.prototype._passedOrientationDeadzone=function(e,t){var i=this._tmpVectors[5];return i.copyFrom(e),i.normalize(),180*Math.abs(V.GetAngleBetweenVectorsOnPlane(t,i,V.UpReadOnly))/Math.PI>this.orientToCameraDeadzoneDegrees},e.prototype._updateLeashing=function(e){if(this.attachedNode&&this._enabled){var t=this.attachedNode.parent;this.attachedNode.setParent(null);var i=this.attachedNode.getWorldMatrix(),r=this._workingPosition,n=this._workingQuaternion,o=this.attachedNode.getPivotPoint(),a=this._tmpInvertView;a.copyFrom(e.getViewMatrix()),a.invert(),V.TransformCoordinatesToRef(o,i,r);var s=this._tmpPosition;s.copyFromFloats(0,0,0),V.TransformCoordinatesToRef(s,i,s),s.scaleInPlace(-1).subtractInPlace(o),r.subtractInPlace(e.globalPosition),this.ignoreCameraPitchAndRoll&&this._applyPitchOffset(a);var l=!1,c=this._tmpForward;c.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),V.TransformNormalToRef(c,a,c);var u=this._tmpNodeForward;if(u.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),V.TransformNormalToRef(u,i,u),this._recenterNextUpdate)r.copyFrom(c).scaleInPlace(this.defaultDistance);else if(this.ignoreAngleClamp){var h=r.length();r.copyFrom(c).scaleInPlace(h)}else l=this._angularClamp(a,r);var d=!1;this.ignoreDistanceClamp||(d=this._distanceClamp(r,l),this._applyVerticalClamp(r)),this.useFixedVerticalOffset&&(r.y=s.y-e.globalPosition.y+this.fixedVerticalOffset),(l||d||this._passedOrientationDeadzone(r,u)||this._recenterNextUpdate)&&this._orientationClamp(r,n),this._workingPosition.subtractInPlace(o),this._recenterNextUpdate=!1,this.attachedNode.setParent(t)}},e.prototype._updateTransformToGoal=function(e){if(this.attachedNode&&this.followedCamera&&this._enabled){this.attachedNode.rotationQuaternion||(this.attachedNode.rotationQuaternion=G.Identity());var t=this.attachedNode.parent;if(this.attachedNode.setParent(null),!this.interpolatePose)return this.attachedNode.position.copyFrom(this.followedCamera.globalPosition).addInPlace(this._workingPosition),void this.attachedNode.rotationQuaternion.copyFrom(this._workingQuaternion);var i=new V;i.copyFrom(this.attachedNode.position).subtractInPlace(this.followedCamera.globalPosition),V.SmoothToRef(i,this._workingPosition,e,this.lerpTime,i),i.addInPlace(this.followedCamera.globalPosition),this.attachedNode.position.copyFrom(i);var r=new G;r.copyFrom(this.attachedNode.rotationQuaternion),G.SmoothToRef(r,this._workingQuaternion,e,this.lerpTime,this.attachedNode.rotationQuaternion),this.attachedNode.setParent(t)}},e.prototype._addObservables=function(){var e=this;this._lastTick=Date.now(),this._onBeforeRender=this._scene.onBeforeRenderObservable.add((function(){if(e.followedCamera){var t=Date.now();e._updateLeashing(e.followedCamera),e._updateTransformToGoal(t-e._lastTick),e._lastTick=t}}))},e.prototype._removeObservables=function(){this._onBeforeRender&&this._scene.onBeforeRenderObservable.remove(this._onBeforeRender)},e}(),Ss=function(){function e(){}return e.ANCHOR_SYSTEM="xr-anchor-system",e.BACKGROUND_REMOVER="xr-background-remover",e.HIT_TEST="xr-hit-test",e.MESH_DETECTION="xr-mesh-detection",e.PHYSICS_CONTROLLERS="xr-physics-controller",e.PLANE_DETECTION="xr-plane-detection",e.POINTER_SELECTION="xr-controller-pointer-selection",e.TELEPORTATION="xr-controller-teleportation",e.FEATURE_POINTS="xr-feature-points",e.HAND_TRACKING="xr-hand-tracking",e.IMAGE_TRACKING="xr-image-tracking",e.NEAR_INTERACTION="xr-near-interaction",e.DOM_OVERLAY="xr-dom-overlay",e.MOVEMENT="xr-controller-movement",e.LIGHT_ESTIMATION="xr-light-estimation",e.EYE_TRACKING="xr-eye-tracking",e.WALKING_LOCOMOTION="xr-walking-locomotion",e.LAYERS="xr-layers",e.DEPTH_SENSING="xr-depth-sensing",e.SPACE_WARP="xr-space-warp",e.RAW_CAMERA_ACCESS="xr-raw-camera-access",e}(),xs=function(){function e(e){var t=this;this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add((function(){t.getEnabledFeatures().forEach((function(e){var i=t._features[e];!i.enabled||i.featureImplementation.attached||i.featureImplementation.disableAutoAttach||t.attachFeature(e)}))})),this._xrSessionManager.onXRSessionEnded.add((function(){t.getEnabledFeatures().forEach((function(e){var i=t._features[e];i.enabled&&i.featureImplementation.attached&&t.detachFeature(e)}))}))}return e.AddWebXRFeature=function(e,t,i,r){void 0===i&&(i=1),void 0===r&&(r=!1),this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),r&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t},e.ConstructFeature=function(e,t,i,r){void 0===t&&(t=1);var n=this._AvailableFeatures[e][t];if(!n)throw new Error("feature not found");return n(i,r)},e.GetAvailableFeatures=function(){return Object.keys(this._AvailableFeatures)},e.GetAvailableVersions=function(e){return Object.keys(this._AvailableFeatures[e])},e.GetLatestVersionOfFeature=function(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1},e.GetStableVersionOfFeature=function(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1},e.prototype.attachFeature=function(e){var t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&(t.featureImplementation.attach()||rr.Warn("Feature ".concat(e," failed to attach")))},e.prototype.detachFeature=function(e){var t=this._features[e];t&&t.featureImplementation.attached&&(t.featureImplementation.detach()||rr.Warn("Feature ".concat(e," failed to detach")))},e.prototype.disableFeature=function(e){var t="string"==typeof e?e:e.Name,i=this._features[t];return!(!i||!i.enabled||(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),delete this._features[t],0))},e.prototype.dispose=function(){var e=this;this.getEnabledFeatures().forEach((function(t){e.disableFeature(t)}))},e.prototype.enableFeature=function(t,i,r,n,o){var a=this;void 0===i&&(i="latest"),void 0===r&&(r={}),void 0===n&&(n=!0),void 0===o&&(o=!0);var s="string"==typeof t?t:t.Name,l=0;if("string"==typeof i){if(!i)throw new Error("Error in provided version - ".concat(s," (").concat(i,")"));if(-1===(l="stable"===i?e.GetStableVersionOfFeature(s):"latest"===i?e.GetLatestVersionOfFeature(s):+i)||isNaN(l))throw new Error("feature not found - ".concat(s," (").concat(i,")"))}else l=i;var c=e._ConflictingFeatures[s];if(void 0!==c&&-1!==this.getEnabledFeatures().indexOf(c))throw new Error("Feature ".concat(s," cannot be enabled while ").concat(c," is enabled."));var u=this._features[s],h=e.ConstructFeature(s,l,this._xrSessionManager,r);if(!h)throw new Error("feature not found - ".concat(s));u&&this.disableFeature(s);var d=h();if(d.dependsOn){var p=d.dependsOn.every((function(e){return!!a._features[e]}));if(!p)throw new Error("Dependant features missing. Make sure the following features are enabled - ".concat(d.dependsOn.join(", ")))}if(d.isCompatible())return this._features[s]={featureImplementation:d,enabled:!0,version:l,required:o},n?this._xrSessionManager.session&&!this._features[s].featureImplementation.attached&&this.attachFeature(s):this._features[s].featureImplementation.disableAutoAttach=!0,this._features[s].featureImplementation;if(o)throw new Error("required feature not compatible");return rr.Warn("Feature ".concat(s," not compatible with the current environment/browser and was not enabled.")),d},e.prototype.getEnabledFeature=function(e){return this._features[e]&&this._features[e].featureImplementation},e.prototype.getEnabledFeatures=function(){return Object.keys(this._features)},e.prototype._extendXRSessionInitObject=function(e){return y(this,void 0,void 0,(function(){var t,i,r,n,o,a,s;return b(this,(function(l){switch(l.label){case 0:t=this.getEnabledFeatures(),i=0,r=t,l.label=1;case 1:return i<r.length?(n=r[i],o=this._features[n],(a=o.featureImplementation.xrNativeFeatureName)&&(o.required?(e.requiredFeatures=e.requiredFeatures||[],-1===e.requiredFeatures.indexOf(a)&&e.requiredFeatures.push(a)):(e.optionalFeatures=e.optionalFeatures||[],-1===e.optionalFeatures.indexOf(a)&&e.optionalFeatures.push(a))),o.featureImplementation.getXRSessionInitExtension?[4,o.featureImplementation.getXRSessionInitExtension()]:[3,3]):[3,4];case 2:s=l.sent(),e=g(g({},e),s),l.label=3;case 3:return i++,[3,1];case 4:return[2,e]}}))}))},e._AvailableFeatures={},e._ConflictingFeatures=((ms={})[Ss.TELEPORTATION]=Ss.MOVEMENT,ms[Ss.MOVEMENT]=Ss.TELEPORTATION,ms),e}(),As=function(){function e(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this._xrNativeFeatureName="",this.onFeatureAttachObservable=new f,this.onFeatureDetachObservable=new f}return Object.defineProperty(e.prototype,"xrNativeFeatureName",{get:function(){return this._xrNativeFeatureName},set:function(e){var t;!this._xrSessionManager.isNative&&e&&this._xrSessionManager.inXRSession&&-1===(null===(t=this._xrSessionManager.enabledFeatures)||void 0===t?void 0:t.indexOf(e))&&ae.Warn("The feature ".concat(e," needs to be enabled before starting the XR session. Note - It is still possible it is not supported.")),this._xrNativeFeatureName=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"attached",{get:function(){return this._attached},enumerable:!1,configurable:!0}),e.prototype.attach=function(e){var t=this;if(this.isDisposed)return!1;if(e)this.attached&&this.detach();else if(this.attached)return!1;if(this._xrSessionManager.enabledFeatures){if(!this._xrSessionManager.isNative&&this.xrNativeFeatureName&&-1===this._xrSessionManager.enabledFeatures.indexOf(this.xrNativeFeatureName))return!1}else ae.Warn("session.enabledFeatures is not available on this device. It is possible that this feature is not supported.");return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,(function(e){return t._onXRFrame(e)})),this.onFeatureAttachObservable.notifyObservers(this),!0},e.prototype.detach=function(){return this._attached?(this._attached=!1,this._removeOnDetach.forEach((function(e){e.observable.remove(e.observer)})),this.onFeatureDetachObservable.notifyObservers(this),!0):(this.disableAutoAttach=!0,!1)},e.prototype.dispose=function(){this.detach(),this.isDisposed=!0,this.onFeatureAttachObservable.clear(),this.onFeatureDetachObservable.clear()},e.prototype.isCompatible=function(){return!0},e.prototype._addNewAttachObserver=function(e,t,i){this._removeOnDetach.push({observable:e,observer:e.add(t,void 0,i)})},e}(),Cs=function(){function e(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}return Object.defineProperty(e.prototype,"physicsJoint",{get:function(){return this._physicsJoint},set:function(e){this._physicsJoint,this._physicsJoint=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"physicsPlugin",{set:function(e){this._physicsPlugin=e},enumerable:!1,configurable:!0}),e.prototype.executeNativeFunction=function(e){e(this._physicsPlugin.world,this._physicsJoint)},e.DistanceJoint=0,e.HingeJoint=1,e.BallAndSocketJoint=2,e.WheelJoint=3,e.SliderJoint=4,e.PrismaticJoint=5,e.UniversalJoint=6,e.Hinge2Joint=e.WheelJoint,e.PointToPointJoint=8,e.SpringJoint=9,e.LockJoint=10,e}(),Rs=function(e){function t(t){return e.call(this,Cs.DistanceJoint,t)||this}return m(t,e),t.prototype.updateDistance=function(e,t){this._physicsPlugin.updateDistanceJoint(this,e,t)},t}(Cs),Ps=function(e){function t(t,i){return e.call(this,t,i)||this}return m(t,e),t.prototype.setMotor=function(e,t){this._physicsPlugin.setMotor(this,e||0,t)},t.prototype.setLimit=function(e,t){this._physicsPlugin.setLimit(this,e,t)},t}(Cs),Is=function(e){function t(t){return e.call(this,Cs.HingeJoint,t)||this}return m(t,e),t.prototype.setMotor=function(e,t){this._physicsPlugin.setMotor(this,e||0,t)},t.prototype.setLimit=function(e,t){this._physicsPlugin.setLimit(this,e,t)},t}(Ps),Ms=function(e){function t(t){return e.call(this,Cs.Hinge2Joint,t)||this}return m(t,e),t.prototype.setMotor=function(e,t,i){void 0===i&&(i=0),this._physicsPlugin.setMotor(this,e||0,t,i)},t.prototype.setLimit=function(e,t,i){void 0===i&&(i=0),this._physicsPlugin.setLimit(this,e,t,i)},t}(Ps);Fa._PhysicsImpostorParser=function(e,t,i){return new Ds(t,i.physicsImpostor,{mass:i.physicsMass,friction:i.physicsFriction,restitution:i.physicsRestitution},e)};var Os,Ds=function(){function e(t,i,r,n){void 0===r&&(r={mass:0});var o=this;this.object=t,this.type=i,this._options=r,this._scene=n,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=V.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new G,this._tmpQuat2=new G,this.beforeStep=function(){o._physicsEngine&&(o.object.translate(o._deltaPosition,-1),o._deltaRotationConjugated&&o.object.rotationQuaternion&&o.object.rotationQuaternion.multiplyToRef(o._deltaRotationConjugated,o.object.rotationQuaternion),o.object.computeWorldMatrix(!1),o.object.parent&&o.object.rotationQuaternion?(o.getParentsRotation(),o._tmpQuat.multiplyToRef(o.object.rotationQuaternion,o._tmpQuat)):o._tmpQuat.copyFrom(o.object.rotationQuaternion||new G),o._options.disableBidirectionalTransformation||o.object.rotationQuaternion&&o._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(o,o.object.getAbsolutePosition(),o._tmpQuat),o._onBeforePhysicsStepCallbacks.forEach((function(e){e(o)})))},this.afterStep=function(){o._physicsEngine&&(o._onAfterPhysicsStepCallbacks.forEach((function(e){e(o)})),o._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(o),o.object.parent&&o.object.rotationQuaternion&&(o.getParentsRotation(),o._tmpQuat.conjugateInPlace(),o._tmpQuat.multiplyToRef(o.object.rotationQuaternion,o.object.rotationQuaternion)),o.object.setAbsolutePosition(o.object.position),o._deltaRotation?(o.object.rotationQuaternion&&o.object.rotationQuaternion.multiplyToRef(o._deltaRotation,o.object.rotationQuaternion),o._deltaPosition.applyRotationQuaternionToRef(o._deltaRotation,e._TmpVecs[0]),o.object.translate(e._TmpVecs[0],1)):o.object.translate(o._deltaPosition,1),o.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=function(e){if((o._onPhysicsCollideCallbacks.length||o.onCollideEvent)&&o._physicsEngine){var t=o._physicsEngine.getImpostorWithPhysicsBody(e.body);t&&(o.onCollideEvent&&o.onCollideEvent(o,t),o._onPhysicsCollideCallbacks.filter((function(e){return-1!==e.otherImpostors.indexOf(t)})).forEach((function(i){i.callback(o,t,e.point,e.distance,e.impulse,e.normal)})))}},this.object?(this.object.parent&&0!==r.mass&&ae.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur."),!this._scene&&t.getScene&&(this._scene=t.getScene()),this._scene&&(this.type>100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=G.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new G),this._options.mass=void 0===r.mass?0:r.mass,this._options.friction=void 0===r.friction?.2:r.friction,this._options.restitution=void 0===r.restitution?.2:r.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=void 0===r.pressure?200:r.pressure,this._options.stiffness=void 0===r.stiffness?1:r.stiffness,this._options.velocityIterations=void 0===r.velocityIterations?20:r.velocityIterations,this._options.positionIterations=void 0===r.positionIterations?20:r.positionIterations,this._options.fixedPoints=void 0===r.fixedPoints?0:r.fixedPoints,this._options.margin=void 0===r.margin?0:r.margin,this._options.damping=void 0===r.damping?0:r.damping,this._options.path=void 0===r.path?null:r.path,this._options.shape=void 0===r.shape?null:r.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&ae.Warn("You must affect impostors to children before affecting impostor to parent.")):ae.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))):ae.Error("No object was provided. A physics object is obligatory")}return Object.defineProperty(e.prototype,"isDisposed",{get:function(){return this._isDisposed},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"mass",{get:function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0},set:function(e){this.setMass(e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"friction",{get:function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0},set:function(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"restitution",{get:function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0},set:function(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"pressure",{get:function(){if(!this._physicsEngine)return 0;var e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0},set:function(e){if(this._physicsEngine){var t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stiffness",{get:function(){if(!this._physicsEngine)return 0;var e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0},set:function(e){if(this._physicsEngine){var t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"velocityIterations",{get:function(){if(!this._physicsEngine)return 0;var e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0},set:function(e){if(this._physicsEngine){var t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"positionIterations",{get:function(){if(!this._physicsEngine)return 0;var e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0},set:function(e){if(this._physicsEngine){var t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}},enumerable:!1,configurable:!0}),e.prototype._init=function(){this._physicsEngine&&(this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),this._isDisposed||this.parent&&!this._options.ignoreParent||this._physicsEngine.addImpostor(this))},e.prototype._getPhysicsParent=function(){return this.object.parent instanceof Uo?this.object.parent.physicsImpostor:null},e.prototype.isBodyInitRequired=function(){return this._bodyUpdateRequired||!this._physicsBody&&(!this._parent||!!this._options.ignoreParent)},e.prototype.setScalingUpdated=function(){this.forceUpdate()},e.prototype.forceUpdate=function(){this._init(),this.parent&&!this._options.ignoreParent&&this.parent.forceUpdate()},Object.defineProperty(e.prototype,"physicsBody",{get:function(){return this._parent&&!this._options.ignoreParent?this._parent.physicsBody:this._physicsBody},set:function(e){this._physicsBody&&this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=e,this.resetUpdateFlags()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"parent",{get:function(){return!this._options.ignoreParent&&this._parent?this._parent:null},set:function(e){this._parent=e},enumerable:!1,configurable:!0}),e.prototype.resetUpdateFlags=function(){this._bodyUpdateRequired=!1},e.prototype.getObjectExtents=function(){if(this.object.getBoundingInfo){var t=this.object.rotationQuaternion,i=this.object.scaling.clone();this.object.rotationQuaternion=e.IDENTITY_QUATERNION;var r=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);r&&r.decompose(i,void 0,void 0);var n=this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiplyInPlace(i);return n.x=Math.abs(n.x),n.y=Math.abs(n.y),n.z=Math.abs(n.z),this.object.rotationQuaternion=t,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),n}return e.DEFAULT_OBJECT_SIZE},e.prototype.getObjectCenter=function(){return this.object.getBoundingInfo?this.object.getBoundingInfo().boundingBox.centerWorld:this.object.position},e.prototype.getParam=function(e){return this._options[e]},e.prototype.setParam=function(e,t){this._options[e]=t,this._bodyUpdateRequired=!0},e.prototype.setMass=function(e){this.getParam("mass")!==e&&this.setParam("mass",e),this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyMass(this,e)},e.prototype.getLinearVelocity=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this):V.Zero()},e.prototype.setLinearVelocity=function(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)},e.prototype.getAngularVelocity=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):V.Zero()},e.prototype.setAngularVelocity=function(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,e)},e.prototype.executeNativeFunction=function(e){this._physicsEngine&&e(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)},e.prototype.registerBeforePhysicsStep=function(e){this._onBeforePhysicsStepCallbacks.push(e)},e.prototype.unregisterBeforePhysicsStep=function(e){var t=this._onBeforePhysicsStepCallbacks.indexOf(e);t>-1?this._onBeforePhysicsStepCallbacks.splice(t,1):ae.Warn("Function to remove was not found")},e.prototype.registerAfterPhysicsStep=function(e){this._onAfterPhysicsStepCallbacks.push(e)},e.prototype.unregisterAfterPhysicsStep=function(e){var t=this._onAfterPhysicsStepCallbacks.indexOf(e);t>-1?this._onAfterPhysicsStepCallbacks.splice(t,1):ae.Warn("Function to remove was not found")},e.prototype.registerOnPhysicsCollide=function(e,t){var i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})},e.prototype.unregisterOnPhysicsCollide=function(e,t){var i=e instanceof Array?e:[e],r=-1;this._onPhysicsCollideCallbacks.some((function(e,n){if(e.callback===t&&e.otherImpostors.length===i.length){var o=e.otherImpostors.every((function(e){return i.indexOf(e)>-1}));return o&&(r=n),o}return!1}))?this._onPhysicsCollideCallbacks.splice(r,1):ae.Warn("Function to remove was not found")},e.prototype.getParentsRotation=function(){var e=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);e;)e.rotationQuaternion?this._tmpQuat2.copyFrom(e.rotationQuaternion):G.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),e=e.parent;return this._tmpQuat},e.prototype.applyForce=function(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this},e.prototype.applyImpulse=function(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this},e.prototype.createJoint=function(e,t,i){var r=new Cs(t,i);return this.addJoint(e,r),this},e.prototype.addJoint=function(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this},e.prototype.addAnchor=function(e,t,i,r,n){if(!this._physicsEngine)return this;var o=this._physicsEngine.getPhysicsPlugin();return o.appendAnchor?(this._physicsEngine&&o.appendAnchor(this,e,t,i,r,n),this):this},e.prototype.addHook=function(e,t,i,r){if(!this._physicsEngine)return this;var n=this._physicsEngine.getPhysicsPlugin();return n.appendAnchor?(this._physicsEngine&&n.appendHook(this,e,t,i,r),this):this},e.prototype.sleep=function(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this},e.prototype.wakeUp=function(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this},e.prototype.clone=function(t){return t?new e(t,this.type,this._options,this._scene):null},e.prototype.dispose=function(){var e=this;this._physicsEngine&&(this._joints.forEach((function(t){e._physicsEngine&&e._physicsEngine.removeJoint(e,t.otherImpostor,t.joint)})),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)},e.prototype.setDeltaPosition=function(e){this._deltaPosition.copyFrom(e)},e.prototype.setDeltaRotation=function(e){this._deltaRotation||(this._deltaRotation=new G),this._deltaRotation.copyFrom(e),this._deltaRotationConjugated=this._deltaRotation.conjugate()},e.prototype.getBoxSizeToRef=function(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this},e.prototype.getRadius=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0},e.prototype.syncBoneWithImpostor=function(t,i,r,n,o){var a=e._TmpVecs[0],s=this.object;if(s.rotationQuaternion)if(o){var l=e._TmpQuat;s.rotationQuaternion.multiplyToRef(o,l),t.setRotationQuaternion(l,dn.WORLD,i)}else t.setRotationQuaternion(s.rotationQuaternion,dn.WORLD,i);a.x=0,a.y=0,a.z=0,r&&(a.x=r.x,a.y=r.y,a.z=r.z,t.getDirectionToRef(a,i,a),null==n&&(n=r.length()),a.x*=n,a.y*=n,a.z*=n),t.getParent()?(a.addInPlace(s.getAbsolutePosition()),t.setAbsolutePosition(a,i)):(i.setAbsolutePosition(s.getAbsolutePosition()),i.position.x-=a.x,i.position.y-=a.y,i.position.z-=a.z)},e.prototype.syncImpostorWithBone=function(t,i,r,n,o,a){var s=this.object;if(s.rotationQuaternion)if(o){var l=e._TmpQuat;t.getRotationQuaternionToRef(dn.WORLD,i,l),l.multiplyToRef(o,s.rotationQuaternion)}else t.getRotationQuaternionToRef(dn.WORLD,i,s.rotationQuaternion);var c=e._TmpVecs[0],u=e._TmpVecs[1];a||((a=e._TmpVecs[2]).x=0,a.y=1,a.z=0),t.getDirectionToRef(a,i,u),t.getAbsolutePositionToRef(i,c),null==n&&r&&(n=r.length()),null!=n&&(c.x+=u.x*n,c.y+=u.y*n,c.z+=u.z*n),s.setAbsolutePosition(c)},e.DEFAULT_OBJECT_SIZE=new V(1,1,1),e.IDENTITY_QUATERNION=G.Identity(),e._TmpVecs=C.BuildArray(3,V.Zero),e._TmpQuat=G.Identity(),e.NoImpostor=0,e.SphereImpostor=1,e.BoxImpostor=2,e.PlaneImpostor=3,e.MeshImpostor=4,e.CapsuleImpostor=6,e.CylinderImpostor=7,e.ParticleImpostor=8,e.HeightmapImpostor=9,e.ConvexHullImpostor=10,e.CustomImpostor=100,e.RopeImpostor=101,e.ClothImpostor=102,e.SoftbodyImpostor=103,e}();!function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(Os||(Os={}));var Ns,Fs,Ls=function(){function e(){}return Object.defineProperty(e,"ForceFullSceneLoadingForIncremental",{get:function(){return mo.ForceFullSceneLoadingForIncremental},set:function(e){mo.ForceFullSceneLoadingForIncremental=e},enumerable:!1,configurable:!0}),Object.defineProperty(e,"ShowLoadingScreen",{get:function(){return mo.ShowLoadingScreen},set:function(e){mo.ShowLoadingScreen=e},enumerable:!1,configurable:!0}),Object.defineProperty(e,"loggingLevel",{get:function(){return mo.loggingLevel},set:function(e){mo.loggingLevel=e},enumerable:!1,configurable:!0}),Object.defineProperty(e,"CleanBoneMatrixWeights",{get:function(){return mo.CleanBoneMatrixWeights},set:function(e){mo.CleanBoneMatrixWeights=e},enumerable:!1,configurable:!0}),e.GetDefaultPlugin=function(){return e._RegisteredPlugins[".babylon"]},e._GetPluginForExtension=function(t){return e._RegisteredPlugins[t]||(ae.Warn("Unable to find a plugin to load "+t+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"),e.GetDefaultPlugin())},e._GetPluginForDirectLoad=function(t){for(var i in e._RegisteredPlugins){var r=e._RegisteredPlugins[i].plugin;if(r.canDirectLoad&&r.canDirectLoad(t))return e._RegisteredPlugins[i]}return e.GetDefaultPlugin()},e._GetPluginForFilename=function(t){var i=t.indexOf("?");-1!==i&&(t=t.substring(0,i));var r=t.lastIndexOf("."),n=t.substring(r,t.length).toLowerCase();return e._GetPluginForExtension(n)},e._GetDirectLoad=function(e){return"data:"===e.substr(0,5)?e.substr(5):null},e._FormatErrorMessage=function(e,t,i){var r="Unable to load from "+(e.rawData?"binary data":e.url);return t?r+=": ".concat(t):i&&(r+=": ".concat(i)),r},e._LoadData=function(t,i,r,n,o,a,s,l){var c=e._GetDirectLoad(t.url);if(t.rawData&&!s)throw"When using ArrayBufferView to load data the file extension must be provided.";var u,h=s?e._GetPluginForExtension(s):c?e._GetPluginForDirectLoad(t.url):e._GetPluginForFilename(t.url);if(t.rawData&&!h.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";if(!(u=void 0!==h.plugin.createPlugin?h.plugin.createPlugin():h.plugin))throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";if(e.OnPluginActivatedObservable.notifyObservers(u),c&&(u.canDirectLoad&&u.canDirectLoad(t.url)||!zi(t.url))){if(u.directLoad){var d=u.directLoad(i,c);d.then?d.then((function(e){r(u,e)})).catch((function(e){o("Error in directLoad of _loadData: "+e,e)})):r(u,d)}else r(u,c);return u}var p=h.isBinary,f=function(e,t){i.isDisposed?o("Scene has been disposed"):r(u,e,t)},_=null,m=!1,g=u.onDisposeObservable;g&&g.add((function(){m=!0,_&&(_.abort(),_=null),a()}));var v=function(){if(!m){var e=function(e,t){o(null==e?void 0:e.statusText,t)};if(!u.loadFile&&t.rawData)throw"Plugin does not support loading ArrayBufferView.";_=u.loadFile?u.loadFile(i,t.rawData||t.file||t.url,t.rootUrl,f,n,p,e,l):i._loadFile(t.file||t.url,f,n,!0,p,e)}},y=i.getEngine(),b=y.enableOfflineSupport;if(b){for(var T=!1,E=0,S=i.disableOfflineSupportExceptionRules;E<S.length;E++)if(S[E].test(t.url)){T=!0;break}b=!T}return b&&Do.OfflineProviderFactory?i.offlineProvider=Do.OfflineProviderFactory(t.url,v,y.disableManifestCheck):v(),u},e._GetFileInfo=function(e,t){var i,r,n=null,o=null;if(t)if(t.name){var a=t;i="file:".concat(a.name),r=a.name,n=a}else if(ArrayBuffer.isView(t))i="",r=Qi(),o=t;else if("string"==typeof t&&t.startsWith("data:"))i=t,r="";else{var s=t;if("/"===s.substr(0,1))return rr.Error("Wrong sceneFilename parameter"),null;i=e+s,r=s}else i=e,r=rr.GetFilename(e),e=rr.GetFolderPath(e);return{url:i,rootUrl:e,name:r,file:n,rawData:o}},e.GetPluginForExtension=function(t){return e._GetPluginForExtension(t).plugin},e.IsPluginForExtensionAvailable=function(t){return!!e._RegisteredPlugins[t]},e.RegisterPlugin=function(t){if("string"==typeof t.extensions){var i=t.extensions;e._RegisteredPlugins[i.toLowerCase()]={plugin:t,isBinary:!1}}else{var r=t.extensions;Object.keys(r).forEach((function(i){e._RegisteredPlugins[i.toLowerCase()]={plugin:t,isBinary:r[i].isBinary}}))}},e.ImportMesh=function(t,i,r,n,o,a,s,l,c){if(void 0===r&&(r=""),void 0===n&&(n=M.LastCreatedScene),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null),void 0===l&&(l=null),void 0===c&&(c=""),!n)return ae.Error("No scene available to import mesh to"),null;var u=e._GetFileInfo(i,r);if(!u)return null;var h={};n.addPendingData(h);var d=function(){n.removePendingData(h)},p=function(t,i){var r=e._FormatErrorMessage(u,t,i);s?s(n,r,new bt(r,yt.SceneLoaderError,i)):ae.Error(r),d()},f=a?function(e){try{a(e)}catch(e){p("Error in onProgress callback: "+e,e)}}:void 0,_=function(e,t,i,r,a,s,l,c){if(n.importedMeshesFiles.push(u.url),o)try{o(e,t,i,r,a,s,l,c)}catch(e){p("Error in onSuccess callback: "+e,e)}n.removePendingData(h)};return e._LoadData(u,n,(function(e,i,r){if(e.rewriteRootURL&&(u.rootUrl=e.rewriteRootURL(u.rootUrl,r)),e.importMesh){var o=[],a=[],s=[];if(!e.importMesh(t,n,i,u.rootUrl,o,a,s,p))return;n.loadingPluginName=e.name,_(o,a,s,[],[],[],[],[])}else e.importMeshAsync(t,n,i,u.rootUrl,f,u.name).then((function(t){n.loadingPluginName=e.name,_(t.meshes,t.particleSystems,t.skeletons,t.animationGroups,t.transformNodes,t.geometries,t.lights,t.spriteManagers)})).catch((function(e){p(e.message,e)}))}),f,p,d,l,c)},e.ImportMeshAsync=function(t,i,r,n,o,a,s){return void 0===r&&(r=""),void 0===n&&(n=M.LastCreatedScene),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=""),new Promise((function(l,c){e.ImportMesh(t,i,r,n,(function(e,t,i,r,n,o,a,s){l({meshes:e,particleSystems:t,skeletons:i,animationGroups:r,transformNodes:n,geometries:o,lights:a,spriteManagers:s})}),o,(function(e,t,i){c(i||new Error(t))}),a,s)}))},e.Load=function(t,i,r,n,o,a,s,l){return void 0===i&&(i=""),void 0===r&&(r=M.LastCreatedEngine),void 0===n&&(n=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null),void 0===l&&(l=""),r?e.Append(t,i,new pn(r),n,o,a,s,l):(rr.Error("No engine available"),null)},e.LoadAsync=function(t,i,r,n,o,a){return void 0===i&&(i=""),void 0===r&&(r=M.LastCreatedEngine),void 0===n&&(n=null),void 0===o&&(o=null),void 0===a&&(a=""),new Promise((function(s,l){e.Load(t,i,r,(function(e){s(e)}),n,(function(e,t,i){l(i||new Error(t))}),o,a)}))},e.Append=function(t,i,r,n,o,a,s,l){var c=this;if(void 0===i&&(i=""),void 0===r&&(r=M.LastCreatedScene),void 0===n&&(n=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null),void 0===l&&(l=""),!r)return ae.Error("No scene available to append to"),null;var u=e._GetFileInfo(t,i);if(!u)return null;var h={};r.addPendingData(h);var d=function(){r.removePendingData(h)};e.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,r.getEngine().displayLoadingUI(),r.executeWhenReady((function(){r.getEngine().hideLoadingUI(),c._ShowingLoadingScreen=!1})));var p=function(t,i){var n=e._FormatErrorMessage(u,t,i);a?a(r,n,new bt(n,yt.SceneLoaderError,i)):ae.Error(n),d()},f=o?function(e){try{o(e)}catch(e){p("Error in onProgress callback",e)}}:void 0,_=function(){if(n)try{n(r)}catch(e){p("Error in onSuccess callback",e)}r.removePendingData(h)};return e._LoadData(u,r,(function(e,t){if(e.load){if(!e.load(r,t,u.rootUrl,p))return;r.loadingPluginName=e.name,_()}else e.loadAsync(r,t,u.rootUrl,f,u.name).then((function(){r.loadingPluginName=e.name,_()})).catch((function(e){p(e.message,e)}))}),f,p,d,s,l)},e.AppendAsync=function(t,i,r,n,o,a){return void 0===i&&(i=""),void 0===r&&(r=M.LastCreatedScene),void 0===n&&(n=null),void 0===o&&(o=null),void 0===a&&(a=""),new Promise((function(s,l){e.Append(t,i,r,(function(e){s(e)}),n,(function(e,t,i){l(i||new Error(t))}),o,a)}))},e.LoadAssetContainer=function(t,i,r,n,o,a,s,l){if(void 0===i&&(i=""),void 0===r&&(r=M.LastCreatedScene),void 0===n&&(n=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null),void 0===l&&(l=""),!r)return ae.Error("No scene available to load asset container to"),null;var c=e._GetFileInfo(t,i);if(!c)return null;var u={};r.addPendingData(u);var h=function(){r.removePendingData(u)},d=function(t,i){var n=e._FormatErrorMessage(c,t,i);a?a(r,n,new bt(n,yt.SceneLoaderError,i)):ae.Error(n),h()},p=o?function(e){try{o(e)}catch(e){d("Error in onProgress callback",e)}}:void 0,f=function(e){if(n)try{n(e)}catch(e){d("Error in onSuccess callback",e)}r.removePendingData(u)};return e._LoadData(c,r,(function(e,t){if(e.loadAssetContainer){var i=e.loadAssetContainer(r,t,c.rootUrl,d);if(!i)return;i.populateRootNodes(),r.loadingPluginName=e.name,f(i)}else e.loadAssetContainerAsync?e.loadAssetContainerAsync(r,t,c.rootUrl,p,c.name).then((function(t){t.populateRootNodes(),r.loadingPluginName=e.name,f(t)})).catch((function(e){d(e.message,e)})):d("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")}),p,d,h,s,l)},e.LoadAssetContainerAsync=function(t,i,r,n,o){return void 0===i&&(i=""),void 0===r&&(r=M.LastCreatedScene),void 0===n&&(n=null),void 0===o&&(o=null),new Promise((function(a,s){e.LoadAssetContainer(t,i,r,(function(e){a(e)}),n,(function(e,t,i){s(i||new Error(t))}),o)}))},e.ImportAnimations=function(e,t,i,r,n,o,a,s,l,c){if(void 0===t&&(t=""),void 0===i&&(i=M.LastCreatedScene),void 0===r&&(r=!0),void 0===n&&(n=Os.Clean),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null),void 0===l&&(l=null),void 0===c&&(c=null),i){if(r){for(var u=0,h=i.animatables;u<h.length;u++)h[u].reset();i.stopAllAnimations(),i.animationGroups.slice().forEach((function(e){e.dispose()})),i.getNodes().forEach((function(e){e.animations&&(e.animations=[])}))}else switch(n){case Os.Clean:i.animationGroups.slice().forEach((function(e){e.dispose()}));break;case Os.Stop:i.animationGroups.forEach((function(e){e.stop()}));break;case Os.Sync:i.animationGroups.forEach((function(e){e.reset(),e.restart()}));break;case Os.NoSync:break;default:return void ae.Error("Unknown animation group loading mode value '"+n+"'")}var d=i.animatables.length;this.LoadAssetContainer(e,t,i,(function(e){e.mergeAnimationsTo(i,i.animatables.slice(d),o),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),a&&a(i)}),s,l,c)}else ae.Error("No scene available to load animations to")},e.ImportAnimationsAsync=function(t,i,r,n,o,a,s,l,c,u){return void 0===i&&(i=""),void 0===r&&(r=M.LastCreatedScene),void 0===n&&(n=!0),void 0===o&&(o=Os.Clean),void 0===a&&(a=null),void 0===s&&(s=null),void 0===l&&(l=null),void 0===c&&(c=null),void 0===u&&(u=null),new Promise((function(s,c){e.ImportAnimations(t,i,r,n,o,a,(function(e){s(e)}),l,(function(e,t,i){c(i||new Error(t))}),u)}))},e.NO_LOGGING=u.SCENELOADER_NO_LOGGING,e.MINIMAL_LOGGING=u.SCENELOADER_MINIMAL_LOGGING,e.SUMMARY_LOGGING=u.SCENELOADER_SUMMARY_LOGGING,e.DETAILED_LOGGING=u.SCENELOADER_DETAILED_LOGGING,e.OnPluginActivatedObservable=new f,e._RegisteredPlugins={},e._ShowingLoadingScreen=!1,e}(),ws=function(e){function t(t,i,r){void 0===r&&(r=!0);var n=e.call(this,t,i)||this;return n._normalMatrix=new z,n._storeEffectOnSubMeshes=r,n}return m(t,e),t.prototype.getEffect=function(){return this._storeEffectOnSubMeshes?this._activeEffect:e.prototype.getEffect.call(this)},t.prototype.isReady=function(e,t){return!!e&&(!this._storeEffectOnSubMeshes||!e.subMeshes||0===e.subMeshes.length||this.isReadyForSubMesh(e,e.subMeshes[0],t))},t.prototype._isReadyForSubMesh=function(e){var t=e.materialDefines;return!(this.checkReadyOnEveryCall||!e.effect||!t||t._renderId!==this.getScene().getRenderId())},t.prototype.bindOnlyWorldMatrix=function(e){this._activeEffect.setMatrix("world",e)},t.prototype.bindOnlyNormalMatrix=function(e){this._activeEffect.setMatrix("normalMatrix",e)},t.prototype.bind=function(e,t){t&&this.bindForSubMesh(e,t,t.subMeshes[0])},t.prototype._afterBind=function(t,i,r){void 0===i&&(i=null),e.prototype._afterBind.call(this,t,i,r),this.getScene()._cachedEffect=i,r?r._drawWrapper._forceRebindOnNextCall=!1:this._drawWrapper._forceRebindOnNextCall=!1},t.prototype._mustRebind=function(e,t,i,r){return void 0===r&&(r=1),i._drawWrapper._forceRebindOnNextCall||e.isCachedMaterialInvalid(this,t,r)},t.prototype.dispose=function(t,i,r){this._activeEffect=void 0,e.prototype.dispose.call(this,t,i,r)},t}(Ca);!function(e){e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=4]="Vector2",e[e.Vector3=8]="Vector3",e[e.Vector4=16]="Vector4",e[e.Color3=32]="Color3",e[e.Color4=64]="Color4",e[e.Matrix=128]="Matrix",e[e.Object=256]="Object",e[e.AutoDetect=1024]="AutoDetect",e[e.BasedOnInput=2048]="BasedOnInput",e[e.All=4095]="All"}(Ns||(Ns={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Neutral=4]="Neutral",e[e.VertexAndFragment=3]="VertexAndFragment"}(Fs||(Fs={}));var Bs,Us,Vs=function(){function e(){this.supportUniformBuffers=!1,this.attributes=[],this.uniforms=[],this.constants=[],this.samplers=[],this.functions={},this.extensions={},this.prePassOutput={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}return Object.defineProperty(e.prototype,"shaderLanguage",{get:function(){return this.sharedData.nodeMaterial.shaderLanguage},enumerable:!1,configurable:!0}),e.prototype.finalize=function(e){var t=e.sharedData.emitComments,i=this.target===Fs.Fragment;this.shaderLanguage===pt.WGSL?this.compilationString=i?"\n".concat(t?"//Entry point\n":"","@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n").concat(this.compilationString):"\n".concat(t?"//Entry point\n":"","@vertex\nfn main(input: VertexInputs) -> FragmentInputs{\n").concat(this.compilationString):this.compilationString="\n".concat(t?"//Entry point\n":"","void main(void) {\n").concat(this.compilationString),this._constantDeclaration&&(this.compilationString="\n".concat(t?"//Constants\n":"").concat(this._constantDeclaration,"\n").concat(this.compilationString));var r="";for(var n in this.functions)r+=this.functions[n]+"\n";if(this.compilationString="\n".concat(r,"\n").concat(this.compilationString),!i&&this._varyingTransfer&&(this.compilationString="".concat(this.compilationString,"\n").concat(this._varyingTransfer)),this._injectAtEnd&&(this.compilationString="".concat(this.compilationString,"\n").concat(this._injectAtEnd)),this.compilationString="".concat(this.compilationString,"\n}"),this.sharedData.varyingDeclaration&&(this.compilationString="\n".concat(t?"//Varyings\n":"").concat(this.sharedData.varyingDeclaration,"\n").concat(this.compilationString)),this._samplerDeclaration&&(this.compilationString="\n".concat(t?"//Samplers\n":"").concat(this._samplerDeclaration,"\n").concat(this.compilationString)),this._uniformDeclaration&&(this.compilationString="\n".concat(t?"//Uniforms\n":"").concat(this._uniformDeclaration,"\n").concat(this.compilationString)),this._attributeDeclaration&&!i&&(this.compilationString="\n".concat(t?"//Attributes\n":"").concat(this._attributeDeclaration,"\n").concat(this.compilationString)),this.shaderLanguage!==pt.WGSL)for(var o in this.compilationString="precision highp float;\n"+this.compilationString,this.compilationString="#if defined(WEBGL2) || defines(WEBGPU)\nprecision highp sampler2DArray;\n#endif\n"+this.compilationString,i&&(this.compilationString="#if defined(PREPASS)\r\n#extension GL_EXT_draw_buffers : require\r\nlayout(location = 0) out highp vec4 glFragData[SCENE_MRT_COUNT];\r\nhighp vec4 gl_FragColor;\r\n#endif\r\n"+this.compilationString),this.extensions){var a=this.extensions[o];this.compilationString="\n".concat(a,"\n").concat(this.compilationString)}this._builtCompilationString=this.compilationString},Object.defineProperty(e.prototype,"_repeatableContentAnchor",{get:function(){return"###___ANCHOR".concat(this._repeatableContentAnchorIndex++,"___###")},enumerable:!1,configurable:!0}),e.prototype._getFreeVariableName=function(e){return e=e.replace(/[^a-zA-Z_]+/g,""),void 0===this.sharedData.variableNames[e]?(this.sharedData.variableNames[e]=0,"output"===e||"texture"===e?e+this.sharedData.variableNames[e]:e):(this.sharedData.variableNames[e]++,e+this.sharedData.variableNames[e])},e.prototype._getFreeDefineName=function(e){return void 0===this.sharedData.defineNames[e]?this.sharedData.defineNames[e]=0:this.sharedData.defineNames[e]++,e+this.sharedData.defineNames[e]},e.prototype._excludeVariableName=function(e){this.sharedData.variableNames[e]=0},e.prototype._emit2DSampler=function(e,t){void 0===t&&(t=""),this.samplers.indexOf(e)<0&&(this.shaderLanguage===pt.WGSL?(this._samplerDeclaration+="var ".concat(e,": sampler;\n"),this._samplerDeclaration+="var ".concat(t,": texture_2d<f32>;\n")):this._samplerDeclaration+="uniform sampler2D ".concat(e,";\n"),this.samplers.push(e))},e.prototype._emit2DArraySampler=function(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+="uniform sampler2DArray ".concat(e,";\n"),this.samplers.push(e))},e.prototype._getGLType=function(e){switch(e){case Ns.Float:return"float";case Ns.Int:return"int";case Ns.Vector2:return"vec2";case Ns.Color3:case Ns.Vector3:return"vec3";case Ns.Color4:case Ns.Vector4:return"vec4";case Ns.Matrix:return"mat4"}return""},e.prototype._getShaderType=function(e){var t=this.shaderLanguage===pt.WGSL;switch(e){case Ns.Float:return t?"f32":"float";case Ns.Int:return t?"i32":"int";case Ns.Vector2:return t?"vec2<f32>":"vec2";case Ns.Color3:case Ns.Vector3:return t?"vec3<f32>":"vec3";case Ns.Color4:case Ns.Vector4:return t?"vec4<f32>":"vec4";case Ns.Matrix:return t?"mat4x4<f32>":"mat4"}return""},e.prototype._emitExtension=function(e,t,i){void 0===i&&(i=""),this.extensions[e]||(i&&(t="#if ".concat(i,"\n").concat(t,"\n#endif")),this.extensions[e]=t)},e.prototype._emitFunction=function(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+"\n"+t),this.functions[e]=t)},e.prototype._emitCodeFromInclude=function(e,t,i){if(i&&i.repeatKey)return"#include<".concat(e,">").concat(i.substitutionVars?"("+i.substitutionVars+")":"","[0..").concat(i.repeatKey,"]\n");var r=Ei.IncludesShadersStore[e]+"\n";if(this.sharedData.emitComments&&(r=t+"\n"+r),!i)return r;if(i.replaceStrings)for(var n=0;n<i.replaceStrings.length;n++){var o=i.replaceStrings[n];r=r.replace(o.search,o.replace)}return r},e.prototype._emitFunctionFromInclude=function(e,t,i,r){void 0===r&&(r="");var n=e+r;if(!this.functions[n]){if(!i||!(i.removeAttributes||i.removeUniforms||i.removeVaryings||i.removeIfDef||i.replaceStrings))return i&&i.repeatKey?this.functions[n]="#include<".concat(e,">").concat(i.substitutionVars?"("+i.substitutionVars+")":"","[0..").concat(i.repeatKey,"]\n"):this.functions[n]="#include<".concat(e,">").concat((null==i?void 0:i.substitutionVars)?"("+(null==i?void 0:i.substitutionVars)+")":"","\n"),void(this.sharedData.emitComments&&(this.functions[n]=t+"\n"+this.functions[n]));var o=li.GetIncludesShadersStore(this.shaderLanguage);if(this.functions[n]=o[e],this.sharedData.emitComments&&(this.functions[n]=t+"\n"+this.functions[n]),i.removeIfDef&&(this.functions[n]=this.functions[n].replace(/^\s*?#ifdef.+$/gm,""),this.functions[n]=this.functions[n].replace(/^\s*?#endif.*$/gm,""),this.functions[n]=this.functions[n].replace(/^\s*?#else.*$/gm,""),this.functions[n]=this.functions[n].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[n]=this.functions[n].replace(/\s*?attribute .+?;/g,"\n")),i.removeUniforms&&(this.functions[n]=this.functions[n].replace(/\s*?uniform .*?;/g,"\n")),i.removeVaryings&&(this.functions[n]=this.functions[n].replace(/\s*?(varying|in) .+?;/g,"\n")),i.replaceStrings)for(var a=0;a<i.replaceStrings.length;a++){var s=i.replaceStrings[a];this.functions[n]=this.functions[n].replace(s.search,s.replace)}}},e.prototype._registerTempVariable=function(e){return-1===this.sharedData.temps.indexOf(e)&&(this.sharedData.temps.push(e),!0)},e.prototype._emitVaryingFromString=function(e,t,i,r){if(void 0===i&&(i=""),void 0===r&&(r=!1),-1!==this.sharedData.varyings.indexOf(e))return!1;this.sharedData.varyings.push(e),i&&(i.startsWith("defined(")?this.sharedData.varyingDeclaration+="#if ".concat(i,"\n"):this.sharedData.varyingDeclaration+="".concat(r?"#ifndef":"#ifdef"," ").concat(i,"\n"));var n=this._getShaderType(t);return this.shaderLanguage===pt.WGSL?this.sharedData.varyingDeclaration+="varying ".concat(e,": ").concat(n,";\n"):this.sharedData.varyingDeclaration+="varying ".concat(n," ").concat(e,";\n"),i&&(this.sharedData.varyingDeclaration+="#endif\n"),!0},e.prototype._getVaryingName=function(e){return this.shaderLanguage===pt.WGSL?(this.target!==Fs.Fragment?"vertexOutputs.":"fragmentInputs.")+e:e},e.prototype._emitUniformFromString=function(e,t,i,r){if(void 0===i&&(i=""),void 0===r&&(r=!1),-1===this.uniforms.indexOf(e)){this.uniforms.push(e),i&&(i.startsWith("defined(")?this._uniformDeclaration+="#if ".concat(i,"\n"):this._uniformDeclaration+="".concat(r?"#ifndef":"#ifdef"," ").concat(i,"\n"));var n=this._getShaderType(t);this.shaderLanguage===pt.WGSL?this._uniformDeclaration+="uniform ".concat(e,": ").concat(n,";\n"):this._uniformDeclaration+="uniform ".concat(n," ").concat(e,";\n"),i&&(this._uniformDeclaration+="#endif\n")}},e.prototype._generateTertiary=function(e,t,i){return this.shaderLanguage===pt.WGSL?"select(".concat(t,", ").concat(e,", ").concat(i,")"):"".concat(i," ? ").concat(e," : ").concat(t)},e.prototype._emitFloat=function(e){return e.toString()===e.toFixed(0)?"".concat(e,".0"):e.toString()},e.prototype._declareOutput=function(e){return this._declareLocalVar(e.associatedVariableName,e.type)},e.prototype._declareLocalVar=function(e,t){return this.shaderLanguage===pt.WGSL?"var ".concat(e,": ").concat(this._getShaderType(t)):"".concat(this._getShaderType(t)," ").concat(e)},e.prototype._convertVariableDeclarationToWGSL=function(e,t,i){return i.replace(new RegExp("(".concat(e,")\\s+(\\w+)"),"g"),"var $2: ".concat(t))},e.prototype._convertVariableConstructorsToWGSL=function(e,t,i){return i.replace(new RegExp("(".concat(e,")\\("),"g")," ".concat(t,"("))},e.prototype._convertOutParametersToWGSL=function(e){return e.replace(new RegExp("out\\s+var\\s+(\\w+)\\s*:\\s*(\\w+)","g"),"$1: ptr<function, $2>")},e.prototype._convertFunctionsToWGSL=function(e){var t=e.match(/var\s+(\w+)\s*:\s*(\w+)\((.*)\)/);if(t){var i=t[1],r=t[2],n=t[3].replace(/var\s/g,"");return e.replace(t[0],"fn ".concat(i,"(").concat(n,") -> ").concat(r))}return e},e.prototype._babylonSLtoWGSL=function(e){return e=this._convertVariableDeclarationToWGSL("void","voidnull",e),e=this._convertVariableDeclarationToWGSL("int","i32",e),e=this._convertVariableDeclarationToWGSL("uint","u32",e),e=this._convertVariableDeclarationToWGSL("float","f32",e),e=this._convertVariableDeclarationToWGSL("vec2","vec2f",e),e=this._convertVariableDeclarationToWGSL("vec3","vec3f",e),e=this._convertVariableDeclarationToWGSL("vec4","vec4f",e),e=this._convertVariableDeclarationToWGSL("mat2","mat2x2f",e),e=this._convertVariableDeclarationToWGSL("mat3","mat3x3f",e),e=this._convertVariableDeclarationToWGSL("mat4","mat4x4f",e),e=this._convertVariableConstructorsToWGSL("float","f32",e),e=this._convertVariableConstructorsToWGSL("vec2","vec2f",e),e=this._convertVariableConstructorsToWGSL("vec3","vec3f",e),e=this._convertVariableConstructorsToWGSL("vec4","vec4f",e),e=this._convertVariableConstructorsToWGSL("mat2","mat2x2f",e),e=this._convertVariableConstructorsToWGSL("mat3","mat3x3f",e),e=this._convertVariableConstructorsToWGSL("mat4","mat4x4f",e),e=(e=this._convertOutParametersToWGSL(e)).replace(/\[\*\]/g,"*"),(e=this._convertFunctionsToWGSL(e)).replace(/\s->\svoidnull/g,"")},e.prototype._babylonSLtoGLSL=function(e){return e.replace(/\[\*\]/g,"")},e}(),ks=function(){function e(){this.temps=[],this.varyings=[],this.varyingDeclaration="",this.inputBlocks=[],this.textureBlocks=[],this.bindableBlocks=[],this.forcedBindableBlocks=[],this.blocksWithFallbacks=[],this.blocksWithDefines=[],this.repeatableContentBlocks=[],this.dynamicUniformBlocks=[],this.blockingBlocks=[],this.animatedInputs=[],this.variableNames={},this.defineNames={},this.hints={needWorldViewMatrix:!1,needWorldViewProjectionMatrix:!1,needAlphaBlending:!1,needAlphaTesting:!1},this.checks={emitVertex:!1,emitFragment:!1,notConnectedNonOptionalInputs:new Array},this.allowEmptyVertexProgram=!1,this.variableNames.position=0,this.variableNames.normal=0,this.variableNames.tangent=0,this.variableNames.uv=0,this.variableNames.uv2=0,this.variableNames.uv3=0,this.variableNames.uv4=0,this.variableNames.uv5=0,this.variableNames.uv6=0,this.variableNames.color=0,this.variableNames.matricesIndices=0,this.variableNames.matricesWeights=0,this.variableNames.matricesIndicesExtra=0,this.variableNames.matricesWeightsExtra=0,this.variableNames.diffuseBase=0,this.variableNames.specularBase=0,this.variableNames.worldPos=0,this.variableNames.shadow=0,this.variableNames.view=0,this.variableNames.vTBN=0,this.defineNames.MAINUV0=0,this.defineNames.MAINUV1=0,this.defineNames.MAINUV2=0,this.defineNames.MAINUV3=0,this.defineNames.MAINUV4=0,this.defineNames.MAINUV5=0,this.defineNames.MAINUV6=0,this.defineNames.MAINUV7=0}return e.prototype.emitErrors=function(){var e="";this.checks.emitVertex||this.allowEmptyVertexProgram||(e+="NodeMaterial does not have a vertex output. You need to at least add a block that generates a glPosition value.\n"),this.checks.emitFragment||(e+="NodeMaterial does not have a fragment output. You need to at least add a block that generates a glFragColor value.\n");for(var t=0,i=this.checks.notConnectedNonOptionalInputs;t<i.length;t++){var r=i[t];e+="input ".concat(r.name," from block ").concat(r.ownerBlock.name,"[").concat(r.ownerBlock.getClassName(),"] is not connected and is not optional.\n")}if(e)throw"Build of NodeMaterial failed:\n"+e},e}(),Gs=function(){function e(e){if(this._keys=[],this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1,this._externalProperties=e,e)for(var t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._setDefaultValue(t)}return Object.defineProperty(e.prototype,"isDirty",{get:function(){return this._isDirty},enumerable:!1,configurable:!0}),e.prototype.markAsProcessed=function(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._arePrePassDirty=!1,this._areImageProcessingDirty=!1},e.prototype.markAsUnprocessed=function(){this._isDirty=!0},e.prototype.markAllAsDirty=function(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!1,this._areImageProcessingDirty=!0,this._isDirty=!0},e.prototype.markAsImageProcessingDirty=function(){this._areImageProcessingDirty=!0,this._isDirty=!0},e.prototype.markAsLightDirty=function(e){void 0===e&&(e=!1),this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||e,this._isDirty=!0},e.prototype.markAsAttributesDirty=function(){this._areAttributesDirty=!0,this._isDirty=!0},e.prototype.markAsTexturesDirty=function(){this._areTexturesDirty=!0,this._isDirty=!0},e.prototype.markAsFresnelDirty=function(){this._areFresnelDirty=!0,this._isDirty=!0},e.prototype.markAsMiscDirty=function(){this._areMiscDirty=!0,this._isDirty=!0},e.prototype.markAsPrePassDirty=function(){this._arePrePassDirty=!0,this._isDirty=!0},e.prototype.rebuild=function(){this._keys.length=0;for(var e=0,t=Object.keys(this);e<t.length;e++){var i=t[e];"_"!==i[0]&&this._keys.push(i)}if(this._externalProperties)for(var r in this._externalProperties)-1===this._keys.indexOf(r)&&this._keys.push(r)},e.prototype.isEqual=function(e){if(this._keys.length!==e._keys.length)return!1;for(var t=0;t<this._keys.length;t++){var i=this._keys[t];if(this[i]!==e[i])return!1}return!0},e.prototype.cloneTo=function(e){this._keys.length!==e._keys.length&&(e._keys=this._keys.slice(0));for(var t=0;t<this._keys.length;t++){var i=this._keys[t];e[i]=this[i]}},e.prototype.reset=function(){var e=this;this._keys.forEach((function(t){return e._setDefaultValue(t)}))},e.prototype._setDefaultValue=function(e){var t,i,r,n,o,a=null!==(r=null===(i=null===(t=this._externalProperties)||void 0===t?void 0:t[e])||void 0===i?void 0:i.type)&&void 0!==r?r:typeof this[e],s=null===(o=null===(n=this._externalProperties)||void 0===n?void 0:n[e])||void 0===o?void 0:o.default;switch(a){case"number":this[e]=null!=s?s:0;break;case"string":this[e]=null!=s?s:"";break;default:this[e]=null!=s&&s}},e.prototype.toString=function(){for(var e="",t=0;t<this._keys.length;t++){var i=this._keys[t],r=this[i];switch(typeof r){case"number":case"string":e+="#define "+i+" "+r+"\n";break;default:r&&(e+="#define "+i+"\n")}}return e},e}();!function(e){e[e.Compatible=0]="Compatible",e[e.TypeIncompatible=1]="TypeIncompatible",e[e.TargetIncompatible=2]="TargetIncompatible",e[e.HierarchyIssue=3]="HierarchyIssue"}(Bs||(Bs={})),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(Us||(Us={}));var zs=function(){function e(e,t,i){this._connectedPointBackingField=null,this._endpoints=new Array,this._typeConnectionSourceBackingField=null,this._defaultConnectionPointTypeBackingField=null,this._linkedConnectionSourceBackingField=null,this._acceptedConnectionPointType=null,this._type=Ns.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new f,this.onDisconnectionObservable=new f,this.onTypeChangedObservable=new f,this._isTypeChangeObservableNotifying=!1,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=Fs.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}return e.AreEquivalentTypes=function(e,t){switch(e){case Ns.Vector3:if(t===Ns.Color3)return!0;break;case Ns.Vector4:if(t===Ns.Color4)return!0;break;case Ns.Color3:if(t===Ns.Vector3)return!0;break;case Ns.Color4:if(t===Ns.Vector4)return!0}return!1},Object.defineProperty(e.prototype,"_connectedPoint",{get:function(){return this._connectedPointBackingField},set:function(e){var t,i=this;this._connectedPointBackingField!==e&&(null===(t=this._connectedPointTypeChangedObserver)||void 0===t||t.remove(),this._updateTypeDependentState((function(){return i._connectedPointBackingField=e})),this._connectedPointBackingField&&(this._connectedPointTypeChangedObserver=this._connectedPointBackingField.onTypeChangedObservable.add((function(){i._notifyTypeChanged()}))))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"_typeConnectionSource",{get:function(){return this._typeConnectionSourceBackingField},set:function(e){var t,i=this;this._typeConnectionSourceBackingField!==e&&(null===(t=this._typeConnectionSourceTypeChangedObserver)||void 0===t||t.remove(),this._updateTypeDependentState((function(){return i._typeConnectionSourceBackingField=e})),this._typeConnectionSourceBackingField&&(this._typeConnectionSourceTypeChangedObserver=this._typeConnectionSourceBackingField.onTypeChangedObservable.add((function(){i._notifyTypeChanged()}))))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"_defaultConnectionPointType",{get:function(){return this._defaultConnectionPointTypeBackingField},set:function(e){var t=this;this._updateTypeDependentState((function(){return t._defaultConnectionPointTypeBackingField=e}))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"_linkedConnectionSource",{get:function(){return this._linkedConnectionSourceBackingField},set:function(e){var t,i=this;this._linkedConnectionSourceBackingField!==e&&(null===(t=this._linkedConnectionSourceTypeChangedObserver)||void 0===t||t.remove(),this._updateTypeDependentState((function(){return i._linkedConnectionSourceBackingField=e})),this._linkedConnectionSourceBackingField&&(this._linkedConnectionSourceTypeChangedObserver=this._linkedConnectionSourceBackingField.onTypeChangedObservable.add((function(){i._notifyTypeChanged()}))))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"direction",{get:function(){return this._direction},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"declarationVariableName",{get:function(){return this._ownerBlock.isInput?this._ownerBlock.declarationVariableName:this._enforceAssociatedVariableName&&this._associatedVariableName||!this._connectedPoint?this._associatedVariableName:this._connectedPoint.declarationVariableName},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"associatedVariableName",{get:function(){return this._ownerBlock.isInput?this._ownerBlock.associatedVariableName:this._enforceAssociatedVariableName&&this._associatedVariableName||!this._connectedPoint?this._associatedVariableName:this._connectedPoint.associatedVariableName},set:function(e){this._associatedVariableName=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"innerType",{get:function(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"type",{get:function(){if(this._type===Ns.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.type}if(this._type===Ns.BasedOnInput){if(this._typeConnectionSource)return!this._typeConnectionSource.isConnected&&this._defaultConnectionPointType?this._defaultConnectionPointType:this._typeConnectionSource.type;if(this._defaultConnectionPointType)return this._defaultConnectionPointType}return this._type},set:function(e){var t=this;this._updateTypeDependentState((function(){return t._type=e}))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"target",{get:function(){return this._prioritizeVertex&&this._ownerBlock?this._target!==Fs.VertexAndFragment?this._target:this._ownerBlock.target===Fs.Fragment?Fs.Fragment:Fs.Vertex:this._target},set:function(e){this._target=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isConnected",{get:function(){return null!==this.connectedPoint||this.hasEndpoints},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isConnectedToInputBlock",{get:function(){return null!==this.connectedPoint&&this.connectedPoint.ownerBlock.isInput},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connectInputBlock",{get:function(){return this.isConnectedToInputBlock?this.connectedPoint.ownerBlock:null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connectedPoint",{get:function(){return this._connectedPoint},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"ownerBlock",{get:function(){return this._ownerBlock},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sourceBlock",{get:function(){return this._connectedPoint?this._connectedPoint.ownerBlock:null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connectedBlocks",{get:function(){return 0===this._endpoints.length?[]:this._endpoints.map((function(e){return e.ownerBlock}))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"endpoints",{get:function(){return this._endpoints},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hasEndpoints",{get:function(){return this._endpoints&&this._endpoints.length>0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isDirectlyConnectedToVertexOutput",{get:function(){if(!this.hasEndpoints)return!1;for(var e=0,t=this._endpoints;e<t.length;e++){var i=t[e];if(i.ownerBlock.target===Fs.Vertex)return!0;if((i.ownerBlock.target===Fs.Neutral||i.ownerBlock.target===Fs.VertexAndFragment)&&i.ownerBlock.outputs.some((function(e){return e.isDirectlyConnectedToVertexOutput})))return!0}return!1},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isConnectedInVertexShader",{get:function(){if(this.target===Fs.Vertex)return!0;if(!this.hasEndpoints)return!1;for(var e=0,t=this._endpoints;e<t.length;e++){var i=t[e];if(i.ownerBlock.target===Fs.Vertex)return!0;if(i.target===Fs.Vertex)return!0;if((i.ownerBlock.target===Fs.Neutral||i.ownerBlock.target===Fs.VertexAndFragment)&&i.ownerBlock.outputs.some((function(e){return e.isConnectedInVertexShader})))return!0}return!1},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isConnectedInFragmentShader",{get:function(){if(this.target===Fs.Fragment)return!0;if(!this.hasEndpoints)return!1;for(var e=0,t=this._endpoints;e<t.length;e++){var i=t[e];if(i.ownerBlock.target===Fs.Fragment)return!0;if((i.ownerBlock.target===Fs.Neutral||i.ownerBlock.target===Fs.VertexAndFragment)&&i.ownerBlock.isConnectedInFragmentShader())return!0}return!1},enumerable:!1,configurable:!0}),e.prototype.createCustomInputBlock=function(){return null},e.prototype.getClassName=function(){return"NodeMaterialConnectionPoint"},e.prototype.canConnectTo=function(e){return this.checkCompatibilityState(e)===Bs.Compatible},e.prototype.checkCompatibilityState=function(t){var i=this._ownerBlock,r=t.ownerBlock;if(i.target===Fs.Fragment){if(r.target===Fs.Vertex)return Bs.TargetIncompatible;for(var n=0,o=r.outputs;n<o.length;n++){var a=o[n];if(a.ownerBlock.target!=Fs.Neutral&&a.isConnectedInVertexShader)return Bs.TargetIncompatible}}if(this.type!==t.type&&t.innerType!==Ns.AutoDetect)return e.AreEquivalentTypes(this.type,t.type)||t.acceptedConnectionPointTypes&&-1!==t.acceptedConnectionPointTypes.indexOf(this.type)||t._acceptedConnectionPointType&&e.AreEquivalentTypes(t._acceptedConnectionPointType.type,this.type)?Bs.Compatible:Bs.TypeIncompatible;if(t.excludedConnectionPointTypes&&-1!==t.excludedConnectionPointTypes.indexOf(this.type))return Bs.TypeIncompatible;var s=r,l=i;return this.direction===Us.Input&&(s=i,l=r),s.isAnAncestorOf(l)?Bs.HierarchyIssue:Bs.Compatible},e.prototype.connectTo=function(e,t){if(void 0===t&&(t=!1),!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this},e.prototype.disconnectFrom=function(e){var t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this._enforceAssociatedVariableName=!1,e._enforceAssociatedVariableName=!1,this.onDisconnectionObservable.notifyObservers(e),e.onDisconnectionObservable.notifyObservers(this)),this},e.prototype.addExcludedConnectionPointFromAllowedTypes=function(e){for(var t=1;t<Ns.All;)e&t||this.excludedConnectionPointTypes.push(t),t<<=1},e.prototype.serialize=function(e){void 0===e&&(e=!0);var t={};return t.name=this.name,t.displayName=this.displayName,e&&this.connectedPoint&&(t.inputName=this.name,t.targetBlockId=this.connectedPoint.ownerBlock.uniqueId,t.targetConnectionName=this.connectedPoint.name,t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),(this.isExposedOnFrame||this.exposedPortPosition>=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t},e.prototype.dispose=function(){this.onConnectionObservable.clear(),this.onDisconnectionObservable.clear(),this.onTypeChangedObservable.clear(),this._connectedPoint=null,this._typeConnectionSource=null,this._linkedConnectionSource=null},e.prototype._updateTypeDependentState=function(e){var t=this.type;e(),this.type!==t&&this._notifyTypeChanged()},e.prototype._notifyTypeChanged=function(){this._isTypeChangeObservableNotifying||(this._isTypeChangeObservableNotifying=!0,this.onTypeChangedObservable.notifyObservers(this.type),this._isTypeChangeObservableNotifying=!1)},e}(),Ws=function(){function e(e,t,i){void 0===t&&(t=Fs.Vertex),void 0===i&&(i=!1),this._isFinalMerger=!1,this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=new Array,this._outputs=new Array,this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=t,this._originalTargetIsNeutral=t===Fs.Neutral,this._isFinalMerger=i,this._isInput="InputBlock"===this.getClassName(),this._isTeleportOut="NodeMaterialTeleportOutBlock"===this.getClassName(),this._isTeleportIn="NodeMaterialTeleportInBlock"===this.getClassName(),this._name=e,this.uniqueId=cn.UniqueId}return Object.defineProperty(e.prototype,"name",{get:function(){return this._name},set:function(e){this.validateBlockName(e)&&(this._name=e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isUnique",{get:function(){return this._isUnique},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isFinalMerger",{get:function(){return this._isFinalMerger},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isInput",{get:function(){return this._isInput},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isTeleportOut",{get:function(){return this._isTeleportOut},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isTeleportIn",{get:function(){return this._isTeleportIn},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"buildId",{get:function(){return this._buildId},set:function(e){this._buildId=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"target",{get:function(){return this._target},set:function(e){this._target&e||(this._target=e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"inputs",{get:function(){return this._inputs},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"outputs",{get:function(){return this._outputs},enumerable:!1,configurable:!0}),e.prototype.getInputByName=function(e){var t=this._inputs.filter((function(t){return t.name===e}));return t.length?t[0]:null},e.prototype.getOutputByName=function(e){var t=this._outputs.filter((function(t){return t.name===e}));return t.length?t[0]:null},e.prototype._setInitialTarget=function(e){this._target=e,this._originalTargetIsNeutral=e===Fs.Neutral},e.prototype.initialize=function(e){},e.prototype.bind=function(e,t,i,r){},e.prototype._writeVariable=function(e){return e.connectedPoint?"".concat(e.associatedVariableName):"0."},e.prototype._writeFloat=function(e){var t=e.toString();return-1===t.indexOf(".")&&(t+=".0"),"".concat(t)},e.prototype.getClassName=function(){return"NodeMaterialBlock"},e.prototype.isConnectedInFragmentShader=function(){return this.outputs.some((function(e){return e.isConnectedInFragmentShader}))},e.prototype.registerInput=function(e,t,i,r,n){return void 0===i&&(i=!1),(n=null!=n?n:new zs(e,this,Us.Input)).type=t,n.isOptional=i,r&&(n.target=r),this._inputs.push(n),this},e.prototype.registerOutput=function(e,t,i,r){return(r=null!=r?r:new zs(e,this,Us.Output)).type=t,i&&(r.target=i),this._outputs.push(r),this},e.prototype.getFirstAvailableInput=function(e){void 0===e&&(e=null);for(var t=0,i=this._inputs;t<i.length;t++){var r=i[t];if(!(r.connectedPoint||e&&e.type!==r.type&&r.type!==Ns.AutoDetect))return r}return null},e.prototype.getFirstAvailableOutput=function(e){void 0===e&&(e=null);for(var t=0,i=this._outputs;t<i.length;t++){var r=i[t];if(!e||!e.target||e.target===Fs.Neutral||e.target&r.target)return r}return null},e.prototype.getSiblingOutput=function(e){var t=this._outputs.indexOf(e);return-1===t||t>=this._outputs.length?null:this._outputs[t+1]},e.prototype.isAnAncestorOf=function(e){for(var t=0,i=this._outputs;t<i.length;t++){var r=i[t];if(r.hasEndpoints)for(var n=0,o=r.endpoints;n<o.length;n++){var a=o[n];if(a.ownerBlock===e)return!0;if(a.ownerBlock.isAnAncestorOf(e))return!0}}return!1},e.prototype.connectTo=function(e,t){if(0!==this._outputs.length){for(var i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),r=!0;r;){var n=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&n&&i.canConnectTo(n))i.connectTo(n),r=!1;else{if(!i)throw"Unable to find a compatible match";i=this.getSiblingOutput(i)}}return this}},e.prototype._buildBlock=function(e){},e.prototype.updateUniformsAndSamples=function(e,t,i,r){},e.prototype.provideFallbacks=function(e,t){},e.prototype.initializeDefines=function(e,t,i,r){void 0===r&&(r=!1)},e.prototype.prepareDefines=function(e,t,i,r,n){void 0===r&&(r=!1)},e.prototype.autoConfigure=function(e,t){void 0===t&&(t=function(){return!0})},e.prototype.replaceRepeatableContent=function(e,t,i,r){},Object.defineProperty(e.prototype,"willBeGeneratedIntoVertexShaderFromFragmentShader",{get:function(){return!(this.isInput||this.isFinalMerger||this._outputs.some((function(e){return e.isDirectlyConnectedToVertexOutput}))||this.target===Fs.Vertex||this.target!==Fs.VertexAndFragment&&this.target!==Fs.Neutral||!this._outputs.some((function(e){return e.isConnectedInVertexShader})))},enumerable:!1,configurable:!0}),e.prototype.isReady=function(e,t,i,r){return void 0===r&&(r=!1),!0},e.prototype._linkConnectionTypes=function(e,t,i){void 0===i&&(i=!1),i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]},e.prototype._processBuild=function(e,t,i,r){e.build(t,r);var n=null!=t._vertexState,o=e._buildTarget===Fs.Vertex&&e.target!==Fs.VertexAndFragment;if(n&&(!(e.target&e._buildTarget)||!(e.target&i.target)||this.target!==Fs.VertexAndFragment&&o)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){var a=i.connectedPoint;if(t._vertexState._emitVaryingFromString("v_"+a.declarationVariableName,a.type)){var s=t.shaderLanguage===pt.WGSL?"vertexOutputs.":"";t._vertexState.compilationString+="".concat(s).concat("v_"+a.declarationVariableName," = ").concat(a.associatedVariableName,";\n")}var l=t.shaderLanguage===pt.WGSL?"fragmentInputs.":"";i.associatedVariableName=l+"v_"+a.declarationVariableName,i._enforceAssociatedVariableName=!0}},e.prototype.validateBlockName=function(e){for(var t=0,i=["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"];t<i.length;t++)if(e===i[t])return!1;return!0},e.prototype._customBuildStep=function(e,t){},e.prototype.build=function(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(var i=0,r=this._outputs;i<r.length;i++)(c=r[i]).associatedVariableName||(c.associatedVariableName=e._getFreeVariableName(c.name));for(var n=0,o=this._inputs;n<o.length;n++){var a=o[n];if(a.connectedPoint){if(this.target!==Fs.Neutral){if(!(a.target&this.target))continue;if(!(a.target&e.target))continue}(d=a.connectedPoint.ownerBlock)&&d!==this&&this._processBuild(d,e,a,t)}else a.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(a)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&ae.Log("".concat(e.target===Fs.Vertex?"Vertex shader":"Fragment shader",": Building ").concat(this.name," [").concat(this.getClassName(),"]")),this.isFinalMerger)switch(e.target){case Fs.Vertex:e.sharedData.checks.emitVertex=!0;break;case Fs.Fragment:e.sharedData.checks.emitFragment=!0}!this.isInput&&e.sharedData.emitComments&&(e.compilationString+="\n//".concat(this.name,"\n")),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target;for(var s=0,l=this._outputs;s<l.length;s++){var c;if((c=l[s]).target&e.target)for(var u=0,h=c.endpoints;u<h.length;u++){var d,p=h[u];(d=p.ownerBlock)&&d.target&e.target&&-1!==t.indexOf(d)&&this._processBuild(d,e,p,t)}}return!1},e.prototype._inputRename=function(e){return e},e.prototype._outputRename=function(e){return e},e.prototype._dumpPropertiesCode=function(){var e=this._codeVariableName;return"".concat(e,".visibleInInspector = ").concat(this.visibleInInspector,";\n").concat(e,".visibleOnFrame = ").concat(this.visibleOnFrame,";\n").concat(e,".target = ").concat(this.target,";\n")},e.prototype._dumpCode=function(e,t){t.push(this);var i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||"".concat(this.getClassName(),"_").concat(this.uniqueId),-1!==e.indexOf(this._codeVariableName)){var r=0;do{r++,this._codeVariableName=i+r}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);var n="\n// ".concat(this.getClassName(),"\n");this.comments&&(n+="// ".concat(this.comments,"\n")),n+="var ".concat(this._codeVariableName," = new BABYLON.").concat(this.getClassName(),'("').concat(this.name,'");\n'),n+=this._dumpPropertiesCode();for(var o=0,a=this.inputs;o<a.length;o++){var s=a[o];if(s.isConnected){var l=s.connectedPoint.ownerBlock;-1===t.indexOf(l)&&(n+=l._dumpCode(e,t))}}for(var c=0,u=this.outputs;c<u.length;c++){var h=u[c];if(h.hasEndpoints)for(var d=0,p=h.endpoints;d<p.length;d++)(l=p[d].ownerBlock)&&-1===t.indexOf(l)&&(n+=l._dumpCode(e,t))}return n},e.prototype._dumpCodeForOutputConnections=function(e){var t="";if(-1!==e.indexOf(this))return t;e.push(this);for(var i=0,r=this.inputs;i<r.length;i++){var n=r[i];if(n.isConnected){var o=n.connectedPoint,a=o.ownerBlock;t+=a._dumpCodeForOutputConnections(e),t+="".concat(a._codeVariableName,".").concat(a._outputRename(o.name),".connectTo(").concat(this._codeVariableName,".").concat(this._inputRename(n.name),");\n")}}return t},e.prototype.clone=function(e,t){void 0===t&&(t="");var i=this.serialize(),r=s(i.customType);if(r){var n=new r;return n._deserialize(i,e,t),n}return null},e.prototype.serialize=function(){var e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.comments=this.comments,e.visibleInInspector=this.visibleInInspector,e.visibleOnFrame=this.visibleOnFrame,e.target=this.target,e.inputs=[],e.outputs=[];for(var t=0,i=this.inputs;t<i.length;t++){var r=i[t];e.inputs.push(r.serialize())}for(var n=0,o=this.outputs;n<o.length;n++){var a=o[n];e.outputs.push(a.serialize(!1))}return e},e.prototype._deserialize=function(e,t,i,r){var n;this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=null!==(n=e.target)&&void 0!==n?n:this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)},e.prototype._deserializePortDisplayNamesAndExposedOnFrame=function(e){var t=this,i=e.inputs,r=e.outputs;i&&i.forEach((function(e,i){e.displayName&&(t.inputs[i].displayName=e.displayName),e.isExposedOnFrame&&(t.inputs[i].isExposedOnFrame=e.isExposedOnFrame,t.inputs[i].exposedPortPosition=e.exposedPortPosition)})),r&&r.forEach((function(e,i){e.displayName&&(t.outputs[i].displayName=e.displayName),e.isExposedOnFrame&&(t.outputs[i].isExposedOnFrame=e.isExposedOnFrame,t.outputs[i].exposedPortPosition=e.exposedPortPosition)}))},e.prototype.dispose=function(){for(var e=0,t=this.inputs;e<t.length;e++)t[e].dispose();for(var i=0,r=this.outputs;i<r.length;i++)r[i].dispose()},e}(),Hs=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.complementW=1,i.complementZ=0,i.target=Fs.Vertex,i.registerInput("vector",Ns.AutoDetect),i.registerInput("transform",Ns.Matrix),i.registerOutput("output",Ns.Vector4),i.registerOutput("xyz",Ns.Vector3),i._inputs[0].onConnectionObservable.add((function(e){if(e.ownerBlock.isInput){var t=e.ownerBlock;"normal"!==t.name&&"tangent"!==t.name||(i.complementW=0)}})),i}return m(t,e),t.prototype.getClassName=function(){return"TransformBlock"},Object.defineProperty(t.prototype,"vector",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xyz",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"transform",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this.vector,r=this.transform,n=t._getShaderType(Ns.Vector4),o=t._getShaderType(Ns.Vector3);if(i.connectedPoint){if(0===this.complementW){var a="//".concat(this.name);t._emitFunctionFromInclude("helperFunctions",a),t.sharedData.blocksWithDefines.push(this);var s=t._getFreeVariableName("".concat(r.associatedVariableName,"_NUS"));switch(t.shaderLanguage===pt.WGSL?t.compilationString+="let ".concat(s,": mat3x3f = mat3x3f(").concat(r.associatedVariableName,"[0].xyz, ").concat(r.associatedVariableName,"[1].xyz, ").concat(r.associatedVariableName,"[2].xyz);\n"):t.compilationString+="mat3 ".concat(s," = mat3(").concat(r.associatedVariableName,");\n"),t.compilationString+="#ifdef NONUNIFORMSCALING\n",t.compilationString+="".concat(s," = transposeMat3(inverseMat3(").concat(s,"));\n"),t.compilationString+="#endif\n",i.connectedPoint.type){case Ns.Vector2:t.compilationString+=t._declareOutput(this.output)+" = ".concat(n,"(").concat(s," * ").concat(o,"(").concat(i.associatedVariableName,", ").concat(this._writeFloat(this.complementZ),"), ").concat(this._writeFloat(this.complementW),");\n");break;case Ns.Vector3:case Ns.Color3:t.compilationString+=t._declareOutput(this.output)+" = ".concat(n,"(").concat(s," * ").concat(i.associatedVariableName,", ").concat(this._writeFloat(this.complementW),");\n");break;default:t.compilationString+=t._declareOutput(this.output)+" = ".concat(n,"(").concat(s," * ").concat(i.associatedVariableName,".xyz, ").concat(this._writeFloat(this.complementW),");\n")}}else switch(s=r.associatedVariableName,i.connectedPoint.type){case Ns.Vector2:t.compilationString+=t._declareOutput(this.output)+" = ".concat(s," * ").concat(n,"(").concat(i.associatedVariableName,", ").concat(this._writeFloat(this.complementZ),", ").concat(this._writeFloat(this.complementW),");\n");break;case Ns.Vector3:case Ns.Color3:t.compilationString+=t._declareOutput(this.output)+" = ".concat(s," * ").concat(n,"(").concat(i.associatedVariableName,", ").concat(this._writeFloat(this.complementW),");\n");break;default:t.compilationString+=t._declareOutput(this.output)+" = ".concat(s," * ").concat(i.associatedVariableName,";\n")}this.xyz.hasEndpoints&&(t.compilationString+=t._declareOutput(this.xyz)+" = ".concat(this.output.associatedVariableName,".xyz;\n"))}return this},t.prototype.prepareDefines=function(e,t,i){e.nonUniformScaling&&i.setValue("NONUNIFORMSCALING",!0)},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.complementZ=this.complementZ,t.complementW=this.complementW,t},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),this.complementZ=void 0!==t.complementZ?t.complementZ:0,this.complementW=void 0!==t.complementW?t.complementW:1},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".complementZ = ").concat(this.complementZ,";\n")+"".concat(this._codeVariableName,".complementW = ").concat(this.complementW,";\n")},t}(Ws);a("BABYLON.TransformBlock",Hs);var Xs,js=function(e){function t(t){var i=e.call(this,t,Fs.Vertex,!0)||this;return i.registerInput("vector",Ns.Vector4),i}return m(t,e),t.prototype.getClassName=function(){return"VertexOutputBlock"},Object.defineProperty(t.prototype,"vector",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),t.prototype._isLogarithmicDepthEnabled=function(e,t){if(t)return!0;for(var i=0,r=e;i<r.length;i++)if(r[i].useLogarithmicDepth)return!0;return!1},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this.vector;return t.shaderLanguage===pt.WGSL?t.compilationString+="vertexOutputs.position = ".concat(i.associatedVariableName,";\n"):t.compilationString+="gl_Position = ".concat(i.associatedVariableName,";\n"),this._isLogarithmicDepthEnabled(t.sharedData.fragmentOutputNodes,t.sharedData.nodeMaterial.useLogarithmicDepth)&&(t._emitUniformFromString("logarithmicDepthConstant",Ns.Float),t._emitVaryingFromString("vFragmentDepth",Ns.Float),t.compilationString+="vFragmentDepth = 1.0 + gl_Position.w;\n",t.compilationString+="gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\n"),this},t}(Ws);function Ys(e,t,i,r){return void 0===t&&(t=Xs.Boolean),void 0===i&&(i="PROPERTIES"),function(n,o){var a=n._propStore;a||(a=[],n._propStore=a),a.push({propertyName:o,displayName:e,type:t,groupName:i,options:null!=r?r:{}})}}a("BABYLON.VertexOutputBlock",js),function(e){e[e.Boolean=0]="Boolean",e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=3]="Vector2",e[e.List=4]="List"}(Xs||(Xs={}));var Ks,Qs,qs=function(e){function t(t){var i=e.call(this,t,Fs.Fragment,!0)||this;return i.convertToGammaSpace=!1,i.convertToLinearSpace=!1,i.useLogarithmicDepth=!1,i.registerInput("rgba",Ns.Color4,!0),i.registerInput("rgb",Ns.AutoDetect,!0),i.registerInput("a",Ns.Float,!0),i.rgb.addExcludedConnectionPointFromAllowedTypes(Ns.Color3|Ns.Vector3|Ns.Float),i}return m(t,e),t.prototype.getClassName=function(){return"FragmentOutputBlock"},t.prototype.initialize=function(e){e._excludeVariableName("logarithmicDepthConstant"),e._excludeVariableName("vFragmentDepth")},Object.defineProperty(t.prototype,"rgba",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rgb",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"a",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),t.prototype.prepareDefines=function(e,t,i){i.setValue(this._linearDefineName,this.convertToLinearSpace,!0),i.setValue(this._gammaDefineName,this.convertToGammaSpace,!0)},t.prototype.bind=function(e,t,i){(this.useLogarithmicDepth||t.useLogarithmicDepth)&&i&&Ko(void 0,e,i.getScene())},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this.rgba,r=this.rgb,n=this.a;t.sharedData.hints.needAlphaBlending=i.isConnected||n.isConnected,t.sharedData.blocksWithDefines.push(this),(this.useLogarithmicDepth||t.sharedData.nodeMaterial.useLogarithmicDepth)&&(t._emitUniformFromString("logarithmicDepthConstant",Ns.Float),t._emitVaryingFromString("vFragmentDepth",Ns.Float),t.sharedData.bindableBlocks.push(this)),this._linearDefineName=t._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=t._getFreeDefineName("CONVERTTOGAMMA");var o="//".concat(this.name);t._emitFunctionFromInclude("helperFunctions",o);var a="gl_FragColor";t.shaderLanguage===pt.WGSL&&(a="fragmentOutputs.color");var s=t._getShaderType(Ns.Vector4);if(i.connectedPoint)n.isConnected?t.compilationString+="".concat(a," = ").concat(s,"(").concat(i.associatedVariableName,".rgb, ").concat(n.associatedVariableName,");\n"):t.compilationString+="".concat(a," = ").concat(i.associatedVariableName,";\n");else if(r.connectedPoint){var l="1.0";n.connectedPoint&&(l=n.associatedVariableName),r.connectedPoint.type===Ns.Float?t.compilationString+="".concat(a," = ").concat(s,"(").concat(r.associatedVariableName,", ").concat(r.associatedVariableName,", ").concat(r.associatedVariableName,", ").concat(l,");\n"):t.compilationString+="".concat(a," = ").concat(s,"(").concat(r.associatedVariableName,", ").concat(l,");\n")}else t.sharedData.checks.notConnectedNonOptionalInputs.push(i);return t.compilationString+="#ifdef ".concat(this._linearDefineName,"\n"),t.compilationString+="".concat(a," = toLinearSpace(").concat(a,");\n"),t.compilationString+="#endif\n",t.compilationString+="#ifdef ".concat(this._gammaDefineName,"\n"),t.compilationString+="".concat(a," = toGammaSpace(").concat(a,");\n"),t.compilationString+="#endif\n",(this.useLogarithmicDepth||t.sharedData.nodeMaterial.useLogarithmicDepth)&&(t.compilationString+="gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\n"),t.compilationString+="#if defined(PREPASS)\r\n",t.compilationString+="gl_FragData[0] = gl_FragColor;\r\n",t.compilationString+="#endif\r\n",this},t.prototype._dumpPropertiesCode=function(){var t=e.prototype._dumpPropertiesCode.call(this);return t+="".concat(this._codeVariableName,".convertToGammaSpace = ").concat(this.convertToGammaSpace,";\n"),(t+="".concat(this._codeVariableName,".convertToLinearSpace = ").concat(this.convertToLinearSpace,";\n"))+"".concat(this._codeVariableName,".useLogarithmicDepth = ").concat(this.useLogarithmicDepth,";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.convertToGammaSpace=this.convertToGammaSpace,t.convertToLinearSpace=this.convertToLinearSpace,t.useLogarithmicDepth=this.useLogarithmicDepth,t},t.prototype._deserialize=function(t,i,r){var n;e.prototype._deserialize.call(this,t,i,r),this.convertToGammaSpace=t.convertToGammaSpace,this.convertToLinearSpace=t.convertToLinearSpace,this.useLogarithmicDepth=null!==(n=t.useLogarithmicDepth)&&void 0!==n&&n},v([Ys("Convert to gamma space",Xs.Boolean,"PROPERTIES",{notifiers:{update:!0}})],t.prototype,"convertToGammaSpace",void 0),v([Ys("Convert to linear space",Xs.Boolean,"PROPERTIES",{notifiers:{update:!0}})],t.prototype,"convertToLinearSpace",void 0),v([Ys("Use logarithmic depth",Xs.Boolean,"PROPERTIES")],t.prototype,"useLogarithmicDepth",void 0),t}(Ws);a("BABYLON.FragmentOutputBlock",qs),function(e){e[e.Uniform=0]="Uniform",e[e.Attribute=1]="Attribute",e[e.Varying=2]="Varying",e[e.Undefined=3]="Undefined"}(Ks||(Ks={})),function(e){e[e.World=1]="World",e[e.View=2]="View",e[e.Projection=3]="Projection",e[e.ViewProjection=4]="ViewProjection",e[e.WorldView=5]="WorldView",e[e.WorldViewProjection=6]="WorldViewProjection",e[e.CameraPosition=7]="CameraPosition",e[e.FogColor=8]="FogColor",e[e.DeltaTime=9]="DeltaTime",e[e.CameraParameters=10]="CameraParameters",e[e.MaterialAlpha=11]="MaterialAlpha"}(Qs||(Qs={}));var Zs,Js=function(){function e(e,t){void 0===e&&(e=V.Zero()),void 0===t&&(t=V.Up()),this.position=e,this.normal=t}return e.prototype.clone=function(){return new e(this.position.clone(),this.normal.clone())},e}(),$s=function(){function e(e,t,i){void 0===e&&(e=V.Zero()),void 0===t&&(t=V.Up()),void 0===i&&(i=U.Zero()),this.position=e,this.normal=t,this.uv=i}return e.prototype.clone=function(){return new e(this.position.clone(),this.normal.clone(),this.uv.clone())},e}();!function(e){e[e.None=0]="None",e[e.Time=1]="Time",e[e.RealTime=2]="RealTime",e[e.MouseInfo=3]="MouseInfo"}(Zs||(Zs={}));var el={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},tl={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},il={particle_texturemask:!0},rl=function(e){function t(t,i,r){void 0===i&&(i=Fs.Vertex),void 0===r&&(r=Ns.AutoDetect);var n=e.call(this,t,i,!1)||this;return n._mode=Ks.Undefined,n._animationType=Zs.None,n._prefix="",n.min=0,n.max=0,n.isBoolean=!1,n.matrixMode=0,n._systemValue=null,n.isConstant=!1,n.groupInInspector="",n.onValueChangedObservable=new f,n.convertToGammaSpace=!1,n.convertToLinearSpace=!1,n._type=r,n.setDefaultValue(),n.registerOutput("output",r),n}return m(t,e),Object.defineProperty(t.prototype,"type",{get:function(){if(this._type===Ns.AutoDetect){if(this.isUniform&&null!=this.value){if(!isNaN(this.value))return this._type=Ns.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=Ns.Vector2,this._type;case"Vector3":return this._type=Ns.Vector3,this._type;case"Vector4":return this._type=Ns.Vector4,this._type;case"Color3":return this._type=Ns.Color3,this._type;case"Color4":return this._type=Ns.Color4,this._type;case"Matrix":return this._type=Ns.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=Ns.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=Ns.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=Ns.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=Ns.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case Qs.World:case Qs.WorldView:case Qs.WorldViewProjection:case Qs.View:case Qs.ViewProjection:case Qs.Projection:return this._type=Ns.Matrix,this._type;case Qs.CameraPosition:return this._type=Ns.Vector3,this._type;case Qs.FogColor:return this._type=Ns.Color3,this._type;case Qs.DeltaTime:case Qs.MaterialAlpha:return this._type=Ns.Float,this._type;case Qs.CameraParameters:return this._type=Ns.Vector4,this._type}}return this._type},enumerable:!1,configurable:!0}),t.prototype.validateBlockName=function(t){return!!this.isAttribute||e.prototype.validateBlockName.call(this,t)},Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.setAsAttribute=function(e){return this._mode=Ks.Attribute,e&&(this.name=e),this},t.prototype.setAsSystemValue=function(e){return this.systemValue=e,this},Object.defineProperty(t.prototype,"value",{get:function(){return this._storedValue},set:function(e){this.type===Ns.Float&&(this.isBoolean?e=e?1:0:this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e))),this._storedValue=e,this._mode=Ks.Uniform,this.onValueChangedObservable.notifyObservers(this)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"valueCallback",{get:function(){return this._valueCallback},set:function(e){this._valueCallback=e,this._mode=Ks.Uniform},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"declarationVariableName",{get:function(){return this._associatedVariableName},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"associatedVariableName",{get:function(){return this._prefix+this._associatedVariableName},set:function(e){this._associatedVariableName=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"animationType",{get:function(){return this._animationType},set:function(e){this._animationType=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isUndefined",{get:function(){return this._mode===Ks.Undefined},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isUniform",{get:function(){return this._mode===Ks.Uniform},set:function(e){this._mode=e?Ks.Uniform:Ks.Undefined,this.associatedVariableName=""},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isAttribute",{get:function(){return this._mode===Ks.Attribute},set:function(e){this._mode=e?Ks.Attribute:Ks.Undefined,this.associatedVariableName=""},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isVarying",{get:function(){return this._mode===Ks.Varying},set:function(e){this._mode=e?Ks.Varying:Ks.Undefined,this.associatedVariableName=""},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isSystemValue",{get:function(){return null!=this._systemValue},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"systemValue",{get:function(){return this._systemValue},set:function(e){this._mode=Ks.Uniform,this.associatedVariableName="",this._systemValue=e},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"InputBlock"},t.prototype.animate=function(e){switch(this._animationType){case Zs.Time:this.type===Ns.Float&&(this.value+=.01*e.getAnimationRatio());break;case Zs.RealTime:this.type===Ns.Float&&(this.value=(_t.Now-e.getEngine().startTime)/1e3);break;case Zs.MouseInfo:if(this.type===Ns.Vector4){var t=e._inputManager._originMouseEvent;if(t){var i=t.offsetX,r=t.offsetY,n=1&t.buttons?1:0,o=2&t.buttons?1:0;this.value=new k(i,r,n,o)}else this.value=new k(0,0,0,0)}}},t.prototype._emitDefine=function(e){return"!"===e[0]?"#ifndef ".concat(e.substring(1),"\n"):"#ifdef ".concat(e,"\n")},t.prototype.initialize=function(){this.associatedVariableName=""},t.prototype.setDefaultValue=function(){switch(this.type){case Ns.Float:this.value=0;break;case Ns.Vector2:this.value=U.Zero();break;case Ns.Vector3:this.value=V.Zero();break;case Ns.Vector4:this.value=k.Zero();break;case Ns.Color3:this.value=Z.White();break;case Ns.Color4:this.value=new J(1,1,1,1);break;case Ns.Matrix:this.value=z.Identity()}},t.prototype._emitConstant=function(e){switch(this.type){case Ns.Float:return"".concat(e._emitFloat(this.value));case Ns.Vector2:return"vec2(".concat(this.value.x,", ").concat(this.value.y,")");case Ns.Vector3:return"vec3(".concat(this.value.x,", ").concat(this.value.y,", ").concat(this.value.z,")");case Ns.Vector4:return"vec4(".concat(this.value.x,", ").concat(this.value.y,", ").concat(this.value.z,", ").concat(this.value.w,")");case Ns.Color3:return $.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&$.Color3[0].toGammaSpaceToRef($.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&$.Color3[0].toLinearSpaceToRef($.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),"vec3(".concat($.Color3[0].r,", ").concat($.Color3[0].g,", ").concat($.Color3[0].b,")");case Ns.Color4:return $.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&$.Color4[0].toGammaSpaceToRef($.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&$.Color4[0].toLinearSpaceToRef($.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),"vec4(".concat($.Color4[0].r,", ").concat($.Color4[0].g,", ").concat($.Color4[0].b,", ").concat($.Color4[0].a,")")}return""},Object.defineProperty(t.prototype,"_noContextSwitch",{get:function(){return tl[this.name]},enumerable:!1,configurable:!0}),t.prototype._emit=function(e,t){var i;if(this.isUniform){if(this._associatedVariableName||(this._associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(-1!==e.constants.indexOf(this.associatedVariableName))return;return e.constants.push(this.associatedVariableName),void(e._constantDeclaration+=e._declareOutput(this.output)+" = ".concat(this._emitConstant(e),";\n"))}if(-1!==e.uniforms.indexOf(this.associatedVariableName))return;e.uniforms.push(this.associatedVariableName),t&&(e._uniformDeclaration+=this._emitDefine(t));var r=e._getShaderType(this.type);e.shaderLanguage===pt.WGSL?(e._uniformDeclaration+="uniform ".concat(this._associatedVariableName,": ").concat(r,";\n"),this._prefix="uniforms."):e._uniformDeclaration+="uniform ".concat(r," ").concat(this.associatedVariableName,";\n"),t&&(e._uniformDeclaration+="#endif\n");var n=e.sharedData.hints;if(null!==this._systemValue&&void 0!==this._systemValue)switch(this._systemValue){case Qs.WorldView:n.needWorldViewMatrix=!0;break;case Qs.WorldViewProjection:n.needWorldViewProjectionMatrix=!0}else this._animationType!==Zs.None&&e.sharedData.animatedInputs.push(this)}else if(this.isAttribute){if(this.associatedVariableName=null!==(i=el[this.name])&&void 0!==i?i:this.name,this.target===Fs.Vertex&&e._vertexState)return void(tl[this.name]?il[this.name]?(e._emitUniformFromString(this.associatedVariableName,this.type,t),e.shaderLanguage===pt.WGSL&&(this._prefix="vertexInputs.")):e._emitVaryingFromString(this.associatedVariableName,this.type,t):this._emit(e._vertexState,t));if(-1!==e.attributes.indexOf(this.associatedVariableName))return;e.attributes.push(this.associatedVariableName),tl[this.name]?il[this.name]?e._emitUniformFromString(this.associatedVariableName,this.type,t):e._emitVaryingFromString(this.associatedVariableName,this.type,t):(t&&(e._attributeDeclaration+=this._emitDefine(t)),e.shaderLanguage===pt.WGSL?(e._attributeDeclaration+="attribute ".concat(this.associatedVariableName,": ").concat(e._getShaderType(this.type),";\n"),this._prefix="vertexInputs."):e._attributeDeclaration+="attribute ".concat(e._getShaderType(this.type)," ").concat(this.associatedVariableName,";\n"),t&&(e._attributeDeclaration+="#endif\n"))}},t.prototype._transmitWorld=function(e,t,i,r){if(this._systemValue){var n=this._associatedVariableName;switch(this._systemValue){case Qs.World:e.setMatrix(n,t);break;case Qs.WorldView:e.setMatrix(n,i);break;case Qs.WorldViewProjection:e.setMatrix(n,r)}}},t.prototype._transmit=function(e,t,i){if(!this.isAttribute){var r=this._associatedVariableName;if(this._systemValue)switch(this._systemValue){case Qs.World:case Qs.WorldView:case Qs.WorldViewProjection:return;case Qs.View:e.setMatrix(r,t.getViewMatrix());break;case Qs.Projection:e.setMatrix(r,t.getProjectionMatrix());break;case Qs.ViewProjection:e.setMatrix(r,t.getTransformMatrix());break;case Qs.CameraPosition:t.bindEyePosition(e,r,!0);break;case Qs.FogColor:e.setColor3(r,t.fogColor);break;case Qs.DeltaTime:e.setFloat(r,t.deltaTime/1e3);break;case Qs.CameraParameters:t.activeCamera&&e.setFloat4(r,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case Qs.MaterialAlpha:e.setFloat(r,i.alpha)}else{var n=this._valueCallback?this._valueCallback():this._storedValue;if(null!==n)switch(this.type){case Ns.Float:e.setFloat(r,n);break;case Ns.Int:e.setInt(r,n);break;case Ns.Color3:$.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&$.Color3[0].toGammaSpaceToRef($.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&$.Color3[0].toLinearSpaceToRef($.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(r,$.Color3[0]);break;case Ns.Color4:$.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&$.Color4[0].toGammaSpaceToRef($.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&$.Color4[0].toLinearSpaceToRef($.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(r,$.Color4[0]);break;case Ns.Vector2:e.setVector2(r,n);break;case Ns.Vector3:e.setVector3(r,n);break;case Ns.Vector4:e.setVector4(r,n);break;case Ns.Matrix:e.setMatrix(r,n)}}}},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t),(this.isUniform||this.isSystemValue)&&t.sharedData.inputBlocks.push(this),this._emit(t)},t.prototype._dumpPropertiesCode=function(){var t=this._codeVariableName;if(this.isAttribute)return e.prototype._dumpPropertiesCode.call(this)+"".concat(t,'.setAsAttribute("').concat(this.name,'");\n');if(this.isSystemValue)return e.prototype._dumpPropertiesCode.call(this)+"".concat(t,".setAsSystemValue(BABYLON.NodeMaterialSystemValues.").concat(Qs[this._systemValue],");\n");if(this.isUniform){var i=[],r="";switch(this.type){case Ns.Float:r="".concat(this.value);break;case Ns.Vector2:r="new BABYLON.Vector2(".concat(this.value.x,", ").concat(this.value.y,")");break;case Ns.Vector3:r="new BABYLON.Vector3(".concat(this.value.x,", ").concat(this.value.y,", ").concat(this.value.z,")");break;case Ns.Vector4:r="new BABYLON.Vector4(".concat(this.value.x,", ").concat(this.value.y,", ").concat(this.value.z,", ").concat(this.value.w,")");break;case Ns.Color3:r="new BABYLON.Color3(".concat(this.value.r,", ").concat(this.value.g,", ").concat(this.value.b,")"),this.convertToGammaSpace&&(r+=".toGammaSpace()"),this.convertToLinearSpace&&(r+=".toLinearSpace()");break;case Ns.Color4:r="new BABYLON.Color4(".concat(this.value.r,", ").concat(this.value.g,", ").concat(this.value.b,", ").concat(this.value.a,")"),this.convertToGammaSpace&&(r+=".toGammaSpace()"),this.convertToLinearSpace&&(r+=".toLinearSpace()");break;case Ns.Matrix:r="BABYLON.Matrix.FromArray([".concat(this.value.m,"])")}return i.push("".concat(t,".value = ").concat(r)),this.type===Ns.Float&&i.push("".concat(t,".min = ").concat(this.min),"".concat(t,".max = ").concat(this.max),"".concat(t,".isBoolean = ").concat(this.isBoolean),"".concat(t,".matrixMode = ").concat(this.matrixMode),"".concat(t,".animationType = BABYLON.AnimatedInputBlockTypes.").concat(Zs[this.animationType])),i.push("".concat(t,".isConstant = ").concat(this.isConstant)),i.push(""),e.prototype._dumpPropertiesCode.call(this)+i.join(";\n")}return e.prototype._dumpPropertiesCode.call(this)},t.prototype.dispose=function(){this.onValueChangedObservable.clear(),e.prototype.dispose.call(this)},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.type=this.type,t.mode=this._mode,t.systemValue=this._systemValue,t.animationType=this._animationType,t.min=this.min,t.max=this.max,t.isBoolean=this.isBoolean,t.matrixMode=this.matrixMode,t.isConstant=this.isConstant,t.groupInInspector=this.groupInInspector,t.convertToGammaSpace=this.convertToGammaSpace,t.convertToLinearSpace=this.convertToLinearSpace,null!=this._storedValue&&this._mode===Ks.Uniform&&(this._storedValue.asArray?(t.valueType="BABYLON."+this._storedValue.getClassName(),t.value=this._storedValue.asArray()):(t.valueType="number",t.value=this._storedValue)),t},t.prototype._deserialize=function(t,i,r){if(this._mode=t.mode,e.prototype._deserialize.call(this,t,i,r),this._type=t.type,this._systemValue=t.systemValue||t.wellKnownValue,this._animationType=t.animationType,this.min=t.min||0,this.max=t.max||0,this.isBoolean=!!t.isBoolean,this.matrixMode=t.matrixMode||0,this.isConstant=!!t.isConstant,this.groupInInspector=t.groupInInspector||"",this.convertToGammaSpace=!!t.convertToGammaSpace,this.convertToLinearSpace=!!t.convertToLinearSpace,"tangent"===t.name&&t.mode===Ks.Attribute&&t.type===Ns.Vector3&&(this._type=Ns.Vector4),t.valueType)if("number"===t.valueType)this._storedValue=t.value;else{var n=s(t.valueType);n&&(this._storedValue=n.FromArray(t.value))}},t}(Ws);a("BABYLON.InputBlock",rl);var nl=function(e){function t(t){var i=e.call(this,t,Fs.VertexAndFragment)||this;return i._samplerName="textureSampler",i.convertToGammaSpace=!1,i.convertToLinearSpace=!1,i._isUnique=!1,i.registerInput("uv",Ns.AutoDetect,!1,Fs.VertexAndFragment),i.registerOutput("rgba",Ns.Color4,Fs.Neutral),i.registerOutput("rgb",Ns.Color3,Fs.Neutral),i.registerOutput("r",Ns.Float,Fs.Neutral),i.registerOutput("g",Ns.Float,Fs.Neutral),i.registerOutput("b",Ns.Float,Fs.Neutral),i.registerOutput("a",Ns.Float,Fs.Neutral),i._inputs[0].addExcludedConnectionPointFromAllowedTypes(Ns.Vector2|Ns.Vector3|Ns.Vector4),i._inputs[0]._prioritizeVertex=!1,i}return m(t,e),t.prototype.getClassName=function(){return"CurrentScreenBlock"},Object.defineProperty(t.prototype,"uv",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rgba",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rgb",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"r",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"g",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"b",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"a",{get:function(){return this._outputs[5]},enumerable:!1,configurable:!0}),t.prototype.initialize=function(e){e._excludeVariableName("textureSampler")},Object.defineProperty(t.prototype,"target",{get:function(){return this.uv.isConnected?this.uv.sourceBlock.isInput?Fs.VertexAndFragment:Fs.Fragment:Fs.VertexAndFragment},enumerable:!1,configurable:!0}),t.prototype.prepareDefines=function(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)},t.prototype.isReady=function(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())},t.prototype._injectVertexCode=function(e){var t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,Ns.Vector2)),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,Ns.Vector2),e.compilationString+="".concat(this._mainUVName," = ").concat(t.associatedVariableName,".xy;\n"),this._outputs.some((function(e){return e.isConnectedInVertexShader}))){this._writeTextureRead(e,!0);for(var i=0,r=this._outputs;i<r.length;i++){var n=r[i];n.hasEndpoints&&this._writeOutput(e,n,n.name,!0)}}},t.prototype._writeTextureRead=function(e,t){void 0===t&&(t=!1);var i=this.uv;if(t){if(e.target===Fs.Fragment)return;e.compilationString+="vec4 ".concat(this._tempTextureRead," = texture2D(").concat(this._samplerName,", ").concat(i.associatedVariableName,");\n")}else this.uv.ownerBlock.target!==Fs.Fragment?e.compilationString+="vec4 ".concat(this._tempTextureRead," = texture2D(").concat(this._samplerName,", ").concat(this._mainUVName,");\n"):e.compilationString+="vec4 ".concat(this._tempTextureRead," = texture2D(").concat(this._samplerName,", ").concat(i.associatedVariableName,");\n")},t.prototype._writeOutput=function(e,t,i,r){if(void 0===r&&(r=!1),r){if(e.target===Fs.Fragment)return;e.compilationString+="".concat(e._declareOutput(t)," = ").concat(this._tempTextureRead,".").concat(i,";\n")}else this.uv.ownerBlock.target!==Fs.Fragment?(e.compilationString+="".concat(e._declareOutput(t)," = ").concat(this._tempTextureRead,".").concat(i,";\n"),e.compilationString+="#ifdef ".concat(this._linearDefineName,"\n"),e.compilationString+="".concat(t.associatedVariableName," = toGammaSpace(").concat(t.associatedVariableName,");\n"),e.compilationString+="#endif\n",e.compilationString+="#ifdef ".concat(this._gammaDefineName,"\n"),e.compilationString+="".concat(t.associatedVariableName," = toLinearSpace(").concat(t.associatedVariableName,");\n"),e.compilationString+="#endif\n"):e.compilationString+="".concat(e._declareOutput(t)," = ").concat(this._tempTextureRead,".").concat(i,";\n")},t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),this._tempTextureRead=t._getFreeVariableName("tempTextureRead"),t.sharedData.blockingBlocks.indexOf(this)<0&&t.sharedData.blockingBlocks.push(this),t.sharedData.textureBlocks.indexOf(this)<0&&t.sharedData.textureBlocks.push(this),t.sharedData.blocksWithDefines.indexOf(this)<0&&t.sharedData.blocksWithDefines.push(this),t.target!==Fs.Fragment)return t._emit2DSampler(this._samplerName),void this._injectVertexCode(t);if(this._outputs.some((function(e){return e.isConnectedInFragmentShader}))){t._emit2DSampler(this._samplerName),this._linearDefineName=t._getFreeDefineName("ISLINEAR"),this._gammaDefineName=t._getFreeDefineName("ISGAMMA");var i="//".concat(this.name);t._emitFunctionFromInclude("helperFunctions",i),this._writeTextureRead(t);for(var r=0,n=this._outputs;r<n.length;r++){var o=n[r];o.hasEndpoints&&this._writeOutput(t,o,o.name)}return this}},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.convertToGammaSpace=this.convertToGammaSpace,t.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(t.texture=this.texture.serialize()),t},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),this.convertToGammaSpace=t.convertToGammaSpace,this.convertToLinearSpace=!!t.convertToLinearSpace,t.texture&&(r=0===t.texture.url.indexOf("data:")?"":r,this.texture=Ja.Parse(t.texture,i,r))},t}(Ws);a("BABYLON.CurrentScreenBlock",nl);var ol=function(e){function t(t){var i=e.call(this,t,Fs.Fragment)||this;return i._samplerName="diffuseSampler",i.convertToGammaSpace=!1,i.convertToLinearSpace=!1,i._isUnique=!1,i.registerInput("uv",Ns.AutoDetect,!1,Fs.VertexAndFragment),i.registerOutput("rgba",Ns.Color4,Fs.Neutral),i.registerOutput("rgb",Ns.Color3,Fs.Neutral),i.registerOutput("r",Ns.Float,Fs.Neutral),i.registerOutput("g",Ns.Float,Fs.Neutral),i.registerOutput("b",Ns.Float,Fs.Neutral),i.registerOutput("a",Ns.Float,Fs.Neutral),i._inputs[0].addExcludedConnectionPointFromAllowedTypes(Ns.Vector2|Ns.Vector3|Ns.Vector4),i}return m(t,e),t.prototype.getClassName=function(){return"ParticleTextureBlock"},Object.defineProperty(t.prototype,"uv",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rgba",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rgb",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"r",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"g",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"b",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"a",{get:function(){return this._outputs[5]},enumerable:!1,configurable:!0}),t.prototype.initialize=function(e){e._excludeVariableName("diffuseSampler")},t.prototype.autoConfigure=function(e,t){if(void 0===t&&(t=function(){return!0}),!this.uv.isConnected){var i=e.getInputBlockByPredicate((function(e){return e.isAttribute&&"particle_uv"===e.name&&t(e)}));i||(i=new rl("uv")).setAsAttribute("particle_uv"),i.output.connectTo(this.uv)}},t.prototype.prepareDefines=function(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)},t.prototype.isReady=function(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())},t.prototype._writeOutput=function(e,t,i){e.compilationString+="".concat(e._declareOutput(t)," = ").concat(this._tempTextureRead,".").concat(i,";\n"),e.compilationString+="#ifdef ".concat(this._linearDefineName,"\n"),e.compilationString+="".concat(t.associatedVariableName," = toGammaSpace(").concat(t.associatedVariableName,");\n"),e.compilationString+="#endif\n",e.compilationString+="#ifdef ".concat(this._gammaDefineName,"\n"),e.compilationString+="".concat(t.associatedVariableName," = toLinearSpace(").concat(t.associatedVariableName,");\n"),e.compilationString+="#endif\n"},t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),t.target!==Fs.Vertex){this._tempTextureRead=t._getFreeVariableName("tempTextureRead"),t._emit2DSampler(this._samplerName),t.sharedData.blockingBlocks.push(this),t.sharedData.textureBlocks.push(this),t.sharedData.blocksWithDefines.push(this),this._linearDefineName=t._getFreeDefineName("ISLINEAR"),this._gammaDefineName=t._getFreeDefineName("ISGAMMA");var i="//".concat(this.name);t._emitFunctionFromInclude("helperFunctions",i),t.compilationString+="vec4 ".concat(this._tempTextureRead," = texture2D(").concat(this._samplerName,", ").concat(this.uv.associatedVariableName,");\n");for(var r=0,n=this._outputs;r<n.length;r++){var o=n[r];o.hasEndpoints&&this._writeOutput(t,o,o.name)}return this}},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.convertToGammaSpace=this.convertToGammaSpace,t.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(t.texture=this.texture.serialize()),t},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),this.convertToGammaSpace=t.convertToGammaSpace,this.convertToLinearSpace=!!t.convertToLinearSpace,t.texture&&(r=0===t.texture.url.indexOf("data:")?"":r,this.texture=Ja.Parse(t.texture,i,r))},t}(Ws);a("BABYLON.ParticleTextureBlock",ol);var al=function(e){function t(t){var i=e.call(this,t,Fs.Fragment)||this;return i._isUnique=!0,i.registerInput("color",Ns.Color4,!1,Fs.Fragment),i.registerOutput("rampColor",Ns.Color4,Fs.Fragment),i}return m(t,e),t.prototype.getClassName=function(){return"ParticleRampGradientBlock"},Object.defineProperty(t.prototype,"color",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rampColor",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.initialize=function(e){e._excludeVariableName("remapRanges"),e._excludeVariableName("rampSampler"),e._excludeVariableName("baseColor"),e._excludeVariableName("alpha"),e._excludeVariableName("remappedColorIndex"),e._excludeVariableName("rampColor"),e._excludeVariableName("finalAlpha")},t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),t.target!==Fs.Vertex)return t._emit2DSampler("rampSampler"),t._emitVaryingFromString("remapRanges",Ns.Vector4,"RAMPGRADIENT"),t.compilationString+="\n #ifdef RAMPGRADIENT\n vec4 baseColor = ".concat(this.color.associatedVariableName,";\n float alpha = ").concat(this.color.associatedVariableName,".a;\n\n float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0);\n\n vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.));\n baseColor.rgb *= rampColor.rgb;\n\n // Remapped alpha\n float finalAlpha = baseColor.a;\n baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0);\n\n ").concat(t._declareOutput(this.rampColor)," = baseColor;\n #else\n ").concat(t._declareOutput(this.rampColor)," = ").concat(this.color.associatedVariableName,";\n #endif\n "),this},t}(Ws);a("BABYLON.ParticleRampGradientBlock",al);var sl=function(e){function t(t){var i=e.call(this,t,Fs.Fragment)||this;return i._isUnique=!0,i.registerInput("color",Ns.Color4,!1,Fs.Fragment),i.registerInput("alphaTexture",Ns.Float,!1,Fs.Fragment),i.registerInput("alphaColor",Ns.Float,!1,Fs.Fragment),i.registerOutput("blendColor",Ns.Color4,Fs.Fragment),i}return m(t,e),t.prototype.getClassName=function(){return"ParticleBlendMultiplyBlock"},Object.defineProperty(t.prototype,"color",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"alphaTexture",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"alphaColor",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"blendColor",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.initialize=function(e){e._excludeVariableName("sourceAlpha")},t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),t.target!==Fs.Vertex)return t.compilationString+="\n #ifdef BLENDMULTIPLYMODE\n ".concat(t._declareOutput(this.blendColor),";\n float sourceAlpha = ").concat(this.alphaColor.associatedVariableName," * ").concat(this.alphaTexture.associatedVariableName,";\n ").concat(this.blendColor.associatedVariableName,".rgb = ").concat(this.color.associatedVariableName,".rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha);\n ").concat(this.blendColor.associatedVariableName,".a = ").concat(this.color.associatedVariableName,".a;\n #else\n ").concat(t._declareOutput(this.blendColor)," = ").concat(this.color.associatedVariableName,";\n #endif\n "),this},t}(Ws);a("BABYLON.ParticleBlendMultiplyBlock",sl);var ll=function(){function e(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}return e.prototype.unBindMesh=function(){this._mesh=null},e.prototype.addFallback=function(e,t){this._defines[e]||(e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)},e.prototype.addCPUSkinningFallback=function(e,t){this._mesh=t,e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e)},Object.defineProperty(e.prototype,"hasMoreFallbacks",{get:function(){return this._currentRank<=this._maxRank},enumerable:!1,configurable:!0}),e.prototype.reduce=function(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;for(var i=this._mesh.getScene(),r=0;r<i.meshes.length;r++){var n=i.meshes[r];if(n.material){if(n.computeBonesUsingShaders&&0!==n.numBoneInfluencers)if(n.material.getEffect()===t)n.computeBonesUsingShaders=!1;else if(n.subMeshes)for(var o=0,a=n.subMeshes;o<a.length;o++)if(a[o].effect===t){n.computeBonesUsingShaders=!1;break}}else!this._mesh.material&&n.computeBonesUsingShaders&&n.numBoneInfluencers>0&&(n.computeBonesUsingShaders=!1)}}else{var s=this._defines[this._currentRank];if(s)for(r=0;r<s.length;r++)e=e.replace("#define "+s[r],"");this._currentRank++}return e},e}();li.ShadersStore.postprocessVertexShader="attribute vec2 position;uniform vec2 scale;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=(position*madd+madd)*scale;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";var cl=function(){function e(e,t,i,r,n){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=r,this._depthStencilTexture=null,this.label=n}return Object.defineProperty(e.prototype,"depthStencilTexture",{get:function(){return this._depthStencilTexture},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"depthStencilTextureWithStencil",{get:function(){return this._depthStencilTextureWithStencil},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isCube",{get:function(){return this._isCube},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isMulti",{get:function(){return this._isMulti},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"is2DArray",{get:function(){return this.layers>0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"is3D",{get:function(){return this.depth>0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return this.width},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"width",{get:function(){return this._size.width||this._size},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"height",{get:function(){return this._size.height||this._size},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"layers",{get:function(){return this._size.layers||0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"depth",{get:function(){return this._size.depth||0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"texture",{get:function(){var e,t;return null!==(t=null===(e=this._textures)||void 0===e?void 0:e[0])&&void 0!==t?t:null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"textures",{get:function(){return this._textures},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"faceIndices",{get:function(){return this._faceIndices},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"layerIndices",{get:function(){return this._layerIndices},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"samples",{get:function(){return this._samples},enumerable:!1,configurable:!0}),e.prototype.setSamples=function(e,t,i){if(void 0===t&&(t=!0),void 0===i&&(i=!1),this.samples===e&&!i)return e;var r=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,r},e.prototype.setTextures=function(e){Array.isArray(e)?this._textures=e:this._textures=e?[e]:null},e.prototype.setTexture=function(e,t,i){void 0===t&&(t=0),void 0===i&&(i=!0),this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)},e.prototype.setLayerAndFaceIndices=function(e,t){this._layerIndices=e,this._faceIndices=t},e.prototype.setLayerAndFaceIndex=function(e,t,i){void 0===e&&(e=0),this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),void 0!==t&&t>=0&&(this._layerIndices[e]=t),void 0!==i&&i>=0&&(this._faceIndices[e]=i)},e.prototype.createDepthStencilTexture=function(e,t,i,r,n,o){var a;return void 0===e&&(e=0),void 0===t&&(t=!0),void 0===i&&(i=!1),void 0===r&&(r=1),void 0===n&&(n=u.TEXTUREFORMAT_DEPTH32_FLOAT),null===(a=this._depthStencilTexture)||void 0===a||a.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=o,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:r,depthTextureFormat:n,label:o},this),this._depthStencilTexture},e.prototype._shareDepth=function(e){this.shareDepth(e)},e.prototype.shareDepth=function(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,e._depthStencilTextureWithStencil=this._depthStencilTextureWithStencil,this._depthStencilTexture.incrementReferences())},e.prototype._swapAndDie=function(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)},e.prototype._cloneRenderTargetWrapper=function(){var e,t,i,r,n,o,a,s,l=null;if(this._isMulti){var c=this.textures;if(c&&c.length>0){var h=!1,d=c.length,p=-1,f=c[c.length-1]._source;f!==Ti.Depth&&f!==Ti.DepthStencil||(h=!0,p=c[c.length-1].format,d--);for(var _=[],m=[],g=[],v=[],y=[],b=[],T=[],E={},S=0;S<d;++S){var x=c[S];_.push(x.samplingMode),m.push(x.type),g.push(x.format),void 0!==(R=E[x.uniqueId])?(v.push(-1),T.push(0)):(E[x.uniqueId]=S,x.is2DArray?(v.push(u.TEXTURE_2D_ARRAY),T.push(x.depth)):x.isCube?(v.push(u.TEXTURE_CUBE_MAP),T.push(0)):x.is3D?(v.push(u.TEXTURE_3D),T.push(x.depth)):(v.push(u.TEXTURE_2D),T.push(0))),this._faceIndices&&y.push(null!==(e=this._faceIndices[S])&&void 0!==e?e:0),this._layerIndices&&b.push(null!==(t=this._layerIndices[S])&&void 0!==t?t:0)}var A={samplingModes:_,generateMipMaps:c[0].generateMipMaps,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:this._generateStencilBuffer,generateDepthTexture:h,depthTextureFormat:p,types:m,formats:g,textureCount:d,targetTypes:v,faceIndex:y,layerIndex:b,layerCounts:T,label:this.label},C={width:this.width,height:this.height,depth:this.depth};for(l=this._engine.createMultipleRenderTarget(C,A),S=0;S<d;++S)if(-1===v[S]){var R=E[c[S].uniqueId];l.setTexture(l.textures[R],S)}}}else{var P={};P.generateDepthBuffer=this._generateDepthBuffer,P.generateMipMaps=null!==(r=null===(i=this.texture)||void 0===i?void 0:i.generateMipMaps)&&void 0!==r&&r,P.generateStencilBuffer=this._generateStencilBuffer,P.samplingMode=null===(n=this.texture)||void 0===n?void 0:n.samplingMode,P.type=null===(o=this.texture)||void 0===o?void 0:o.type,P.format=null===(a=this.texture)||void 0===a?void 0:a.format,P.noColorAttachment=!this._textures,P.label=this.label,this.isCube?l=this._engine.createRenderTargetCubeTexture(this.width,P):(C={width:this.width,height:this.height,layers:this.is2DArray||this.is3D?null===(s=this.texture)||void 0===s?void 0:s.depth:void 0},l=this._engine.createRenderTargetTexture(C,P)),l.texture&&(l.texture.isReady=!0)}return l},e.prototype._swapRenderTargetWrapper=function(e){if(this._textures&&e._textures)for(var t=0;t<this._textures.length;++t)this._textures[t]._swapAndDie(e._textures[t],!1),e._textures[t].isReady=!0;this._depthStencilTexture&&e._depthStencilTexture&&(this._depthStencilTexture._swapAndDie(e._depthStencilTexture),e._depthStencilTexture.isReady=!0),this._textures=null,this._depthStencilTexture=null},e.prototype._rebuild=function(){var e=this._cloneRenderTargetWrapper();if(e){if(this._depthStencilTexture){var t=this._depthStencilTexture.samplingMode,i=this._depthStencilTexture.format,r=t===u.TEXTURE_BILINEAR_SAMPLINGMODE||t===u.TEXTURE_TRILINEAR_SAMPLINGMODE||t===u.TEXTURE_LINEAR_LINEAR_MIPNEAREST;e.createDepthStencilTexture(this._depthStencilTexture._comparisonFunction,r,this._depthStencilTextureWithStencil,this._depthStencilTexture.samples,i,this._depthStencilTextureLabel)}this.samples>1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}},e.prototype.releaseTextures=function(){var e,t;if(this._textures)for(var i=0;null!==(t=i<(null===(e=this._textures)||void 0===e?void 0:e.length))&&void 0!==t&&t;++i)this._textures[i].dispose();this._textures=null},e.prototype.dispose=function(e){var t;void 0===e&&(e=!1),e||(null===(t=this._depthStencilTexture)||void 0===t||t.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)},e}(),ul=function(e){function t(t,i,r,n,o){var a=e.call(this,t,i,r,n)||this;return a._framebuffer=null,a._depthStencilBuffer=null,a._MSAAFramebuffer=null,a._colorTextureArray=null,a._depthStencilTextureArray=null,a._disposeOnlyFramebuffers=!1,a._currentLOD=0,a._context=o,a}return m(t,e),t.prototype._cloneRenderTargetWrapper=function(){var t=null;return this._colorTextureArray&&this._depthStencilTextureArray?(t=this._engine.createMultiviewRenderTargetTexture(this.width,this.height)).texture.isReady=!0:t=e.prototype._cloneRenderTargetWrapper.call(this),t},t.prototype._swapRenderTargetWrapper=function(t){e.prototype._swapRenderTargetWrapper.call(this,t),t._framebuffer=this._framebuffer,t._depthStencilBuffer=this._depthStencilBuffer,t._MSAAFramebuffer=this._MSAAFramebuffer,t._colorTextureArray=this._colorTextureArray,t._depthStencilTextureArray=this._depthStencilTextureArray,this._framebuffer=this._depthStencilBuffer=this._MSAAFramebuffer=this._colorTextureArray=this._depthStencilTextureArray=null},t.prototype.createDepthStencilTexture=function(t,i,r,n,o,a){if(void 0===t&&(t=0),void 0===i&&(i=!0),void 0===r&&(r=!1),void 0===n&&(n=1),void 0===o&&(o=u.TEXTUREFORMAT_DEPTH32_FLOAT),this._depthStencilBuffer){var s=this._engine,l=s._currentFramebuffer,c=this._context;s._bindUnboundFramebuffer(this._framebuffer),c.framebufferRenderbuffer(c.FRAMEBUFFER,c.DEPTH_STENCIL_ATTACHMENT,c.RENDERBUFFER,null),c.framebufferRenderbuffer(c.FRAMEBUFFER,c.DEPTH_ATTACHMENT,c.RENDERBUFFER,null),c.framebufferRenderbuffer(c.FRAMEBUFFER,c.STENCIL_ATTACHMENT,c.RENDERBUFFER,null),s._bindUnboundFramebuffer(l),c.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null}return e.prototype.createDepthStencilTexture.call(this,t,i,r,n,o,a)},t.prototype.shareDepth=function(t){e.prototype.shareDepth.call(this,t);var i=this._context,r=this._depthStencilBuffer,n=t._MSAAFramebuffer||t._framebuffer,o=this._engine;t._depthStencilBuffer&&t._depthStencilBuffer!==r&&i.deleteRenderbuffer(t._depthStencilBuffer),t._depthStencilBuffer=r;var a=t._generateStencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;o._bindUnboundFramebuffer(n),i.framebufferRenderbuffer(i.FRAMEBUFFER,a,i.RENDERBUFFER,r),o._bindUnboundFramebuffer(null)},t.prototype._bindTextureRenderTarget=function(e,t,i,r){var n,o,a,s;if(void 0===t&&(t=0),void 0===r&&(r=0),e._hardwareTexture){var l=this._framebuffer,c=this._engine,u=c._currentFramebuffer;if(c._bindUnboundFramebuffer(l),c.webGLVersion>1){var h=(d=this._context)["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=null!==(o=null!=i?i:null===(n=this.layerIndices)||void 0===n?void 0:n[t])&&void 0!==o?o:0,d.framebufferTextureLayer(d.FRAMEBUFFER,h,e._hardwareTexture.underlyingResource,r,i)):e.isCube?(i=null!==(s=null!=i?i:null===(a=this.faceIndices)||void 0===a?void 0:a[t])&&void 0!==s?s:0,d.framebufferTexture2D(d.FRAMEBUFFER,h,d.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,r)):d.framebufferTexture2D(d.FRAMEBUFFER,h,d.TEXTURE_2D,e._hardwareTexture.underlyingResource,r)}else{h=(d=this._context)["COLOR_ATTACHMENT"+t+"_WEBGL"];var d,p=void 0!==i?d.TEXTURE_CUBE_MAP_POSITIVE_X+i:d.TEXTURE_2D;d.framebufferTexture2D(d.FRAMEBUFFER,h,p,e._hardwareTexture.underlyingResource,r)}c._bindUnboundFramebuffer(u)}},t.prototype.setTexture=function(t,i,r){void 0===i&&(i=0),void 0===r&&(r=!0),e.prototype.setTexture.call(this,t,i,r),this._bindTextureRenderTarget(t,i)},t.prototype.setLayerAndFaceIndices=function(t,i){var r,n;if(e.prototype.setLayerAndFaceIndices.call(this,t,i),this.textures&&this.layerIndices&&this.faceIndices)for(var o=null!==(n=null===(r=this._attachments)||void 0===r?void 0:r.length)&&void 0!==n?n:this.textures.length,a=0;a<o;a++){var s=this.textures[a];s&&(s.is2DArray||s.is3D?this._bindTextureRenderTarget(s,a,this.layerIndices[a]):s.isCube?this._bindTextureRenderTarget(s,a,this.faceIndices[a]):this._bindTextureRenderTarget(s,a))}},t.prototype.setLayerAndFaceIndex=function(t,i,r){if(void 0===t&&(t=0),e.prototype.setLayerAndFaceIndex.call(this,t,i,r),this.textures&&this.layerIndices&&this.faceIndices){var n=this.textures[t];n.is2DArray||n.is3D?this._bindTextureRenderTarget(this.textures[t],t,this.layerIndices[t]):n.isCube&&this._bindTextureRenderTarget(this.textures[t],t,this.faceIndices[t])}},t.prototype.dispose=function(t){void 0===t&&(t=this._disposeOnlyFramebuffers);var i=this._context;t||(this._colorTextureArray&&(this._context.deleteTexture(this._colorTextureArray),this._colorTextureArray=null),this._depthStencilTextureArray&&(this._context.deleteTexture(this._depthStencilTextureArray),this._depthStencilTextureArray=null)),this._framebuffer&&(i.deleteFramebuffer(this._framebuffer),this._framebuffer=null),this._depthStencilBuffer&&(i.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null),this._MSAAFramebuffer&&(i.deleteFramebuffer(this._MSAAFramebuffer),this._MSAAFramebuffer=null),e.prototype.dispose.call(this,t)},t}(cl);Er.prototype._createHardwareRenderTargetWrapper=function(e,t,i){var r=new ul(e,t,i,this,this._gl);return this._renderTargetWrapperCache.push(r),r},Er.prototype.createRenderTargetTexture=function(e,t){var i,r,n=this._createHardwareRenderTargetWrapper(!1,!1,e),o=!0,a=!1,s=!1,l=void 0,c=1,u=void 0;void 0!==t&&"object"==typeof t&&(o=null===(i=t.generateDepthBuffer)||void 0===i||i,a=!!t.generateStencilBuffer,s=!!t.noColorAttachment,l=t.colorAttachment,c=null!==(r=t.samples)&&void 0!==r?r:1,u=t.label);var h=l||(s?null:this._createInternalTexture(e,t,!0,Ti.RenderTarget)),d=e.width||e,p=e.height||e,f=this._currentFramebuffer,_=this._gl,m=_.createFramebuffer();return this._bindUnboundFramebuffer(m),n._depthStencilBuffer=this._setupFramebufferDepthAttachments(a,o,d,p),!h||h.is2DArray||h.is3D||_.framebufferTexture2D(_.FRAMEBUFFER,_.COLOR_ATTACHMENT0,_.TEXTURE_2D,h._hardwareTexture.underlyingResource,0),this._bindUnboundFramebuffer(f),n.label=null!=u?u:"RenderTargetWrapper",n._framebuffer=m,n._generateDepthBuffer=o,n._generateStencilBuffer=a,n.setTextures(h),this.updateRenderTargetTextureSampleCount(n,c),n},Er.prototype._createDepthStencilTexture=function(e,t){var i=this._gl,r=e.layers||0,n=e.depth||0,o=i.TEXTURE_2D;0!==r?o=i.TEXTURE_2D_ARRAY:0!==n&&(o=i.TEXTURE_3D);var a=new Pi(this,Ti.DepthStencil);if(a.label=t.label,!this._caps.depthTextureExtension)return ae.Error("Depth texture is not supported by your browser or hardware."),a;var s=g({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},t);if(this._bindTextureDirectly(o,a,!0),this._setupDepthStencilTexture(a,e,s.generateStencil,0!==s.comparisonFunction&&s.bilinearFiltering,s.comparisonFunction,s.samples),void 0!==s.depthTextureFormat){if(s.depthTextureFormat!==u.TEXTUREFORMAT_DEPTH16&&s.depthTextureFormat!==u.TEXTUREFORMAT_DEPTH24&&s.depthTextureFormat!==u.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8&&s.depthTextureFormat!==u.TEXTUREFORMAT_DEPTH24_STENCIL8&&s.depthTextureFormat!==u.TEXTUREFORMAT_DEPTH32_FLOAT&&s.depthTextureFormat!==u.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8)return ae.Error("Depth texture format is not supported."),a;a.format=s.depthTextureFormat}else a.format=s.generateStencil?u.TEXTUREFORMAT_DEPTH24_STENCIL8:u.TEXTUREFORMAT_DEPTH24;var l=a.format===u.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||a.format===u.TEXTUREFORMAT_DEPTH24_STENCIL8||a.format===u.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8,c=i.UNSIGNED_INT;a.format===u.TEXTUREFORMAT_DEPTH16?c=i.UNSIGNED_SHORT:a.format===u.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||a.format===u.TEXTUREFORMAT_DEPTH24_STENCIL8?c=i.UNSIGNED_INT_24_8:a.format===u.TEXTUREFORMAT_DEPTH32_FLOAT?c=i.FLOAT:a.format===u.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8&&(c=i.FLOAT_32_UNSIGNED_INT_24_8_REV);var h=l?i.DEPTH_STENCIL:i.DEPTH_COMPONENT,d=h;return this.webGLVersion>1&&(a.format===u.TEXTUREFORMAT_DEPTH16?d=i.DEPTH_COMPONENT16:a.format===u.TEXTUREFORMAT_DEPTH24?d=i.DEPTH_COMPONENT24:a.format===u.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||a.format===u.TEXTUREFORMAT_DEPTH24_STENCIL8?d=i.DEPTH24_STENCIL8:a.format===u.TEXTUREFORMAT_DEPTH32_FLOAT?d=i.DEPTH_COMPONENT32F:a.format===u.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8&&(d=i.DEPTH32F_STENCIL8)),a.is2DArray?i.texImage3D(o,0,d,a.width,a.height,r,0,h,c,null):a.is3D?i.texImage3D(o,0,d,a.width,a.height,n,0,h,c,null):i.texImage2D(o,0,d,a.width,a.height,0,h,c,null),this._bindTextureDirectly(o,null),this._internalTexturesCache.push(a),a},Er.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;var i=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null);var r=e.texture._hardwareTexture;if(r.releaseMSAARenderBuffers(),t>1&&"function"==typeof i.renderbufferStorageMultisample){var n=i.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=n,this._bindUnboundFramebuffer(e._MSAAFramebuffer);var o=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBABufferInternalSizedFormat(e.texture.type,e.texture.format,e.texture._useSRGBBuffer),i.COLOR_ATTACHMENT0,!1);if(!o)throw new Error("Unable to create multi sampled framebuffer");r.addMSAARenderBuffer(o)}else this._bindUnboundFramebuffer(e._framebuffer);return e.texture.samples=t,e._samples=t,e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t),this._bindUnboundFramebuffer(null),t};var hl=function(){function e(e,t,i,r,n,o,a,s,l,c,h,d,p,_,m,g){var v,y,b,T,E,S,x,A,C,R,P,I;void 0===a&&(a=u.TEXTURE_NEAREST_SAMPLINGMODE),void 0===c&&(c=null),void 0===h&&(h=u.TEXTURETYPE_UNSIGNED_INT),void 0===d&&(d="postprocess"),void 0===_&&(_=!1),void 0===m&&(m=u.TEXTUREFORMAT_RGBA),void 0===g&&(g=pt.GLSL),this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=u.ALPHA_DISABLE,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=u.SCALEMODE_FLOOR,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new ar(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new U(1,1),this._texelSize=U.Zero(),this.onActivateObservable=new f,this.onSizeChangedObservable=new f,this.onApplyObservable=new f,this.onBeforeRenderObservable=new f,this.onAfterRenderObservable=new f,this.name=e;var M=1,O=null;if(i&&!Array.isArray(i)){var D=i;i=null!==(v=D.uniforms)&&void 0!==v?v:null,r=null!==(y=D.samplers)&&void 0!==y?y:null,M=null!==(b=D.size)&&void 0!==b?b:1,o=null!==(T=D.camera)&&void 0!==T?T:null,a=null!==(E=D.samplingMode)&&void 0!==E?E:u.TEXTURE_NEAREST_SAMPLINGMODE,s=D.engine,l=D.reusable,c=null!==(S=D.defines)&&void 0!==S?S:null,h=null!==(x=D.textureType)&&void 0!==x?x:u.TEXTURETYPE_UNSIGNED_INT,d=null!==(A=D.vertexUrl)&&void 0!==A?A:"postprocess",p=D.indexParameters,_=null!==(C=D.blockCompilation)&&void 0!==C&&C,m=null!==(R=D.textureFormat)&&void 0!==R?R:u.TEXTUREFORMAT_RGBA,g=null!==(P=D.shaderLanguage)&&void 0!==P?P:pt.GLSL,O=null!==(I=D.uniformBuffers)&&void 0!==I?I:null}else n&&(M="number"==typeof n?n:{width:n.width,height:n.height});null!=o?(this._camera=o,this._scene=o.getScene(),o.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):s&&(this._engine=s,this._engine.postProcesses.push(this)),this._options=M,this.renderTargetSamplingMode=a||u.TEXTURE_NEAREST_SAMPLINGMODE,this._reusable=l||!1,this._textureType=h,this._textureFormat=m,this._shaderLanguage=g,this._samplers=r||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=d,this._parameters=i||[],this._parameters.push("scale"),this._uniformBuffers=O||[],this._indexParameters=p,this._drawWrapper=new ho(this._engine),_||this.updateEffect(c)}return e.RegisterShaderCodeProcessing=function(t,i){i?e._CustomShaderCodeProcessing[null!=t?t:""]=i:delete e._CustomShaderCodeProcessing[null!=t?t:""]},e._GetShaderCodeProcessing=function(t){var i;return null!==(i=e._CustomShaderCodeProcessing[t])&&void 0!==i?i:e._CustomShaderCodeProcessing[""]},Object.defineProperty(e.prototype,"samples",{get:function(){return this._samples},set:function(e){var t=this;this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach((function(e){e.setSamples(t._samples)}))},enumerable:!1,configurable:!0}),e.prototype.getEffectName=function(){return this._fragmentUrl},Object.defineProperty(e.prototype,"onActivate",{set:function(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onSizeChanged",{set:function(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onApply",{set:function(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onBeforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onAfterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"inputTexture",{get:function(){return this._textures.data[this._currentRenderTextureInd]},set:function(e){this._forcedOutputTexture=e},enumerable:!1,configurable:!0}),e.prototype.restoreDefaultInputTexture=function(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())},e.prototype.getCamera=function(){return this._camera},Object.defineProperty(e.prototype,"texelSize",{get:function(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)},enumerable:!1,configurable:!0}),e.prototype.getClassName=function(){return"PostProcess"},e.prototype.getEngine=function(){return this._engine},e.prototype.getEffect=function(){return this._drawWrapper.effect},e.prototype.shareOutputWith=function(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this},e.prototype.useOwnOutput=function(){0==this._textures.length&&(this._textures=new ar(2)),this._shareOutputWithPostProcess=null},e.prototype.updateEffect=function(t,i,r,n,o,a,s,l){var c,u,h=this;void 0===t&&(t=null),void 0===i&&(i=null),void 0===r&&(r=null);var d=e._GetShaderCodeProcessing(this.name);if(null==d?void 0:d.defineCustomBindings){var p=null!==(c=null==i?void 0:i.slice())&&void 0!==c?c:[];p.push.apply(p,this._parameters);var f=null!==(u=null==r?void 0:r.slice())&&void 0!==u?u:[];f.push.apply(f,this._samplers),t=d.defineCustomBindings(this.name,t,p,f),i=p,r=f}this._postProcessDefines=t,this._drawWrapper.effect=this._engine.createEffect({vertex:null!=s?s:this._vertexUrl,fragment:null!=l?l:this._fragmentUrl},{attributes:["position"],uniformsNames:i||this._parameters,uniformBuffersNames:this._uniformBuffers,samplers:r||this._samplers,defines:null!==t?t:"",fallbacks:null,onCompiled:null!=o?o:null,onError:null!=a?a:null,indexParameters:n||this._indexParameters,processCodeAfterIncludes:(null==d?void 0:d.processCodeAfterIncludes)?function(e,t){return d.processCodeAfterIncludes(h.name,e,t)}:null,processFinalCode:(null==d?void 0:d.processFinalCode)?function(e,t){return d.processFinalCode(h.name,e,t)}:null,shaderLanguage:this._shaderLanguage},this._engine)},e.prototype.isReusable=function(){return this._reusable},e.prototype.markTextureDirty=function(){this.width=-1},e.prototype._createRenderTargetTexture=function(e,t,i){void 0===i&&(i=0);for(var r=0;r<this._textureCache.length;r++)if(this._textureCache[r].texture.width===e.width&&this._textureCache[r].texture.height===e.height&&this._textureCache[r].postProcessChannel===i&&this._textureCache[r].texture._generateDepthBuffer===t.generateDepthBuffer&&this._textureCache[r].texture.samples===t.samples)return this._textureCache[r].texture;var n=this._engine.createRenderTargetTexture(e,t);return this._textureCache.push({texture:n,postProcessChannel:i,lastUsedRenderId:-1}),n},e.prototype._flushTextureCache=function(){for(var e=this._renderId,t=this._textureCache.length-1;t>=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){for(var i=!1,r=0;r<this._textures.length;r++)if(this._textures.data[r]===this._textureCache[t].texture){i=!0;break}i||(this._textureCache[t].texture.dispose(),this._textureCache.splice(t,1))}},e.prototype.resize=function(e,t,i,r,n){void 0===i&&(i=null),void 0===r&&(r=!1),void 0===n&&(n=!1),this._textures.length>0&&this._textures.reset(),this.width=e,this.height=t;var o=null;if(i)for(var a=0;a<i._postProcesses.length;a++)if(null!==i._postProcesses[a]){o=i._postProcesses[a];break}var s={width:this.width,height:this.height},l={generateMipMaps:r,generateDepthBuffer:n||o===this,generateStencilBuffer:(n||o===this)&&this._engine.isStencilEnable,samplingMode:this.renderTargetSamplingMode,type:this._textureType,format:this._textureFormat,samples:this._samples,label:"PostProcessRTT-"+this.name};this._textures.push(this._createRenderTargetTexture(s,l,0)),this._reusable&&this._textures.push(this._createRenderTargetTexture(s,l,1)),this._texelSize.copyFromFloats(1/this.width,1/this.height),this.onSizeChangedObservable.notifyObservers(this)},e.prototype._getTarget=function(){var e;if(this._shareOutputWithPostProcess)e=this._shareOutputWithPostProcess.inputTexture;else if(this._forcedOutputTexture)e=this._forcedOutputTexture,this.width=this._forcedOutputTexture.width,this.height=this._forcedOutputTexture.height;else{e=this.inputTexture;for(var t=void 0,i=0;i<this._textureCache.length;i++)if(this._textureCache[i].texture===e){t=this._textureCache[i];break}t&&(t.lastUsedRenderId=this._renderId)}return e},e.prototype.activate=function(e,t,i){var r,n,o=this;void 0===t&&(t=null);var a=(e=e||this._camera).getScene(),s=a.getEngine(),l=s.getCaps().maxTextureSize,c=(t?t.width:this._engine.getRenderWidth(!0))*this._options|0,h=(t?t.height:this._engine.getRenderHeight(!0))*this._options|0,d=this._options.width||c,p=this._options.height||h,f=this.renderTargetSamplingMode!==u.TEXTURE_NEAREST_LINEAR&&this.renderTargetSamplingMode!==u.TEXTURE_NEAREST_NEAREST&&this.renderTargetSamplingMode!==u.TEXTURE_LINEAR_LINEAR,_=null;if(!this._shareOutputWithPostProcess&&!this._forcedOutputTexture){if(this.adaptScaleToCurrentViewport){var m=s.currentViewport;m&&(d*=m.width,p*=m.height)}(f||this.alwaysForcePOT)&&(this._options.width||(d=s.needPOTTextures?ir(d,l,this.scaleMode):d),this._options.height||(p=s.needPOTTextures?ir(p,l,this.scaleMode):p)),this.width===d&&this.height===p&&(_=this._getTarget())||this.resize(d,p,e,f,i),this._textures.forEach((function(e){e.samples!==o.samples&&o._engine.updateRenderTargetTextureSampleCount(e,o.samples)})),this._flushTextureCache(),this._renderId++}return _||(_=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(c/d,h/p),this._engine.bindFramebuffer(_,0,c,h,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(_,0,void 0,void 0,this.forceFullscreenViewport)),null===(n=(r=this._engine)._debugInsertMarker)||void 0===n||n.call(r,"post process ".concat(this.name," input")),this.onActivateObservable.notifyObservers(e),this.autoClear&&(this.alphaMode===u.ALPHA_DISABLE||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:a.clearColor,a._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),_},Object.defineProperty(e.prototype,"isSupported",{get:function(){return this._drawWrapper.effect.isSupported},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"aspectRatio",{get:function(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height},enumerable:!1,configurable:!0}),e.prototype.isReady=function(){var e,t;return null!==(t=null===(e=this._drawWrapper.effect)||void 0===e?void 0:e.isReady())&&void 0!==t&&t},e.prototype.apply=function(){var t,i,r,n;return(null===(t=this._drawWrapper.effect)||void 0===t?void 0:t.isReady())?(this._engine.enableEffect(this._drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._engine.setAlphaMode(this.alphaMode),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),n=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",null==n?void 0:n.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),null===(r=null===(i=e._GetShaderCodeProcessing(this.name))||void 0===i?void 0:i.bindCustomBindings)||void 0===r||r.call(i,this.name,this._drawWrapper.effect),this._drawWrapper.effect):null},e.prototype._disposeTextures=function(){this._shareOutputWithPostProcess||this._forcedOutputTexture?this._disposeTextureCache():(this._disposeTextureCache(),this._textures.dispose())},e.prototype._disposeTextureCache=function(){for(var e=this._textureCache.length-1;e>=0;e--)this._textureCache[e].texture.dispose();this._textureCache.length=0},e.prototype.setPrePassRenderer=function(e){return!!this._prePassEffectConfiguration&&(this._prePassEffectConfiguration=e.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0)},e.prototype.dispose=function(e){var t;if(e=e||this._camera,this._disposeTextures(),this._scene&&-1!==(t=this._scene.postProcesses.indexOf(this))&&this._scene.postProcesses.splice(t,1),this._parentContainer){var i=this._parentContainer.postProcesses.indexOf(this);i>-1&&this._parentContainer.postProcesses.splice(i,1),this._parentContainer=null}if(-1!==(t=this._engine.postProcesses.indexOf(this))&&this._engine.postProcesses.splice(t,1),e){if(e.detachPostProcess(this),0===(t=e._postProcesses.indexOf(this))&&e._postProcesses.length>0){var r=this._camera._getFirstPostProcess();r&&r.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}},e.prototype.serialize=function(){var e=Ke.Serialize(this),t=this.getCamera()||this._scene&&this._scene.activeCamera;return e.customType="BABYLON."+this.getClassName(),e.cameraId=t?t.id:null,e.reusable=this._reusable,e.textureType=this._textureType,e.fragmentUrl=this._fragmentUrl,e.parameters=this._parameters,e.samplers=this._samplers,e.options=this._options,e.defines=this._postProcessDefines,e.textureFormat=this._textureFormat,e.vertexUrl=this._vertexUrl,e.indexParameters=this._indexParameters,e},e.prototype.clone=function(){var t=this.serialize();t._engine=this._engine,t.cameraId=null;var i=e.Parse(t,this._scene,"");return i?(i.onActivateObservable=this.onActivateObservable.clone(),i.onSizeChangedObservable=this.onSizeChangedObservable.clone(),i.onApplyObservable=this.onApplyObservable.clone(),i.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),i.onAfterRenderObservable=this.onAfterRenderObservable.clone(),i._prePassEffectConfiguration=this._prePassEffectConfiguration,i):null},e.Parse=function(e,t,i){var r=s(e.customType);if(!r||!r._Parse)return null;var n=t?t.getCameraById(e.cameraId):null;return r._Parse(e,n,t,i)},e._Parse=function(t,i,r,n){return Ke.Parse((function(){return new e(t.name,t.fragmentUrl,t.parameters,t.samplers,t.options,i,t.renderTargetSamplingMode,t._engine,t.reusable,t.defines,t.textureType,t.vertexUrl,t.indexParameters,!1,t.textureFormat)}),t,r,n)},e._CustomShaderCodeProcessing={},v([Ie()],e.prototype,"uniqueId",void 0),v([Ie()],e.prototype,"name",void 0),v([Ie()],e.prototype,"width",void 0),v([Ie()],e.prototype,"height",void 0),v([Ie()],e.prototype,"renderTargetSamplingMode",void 0),v([Be()],e.prototype,"clearColor",void 0),v([Ie()],e.prototype,"autoClear",void 0),v([Ie()],e.prototype,"forceAutoClearInAlphaMode",void 0),v([Ie()],e.prototype,"alphaMode",void 0),v([Ie()],e.prototype,"alphaConstants",void 0),v([Ie()],e.prototype,"enablePixelPerfectMode",void 0),v([Ie()],e.prototype,"forceFullscreenViewport",void 0),v([Ie()],e.prototype,"scaleMode",void 0),v([Ie()],e.prototype,"alwaysForcePOT",void 0),v([Ie("samples")],e.prototype,"_samples",void 0),v([Ie()],e.prototype,"adaptScaleToCurrentViewport",void 0),e}();a("BABYLON.PostProcess",hl);var dl=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.xSwizzle="x",i.ySwizzle="y",i.zSwizzle="z",i.wSwizzle="w",i.registerInput("xyzw ",Ns.Vector4,!0),i.registerInput("xyz ",Ns.Vector3,!0),i.registerInput("xy ",Ns.Vector2,!0),i.registerInput("zw ",Ns.Vector2,!0),i.registerInput("x",Ns.Float,!0),i.registerInput("y",Ns.Float,!0),i.registerInput("z",Ns.Float,!0),i.registerInput("w",Ns.Float,!0),i.registerOutput("xyzw",Ns.Vector4),i.registerOutput("xyz",Ns.Vector3),i.registerOutput("xy",Ns.Vector2),i.registerOutput("zw",Ns.Vector2),i}return m(t,e),t.prototype.getClassName=function(){return"VectorMergerBlock"},Object.defineProperty(t.prototype,"xyzwIn",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xyzIn",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xyIn",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"zwIn",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"x",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"y",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"z",{get:function(){return this._inputs[6]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"w",{get:function(){return this._inputs[7]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xyzw",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xyzOut",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xyOut",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"zwOut",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xy",{get:function(){return this.xyOut},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xyz",{get:function(){return this.xyzOut},enumerable:!1,configurable:!0}),t.prototype._inputRename=function(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":e},t.prototype._buildSwizzle=function(e){return"."+(this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle).substr(0,e)},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this.x,r=this.y,n=this.z,o=this.w,a=this.xyIn,s=this.zwIn,l=this.xyzIn,c=this.xyzwIn,u=this._outputs[0],h=this._outputs[1],d=this._outputs[2],p=this._outputs[3],f=t._getShaderType(Ns.Vector4),_=t._getShaderType(Ns.Vector3),m=t._getShaderType(Ns.Vector2);return c.isConnected?(u.hasEndpoints&&(t.compilationString+=t._declareOutput(u)+" = ".concat(c.associatedVariableName).concat(this._buildSwizzle(4),";\n")),h.hasEndpoints&&(t.compilationString+=t._declareOutput(h)+" = ".concat(c.associatedVariableName).concat(this._buildSwizzle(3),";\n")),d.hasEndpoints&&(t.compilationString+=t._declareOutput(d)+" = ".concat(c.associatedVariableName).concat(this._buildSwizzle(2),";\n"))):l.isConnected?(u.hasEndpoints&&(t.compilationString+=t._declareOutput(u)+" = ".concat(f,"(").concat(l.associatedVariableName,", ").concat(o.isConnected?this._writeVariable(o):"0.0",")").concat(this._buildSwizzle(4),";\n")),h.hasEndpoints&&(t.compilationString+=t._declareOutput(h)+" = ".concat(l.associatedVariableName).concat(this._buildSwizzle(3),";\n")),d.hasEndpoints&&(t.compilationString+=t._declareOutput(d)+" = ".concat(l.associatedVariableName).concat(this._buildSwizzle(2),";\n"))):a.isConnected?(u.hasEndpoints&&(s.isConnected?t.compilationString+=t._declareOutput(u)+" = ".concat(f,"(").concat(a.associatedVariableName,", ").concat(s.associatedVariableName,")").concat(this._buildSwizzle(4),";\n"):t.compilationString+=t._declareOutput(u)+" = ".concat(f,"(").concat(a.associatedVariableName,", ").concat(n.isConnected?this._writeVariable(n):"0.0",", ").concat(o.isConnected?this._writeVariable(o):"0.0",")").concat(this._buildSwizzle(4),";\n")),h.hasEndpoints&&(t.compilationString+=t._declareOutput(h)+" = ".concat(_,"(").concat(a.associatedVariableName,", ").concat(n.isConnected?this._writeVariable(n):"0.0",")").concat(this._buildSwizzle(3),";\n")),d.hasEndpoints&&(t.compilationString+=t._declareOutput(d)+" = ".concat(a.associatedVariableName).concat(this._buildSwizzle(2),";\n")),p.hasEndpoints&&(s.isConnected?t.compilationString+=t._declareOutput(p)+" = ".concat(s.associatedVariableName).concat(this._buildSwizzle(2),";\n"):t.compilationString+=t._declareOutput(p)+" = ".concat(m,"(").concat(n.isConnected?this._writeVariable(n):"0.0",", ").concat(o.isConnected?this._writeVariable(o):"0.0",")").concat(this._buildSwizzle(2),";\n"))):(u.hasEndpoints&&(s.isConnected?t.compilationString+=t._declareOutput(u)+" = ".concat(f,"(").concat(i.isConnected?this._writeVariable(i):"0.0",", ").concat(r.isConnected?this._writeVariable(r):"0.0",", ").concat(s.associatedVariableName,")").concat(this._buildSwizzle(4),";\n"):t.compilationString+=t._declareOutput(u)+" = ".concat(f,"(").concat(i.isConnected?this._writeVariable(i):"0.0",", ").concat(r.isConnected?this._writeVariable(r):"0.0",", ").concat(n.isConnected?this._writeVariable(n):"0.0",", ").concat(o.isConnected?this._writeVariable(o):"0.0",")").concat(this._buildSwizzle(4),";\n")),h.hasEndpoints&&(t.compilationString+=t._declareOutput(h)+" = ".concat(_,"(").concat(i.isConnected?this._writeVariable(i):"0.0",", ").concat(r.isConnected?this._writeVariable(r):"0.0",", ").concat(n.isConnected?this._writeVariable(n):"0.0",")").concat(this._buildSwizzle(3),";\n")),d.hasEndpoints&&(t.compilationString+=t._declareOutput(d)+" = ".concat(m,"(").concat(i.isConnected?this._writeVariable(i):"0.0",", ").concat(r.isConnected?this._writeVariable(r):"0.0",")").concat(this._buildSwizzle(2),";\n")),p.hasEndpoints&&(s.isConnected?t.compilationString+=t._declareOutput(p)+" = ".concat(s.associatedVariableName).concat(this._buildSwizzle(2),";\n"):t.compilationString+=t._declareOutput(p)+" = ".concat(m,"(").concat(n.isConnected?this._writeVariable(n):"0.0",", ").concat(o.isConnected?this._writeVariable(o):"0.0",")").concat(this._buildSwizzle(2),";\n"))),this},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.xSwizzle=this.xSwizzle,t.ySwizzle=this.ySwizzle,t.zSwizzle=this.zSwizzle,t.wSwizzle=this.wSwizzle,t},t.prototype._deserialize=function(t,i,r){var n,o,a,s;e.prototype._deserialize.call(this,t,i,r),this.xSwizzle=null!==(n=t.xSwizzle)&&void 0!==n?n:"x",this.ySwizzle=null!==(o=t.ySwizzle)&&void 0!==o?o:"y",this.zSwizzle=null!==(a=t.zSwizzle)&&void 0!==a?a:"z",this.wSwizzle=null!==(s=t.wSwizzle)&&void 0!==s?s:"w"},t.prototype._dumpPropertiesCode=function(){var t=e.prototype._dumpPropertiesCode.call(this);return t+="".concat(this._codeVariableName,'.xSwizzle = "').concat(this.xSwizzle,'";\n'),t+="".concat(this._codeVariableName,'.ySwizzle = "').concat(this.ySwizzle,'";\n'),(t+="".concat(this._codeVariableName,'.zSwizzle = "').concat(this.zSwizzle,'";\n'))+"".concat(this._codeVariableName,'.wSwizzle = "').concat(this.wSwizzle,'";\n')},t}(Ws);a("BABYLON.VectorMergerBlock",dl);var pl=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.sourceRange=new U(-1,1),i.targetRange=new U(0,1),i.registerInput("input",Ns.AutoDetect),i.registerInput("sourceMin",Ns.Float,!0),i.registerInput("sourceMax",Ns.Float,!0),i.registerInput("targetMin",Ns.Float,!0),i.registerInput("targetMax",Ns.Float,!0),i.registerOutput("output",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i}return m(t,e),t.prototype.getClassName=function(){return"RemapBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"sourceMin",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"sourceMax",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"targetMin",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"targetMax",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],r=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),n=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),o=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),a=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return t.compilationString+=t._declareOutput(i)+" = ".concat(o," + (").concat(this._inputs[0].associatedVariableName," - ").concat(r,") * (").concat(a," - ").concat(o,") / (").concat(n," - ").concat(r,");\n"),this},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".sourceRange = new BABYLON.Vector2(").concat(this.sourceRange.x,", ").concat(this.sourceRange.y,");\n")+"".concat(this._codeVariableName,".targetRange = new BABYLON.Vector2(").concat(this.targetRange.x,", ").concat(this.targetRange.y,");\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.sourceRange=this.sourceRange.asArray(),t.targetRange=this.targetRange.asArray(),t},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),this.sourceRange=U.FromArray(t.sourceRange),this.targetRange=U.FromArray(t.targetRange)},v([Ys("From",Xs.Vector2)],t.prototype,"sourceRange",void 0),v([Ys("To",Xs.Vector2)],t.prototype,"targetRange",void 0),t}(Ws);a("BABYLON.RemapBlock",pl);var fl,_l=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("left",Ns.AutoDetect),i.registerInput("right",Ns.AutoDetect),i.registerOutput("output",Ns.BasedOnInput),i.output._typeConnectionSource=i.left,i._linkConnectionTypes(0,1,!0),i.left.acceptedConnectionPointTypes.push(Ns.Float),i.right.acceptedConnectionPointTypes.push(Ns.Float),i._connectionObservers=[i.left.onTypeChangedObservable.add((function(){return i._updateInputOutputTypes()})),i.right.onTypeChangedObservable.add((function(){return i._updateInputOutputTypes()}))],i}return m(t,e),Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._updateInputOutputTypes=function(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===Ns.Int||this.left.type===Ns.Float&&this.right.type!==Ns.Int)&&(this.output._typeConnectionSource=this.right):this.left.isConnected!==this.right.isConnected&&(this.output._typeConnectionSource=this.left.isConnected?this.left:this.right),this.left.isConnected||this.right.isConnected)for(var e=0,t=[[this.left,this.right],[this.right,this.left]];e<t.length;e++){var i=t[e],r=i[0],n=i[1];r.acceptedConnectionPointTypes=[Ns.Int,Ns.Float],n.isConnected&&(r.acceptedConnectionPointTypes.push(n.type),n.type!==Ns.Int&&n.type!==Ns.Float||r.acceptedConnectionPointTypes.push(Ns.Vector2,Ns.Vector3,Ns.Vector4,Ns.Color3,Ns.Color4,Ns.Matrix))}},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._connectionObservers.forEach((function(e){return e.remove()})),this._connectionObservers.length=0},t}(Ws),ml=function(e){function t(t){return e.call(this,t)||this}return m(t,e),t.prototype.getClassName=function(){return"MultiplyBlock"},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = ".concat(this.left.associatedVariableName," * ").concat(this.right.associatedVariableName,";\n"),this},t}(_l);a("BABYLON.MultiplyBlock",ml),function(e){e[e.Material=0]="Material",e[e.PostProcess=1]="PostProcess",e[e.Particle=2]="Particle",e[e.ProceduralTexture=3]="ProceduralTexture"}(fl||(fl={}));var gl=function(e){function t(){var t=e.call(this)||this;return t.IMAGEPROCESSING=!1,t.VIGNETTE=!1,t.VIGNETTEBLENDMODEMULTIPLY=!1,t.VIGNETTEBLENDMODEOPAQUE=!1,t.TONEMAPPING=0,t.CONTRAST=!1,t.COLORCURVES=!1,t.COLORGRADING=!1,t.COLORGRADING3D=!1,t.SAMPLER3DGREENDEPTH=!1,t.SAMPLER3DBGRMAP=!1,t.DITHER=!1,t.IMAGEPROCESSINGPOSTPROCESS=!1,t.EXPOSURE=!1,t.SKIPFINALCOLORCLAMP=!1,t.rebuild(),t}return m(t,e),t}(Gs),vl=function(){function e(t){this.animations=[],this.renderingGroupId=0,this.emitter=V.Zero(),this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this.applyFog=!1,this._wasDispatched=!1,this._rootUrl="",this.noiseStrength=new V(10,10,10),this.onAnimationEnd=null,this.blendMode=e.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.preWarmCycles=0,this.preWarmStepOffset=1,this.spriteCellChangeSpeed=1,this.startSpriteCellID=0,this.endSpriteCellID=0,this.spriteCellWidth=0,this.spriteCellHeight=0,this.spriteCellLoop=!0,this.spriteRandomStartCell=!1,this.translationPivot=new U(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new V(0,0,0),this._useLogarithmicDepth=!1,this.gravity=V.Zero(),this._colorGradients=null,this._sizeGradients=null,this._lifeTimeGradients=null,this._angularSpeedGradients=null,this._velocityGradients=null,this._limitVelocityGradients=null,this._dragGradients=null,this._emitRateGradients=null,this._startSizeGradients=null,this._rampGradients=null,this._colorRemapGradients=null,this._alphaRemapGradients=null,this.startDelay=0,this.limitVelocityDamping=.4,this.color1=new J(1,1,1,1),this.color2=new J(1,1,1,1),this.colorDead=new J(0,0,0,1),this.textureMask=new J(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=u.PARTICLES_BILLBOARDMODE_ALL,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new gl,this.id=t,this.name=t}return Object.defineProperty(e.prototype,"noiseTexture",{get:function(){return this._noiseTexture},set:function(e){this._noiseTexture!==e&&(this._noiseTexture=e,this._reset())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isAnimationSheetEnabled",{get:function(){return this._isAnimationSheetEnabled},set:function(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._reset())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useLogarithmicDepth",{get:function(){return this._useLogarithmicDepth},set:function(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported},enumerable:!1,configurable:!0}),e.prototype.getScene=function(){return this._scene},e.prototype._hasTargetStopDurationDependantGradient=function(){return this._startSizeGradients&&this._startSizeGradients.length>0||this._emitRateGradients&&this._emitRateGradients.length>0||this._lifeTimeGradients&&this._lifeTimeGradients.length>0},e.prototype.getDragGradients=function(){return this._dragGradients},e.prototype.getLimitVelocityGradients=function(){return this._limitVelocityGradients},e.prototype.getColorGradients=function(){return this._colorGradients},e.prototype.getSizeGradients=function(){return this._sizeGradients},e.prototype.getColorRemapGradients=function(){return this._colorRemapGradients},e.prototype.getAlphaRemapGradients=function(){return this._alphaRemapGradients},e.prototype.getLifeTimeGradients=function(){return this._lifeTimeGradients},e.prototype.getAngularSpeedGradients=function(){return this._angularSpeedGradients},e.prototype.getVelocityGradients=function(){return this._velocityGradients},e.prototype.getStartSizeGradients=function(){return this._startSizeGradients},e.prototype.getEmitRateGradients=function(){return this._emitRateGradients},Object.defineProperty(e.prototype,"direction1",{get:function(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:V.Zero()},set:function(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"direction2",{get:function(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:V.Zero()},set:function(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"minEmitBox",{get:function(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:V.Zero()},set:function(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxEmitBox",{get:function(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:V.Zero()},set:function(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"billboardMode",{get:function(){return this._billboardMode},set:function(e){this._billboardMode!==e&&(this._billboardMode=e,this._reset())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isBillboardBased",{get:function(){return this._isBillboardBased},set:function(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e)},enumerable:!1,configurable:!0}),e.prototype._attachImageProcessingConfiguration=function(e){e!==this._imageProcessingConfiguration&&(!e&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=e)},e.prototype._reset=function(){},e.prototype._removeGradientAndTexture=function(e,t,i){if(!t)return this;for(var r=0,n=0,o=t;n<o.length;n++){if(o[n].gradient===e){t.splice(r,1);break}r++}return i&&i.dispose(),this},e.prototype.createPointEmitter=function(e,t){throw new Error("Method not implemented.")},e.prototype.createHemisphericEmitter=function(e,t){throw void 0===e&&(e=1),void 0===t&&(t=1),new Error("Method not implemented.")},e.prototype.createSphereEmitter=function(e,t){throw void 0===e&&(e=1),void 0===t&&(t=1),new Error("Method not implemented.")},e.prototype.createDirectedSphereEmitter=function(e,t,i){throw void 0===e&&(e=1),void 0===t&&(t=new V(0,1,0)),void 0===i&&(i=new V(0,1,0)),new Error("Method not implemented.")},e.prototype.createCylinderEmitter=function(e,t,i,r){throw void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=1),void 0===r&&(r=0),new Error("Method not implemented.")},e.prototype.createDirectedCylinderEmitter=function(e,t,i,r,n){throw void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=1),void 0===r&&(r=new V(0,1,0)),void 0===n&&(n=new V(0,1,0)),new Error("Method not implemented.")},e.prototype.createConeEmitter=function(e,t){throw void 0===e&&(e=1),void 0===t&&(t=Math.PI/4),new Error("Method not implemented.")},e.prototype.createBoxEmitter=function(e,t,i,r){throw new Error("Method not implemented.")},e.BLENDMODE_ONEONE=0,e.BLENDMODE_STANDARD=1,e.BLENDMODE_ADD=2,e.BLENDMODE_MULTIPLY=3,e.BLENDMODE_MULTIPLYADD=4,e}();a("BABYLON.BaseParticleSystem",vl);var yl=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("rgba",Ns.Color4,!0),i.registerInput("rgb ",Ns.Color3,!0),i.registerOutput("rgb",Ns.Color3),i.registerOutput("r",Ns.Float),i.registerOutput("g",Ns.Float),i.registerOutput("b",Ns.Float),i.registerOutput("a",Ns.Float),i.inputsAreExclusive=!0,i}return m(t,e),t.prototype.getClassName=function(){return"ColorSplitterBlock"},Object.defineProperty(t.prototype,"rgba",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rgbIn",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rgbOut",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"r",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"g",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"b",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"a",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),t.prototype._inputRename=function(e){return"rgb "===e?"rgbIn":e},t.prototype._outputRename=function(e){return"rgb"===e?"rgbOut":e},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this.rgba.isConnected?this.rgba:this.rgbIn;if(i.isConnected){var r=this._outputs[0],n=this._outputs[1],o=this._outputs[2],a=this._outputs[3],s=this._outputs[4];return r.hasEndpoints&&(t.compilationString+=t._declareOutput(r)+" = ".concat(i.associatedVariableName,".rgb;\n")),n.hasEndpoints&&(t.compilationString+=t._declareOutput(n)+" = ".concat(i.associatedVariableName,".r;\n")),o.hasEndpoints&&(t.compilationString+=t._declareOutput(o)+" = ".concat(i.associatedVariableName,".g;\n")),a.hasEndpoints&&(t.compilationString+=t._declareOutput(a)+" = ".concat(i.associatedVariableName,".b;\n")),s.hasEndpoints&&(t.compilationString+=t._declareOutput(s)+" = ".concat(i.associatedVariableName,".a;\n")),this}},t}(Ws);a("BABYLON.ColorSplitterBlock",yl),Er.prototype.createRenderTargetCubeTexture=function(e,t){var i=this._createHardwareRenderTargetWrapper(!1,!0,e),r=g({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:u.TEXTURETYPE_UNSIGNED_INT,samplingMode:u.TEXTURE_TRILINEAR_SAMPLINGMODE,format:u.TEXTUREFORMAT_RGBA},t);r.generateStencilBuffer=r.generateDepthBuffer&&r.generateStencilBuffer,(r.type!==u.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(r.type!==u.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(r.samplingMode=u.TEXTURE_NEAREST_SAMPLINGMODE);var n=this._gl,o=new Pi(this,Ti.RenderTarget);this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,o,!0);var a=this._getSamplingParameters(r.samplingMode,r.generateMipMaps);r.type!==u.TEXTURETYPE_FLOAT||this._caps.textureFloat||(r.type=u.TEXTURETYPE_UNSIGNED_INT,ae.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MAG_FILTER,a.mag),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MIN_FILTER,a.min),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE);for(var s=0;s<6;s++)n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+s,0,this._getRGBABufferInternalSizedFormat(r.type,r.format),e,e,0,this._getInternalFormat(r.format),this._getWebGLTextureType(r.type),null);var l=n.createFramebuffer();return this._bindUnboundFramebuffer(l),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(r.generateStencilBuffer,r.generateDepthBuffer,e,e),r.generateMipMaps&&n.generateMipmap(n.TEXTURE_CUBE_MAP),this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=l,i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=r.generateStencilBuffer,o.width=e,o.height=e,o.isReady=!0,o.isCube=!0,o.samples=1,o.generateMipMaps=r.generateMipMaps,o.samplingMode=r.samplingMode,o.type=r.type,o.format=r.format,this._internalTexturesCache.push(o),i.setTextures(o),i};var bl={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]},Tl=function(){function e(e,t){var i;void 0===t&&(t=bl);var r,n,o=this;this._fullscreenViewport=new Jn(0,0,1,1);var a=null!==(r=t.positions)&&void 0!==r?r:bl.positions,s=null!==(n=t.indices)&&void 0!==n?n:bl.indices;this.engine=e,this._vertexBuffers=((i={})[Nr.PositionKind]=new Nr(e,a,Nr.PositionKind,!1,!1,2),i),this._indexBuffer=e.createIndexBuffer(s),this._onContextRestoredObserver=e.onContextRestoredObservable.add((function(){for(var t in o._indexBuffer=e.createIndexBuffer(s),o._vertexBuffers)o._vertexBuffers[t]._rebuild()}))}return e.prototype.setViewport=function(e){void 0===e&&(e=this._fullscreenViewport),this.engine.setViewport(e)},e.prototype.bindBuffers=function(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)},e.prototype.applyEffectWrapper=function(e){this.engine.setState(!0),this.engine.depthCullingState.depthTest=!1,this.engine.stencilState.stencilTest=!1,this.engine.enableEffect(e._drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})},e.prototype.saveStates=function(){this._savedStateDepthTest=this.engine.depthCullingState.depthTest,this._savedStateStencilTest=this.engine.stencilState.stencilTest},e.prototype.restoreStates=function(){this.engine.depthCullingState.depthTest=this._savedStateDepthTest,this.engine.stencilState.stencilTest=this._savedStateStencilTest},e.prototype.draw=function(){this.engine.drawElementsType(u.MATERIAL_TriangleFillMode,0,6)},e.prototype._isRenderTargetTexture=function(e){return void 0!==e.renderTarget},e.prototype.render=function(e,t){if(void 0===t&&(t=null),e.effect.isReady()){this.saveStates(),this.setViewport();var i=null===t?null:this._isRenderTargetTexture(t)?t.renderTarget:t;i&&this.engine.bindFramebuffer(i),this.applyEffectWrapper(e),this.draw(),i&&this.engine.unBindFramebuffer(i),this.restoreStates()}},e.prototype.dispose=function(){var e=this._vertexBuffers[Nr.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[Nr.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)},e}(),El=function(){function e(e){var t,i=this;this.onApplyObservable=new f;var r=e.uniformNames||[];e.vertexShader?t={fragmentSource:e.fragmentShader,vertexSource:e.vertexShader,spectorName:e.name||"effectWrapper"}:(r.push("scale"),t={fragmentSource:e.fragmentShader,vertex:"postprocess",spectorName:e.name||"effectWrapper"},this.onApplyObservable.add((function(){i.effect.setFloat2("scale",1,1)})));var n=e.defines?e.defines.join("\n"):"";this._drawWrapper=new ho(e.engine),e.useShaderStore?(t.fragment=t.fragmentSource,t.vertex||(t.vertex=t.vertexSource),delete t.fragmentSource,delete t.vertexSource,this.effect=e.engine.createEffect(t,e.attributeNames||["position"],r,e.samplerNames,n,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new Ei(t,e.attributeNames||["position"],r,e.samplerNames,e.engine,n,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add((function(){i.effect._pipelineContext=null,i.effect._prepareEffect()})))}return Object.defineProperty(e.prototype,"effect",{get:function(){return this._drawWrapper.effect},set:function(e){this._drawWrapper.effect=e},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()},e}(),Sl="passPixelShader",xl="varying vec2 vUV;uniform sampler2D textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);}";li.ShadersStore[Sl]=xl;var Al=Sl,Cl=xl,Rl=function(){function e(){}return e._CreateDumpRenderer=function(){if(!e._DumpToolsEngine){var t=void 0,i=null,r={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{t=new OffscreenCanvas(100,100),i=new Er(t,!1,r)}catch(e){t=document.createElement("canvas"),i=new Er(t,!1,r)}M.Instances.pop(),M.OnEnginesDisposedObservable.add((function(e){i&&e!==i&&!i.isDisposed&&i.dispose()})),i.getCaps().parallelShaderCompile=void 0;var n=new Tl(i),o=new El({engine:i,name:Al,fragmentShader:Cl,samplerNames:["textureSampler"]});e._DumpToolsEngine={canvas:t,engine:i,renderer:n,wrapper:o}}return e._DumpToolsEngine},e.DumpFramebuffer=function(t,i,r,n,o,a,s){return void 0===o&&(o="image/png"),y(this,void 0,void 0,(function(){var l,c;return b(this,(function(u){switch(u.label){case 0:return[4,r.readPixels(0,0,t,i)];case 1:return l=u.sent(),c=new Uint8Array(l.buffer),e.DumpData(t,i,c,n,o,a,!0,void 0,s),[2]}}))}))},e.DumpDataAsync=function(t,i,r,n,o,a,s,l){return void 0===n&&(n="image/png"),void 0===a&&(a=!1),void 0===s&&(s=!1),new Promise((function(c){e.DumpData(t,i,r,(function(e){return c(e)}),n,o,a,s,l)}))},e.DumpData=function(t,i,r,n,o,a,s,l,c){void 0===o&&(o="image/png"),void 0===s&&(s=!1),void 0===l&&(l=!1);var h=e._CreateDumpRenderer();if(h.engine.setSize(t,i,!0),r instanceof Float32Array){for(var d=new Uint8Array(r.length),p=r.length;p--;){var f=r[p];d[p]=Math.round(255*j.Clamp(f))}r=d}var _=h.engine.createRawTexture(r,t,i,u.TEXTUREFORMAT_RGBA,!1,!s,u.TEXTURE_NEAREST_NEAREST);h.renderer.setViewport(),h.renderer.applyEffectWrapper(h.wrapper),h.wrapper.effect._bindTexture("textureSampler",_),h.renderer.draw(),l?rr.ToBlob(h.canvas,(function(e){var t=new FileReader;t.onload=function(e){var t=e.target.result;n&&n(t)},t.readAsArrayBuffer(e)}),o,c):rr.EncodeScreenshotCanvasData(h.canvas,n,o,a,c),_.dispose()},e.Dispose=function(){e._DumpToolsEngine&&(e._DumpToolsEngine.wrapper.dispose(),e._DumpToolsEngine.renderer.dispose(),e._DumpToolsEngine.engine.dispose()),e._DumpToolsEngine=null},e}();rr.DumpData=Rl.DumpData,rr.DumpDataAsync=Rl.DumpDataAsync,rr.DumpFramebuffer=Rl.DumpFramebuffer;var Pl=function(e){function t(t,i,r,n,o,a,s,l,c,h,d,p,_,m,g,v,y){void 0===n&&(n=!1),void 0===o&&(o=!0),void 0===a&&(a=u.TEXTURETYPE_UNSIGNED_INT),void 0===s&&(s=!1),void 0===l&&(l=Ja.TRILINEAR_SAMPLINGMODE),void 0===c&&(c=!0),void 0===h&&(h=!1),void 0===d&&(d=!1),void 0===p&&(p=u.TEXTUREFORMAT_RGBA),void 0===_&&(_=!1),void 0===v&&(v=!1),void 0===y&&(y=!1);var b,T,E,S,x,A,C,R=this,P=void 0,I=!0;if("object"==typeof n){var M=n;n=!!M.generateMipMaps,o=null===(b=M.doNotChangeAspectRatio)||void 0===b||b,a=null!==(T=M.type)&&void 0!==T?T:u.TEXTURETYPE_UNSIGNED_BYTE,s=!!M.isCube,l=null!==(E=M.samplingMode)&&void 0!==E?E:Ja.TRILINEAR_SAMPLINGMODE,c=null===(S=M.generateDepthBuffer)||void 0===S||S,h=!!M.generateStencilBuffer,d=!!M.isMulti,p=null!==(x=M.format)&&void 0!==x?x:u.TEXTUREFORMAT_RGBA,_=!!M.delayAllocation,m=M.samples,g=M.creationFlags,v=!!M.noColorAttachment,y=!!M.useSRGBBuffer,P=M.colorAttachment,I=null!==(A=M.gammaSpace)&&void 0!==A?A:I}if((R=e.call(this,null,r,!n,void 0,l,void 0,void 0,void 0,void 0,p)||this)._unObserveRenderList=null,R._renderListHasChanged=function(e,t){var i,r=R._renderList?R._renderList.length:0;(0===t&&r>0||0===r)&&(null===(i=R.getScene())||void 0===i||i.meshes.forEach((function(e){e._markSubMeshesAsLightDirty()})))},R.renderParticles=!0,R.renderSprites=!1,R.forceLayerMaskCheck=!1,R.ignoreCameraViewport=!1,R.onBeforeBindObservable=new f,R.onAfterUnbindObservable=new f,R.onBeforeRenderObservable=new f,R.onAfterRenderObservable=new f,R.onClearObservable=new f,R.onResizeObservable=new f,R._cleared=!1,R.skipInitialClear=!1,R._currentRefreshId=-1,R._refreshRate=1,R._samples=1,R._canRescale=!0,R._renderTarget=null,R.boundingBoxPosition=V.Zero(),!(r=R.getScene()))return R;var O=R.getScene().getEngine();return R._gammaSpace=I,R._coordinatesMode=Ja.PROJECTION_MODE,R.renderList=[],R.name=t,R.isRenderTarget=!0,R._initialSizeParameter=i,R._renderPassIds=[],R._isCubeData=s,R._processSizeParameter(i),R.renderPassId=R._renderPassIds[0],R._resizeObserver=O.onResizeObservable.add((function(){})),R._generateMipMaps=!!n,R._doNotChangeAspectRatio=o,R._renderingManager=new Ur(r),R._renderingManager._useSceneAutoClearSetup=!0,d||(R._renderTargetOptions={generateMipMaps:n,type:a,format:null!==(C=R._format)&&void 0!==C?C:void 0,samplingMode:R.samplingMode,generateDepthBuffer:c,generateStencilBuffer:h,samples:m,creationFlags:g,noColorAttachment:v,useSRGBBuffer:y,colorAttachment:P,label:R.name},R.samplingMode===Ja.NEAREST_SAMPLINGMODE&&(R.wrapU=Ja.CLAMP_ADDRESSMODE,R.wrapV=Ja.CLAMP_ADDRESSMODE),_||(s?(R._renderTarget=r.getEngine().createRenderTargetCubeTexture(R.getRenderSize(),R._renderTargetOptions),R.coordinatesMode=Ja.INVCUBIC_MODE,R._textureMatrix=z.Identity()):R._renderTarget=r.getEngine().createRenderTargetTexture(R._size,R._renderTargetOptions),R._texture=R._renderTarget.texture,void 0!==m&&(R.samples=m))),R}return m(t,e),Object.defineProperty(t.prototype,"renderList",{get:function(){return this._renderList},set:function(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=P(e,this._renderListHasChanged)),this._renderList=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"postProcesses",{get:function(){return this._postProcesses},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_prePassEnabled",{get:function(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onAfterUnbind",{set:function(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onBeforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onAfterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"onClear",{set:function(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"renderPassIds",{get:function(){return this._renderPassIds},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"currentRefreshId",{get:function(){return this._currentRefreshId},enumerable:!1,configurable:!0}),t.prototype.setMaterialForRendering=function(e,t){var i;i=Array.isArray(e)?e:[e];for(var r=0;r<i.length;++r)for(var n=0;n<this._renderPassIds.length;++n)i[r].setMaterialForRenderPass(this._renderPassIds[n],void 0!==t?Array.isArray(t)?t[n]:t:void 0)},Object.defineProperty(t.prototype,"isMulti",{get:function(){var e,t;return null!==(t=null===(e=this._renderTarget)||void 0===e?void 0:e.isMulti)&&void 0!==t&&t},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"renderTargetOptions",{get:function(){return this._renderTargetOptions},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"renderTarget",{get:function(){return this._renderTarget},enumerable:!1,configurable:!0}),t.prototype._onRatioRescale=function(){this._sizeRatio&&this.resize(this._initialSizeParameter)},Object.defineProperty(t.prototype,"boundingBoxSize",{get:function(){return this._boundingBoxSize},set:function(e){if(!this._boundingBoxSize||!this._boundingBoxSize.equals(e)){this._boundingBoxSize=e;var t=this.getScene();t&&t.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag)}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"depthStencilTexture",{get:function(){var e,t;return null!==(t=null===(e=this._renderTarget)||void 0===e?void 0:e._depthStencilTexture)&&void 0!==t?t:null},enumerable:!1,configurable:!0}),t.prototype.createDepthStencilTexture=function(e,t,i,r,n,o){var a;void 0===e&&(e=0),void 0===t&&(t=!0),void 0===i&&(i=!1),void 0===r&&(r=1),void 0===n&&(n=u.TEXTUREFORMAT_DEPTH32_FLOAT),null===(a=this._renderTarget)||void 0===a||a.createDepthStencilTexture(e,t,i,r,n,o)},t.prototype._releaseRenderPassId=function(){if(this._scene)for(var e=this._scene.getEngine(),t=0;t<this._renderPassIds.length;++t)e.releaseRenderPassId(this._renderPassIds[t]);this._renderPassIds=[]},t.prototype._createRenderPassId=function(){this._releaseRenderPassId();for(var e=this._scene.getEngine(),t=this._isCubeData?6:this.getRenderLayers()||1,i=0;i<t;++i)this._renderPassIds[i]=e.createRenderPassId("RenderTargetTexture - ".concat(this.name,"#").concat(i))},t.prototype._processSizeParameter=function(e,t){if(void 0===t&&(t=!0),e.ratio){this._sizeRatio=e.ratio;var i=this._getEngine();this._size={width:this._bestReflectionRenderTargetDimension(i.getRenderWidth(),this._sizeRatio),height:this._bestReflectionRenderTargetDimension(i.getRenderHeight(),this._sizeRatio)}}else this._size=e;t&&this._createRenderPassId()},Object.defineProperty(t.prototype,"samples",{get:function(){var e,t;return null!==(t=null===(e=this._renderTarget)||void 0===e?void 0:e.samples)&&void 0!==t?t:this._samples},set:function(e){this._renderTarget&&(this._samples=this._renderTarget.setSamples(e))},enumerable:!1,configurable:!0}),t.prototype.resetRefreshCounter=function(){this._currentRefreshId=-1},Object.defineProperty(t.prototype,"refreshRate",{get:function(){return this._refreshRate},set:function(e){this._refreshRate=e,this.resetRefreshCounter()},enumerable:!1,configurable:!0}),t.prototype.addPostProcess=function(e){if(!this._postProcessManager){var t=this.getScene();if(!t)return;this._postProcessManager=new Lr(t),this._postProcesses=new Array}this._postProcesses.push(e),this._postProcesses[0].autoClear=!1},t.prototype.clearPostProcesses=function(e){if(void 0===e&&(e=!1),this._postProcesses){if(e)for(var t=0,i=this._postProcesses;t<i.length;t++)i[t].dispose();this._postProcesses=[]}},t.prototype.removePostProcess=function(e){if(this._postProcesses){var t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses.splice(t,1),this._postProcesses.length>0&&(this._postProcesses[0].autoClear=!1))}},t.prototype._shouldRender=function(){return-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)},t.prototype.getRenderSize=function(){return this.getRenderWidth()},t.prototype.getRenderWidth=function(){return this._size.width?this._size.width:this._size},t.prototype.getRenderHeight=function(){return this._size.width?this._size.height:this._size},t.prototype.getRenderLayers=function(){var e=this._size.layers;return e||(this._size.depth||0)},t.prototype.disableRescaling=function(){this._canRescale=!1},Object.defineProperty(t.prototype,"canRescale",{get:function(){return this._canRescale},enumerable:!1,configurable:!0}),t.prototype.scale=function(e){var t=Math.max(1,this.getRenderSize()*e);this.resize(t)},t.prototype.getReflectionTextureMatrix=function(){return this.isCube?this._textureMatrix:e.prototype.getReflectionTextureMatrix.call(this)},t.prototype.resize=function(e){var t,i=this.isCube;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null;var r=this.getScene();r&&(this._processSizeParameter(e,!1),this._renderTarget=i?r.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):r.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==this._renderTargetOptions.samples&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))},t.prototype.render=function(e,t){void 0===e&&(e=!1),void 0===t&&(t=!1),this._render(e,t)},t.prototype.isReadyForRendering=function(){return this._render(!1,!1,!0)},t.prototype._render=function(e,t,i){var r;void 0===e&&(e=!1),void 0===t&&(t=!1),void 0===i&&(i=!1);var n=this.getScene();if(!n)return i;var o=n.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(var a=0;a<this._waitingRenderList.length;a++){var s=this._waitingRenderList[a];(u=n.getMeshById(s))&&this.renderList.push(u)}}this._waitingRenderList=void 0}if(this.renderListPredicate){this.renderList?this.renderList.length=0:this.renderList=[];var l=this.getScene();if(!l)return i;var c=l.meshes;for(a=0;a<c.length;a++){var u=c[a];this.renderListPredicate(u)&&this.renderList.push(u)}}var h=o.currentRenderPassId;this.onBeforeBindObservable.notifyObservers(this);var d=null!==(r=this.activeCamera)&&void 0!==r?r:n.activeCamera,p=n.activeCamera;d&&(d!==n.activeCamera&&(n.setTransformMatrix(d.getViewMatrix(),d.getProjectionMatrix(!0)),n.activeCamera=d),o.setViewport(d.rigParent?d.rigParent.viewport:d.viewport,this.getRenderWidth(),this.getRenderHeight())),this._defaultRenderListPrepared=!1;var f=i;if(i){n.getViewMatrix()||n.updateTransformMatrix();var _=this.is2DArray||this.is3D?this.getRenderLayers():this.isCube?6:1;for(T=0;T<_&&f;T++){var m=null,g=this.renderList?this.renderList:n.getActiveMeshes().data,v=this.renderList?this.renderList.length:n.getActiveMeshes().length;o.currentRenderPassId=this._renderPassIds[T],this.onBeforeRenderObservable.notifyObservers(T),this.getCustomRenderList&&(m=this.getCustomRenderList(T,g,v)),m||(m=g),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0);for(var y=0;y<m.length&&f;++y)if((u=m[y]).isEnabled()&&!u.isBlocked&&u.isVisible&&u.subMeshes)if(this.customIsReadyFunction){if(!this.customIsReadyFunction(u,this.refreshRate,i)){f=!1;continue}}else if(!u.isReady(!0)){f=!1;continue}this.onAfterRenderObservable.notifyObservers(T),(this.is2DArray||this.is3D||this.isCube)&&(n.incrementRenderId(),n.resetCachedMaterial())}}else if(!this.is2DArray&&!this.is3D||this.isMulti)if(this.isCube&&!this.isMulti)for(var b=0;b<6;b++)this._renderToTarget(b,e,t,void 0,d),n.incrementRenderId(),n.resetCachedMaterial();else this._renderToTarget(0,e,t,void 0,d);else for(var T=0;T<this.getRenderLayers();T++)this._renderToTarget(0,e,t,T,d),n.incrementRenderId(),n.resetCachedMaterial();return this.onAfterUnbindObservable.notifyObservers(this),o.currentRenderPassId=h,p&&(n.activeCamera=p,this.activeCamera&&this.activeCamera!==n.activeCamera&&n.setTransformMatrix(n.activeCamera.getViewMatrix(),n.activeCamera.getProjectionMatrix(!0)),o.setViewport(n.activeCamera.viewport)),n.resetCachedMaterial(),f},t.prototype._bestReflectionRenderTargetDimension=function(e,t){var i=e*t,r=$i(i+16384/(128+i));return Math.min(tr(e),r)},t.prototype._prepareRenderingManager=function(e,t,i,r){var n=this.getScene();if(n){this._renderingManager.reset();for(var o=n.getRenderId(),a=0;a<t;a++){var s=e[a];if(s&&!s.isBlocked){if(this.customIsReadyFunction){if(!this.customIsReadyFunction(s,this.refreshRate,!1)){this.resetRefreshCounter();continue}}else if(!s.isReady(0===this.refreshRate)){this.resetRefreshCounter();continue}if(!s._internalAbstractMeshDataInfo._currentLODIsUpToDate&&n.activeCamera&&(s._internalAbstractMeshDataInfo._currentLOD=n.customLODSelector?n.customLODSelector(s,this.activeCamera||n.activeCamera):s.getLOD(this.activeCamera||n.activeCamera),s._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0),!s._internalAbstractMeshDataInfo._currentLOD)continue;var l=s._internalAbstractMeshDataInfo._currentLOD;l._preActivateForIntermediateRendering(o);var c;if(c=!(!r||!i||s.layerMask&i.layerMask),s.isEnabled()&&s.isVisible&&s.subMeshes&&!c&&(l!==s&&l._activate(o,!0),s._activate(o,!0)&&s.subMeshes.length)){s.isAnInstance?s._internalAbstractMeshDataInfo._actAsRegularMesh&&(l=s):l._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!1,l._internalAbstractMeshDataInfo._isActiveIntermediate=!0;for(var u=0;u<l.subMeshes.length;u++){var h=l.subMeshes[u];this._renderingManager.dispatch(h,l)}}}}for(var d=0;d<n.particleSystems.length;d++){var p=n.particleSystems[d],f=p.emitter;p.isStarted()&&f&&(!f.position||f.isEnabled())&&this._renderingManager.dispatchParticles(p)}}},t.prototype._bindFrameBuffer=function(e,t){void 0===e&&(e=0),void 0===t&&(t=0);var i=this.getScene();if(i){var r=i.getEngine();this._renderTarget&&r.bindFramebuffer(this._renderTarget,this.isCube?e:void 0,void 0,void 0,this.ignoreCameraViewport,0,t)}},t.prototype._unbindFrameBuffer=function(e,t){var i=this;this._renderTarget&&e.unBindFramebuffer(this._renderTarget,this.isCube,(function(){i.onAfterRenderObservable.notifyObservers(t)}))},t.prototype._prepareFrame=function(e,t,i,r){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):r&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)},t.prototype._renderToTarget=function(e,t,i,r,n){var o,a,s,l,c,h;void 0===r&&(r=0),void 0===n&&(n=null);var d=this.getScene();if(d){var p=d.getEngine();if(null===(o=p._debugPushGroup)||void 0===o||o.call(p,"render to face #".concat(e," layer #").concat(r),1),this._prepareFrame(d,e,r,t),this.is2DArray||this.is3D?(p.currentRenderPassId=this._renderPassIds[r],this.onBeforeRenderObservable.notifyObservers(r)):(p.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),p.snapshotRendering&&p.snapshotRenderingMode===u.SNAPSHOTRENDERING_FAST)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(p):this.skipInitialClear||p.clear(this.clearColor||d.clearColor,!0,!0,!0);else{var f=null,_=this.renderList?this.renderList:d.getActiveMeshes().data,m=this.renderList?this.renderList.length:d.getActiveMeshes().length;this.getCustomRenderList&&(f=this.getCustomRenderList(this.is2DArray||this.is3D?r:e,_,m)),f?this._prepareRenderingManager(f,f.length,n,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(_,m,n,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),f=_);for(var g=0,v=d._beforeRenderTargetClearStage;g<v.length;g++)v[g].action(this,e,r);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(p):this.skipInitialClear||p.clear(this.clearColor||d.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||d.updateTransformMatrix(!0);for(var y=0,b=d._beforeRenderTargetDrawStage;y<b.length;y++)b[y].action(this,e,r);this._renderingManager.render(this.customRenderFunction,f,this.renderParticles,this.renderSprites);for(var T=0,E=d._afterRenderTargetDrawStage;T<E.length;T++)E[T].action(this,e,r);var S=null!==(s=null===(a=this._texture)||void 0===a?void 0:a.generateMipMaps)&&void 0!==s&&s;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,null!==(l=this._renderTarget)&&void 0!==l?l:void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&d.postProcessManager._finalizeFrame(!1,null!==(c=this._renderTarget)&&void 0!==c?c:void 0,e);for(var x=0,A=d._afterRenderTargetPostProcessStage;x<A.length;x++)A[x].action(this,e,r);this._texture&&(this._texture.generateMipMaps=S),this._doNotChangeAspectRatio||d.updateTransformMatrix(!0),i&&Rl.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),p)}this._unbindFrameBuffer(p,e),this._texture&&this.isCube&&5===e&&p.generateMipMapsForCubemap(this._texture,!0),null===(h=p._debugPopGroup)||void 0===h||h.call(p,1)}},t.prototype.setRenderingOrder=function(e,t,i,r){void 0===t&&(t=null),void 0===i&&(i=null),void 0===r&&(r=null),this._renderingManager.setRenderingOrder(e,t,i,r)},t.prototype.setRenderingAutoClearDepthStencil=function(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1},t.prototype.clone=function(){var e=this.getSize(),i=new t(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.coordinatesMode=this.coordinatesMode,this.renderList&&(i.renderList=this.renderList.slice(0)),i},t.prototype.serialize=function(){if(!this.name)return null;var t=e.prototype.serialize.call(this);if(t.renderTargetSize=this.getRenderSize(),t.renderList=[],this.renderList)for(var i=0;i<this.renderList.length;i++)t.renderList.push(this.renderList[i].id);return t},t.prototype.disposeFramebufferObjects=function(){var e;null===(e=this._renderTarget)||void 0===e||e.dispose(!0)},t.prototype.releaseInternalTexture=function(){var e;null===(e=this._renderTarget)||void 0===e||e.releaseTextures(),this._texture=null},t.prototype.dispose=function(){var t;this.onResizeObservable.clear(),this.onClearObservable.clear(),this.onAfterRenderObservable.clear(),this.onAfterUnbindObservable.clear(),this.onBeforeBindObservable.clear(),this.onBeforeRenderObservable.clear(),this._postProcessManager&&(this._postProcessManager.dispose(),this._postProcessManager=null),this._prePassRenderTarget&&this._prePassRenderTarget.dispose(),this._releaseRenderPassId(),this.clearPostProcesses(!0),this._resizeObserver&&(this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.renderList=null;var i=this.getScene();if(i){var r=i.customRenderTargets.indexOf(this);r>=0&&i.customRenderTargets.splice(r,1);for(var n=0,o=i.cameras;n<o.length;n++){var a=o[n];(r=a.customRenderTargets.indexOf(this))>=0&&a.customRenderTargets.splice(r,1)}null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null,this._texture=null,e.prototype.dispose.call(this)}},t.prototype._rebuild=function(){this.refreshRate===t.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=t.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()},t.prototype.freeRenderingGroups=function(){this._renderingManager&&this._renderingManager.freeRenderingGroups()},t.prototype.getViewCount=function(){return 1},t.REFRESHRATE_RENDER_ONCE=0,t.REFRESHRATE_RENDER_ONEVERYFRAME=1,t.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,t}(Ja);Ja._CreateRenderTargetTexture=function(e,t,i,r,n){return new Pl(e,t,i,r)};var Il=function(){function e(e){this.name=Vr.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=[]}return e.prototype.register=function(){this.scene._beforeClearStage.registerStep(Vr.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)},e.prototype.rebuild=function(){},e.prototype.dispose=function(){},e.prototype._beforeClear=function(){if(this.scene.proceduralTexturesEnabled){rr.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(var e=0;e<this.scene.proceduralTextures.length;e++){var t=this.scene.proceduralTextures[e];t._shouldRender()&&t.render()}rr.EndPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0)}},e}();li.ShadersStore.proceduralVertexShader="attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";var Ml,Ol=function(e){function t(t,i,r,n,o,a,s,l){void 0===o&&(o=null),void 0===a&&(a=!0),void 0===s&&(s=!1),void 0===l&&(l=u.TEXTURETYPE_UNSIGNED_INT);var c,h=this;(h=e.call(this,null,n,!a)||this).isEnabled=!0,h.autoClear=!0,h.onGeneratedObservable=new f,h.onBeforeGenerationObservable=new f,h.nodeMaterialSource=null,h._textures={},h._currentRefreshId=-1,h._frameId=-1,h._refreshRate=1,h._vertexBuffers={},h._uniforms=new Array,h._samplers=new Array,h._floats={},h._ints={},h._floatsArrays={},h._colors3={},h._colors4={},h._vectors2={},h._vectors3={},h._vectors4={},h._matrices={},h._fallbackTextureUsed=!1,h._cachedDefines=null,h._contentUpdateId=-1,h._rtWrapper=null,null===o||o instanceof Ja?(h._options={},h._fallbackTexture=o):(h._options=o,h._fallbackTexture=null!==(c=o.fallbackTexture)&&void 0!==c?c:null);var d=(n=h.getScene()||M.LastCreatedScene)._getComponent(Vr.NAME_PROCEDURALTEXTURE);d||(d=new Il(n),n._addComponent(d)),n.proceduralTextures.push(h),h._fullEngine=n.getEngine(),h.name=t,h.isRenderTarget=!0,h._size=i,h._textureType=l,h._generateMipMaps=a,h._drawWrapper=new ho(h._fullEngine),h.setFragment(r);var p=h._createRtWrapper(s,i,a,l);h._texture=p.texture;var _=[];return _.push(1,1),_.push(-1,1),_.push(-1,-1),_.push(1,-1),h._vertexBuffers[Nr.PositionKind]=new Nr(h._fullEngine,_,Nr.PositionKind,!1,!1,2),h._createIndexBuffer(),h}return m(t,e),t.prototype._createRtWrapper=function(e,t,i,r){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,g({generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r},this._options)),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,g({generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r},this._options)),this._rtWrapper},t.prototype.getEffect=function(){return this._drawWrapper.effect},t.prototype._setEffect=function(e){this._drawWrapper.effect=e},t.prototype.getContent=function(){var e=this;return this._contentData&&this._frameId===this._contentUpdateId||(this._contentData?this._contentData.then((function(t){e._contentData=e.readPixels(0,0,t),e._contentUpdateId=e._frameId})):(this._contentData=this.readPixels(0,0),this._contentUpdateId=this._frameId)),this._contentData},t.prototype._createIndexBuffer=function(){var e=this._fullEngine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)},t.prototype._rebuild=function(){var e=this._vertexBuffers[Nr.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===Pl.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=Pl.REFRESHRATE_RENDER_ONCE)},t.prototype.reset=function(){var e;null===(e=this._drawWrapper.effect)||void 0===e||e.dispose(),this._drawWrapper.effect=null,this._cachedDefines=null},t.prototype._getDefines=function(){return""},t.prototype.executeWhenReady=function(e){var t=this;if(this.isReady())e(this);else{var i=this.getEffect();i&&i.executeWhenCompiled((function(){e(t)}))}},t.prototype.isReady=function(){var e=this,t=this._fullEngine;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;var i=this._getDefines();if(this._drawWrapper.effect&&i===this._cachedDefines&&this._drawWrapper.effect.isReady())return!0;var r={vertex:"procedural",fragmentElement:this._fragment.fragmentElement,fragmentSource:this._fragment.fragmentSource,fragment:"string"==typeof this._fragment?this._fragment:void 0};return this._cachedDefines!==i&&(this._cachedDefines=i,this._drawWrapper.effect=t.createEffect(r,[Nr.PositionKind],this._uniforms,this._samplers,i,void 0,void 0,(function(){var t;null===(t=e._rtWrapper)||void 0===t||t.dispose(),e._rtWrapper=e._texture=null,e._fallbackTexture&&(e._texture=e._fallbackTexture._texture,e._texture&&e._texture.incrementReferences()),e._fallbackTextureUsed=!0}))),this._drawWrapper.effect.isReady()},t.prototype.resetRefreshCounter=function(){this._currentRefreshId=-1},t.prototype.setFragment=function(e){this._fragment=e},Object.defineProperty(t.prototype,"refreshRate",{get:function(){return this._refreshRate},set:function(e){this._refreshRate=e,this.resetRefreshCounter()},enumerable:!1,configurable:!0}),t.prototype._shouldRender=function(){return this.isEnabled&&this.isReady()&&this._texture?!this._fallbackTextureUsed&&(-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)):(this._texture&&(this._texture.isReady=!1),!1)},t.prototype.getRenderSize=function(){return this._size},t.prototype.resize=function(e,t){if(!this._fallbackTextureUsed&&this._rtWrapper&&this._texture){var i=this._texture.isCube;this._rtWrapper.dispose();var r=this._createRtWrapper(i,e,t,this._textureType);this._texture=r.texture,this._size=e,this._generateMipMaps=t}},t.prototype._checkUniform=function(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)},t.prototype.setTexture=function(e,t){return-1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this},t.prototype.setFloat=function(e,t){return this._checkUniform(e),this._floats[e]=t,this},t.prototype.setInt=function(e,t){return this._checkUniform(e),this._ints[e]=t,this},t.prototype.setFloats=function(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this},t.prototype.setColor3=function(e,t){return this._checkUniform(e),this._colors3[e]=t,this},t.prototype.setColor4=function(e,t){return this._checkUniform(e),this._colors4[e]=t,this},t.prototype.setVector2=function(e,t){return this._checkUniform(e),this._vectors2[e]=t,this},t.prototype.setVector3=function(e,t){return this._checkUniform(e),this._vectors3[e]=t,this},t.prototype.setVector4=function(e,t){return this._checkUniform(e),this._vectors4[e]=t,this},t.prototype.setMatrix=function(e,t){return this._checkUniform(e),this._matrices[e]=t,this},t.prototype.render=function(e){var t,i,r=this.getScene();if(r){var n=this._fullEngine;if(n.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),n.setState(!1),!this.nodeMaterialSource){for(var o in this._textures)this._drawWrapper.effect.setTexture(o,this._textures[o]);for(var a in this._ints)this._drawWrapper.effect.setInt(a,this._ints[a]);for(var s in this._floats)this._drawWrapper.effect.setFloat(s,this._floats[s]);for(var l in this._floatsArrays)this._drawWrapper.effect.setArray(l,this._floatsArrays[l]);for(var c in this._colors3)this._drawWrapper.effect.setColor3(c,this._colors3[c]);for(var u in this._colors4){var h=this._colors4[u];this._drawWrapper.effect.setFloat4(u,h.r,h.g,h.b,h.a)}for(var d in this._vectors2)this._drawWrapper.effect.setVector2(d,this._vectors2[d]);for(var p in this._vectors3)this._drawWrapper.effect.setVector3(p,this._vectors3[p]);for(var f in this._vectors4)this._drawWrapper.effect.setVector4(f,this._vectors4[f]);for(var _ in this._matrices)this._drawWrapper.effect.setMatrix(_,this._matrices[_])}if(this._texture&&this._rtWrapper){null===(t=n._debugPushGroup)||void 0===t||t.call(n,"procedural texture generation for ".concat(this.name),1);var m=n.currentViewport;if(this.isCube)for(var g=0;g<6;g++)n.bindFramebuffer(this._rtWrapper,g,void 0,void 0,!0),n.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",g),this.autoClear&&n.clear(r.clearColor,!0,!1,!1),n.drawElementsType(Ca.TriangleFillMode,0,6);else n.bindFramebuffer(this._rtWrapper,0,void 0,void 0,!0),n.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this.autoClear&&n.clear(r.clearColor,!0,!1,!1),n.drawElementsType(Ca.TriangleFillMode,0,6);n.unBindFramebuffer(this._rtWrapper,this.isCube),m&&n.setViewport(m),this.isCube&&n.generateMipMapsForCubemap(this._texture,!0),null===(i=n._debugPopGroup)||void 0===i||i.call(n,1),this.onGenerated&&this.onGenerated(),this.onGeneratedObservable.notifyObservers(this)}}},t.prototype.clone=function(){var e=this.getSize(),i=new t(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.coordinatesMode=this.coordinatesMode,i},t.prototype.dispose=function(){var t=this.getScene();if(t){var i=t.proceduralTextures.indexOf(this);i>=0&&t.proceduralTextures.splice(i,1);var r=this._vertexBuffers[Nr.PositionKind];r&&(r.dispose(),this._vertexBuffers[Nr.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),e.prototype.dispose.call(this)}},v([Ie()],t.prototype,"isEnabled",void 0),v([Ie()],t.prototype,"autoClear",void 0),v([Ie()],t.prototype,"_generateMipMaps",void 0),v([Ie()],t.prototype,"_size",void 0),v([Ie()],t.prototype,"refreshRate",null),t}(Ja);a("BABYLON.ProceduralTexture",Ol),function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Exp2=4]="Exp2",e[e.Round=5]="Round",e[e.Floor=6]="Floor",e[e.Ceiling=7]="Ceiling",e[e.Sqrt=8]="Sqrt",e[e.Log=9]="Log",e[e.Tan=10]="Tan",e[e.ArcTan=11]="ArcTan",e[e.ArcCos=12]="ArcCos",e[e.ArcSin=13]="ArcSin",e[e.Fract=14]="Fract",e[e.Sign=15]="Sign",e[e.Radians=16]="Radians",e[e.Degrees=17]="Degrees",e[e.Set=18]="Set"}(Ml||(Ml={}));var Dl=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.operation=Ml.Cos,i.registerInput("input",Ns.AutoDetect),i.registerOutput("output",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i}return m(t,e),t.prototype.getClassName=function(){return"TrigonometryBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],r="";switch(this.operation){case Ml.Cos:r="cos";break;case Ml.Sin:r="sin";break;case Ml.Abs:r="abs";break;case Ml.Exp:r="exp";break;case Ml.Exp2:r="exp2";break;case Ml.Round:r="round";break;case Ml.Floor:r="floor";break;case Ml.Ceiling:r="ceil";break;case Ml.Sqrt:r="sqrt";break;case Ml.Log:r="log";break;case Ml.Tan:r="tan";break;case Ml.ArcTan:r="atan";break;case Ml.ArcCos:r="acos";break;case Ml.ArcSin:r="asin";break;case Ml.Fract:r="fract";break;case Ml.Sign:r="sign";break;case Ml.Radians:r="radians";break;case Ml.Degrees:r="degrees";break;case Ml.Set:r=""}return t.compilationString+=t._declareOutput(i)+" = ".concat(r,"(").concat(this.input.associatedVariableName,");\n"),this},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.operation=this.operation,t},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),this.operation=t.operation},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".operation = BABYLON.TrigonometryBlockOperations.").concat(Ml[this.operation],";\n")},t}(Ws);a("BABYLON.TrigonometryBlock",Dl);var Nl={effect:null,subMesh:null},Fl=function(e){function t(){var t=e.call(this)||this;return t.NORMAL=!1,t.TANGENT=!1,t.VERTEXCOLOR_NME=!1,t.UV1=!1,t.UV2=!1,t.UV3=!1,t.UV4=!1,t.UV5=!1,t.UV6=!1,t.PREPASS=!1,t.PREPASS_NORMAL=!1,t.PREPASS_NORMAL_INDEX=-1,t.PREPASS_POSITION=!1,t.PREPASS_POSITION_INDEX=-1,t.PREPASS_DEPTH=!1,t.PREPASS_DEPTH_INDEX=-1,t.SCENE_MRT_COUNT=0,t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.BONETEXTURE=!1,t.MORPHTARGETS=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_UV=!1,t.NUM_MORPH_INFLUENCERS=0,t.MORPHTARGETS_TEXTURE=!1,t.IMAGEPROCESSING=!1,t.VIGNETTE=!1,t.VIGNETTEBLENDMODEMULTIPLY=!1,t.VIGNETTEBLENDMODEOPAQUE=!1,t.TONEMAPPING=0,t.CONTRAST=!1,t.EXPOSURE=!1,t.COLORCURVES=!1,t.COLORGRADING=!1,t.COLORGRADING3D=!1,t.SAMPLER3DGREENDEPTH=!1,t.SAMPLER3DBGRMAP=!1,t.DITHER=!1,t.IMAGEPROCESSINGPOSTPROCESS=!1,t.SKIPFINALCOLORCLAMP=!1,t.BUMPDIRECTUV=0,t.CAMERA_ORTHOGRAPHIC=!1,t.CAMERA_PERSPECTIVE=!1,t.rebuild(),t}return m(t,e),t.prototype.setValue=function(e,t,i){void 0===i&&(i=!1),void 0===this[e]&&this._keys.push(e),i&&this[e]!==t&&this.markAsUnprocessed(),this[e]=t},t}(Gs),Ll=function(e){function t(i,r,n){void 0===n&&(n={});var o=e.call(this,i,r||M.LastCreatedScene)||this;return o._buildId=t._BuildIdGenerator++,o._buildWasSuccessful=!1,o._cachedWorldViewMatrix=new z,o._cachedWorldViewProjectionMatrix=new z,o._optimizers=new Array,o._animationFrame=-1,o.BJSNODEMATERIALEDITOR=o._getGlobalNodeMaterialEditor(),o.editorData=null,o.ignoreAlpha=!1,o.maxSimultaneousLights=4,o.onBuildObservable=new f,o._vertexOutputNodes=new Array,o._fragmentOutputNodes=new Array,o.attachedBlocks=[],o._mode=fl.Material,o.forceAlphaBlending=!1,o._options=g({emitComments:!1,shaderLanguage:pt.GLSL},n),o._attachImageProcessingConfiguration(null),o}return m(t,e),t._BlockIsTextureBlock=function(e){return"TextureBlock"===e.getClassName()||"ReflectionTextureBaseBlock"===e.getClassName()||"ReflectionTextureBlock"===e.getClassName()||"ReflectionBlock"===e.getClassName()||"RefractionBlock"===e.getClassName()||"CurrentScreenBlock"===e.getClassName()||"ParticleTextureBlock"===e.getClassName()||"ImageSourceBlock"===e.getClassName()||"TriPlanarBlock"===e.getClassName()||"BiPlanarBlock"===e.getClassName()||"PrePassTextureBlock"===e.getClassName()},t.prototype._getGlobalNodeMaterialEditor=function(){return"undefined"!=typeof NODEEDITOR?NODEEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeEditor?BABYLON:void 0},Object.defineProperty(t.prototype,"shaderLanguage",{get:function(){return this._options.shaderLanguage},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"options",{get:function(){return this._options},set:function(e){this._options=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"mode",{get:function(){return this._mode},set:function(e){this._mode=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buildId",{get:function(){return this._buildId},set:function(e){this._buildId=e},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"NodeMaterial"},t.prototype._attachImageProcessingConfiguration=function(e){var t=this;e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((function(){t._markAllSubMeshesAsImageProcessingDirty()}))))},t.prototype.getBlockByName=function(e){for(var t=null,i=0,r=this.attachedBlocks;i<r.length;i++){var n=r[i];if(n.name===e){if(t)return rr.Warn("More than one block was found with the name `"+e+"`"),t;t=n}}return t},t.prototype.getBlockByPredicate=function(e){for(var t=0,i=this.attachedBlocks;t<i.length;t++){var r=i[t];if(e(r))return r}return null},t.prototype.getInputBlockByPredicate=function(e){for(var t=0,i=this.attachedBlocks;t<i.length;t++){var r=i[t];if(r.isInput&&e(r))return r}return null},t.prototype.getInputBlocks=function(){for(var e=[],t=0,i=this.attachedBlocks;t<i.length;t++){var r=i[t];r.isInput&&e.push(r)}return e},t.prototype.registerOptimizer=function(e){if(!(this._optimizers.indexOf(e)>-1))return this._optimizers.push(e),this},t.prototype.unregisterOptimizer=function(e){var t=this._optimizers.indexOf(e);if(-1!==t)return this._optimizers.splice(t,1),this},t.prototype.addOutputNode=function(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return e.target&Fs.Vertex&&this._addVertexOutputNode(e),e.target&Fs.Fragment&&this._addFragmentOutputNode(e),this},t.prototype.removeOutputNode=function(e){return null===e.target||(e.target&Fs.Vertex&&this._removeVertexOutputNode(e),e.target&Fs.Fragment&&this._removeFragmentOutputNode(e)),this},t.prototype._addVertexOutputNode=function(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=Fs.Vertex,this._vertexOutputNodes.push(e),this},t.prototype._removeVertexOutputNode=function(e){var t=this._vertexOutputNodes.indexOf(e);if(-1!==t)return this._vertexOutputNodes.splice(t,1),this},t.prototype._addFragmentOutputNode=function(e){if(-1===this._fragmentOutputNodes.indexOf(e))return e.target=Fs.Fragment,this._fragmentOutputNodes.push(e),this},t.prototype._removeFragmentOutputNode=function(e){var t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this},t.prototype.needAlphaBlending=function(){return!this.ignoreAlpha&&(this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)},t.prototype.needAlphaTesting=function(){return this._sharedData&&this._sharedData.hints.needAlphaTesting},t.prototype._processInitializeOnLink=function(e,t,i,r){void 0===r&&(r=!0),(e.target===Fs.VertexAndFragment||t.target===Fs.Fragment&&e.target===Fs.Vertex&&e._preparationId!==this._buildId)&&i.push(e),this._initializeBlock(e,t,i,r)},t.prototype._initializeBlock=function(e,t,i,r){if(void 0===r&&(r=!0),e.initialize(t),r&&e.autoConfigure(this),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)){if(e.isUnique)for(var n=e.getClassName(),o=0,a=this.attachedBlocks;o<a.length;o++)if(a[o].getClassName()===n)throw"Cannot have multiple blocks of type ".concat(n," in the same NodeMaterial");this.attachedBlocks.push(e)}for(var s=0,l=e.inputs;s<l.length;s++){var c=l[s];c.associatedVariableName="";var u=c.connectedPoint;if(u){var h=u.ownerBlock;h!==e&&this._processInitializeOnLink(h,t,i,r)}}if(e.isTeleportOut){var d=e;d.entryPoint&&this._processInitializeOnLink(d.entryPoint,t,i,r)}for(var p=0,f=e.outputs;p<f.length;p++)f[p].associatedVariableName=""},t.prototype._resetDualBlocks=function(e,t){e.target===Fs.VertexAndFragment&&(e.buildId=t);for(var i=0,r=e.inputs;i<r.length;i++){var n=r[i].connectedPoint;if(n){var o=n.ownerBlock;o!==e&&this._resetDualBlocks(o,t)}}if(e.isTeleportOut){var a=e;a.entryPoint&&this._resetDualBlocks(a.entryPoint,t)}},t.prototype.removeBlock=function(e){var t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)},t.prototype.build=function(e,i,r){void 0===e&&(e=!1),void 0===i&&(i=!0),void 0===r&&(r=!1),this._vertexCompilationState||r||(r=!0),this._buildWasSuccessful=!1;var n=this.getScene().getEngine(),o=this._mode===fl.Particle;if(0===this._vertexOutputNodes.length&&!o)throw"You must define at least one vertexOutputNode";if(0===this._fragmentOutputNodes.length)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new Vs,this._vertexCompilationState.supportUniformBuffers=n.supportsUniformBuffers,this._vertexCompilationState.target=Fs.Vertex,this._fragmentCompilationState=new Vs,this._fragmentCompilationState.supportUniformBuffers=n.supportsUniformBuffers,this._fragmentCompilationState.target=Fs.Fragment,this._sharedData=new ks,this._sharedData.nodeMaterial=this,this._sharedData.fragmentOutputNodes=this._fragmentOutputNodes,this._vertexCompilationState.sharedData=this._sharedData,this._fragmentCompilationState.sharedData=this._sharedData,this._sharedData.buildId=this._buildId,this._sharedData.emitComments=this._options.emitComments,this._sharedData.verbose=e,this._sharedData.scene=this.getScene(),this._sharedData.allowEmptyVertexProgram=o;for(var a=[],s=[],l=0,c=this._vertexOutputNodes;l<c.length;l++){var u=c[l];a.push(u),this._initializeBlock(u,this._vertexCompilationState,s,r)}for(var h=0,d=this._fragmentOutputNodes;h<d.length;h++){var p=d[h];s.push(p),this._initializeBlock(p,this._fragmentCompilationState,a,r)}this.optimize();for(var f=0,_=a;f<_.length;f++)(u=_[f]).build(this._vertexCompilationState,a);this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState;for(var m=0,g=s;m<g.length;m++)p=g[m],this._resetDualBlocks(p,this._buildId-1);for(var v=0,y=s;v<y.length;v++)(p=y[v]).build(this._fragmentCompilationState,s);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),i&&(this._buildId=t._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(ae.Log("Vertex shader:"),ae.Log(this._vertexCompilationState.compilationString),ae.Log("Fragment shader:"),ae.Log(this._fragmentCompilationState.compilationString)),this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this);for(var b=0,T=this.getScene().meshes;b<T.length;b++){var E=T[b];if(E.subMeshes)for(var S=0,x=E.subMeshes;S<x.length;S++){var A=x[S];if(A.getMaterial()===this&&A.materialDefines){var C=A.materialDefines;C.markAllAsDirty(),C.reset()}}}this.prePassTextureInputs.length&&this.getScene().enablePrePassRenderer();var R=this.getScene().prePassRenderer;R&&R.markAsDirty()},t.prototype.optimize=function(){for(var e=0,t=this._optimizers;e<t.length;e++)t[e].optimize(this._vertexOutputNodes,this._fragmentOutputNodes)},t.prototype._prepareDefinesForAttributes=function(e,t){var i=t.NORMAL,r=t.TANGENT,n=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(Nr.NormalKind),t.TANGENT=e.isVerticesDataPresent(Nr.TangentKind);var o=e.useVertexColors&&e.isVerticesDataPresent(Nr.ColorKind);t.VERTEXCOLOR_NME=o;for(var a=!1,s=1;s<=u.MAX_SUPPORTED_UV_SETS;++s){var l=t["UV"+s];t["UV"+s]=e.isVerticesDataPresent("uv".concat(1===s?"":s)),a=a||t["UV"+s]!==l}var c=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;Ea(this.getScene(),t,!c),(i!==t.NORMAL||r!==t.TANGENT||n!==t.VERTEXCOLOR_NME||a)&&t.markAsAttributesDirty()},Object.defineProperty(t.prototype,"isPrePassCapable",{get:function(){return!0},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"prePassTextureOutputs",{get:function(){var e=this.getBlockByPredicate((function(e){return"PrePassOutputBlock"===e.getClassName()})),t=[u.PREPASS_COLOR_TEXTURE_TYPE];return e?(this.prePassTextureInputs.length||(e.viewDepth.isConnected&&t.push(u.PREPASS_DEPTH_TEXTURE_TYPE),e.viewNormal.isConnected&&t.push(u.PREPASS_NORMAL_TEXTURE_TYPE),e.worldPosition.isConnected&&t.push(u.PREPASS_POSITION_TEXTURE_TYPE)),t):t},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"prePassTextureInputs",{get:function(){for(var e=this.getAllTextureBlocks().filter((function(e){return"PrePassTextureBlock"===e.getClassName()})),t=[],i=0,r=e;i<r.length;i++){var n=r[i];n.position.isConnected&&!t.includes(u.PREPASS_POSITION_TEXTURE_TYPE)&&t.push(u.PREPASS_POSITION_TEXTURE_TYPE),n.depth.isConnected&&!t.includes(u.PREPASS_DEPTH_TEXTURE_TYPE)&&t.push(u.PREPASS_DEPTH_TEXTURE_TYPE),n.normal.isConnected&&!t.includes(u.PREPASS_NORMAL_TEXTURE_TYPE)&&t.push(u.PREPASS_NORMAL_TEXTURE_TYPE)}return t},enumerable:!1,configurable:!0}),t.prototype.setPrePassRenderer=function(e){var t=this.prePassTextureInputs.concat(this.prePassTextureOutputs);if(e&&t.length>1){var i=e.getEffectConfiguration("nodeMaterial");i||(i=e.addEffectConfiguration({enabled:!0,needsImageProcessing:!1,name:"nodeMaterial",texturesRequired:[]}));for(var r=0,n=t;r<n.length;r++){var o=n[r];i.texturesRequired.includes(o)||i.texturesRequired.push(o)}i.enabled=!0}return t.length>1},t.prototype.createPostProcess=function(e,t,i,r,n,o,a){return void 0===t&&(t=1),void 0===i&&(i=u.TEXTURE_NEAREST_SAMPLINGMODE),void 0===o&&(o=u.TEXTURETYPE_UNSIGNED_INT),void 0===a&&(a=u.TEXTUREFORMAT_RGBA),this.mode!==fl.PostProcess?(ae.Log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,r,n,o,a)},t.prototype.createEffectForPostProcess=function(e){this._createEffectForPostProcess(e)},t.prototype._createEffectForPostProcess=function(e,t,i,r,n,o,a,s){var l=this;void 0===i&&(i=1),void 0===r&&(r=u.TEXTURE_NEAREST_SAMPLINGMODE),void 0===a&&(a=u.TEXTURETYPE_UNSIGNED_INT),void 0===s&&(s=u.TEXTUREFORMAT_RGBA);var c=this.name+this._buildId,h=new Fl,d=new Uo(c+"PostProcess",this.getScene()),p=this._buildId;return this._processDefines(d,h),Ei.RegisterShader(c,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),e?e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,c,c):e=new hl(this.name+"PostProcess",c,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,r,n,o,h.toString(),a,c,{maxSimultaneousLights:this.maxSimultaneousLights},!1,s),e.nodeMaterialSource=this,e.onApplyObservable.add((function(t){p!==l._buildId&&(delete Ei.ShadersStore[c+"VertexShader"],delete Ei.ShadersStore[c+"PixelShader"],c=l.name+l._buildId,h.markAllAsDirty(),p=l._buildId),l._processDefines(d,h)&&(Ei.RegisterShader(c,l._fragmentCompilationState._builtCompilationString,l._vertexCompilationState._builtCompilationString),si.SetImmediate((function(){return e.updateEffect(h.toString(),l._fragmentCompilationState.uniforms,l._fragmentCompilationState.samplers,{maxSimultaneousLights:l.maxSimultaneousLights},void 0,void 0,c,c)}))),l._checkInternals(t)})),e},t.prototype.createProceduralTexture=function(e,t){var i=this;if(this.mode!==fl.ProceduralTexture)return ae.Log("Incompatible material mode"),null;var r=this.name+this._buildId,n=new Ol(r,e,null,t),o=new Uo(r+"Procedural",this.getScene());o.reservedDataStore={hidden:!0};var a=new Fl,s=this._processDefines(o,a);Ei.RegisterShader(r,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);var l=this.getScene().getEngine().createEffect({vertexElement:r,fragmentElement:r},[Nr.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,a.toString(),null==s?void 0:s.fallbacks,void 0);n.nodeMaterialSource=this,n._setEffect(l);var c=this._buildId;return n.onBeforeGenerationObservable.add((function(){c!==i._buildId&&(delete Ei.ShadersStore[r+"VertexShader"],delete Ei.ShadersStore[r+"PixelShader"],r=i.name+i._buildId,a.markAllAsDirty(),c=i._buildId);var e=i._processDefines(o,a);e&&(Ei.RegisterShader(r,i._fragmentCompilationState._builtCompilationString,i._vertexCompilationState._builtCompilationString),si.SetImmediate((function(){l=i.getScene().getEngine().createEffect({vertexElement:r,fragmentElement:r},[Nr.PositionKind],i._fragmentCompilationState.uniforms,i._fragmentCompilationState.samplers,a.toString(),null==e?void 0:e.fallbacks,void 0),n._setEffect(l)}))),i._checkInternals(l)})),n},t.prototype._createEffectForParticles=function(e,t,i,r,n,o,a,s){var l=this;void 0===s&&(s="");var c=this.name+this._buildId+"_"+t;o||(o=new Fl),a||(a=this.getScene().getMeshByName(this.name+"Particle"))||((a=new Uo(this.name+"Particle",this.getScene())).reservedDataStore={hidden:!0});var u=this._buildId,h=[],d=s;if(!n){var p=this._processDefines(a,o);Ei.RegisterShader(c,this._fragmentCompilationState._builtCompilationString),e.fillDefines(h,t),d=h.join("\n"),n=this.getScene().getEngine().createEffectForParticles(c,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,o.toString()+"\n"+d,null==p?void 0:p.fallbacks,i,r,e),e.setCustomEffect(n,t)}n.onBindObservable.add((function(n){u!==l._buildId&&(delete Ei.ShadersStore[c+"PixelShader"],c=l.name+l._buildId+"_"+t,o.markAllAsDirty(),u=l._buildId),h.length=0,e.fillDefines(h,t);var p=h.join("\n");p!==d&&(o.markAllAsDirty(),d=p);var f=l._processDefines(a,o);if(f)return Ei.RegisterShader(c,l._fragmentCompilationState._builtCompilationString),n=l.getScene().getEngine().createEffectForParticles(c,l._fragmentCompilationState.uniforms,l._fragmentCompilationState.samplers,o.toString()+"\n"+d,null==f?void 0:f.fallbacks,i,r,e),e.setCustomEffect(n,t),void l._createEffectForParticles(e,t,i,r,n,o,a,s);l._checkInternals(n)}))},t.prototype._checkInternals=function(e){if(this._sharedData.animatedInputs){var t=this.getScene(),i=t.getFrameId();if(this._animationFrame!==i){for(var r=0,n=this._sharedData.animatedInputs;r<n.length;r++)n[r].animate(t);this._animationFrame=i}}for(var o=0,a=this._sharedData.bindableBlocks;o<a.length;o++)a[o].bind(e,this);for(var s=0,l=this._sharedData.inputBlocks;s<l.length;s++)l[s]._transmit(e,this.getScene(),this)},t.prototype.createEffectForParticles=function(e,t,i){this.mode===fl.Particle?(this._createEffectForParticles(e,vl.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,vl.BLENDMODE_MULTIPLY,t,i)):ae.Log("Incompatible material mode")},t.prototype.createAsShadowDepthWrapper=function(e){this.mode===fl.Material?e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene()):ae.Log("Incompatible material mode")},t.prototype._processDefines=function(e,t,i,r){var n=this;void 0===i&&(i=!1);var o=null;if(Sa(this.getScene(),t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach((function(r){r.initializeDefines(e,n,t,i)})),this._sharedData.blocksWithDefines.forEach((function(o){o.prepareDefines(e,n,t,i,r)})),t.isDirty){var a=t._areLightsDisposed;t.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach((function(i){i.replaceRepeatableContent(n._vertexCompilationState,n._fragmentCompilationState,e,t)}));var s=[];this._sharedData.dynamicUniformBlocks.forEach((function(e){e.updateUniformsAndSamples(n._vertexCompilationState,n,t,s)}));var l=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach((function(e){-1===l.indexOf(e)&&l.push(e)}));var c=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach((function(e){-1===c.indexOf(e)&&c.push(e)}));var u=new ll;this._sharedData.blocksWithFallbacks.forEach((function(t){t.provideFallbacks(e,u)})),o={lightDisposed:a,uniformBuffers:s,mergedUniforms:l,mergedSamplers:c,fallbacks:u}}return o},t.prototype.isReadyForSubMesh=function(e,t,i){var r=this;if(void 0===i&&(i=!1),!this._buildWasSuccessful)return!1;var n=this.getScene();if(this._sharedData.animatedInputs){var o=n.getFrameId();if(this._animationFrame!==o){for(var a=0,s=this._sharedData.animatedInputs;a<s.length;a++)s[a].animate(n);this._animationFrame=o}}var l=t._drawWrapper;if(l.effect&&this.isFrozen&&l._wasPreviouslyReady&&l._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new Fl);var c=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;var u=n.getEngine();if(this._prepareDefinesForAttributes(e,c),this._sharedData.blockingBlocks.some((function(t){return!t.isReady(e,r,c,i)})))return!1;var h=this._processDefines(e,c,i,t);if(h){var d=t.effect,p=c.toString(),f=u.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:h.mergedUniforms,uniformBuffersNames:h.uniformBuffers,samplers:h.mergedSamplers,defines:p,fallbacks:h.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:c.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:c.NUM_MORPH_INFLUENCERS},shaderLanguage:this.shaderLanguage},u);if(f)if(this._onEffectCreatedObservable&&(Nl.effect=f,Nl.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Nl)),this.allowShaderHotSwapping&&d&&!f.isReady()){if(f=d,c.markAsUnprocessed(),h.lightDisposed)return c._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(f,c,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(c._renderId=n.getRenderId(),l._wasPreviouslyReady=!0,l._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))},Object.defineProperty(t.prototype,"compiledShaders",{get:function(){return"// Vertex shader\n".concat(this._vertexCompilationState.compilationString,"\n\n// Fragment shader\n").concat(this._fragmentCompilationState.compilationString)},enumerable:!1,configurable:!0}),t.prototype.bindOnlyWorldMatrix=function(e){var t=this.getScene();if(this._activeEffect){var i=this._sharedData.hints;i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix);for(var r=0,n=this._sharedData.inputBlocks;r<n.length;r++)n[r]._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}},t.prototype.bindForSubMesh=function(e,t,i){var r=this.getScene(),n=i.effect;if(n){this._activeEffect=n,this.bindOnlyWorldMatrix(e);var o=this._mustRebind(r,n,i,t.visibility),a=this._sharedData;if(o){for(var s=0,l=a.bindableBlocks;s<l.length;s++)l[s].bind(n,this,t,i);for(var c=0,u=a.forcedBindableBlocks;c<u.length;c++)u[c].bind(n,this,t,i);for(var h=0,d=a.inputBlocks;h<d.length;h++)d[h]._transmit(n,r,this)}else if(!this.isFrozen)for(var p=0,f=a.forcedBindableBlocks;p<f.length;p++)f[p].bind(n,this,t,i);this._afterBind(t,this._activeEffect,i)}},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);return this._sharedData&&t.push.apply(t,this._sharedData.textureBlocks.filter((function(e){return e.texture})).map((function(e){return e.texture}))),t},t.prototype.getTextureBlocks=function(){return this._sharedData?this._sharedData.textureBlocks:[]},t.prototype.getAllTextureBlocks=function(){for(var e=[],i=0,r=this.attachedBlocks;i<r.length;i++){var n=r[i];t._BlockIsTextureBlock(n)&&e.push(n)}return e},t.prototype.hasTexture=function(t){if(e.prototype.hasTexture.call(this,t))return!0;if(!this._sharedData)return!1;for(var i=0,r=this._sharedData.textureBlocks;i<r.length;i++)if(r[i].texture===t)return!0;return!1},t.prototype.dispose=function(t,i,r){if(i)for(var n=0,o=this.getTextureBlocks().filter((function(e){return e.texture})).map((function(e){return e.texture}));n<o.length;n++)o[n].dispose();for(var a=0,s=this.attachedBlocks;a<s.length;a++)s[a].dispose();this.attachedBlocks.length=0,this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this._imageProcessingObserver&&(this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingObserver=null),e.prototype.dispose.call(this,t,i,r)},t.prototype._createNodeEditor=function(e){var t=g({nodeMaterial:this},e);this.BJSNODEMATERIALEDITOR.NodeEditor.Show(t)},t.prototype.edit=function(e){var i=this;return new Promise((function(r){if(i.BJSNODEMATERIALEDITOR=i.BJSNODEMATERIALEDITOR||i._getGlobalNodeMaterialEditor(),void 0===i.BJSNODEMATERIALEDITOR){var n=e&&e.editorURL?e.editorURL:t.EditorURL;rr.LoadBabylonScript(n,(function(){i.BJSNODEMATERIALEDITOR=i.BJSNODEMATERIALEDITOR||i._getGlobalNodeMaterialEditor(),i._createNodeEditor(null==e?void 0:e.nodeEditorConfig),r()}))}else i._createNodeEditor(null==e?void 0:e.nodeEditorConfig),r()}))},t.prototype.clear=function(){this._vertexOutputNodes.length=0,this._fragmentOutputNodes.length=0,this.attachedBlocks.length=0},t.prototype.setToDefault=function(){this.clear(),this.editorData=null;var e=new rl("Position");e.setAsAttribute("position");var t=new rl("World");t.setAsSystemValue(Qs.World);var i=new Hs("WorldPos");e.connectTo(i),t.connectTo(i);var r=new rl("ViewProjection");r.setAsSystemValue(Qs.ViewProjection);var n=new Hs("WorldPos * ViewProjectionTransform");i.connectTo(n),r.connectTo(n);var o=new js("VertexOutput");n.connectTo(o);var a=new rl("color");a.value=new J(.8,.8,.8,1);var s=new qs("FragmentOutput");a.connectTo(s),this.addOutputNode(o),this.addOutputNode(s),this._mode=fl.Material},t.prototype.setToDefaultPostProcess=function(){this.clear(),this.editorData=null;var e=new rl("Position");e.setAsAttribute("position2d");var t=new rl("Constant1");t.isConstant=!0,t.value=1;var i=new dl("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});var r=new js("VertexOutput");i.connectTo(r);var n=new rl("Scale");n.visibleInInspector=!0,n.value=new U(1,1);var o=new pl("uv0");e.connectTo(o);var a=new ml("UV scale");o.connectTo(a),n.connectTo(a);var s=new nl("CurrentScreen");a.connectTo(s),s.texture=new Ja("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());var l=new qs("FragmentOutput");s.connectTo(l,{output:"rgba"}),this.addOutputNode(r),this.addOutputNode(l),this._mode=fl.PostProcess},t.prototype.setToDefaultProceduralTexture=function(){this.clear(),this.editorData=null;var e=new rl("Position");e.setAsAttribute("position2d");var t=new rl("Constant1");t.isConstant=!0,t.value=1;var i=new dl("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});var r=new js("VertexOutput");i.connectTo(r);var n=new rl("Time");n.value=0,n.min=0,n.max=0,n.isBoolean=!1,n.matrixMode=0,n.animationType=Zs.Time,n.isConstant=!1;var o=new rl("Color3");o.value=new Z(1,1,1),o.isConstant=!1;var a=new qs("FragmentOutput"),s=new dl("VectorMerger");s.visibleInInspector=!1;var l=new Dl("Cos");l.operation=Ml.Cos,e.connectTo(s),n.output.connectTo(l.input),l.output.connectTo(s.z),s.xyzOut.connectTo(a.rgb),this.addOutputNode(r),this.addOutputNode(a),this._mode=fl.ProceduralTexture},t.prototype.setToDefaultParticle=function(){this.clear(),this.editorData=null;var e=new rl("uv");e.setAsAttribute("particle_uv");var t=new ol("ParticleTexture");e.connectTo(t);var i=new rl("Color");i.setAsAttribute("particle_color");var r=new ml("Texture * Color");t.connectTo(r),i.connectTo(r);var n=new al("ParticleRampGradient");r.connectTo(n);var o=new yl("ColorSplitter");i.connectTo(o);var a=new sl("ParticleBlendMultiply");n.connectTo(a),t.connectTo(a,{output:"a"}),o.connectTo(a,{output:"a"});var s=new qs("FragmentOutput");a.connectTo(s),this.addOutputNode(s),this._mode=fl.Particle},t.prototype.loadAsync=function(e,i){return void 0===i&&(i=""),y(this,void 0,void 0,(function(){return b(this,(function(r){return[2,t.ParseFromFileAsync("",e,this.getScene(),i,!0,this)]}))}))},t.prototype._gatherBlocks=function(e,t){if(-1===t.indexOf(e)){t.push(e);for(var i=0,r=e.inputs;i<r.length;i++){var n=r[i].connectedPoint;n&&(o=n.ownerBlock)!==e&&this._gatherBlocks(o,t)}var o;e.isTeleportOut&&(o=e).entryPoint&&this._gatherBlocks(o.entryPoint,t)}},t.prototype.generateCode=function(){for(var e=[],t=[],i=["const","var","let"],r=0,n=this._vertexOutputNodes;r<n.length;r++){var o=n[r];this._gatherBlocks(o,t)}for(var a=[],s=0,l=this._fragmentOutputNodes;s<l.length;s++)o=l[s],this._gatherBlocks(o,a);var c='var nodeMaterial = new BABYLON.NodeMaterial("'.concat(this.name||"node material",'");\n');c+="nodeMaterial.mode = BABYLON.NodeMaterialModes.".concat(fl[this.mode],";\n");for(var u=0,h=t;u<h.length;u++)(b=h[u]).isInput&&-1===e.indexOf(b)&&(c+=b._dumpCode(i,e));for(var d=0,p=a;d<p.length;d++)(b=p[d]).isInput&&-1===e.indexOf(b)&&(c+=b._dumpCode(i,e));e=[],c+="\n// Connections\n";for(var f=0,_=this._vertexOutputNodes;f<_.length;f++)c+=(b=_[f])._dumpCodeForOutputConnections(e);for(var m=0,g=this._fragmentOutputNodes;m<g.length;m++)c+=(b=g[m])._dumpCodeForOutputConnections(e);c+="\n// Output nodes\n";for(var v=0,y=this._vertexOutputNodes;v<y.length;v++){var b=y[v];c+="nodeMaterial.addOutputNode(".concat(b._codeVariableName,");\n")}for(var T=0,E=this._fragmentOutputNodes;T<E.length;T++)b=E[T],c+="nodeMaterial.addOutputNode(".concat(b._codeVariableName,");\n");return c+"nodeMaterial.build();\n"},t.prototype.serialize=function(e){var t=e?{}:Ke.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));var i=[];if(e)i=e;else{t.customType="BABYLON.NodeMaterial",t.outputNodes=[];for(var r=0,n=this._vertexOutputNodes;r<n.length;r++){var o=n[r];this._gatherBlocks(o,i),t.outputNodes.push(o.uniqueId)}for(var a=0,s=this._fragmentOutputNodes;a<s.length;a++)o=s[a],this._gatherBlocks(o,i),-1===t.outputNodes.indexOf(o.uniqueId)&&t.outputNodes.push(o.uniqueId)}t.blocks=[];for(var l=0,c=i;l<c.length;l++){var u=c[l];t.blocks.push(u.serialize())}if(!e)for(var h=0,d=this.attachedBlocks;h<d.length;h++)u=d[h],-1===i.indexOf(u)&&t.blocks.push(u.serialize());return t},t.prototype._restoreConnections=function(e,t,i){for(var r=0,n=e.outputs;r<n.length;r++)for(var o=n[r],a=0,s=t.blocks;a<s.length;a++){var l=s[a],c=i[l.id];if(c)for(var u=0,h=l.inputs;u<h.length;u++){var d=h[u];if(i[d.targetBlockId]!==e||d.targetConnectionName!==o.name);else{var p=c.getInputByName(d.inputName);if(!p||p.isConnected)continue;o.connectTo(p,!0),this._restoreConnections(c,t,i)}}}},t.prototype.parseSerializedObject=function(e,t,i,r){var n;void 0===t&&(t=""),void 0===i&&(i=!1),i||this.clear();for(var o={},a=0,l=e.blocks;a<l.length;a++){var c=s((_=l[a]).customType);c&&((m=new c)._deserialize(_,this.getScene(),t,r),o[_.id]=m,this.attachedBlocks.push(m))}for(var u=0,h=this.attachedBlocks;u<h.length;u++)if((m=h[u]).isTeleportOut){var d=m,p=d._tempEntryPointUniqueId;p&&o[p].attachToEndpoint(d)}for(var f=0;f<e.blocks.length;f++){var _,m;(m=o[(_=e.blocks[f]).id])&&(m.inputs.length&&!i||this._restoreConnections(m,e,o))}if(e.outputNodes)for(var g=0,v=e.outputNodes;g<v.length;g++){var y=v[g];this.addOutputNode(o[y])}if(e.locations||e.editorData&&e.editorData.locations){for(var b=e.locations||e.editorData.locations,T=0,E=b;T<E.length;T++){var S=E[T];o[S.blockId]&&(S.blockId=o[S.blockId].uniqueId)}i&&this.editorData&&this.editorData.locations&&b.concat(this.editorData.locations),e.locations?this.editorData={locations:b}:(this.editorData=e.editorData,this.editorData.locations=b);var x=[];for(var A in o)x[A]=o[A].uniqueId;this.editorData.map=x}this.comment=e.comment,void 0!==e.forceAlphaBlending&&(this.forceAlphaBlending=e.forceAlphaBlending),void 0!==e.alphaMode&&(this.alphaMode=e.alphaMode),i||(this._mode=null!==(n=e.mode)&&void 0!==n?n:fl.Material)},t.prototype.loadFromSerialization=function(e,t,i){void 0===t&&(t=""),void 0===i&&(i=!1),this.parseSerializedObject(e,t,i)},t.prototype.clone=function(e,i){var r=this;void 0===i&&(i=!1);var n=this.serialize(),o=Ke.Clone((function(){return new t(e,r.getScene(),r.options)}),this);return o.id=e,o.name=e,o.parseSerializedObject(n),o._buildId=this._buildId,o.build(!1,!i),o},t.prototype.whenTexturesReadyAsync=function(){var e=[];return this.getActiveTextures().forEach((function(t){var i=t.getInternalTexture();i&&!i.isReady&&e.push(new Promise((function(e,t){i.onLoadedObservable.addOnce((function(){e()})),i.onErrorObservable.addOnce((function(e){t(e)}))})))})),Promise.all(e)},t.Parse=function(e,i,r,n){void 0===r&&(r=""),void 0===n&&(n=pt.GLSL);var o=Ke.Parse((function(){return new t(e.name,i,{shaderLanguage:n})}),e,i,r);return o.parseSerializedObject(e,r),o.build(),o},t.ParseFromFileAsync=function(e,i,r,n,o,a,s){return void 0===n&&(n=""),void 0===o&&(o=!1),y(this,void 0,void 0,(function(){var l,c,u;return b(this,(function(h){switch(h.label){case 0:return l=null!=a?a:new t(e,r),[4,r._loadFileAsync(i)];case 1:return c=h.sent(),u=JSON.parse(c),l.parseSerializedObject(u,n,void 0,s),o||l.build(),[2,l]}}))}))},t.ParseFromSnippetAsync=function(e,i,r,n,o,a,s){var l=this;return void 0===i&&(i=M.LastCreatedScene),void 0===r&&(r=""),void 0===o&&(o=!1),void 0===a&&(a=!1),"_BLANK"===e?Promise.resolve(t.CreateDefault("blank",i)):new Promise((function(c,u){var h=new Je;h.addEventListener("readystatechange",(function(){if(4==h.readyState)if(200==h.status){var l=JSON.parse(JSON.parse(h.responseText).jsonPayload),d=JSON.parse(l.nodeMaterial);n||((n=Ke.Parse((function(){return new t(e,i)}),d,i,r)).uniqueId=i.getUniqueId()),n.parseSerializedObject(d,void 0,void 0,s),n.snippetId=e;try{o||n.build()}catch(e){u(e)}a?n.whenTexturesReadyAsync().then((function(){c(n)})).catch((function(e){u(e)})):c(n)}else u("Unable to load the snippet "+e)})),h.open("GET",l.SnippetUrl+"/"+e.replace(/#/g,"/")),h.send()}))},t.CreateDefault=function(e,i){var r=new t(e,i);return r.setToDefault(),r.build(),r},t._BuildIdGenerator=0,t.EditorURL="".concat(rr._DefaultCdnUrl,"/v").concat(Mi.Version,"/nodeEditor/babylon.nodeEditor.js"),t.SnippetUrl=u.SnippetUrl,t.IgnoreTexturesAtLoadTime=!1,v([Ie()],t.prototype,"ignoreAlpha",void 0),v([Ie()],t.prototype,"maxSimultaneousLights",void 0),v([Ie("mode")],t.prototype,"_mode",void 0),v([Ie("comment")],t.prototype,"comment",void 0),v([Ie()],t.prototype,"forceAlphaBlending",void 0),t}(ws);function wl(e){var t,i=e.sideOrientation||_o.DEFAULTSIDE,r=e.radius||1,n=void 0===e.flat||e.flat,o=0|(e.subdivisions||4),a=e.radiusX||r,s=e.radiusY||r,l=e.radiusZ||r,c=(1+Math.sqrt(5))/2,u=[-1,c,-0,1,c,0,-1,-c,0,1,-c,0,0,-1,-c,0,1,-c,0,-1,c,0,1,c,c,0,1,c,0,-1,-c,0,1,-c,0,-1],h=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],d=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],p=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],f=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],_=[],m=[],g=[],v=[],y=0,b=new Array(3),T=new Array(3);for(t=0;t<3;t++)b[t]=V.Zero(),T[t]=U.Zero();for(var E=0;E<20;E++){for(t=0;t<3;t++){var S=h[3*E+t];b[t].copyFromFloats(u[3*d[S]],u[3*d[S]+1],u[3*d[S]+2]),b[t].normalize(),T[t].copyFromFloats(.134765625*p[2*S]+.05859375+-.0390625*f[E],.2333984375*p[2*S+1]+.025390625+.01953125*f[E])}for(var x=function(e,t,i,r){var c,u=V.Lerp(b[0],b[2],t/o),h=V.Lerp(b[1],b[2],t/o),d=o===t?b[2]:V.Lerp(u,h,e/(o-t));if(d.normalize(),n){var p=V.Lerp(b[0],b[2],r/o),f=V.Lerp(b[1],b[2],r/o);c=V.Lerp(p,f,i/(o-r))}else c=new V(d.x,d.y,d.z);c.x/=a,c.y/=s,c.z/=l,c.normalize();var E=U.Lerp(T[0],T[2],t/o),S=U.Lerp(T[1],T[2],t/o),x=o===t?T[2]:U.Lerp(E,S,e/(o-t));m.push(d.x*a,d.y*s,d.z*l),g.push(c.x,c.y,c.z),v.push(x.x,go.UseOpenGLOrientationForUV?1-x.y:x.y),_.push(y),y++},A=0;A<o;A++)for(var C=0;C+A<o;C++)x(C,A,C+1/3,A+1/3),x(C+1,A,C+1/3,A+1/3),x(C,A+1,C+1/3,A+1/3),C+A+1<o&&(x(C+1,A,C+2/3,A+2/3),x(C+1,A+1,C+2/3,A+2/3),x(C,A+1,C+2/3,A+2/3))}_o._ComputeSides(i,m,_,g,v,e.frontUVs,e.backUVs);var R=new _o;return R.indices=_,R.positions=m,R.normals=g,R.uvs=v,R}function Bl(e,t,i){void 0===t&&(t={}),void 0===i&&(i=null);var r=new Fa(e,i);return t.sideOrientation=Fa._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,wl(t).applyToMesh(r,t.updatable),r}a("BABYLON.NodeMaterial",Ll);var Ul,Vl,kl,Gl={CreateIcoSphere:Bl};_o.CreateIcoSphere=wl,Fa.CreateIcoSphere=function(e,t,i){return Bl(e,t,i)},function(e){e.WRIST="wrist",e.THUMB="thumb",e.INDEX="index",e.MIDDLE="middle",e.RING="ring",e.LITTLE="little"}(Vl||(Vl={})),function(e){e.WRIST="wrist",e.THUMB_METACARPAL="thumb-metacarpal",e.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",e.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",e.THUMB_TIP="thumb-tip",e.INDEX_FINGER_METACARPAL="index-finger-metacarpal",e.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",e.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",e.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",e.INDEX_FINGER_TIP="index-finger-tip",e.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",e.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",e.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",e.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",e.MIDDLE_FINGER_TIP="middle-finger-tip",e.RING_FINGER_METACARPAL="ring-finger-metacarpal",e.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",e.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",e.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",e.RING_FINGER_TIP="ring-finger-tip",e.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",e.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",e.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",e.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",e.PINKY_FINGER_TIP="pinky-finger-tip"}(kl||(kl={}));var zl,Wl,Hl,Xl=[kl.WRIST,kl.THUMB_METACARPAL,kl.THUMB_PHALANX_PROXIMAL,kl.THUMB_PHALANX_DISTAL,kl.THUMB_TIP,kl.INDEX_FINGER_METACARPAL,kl.INDEX_FINGER_PHALANX_PROXIMAL,kl.INDEX_FINGER_PHALANX_INTERMEDIATE,kl.INDEX_FINGER_PHALANX_DISTAL,kl.INDEX_FINGER_TIP,kl.MIDDLE_FINGER_METACARPAL,kl.MIDDLE_FINGER_PHALANX_PROXIMAL,kl.MIDDLE_FINGER_PHALANX_INTERMEDIATE,kl.MIDDLE_FINGER_PHALANX_DISTAL,kl.MIDDLE_FINGER_TIP,kl.RING_FINGER_METACARPAL,kl.RING_FINGER_PHALANX_PROXIMAL,kl.RING_FINGER_PHALANX_INTERMEDIATE,kl.RING_FINGER_PHALANX_DISTAL,kl.RING_FINGER_TIP,kl.PINKY_FINGER_METACARPAL,kl.PINKY_FINGER_PHALANX_PROXIMAL,kl.PINKY_FINGER_PHALANX_INTERMEDIATE,kl.PINKY_FINGER_PHALANX_DISTAL,kl.PINKY_FINGER_TIP],jl=((Ul={})[Vl.WRIST]=[kl.WRIST],Ul[Vl.THUMB]=[kl.THUMB_METACARPAL,kl.THUMB_PHALANX_PROXIMAL,kl.THUMB_PHALANX_DISTAL,kl.THUMB_TIP],Ul[Vl.INDEX]=[kl.INDEX_FINGER_METACARPAL,kl.INDEX_FINGER_PHALANX_PROXIMAL,kl.INDEX_FINGER_PHALANX_INTERMEDIATE,kl.INDEX_FINGER_PHALANX_DISTAL,kl.INDEX_FINGER_TIP],Ul[Vl.MIDDLE]=[kl.MIDDLE_FINGER_METACARPAL,kl.MIDDLE_FINGER_PHALANX_PROXIMAL,kl.MIDDLE_FINGER_PHALANX_INTERMEDIATE,kl.MIDDLE_FINGER_PHALANX_DISTAL,kl.MIDDLE_FINGER_TIP],Ul[Vl.RING]=[kl.RING_FINGER_METACARPAL,kl.RING_FINGER_PHALANX_PROXIMAL,kl.RING_FINGER_PHALANX_INTERMEDIATE,kl.RING_FINGER_PHALANX_DISTAL,kl.RING_FINGER_TIP],Ul[Vl.LITTLE]=[kl.PINKY_FINGER_METACARPAL,kl.PINKY_FINGER_PHALANX_PROXIMAL,kl.PINKY_FINGER_PHALANX_INTERMEDIATE,kl.PINKY_FINGER_PHALANX_DISTAL,kl.PINKY_FINGER_TIP],Ul),Yl=function(){function e(e,t,i,r,n,o,a){void 0===n&&(n=!1),void 0===o&&(o=!1),void 0===a&&(a=1),this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=r,this._leftHandedMeshes=n,this._jointsInvisible=o,this._jointScaleFactor=a,this.onHandMeshSetObservable=new f,this._jointTransforms=new Array(Xl.length),this._jointTransformMatrices=new Float32Array(16*Xl.length),this._tempJointMatrix=new z,this._jointRadii=new Float32Array(Xl.length),this._scene=t[0].getScene();for(var s=0;s<this._jointTransforms.length;s++)(this._jointTransforms[s]=new Fo(Xl[s],this._scene)).rotationQuaternion=new G,t[s].rotationQuaternion=new G;i&&this.setHandMesh(i,r),this.xrController.motionController&&this.xrController.motionController.rootMesh&&this.xrController.motionController.rootMesh.dispose(!1,!0),this.xrController.onMotionControllerInitObservable.add((function(e){e._doNotLoadControllerMesh=!0}))}return Object.defineProperty(e.prototype,"handMesh",{get:function(){return this._handMesh},enumerable:!1,configurable:!0}),e.prototype.getHandPartMeshes=function(e){var t=this;return jl[e].map((function(e){return t._jointMeshes[Xl.indexOf(e)]}))},e.prototype.getJointMesh=function(e){return this._jointMeshes[Xl.indexOf(e)]},e.prototype.setHandMesh=function(e,t,i){var r=this;if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach((function(e){e.alwaysSelectAsActiveMesh=!0})),this._handMesh.skeleton){var n=this._handMesh.skeleton;Xl.forEach((function(e,i){var o=n.getBoneIndexByName(t?t[e]:e);-1!==o&&n.bones[o].linkTransformNode(r._jointTransforms[i])}))}this.onHandMeshSetObservable.notifyObservers(this)},e.prototype.updateFromXRFrame=function(e,t){var i=this,r=this.xrController.inputSource.hand;if(r){var n=r,o=Xl.map((function(e){return n[e]||r.get(e)})),a=!1;if(e.fillPoses&&e.fillJointRadii)a=e.fillPoses(o,t,this._jointTransformMatrices)&&e.fillJointRadii(o,this._jointRadii);else if(e.getJointPose){a=!0;for(var s=0;s<o.length;s++){var l=e.getJointPose(o[s],t);if(!l){a=!1;break}this._jointTransformMatrices.set(l.transform.matrix,16*s),this._jointRadii[s]=l.radius||.008}}a&&(Xl.forEach((function(e,t){var r=i._jointTransforms[t];z.FromArrayToRef(i._jointTransformMatrices,16*t,i._tempJointMatrix),i._tempJointMatrix.decompose(void 0,r.rotationQuaternion,r.position);var n=i._jointRadii[t]*i._jointScaleFactor,o=i._jointMeshes[t];o.isVisible=!i._handMesh&&!i._jointsInvisible,o.position.copyFrom(r.position),o.rotationQuaternion.copyFrom(r.rotationQuaternion),o.scaling.setAll(n),i._scene.useRightHandedSystem||(o.position.z*=-1,o.rotationQuaternion.z*=-1,o.rotationQuaternion.w*=-1,i._leftHandedMeshes&&i._handMesh&&(r.position.z*=-1,r.rotationQuaternion.z*=-1,r.rotationQuaternion.w*=-1))})),this._handMesh&&(this._handMesh.isVisible=!0))}},e.prototype.dispose=function(e){var t;void 0===e&&(e=!1),this._handMesh&&(e?(null===(t=this._handMesh.skeleton)||void 0===t||t.dispose(),this._handMesh.dispose(!1,!0)):this._handMesh.isVisible=!1)},e}(),Kl=function(e){function t(t,i){var r=e.call(this,t)||this;r.options=i,r._attachedHands={},r._trackingHands={left:null,right:null},r._handResources={jointMeshes:null,handMeshes:null,rigMappings:null},r._worldScaleObserver=null,r.onHandAddedObservable=new f,r.onHandRemovedObservable=new f,r._attachHand=function(e){var t,i,n;if(e.inputSource.hand&&"none"!=e.inputSource.handedness&&r._handResources.jointMeshes){var o=e.inputSource.handedness,a=new Yl(e,r._handResources.jointMeshes[o],r._handResources.handMeshes&&r._handResources.handMeshes[o],r._handResources.rigMappings&&r._handResources.rigMappings[o],null===(t=r.options.handMeshes)||void 0===t?void 0:t.meshesUseLeftHandedCoordinates,null===(i=r.options.jointMeshes)||void 0===i?void 0:i.invisible,null===(n=r.options.jointMeshes)||void 0===n?void 0:n.scaleFactor);r._attachedHands[e.uniqueId]=a,r._trackingHands[o]=a,r.onHandAddedObservable.notifyObservers(a)}},r._detachHand=function(e){r._detachHandById(e.uniqueId)},r.xrNativeFeatureName="hand-tracking";var n=i.jointMeshes;if(n&&(void 0!==n.disableDefaultHandMesh&&(i.handMeshes=i.handMeshes||{},i.handMeshes.disableDefaultMeshes=n.disableDefaultHandMesh),void 0!==n.handMeshes&&(i.handMeshes=i.handMeshes||{},i.handMeshes.customMeshes=n.handMeshes),void 0!==n.leftHandedSystemMeshes&&(i.handMeshes=i.handMeshes||{},i.handMeshes.meshesUseLeftHandedCoordinates=n.leftHandedSystemMeshes),void 0!==n.rigMapping)){i.handMeshes=i.handMeshes||{};var o={},a={};[[n.rigMapping.left,o],[n.rigMapping.right,a]].forEach((function(e){var t=e[0],i=e[1];t.forEach((function(e,t){i[Xl[t]]=e}))})),i.handMeshes.customRigMappings={left:o,right:a}}return r}return m(t,e),t._GenerateTrackedJointMeshes=function(e){var i={};return["left","right"].map((function(r){var n,o,a,s,l,c=[],u=(null===(n=e.jointMeshes)||void 0===n?void 0:n.sourceMesh)||Bl("jointParent",t._ICOSPHERE_PARAMS);u.isVisible=!!(null===(o=e.jointMeshes)||void 0===o?void 0:o.keepOriginalVisible);for(var h=0;h<Xl.length;++h){var d=u.createInstance("".concat(r,"-handJoint-").concat(h));if(null===(a=e.jointMeshes)||void 0===a?void 0:a.onHandJointMeshGenerated){var p=e.jointMeshes.onHandJointMeshGenerated(d,h,r);p&&p!==d&&(d.dispose(),d=p)}if(d.isPickable=!1,null===(s=e.jointMeshes)||void 0===s?void 0:s.enablePhysics){var f=(null===(l=e.jointMeshes)||void 0===l?void 0:l.physicsProps)||{};d.scaling.setAll(.02);var _=void 0!==f.impostorType?f.impostorType:Ds.SphereImpostor;d.physicsImpostor=new Ds(d,_,g({mass:0},f))}d.rotationQuaternion=new G,d.isVisible=!1,c.push(d)}i[r]=c})),{left:i.left,right:i.right}},t._GenerateDefaultHandMeshesAsync=function(e,i,r){var n=this;return new Promise((function(o){return y(n,void 0,void 0,(function(){var n,a,s,l,c,h,d,p,f,_,m,v,y;return b(this,(function(b){switch(b.label){case 0:return n={},(null===(f=null===(p=t._RightHandGLB)||void 0===p?void 0:p.meshes[1])||void 0===f?void 0:f.isDisposed())&&(t._RightHandGLB=null),(null===(m=null===(_=t._LeftHandGLB)||void 0===_?void 0:_.meshes[1])||void 0===m?void 0:m.isDisposed())&&(t._LeftHandGLB=null),a=!(!t._RightHandGLB||!t._LeftHandGLB),[4,Promise.all([t._RightHandGLB||Ls.ImportMeshAsync("",t.DEFAULT_HAND_MODEL_BASE_URL,t.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),t._LeftHandGLB||Ls.ImportMeshAsync("",t.DEFAULT_HAND_MODEL_BASE_URL,t.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)])];case 1:return s=b.sent(),t._RightHandGLB=s[0],t._LeftHandGLB=s[1],[4,Ll.ParseFromFileAsync("handShader",t.DEFAULT_HAND_MODEL_SHADER_URL,e)];case 2:return(l=b.sent()).needDepthPrePass=!0,l.transparencyMode=Ca.MATERIAL_ALPHABLEND,l.alphaMode=u.ALPHA_COMBINE,l.build(!1),c=g({base:Z.FromInts(116,63,203),fresnel:Z.FromInts(149,102,229),fingerColor:Z.FromInts(177,130,255),tipFresnel:Z.FromInts(220,200,255)},null===(v=null==r?void 0:r.handMeshes)||void 0===v?void 0:v.customColors),(h={base:l.getBlockByName("baseColor"),fresnel:l.getBlockByName("fresnelColor"),fingerColor:l.getBlockByName("fingerColor"),tipFresnel:l.getBlockByName("tipFresnelColor")}).base.value=c.base,h.fresnel.value=c.fresnel,h.fingerColor.value=c.fingerColor,h.tipFresnel.value=c.tipFresnel,d=null===(y=i._getBaseLayerWrapper())||void 0===y?void 0:y.isMultiview,["left","right"].forEach((function(i){var r="left"==i?t._LeftHandGLB:t._RightHandGLB;if(!r)throw new Error("Could not load hand model");var o=r.meshes[1];o._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,d||(o.material=l.clone("".concat(i,"HandShaderClone"),!0)),o.isVisible=!1,n[i]=o,a||e.useRightHandedSystem||r.meshes[1].rotate(_n.Y,Math.PI)})),l.dispose(),o({left:n.left,right:n.right}),[2]}}))}))}))},t._GenerateDefaultHandMeshRigMapping=function(e){var t,i="right"==e?"R":"L";return(t={})[kl.WRIST]="wrist_".concat(i),t[kl.THUMB_METACARPAL]="thumb_metacarpal_".concat(i),t[kl.THUMB_PHALANX_PROXIMAL]="thumb_proxPhalanx_".concat(i),t[kl.THUMB_PHALANX_DISTAL]="thumb_distPhalanx_".concat(i),t[kl.THUMB_TIP]="thumb_tip_".concat(i),t[kl.INDEX_FINGER_METACARPAL]="index_metacarpal_".concat(i),t[kl.INDEX_FINGER_PHALANX_PROXIMAL]="index_proxPhalanx_".concat(i),t[kl.INDEX_FINGER_PHALANX_INTERMEDIATE]="index_intPhalanx_".concat(i),t[kl.INDEX_FINGER_PHALANX_DISTAL]="index_distPhalanx_".concat(i),t[kl.INDEX_FINGER_TIP]="index_tip_".concat(i),t[kl.MIDDLE_FINGER_METACARPAL]="middle_metacarpal_".concat(i),t[kl.MIDDLE_FINGER_PHALANX_PROXIMAL]="middle_proxPhalanx_".concat(i),t[kl.MIDDLE_FINGER_PHALANX_INTERMEDIATE]="middle_intPhalanx_".concat(i),t[kl.MIDDLE_FINGER_PHALANX_DISTAL]="middle_distPhalanx_".concat(i),t[kl.MIDDLE_FINGER_TIP]="middle_tip_".concat(i),t[kl.RING_FINGER_METACARPAL]="ring_metacarpal_".concat(i),t[kl.RING_FINGER_PHALANX_PROXIMAL]="ring_proxPhalanx_".concat(i),t[kl.RING_FINGER_PHALANX_INTERMEDIATE]="ring_intPhalanx_".concat(i),t[kl.RING_FINGER_PHALANX_DISTAL]="ring_distPhalanx_".concat(i),t[kl.RING_FINGER_TIP]="ring_tip_".concat(i),t[kl.PINKY_FINGER_METACARPAL]="little_metacarpal_".concat(i),t[kl.PINKY_FINGER_PHALANX_PROXIMAL]="little_proxPhalanx_".concat(i),t[kl.PINKY_FINGER_PHALANX_INTERMEDIATE]="little_intPhalanx_".concat(i),t[kl.PINKY_FINGER_PHALANX_DISTAL]="little_distPhalanx_".concat(i),t[kl.PINKY_FINGER_TIP]="little_tip_".concat(i),t},t.prototype.isCompatible=function(){return"undefined"!=typeof XRHand},t.prototype.getHandByControllerId=function(e){return this._attachedHands[e]},t.prototype.getHandByHandedness=function(e){return"none"==e?null:this._trackingHands[e]},t.prototype.attach=function(){var i,r,n,o,a=this;return!!e.prototype.attach.call(this)&&(this._handResources={jointMeshes:t._GenerateTrackedJointMeshes(this.options),handMeshes:(null===(i=this.options.handMeshes)||void 0===i?void 0:i.customMeshes)||null,rigMappings:(null===(r=this.options.handMeshes)||void 0===r?void 0:r.customRigMappings)||null},(null===(n=this.options.handMeshes)||void 0===n?void 0:n.customMeshes)||(null===(o=this.options.handMeshes)||void 0===o?void 0:o.disableDefaultMeshes)||(t._GenerateDefaultHandMeshesAsync(M.LastCreatedScene,this._xrSessionManager,this.options).then((function(e){var i,r;a._handResources.handMeshes=e,a._handResources.rigMappings={left:t._GenerateDefaultHandMeshRigMapping("left"),right:t._GenerateDefaultHandMeshRigMapping("right")},null===(i=a._trackingHands.left)||void 0===i||i.setHandMesh(a._handResources.handMeshes.left,a._handResources.rigMappings.left,a._xrSessionManager),null===(r=a._trackingHands.right)||void 0===r||r.setHandMesh(a._handResources.handMeshes.right,a._handResources.rigMappings.right,a._xrSessionManager),a._handResources.handMeshes.left.scaling.setAll(a._xrSessionManager.worldScalingFactor),a._handResources.handMeshes.right.scaling.setAll(a._xrSessionManager.worldScalingFactor)})),this._worldScaleObserver=this._xrSessionManager.onWorldScaleFactorChangedObservable.add((function(e){a._handResources.handMeshes&&(a._handResources.handMeshes.left.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor),a._handResources.handMeshes.right.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor))}))),this.options.xrInput.controllers.forEach(this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable,this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable,this._detachHand),!0)},t.prototype._onXRFrame=function(e){var t,i;null===(t=this._trackingHands.left)||void 0===t||t.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),null===(i=this._trackingHands.right)||void 0===i||i.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)},t.prototype._detachHandById=function(e,t){var i,r=this.getHandByControllerId(e);if(r){var n="left"==r.xrController.inputSource.handedness?"left":"right";(null===(i=this._trackingHands[n])||void 0===i?void 0:i.xrController.uniqueId)===e&&(this._trackingHands[n]=null),this.onHandRemovedObservable.notifyObservers(r),r.dispose(t),delete this._attachedHands[e]}},t.prototype.detach=function(){var t,i=this;return!!e.prototype.detach.call(this)&&(Object.keys(this._attachedHands).forEach((function(e){var t;return i._detachHandById(e,null===(t=i.options.handMeshes)||void 0===t?void 0:t.disposeOnSessionEnd)})),(null===(t=this.options.handMeshes)||void 0===t?void 0:t.disposeOnSessionEnd)&&this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach((function(e){return e.dispose()})),this._handResources.jointMeshes.right.forEach((function(e){return e.dispose()}))),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver),!0)},t.prototype.dispose=function(){var i;e.prototype.dispose.call(this),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),this._handResources.handMeshes&&!(null===(i=this.options.handMeshes)||void 0===i?void 0:i.customMeshes)&&(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),t._RightHandGLB=null,t._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach((function(e){return e.dispose()})),this._handResources.jointMeshes.right.forEach((function(e){return e.dispose()})))},t.Name=Ss.HAND_TRACKING,t.Version=1,t.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/",t.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb",t.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb",t.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json",t._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2},t._RightHandGLB=null,t._LeftHandGLB=null,t}(As);xs.AddWebXRFeature(Kl.Name,(function(e,t){return function(){return new Kl(e,t)}}),Kl.Version,!1),function(e){e[e.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",e[e.RADIAL_SIDE=1]="RADIAL_SIDE",e[e.ULNAR_SIDE=2]="ULNAR_SIDE",e[e.BELOW_WRIST=3]="BELOW_WRIST"}(zl||(zl={})),function(e){e[e.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",e[e.HAND_ROTATION=1]="HAND_ROTATION"}(Wl||(Wl={})),function(e){e[e.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",e[e.PALM_UP=1]="PALM_UP",e[e.GAZE_FOCUS=2]="GAZE_FOCUS",e[e.PALM_AND_GAZE=3]="PALM_AND_GAZE"}(Hl||(Hl={}));var Ql,ql=function(){function e(){this._sceneRenderObserver=null,this._zoneAxis={},this.handConstraintVisibility=Hl.PALM_AND_GAZE,this.palmUpStrictness=.95,this.gazeProximityRadius=.15,this.targetOffset=.1,this.targetZone=zl.ULNAR_SIDE,this.zoneOrientationMode=Wl.HAND_ROTATION,this.nodeOrientationMode=Wl.HAND_ROTATION,this.handedness="none",this.lerpTime=100,this._zoneAxis[zl.ABOVE_FINGER_TIPS]=new V(0,1,0),this._zoneAxis[zl.RADIAL_SIDE]=new V(-1,0,0),this._zoneAxis[zl.ULNAR_SIDE]=new V(1,0,0),this._zoneAxis[zl.BELOW_WRIST]=new V(0,-1,0)}return Object.defineProperty(e.prototype,"name",{get:function(){return"HandConstraint"},enumerable:!1,configurable:!0}),e.prototype.enable=function(){this._node.setEnabled(!0)},e.prototype.disable=function(){this._node.setEnabled(!1)},e.prototype._getHandPose=function(){if(!this._handTracking)return null;var e;if(e="none"===this.handedness?this._handTracking.getHandByHandedness("left")||this._handTracking.getHandByHandedness("right"):this._handTracking.getHandByHandedness(this.handedness)){var t=e.getJointMesh(kl.PINKY_FINGER_METACARPAL),i=e.getJointMesh(kl.MIDDLE_FINGER_METACARPAL),r=e.getJointMesh(kl.WRIST);if(r&&i&&t){var n={position:i.absolutePosition,quaternion:new G,id:e.xrController.uniqueId},o=H.Vector3[0],a=H.Vector3[1],s=H.Vector3[2];return o.copyFrom(i.absolutePosition).subtractInPlace(r.absolutePosition).normalize(),a.copyFrom(t.absolutePosition).subtractInPlace(i.absolutePosition).normalize(),V.CrossToRef(o,a,a),V.CrossToRef(a,o,s),G.FromLookDirectionLHToRef(a,o,n.quaternion),n}}return null},e.prototype.init=function(){},e.prototype.attach=function(e){var t=this;this._node=e,this._scene=e.getScene(),this._node.rotationQuaternion||(this._node.rotationQuaternion=G.RotationYawPitchRoll(this._node.rotation.y,this._node.rotation.x,this._node.rotation.z));var i=Date.now();this._sceneRenderObserver=this._scene.onBeforeRenderObservable.add((function(){var e=t._getHandPose();if(t._node.reservedDataStore=t._node.reservedDataStore||{},t._node.reservedDataStore.nearInteraction=t._node.reservedDataStore.nearInteraction||{},t._node.reservedDataStore.nearInteraction.excludedControllerId=null,e){var r=H.Vector3[0],n=t._scene.activeCamera;r.copyFrom(t._zoneAxis[t.targetZone]);var o=H.Quaternion[0];if(n&&(t.zoneOrientationMode===Wl.LOOK_AT_CAMERA||t.nodeOrientationMode===Wl.LOOK_AT_CAMERA)){var a=H.Vector3[1];a.copyFrom(n.position).subtractInPlace(e.position).normalize(),t._scene.useRightHandedSystem?G.FromLookDirectionRHToRef(a,V.UpReadOnly,o):G.FromLookDirectionLHToRef(a,V.UpReadOnly,o)}t.zoneOrientationMode===Wl.HAND_ROTATION?e.quaternion.toRotationMatrix(H.Matrix[0]):o.toRotationMatrix(H.Matrix[0]),V.TransformNormalToRef(r,H.Matrix[0],r),r.scaleInPlace(t.targetOffset);var s=H.Vector3[2],l=H.Quaternion[1];s.copyFrom(e.position).addInPlace(r),t.nodeOrientationMode===Wl.HAND_ROTATION?l.copyFrom(e.quaternion):l.copyFrom(o);var c=Date.now()-i;V.SmoothToRef(t._node.position,s,c,t.lerpTime,t._node.position),G.SmoothToRef(t._node.rotationQuaternion,l,c,t.lerpTime,t._node.rotationQuaternion),t._node.reservedDataStore.nearInteraction.excludedControllerId=e.id}t._setVisibility(e),i=Date.now()}))},e.prototype._setVisibility=function(e){var t=!0,i=!0,r=this._scene.activeCamera;if(r){var n=r.getForwardRay();if(this.handConstraintVisibility===Hl.GAZE_FOCUS||this.handConstraintVisibility===Hl.PALM_AND_GAZE){i=!1;var o=void 0;this._eyeTracking&&(o=this._eyeTracking.getEyeGaze()),o=o||n;var a=H.Vector3[0];e?e.position.subtractToRef(o.origin,a):this._node.getAbsolutePosition().subtractToRef(o.origin,a);var s=V.Dot(a,o.direction),l=s*s;s>0&&a.lengthSquared()-l<this.gazeProximityRadius*this.gazeProximityRadius&&(i=!0)}if((this.handConstraintVisibility===Hl.PALM_UP||this.handConstraintVisibility===Hl.PALM_AND_GAZE)&&(t=!1,e)){var c=H.Vector3[0];V.LeftHandedForwardReadOnly.rotateByQuaternionToRef(e.quaternion,c),V.Dot(c,n.direction)>2*this.palmUpStrictness-1&&(t=!0)}}this._node.setEnabled(t&&i)},e.prototype.detach=function(){this._scene.onBeforeRenderObservable.remove(this._sceneRenderObserver)},e.prototype.linkToXRExperience=function(e){var t=e.featuresManager?e.featuresManager:e;if(t){try{this._eyeTracking=t.getEnabledFeature(Ss.EYE_TRACKING)}catch(e){}try{this._handTracking=t.getEnabledFeature(Ss.HAND_TRACKING)}catch(e){rr.Error("Hand tracking must be enabled for the Hand Menu to work")}}else rr.Error("XR features manager must be available or provided directly for the Hand Menu to work")},e}(),Zl=function(){function e(e,t,i){this.targetPosition=V.Zero(),this.poleTargetPosition=V.Zero(),this.poleTargetLocalOffset=V.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=G.Identity(),this._bone1Mat=z.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=V.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;var r=t.getParent();if(!r)return this._notEnoughInformation=!0,void ae.Error("BoneIKController: bone must have a parent for IK to work.");if(this._bone1=r,0===this._bone2.children.length&&!this._bone2.length)return this._notEnoughInformation=!0,void ae.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");this.mesh=e,t.getSkeleton().computeAbsoluteMatrices();var n=t.getPosition();if(t.getAbsoluteMatrix().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,n.x>n.y&&n.x>n.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length&&this._bone2.length){var o=this._bone1.getScale(),a=this._bone2.getScale();this._bone1Length=this._bone1.length*o.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*a.y*this.mesh.scaling.y}else if(this._bone2.children[0]){e.computeWorldMatrix(!0);var s=this._bone2.children[0].getAbsolutePosition(e),l=this._bone2.getAbsolutePosition(e),c=this._bone1.getAbsolutePosition(e);this._bone2Length=V.Distance(s,l),this._bone1Length=V.Distance(l,c)}else e.computeWorldMatrix(!0),a=this._bone2.getScale(),this._bone2Length=this._bone2.length*a.y*this.mesh.scaling.y,l=this._bone2.getAbsolutePosition(e),c=this._bone1.getAbsolutePosition(e),this._bone1Length=V.Distance(l,c);this._bone1.getRotationMatrixToRef(dn.WORLD,e,this._bone1Mat),this.maxAngle=Math.PI,i&&(i.targetMesh&&(this.targetMesh=i.targetMesh,this.targetMesh.computeWorldMatrix(!0)),i.poleTargetMesh?(this.poleTargetMesh=i.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):i.poleTargetBone?this.poleTargetBone=i.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),i.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(i.poleTargetLocalOffset),i.poleAngle&&(this.poleAngle=i.poleAngle),i.bendAxis&&this._bendAxis.copyFrom(i.bendAxis),i.maxAngle&&(this.maxAngle=i.maxAngle),i.slerpAmount&&(this.slerpAmount=i.slerpAmount))}return Object.defineProperty(e.prototype,"maxAngle",{get:function(){return this._maxAngle},set:function(e){this._setMaxAngle(e)},enumerable:!1,configurable:!0}),e.prototype._setMaxAngle=function(e){e<0&&(e=0),(e>Math.PI||null==e)&&(e=Math.PI),this._maxAngle=e;var t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))},e.prototype.update=function(){if(!this._notEnoughInformation){var t=this.targetPosition,i=this.poleTargetPosition,r=e._TmpMats[0],n=e._TmpMats[1];this.targetMesh&&t.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,i):this.poleTargetMesh&&V.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),i);var o=e._TmpVecs[0],a=e._TmpVecs[1],s=e._TmpVecs[2],l=e._TmpVecs[3],c=e._TmpVecs[4],u=e._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,o),i.subtractToRef(o,c),0==c.x&&0==c.y&&0==c.z?c.y=1:c.normalize(),t.subtractToRef(o,l),l.normalize(),V.CrossToRef(l,c,a),a.normalize(),V.CrossToRef(l,a,s),s.normalize(),z.FromXYZAxesToRef(s,l,a,r);var h=this._bone1Length,d=this._bone2Length,p=V.Distance(o,t);this._maxReach>0&&(p=Math.min(this._maxReach,p));var f=(d*d+p*p-h*h)/(2*d*p),_=(p*p+h*h-d*d)/(2*p*h);f>1&&(f=1),_>1&&(_=1),f<-1&&(f=-1),_<-1&&(_=-1);var m=Math.acos(f),g=Math.acos(_),v=-m-g;if(this._rightHandedSystem)z.RotationYawPitchRollToRef(0,0,this._adjustRoll,n),n.multiplyToRef(r,r),z.RotationAxisToRef(this._bendAxis,g,n),n.multiplyToRef(r,r);else{var y=e._TmpVecs[5];y.copyFrom(this._bendAxis),y.x*=-1,z.RotationAxisToRef(y,-g,n),n.multiplyToRef(r,r)}this.poleAngle&&(z.RotationAxisToRef(l,this.poleAngle,n),r.multiplyToRef(n,r)),this._bone1&&(this.slerpAmount<1?(this._slerping||G.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),G.FromRotationMatrixToRef(r,u),G.SlerpToRef(this._bone1Quat,u,this.slerpAmount,this._bone1Quat),v=this._bone2Ang*(1-this.slerpAmount)+v*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,dn.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(r,dn.WORLD,this.mesh),this._bone1Mat.copyFrom(r),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,v,dn.LOCAL),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=v}},e.prototype._updateLinkedTransformRotation=function(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new G),e.getRotationQuaternionToRef(dn.LOCAL,null,e._linkedTransformNode.rotationQuaternion))},e._TmpVecs=[V.Zero(),V.Zero(),V.Zero(),V.Zero(),V.Zero(),V.Zero()],e._TmpQuat=G.Identity(),e._TmpMats=[z.Identity(),z.Identity()],e}(),Jl=function(){function e(e,t,i,r){if(this.upAxis=V.Up(),this.upAxisSpace=dn.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=G.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=V.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,r){if(r.adjustYaw&&(this.adjustYaw=r.adjustYaw),r.adjustPitch&&(this.adjustPitch=r.adjustPitch),r.adjustRoll&&(this.adjustRoll=r.adjustRoll),null!=r.maxYaw?this.maxYaw=r.maxYaw:this.maxYaw=Math.PI,null!=r.minYaw?this.minYaw=r.minYaw:this.minYaw=-Math.PI,null!=r.maxPitch?this.maxPitch=r.maxPitch:this.maxPitch=Math.PI,null!=r.minPitch?this.minPitch=r.minPitch:this.minPitch=-Math.PI,null!=r.slerpAmount&&(this.slerpAmount=r.slerpAmount),null!=r.upAxis&&(this.upAxis=r.upAxis),null!=r.upAxisSpace&&(this.upAxisSpace=r.upAxisSpace),null!=r.yawAxis||null!=r.pitchAxis){var n=_n.Y,o=_n.X;null!=r.yawAxis&&(n=r.yawAxis.clone()).normalize(),null!=r.pitchAxis&&(o=r.pitchAxis.clone()).normalize();var a=V.Cross(o,n);this._transformYawPitch=z.Identity(),z.FromXYZAxesToRef(o,n,a,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}void 0!==r.useAbsoluteValueForYaw&&(this.useAbsoluteValueForYaw=r.useAbsoluteValueForYaw)}t.getParent()||this.upAxisSpace!=dn.BONE||(this.upAxisSpace=dn.LOCAL)}return Object.defineProperty(e.prototype,"minYaw",{get:function(){return this._minYaw},set:function(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxYaw",{get:function(){return this._maxYaw},set:function(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"minPitch",{get:function(){return this._minPitch},set:function(e){this._minPitch=e,this._minPitchTan=Math.tan(e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxPitch",{get:function(){return this._maxPitch},set:function(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)},enumerable:!1,configurable:!0}),e.prototype.update=function(){if(this.slerpAmount<1&&!this._firstFrameSkipped)this._firstFrameSkipped=!0;else{var t=this.bone,i=e._TmpVecs[0];t.getAbsolutePositionToRef(this.mesh,i);var r=this.target,n=e._TmpMats[0],o=e._TmpMats[1],a=this.mesh,s=t.getParent(),l=e._TmpVecs[1];l.copyFrom(this.upAxis),this.upAxisSpace==dn.BONE&&s?(this._transformYawPitch&&V.TransformCoordinatesToRef(l,this._transformYawPitchInv,l),s.getDirectionToRef(l,this.mesh,l)):this.upAxisSpace==dn.LOCAL&&(a.getDirectionToRef(l,l),1==a.scaling.x&&1==a.scaling.y&&1==a.scaling.z||l.normalize());var c=!1,u=!1;if(this._maxYaw==Math.PI&&this._minYaw==-Math.PI||(c=!0),this._maxPitch==Math.PI&&this._minPitch==-Math.PI||(u=!0),c||u){var h=e._TmpMats[2],d=e._TmpMats[3];if(this.upAxisSpace==dn.BONE&&1==l.y&&s)s.getRotationMatrixToRef(dn.WORLD,this.mesh,h);else if(this.upAxisSpace!=dn.LOCAL||1!=l.y||s){var p=e._TmpVecs[2];p.copyFrom(this._fowardAxis),this._transformYawPitch&&V.TransformCoordinatesToRef(p,this._transformYawPitchInv,p),s?s.getDirectionToRef(p,this.mesh,p):a.getDirectionToRef(p,p);var f=V.Cross(l,p);f.normalize(),p=V.Cross(f,l),z.FromXYZAxesToRef(f,l,p,h)}else h.copyFrom(a.getWorldMatrix());h.invertToRef(d);var _=null;if(u){var m=e._TmpVecs[3];r.subtractToRef(i,m),V.TransformCoordinatesToRef(m,d,m),_=Math.sqrt(m.x*m.x+m.z*m.z);var g=Math.atan2(m.y,_),v=g;g>this._maxPitch?(m.y=this._maxPitchTan*_,v=this._maxPitch):g<this._minPitch&&(m.y=this._minPitchTan*_,v=this._minPitch),g!=v&&(V.TransformCoordinatesToRef(m,h,m),m.addInPlace(i),r=m)}if(c){m=e._TmpVecs[4],r.subtractToRef(i,m),V.TransformCoordinatesToRef(m,d,m);var y=Math.atan2(m.x,m.z),b=this.useAbsoluteValueForYaw?Math.abs(y):y,T=y;if((b>this._maxYaw||b<this._minYaw)&&(null==_&&(_=Math.sqrt(m.x*m.x+m.z*m.z)),this._yawRange>Math.PI?this._isAngleBetween(y,this._maxYaw,this._midYawConstraint)?(m.z=this._maxYawCos*_,m.x=this._maxYawSin*_,T=this._maxYaw):this._isAngleBetween(y,this._midYawConstraint,this._minYaw)&&(m.z=this._minYawCos*_,m.x=this._minYawSin*_,T=this._minYaw):b>this._maxYaw?(m.z=this._maxYawCos*_,m.x=this._maxYawSin*_,y<0&&this.useAbsoluteValueForYaw&&(m.x*=-1),T=this._maxYaw):b<this._minYaw&&(m.z=this._minYawCos*_,m.x=this._minYawSin*_,y<0&&this.useAbsoluteValueForYaw&&(m.x*=-1),T=this._minYaw)),this._slerping&&this._yawRange>Math.PI){var E=e._TmpVecs[8];E.copyFrom(_n.Z),this._transformYawPitch&&V.TransformCoordinatesToRef(E,this._transformYawPitchInv,E);var S=e._TmpMats[4];this._boneQuat.toRotationMatrix(S),this.mesh.getWorldMatrix().multiplyToRef(S,S),V.TransformCoordinatesToRef(E,S,E),V.TransformCoordinatesToRef(E,d,E);var x=Math.atan2(E.x,E.z);if(this._getAngleBetween(x,y)>this._getAngleBetween(x,this._midYawConstraint)){null==_&&(_=Math.sqrt(m.x*m.x+m.z*m.z));var A=this._getAngleBetween(x,this._maxYaw);this._getAngleBetween(x,this._minYaw)<A?(T=x+.75*Math.PI,m.z=Math.cos(T)*_,m.x=Math.sin(T)*_):(T=x-.75*Math.PI,m.z=Math.cos(T)*_,m.x=Math.sin(T)*_)}}y!=T&&(V.TransformCoordinatesToRef(m,h,m),m.addInPlace(i),r=m)}}var C=e._TmpVecs[5],R=e._TmpVecs[6],P=e._TmpVecs[7],I=e._TmpQuat,M=e._TmpVecs[9];r.subtractToRef(i,C),C.normalize(),V.CrossToRef(l,C,R),R.normalize(),V.CrossToRef(C,R,P),P.normalize(),z.FromXYZAxesToRef(R,P,C,n),0===R.x&&0===R.y&&0===R.z||0===P.x&&0===P.y&&0===P.z||0===C.x&&0===C.y&&0===C.z||((this.adjustYaw||this.adjustPitch||this.adjustRoll)&&(z.RotationYawPitchRollToRef(this.adjustYaw,this.adjustPitch,this.adjustRoll,o),o.multiplyToRef(n,n)),M.copyFrom(this.bone.getScale()),this.slerpAmount<1?(this._slerping||this.bone.getRotationQuaternionToRef(dn.WORLD,this.mesh,this._boneQuat),this._transformYawPitch&&this._transformYawPitch.multiplyToRef(n,n),G.FromRotationMatrixToRef(n,I),G.SlerpToRef(this._boneQuat,I,this.slerpAmount,this._boneQuat),this.bone.setRotationQuaternion(this._boneQuat,dn.WORLD,this.mesh),this._slerping=!0):(this._transformYawPitch&&this._transformYawPitch.multiplyToRef(n,n),this.bone.setRotationMatrix(n,dn.WORLD,this.mesh),this._slerping=!1),this.bone.setScale(M),this._updateLinkedTransformRotation())}},e.prototype._getAngleDiff=function(e,t){var i=t-e;return(i%=2*Math.PI)>Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i},e.prototype._getAngleBetween=function(e,t){var i=0;return(i=(e=(e%=2*Math.PI)<0?e+2*Math.PI:e)<(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)?t-e:e-t)>Math.PI&&(i=2*Math.PI-i),i},e.prototype._isAngleBetween=function(e,t,i){if(e=(e%=2*Math.PI)<0?e+2*Math.PI:e,(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)<(i=(i%=2*Math.PI)<0?i+2*Math.PI:i)){if(e>t&&e<i)return!0}else if(e>i&&e<t)return!0;return!1},e.prototype._updateLinkedTransformRotation=function(){var e=this.bone;e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new G),e.getRotationQuaternionToRef(dn.LOCAL,null,e._linkedTransformNode.rotationQuaternion))},e._TmpVecs=C.BuildArray(10,V.Zero),e._TmpQuat=G.Identity(),e._TmpMats=C.BuildArray(5,z.Identity),e}(),$l=function(){function e(e,t,i,r){void 0===i&&(i=u.BUFFER_CREATIONFLAG_READWRITE),this._engine=e,this._label=r,this._engine._storageBuffers.push(this),this._create(t,i)}return e.prototype._create=function(e,t){this._bufferSize=e,this._creationFlags=t,this._buffer=this._engine.createStorageBuffer(e,t,this._label)},e.prototype._rebuild=function(){this._create(this._bufferSize,this._creationFlags)},e.prototype.getBuffer=function(){return this._buffer},e.prototype.update=function(e,t,i){this._buffer&&this._engine.updateStorageBuffer(this._buffer,e,t,i)},e.prototype.read=function(e,t,i,r){return this._engine.readFromStorageBuffer(this._buffer,e,t,i,r)},e.prototype.dispose=function(){var e=this._engine._storageBuffers,t=e.indexOf(this);-1!==t&&(e[t]=e[e.length-1],e.pop()),this._engine._releaseBuffer(this._buffer),this._buffer=null},e}(),ec=(Ql=new Uint8Array(4),!!((new Uint32Array(Ql.buffer)[0]=1)&Ql[0]));Object.defineProperty(Nr.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0}),Object.defineProperty(Nr.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0}),Object.defineProperty(Nr.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0}),Nr.prototype._rebuild=function(){var e,t;null===(e=this._buffer)||void 0===e||e._rebuild(),null===(t=this._alignedBuffer)||void 0===t||t._rebuild()},Nr.prototype.dispose=function(){var e;this._ownsBuffer&&this._buffer.dispose(),null===(e=this._alignedBuffer)||void 0===e||e.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0},Nr.prototype.getWrapperBuffer=function(){return this._alignedBuffer||this._buffer},Nr.prototype._alignBuffer=function(){var e,t,i=this._buffer.getData();if(this.engine._features.forceVertexBufferStrideAndOffsetMultiple4Bytes&&(this.byteStride%4!=0||this.byteOffset%4!=0)&&i){var r,n,o=Nr.GetTypeByteLength(this.type),a=this.byteStride+3&-4,s=a/o,l=this._maxVerticesCount,c=l*a/o;if(Array.isArray(i)){var u=new Float32Array(i);r=new DataView(u.buffer,u.byteOffset,u.byteLength)}else r=i instanceof ArrayBuffer?new DataView(i,0,i.byteLength):new DataView(i.buffer,i.byteOffset,i.byteLength);n=this.type===Nr.BYTE?new Int8Array(c):this.type===Nr.UNSIGNED_BYTE?new Uint8Array(c):this.type===Nr.SHORT?new Int16Array(c):this.type===Nr.UNSIGNED_SHORT?new Uint16Array(c):this.type===Nr.INT?new Int32Array(c):this.type===Nr.UNSIGNED_INT?new Uint32Array(c):new Float32Array(c);for(var h=this.getSize(),d=this.byteOffset,p=0;p<l;++p){for(var f=0;f<h;++f)switch(this.type){case Nr.BYTE:n[p*s+f]=r.getInt8(d+f);break;case Nr.UNSIGNED_BYTE:n[p*s+f]=r.getUint8(d+f);break;case Nr.SHORT:n[p*s+f]=r.getInt16(d+2*f,ec);break;case Nr.UNSIGNED_SHORT:n[p*s+f]=r.getUint16(d+2*f,ec);break;case Nr.INT:n[p*s+f]=r.getInt32(d+4*f,ec);break;case Nr.UNSIGNED_INT:n[p*s+f]=r.getUint32(d+4*f,ec);break;case Nr.FLOAT:n[p*s+f]=r.getFloat32(d+4*f,ec)}d+=this.byteStride}null===(e=this._alignedBuffer)||void 0===e||e.dispose(),this._alignedBuffer=new Dr(this.engine,n,!1,a,!1,this.getIsInstanced(),!0,this.instanceDivisor,(null!==(t=this._label)&&void 0!==t?t:"VertexBuffer")+"_aligned")}};var tc=function(){function e(){this.wheelPrecisionX=3,this.wheelPrecisionY=3,this.wheelPrecisionZ=3,this.onChangedObservable=new f,this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0,this._ffMultiplier=12,this._normalize=120}return e.prototype.attachControl=function(e){var t=this;e=rr.BackCompatCameraNoPreventDefault(arguments),this._wheel=function(i){if(i.type===Gr.POINTERWHEEL){var r=i.event,n=r.deltaMode===Qr.DOM_DELTA_LINE?t._ffMultiplier:1;t._wheelDeltaX+=t.wheelPrecisionX*n*r.deltaX/t._normalize,t._wheelDeltaY-=t.wheelPrecisionY*n*r.deltaY/t._normalize,t._wheelDeltaZ+=t.wheelPrecisionZ*n*r.deltaZ/t._normalize,r.preventDefault&&(e||r.preventDefault())}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Gr.POINTERWHEEL)},e.prototype.detachControl=function(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null),this.onChangedObservable&&this.onChangedObservable.clear()},e.prototype.checkInputs=function(){this.onChangedObservable.notifyObservers({wheelDeltaX:this._wheelDeltaX,wheelDeltaY:this._wheelDeltaY,wheelDeltaZ:this._wheelDeltaZ}),this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0},e.prototype.getClassName=function(){return"BaseCameraMouseWheelInput"},e.prototype.getSimpleName=function(){return"mousewheel"},v([Ie()],e.prototype,"wheelPrecisionX",void 0),v([Ie()],e.prototype,"wheelPrecisionY",void 0),v([Ie()],e.prototype,"wheelPrecisionZ",void 0),e}(),ic=function(){function e(){this._currentActiveButton=-1,this.buttons=[0,1,2]}return e.prototype.attachControl=function(e){var t=this;e=rr.BackCompatCameraNoPreventDefault(arguments);var i=this.camera.getEngine(),r=i.getInputElement(),n=0,o=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=function(a){var s,l,c=a.event,u="touch"===c.pointerType;if(a.type===Gr.POINTERMOVE||-1!==t.buttons.indexOf(c.button)){var h=c.target;if(t._altKey=c.altKey,t._ctrlKey=c.ctrlKey,t._metaKey=c.metaKey,t._shiftKey=c.shiftKey,t._buttonsPressed=c.buttons,i.isPointerLock){var d=c.movementX,p=c.movementY;t.onTouch(null,d,p),t._pointA=null,t._pointB=null}else{if(a.type!==Gr.POINTERDOWN&&u&&(null===(s=t._pointA)||void 0===s?void 0:s.pointerId)!==c.pointerId&&(null===(l=t._pointB)||void 0===l?void 0:l.pointerId)!==c.pointerId)return;if(a.type!==Gr.POINTERDOWN||-1!==t._currentActiveButton&&!u)if(a.type===Gr.POINTERDOUBLETAP)t.onDoubleTap(c.pointerType);else if(a.type!==Gr.POINTERUP||t._currentActiveButton!==c.button&&!u){if(a.type===Gr.POINTERMOVE)if(e||c.preventDefault(),t._pointA&&null===t._pointB)d=c.clientX-t._pointA.x,p=c.clientY-t._pointA.y,t.onTouch(t._pointA,d,p),t._pointA.x=c.clientX,t._pointA.y=c.clientY;else if(t._pointA&&t._pointB){var f=t._pointA.pointerId===c.pointerId?t._pointA:t._pointB;f.x=c.clientX,f.y=c.clientY;var _=t._pointA.x-t._pointB.x,m=t._pointA.y-t._pointB.y,g=_*_+m*m,v={x:(t._pointA.x+t._pointB.x)/2,y:(t._pointA.y+t._pointB.y)/2,pointerId:c.pointerId,type:a.type};t.onMultiTouch(t._pointA,t._pointB,n,g,o,v),o=v,n=g}}else{try{null==h||h.releasePointerCapture(c.pointerId)}catch(e){}u||(t._pointB=null),i._badOS?t._pointA=t._pointB=null:t._pointB&&t._pointA&&t._pointA.pointerId==c.pointerId?(t._pointA=t._pointB,t._pointB=null):t._pointA&&t._pointB&&t._pointB.pointerId==c.pointerId?t._pointB=null:t._pointA=t._pointB=null,(0!==n||o)&&(t.onMultiTouch(t._pointA,t._pointB,n,0,o,null),n=0,o=null),t._currentActiveButton=-1,t.onButtonUp(c),e||c.preventDefault()}else{try{null==h||h.setPointerCapture(c.pointerId)}catch(e){}if(null===t._pointA)t._pointA={x:c.clientX,y:c.clientY,pointerId:c.pointerId,type:c.pointerType};else{if(null!==t._pointB)return;t._pointB={x:c.clientX,y:c.clientY,pointerId:c.pointerId,type:c.pointerType}}-1!==t._currentActiveButton||u||(t._currentActiveButton=c.button),t.onButtonDown(c),e||(c.preventDefault(),r&&r.focus())}}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Gr.POINTERDOWN|Gr.POINTERUP|Gr.POINTERMOVE|Gr.POINTERDOUBLETAP),this._onLostFocus=function(){t._pointA=t._pointB=null,n=0,o=null,t.onLostFocus()},this._contextMenuBind=function(e){return t.onContextMenu(e)},r&&r.addEventListener("contextmenu",this._contextMenuBind,!1);var a=this.camera.getScene().getEngine().getHostWindow();a&&rr.RegisterTopRootEvents(a,[{name:"blur",handler:this._onLostFocus}])},e.prototype.detachControl=function(){if(this._onLostFocus){var e=this.camera.getScene().getEngine().getHostWindow();e&&rr.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){var t=this.camera.getScene().getEngine().getInputElement();t&&t.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1},e.prototype.getClassName=function(){return"BaseCameraPointersInput"},e.prototype.getSimpleName=function(){return"pointers"},e.prototype.onDoubleTap=function(e){},e.prototype.onTouch=function(e,t,i){},e.prototype.onMultiTouch=function(e,t,i,r,n,o){},e.prototype.onContextMenu=function(e){e.preventDefault()},e.prototype.onButtonDown=function(e){},e.prototype.onButtonUp=function(e){},e.prototype.onLostFocus=function(){},v([Ie()],e.prototype,"buttons",void 0),e}(),rc={},nc=function(){function e(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=function(){}}return e.prototype.add=function(e){var t=e.getSimpleName();this.attached[t]?ae.Warn("camera input of type "+t+" already exists on camera"):(this.attached[t]=e,e.camera=this.camera,e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e))),this.attachedToElement&&e.attachControl(this.noPreventDefault))},e.prototype.remove=function(e){for(var t in this.attached){var i=this.attached[t];if(i===e)return i.detachControl(),i.camera=null,delete this.attached[t],void this.rebuildInputCheck()}},e.prototype.removeByType=function(e){for(var t in this.attached){var i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}},e.prototype._addCheckInputs=function(e){var t=this.checkInputs;return function(){t(),e()}},e.prototype.attachInput=function(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)},e.prototype.attachElement=function(e){if(void 0===e&&(e=!1),!this.attachedToElement)for(var t in e=!$n.ForceAttachControlToAlwaysPreventDefault&&e,this.attachedToElement=!0,this.noPreventDefault=e,this.attached)this.attached[t].attachControl(e)},e.prototype.detachElement=function(e){for(var t in void 0===e&&(e=!1),this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1},e.prototype.rebuildInputCheck=function(){for(var e in this.checkInputs=function(){},this.attached){var t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}},e.prototype.clear=function(){this.attachedToElement&&this.detachElement(!0),this.attached={},this.attachedToElement=!1,this.checkInputs=function(){}},e.prototype.serialize=function(e){var t={};for(var i in this.attached){var r=this.attached[i],n=Ke.Serialize(r);t[r.getClassName()]=n}e.inputsmgr=t},e.prototype.parse=function(e){var t=e.inputsmgr;if(t){this.clear();var i=function(e){var i=rc[e];if(i){var n=t[e],o=Ke.Parse((function(){return new i}),n,null);r.add(o)}},r=this;for(var n in t)i(n)}else{var o=function(t){var i=rc[a.attached[t].getClassName()];if(i){var r=Ke.Parse((function(){return new i}),e,null);a.remove(a.attached[t]),a.add(r)}},a=this;for(var n in this.attached)o(n)}},e}(),oc=function(e,t){this.x=e,this.y=t},ac=function(){function e(t,i,r,n,o,a,s){void 0===n&&(n=0),void 0===o&&(o=1),void 0===a&&(a=2),void 0===s&&(s=3),this.id=t,this.index=i,this.browserGamepad=r,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=e.GAMEPAD,this._leftStickAxisX=n,this._leftStickAxisY=o,this._rightStickAxisX=a,this._rightStickAxisY=s,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}return Object.defineProperty(e.prototype,"isConnected",{get:function(){return this._isConnected},enumerable:!1,configurable:!0}),e.prototype.onleftstickchanged=function(e){this._onleftstickchanged=e},e.prototype.onrightstickchanged=function(e){this._onrightstickchanged=e},Object.defineProperty(e.prototype,"leftStick",{get:function(){return this._leftStick},set:function(e){!this._onleftstickchanged||this._leftStick.x===e.x&&this._leftStick.y===e.y||this._onleftstickchanged(e),this._leftStick=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"rightStick",{get:function(){return this._rightStick},set:function(e){!this._onrightstickchanged||this._rightStick.x===e.x&&this._rightStick.y===e.y||this._onrightstickchanged(e),this._rightStick=e},enumerable:!1,configurable:!0}),e.prototype.update=function(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})},e.prototype.dispose=function(){},e.GAMEPAD=0,e.GENERIC=1,e.XBOX=2,e.POSE_ENABLED=3,e.DUALSHOCK=4,e}(),sc=function(e){function t(t,i,r){var n=e.call(this,t,i,r)||this;return n.onButtonDownObservable=new f,n.onButtonUpObservable=new f,n.type=ac.GENERIC,n._buttons=new Array(r.buttons.length),n}return m(t,e),t.prototype.onbuttondown=function(e){this._onbuttondown=e},t.prototype.onbuttonup=function(e){this._onbuttonup=e},t.prototype._setButtonValue=function(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e},t.prototype.update=function(){e.prototype.update.call(this);for(var t=0;t<this._buttons.length;t++)this._buttons[t]=this._setButtonValue(this.browserGamepad.buttons[t].value,this._buttons[t],t)},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear()},t}(ac),lc=function(){function e(){this.gamepadRotationSensibility=80,this.gamepadMoveSensibility=40,this._yAxisScale=1}return Object.defineProperty(e.prototype,"invertYAxis",{get:function(){return 1!==this._yAxisScale},set:function(e){this._yAxisScale=e?-1:1},enumerable:!1,configurable:!0}),e.prototype.attachControl=function(){var e=this,t=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=t.onGamepadConnectedObservable.add((function(t){t.type!==ac.POSE_ENABLED&&(e.gamepad&&t.type!==ac.XBOX||(e.gamepad=t))})),this._onGamepadDisconnectedObserver=t.onGamepadDisconnectedObservable.add((function(t){e.gamepad===t&&(e.gamepad=null)})),this.gamepad=t.getGamepadByType(ac.XBOX),!this.gamepad&&t.gamepads.length&&(this.gamepad=t.gamepads[0])},e.prototype.detachControl=function(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null},e.prototype.checkInputs=function(){if(this.gamepad){var e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){var i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){var r=t.y/this.gamepadRotationSensibility*this._yAxisScale;0!=r&&Math.abs(r)>.005&&(e.inertialBetaOffset+=r)}}var n=this.gamepad.leftStick;if(n&&0!=n.y){var o=n.y/this.gamepadMoveSensibility;0!=o&&Math.abs(o)>.005&&(this.camera.inertialRadiusOffset-=o)}}},e.prototype.getClassName=function(){return"ArcRotateCameraGamepadInput"},e.prototype.getSimpleName=function(){return"gamepad"},v([Ie()],e.prototype,"gamepadRotationSensibility",void 0),v([Ie()],e.prototype,"gamepadMoveSensibility",void 0),e}();rc.ArcRotateCameraGamepadInput=lc;var cc=function(){function e(){this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0,this.angularSpeed=.01,this._keys=new Array}return e.prototype.attachControl=function(e){var t=this;e=rr.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((function(){t._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((function(i){var r,n=i.event;n.metaKey||(i.type===Xr.KEYDOWN?(t._ctrlPressed=n.ctrlKey,t._altPressed=n.altKey,(-1!==t.keysUp.indexOf(n.keyCode)||-1!==t.keysDown.indexOf(n.keyCode)||-1!==t.keysLeft.indexOf(n.keyCode)||-1!==t.keysRight.indexOf(n.keyCode)||-1!==t.keysReset.indexOf(n.keyCode))&&(-1===(r=t._keys.indexOf(n.keyCode))&&t._keys.push(n.keyCode),n.preventDefault&&(e||n.preventDefault()))):-1===t.keysUp.indexOf(n.keyCode)&&-1===t.keysDown.indexOf(n.keyCode)&&-1===t.keysLeft.indexOf(n.keyCode)&&-1===t.keysRight.indexOf(n.keyCode)&&-1===t.keysReset.indexOf(n.keyCode)||((r=t._keys.indexOf(n.keyCode))>=0&&t._keys.splice(r,1),n.preventDefault&&(e||n.preventDefault())))})))},e.prototype.detachControl=function(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0},e.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var e=this.camera,t=0;t<this._keys.length;t++){var i=this._keys[t];-1!==this.keysLeft.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX-=1/this.panningSensibility:e.inertialAlphaOffset-=this.angularSpeed:-1!==this.keysUp.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY+=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset+=1/this.zoomingSensibility:e.inertialBetaOffset-=this.angularSpeed:-1!==this.keysRight.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX+=1/this.panningSensibility:e.inertialAlphaOffset+=this.angularSpeed:-1!==this.keysDown.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY-=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset-=1/this.zoomingSensibility:e.inertialBetaOffset+=this.angularSpeed:-1!==this.keysReset.indexOf(i)&&e.useInputToRestoreState&&e.restoreState()}},e.prototype.getClassName=function(){return"ArcRotateCameraKeyboardMoveInput"},e.prototype.getSimpleName=function(){return"keyboard"},v([Ie()],e.prototype,"keysUp",void 0),v([Ie()],e.prototype,"keysDown",void 0),v([Ie()],e.prototype,"keysLeft",void 0),v([Ie()],e.prototype,"keysRight",void 0),v([Ie()],e.prototype,"keysReset",void 0),v([Ie()],e.prototype,"panningSensibility",void 0),v([Ie()],e.prototype,"zoomingSensibility",void 0),v([Ie()],e.prototype,"useAltToZoom",void 0),v([Ie()],e.prototype,"angularSpeed",void 0),e}();rc.ArcRotateCameraKeyboardMoveInput=cc;var uc=function(){function e(){this.wheelPrecision=3,this.zoomToMouseLocation=!1,this.wheelDeltaPercentage=0,this.customComputeDeltaFromMouseWheel=null,this._viewOffset=new V(0,0,0),this._globalOffset=new V(0,0,0),this._inertialPanning=V.Zero()}return e.prototype._computeDeltaFromMouseWheelLegacyEvent=function(e,t){var i=.01*e*this.wheelDeltaPercentage*t;return e>0?i/(1+this.wheelDeltaPercentage):i*(1+this.wheelDeltaPercentage)},e.prototype.attachControl=function(e){var t=this;e=rr.BackCompatCameraNoPreventDefault(arguments),this._wheel=function(i){if(i.type===Gr.POINTERWHEEL){var r=i.event,n=0,o=r.deltaMode===Qr.DOM_DELTA_LINE?40:1,a=-r.deltaY*o;if(t.customComputeDeltaFromMouseWheel)n=t.customComputeDeltaFromMouseWheel(a,t,r);else if(t.wheelDeltaPercentage){if((n=t._computeDeltaFromMouseWheelLegacyEvent(a,t.camera.radius))>0){for(var s=t.camera.radius,l=t.camera.inertialRadiusOffset+n,c=0;c<20&&Math.abs(l)>.001;c++)s-=l,l*=t.camera.inertia;s=j.Clamp(s,0,Number.MAX_VALUE),n=t._computeDeltaFromMouseWheelLegacyEvent(a,s)}}else n=a/(40*t.wheelPrecision);n&&(t.zoomToMouseLocation?(t._hitPlane||t._updateHitPlane(),t._zoomToMouse(n)):t.camera.inertialRadiusOffset+=n),r.preventDefault&&(e||r.preventDefault())}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Gr.POINTERWHEEL),this.zoomToMouseLocation&&this._inertialPanning.setAll(0)},e.prototype.detachControl=function(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)},e.prototype.checkInputs=function(){if(this.zoomToMouseLocation){var e=this.camera;0+e.inertialAlphaOffset+e.inertialBetaOffset+e.inertialRadiusOffset&&(this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(e.inertia),this._zeroIfClose(this._inertialPanning))}},e.prototype.getClassName=function(){return"ArcRotateCameraMouseWheelInput"},e.prototype.getSimpleName=function(){return"mousewheel"},e.prototype._updateHitPlane=function(){var e=this.camera,t=e.target.subtract(e.position);this._hitPlane=sn.FromPositionAndNormal(e.target,t)},e.prototype._getPosition=function(){var e,t=this.camera,i=t.getScene(),r=i.createPickingRay(i.pointerX,i.pointerY,z.Identity(),t,!1);0===t.targetScreenOffset.x&&0===t.targetScreenOffset.y||(this._viewOffset.set(t.targetScreenOffset.x,t.targetScreenOffset.y,0),t.getViewMatrix().invertToRef(t._cameraTransformMatrix),this._globalOffset=V.TransformNormal(this._viewOffset,t._cameraTransformMatrix),r.origin.addInPlace(this._globalOffset));var n=0;return this._hitPlane&&(n=null!==(e=r.intersectsPlane(this._hitPlane))&&void 0!==e?e:0),r.origin.addInPlace(r.direction.scaleInPlace(n))},e.prototype._zoomToMouse=function(e){var t,i,r=this.camera,n=1-r.inertia;if(r.lowerRadiusLimit){var o=null!==(t=r.lowerRadiusLimit)&&void 0!==t?t:0;r.radius-(r.inertialRadiusOffset+e)/n<o&&(e=(r.radius-o)*n-r.inertialRadiusOffset)}if(r.upperRadiusLimit){var a=null!==(i=r.upperRadiusLimit)&&void 0!==i?i:0;r.radius-(r.inertialRadiusOffset+e)/n>a&&(e=(r.radius-a)*n-r.inertialRadiusOffset)}var s=e/n/r.radius,l=this._getPosition(),c=H.Vector3[6];l.subtractToRef(r.target,c),c.scaleInPlace(s),c.scaleInPlace(n),this._inertialPanning.addInPlace(c),r.inertialRadiusOffset+=e},e.prototype._zeroIfClose=function(e){Math.abs(e.x)<A&&(e.x=0),Math.abs(e.y)<A&&(e.y=0),Math.abs(e.z)<A&&(e.z=0)},v([Ie()],e.prototype,"wheelPrecision",void 0),v([Ie()],e.prototype,"zoomToMouseLocation",void 0),v([Ie()],e.prototype,"wheelDeltaPercentage",void 0),e}();rc.ArcRotateCameraMouseWheelInput=uc;var hc=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.buttons=[0,1,2],t.angularSensibilityX=1e3,t.angularSensibilityY=1e3,t.pinchPrecision=12,t.pinchDeltaPercentage=0,t.useNaturalPinchZoom=!1,t.pinchZoom=!0,t.panningSensibility=1e3,t.multiTouchPanning=!0,t.multiTouchPanAndZoom=!0,t.pinchInwards=!0,t._isPanClick=!1,t._twoFingerActivityCount=0,t._isPinching=!1,t}return m(t,e),t.prototype.getClassName=function(){return"ArcRotateCameraPointersInput"},t.prototype._computeMultiTouchPanning=function(e,t){if(0!==this.panningSensibility&&e&&t){var i=t.x-e.x,r=t.y-e.y;this.camera.inertialPanningX+=-i/this.panningSensibility,this.camera.inertialPanningY+=r/this.panningSensibility}},t.prototype._computePinchZoom=function(e,i){var r=this.camera.radius||t.MinimumRadiusForPinch;this.useNaturalPinchZoom?this.camera.radius=r*Math.sqrt(e)/Math.sqrt(i):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=.001*(i-e)*r*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(i-e)/(this.pinchPrecision*(this.pinchInwards?1:-1)*(this.angularSensibilityX+this.angularSensibilityY)/2)},t.prototype.onTouch=function(e,t,i){0!==this.panningSensibility&&(this._ctrlKey&&this.camera._useCtrlForPanning||this._isPanClick)?(this.camera.inertialPanningX+=-t/this.panningSensibility,this.camera.inertialPanningY+=i/this.panningSensibility):(this.camera.inertialAlphaOffset-=t/this.angularSensibilityX,this.camera.inertialBetaOffset-=i/this.angularSensibilityY)},t.prototype.onDoubleTap=function(){this.camera.useInputToRestoreState&&this.camera.restoreState()},t.prototype.onMultiTouch=function(e,t,i,r,n,o){0===i&&null===n||0===r&&null===o||(this.multiTouchPanAndZoom?(this._computePinchZoom(i,r),this._computeMultiTouchPanning(n,o)):this.multiTouchPanning&&this.pinchZoom?(this._twoFingerActivityCount++,this._isPinching||this._twoFingerActivityCount<20&&Math.abs(Math.sqrt(r)-Math.sqrt(i))>this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,r),this._isPinching=!0):this._computeMultiTouchPanning(n,o)):this.multiTouchPanning?this._computeMultiTouchPanning(n,o):this.pinchZoom&&this._computePinchZoom(i,r))},t.prototype.onButtonDown=function(e){this._isPanClick=e.button===this.camera._panningMouseButton},t.prototype.onButtonUp=function(e){this._twoFingerActivityCount=0,this._isPinching=!1},t.prototype.onLostFocus=function(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1},t.MinimumRadiusForPinch=.001,v([Ie()],t.prototype,"buttons",void 0),v([Ie()],t.prototype,"angularSensibilityX",void 0),v([Ie()],t.prototype,"angularSensibilityY",void 0),v([Ie()],t.prototype,"pinchPrecision",void 0),v([Ie()],t.prototype,"pinchDeltaPercentage",void 0),v([Ie()],t.prototype,"useNaturalPinchZoom",void 0),v([Ie()],t.prototype,"pinchZoom",void 0),v([Ie()],t.prototype,"panningSensibility",void 0),v([Ie()],t.prototype,"multiTouchPanning",void 0),v([Ie()],t.prototype,"multiTouchPanAndZoom",void 0),t}(ic);rc.ArcRotateCameraPointersInput=hc;var dc=function(e){function t(t){return e.call(this,t)||this}return m(t,e),t.prototype.addMouseWheel=function(){return this.add(new uc),this},t.prototype.addPointers=function(){return this.add(new hc),this},t.prototype.addKeyboard=function(){return this.add(new cc),this},t}(nc);dc.prototype.addVRDeviceOrientation=function(){return this.add(new pc),this};var pc=function(){function e(){var e=this;this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=function(t){return e._onOrientationEvent(t)}}return e.prototype.attachControl=function(e){var t=this;e=rr.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);var i=this.camera.getScene().getEngine().getHostWindow();i&&("undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((function(e){"granted"===e?i.addEventListener("deviceorientation",t._deviceOrientationHandler):rr.Warn("Permission not granted.")})).catch((function(e){rr.Error(e)})):i.addEventListener("deviceorientation",this._deviceOrientationHandler))},e.prototype._onOrientationEvent=function(e){null!==e.alpha&&(this._alpha=(0|+e.alpha)*this.alphaCorrection),null!==e.gamma&&(this._gamma=(0|+e.gamma)*this.gammaCorrection),this._dirty=!0},e.prototype.checkInputs=function(){this._dirty&&(this._dirty=!1,this._gamma<0&&(this._gamma=180+this._gamma),this.camera.alpha=-this._alpha/180*Math.PI%Math.PI*2,this.camera.beta=this._gamma/180*Math.PI)},e.prototype.detachControl=function(){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)},e.prototype.getClassName=function(){return"ArcRotateCameraVRDeviceOrientationInput"},e.prototype.getSimpleName=function(){return"VRDeviceOrientation"},e}();rc.ArcRotateCameraVRDeviceOrientationInput=pc;var fc=function(){function e(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=new Array}return e.prototype.attachControl=function(e){var t=this;e=rr.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((function(){t._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((function(i){var r,n=i.event;i.type===Xr.KEYDOWN?-1===t.keysForward.indexOf(n.keyCode)&&-1===t.keysBackward.indexOf(n.keyCode)&&-1===t.keysUp.indexOf(n.keyCode)&&-1===t.keysDown.indexOf(n.keyCode)&&-1===t.keysLeft.indexOf(n.keyCode)&&-1===t.keysRight.indexOf(n.keyCode)||(-1===(r=t._keys.indexOf(n.keyCode))&&t._keys.push(n.keyCode),e||n.preventDefault()):-1===t.keysForward.indexOf(n.keyCode)&&-1===t.keysBackward.indexOf(n.keyCode)&&-1===t.keysUp.indexOf(n.keyCode)&&-1===t.keysDown.indexOf(n.keyCode)&&-1===t.keysLeft.indexOf(n.keyCode)&&-1===t.keysRight.indexOf(n.keyCode)||((r=t._keys.indexOf(n.keyCode))>=0&&t._keys.splice(r,1),e||n.preventDefault())})))},e.prototype.detachControl=function(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0},e.prototype.getClassName=function(){return"FlyCameraKeyboardInput"},e.prototype._onLostFocus=function(){this._keys.length=0},e.prototype.getSimpleName=function(){return"keyboard"},e.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var e=this.camera,t=0;t<this._keys.length;t++){var i=this._keys[t],r=e._computeLocalCameraSpeed();-1!==this.keysForward.indexOf(i)?e._localDirection.copyFromFloats(0,0,r):-1!==this.keysBackward.indexOf(i)?e._localDirection.copyFromFloats(0,0,-r):-1!==this.keysUp.indexOf(i)?e._localDirection.copyFromFloats(0,r,0):-1!==this.keysDown.indexOf(i)?e._localDirection.copyFromFloats(0,-r,0):-1!==this.keysRight.indexOf(i)?e._localDirection.copyFromFloats(r,0,0):-1!==this.keysLeft.indexOf(i)&&e._localDirection.copyFromFloats(-r,0,0),e.getScene().useRightHandedSystem&&(e._localDirection.z*=-1),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),V.TransformNormalToRef(e._localDirection,e._cameraTransformMatrix,e._transformedDirection),e.cameraDirection.addInPlace(e._transformedDirection)}},v([Ie()],e.prototype,"keysForward",void 0),v([Ie()],e.prototype,"keysBackward",void 0),v([Ie()],e.prototype,"keysUp",void 0),v([Ie()],e.prototype,"keysDown",void 0),v([Ie()],e.prototype,"keysRight",void 0),v([Ie()],e.prototype,"keysLeft",void 0),e}();rc.FlyCameraKeyboardInput=fc;var _c=function(){function e(){this.buttons=[0,1,2],this.buttonsYaw=[-1,0,1],this.buttonsPitch=[-1,0,1],this.buttonsRoll=[2],this.activeButton=-1,this.angularSensibility=1e3,this._previousPosition=null}return e.prototype.attachControl=function(e){var t=this;e=rr.BackCompatCameraNoPreventDefault(arguments),this._noPreventDefault=e,this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver((function(e){t._pointerInput(e)}),Gr.POINTERDOWN|Gr.POINTERUP|Gr.POINTERMOVE),this._rollObserver=this.camera.getScene().onBeforeRenderObservable.add((function(){t.camera.rollCorrect&&t.camera.restoreRoll(t.camera.rollCorrect)}))},e.prototype.detachControl=function(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver),this._observer=null,this._rollObserver=null,this._previousPosition=null,this._noPreventDefault=void 0)},e.prototype.getClassName=function(){return"FlyCameraMouseInput"},e.prototype.getSimpleName=function(){return"mouse"},e.prototype._pointerInput=function(e){var t=e.event,i=this.camera.getEngine();if((this.touchEnabled||"touch"!==t.pointerType)&&(e.type===Gr.POINTERMOVE||-1!==this.buttons.indexOf(t.button))){var r=t.target;if(e.type===Gr.POINTERDOWN){try{null==r||r.setPointerCapture(t.pointerId)}catch(t){}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||(t.preventDefault(),this._element.focus()),i.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===Gr.POINTERUP){try{null==r||r.releasePointerCapture(t.pointerId)}catch(t){}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===Gr.POINTERMOVE){if(!this._previousPosition)return void(i.isPointerLock&&this._onMouseMove(e.event));var n=t.clientX-this._previousPosition.x,o=t.clientY-this._previousPosition.y;this._rotateCamera(n,o),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}},e.prototype._onMouseMove=function(e){if(this.camera.getEngine().isPointerLock){var t=e.movementX,i=e.movementY;this._rotateCamera(t,i),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}},e.prototype._rotateCamera=function(e,t){var i,r=this,n=this.camera,o=(e*=n._calculateHandednessMultiplier())/this.angularSensibility,a=t/this.angularSensibility,s=G.RotationYawPitchRoll(n.rotation.y,n.rotation.x,n.rotation.z);if(this.buttonsPitch.some((function(e){return e===r.activeButton}))&&(i=G.RotationAxis(_n.X,a),s.multiplyInPlace(i)),this.buttonsYaw.some((function(e){return e===r.activeButton}))){i=G.RotationAxis(_n.Y,o),s.multiplyInPlace(i);var l=n.bankedTurnLimit+n._trackRoll;if(n.bankedTurn&&-l<n.rotation.z&&n.rotation.z<l){var c=n.bankedTurnMultiplier*-o;i=G.RotationAxis(_n.Z,c),s.multiplyInPlace(i)}}this.buttonsRoll.some((function(e){return e===r.activeButton}))&&(i=G.RotationAxis(_n.Z,-o),n._trackRoll-=o,s.multiplyInPlace(i)),s.toEulerAnglesToRef(n.rotation)},v([Ie()],e.prototype,"buttons",void 0),v([Ie()],e.prototype,"angularSensibility",void 0),e}();rc.FlyCameraMouseInput=_c;var mc=function(){function e(){this.keysHeightOffsetIncr=[38],this.keysHeightOffsetDecr=[40],this.keysHeightOffsetModifierAlt=!1,this.keysHeightOffsetModifierCtrl=!1,this.keysHeightOffsetModifierShift=!1,this.keysRotationOffsetIncr=[37],this.keysRotationOffsetDecr=[39],this.keysRotationOffsetModifierAlt=!1,this.keysRotationOffsetModifierCtrl=!1,this.keysRotationOffsetModifierShift=!1,this.keysRadiusIncr=[40],this.keysRadiusDecr=[38],this.keysRadiusModifierAlt=!0,this.keysRadiusModifierCtrl=!1,this.keysRadiusModifierShift=!1,this.heightSensibility=1,this.rotationSensibility=1,this.radiusSensibility=1,this._keys=new Array}return e.prototype.attachControl=function(e){var t=this;e=rr.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((function(){t._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((function(i){var r,n=i.event;n.metaKey||(i.type===Xr.KEYDOWN?(t._ctrlPressed=n.ctrlKey,t._altPressed=n.altKey,t._shiftPressed=n.shiftKey,(-1!==t.keysHeightOffsetIncr.indexOf(n.keyCode)||-1!==t.keysHeightOffsetDecr.indexOf(n.keyCode)||-1!==t.keysRotationOffsetIncr.indexOf(n.keyCode)||-1!==t.keysRotationOffsetDecr.indexOf(n.keyCode)||-1!==t.keysRadiusIncr.indexOf(n.keyCode)||-1!==t.keysRadiusDecr.indexOf(n.keyCode))&&(-1===(r=t._keys.indexOf(n.keyCode))&&t._keys.push(n.keyCode),n.preventDefault&&(e||n.preventDefault()))):-1===t.keysHeightOffsetIncr.indexOf(n.keyCode)&&-1===t.keysHeightOffsetDecr.indexOf(n.keyCode)&&-1===t.keysRotationOffsetIncr.indexOf(n.keyCode)&&-1===t.keysRotationOffsetDecr.indexOf(n.keyCode)&&-1===t.keysRadiusIncr.indexOf(n.keyCode)&&-1===t.keysRadiusDecr.indexOf(n.keyCode)||((r=t._keys.indexOf(n.keyCode))>=0&&t._keys.splice(r,1),n.preventDefault&&(e||n.preventDefault())))})))},e.prototype.detachControl=function(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0},e.prototype.checkInputs=function(){var e=this;this._onKeyboardObserver&&this._keys.forEach((function(t){-1!==e.keysHeightOffsetIncr.indexOf(t)&&e._modifierHeightOffset()?e.camera.heightOffset+=e.heightSensibility:-1!==e.keysHeightOffsetDecr.indexOf(t)&&e._modifierHeightOffset()?e.camera.heightOffset-=e.heightSensibility:-1!==e.keysRotationOffsetIncr.indexOf(t)&&e._modifierRotationOffset()?(e.camera.rotationOffset+=e.rotationSensibility,e.camera.rotationOffset%=360):-1!==e.keysRotationOffsetDecr.indexOf(t)&&e._modifierRotationOffset()?(e.camera.rotationOffset-=e.rotationSensibility,e.camera.rotationOffset%=360):-1!==e.keysRadiusIncr.indexOf(t)&&e._modifierRadius()?e.camera.radius+=e.radiusSensibility:-1!==e.keysRadiusDecr.indexOf(t)&&e._modifierRadius()&&(e.camera.radius-=e.radiusSensibility)}))},e.prototype.getClassName=function(){return"FollowCameraKeyboardMoveInput"},e.prototype.getSimpleName=function(){return"keyboard"},e.prototype._modifierHeightOffset=function(){return this.keysHeightOffsetModifierAlt===this._altPressed&&this.keysHeightOffsetModifierCtrl===this._ctrlPressed&&this.keysHeightOffsetModifierShift===this._shiftPressed},e.prototype._modifierRotationOffset=function(){return this.keysRotationOffsetModifierAlt===this._altPressed&&this.keysRotationOffsetModifierCtrl===this._ctrlPressed&&this.keysRotationOffsetModifierShift===this._shiftPressed},e.prototype._modifierRadius=function(){return this.keysRadiusModifierAlt===this._altPressed&&this.keysRadiusModifierCtrl===this._ctrlPressed&&this.keysRadiusModifierShift===this._shiftPressed},v([Ie()],e.prototype,"keysHeightOffsetIncr",void 0),v([Ie()],e.prototype,"keysHeightOffsetDecr",void 0),v([Ie()],e.prototype,"keysHeightOffsetModifierAlt",void 0),v([Ie()],e.prototype,"keysHeightOffsetModifierCtrl",void 0),v([Ie()],e.prototype,"keysHeightOffsetModifierShift",void 0),v([Ie()],e.prototype,"keysRotationOffsetIncr",void 0),v([Ie()],e.prototype,"keysRotationOffsetDecr",void 0),v([Ie()],e.prototype,"keysRotationOffsetModifierAlt",void 0),v([Ie()],e.prototype,"keysRotationOffsetModifierCtrl",void 0),v([Ie()],e.prototype,"keysRotationOffsetModifierShift",void 0),v([Ie()],e.prototype,"keysRadiusIncr",void 0),v([Ie()],e.prototype,"keysRadiusDecr",void 0),v([Ie()],e.prototype,"keysRadiusModifierAlt",void 0),v([Ie()],e.prototype,"keysRadiusModifierCtrl",void 0),v([Ie()],e.prototype,"keysRadiusModifierShift",void 0),v([Ie()],e.prototype,"heightSensibility",void 0),v([Ie()],e.prototype,"rotationSensibility",void 0),v([Ie()],e.prototype,"radiusSensibility",void 0),e}();rc.FollowCameraKeyboardMoveInput=mc;var gc=function(){function e(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}return e.prototype.attachControl=function(e){var t=this;e=rr.BackCompatCameraNoPreventDefault(arguments),this._wheel=function(i){if(i.type===Gr.POINTERWHEEL){var r=i.event,n=0,o=Math.max(-1,Math.min(1,r.deltaY));t.wheelDeltaPercentage?(+t.axisControlRadius+ +t.axisControlHeight+ +t.axisControlRotation&&ae.Warn("wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+t.axisControlRadius+", axisControlHeightOffset: "+t.axisControlHeight+", axisControlRotationOffset: "+t.axisControlRotation),t.axisControlRadius?n=.01*o*t.wheelDeltaPercentage*t.camera.radius:t.axisControlHeight?n=.01*o*t.wheelDeltaPercentage*t.camera.heightOffset:t.axisControlRotation&&(n=.01*o*t.wheelDeltaPercentage*t.camera.rotationOffset)):n=o*t.wheelPrecision,n&&(t.axisControlRadius?t.camera.radius+=n:t.axisControlHeight?t.camera.heightOffset-=n:t.axisControlRotation&&(t.camera.rotationOffset-=n)),r.preventDefault&&(e||r.preventDefault())}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,Gr.POINTERWHEEL)},e.prototype.detachControl=function(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)},e.prototype.getClassName=function(){return"ArcRotateCameraMouseWheelInput"},e.prototype.getSimpleName=function(){return"mousewheel"},v([Ie()],e.prototype,"axisControlRadius",void 0),v([Ie()],e.prototype,"axisControlHeight",void 0),v([Ie()],e.prototype,"axisControlRotation",void 0),v([Ie()],e.prototype,"wheelPrecision",void 0),v([Ie()],e.prototype,"wheelDeltaPercentage",void 0),e}();rc.FollowCameraMouseWheelInput=gc;var vc=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.angularSensibilityX=1,t.angularSensibilityY=1,t.pinchPrecision=1e4,t.pinchDeltaPercentage=0,t.axisXControlRadius=!1,t.axisXControlHeight=!1,t.axisXControlRotation=!0,t.axisYControlRadius=!1,t.axisYControlHeight=!0,t.axisYControlRotation=!1,t.axisPinchControlRadius=!0,t.axisPinchControlHeight=!1,t.axisPinchControlRotation=!1,t.warningEnable=!0,t._warningCounter=0,t}return m(t,e),t.prototype.getClassName=function(){return"FollowCameraPointersInput"},t.prototype.onTouch=function(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)},t.prototype.onMultiTouch=function(e,t,i,r,n,o){if(!(0===i&&null===n||0===r&&null===o)){var a=(r-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(a*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=a*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=a*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=a*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=a),this.axisPinchControlHeight&&(this.camera.heightOffset+=a),this.axisPinchControlRadius&&(this.camera.radius-=a))}},t.prototype._warning=function(){if(this.warningEnable&&this._warningCounter++%100==0){var e="It probably only makes sense to control ONE camera property with each pointer axis. Set 'warningEnable = false' if you are sure. Currently enabled: ";+this.axisXControlRotation+ +this.axisXControlHeight+ +this.axisXControlRadius<=1&&ae.Warn(e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),+this.axisYControlRotation+ +this.axisYControlHeight+ +this.axisYControlRadius<=1&&ae.Warn(e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),+this.axisPinchControlRotation+ +this.axisPinchControlHeight+ +this.axisPinchControlRadius<=1&&ae.Warn(e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}},v([Ie()],t.prototype,"angularSensibilityX",void 0),v([Ie()],t.prototype,"angularSensibilityY",void 0),v([Ie()],t.prototype,"pinchPrecision",void 0),v([Ie()],t.prototype,"pinchDeltaPercentage",void 0),v([Ie()],t.prototype,"axisXControlRadius",void 0),v([Ie()],t.prototype,"axisXControlHeight",void 0),v([Ie()],t.prototype,"axisXControlRotation",void 0),v([Ie()],t.prototype,"axisYControlRadius",void 0),v([Ie()],t.prototype,"axisYControlHeight",void 0),v([Ie()],t.prototype,"axisYControlRotation",void 0),v([Ie()],t.prototype,"axisPinchControlRadius",void 0),v([Ie()],t.prototype,"axisPinchControlHeight",void 0),v([Ie()],t.prototype,"axisPinchControlRotation",void 0),t}(ic);rc.FollowCameraPointersInput=vc;var yc=function(){function e(){this.keysUp=[38],this.keysUpward=[33],this.keysDown=[40],this.keysDownward=[34],this.keysLeft=[37],this.keysRight=[39],this.rotationSpeed=.5,this.keysRotateLeft=[],this.keysRotateRight=[],this.keysRotateUp=[],this.keysRotateDown=[],this._keys=new Array}return e.prototype.attachControl=function(e){var t=this;e=rr.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((function(){t._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((function(i){var r,n=i.event;n.metaKey||(i.type===Xr.KEYDOWN?-1===t.keysUp.indexOf(n.keyCode)&&-1===t.keysDown.indexOf(n.keyCode)&&-1===t.keysLeft.indexOf(n.keyCode)&&-1===t.keysRight.indexOf(n.keyCode)&&-1===t.keysUpward.indexOf(n.keyCode)&&-1===t.keysDownward.indexOf(n.keyCode)&&-1===t.keysRotateLeft.indexOf(n.keyCode)&&-1===t.keysRotateRight.indexOf(n.keyCode)&&-1===t.keysRotateUp.indexOf(n.keyCode)&&-1===t.keysRotateDown.indexOf(n.keyCode)||(-1===(r=t._keys.indexOf(n.keyCode))&&t._keys.push(n.keyCode),e||n.preventDefault()):-1===t.keysUp.indexOf(n.keyCode)&&-1===t.keysDown.indexOf(n.keyCode)&&-1===t.keysLeft.indexOf(n.keyCode)&&-1===t.keysRight.indexOf(n.keyCode)&&-1===t.keysUpward.indexOf(n.keyCode)&&-1===t.keysDownward.indexOf(n.keyCode)&&-1===t.keysRotateLeft.indexOf(n.keyCode)&&-1===t.keysRotateRight.indexOf(n.keyCode)&&-1===t.keysRotateUp.indexOf(n.keyCode)&&-1===t.keysRotateDown.indexOf(n.keyCode)||((r=t._keys.indexOf(n.keyCode))>=0&&t._keys.splice(r,1),e||n.preventDefault()))})))},e.prototype.detachControl=function(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0},e.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var e=this.camera,t=0;t<this._keys.length;t++){var i=this._keys[t],r=e._computeLocalCameraSpeed();-1!==this.keysLeft.indexOf(i)?e._localDirection.copyFromFloats(-r,0,0):-1!==this.keysUp.indexOf(i)?e._localDirection.copyFromFloats(0,0,r):-1!==this.keysRight.indexOf(i)?e._localDirection.copyFromFloats(r,0,0):-1!==this.keysDown.indexOf(i)?e._localDirection.copyFromFloats(0,0,-r):-1!==this.keysUpward.indexOf(i)?e._localDirection.copyFromFloats(0,r,0):-1!==this.keysDownward.indexOf(i)?e._localDirection.copyFromFloats(0,-r,0):-1!==this.keysRotateLeft.indexOf(i)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y-=this._getLocalRotation()):-1!==this.keysRotateRight.indexOf(i)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y+=this._getLocalRotation()):-1!==this.keysRotateUp.indexOf(i)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x-=this._getLocalRotation()):-1!==this.keysRotateDown.indexOf(i)&&(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x+=this._getLocalRotation()),e.getScene().useRightHandedSystem&&(e._localDirection.z*=-1),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),V.TransformNormalToRef(e._localDirection,e._cameraTransformMatrix,e._transformedDirection),e.cameraDirection.addInPlace(e._transformedDirection)}},e.prototype.getClassName=function(){return"FreeCameraKeyboardMoveInput"},e.prototype._onLostFocus=function(){this._keys.length=0},e.prototype.getSimpleName=function(){return"keyboard"},e.prototype._getLocalRotation=function(){var e=this.camera._calculateHandednessMultiplier();return this.rotationSpeed*this._engine.getDeltaTime()/1e3*e},v([Ie()],e.prototype,"keysUp",void 0),v([Ie()],e.prototype,"keysUpward",void 0),v([Ie()],e.prototype,"keysDown",void 0),v([Ie()],e.prototype,"keysDownward",void 0),v([Ie()],e.prototype,"keysLeft",void 0),v([Ie()],e.prototype,"keysRight",void 0),v([Ie()],e.prototype,"rotationSpeed",void 0),v([Ie()],e.prototype,"keysRotateLeft",void 0),v([Ie()],e.prototype,"keysRotateRight",void 0),v([Ie()],e.prototype,"keysRotateUp",void 0),v([Ie()],e.prototype,"keysRotateDown",void 0),e}();rc.FreeCameraKeyboardMoveInput=yc;var bc,Tc=function(){function e(e){void 0===e&&(e=!0),this.touchEnabled=e,this.buttons=[0,1,2],this.angularSensibility=2e3,this._previousPosition=null,this.onPointerMovedObservable=new f,this._allowCameraRotation=!0,this._currentActiveButton=-1,this._activePointerId=-1}return e.prototype.attachControl=function(e){var t=this;e=rr.BackCompatCameraNoPreventDefault(arguments);var i=this.camera.getEngine(),r=i.getInputElement();this._pointerInput||(this._pointerInput=function(n){var o=n.event,a="touch"===o.pointerType;if((t.touchEnabled||!a)&&(n.type===Gr.POINTERMOVE||-1!==t.buttons.indexOf(o.button))){var s=o.target;if(n.type===Gr.POINTERDOWN){if(a&&-1!==t._activePointerId||!a&&-1!==t._currentActiveButton)return;t._activePointerId=o.pointerId;try{null==s||s.setPointerCapture(o.pointerId)}catch(e){}-1===t._currentActiveButton&&(t._currentActiveButton=o.button),t._previousPosition={x:o.clientX,y:o.clientY},e||(o.preventDefault(),r&&r.focus()),i.isPointerLock&&t._onMouseMove&&t._onMouseMove(n.event)}else if(n.type===Gr.POINTERUP){if(a&&t._activePointerId!==o.pointerId||!a&&t._currentActiveButton!==o.button)return;try{null==s||s.releasePointerCapture(o.pointerId)}catch(e){}t._currentActiveButton=-1,t._previousPosition=null,e||o.preventDefault(),t._activePointerId=-1}else if(n.type===Gr.POINTERMOVE&&(t._activePointerId===o.pointerId||!a))if(i.isPointerLock&&t._onMouseMove)t._onMouseMove(n.event);else if(t._previousPosition){var l=t.camera._calculateHandednessMultiplier(),c=(o.clientX-t._previousPosition.x)*l,u=o.clientY-t._previousPosition.y;t._allowCameraRotation&&(t.camera.cameraRotation.y+=c/t.angularSensibility,t.camera.cameraRotation.x+=u/t.angularSensibility),t.onPointerMovedObservable.notifyObservers({offsetX:c,offsetY:u}),t._previousPosition={x:o.clientX,y:o.clientY},e||o.preventDefault()}}}),this._onMouseMove=function(r){if(i.isPointerLock){var n=t.camera._calculateHandednessMultiplier(),o=r.movementX*n;t.camera.cameraRotation.y+=o/t.angularSensibility;var a=r.movementY;t.camera.cameraRotation.x+=a/t.angularSensibility,t._previousPosition=null,e||r.preventDefault()}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Gr.POINTERDOWN|Gr.POINTERUP|Gr.POINTERMOVE),r&&(this._contextMenuBind=function(e){return t.onContextMenu(e)},r.addEventListener("contextmenu",this._contextMenuBind,!1))},e.prototype.onContextMenu=function(e){e.preventDefault()},e.prototype.detachControl=function(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){var e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this._previousPosition=null}this._activePointerId=-1,this._currentActiveButton=-1},e.prototype.getClassName=function(){return"FreeCameraMouseInput"},e.prototype.getSimpleName=function(){return"mouse"},v([Ie()],e.prototype,"buttons",void 0),v([Ie()],e.prototype,"angularSensibility",void 0),e}();rc.FreeCameraMouseInput=Tc,function(e){e[e.MoveRelative=0]="MoveRelative",e[e.RotateRelative=1]="RotateRelative",e[e.MoveScene=2]="MoveScene"}(bc||(bc={}));var Ec=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._moveRelative=V.Zero(),t._rotateRelative=V.Zero(),t._moveScene=V.Zero(),t._wheelXAction=bc.MoveRelative,t._wheelXActionCoordinate=fn.X,t._wheelYAction=bc.MoveRelative,t._wheelYActionCoordinate=fn.Z,t._wheelZAction=null,t._wheelZActionCoordinate=null,t}return m(t,e),t.prototype.getClassName=function(){return"FreeCameraMouseWheelInput"},Object.defineProperty(t.prototype,"wheelXMoveRelative",{get:function(){return this._wheelXAction!==bc.MoveRelative?null:this._wheelXActionCoordinate},set:function(e){null===e&&this._wheelXAction!==bc.MoveRelative||(this._wheelXAction=bc.MoveRelative,this._wheelXActionCoordinate=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"wheelYMoveRelative",{get:function(){return this._wheelYAction!==bc.MoveRelative?null:this._wheelYActionCoordinate},set:function(e){null===e&&this._wheelYAction!==bc.MoveRelative||(this._wheelYAction=bc.MoveRelative,this._wheelYActionCoordinate=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"wheelZMoveRelative",{get:function(){return this._wheelZAction!==bc.MoveRelative?null:this._wheelZActionCoordinate},set:function(e){null===e&&this._wheelZAction!==bc.MoveRelative||(this._wheelZAction=bc.MoveRelative,this._wheelZActionCoordinate=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"wheelXRotateRelative",{get:function(){return this._wheelXAction!==bc.RotateRelative?null:this._wheelXActionCoordinate},set:function(e){null===e&&this._wheelXAction!==bc.RotateRelative||(this._wheelXAction=bc.RotateRelative,this._wheelXActionCoordinate=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"wheelYRotateRelative",{get:function(){return this._wheelYAction!==bc.RotateRelative?null:this._wheelYActionCoordinate},set:function(e){null===e&&this._wheelYAction!==bc.RotateRelative||(this._wheelYAction=bc.RotateRelative,this._wheelYActionCoordinate=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"wheelZRotateRelative",{get:function(){return this._wheelZAction!==bc.RotateRelative?null:this._wheelZActionCoordinate},set:function(e){null===e&&this._wheelZAction!==bc.RotateRelative||(this._wheelZAction=bc.RotateRelative,this._wheelZActionCoordinate=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"wheelXMoveScene",{get:function(){return this._wheelXAction!==bc.MoveScene?null:this._wheelXActionCoordinate},set:function(e){null===e&&this._wheelXAction!==bc.MoveScene||(this._wheelXAction=bc.MoveScene,this._wheelXActionCoordinate=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"wheelYMoveScene",{get:function(){return this._wheelYAction!==bc.MoveScene?null:this._wheelYActionCoordinate},set:function(e){null===e&&this._wheelYAction!==bc.MoveScene||(this._wheelYAction=bc.MoveScene,this._wheelYActionCoordinate=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"wheelZMoveScene",{get:function(){return this._wheelZAction!==bc.MoveScene?null:this._wheelZActionCoordinate},set:function(e){null===e&&this._wheelZAction!==bc.MoveScene||(this._wheelZAction=bc.MoveScene,this._wheelZActionCoordinate=e)},enumerable:!1,configurable:!0}),t.prototype.checkInputs=function(){if(0!==this._wheelDeltaX||0!==this._wheelDeltaY||0!=this._wheelDeltaZ){this._moveRelative.setAll(0),this._rotateRelative.setAll(0),this._moveScene.setAll(0),this._updateCamera(),this.camera.getScene().useRightHandedSystem&&(this._moveRelative.z*=-1);var t=z.Zero();this.camera.getViewMatrix().invertToRef(t);var i=V.Zero();V.TransformNormalToRef(this._moveRelative,t,i),this.camera.cameraRotation.x+=this._rotateRelative.x/200,this.camera.cameraRotation.y+=this._rotateRelative.y/200,this.camera.cameraDirection.addInPlace(i),this.camera.cameraDirection.addInPlace(this._moveScene),e.prototype.checkInputs.call(this)}},t.prototype._updateCamera=function(){this._updateCameraProperty(this._wheelDeltaX,this._wheelXAction,this._wheelXActionCoordinate),this._updateCameraProperty(this._wheelDeltaY,this._wheelYAction,this._wheelYActionCoordinate),this._updateCameraProperty(this._wheelDeltaZ,this._wheelZAction,this._wheelZActionCoordinate)},t.prototype._updateCameraProperty=function(e,t,i){if(0!==e&&null!==t&&null!==i){var r=null;switch(t){case bc.MoveRelative:r=this._moveRelative;break;case bc.RotateRelative:r=this._rotateRelative;break;case bc.MoveScene:r=this._moveScene}switch(i){case fn.X:r.set(e,0,0);break;case fn.Y:r.set(0,e,0);break;case fn.Z:r.set(0,0,e)}}},v([Ie()],t.prototype,"wheelXMoveRelative",null),v([Ie()],t.prototype,"wheelYMoveRelative",null),v([Ie()],t.prototype,"wheelZMoveRelative",null),v([Ie()],t.prototype,"wheelXRotateRelative",null),v([Ie()],t.prototype,"wheelYRotateRelative",null),v([Ie()],t.prototype,"wheelZRotateRelative",null),v([Ie()],t.prototype,"wheelXMoveScene",null),v([Ie()],t.prototype,"wheelYMoveScene",null),v([Ie()],t.prototype,"wheelZMoveScene",null),t}(tc);rc.FreeCameraMouseWheelInput=Ec;var Sc=function(){function e(e){void 0===e&&(e=!1),this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array,this._isSafari=rr.IsSafari()}return e.prototype.attachControl=function(e){var t=this;e=rr.BackCompatCameraNoPreventDefault(arguments);var i=null;if(void 0===this._pointerInput&&(this._onLostFocus=function(){t._offsetX=null,t._offsetY=null},this._pointerInput=function(r){var n=r.event,o="mouse"===n.pointerType||t._isSafari&&void 0===n.pointerType;if(t.allowMouse||!o)if(r.type===Gr.POINTERDOWN){if(e||n.preventDefault(),t._pointerPressed.push(n.pointerId),1!==t._pointerPressed.length)return;i={x:n.clientX,y:n.clientY}}else if(r.type===Gr.POINTERUP){if(e||n.preventDefault(),-1===(a=t._pointerPressed.indexOf(n.pointerId)))return;if(t._pointerPressed.splice(a,1),0!=a)return;i=null,t._offsetX=null,t._offsetY=null}else if(r.type===Gr.POINTERMOVE){if(e||n.preventDefault(),!i)return;var a;if(0!=(a=t._pointerPressed.indexOf(n.pointerId)))return;t._offsetX=n.clientX-i.x,t._offsetY=-(n.clientY-i.y)}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,Gr.POINTERDOWN|Gr.POINTERUP|Gr.POINTERMOVE),this._onLostFocus){var r=this.camera.getEngine().getInputElement();r&&r.addEventListener("blur",this._onLostFocus)}},e.prototype.detachControl=function(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){var e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null}this._pointerPressed.length=0,this._offsetX=null,this._offsetY=null}},e.prototype.checkInputs=function(){if(null!==this._offsetX&&null!==this._offsetY&&(0!==this._offsetX||0!==this._offsetY)){var e=this.camera,t=e._calculateHandednessMultiplier();if(e.cameraRotation.y=t*this._offsetX/this.touchAngularSensibility,this.singleFingerRotate&&1===this._pointerPressed.length||!this.singleFingerRotate&&this._pointerPressed.length>1)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{var i=e._computeLocalCameraSpeed(),r=new V(0,0,0!==this.touchMoveSensibility?i*this._offsetY/this.touchMoveSensibility:0);z.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(V.TransformCoordinates(r,e._cameraRotationMatrix))}}},e.prototype.getClassName=function(){return"FreeCameraTouchInput"},e.prototype.getSimpleName=function(){return"touch"},v([Ie()],e.prototype,"touchAngularSensibility",void 0),v([Ie()],e.prototype,"touchMoveSensibility",void 0),e}();rc.FreeCameraTouchInput=Sc;var xc=function(e){function t(t){var i=e.call(this,t)||this;return i._mouseInput=null,i._mouseWheelInput=null,i}return m(t,e),t.prototype.addKeyboard=function(){return this.add(new yc),this},t.prototype.addMouse=function(e){return void 0===e&&(e=!0),this._mouseInput||(this._mouseInput=new Tc(e),this.add(this._mouseInput)),this},t.prototype.removeMouse=function(){return this._mouseInput&&this.remove(this._mouseInput),this},t.prototype.addMouseWheel=function(){return this._mouseWheelInput||(this._mouseWheelInput=new Ec,this.add(this._mouseWheelInput)),this},t.prototype.removeMouseWheel=function(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this},t.prototype.addTouch=function(){return this.add(new Sc),this},t.prototype.clear=function(){e.prototype.clear.call(this),this._mouseInput=null},t}(nc);xc.prototype.addDeviceOrientation=function(e){return this._deviceOrientationInput||(this._deviceOrientationInput=new Ac,e&&(this._deviceOrientationInput.smoothFactor=e),this.add(this._deviceOrientationInput)),this};var Ac=function(){function e(){var e=this;this._screenOrientationAngle=0,this._screenQuaternion=new G,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new f,this._orientationChanged=function(){e._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,e._screenOrientationAngle=-rr.ToRadians(e._screenOrientationAngle/2),e._screenQuaternion.copyFromFloats(0,Math.sin(e._screenOrientationAngle),0,Math.cos(e._screenOrientationAngle))},this._deviceOrientation=function(t){e.smoothFactor?(e._alpha=null!==t.alpha?rr.SmoothAngleChange(e._alpha,t.alpha,e.smoothFactor):0,e._beta=null!==t.beta?rr.SmoothAngleChange(e._beta,t.beta,e.smoothFactor):0,e._gamma=null!==t.gamma?rr.SmoothAngleChange(e._gamma,t.gamma,e.smoothFactor):0):(e._alpha=null!==t.alpha?t.alpha:0,e._beta=null!==t.beta?t.beta:0,e._gamma=null!==t.gamma?t.gamma:0),null!==t.alpha&&e._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTranform=new G(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}return e.WaitForOrientationChangeAsync=function(e){return new Promise((function(t,i){var r=!1,n=function(){window.removeEventListener("deviceorientation",n),r=!0,t()};e&&setTimeout((function(){r||(window.removeEventListener("deviceorientation",n),i("WaitForOrientationChangeAsync timed out"))}),e),"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((function(e){"granted"==e?window.addEventListener("deviceorientation",n):rr.Warn("Permission not granted.")})).catch((function(e){rr.Error(e)})):window.addEventListener("deviceorientation",n)}))},Object.defineProperty(e.prototype,"camera",{get:function(){return this._camera},set:function(e){var t=this;this._camera=e,null==this._camera||this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new G),this._camera&&this._camera.onDisposeObservable.add((function(){t._onDeviceOrientationChangedObservable.clear()}))},enumerable:!1,configurable:!0}),e.prototype.attachControl=function(){var e=this,t=this.camera.getScene().getEngine().getHostWindow();if(t){var i=function(){t.addEventListener("orientationchange",e._orientationChanged),t.addEventListener("deviceorientation",e._deviceOrientation),e._orientationChanged()};"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((function(e){"granted"===e?i():rr.Warn("Permission not granted.")})).catch((function(e){rr.Error(e)})):i()}},e.prototype.detachControl=function(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0},e.prototype.checkInputs=function(){this._alpha&&(G.RotationYawPitchRollToRef(rr.ToRadians(this._alpha),rr.ToRadians(this._beta),-rr.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)},e.prototype.getClassName=function(){return"FreeCameraDeviceOrientationInput"},e.prototype.getSimpleName=function(){return"deviceOrientation"},e}();rc.FreeCameraDeviceOrientationInput=Ac;var Cc,Rc=function(){function e(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=z.Identity(),this._deltaTransform=V.Zero(),this._vector3=V.Zero(),this._vector2=U.Zero()}return Object.defineProperty(e.prototype,"invertYAxis",{get:function(){return 1!==this._yAxisScale},set:function(e){this._yAxisScale=e?-1:1},enumerable:!1,configurable:!0}),e.prototype.attachControl=function(){var e=this,t=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=t.onGamepadConnectedObservable.add((function(t){t.type!==ac.POSE_ENABLED&&(e.gamepad&&t.type!==ac.XBOX||(e.gamepad=t))})),this._onGamepadDisconnectedObserver=t.onGamepadDisconnectedObservable.add((function(t){e.gamepad===t&&(e.gamepad=null)})),this.gamepad=t.getGamepadByType(ac.XBOX),!this.gamepad&&t.gamepads.length&&(this.gamepad=t.gamepads[0])},e.prototype.detachControl=function(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null},e.prototype.checkInputs=function(){if(this.gamepad&&this.gamepad.leftStick){var e=this.camera,t=this.gamepad.leftStick;0!==this.gamepadMoveSensibility&&(t.x=Math.abs(t.x)>this.deadzoneDelta?t.x/this.gamepadMoveSensibility:0,t.y=Math.abs(t.y)>this.deadzoneDelta?t.y/this.gamepadMoveSensibility:0);var i=this.gamepad.rightStick;i&&0!==this.gamepadAngularSensibility?(i.x=Math.abs(i.x)>this.deadzoneDelta?i.x/this.gamepadAngularSensibility:0,i.y=(Math.abs(i.y)>this.deadzoneDelta?i.y/this.gamepadAngularSensibility:0)*this._yAxisScale):i={x:0,y:0},e.rotationQuaternion?e.rotationQuaternion.toRotationMatrix(this._cameraTransform):z.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);var r=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*r,0,-t.y*r),V.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),e.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(i.y,i.x),e.cameraRotation.addInPlace(this._vector2)}},e.prototype.getClassName=function(){return"FreeCameraGamepadInput"},e.prototype.getSimpleName=function(){return"gamepad"},v([Ie()],e.prototype,"gamepadAngularSensibility",void 0),v([Ie()],e.prototype,"gamepadMoveSensibility",void 0),e}();rc.FreeCameraGamepadInput=Rc,function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(Cc||(Cc={}));var Pc=function(){function e(t,i){var r=this;this._released=!1;var n=g(g({},e._GetDefaultOptions()),i);if(this._leftJoystick=!!t,e._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=Cc.X,this._axisTargetedByUpAndDown=Cc.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new lr,this.deltaPosition=V.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=function(){e._VJCanvasWidth=window.innerWidth,e._VJCanvasHeight=window.innerHeight,e.Canvas&&(e.Canvas.width=e._VJCanvasWidth,e.Canvas.height=e._VJCanvasHeight),e._HalfWidth=e._VJCanvasWidth/2},!e.Canvas){window.addEventListener("resize",this._onResize,!1),e.Canvas=document.createElement("canvas"),e._VJCanvasWidth=window.innerWidth,e._VJCanvasHeight=window.innerHeight,e.Canvas.width=window.innerWidth,e.Canvas.height=window.innerHeight,e.Canvas.style.width="100%",e.Canvas.style.height="100%",e.Canvas.style.position="absolute",e.Canvas.style.backgroundColor="transparent",e.Canvas.style.top="0px",e.Canvas.style.left="0px",e.Canvas.style.zIndex="5",e.Canvas.style.touchAction="none",e.Canvas.setAttribute("touch-action","none");var o=e.Canvas.getContext("2d");if(!o)throw new Error("Unable to create canvas for virtual joystick");e._VJCanvasContext=o,e._VJCanvasContext.strokeStyle="#ffffff",e._VJCanvasContext.lineWidth=2,document.body.appendChild(e.Canvas)}e._HalfWidth=e.Canvas.width/2,this.pressed=!1,this.limitToContainer=n.limitToContainer,this._joystickColor=n.color,this.containerSize=n.containerSize,this.puckSize=n.puckSize,n.position&&this.setPosition(n.position.x,n.position.y),n.puckImage&&this.setPuckImage(n.puckImage),n.containerImage&&this.setContainerImage(n.containerImage),n.alwaysVisible&&e._AlwaysVisibleSticks++,this.alwaysVisible=n.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new U(0,0),this._joystickPreviousPointerPos=new U(0,0),this._joystickPointerStartPos=new U(0,0),this._deltaJoystickVector=new U(0,0),this._onPointerDownHandlerRef=function(e){r._onPointerDown(e)},this._onPointerMoveHandlerRef=function(e){r._onPointerMove(e)},this._onPointerUpHandlerRef=function(e){r._onPointerUp(e)},e.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),e.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),e.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),e.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),e.Canvas.addEventListener("contextmenu",(function(e){e.preventDefault()}),!1),requestAnimationFrame((function(){r._drawVirtualJoystick()}))}return e._GetDefaultOptions=function(){return{puckSize:40,containerSize:60,color:"cyan",puckImage:void 0,containerImage:void 0,position:void 0,alwaysVisible:!1,limitToContainer:!1}},e.prototype.setJoystickSensibility=function(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)},e.prototype._onPointerDown=function(t){t.preventDefault(),(!0===this._leftJoystick?t.clientX<e._HalfWidth:t.clientX>e._HalfWidth)&&this._joystickPointerId<0?(this._joystickPointerId=t.pointerId,this._joystickPosition?(this._joystickPointerStartPos=this._joystickPosition.clone(),this._joystickPointerPos=this._joystickPosition.clone(),this._joystickPreviousPointerPos=this._joystickPosition.clone(),this._onPointerMove(t)):(this._joystickPointerStartPos.x=t.clientX,this._joystickPointerStartPos.y=t.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone()),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(t.pointerId.toString(),t)):e._GlobalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(t.pointerId.toString(),{x:t.clientX,y:t.clientY,prevX:t.clientX,prevY:t.clientY}))},e.prototype._onPointerMove=function(t){if(this._joystickPointerId==t.pointerId){if(this.limitToContainer){var i=new U(t.clientX-this._joystickPointerStartPos.x,t.clientY-this._joystickPointerStartPos.y),r=i.length();r>this.containerSize&&i.scaleInPlace(this.containerSize/r),this._joystickPointerPos.x=this._joystickPointerStartPos.x+i.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+i.y}else this._joystickPointerPos.x=t.clientX,this._joystickPointerPos.y=t.clientY;this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos),0<e._AlwaysVisibleSticks&&(this._leftJoystick?this._joystickPointerPos.x=Math.min(e._HalfWidth,this._joystickPointerPos.x):this._joystickPointerPos.x=Math.max(e._HalfWidth,this._joystickPointerPos.x));var n=(this.reverseLeftRight?-1:1)*this._deltaJoystickVector.x/this._inversedSensibility;switch(this._axisTargetedByLeftAndRight){case Cc.X:this.deltaPosition.x=Math.min(1,Math.max(-1,n));break;case Cc.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,n));break;case Cc.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,n))}var o=(this.reverseUpDown?1:-1)*this._deltaJoystickVector.y/this._inversedSensibility;switch(this._axisTargetedByUpAndDown){case Cc.X:this.deltaPosition.x=Math.min(1,Math.max(-1,o));break;case Cc.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,o));break;case Cc.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,o))}}else{var a=this._touches.get(t.pointerId.toString());a&&(a.x=t.clientX,a.y=t.clientY)}},e.prototype._onPointerUp=function(t){if(this._joystickPointerId==t.pointerId)this._clearPreviousDraw(),this._joystickPointerId=-1,this.pressed=!1;else{var i=this._touches.get(t.pointerId.toString());i&&e._VJCanvasContext.clearRect(i.prevX-44,i.prevY-44,88,88)}this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this._touches.remove(t.pointerId.toString())},e.prototype.setJoystickColor=function(e){this._joystickColor=e},Object.defineProperty(e.prototype,"containerSize",{get:function(){return this._joystickContainerSize},set:function(e){this._joystickContainerSize=e,this._clearContainerSize=~~(2.1*this._joystickContainerSize),this._clearContainerSizeOffset=~~(this._clearContainerSize/2)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"puckSize",{get:function(){return this._joystickPuckSize},set:function(e){this._joystickPuckSize=e,this._clearPuckSize=~~(2.1*this._joystickPuckSize),this._clearPuckSizeOffset=~~(this._clearPuckSize/2)},enumerable:!1,configurable:!0}),e.prototype.clearPosition=function(){this.alwaysVisible=!1,this._joystickPosition=null},Object.defineProperty(e.prototype,"alwaysVisible",{get:function(){return this._alwaysVisible},set:function(t){this._alwaysVisible!==t&&(t&&this._joystickPosition?(e._AlwaysVisibleSticks++,this._alwaysVisible=!0):(e._AlwaysVisibleSticks--,this._alwaysVisible=!1))},enumerable:!1,configurable:!0}),e.prototype.setPosition=function(e,t){this._joystickPointerStartPos&&this._clearPreviousDraw(),this._joystickPosition=new U(e,t)},e.prototype.setActionOnTouch=function(e){this._action=e},e.prototype.setAxisForLeftRight=function(e){switch(e){case Cc.X:case Cc.Y:case Cc.Z:this._axisTargetedByLeftAndRight=e;break;default:this._axisTargetedByLeftAndRight=Cc.X}},e.prototype.setAxisForUpDown=function(e){switch(e){case Cc.X:case Cc.Y:case Cc.Z:this._axisTargetedByUpAndDown=e;break;default:this._axisTargetedByUpAndDown=Cc.Y}},e.prototype._clearPreviousDraw=function(){var t=this._joystickPosition||this._joystickPointerStartPos;e._VJCanvasContext.clearRect(t.x-this._clearContainerSizeOffset,t.y-this._clearContainerSizeOffset,this._clearContainerSize,this._clearContainerSize),e._VJCanvasContext.clearRect(this._joystickPreviousPointerPos.x-this._clearPuckSizeOffset-1,this._joystickPreviousPointerPos.y-this._clearPuckSizeOffset-1,this._clearPuckSize+2,this._clearPuckSize+2)},e.prototype.setContainerImage=function(e){var t=this,i=new Image;i.src=e,i.onload=function(){return t._containerImage=i}},e.prototype.setPuckImage=function(e){var t=this,i=new Image;i.src=e,i.onload=function(){return t._puckImage=i}},e.prototype._drawContainer=function(){var t=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?e._VJCanvasContext.drawImage(this._containerImage,t.x-this.containerSize,t.y-this.containerSize,2*this.containerSize,2*this.containerSize):(e._VJCanvasContext.beginPath(),e._VJCanvasContext.strokeStyle=this._joystickColor,e._VJCanvasContext.lineWidth=2,e._VJCanvasContext.arc(t.x,t.y,this.containerSize,0,2*Math.PI,!0),e._VJCanvasContext.stroke(),e._VJCanvasContext.closePath(),e._VJCanvasContext.beginPath(),e._VJCanvasContext.lineWidth=6,e._VJCanvasContext.strokeStyle=this._joystickColor,e._VJCanvasContext.arc(t.x,t.y,this.puckSize,0,2*Math.PI,!0),e._VJCanvasContext.stroke(),e._VJCanvasContext.closePath())},e.prototype._drawPuck=function(){this._puckImage?e._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,2*this.puckSize,2*this.puckSize):(e._VJCanvasContext.beginPath(),e._VJCanvasContext.strokeStyle=this._joystickColor,e._VJCanvasContext.lineWidth=2,e._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,2*Math.PI,!0),e._VJCanvasContext.stroke(),e._VJCanvasContext.closePath())},e.prototype._drawVirtualJoystick=function(){var t=this;this._released||(this.alwaysVisible&&this._drawContainer(),this.pressed&&this._touches.forEach((function(i,r){r.pointerId===t._joystickPointerId?(t.alwaysVisible||t._drawContainer(),t._drawPuck(),t._joystickPreviousPointerPos=t._joystickPointerPos.clone()):(e._VJCanvasContext.clearRect(r.prevX-44,r.prevY-44,88,88),e._VJCanvasContext.beginPath(),e._VJCanvasContext.fillStyle="white",e._VJCanvasContext.beginPath(),e._VJCanvasContext.strokeStyle="red",e._VJCanvasContext.lineWidth=6,e._VJCanvasContext.arc(r.x,r.y,40,0,2*Math.PI,!0),e._VJCanvasContext.stroke(),e._VJCanvasContext.closePath(),r.prevX=r.x,r.prevY=r.y)})),requestAnimationFrame((function(){t._drawVirtualJoystick()})))},e.prototype.releaseCanvas=function(){e.Canvas&&(e.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),e.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),e.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),e.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(e.Canvas),e.Canvas=null),this._released=!0},e._GlobalJoystickIndex=0,e._AlwaysVisibleSticks=0,e}();xc.prototype.addVirtualJoystick=function(){return this.add(new Ic),this};var Ic=function(){function e(){}return e.prototype.getLeftJoystick=function(){return this._leftjoystick},e.prototype.getRightJoystick=function(){return this._rightjoystick},e.prototype.checkInputs=function(){if(this._leftjoystick){var e=this.camera,t=50*e._computeLocalCameraSpeed(),i=z.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),r=V.TransformCoordinates(new V(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(r),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}},e.prototype.attachControl=function(){this._leftjoystick=new Pc(!0),this._leftjoystick.setAxisForUpDown(Cc.Z),this._leftjoystick.setAxisForLeftRight(Cc.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new Pc(!1),this._rightjoystick.setAxisForUpDown(Cc.X),this._rightjoystick.setAxisForLeftRight(Cc.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")},e.prototype.detachControl=function(){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()},e.prototype.getClassName=function(){return"FreeCameraVirtualJoystickInput"},e.prototype.getSimpleName=function(){return"virtualJoystick"},e}();rc.FreeCameraVirtualJoystickInput=Ic,qe.AddNodeConstructor("TargetCamera",(function(e,t){return function(){return new Mc(e,V.Zero(),t)}}));var Mc=function(e){function t(t,i,r,n){void 0===n&&(n=!0);var o=e.call(this,t,i,r,n)||this;return o._tmpUpVector=V.Zero(),o._tmpTargetVector=V.Zero(),o.cameraDirection=new V(0,0,0),o.cameraRotation=new U(0,0),o.ignoreParentScaling=!1,o.updateUpVectorFromRotation=!1,o._tmpQuaternion=new G,o.rotation=new V(0,0,0),o.speed=2,o.noRotationConstraint=!1,o.invertRotation=!1,o.inverseRotationSpeed=.2,o.lockedTarget=null,o._currentTarget=V.Zero(),o._initialFocalDistance=1,o._viewMatrix=z.Zero(),o._camMatrix=z.Zero(),o._cameraTransformMatrix=z.Zero(),o._cameraRotationMatrix=z.Zero(),o._referencePoint=new V(0,0,1),o._transformedReferencePoint=V.Zero(),o._deferredPositionUpdate=new V,o._deferredRotationQuaternionUpdate=new G,o._deferredRotationUpdate=new V,o._deferredUpdated=!1,o._deferOnly=!1,o._defaultUp=V.Up(),o._cachedRotationZ=0,o._cachedQuaternionRotationZ=0,o}return m(t,e),t.prototype.getFrontPosition=function(e){this.getWorldMatrix();var t=this.getTarget().subtract(this.position);return t.normalize(),t.scaleInPlace(e),this.globalPosition.add(t)},t.prototype._getLockedTargetPosition=function(){if(!this.lockedTarget)return null;if(this.lockedTarget.absolutePosition){var e=this.lockedTarget;e.computeWorldMatrix().getTranslationToRef(e.absolutePosition)}return this.lockedTarget.absolutePosition||this.lockedTarget},t.prototype.storeState=function(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),e.prototype.storeState.call(this)},t.prototype._restoreStateValues=function(){return!!e.prototype._restoreStateValues.call(this)&&(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0)},t.prototype._initCache=function(){e.prototype._initCache.call(this),this._cache.lockedTarget=new V(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new V(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new G(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)},t.prototype._updateCache=function(t){t||e.prototype._updateCache.call(this);var i=this._getLockedTargetPosition();i?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(i):this._cache.lockedTarget=i.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)},t.prototype._isSynchronizedViewMatrix=function(){if(!e.prototype._isSynchronizedViewMatrix.call(this))return!1;var t=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(t):!t)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))},t.prototype._computeLocalCameraSpeed=function(){var e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(100*e.getFps()))},t.prototype.setTarget=function(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=A),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),z.LookAtLHToRef(this.position,e,this._defaultUp,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);var t=e.subtract(this.position);t.x>=0?this.rotation.y=-Math.atan(t.z/t.x)+Math.PI/2:this.rotation.y=-Math.atan(t.z/t.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&G.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)},Object.defineProperty(t.prototype,"target",{get:function(){return this.getTarget()},set:function(e){this.setTarget(e)},enumerable:!1,configurable:!0}),t.prototype.getTarget=function(){return this._currentTarget},t.prototype._decideIfNeedsToMove=function(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},t.prototype._updatePosition=function(){if(this.parent)return this.parent.getWorldMatrix().invertToRef(H.Matrix[0]),V.TransformNormalToRef(this.cameraDirection,H.Matrix[0],H.Vector3[0]),this._deferredPositionUpdate.addInPlace(H.Vector3[0]),void(this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate));this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)},t.prototype._checkInputs=function(){var t=this.invertRotation?-this.inverseRotationSpeed:1,i=this._decideIfNeedsToMove(),r=this.cameraRotation.x||this.cameraRotation.y;if(this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),i&&this._updatePosition(),r){if(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*t,this._deferredRotationUpdate.y+=this.cameraRotation.y*t,!this.noRotationConstraint){var n=1.570796;this._deferredRotationUpdate.x>n&&(this._deferredRotationUpdate.x=n),this._deferredRotationUpdate.x<-n&&(this._deferredRotationUpdate.x=-n)}this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(G.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate))}i&&(Math.abs(this.cameraDirection.x)<this.speed*A&&(this.cameraDirection.x=0),Math.abs(this.cameraDirection.y)<this.speed*A&&(this.cameraDirection.y=0),Math.abs(this.cameraDirection.z)<this.speed*A&&(this.cameraDirection.z=0),this.cameraDirection.scaleInPlace(this.inertia)),r&&(Math.abs(this.cameraRotation.x)<this.speed*A&&(this.cameraRotation.x=0),Math.abs(this.cameraRotation.y)<this.speed*A&&(this.cameraRotation.y=0),this.cameraRotation.scaleInPlace(this.inertia)),e.prototype._checkInputs.call(this)},t.prototype._updateCameraRotationMatrix=function(){this.rotationQuaternion?this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix):z.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this._cameraRotationMatrix)},t.prototype._rotateUpVectorWithCameraRotationMatrix=function(){return V.TransformNormalToRef(this._defaultUp,this._cameraRotationMatrix,this.upVector),this},t.prototype._getViewMatrix=function(){return this.lockedTarget&&this.setTarget(this._getLockedTargetPosition()),this._updateCameraRotationMatrix(),this.rotationQuaternion&&this._cachedQuaternionRotationZ!=this.rotationQuaternion.z?(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedQuaternionRotationZ=this.rotationQuaternion.z):this._cachedRotationZ!==this.rotation.z&&(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedRotationZ=this.rotation.z),V.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),this.updateUpVectorFromRotation&&(this.rotationQuaternion?_n.Y.rotateByQuaternionToRef(this.rotationQuaternion,this.upVector):(G.FromEulerVectorToRef(this.rotation,this._tmpQuaternion),_n.Y.rotateByQuaternionToRef(this._tmpQuaternion,this.upVector))),this._computeViewMatrix(this.position,this._currentTarget,this.upVector),this._viewMatrix},t.prototype._computeViewMatrix=function(e,t,i){if(this.ignoreParentScaling){if(this.parent){var r=this.parent.getWorldMatrix();V.TransformCoordinatesToRef(e,r,this._globalPosition),V.TransformCoordinatesToRef(t,r,this._tmpTargetVector),V.TransformNormalToRef(i,r,this._tmpUpVector),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e),this._tmpTargetVector.copyFrom(t),this._tmpUpVector.copyFrom(i);this.getScene().useRightHandedSystem?z.LookAtRHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix):z.LookAtLHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix)}else this.getScene().useRightHandedSystem?z.LookAtRHToRef(e,t,i,this._viewMatrix):z.LookAtLHToRef(e,t,i,this._viewMatrix),this.parent?(r=this.parent.getWorldMatrix(),this._viewMatrix.invert(),this._viewMatrix.multiplyToRef(r,this._viewMatrix),this._viewMatrix.getTranslationToRef(this._globalPosition),this._viewMatrix.invert(),this._markSyncedWithParent()):this._globalPosition.copyFrom(e)},t.prototype.createRigCamera=function(e,i){if(this.cameraRigMode!==$n.RIG_MODE_NONE){var r=new t(e,this.position.clone(),this.getScene());return r.isRigCamera=!0,r.rigParent=this,this.cameraRigMode===$n.RIG_MODE_VR&&(this.rotationQuaternion||(this.rotationQuaternion=new G),r._cameraRigParams={},r.rotationQuaternion=new G),r.mode=this.mode,r.orthoLeft=this.orthoLeft,r.orthoRight=this.orthoRight,r.orthoTop=this.orthoTop,r.orthoBottom=this.orthoBottom,r}return null},t.prototype._updateRigCameras=function(){var t=this._rigCameras[0],i=this._rigCameras[1];switch(this.computeWorldMatrix(),this.cameraRigMode){case $n.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case $n.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case $n.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case $n.RIG_MODE_STEREOSCOPIC_OVERUNDER:case $n.RIG_MODE_STEREOSCOPIC_INTERLACED:var r=this.cameraRigMode===$n.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?1:-1,n=this.cameraRigMode===$n.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?-1:1;this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*r,t),this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*n,i);break;case $n.RIG_MODE_VR:t.rotationQuaternion?(t.rotationQuaternion.copyFrom(this.rotationQuaternion),i.rotationQuaternion.copyFrom(this.rotationQuaternion)):(t.rotation.copyFrom(this.rotation),i.rotation.copyFrom(this.rotation)),t.position.copyFrom(this.position),i.position.copyFrom(this.position)}e.prototype._updateRigCameras.call(this)},t.prototype._getRigCamPositionAndTarget=function(e,i){this.getTarget().subtractToRef(this.position,t._TargetFocalPoint),t._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);var r=t._TargetFocalPoint.addInPlace(this.position);z.TranslationToRef(-r.x,-r.y,-r.z,t._TargetTransformMatrix),t._TargetTransformMatrix.multiplyToRef(z.RotationAxis(i.upVector,e),t._RigCamTransformMatrix),z.TranslationToRef(r.x,r.y,r.z,t._TargetTransformMatrix),t._RigCamTransformMatrix.multiplyToRef(t._TargetTransformMatrix,t._RigCamTransformMatrix),V.TransformCoordinatesToRef(this.position,t._RigCamTransformMatrix,i.position),i.setTarget(r)},t.prototype.getClassName=function(){return"TargetCamera"},t._RigCamTransformMatrix=new z,t._TargetTransformMatrix=new z,t._TargetFocalPoint=new V,v([Fe()],t.prototype,"rotation",void 0),v([Ie()],t.prototype,"speed",void 0),v([Le("lockedTargetId")],t.prototype,"lockedTarget",void 0),t}($n),Oc=function(e){function t(t,i,r,n){void 0===n&&(n=!0);var o=e.call(this,t,i,r,n)||this;return o.ellipsoid=new V(.5,1,.5),o.ellipsoidOffset=new V(0,0,0),o.checkCollisions=!1,o.applyGravity=!1,o._needMoveForGravity=!1,o._oldPosition=V.Zero(),o._diffPosition=V.Zero(),o._newPosition=V.Zero(),o._collisionMask=-1,o._onCollisionPositionChange=function(e,t,i){void 0===i&&(i=null),o._newPosition.copyFrom(t),o._newPosition.subtractToRef(o._oldPosition,o._diffPosition),o._diffPosition.length()>Do.CollisionsEpsilon&&(o.position.addToRef(o._diffPosition,o._deferredPositionUpdate),o._deferOnly?o._deferredUpdated=!0:o.position.copyFrom(o._deferredPositionUpdate),o.onCollide&&i&&o.onCollide(i))},o.inputs=new xc(o),o.inputs.addKeyboard().addMouse(),o}return m(t,e),Object.defineProperty(t.prototype,"angularSensibility",{get:function(){var e=this.inputs.attached.mouse;return e?e.angularSensibility:0},set:function(e){var t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysUpward",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUpward:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUpward=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysDownward",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDownward:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDownward=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysRotateLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRotateLeft:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRotateLeft=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysRotateRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRotateRight:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRotateRight=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysRotateUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRotateUp:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRotateUp=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysRotateDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRotateDown:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRotateDown=e)},enumerable:!1,configurable:!0}),t.prototype.attachControl=function(e,t){t=rr.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)},t.prototype.detachControl=function(){this.inputs.detachElement(),this.cameraDirection=new V(0,0,0),this.cameraRotation=new U(0,0)},Object.defineProperty(t.prototype,"collisionMask",{get:function(){return this._collisionMask},set:function(e){this._collisionMask=isNaN(e)?-1:e},enumerable:!1,configurable:!0}),t.prototype._collideWithWorld=function(e){(this.parent?V.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);var t=this.getScene().collisionCoordinator;this._collider||(this._collider=t.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;var i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),t.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)},t.prototype._checkInputs=function(){this._localDirection||(this._localDirection=V.Zero(),this._transformedDirection=V.Zero()),this.inputs.checkInputs(),e.prototype._checkInputs.call(this)},Object.defineProperty(t.prototype,"needMoveForGravity",{get:function(){return this._needMoveForGravity},set:function(e){this._needMoveForGravity=e},enumerable:!1,configurable:!0}),t.prototype._decideIfNeedsToMove=function(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},t.prototype._updatePosition=function(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):e.prototype._updatePosition.call(this)},t.prototype.dispose=function(){this.inputs.clear(),e.prototype.dispose.call(this)},t.prototype.getClassName=function(){return"FreeCamera"},v([Fe()],t.prototype,"ellipsoid",void 0),v([Fe()],t.prototype,"ellipsoidOffset",void 0),v([Ie()],t.prototype,"checkCollisions",void 0),v([Ie()],t.prototype,"applyGravity",void 0),t}(Mc);a("BABYLON.FreeCamera",Oc),qe.AddNodeConstructor("TouchCamera",(function(e,t){return function(){return new Dc(e,V.Zero(),t)}}));var Dc=function(e){function t(t,i,r){var n=e.call(this,t,i,r)||this;return n.inputs.addTouch(),n._setupInputs(),n}return m(t,e),Object.defineProperty(t.prototype,"touchAngularSensibility",{get:function(){var e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0},set:function(e){var t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"touchMoveSensibility",{get:function(){var e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0},set:function(e){var t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"TouchCamera"},t.prototype._setupInputs=function(){var e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!1:e.allowMouse=!0},t}(Oc);qe.AddNodeConstructor("ArcRotateCamera",(function(e,t){return function(){return new Nc(e,0,0,1,V.Zero(),t)}}));var Nc=function(e){function t(t,i,r,n,o,a,s){void 0===s&&(s=!0);var l=e.call(this,t,V.Zero(),a,s)||this;return l.inertialAlphaOffset=0,l.inertialBetaOffset=0,l.inertialRadiusOffset=0,l.lowerAlphaLimit=null,l.upperAlphaLimit=null,l.lowerBetaLimit=.01,l.upperBetaLimit=Math.PI-.01,l.lowerRadiusLimit=null,l.upperRadiusLimit=null,l.inertialPanningX=0,l.inertialPanningY=0,l.pinchToPanMaxDistance=20,l.panningDistanceLimit=null,l.panningOriginTarget=V.Zero(),l.panningInertia=.9,l.zoomOnFactor=1,l.targetScreenOffset=U.Zero(),l.allowUpsideDown=!0,l.useInputToRestoreState=!0,l._viewMatrix=new z,l.panningAxis=new V(1,1,0),l._transformedDirection=new V,l.mapPanning=!1,l.onMeshTargetChangedObservable=new f,l.checkCollisions=!1,l.collisionRadius=new V(.5,.5,.5),l._previousPosition=V.Zero(),l._collisionVelocity=V.Zero(),l._newPosition=V.Zero(),l._computationVector=V.Zero(),l._onCollisionPositionChange=function(e,t,i){void 0===i&&(i=null),i?(l.setPosition(t),l.onCollide&&l.onCollide(i)):l._previousPosition.copyFrom(l._position);var r=Math.cos(l.alpha),n=Math.sin(l.alpha),o=Math.cos(l.beta),a=Math.sin(l.beta);0===a&&(a=1e-4);var s=l._getTargetPosition();l._computationVector.copyFromFloats(l.radius*r*a,l.radius*o,l.radius*n*a),s.addToRef(l._computationVector,l._newPosition),l._position.copyFrom(l._newPosition);var c=l.upVector;l.allowUpsideDown&&l.beta<0&&(c=(c=c.clone()).negate()),l._computeViewMatrix(l._position,s,c),l._viewMatrix.addAtIndex(12,l.targetScreenOffset.x),l._viewMatrix.addAtIndex(13,l.targetScreenOffset.y),l._collisionTriggered=!1},l._target=V.Zero(),o&&l.setTarget(o),l.alpha=i,l.beta=r,l.radius=n,l.getViewMatrix(),l.inputs=new dc(l),l.inputs.addKeyboard().addMouseWheel().addPointers(),l}return m(t,e),Object.defineProperty(t.prototype,"target",{get:function(){return this._target},set:function(e){this.setTarget(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"targetHost",{get:function(){return this._targetHost},set:function(e){e&&this.setTarget(e)},enumerable:!1,configurable:!0}),t.prototype.getTarget=function(){return this.target},Object.defineProperty(t.prototype,"position",{get:function(){return this._position},set:function(e){this.setPosition(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"upVector",{get:function(){return this._upVector},set:function(e){this._upToYMatrix||(this._yToUpMatrix=new z,this._upToYMatrix=new z,this._upVector=V.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()},enumerable:!1,configurable:!0}),t.prototype.setMatUp=function(){z.RotationAlignToRef(V.UpReadOnly,this._upVector,this._yToUpMatrix),z.RotationAlignToRef(this._upVector,V.UpReadOnly,this._upToYMatrix)},Object.defineProperty(t.prototype,"angularSensibilityX",{get:function(){var e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"angularSensibilityY",{get:function(){var e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"pinchPrecision",{get:function(){var e=this.inputs.attached.pointers;return e?e.pinchPrecision:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"pinchDeltaPercentage",{get:function(){var e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"useNaturalPinchZoom",{get:function(){var e=this.inputs.attached.pointers;return!!e&&e.useNaturalPinchZoom},set:function(e){var t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"panningSensibility",{get:function(){var e=this.inputs.attached.pointers;return e?e.panningSensibility:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"wheelPrecision",{get:function(){var e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0},set:function(e){var t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"zoomToMouseLocation",{get:function(){var e=this.inputs.attached.mousewheel;return!!e&&e.zoomToMouseLocation},set:function(e){var t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"wheelDeltaPercentage",{get:function(){var e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0},set:function(e){var t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"bouncingBehavior",{get:function(){return this._bouncingBehavior},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"useBouncingBehavior",{get:function(){return null!=this._bouncingBehavior},set:function(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new as,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"framingBehavior",{get:function(){return this._framingBehavior},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"useFramingBehavior",{get:function(){return null!=this._framingBehavior},set:function(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new ss,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"autoRotationBehavior",{get:function(){return this._autoRotationBehavior},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"useAutoRotationBehavior",{get:function(){return null!=this._autoRotationBehavior},set:function(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new os,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))},enumerable:!1,configurable:!0}),t.prototype._initCache=function(){e.prototype._initCache.call(this),this._cache._target=new V(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=U.Zero()},t.prototype._updateCache=function(t){t||e.prototype._updateCache.call(this),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)},t.prototype._getTargetPosition=function(){if(this._targetHost&&this._targetHost.getAbsolutePosition){var e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}return this._getLockedTargetPosition()||this._target},t.prototype.storeState=function(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),e.prototype.storeState.call(this)},t.prototype._restoreStateValues=function(){return!!e.prototype._restoreStateValues.call(this)&&(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)},t.prototype._isSynchronizedViewMatrix=function(){return!!e.prototype._isSynchronizedViewMatrix.call(this)&&this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset)},t.prototype.attachControl=function(e,t,i,r){var n=this;void 0===i&&(i=!0),void 0===r&&(r=2);var o=arguments;t=rr.BackCompatCameraNoPreventDefault(o),this._useCtrlForPanning=i,this._panningMouseButton=r,"boolean"==typeof o[0]&&(o.length>1&&(this._useCtrlForPanning=o[1]),o.length>2&&(this._panningMouseButton=o[2])),this.inputs.attachElement(t),this._reset=function(){n.inertialAlphaOffset=0,n.inertialBetaOffset=0,n.inertialRadiusOffset=0,n.inertialPanningX=0,n.inertialPanningY=0}},t.prototype.detachControl=function(){this.inputs.detachElement(),this._reset&&this._reset()},t.prototype._checkInputs=function(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){var t=this.invertRotation?-1:1,i=this._calculateHandednessMultiplier(),r=this.inertialAlphaOffset*i;this.beta<0&&(r*=-1),this.alpha+=r*t,this.beta+=this.inertialBetaOffset*t,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)<A&&(this.inertialAlphaOffset=0),Math.abs(this.inertialBetaOffset)<A&&(this.inertialBetaOffset=0),Math.abs(this.inertialRadiusOffset)<this.speed*A&&(this.inertialRadiusOffset=0)}if(0!==this.inertialPanningX||0!==this.inertialPanningY){var n=new V(this.inertialPanningX,this.inertialPanningY,this.inertialPanningY);if(this._viewMatrix.invertToRef(this._cameraTransformMatrix),n.multiplyInPlace(this.panningAxis),V.TransformNormalToRef(n,this._cameraTransformMatrix,this._transformedDirection),this.mapPanning){var o=this.upVector,a=V.CrossToRef(this._transformedDirection,o,this._transformedDirection);V.CrossToRef(o,a,this._transformedDirection)}else this.panningAxis.y||(this._transformedDirection.y=0);if(!this._targetHost)if(this.panningDistanceLimit)this._transformedDirection.addInPlace(this._target),V.DistanceSquared(this._transformedDirection,this.panningOriginTarget)<=this.panningDistanceLimit*this.panningDistanceLimit&&this._target.copyFrom(this._transformedDirection);else{if(this.parent){var s=H.Matrix[0];this.parent.getWorldMatrix().getRotationMatrixToRef(s),s.transposeToRef(s),V.TransformCoordinatesToRef(this._transformedDirection,s,this._transformedDirection)}this._target.addInPlace(this._transformedDirection)}this.inertialPanningX*=this.panningInertia,this.inertialPanningY*=this.panningInertia,Math.abs(this.inertialPanningX)<this.speed*A&&(this.inertialPanningX=0),Math.abs(this.inertialPanningY)<this.speed*A&&(this.inertialPanningY=0)}this._checkLimits(),e.prototype._checkInputs.call(this)}},t.prototype._checkLimits=function(){null===this.lowerBetaLimit||void 0===this.lowerBetaLimit?this.allowUpsideDown&&this.beta>Math.PI&&(this.beta=this.beta-2*Math.PI):this.beta<this.lowerBetaLimit&&(this.beta=this.lowerBetaLimit),null===this.upperBetaLimit||void 0===this.upperBetaLimit?this.allowUpsideDown&&this.beta<-Math.PI&&(this.beta=this.beta+2*Math.PI):this.beta>this.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alpha<this.lowerAlphaLimit&&(this.alpha=this.lowerAlphaLimit),null!==this.upperAlphaLimit&&this.alpha>this.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit,this.inertialRadiusOffset=0),null!==this.upperRadiusLimit&&this.radius>this.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)},t.prototype.rebuildAnglesAndRadius=function(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||V.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);var e=this.alpha;0===this._computationVector.x&&0===this._computationVector.z?this.alpha=Math.PI/2:this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha);var t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=2*t*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()},t.prototype.setPosition=function(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())},t.prototype.setTarget=function(e,t,i,r){var n;if(void 0===t&&(t=!1),void 0===i&&(i=!1),void 0===r&&(r=!1),r=null!==(n=this.overrideCloneAlphaBetaRadius)&&void 0!==n?n:r,e.computeWorldMatrix)t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{var o=e,a=this._getTargetPosition();if(a&&!i&&a.equals(o))return;this._targetHost=null,this._target=o,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}r||this.rebuildAnglesAndRadius()},t.prototype._getViewMatrix=function(){var e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta),r=Math.sin(this.beta);0===r&&(r=1e-4),0===this.radius&&(this.radius=1e-4);var n=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*r,this.radius*i,this.radius*t*r),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||V.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),n.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){var o=this.getScene().collisionCoordinator;this._collider||(this._collider=o.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,o.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);var a=this.upVector;this.allowUpsideDown&&r<0&&(a=a.negate()),this._computeViewMatrix(this._position,n,a),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=n,this._viewMatrix},t.prototype.zoomOn=function(e,t){void 0===t&&(t=!1),e=e||this.getScene().meshes;var i=Fa.MinMax(e),r=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);r=Math.max(Math.min(r,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=r*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:r},t)},t.prototype.focusOn=function(e,t){var i,r;if(void 0===t&&(t=!1),void 0===e.min){var n=e||this.getScene().meshes;i=Fa.MinMax(n),r=V.Distance(i.min,i.max)}else i=e,r=e.distance;this._target=Fa.Center(i),t||(this.maxZ=2*r)},t.prototype.createRigCamera=function(e,i){var r=0;switch(this.cameraRigMode){case $n.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case $n.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case $n.RIG_MODE_STEREOSCOPIC_OVERUNDER:case $n.RIG_MODE_STEREOSCOPIC_INTERLACED:case $n.RIG_MODE_VR:r=this._cameraRigParams.stereoHalfAngle*(0===i?1:-1);break;case $n.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:r=this._cameraRigParams.stereoHalfAngle*(0===i?-1:1)}var n=new t(e,this.alpha+r,this.beta,this.radius,this._target,this.getScene());return n._cameraRigParams={},n.isRigCamera=!0,n.rigParent=this,n.upVector=this.upVector,n.mode=this.mode,n.orthoLeft=this.orthoLeft,n.orthoRight=this.orthoRight,n.orthoBottom=this.orthoBottom,n.orthoTop=this.orthoTop,n},t.prototype._updateRigCameras=function(){var t=this._rigCameras[0],i=this._rigCameras[1];switch(t.beta=i.beta=this.beta,this.cameraRigMode){case $n.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case $n.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case $n.RIG_MODE_STEREOSCOPIC_OVERUNDER:case $n.RIG_MODE_STEREOSCOPIC_INTERLACED:case $n.RIG_MODE_VR:t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,i.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case $n.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,i.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}e.prototype._updateRigCameras.call(this)},t.prototype._calculateLowerRadiusFromModelBoundingSphere=function(e,t,i){void 0===i&&(i=1);var r=V.Distance(e,t),n=this.getScene().getEngine().getAspectRatio(this),o=Math.tan(this.fov/2),a=o*n,s=.5*r*i,l=s*Math.sqrt(1+1/(a*a)),c=s*Math.sqrt(1+1/(o*o));return Math.max(l,c)},t.prototype.dispose=function(){this.inputs.clear(),e.prototype.dispose.call(this)},t.prototype.getClassName=function(){return"ArcRotateCamera"},v([Ie()],t.prototype,"alpha",void 0),v([Ie()],t.prototype,"beta",void 0),v([Ie()],t.prototype,"radius",void 0),v([Ie()],t.prototype,"overrideCloneAlphaBetaRadius",void 0),v([Fe("target")],t.prototype,"_target",void 0),v([Le("targetHost")],t.prototype,"_targetHost",void 0),v([Ie()],t.prototype,"inertialAlphaOffset",void 0),v([Ie()],t.prototype,"inertialBetaOffset",void 0),v([Ie()],t.prototype,"inertialRadiusOffset",void 0),v([Ie()],t.prototype,"lowerAlphaLimit",void 0),v([Ie()],t.prototype,"upperAlphaLimit",void 0),v([Ie()],t.prototype,"lowerBetaLimit",void 0),v([Ie()],t.prototype,"upperBetaLimit",void 0),v([Ie()],t.prototype,"lowerRadiusLimit",void 0),v([Ie()],t.prototype,"upperRadiusLimit",void 0),v([Ie()],t.prototype,"inertialPanningX",void 0),v([Ie()],t.prototype,"inertialPanningY",void 0),v([Ie()],t.prototype,"pinchToPanMaxDistance",void 0),v([Ie()],t.prototype,"panningDistanceLimit",void 0),v([Fe()],t.prototype,"panningOriginTarget",void 0),v([Ie()],t.prototype,"panningInertia",void 0),v([Ie()],t.prototype,"zoomToMouseLocation",null),v([Ie()],t.prototype,"zoomOnFactor",void 0),v([Ne()],t.prototype,"targetScreenOffset",void 0),v([Ie()],t.prototype,"allowUpsideDown",void 0),v([Ie()],t.prototype,"useInputToRestoreState",void 0),t}(Mc);a("BABYLON.ArcRotateCamera",Nc),qe.AddNodeConstructor("DeviceOrientationCamera",(function(e,t){return function(){return new Fc(e,V.Zero(),t)}}));var Fc=function(e){function t(t,i,r){var n=e.call(this,t,i,r)||this;return n._tmpDragQuaternion=new G,n._disablePointerInputWhenUsingDeviceOrientation=!0,n._dragFactor=0,n._quaternionCache=new G,n.inputs.addDeviceOrientation(),n.inputs._deviceOrientationInput&&n.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce((function(){n._disablePointerInputWhenUsingDeviceOrientation&&n.inputs._mouseInput&&(n.inputs._mouseInput._allowCameraRotation=!1,n.inputs._mouseInput.onPointerMovedObservable.add((function(e){0!=n._dragFactor&&(n._initialQuaternion||(n._initialQuaternion=new G),G.FromEulerAnglesToRef(0,e.offsetX*n._dragFactor,0,n._tmpDragQuaternion),n._initialQuaternion.multiplyToRef(n._tmpDragQuaternion,n._initialQuaternion))})))})),n}return m(t,e),Object.defineProperty(t.prototype,"disablePointerInputWhenUsingDeviceOrientation",{get:function(){return this._disablePointerInputWhenUsingDeviceOrientation},set:function(e){this._disablePointerInputWhenUsingDeviceOrientation=e},enumerable:!1,configurable:!0}),t.prototype.enableHorizontalDragging=function(e){void 0===e&&(e=1/300),this._dragFactor=e},t.prototype.getClassName=function(){return"DeviceOrientationCamera"},t.prototype._checkInputs=function(){e.prototype._checkInputs.call(this),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)},t.prototype.resetToCurrentRotation=function(e){var t=this;void 0===e&&(e=_n.Y),this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new G),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach((function(i){e[i]?t._initialQuaternion[i]*=-1:t._initialQuaternion[i]=0})),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))},t}(Oc),Lc=function(e){function t(t){return e.call(this,t)||this}return m(t,e),t.prototype.addKeyboard=function(){return this.add(new fc),this},t.prototype.addMouse=function(){return this.add(new _c),this},t}(nc),wc=function(e){function t(t,i,r,n){void 0===n&&(n=!0);var o=e.call(this,t,i,r,n)||this;return o.ellipsoid=new V(1,1,1),o.ellipsoidOffset=new V(0,0,0),o.checkCollisions=!1,o.applyGravity=!1,o.cameraDirection=V.Zero(),o._trackRoll=0,o.rollCorrect=100,o.bankedTurn=!1,o.bankedTurnLimit=Math.PI/2,o.bankedTurnMultiplier=1,o._needMoveForGravity=!1,o._oldPosition=V.Zero(),o._diffPosition=V.Zero(),o._newPosition=V.Zero(),o._collisionMask=-1,o._onCollisionPositionChange=function(e,t,i){var r;void 0===i&&(i=null),r=t,o._newPosition.copyFrom(r),o._newPosition.subtractToRef(o._oldPosition,o._diffPosition),o._diffPosition.length()>Do.CollisionsEpsilon&&(o.position.addInPlace(o._diffPosition),o.onCollide&&i&&o.onCollide(i))},o.inputs=new Lc(o),o.inputs.addKeyboard().addMouse(),o}return m(t,e),Object.defineProperty(t.prototype,"angularSensibility",{get:function(){var e=this.inputs.attached.mouse;return e?e.angularSensibility:0},set:function(e){var t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysForward",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysForward:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysForward=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysBackward",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysBackward:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!1,configurable:!0}),t.prototype.attachControl=function(e,t){t=rr.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)},t.prototype.detachControl=function(){this.inputs.detachElement(),this.cameraDirection=new V(0,0,0)},Object.defineProperty(t.prototype,"collisionMask",{get:function(){return this._collisionMask},set:function(e){this._collisionMask=isNaN(e)?-1:e},enumerable:!1,configurable:!0}),t.prototype._collideWithWorld=function(e){(this.parent?V.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);var t=this.getScene().collisionCoordinator;this._collider||(this._collider=t.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;var i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),t.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)},t.prototype._checkInputs=function(){this._localDirection||(this._localDirection=V.Zero(),this._transformedDirection=V.Zero()),this.inputs.checkInputs(),e.prototype._checkInputs.call(this)},Object.defineProperty(t.prototype,"needMoveForGravity",{get:function(){return this._needMoveForGravity},set:function(e){this._needMoveForGravity=e},enumerable:!1,configurable:!0}),t.prototype._decideIfNeedsToMove=function(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0},t.prototype._updatePosition=function(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):e.prototype._updatePosition.call(this)},t.prototype.restoreRoll=function(e){var t=this._trackRoll,i=t-this.rotation.z;Math.abs(i)>=.001&&(this.rotation.z+=i/e,Math.abs(t-this.rotation.z)<=.001&&(this.rotation.z=t))},t.prototype.dispose=function(){this.inputs.clear(),e.prototype.dispose.call(this)},t.prototype.getClassName=function(){return"FlyCamera"},v([Fe()],t.prototype,"ellipsoid",void 0),v([Fe()],t.prototype,"ellipsoidOffset",void 0),v([Ie()],t.prototype,"checkCollisions",void 0),v([Ie()],t.prototype,"applyGravity",void 0),t}(Mc);a("BABYLON.FlyCamera",wc);var Bc=function(e){function t(t){return e.call(this,t)||this}return m(t,e),t.prototype.addKeyboard=function(){return this.add(new mc),this},t.prototype.addMouseWheel=function(){return this.add(new gc),this},t.prototype.addPointers=function(){return this.add(new vc),this},t.prototype.addVRDeviceOrientation=function(){return ae.Warn("DeviceOrientation support not yet implemented for FollowCamera."),this},t}(nc);qe.AddNodeConstructor("FollowCamera",(function(e,t){return function(){return new kc(e,V.Zero(),t)}})),qe.AddNodeConstructor("ArcFollowCamera",(function(e,t){return function(){return new Gc(e,0,0,1,null,t)}}));var Uc,Vc,kc=function(e){function t(t,i,r,n){void 0===n&&(n=null);var o=e.call(this,t,i,r)||this;return o.radius=12,o.lowerRadiusLimit=null,o.upperRadiusLimit=null,o.rotationOffset=0,o.lowerRotationOffsetLimit=null,o.upperRotationOffsetLimit=null,o.heightOffset=4,o.lowerHeightOffsetLimit=null,o.upperHeightOffsetLimit=null,o.cameraAcceleration=.05,o.maxCameraSpeed=20,o.lockedTarget=n,o.inputs=new Bc(o),o.inputs.addKeyboard().addMouseWheel().addPointers(),o}return m(t,e),t.prototype._follow=function(e){if(e){var t=H.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);var i=Math.atan2(t.m[8],t.m[10]),r=rr.ToRadians(this.rotationOffset)+i,n=e.getAbsolutePosition(),o=n.x+Math.sin(r)*this.radius,a=n.z+Math.cos(r)*this.radius,s=o-this.position.x,l=n.y+this.heightOffset-this.position.y,c=a-this.position.z,u=s*this.cameraAcceleration*2,h=l*this.cameraAcceleration,d=c*this.cameraAcceleration*2;(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(h>this.maxCameraSpeed||h<-this.maxCameraSpeed)&&(h=h<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new V(this.position.x+u,this.position.y+h,this.position.z+d),this.setTarget(n)}},t.prototype.attachControl=function(e,t){t=rr.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t),this._reset=function(){}},t.prototype.detachControl=function(){this.inputs.detachElement(),this._reset&&this._reset()},t.prototype._checkInputs=function(){this.inputs.checkInputs(),this._checkLimits(),e.prototype._checkInputs.call(this),this.lockedTarget&&this._follow(this.lockedTarget)},t.prototype._checkLimits=function(){null!==this.lowerRadiusLimit&&this.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit),null!==this.upperRadiusLimit&&this.radius>this.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),null!==this.lowerHeightOffsetLimit&&this.heightOffset<this.lowerHeightOffsetLimit&&(this.heightOffset=this.lowerHeightOffsetLimit),null!==this.upperHeightOffsetLimit&&this.heightOffset>this.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),null!==this.lowerRotationOffsetLimit&&this.rotationOffset<this.lowerRotationOffsetLimit&&(this.rotationOffset=this.lowerRotationOffsetLimit),null!==this.upperRotationOffsetLimit&&this.rotationOffset>this.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)},t.prototype.getClassName=function(){return"FollowCamera"},v([Ie()],t.prototype,"radius",void 0),v([Ie()],t.prototype,"lowerRadiusLimit",void 0),v([Ie()],t.prototype,"upperRadiusLimit",void 0),v([Ie()],t.prototype,"rotationOffset",void 0),v([Ie()],t.prototype,"lowerRotationOffsetLimit",void 0),v([Ie()],t.prototype,"upperRotationOffsetLimit",void 0),v([Ie()],t.prototype,"heightOffset",void 0),v([Ie()],t.prototype,"lowerHeightOffsetLimit",void 0),v([Ie()],t.prototype,"upperHeightOffsetLimit",void 0),v([Ie()],t.prototype,"cameraAcceleration",void 0),v([Ie()],t.prototype,"maxCameraSpeed",void 0),v([Le("lockedTargetId")],t.prototype,"lockedTarget",void 0),t}(Mc),Gc=function(e){function t(t,i,r,n,o,a){var s=e.call(this,t,V.Zero(),a)||this;return s.alpha=i,s.beta=r,s.radius=n,s._cartesianCoordinates=V.Zero(),s.setMeshTarget(o),s}return m(t,e),t.prototype.setMeshTarget=function(e){this._meshTarget=e,this._follow()},t.prototype._follow=function(){if(this._meshTarget){this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);var e=this._meshTarget.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}},t.prototype._checkInputs=function(){e.prototype._checkInputs.call(this),this._follow()},t.prototype.getClassName=function(){return"ArcFollowCamera"},t}(Mc);a("BABYLON.FollowCamera",kc),a("BABYLON.ArcFollowCamera",Gc),function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(Uc||(Uc={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Vc||(Vc={}));var zc,Wc,Hc=function(e){function t(t,i,r,n){void 0===n&&(n=!1);var o=e.call(this,t,i,r,0,1,2,3)||this;return o._leftTrigger=0,o._rightTrigger=0,o.onButtonDownObservable=new f,o.onButtonUpObservable=new f,o.onPadDownObservable=new f,o.onPadUpObservable=new f,o._buttonA=0,o._buttonB=0,o._buttonX=0,o._buttonY=0,o._buttonBack=0,o._buttonStart=0,o._buttonLB=0,o._buttonRB=0,o._buttonLeftStick=0,o._buttonRightStick=0,o._dPadUp=0,o._dPadDown=0,o._dPadLeft=0,o._dPadRight=0,o._isXboxOnePad=!1,o.type=ac.XBOX,o._isXboxOnePad=n,o}return m(t,e),t.prototype.onlefttriggerchanged=function(e){this._onlefttriggerchanged=e},t.prototype.onrighttriggerchanged=function(e){this._onrighttriggerchanged=e},Object.defineProperty(t.prototype,"leftTrigger",{get:function(){return this._leftTrigger},set:function(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rightTrigger",{get:function(){return this._rightTrigger},set:function(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e},enumerable:!1,configurable:!0}),t.prototype.onbuttondown=function(e){this._onbuttondown=e},t.prototype.onbuttonup=function(e){this._onbuttonup=e},t.prototype.ondpaddown=function(e){this._ondpaddown=e},t.prototype.ondpadup=function(e){this._ondpadup=e},t.prototype._setButtonValue=function(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e},t.prototype._setDPadValue=function(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e},Object.defineProperty(t.prototype,"buttonA",{get:function(){return this._buttonA},set:function(e){this._buttonA=this._setButtonValue(e,this._buttonA,Uc.A)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonB",{get:function(){return this._buttonB},set:function(e){this._buttonB=this._setButtonValue(e,this._buttonB,Uc.B)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonX",{get:function(){return this._buttonX},set:function(e){this._buttonX=this._setButtonValue(e,this._buttonX,Uc.X)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonY",{get:function(){return this._buttonY},set:function(e){this._buttonY=this._setButtonValue(e,this._buttonY,Uc.Y)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonStart",{get:function(){return this._buttonStart},set:function(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,Uc.Start)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonBack",{get:function(){return this._buttonBack},set:function(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,Uc.Back)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonLB",{get:function(){return this._buttonLB},set:function(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,Uc.LB)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonRB",{get:function(){return this._buttonRB},set:function(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,Uc.RB)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonLeftStick",{get:function(){return this._buttonLeftStick},set:function(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Uc.LeftStick)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonRightStick",{get:function(){return this._buttonRightStick},set:function(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Uc.RightStick)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dPadUp",{get:function(){return this._dPadUp},set:function(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Vc.Up)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dPadDown",{get:function(){return this._dPadDown},set:function(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Vc.Down)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dPadLeft",{get:function(){return this._dPadLeft},set:function(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Vc.Left)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dPadRight",{get:function(){return this._dPadRight},set:function(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Vc.Right)},enumerable:!1,configurable:!0}),t.prototype.update=function(){e.prototype.update.call(this),this._isXboxOnePad,this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()},t}(ac);!function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(zc||(zc={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Wc||(Wc={}));var Xc=function(e){function t(t,i,r){var n=e.call(this,t.replace("STANDARD GAMEPAD","SONY PLAYSTATION DUALSHOCK"),i,r,0,1,2,3)||this;return n._leftTrigger=0,n._rightTrigger=0,n.onButtonDownObservable=new f,n.onButtonUpObservable=new f,n.onPadDownObservable=new f,n.onPadUpObservable=new f,n._buttonCross=0,n._buttonCircle=0,n._buttonSquare=0,n._buttonTriangle=0,n._buttonShare=0,n._buttonOptions=0,n._buttonL1=0,n._buttonR1=0,n._buttonLeftStick=0,n._buttonRightStick=0,n._dPadUp=0,n._dPadDown=0,n._dPadLeft=0,n._dPadRight=0,n.type=ac.DUALSHOCK,n}return m(t,e),t.prototype.onlefttriggerchanged=function(e){this._onlefttriggerchanged=e},t.prototype.onrighttriggerchanged=function(e){this._onrighttriggerchanged=e},Object.defineProperty(t.prototype,"leftTrigger",{get:function(){return this._leftTrigger},set:function(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rightTrigger",{get:function(){return this._rightTrigger},set:function(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e},enumerable:!1,configurable:!0}),t.prototype.onbuttondown=function(e){this._onbuttondown=e},t.prototype.onbuttonup=function(e){this._onbuttonup=e},t.prototype.ondpaddown=function(e){this._ondpaddown=e},t.prototype.ondpadup=function(e){this._ondpadup=e},t.prototype._setButtonValue=function(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e},t.prototype._setDPadValue=function(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e},Object.defineProperty(t.prototype,"buttonCross",{get:function(){return this._buttonCross},set:function(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,zc.Cross)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonCircle",{get:function(){return this._buttonCircle},set:function(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,zc.Circle)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonSquare",{get:function(){return this._buttonSquare},set:function(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,zc.Square)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonTriangle",{get:function(){return this._buttonTriangle},set:function(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,zc.Triangle)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonOptions",{get:function(){return this._buttonOptions},set:function(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,zc.Options)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonShare",{get:function(){return this._buttonShare},set:function(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,zc.Share)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonL1",{get:function(){return this._buttonL1},set:function(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,zc.L1)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonR1",{get:function(){return this._buttonR1},set:function(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,zc.R1)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonLeftStick",{get:function(){return this._buttonLeftStick},set:function(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,zc.LeftStick)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"buttonRightStick",{get:function(){return this._buttonRightStick},set:function(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,zc.RightStick)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dPadUp",{get:function(){return this._dPadUp},set:function(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Wc.Up)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dPadDown",{get:function(){return this._dPadDown},set:function(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Wc.Down)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dPadLeft",{get:function(){return this._dPadLeft},set:function(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Wc.Left)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dPadRight",{get:function(){return this._dPadRight},set:function(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Wc.Right)},enumerable:!1,configurable:!0}),t.prototype.update=function(){e.prototype.update.call(this),this.buttonCross=this.browserGamepad.buttons[0].value,this.buttonCircle=this.browserGamepad.buttons[1].value,this.buttonSquare=this.browserGamepad.buttons[2].value,this.buttonTriangle=this.browserGamepad.buttons[3].value,this.buttonL1=this.browserGamepad.buttons[4].value,this.buttonR1=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonShare=this.browserGamepad.buttons[8].value,this.buttonOptions=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()},t}(ac),jc=function(){function e(e){var t=this;if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new f,ct()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new f((function(e){for(var i in t._babylonGamepads){var r=t._babylonGamepads[i];r&&r._isConnected&&t.onGamepadConnectedObservable.notifyObserver(e,r)}})),this._onGamepadConnectedEvent=function(e){var i,r=e.gamepad;r.index in t._babylonGamepads&&t._babylonGamepads[r.index].isConnected||(t._babylonGamepads[r.index]?((i=t._babylonGamepads[r.index]).browserGamepad=r,i._isConnected=!0):i=t._addNewGamepad(r),t.onGamepadConnectedObservable.notifyObservers(i),t._startMonitoringGamepads())},this._onGamepadDisconnectedEvent=function(e){var i=e.gamepad;for(var r in t._babylonGamepads)if(t._babylonGamepads[r].index===i.index){var n=t._babylonGamepads[r];n._isConnected=!1,t.onGamepadDisconnectedObservable.notifyObservers(n),n.dispose&&n.dispose();break}},this._gamepadSupport)if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){var i=this._scene?this._scene.getEngine().getHostWindow():window;i&&(i.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),i.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}return Object.defineProperty(e.prototype,"gamepads",{get:function(){return this._babylonGamepads},enumerable:!1,configurable:!0}),e.prototype.getGamepadByType=function(e){void 0===e&&(e=ac.XBOX);for(var t=0,i=this._babylonGamepads;t<i.length;t++){var r=i[t];if(r&&r.type===e)return r}return null},e.prototype.dispose=function(){this._gamepadEventSupported&&(this._onGamepadConnectedEvent&&window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent),this._onGamepadDisconnectedEvent&&window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent),this._onGamepadConnectedEvent=null,this._onGamepadDisconnectedEvent=null),this._babylonGamepads.forEach((function(e){e.dispose()})),this.onGamepadConnectedObservable.clear(),this.onGamepadDisconnectedObservable.clear(),this._oneGamepadConnected=!1,this._stopMonitoringGamepads(),this._babylonGamepads=[]},e.prototype._addNewGamepad=function(e){var t;this._oneGamepadConnected||(this._oneGamepadConnected=!0);var i=-1!==e.id.search("054c")&&-1===e.id.search("0ce6"),r=-1!==e.id.search("Xbox One");return t=r||-1!==e.id.search("Xbox 360")||-1!==e.id.search("xinput")||-1!==e.id.search("045e")&&-1===e.id.search("Surface Dock")?new Hc(e.id,e.index,e,r):i?new Xc(e.id,e.index,e):new sc(e.id,e.index,e),this._babylonGamepads[t.index]=t,t},e.prototype._startMonitoringGamepads=function(){this._isMonitoring||(this._isMonitoring=!0,this._checkGamepadsStatus())},e.prototype._stopMonitoringGamepads=function(){this._isMonitoring=!1},e.prototype._checkGamepadsStatus=function(){var e=this;for(var t in this._updateGamepadObjects(),this._babylonGamepads){var i=this._babylonGamepads[t];if(i&&i.isConnected)try{i.update()}catch(e){-1===this._loggedErrors.indexOf(i.index)&&(rr.Warn("Error updating gamepad ".concat(i.id)),this._loggedErrors.push(i.index))}}this._isMonitoring&&Do.QueueNewFrame((function(){e._checkGamepadsStatus()}))},e.prototype._updateGamepadObjects=function(){for(var e=navigator.getGamepads?navigator.getGamepads():[],t=0;t<e.length;t++){var i=e[t];if(i)if(this._babylonGamepads[i.index])this._babylonGamepads[t].browserGamepad=i,this._babylonGamepads[t].isConnected||(this._babylonGamepads[t]._isConnected=!0,this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[t]));else{var r=this._addNewGamepad(i);this.onGamepadConnectedObservable.notifyObservers(r)}}},e}();Object.defineProperty(pn.prototype,"gamepadManager",{get:function(){if(!this._gamepadManager){this._gamepadManager=new jc(this);var e=this._getComponent(Vr.NAME_GAMEPAD);e||(e=new Yc(this),this._addComponent(e))}return this._gamepadManager},enumerable:!0,configurable:!0}),xc.prototype.addGamepad=function(){return this.add(new Rc),this},dc.prototype.addGamepad=function(){return this.add(new lc),this};var Yc=function(){function e(e){this.name=Vr.NAME_GAMEPAD,this.scene=e}return e.prototype.register=function(){this.scene._beforeCameraUpdateStage.registerStep(Vr.STEP_BEFORECAMERAUPDATE_GAMEPAD,this,this._beforeCameraUpdate)},e.prototype.rebuild=function(){},e.prototype.dispose=function(){var e=this.scene._gamepadManager;e&&(e.dispose(),this.scene._gamepadManager=null)},e.prototype._beforeCameraUpdate=function(){var e=this.scene._gamepadManager;e&&e._isMonitoring&&e._checkGamepadsStatus()},e}();qe.AddNodeConstructor("FreeCamera",(function(e,t){return function(){return new Kc(e,V.Zero(),t)}}));var Kc=function(e){function t(t,i,r){var n=e.call(this,t,i,r)||this;return n.inputs.addGamepad(),n}return m(t,e),Object.defineProperty(t.prototype,"gamepadAngularSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"gamepadMoveSensibility",{get:function(){var e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0},set:function(e){var t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"UniversalCamera"},t}(Dc);$n._CreateDefaultParsedCamera=function(e,t){return new Kc(e,V.Zero(),t)},qe.AddNodeConstructor("GamepadCamera",(function(e,t){return function(){return new Qc(e,V.Zero(),t)}}));var Qc=function(e){function t(t,i,r){return e.call(this,t,i,r)||this}return m(t,e),t.prototype.getClassName=function(){return"GamepadCamera"},t}(Kc);li.ShadersStore.passCubePixelShader="varying vec2 vUV;uniform samplerCube textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001));\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));\n#endif\n}";var qc=function(e){function t(t,i,r,n,o,a,s,l){return void 0===r&&(r=null),void 0===s&&(s=u.TEXTURETYPE_UNSIGNED_INT),void 0===l&&(l=!1),e.call(this,t,"pass",null,null,i,r,n,o,a,void 0,s,void 0,null,l)||this}return m(t,e),t.prototype.getClassName=function(){return"PassPostProcess"},t._Parse=function(e,i,r,n){return Ke.Parse((function(){return new t(e.name,e.options,i,e.renderTargetSamplingMode,e._engine,e.reusable)}),e,r,n)},t}(hl);a("BABYLON.PassPostProcess",qc);var Zc=function(e){function t(t,i,r,n,o,a,s,l){void 0===r&&(r=null),void 0===s&&(s=u.TEXTURETYPE_UNSIGNED_INT),void 0===l&&(l=!1);var c=e.call(this,t,"passCube",null,null,i,r,n,o,a,"#define POSITIVEX",s,void 0,null,l)||this;return c._face=0,c}return m(t,e),Object.defineProperty(t.prototype,"face",{get:function(){return this._face},set:function(e){if(!(e<0||e>5))switch(this._face=e,this._face){case 0:this.updateEffect("#define POSITIVEX");break;case 1:this.updateEffect("#define NEGATIVEX");break;case 2:this.updateEffect("#define POSITIVEY");break;case 3:this.updateEffect("#define NEGATIVEY");break;case 4:this.updateEffect("#define POSITIVEZ");break;case 5:this.updateEffect("#define NEGATIVEZ")}},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"PassCubePostProcess"},t._Parse=function(e,i,r,n){return Ke.Parse((function(){return new t(e.name,e.options,i,e.renderTargetSamplingMode,e._engine,e.reusable)}),e,r,n)},t}(hl);Mi._RescalePostProcessFactory=function(e){return new qc("rescale",1,null,u.TEXTURE_BILINEAR_SAMPLINGMODE,e,!1,u.TEXTURETYPE_UNSIGNED_INT)};li.ShadersStore.anaglyphPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 leftFrag=texture2D(leftSampler,vUV);leftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);vec4 rightFrag=texture2D(textureSampler,vUV);rightFrag=vec4(rightFrag.r,1.0,1.0,1.0);gl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);}";var Jc=function(e){function t(t,i,r,n,o,a){var s=e.call(this,t,"anaglyph",null,["leftSampler"],i,r[1],n,o,a)||this;return s._passedProcess=r[0]._rigPostProcess,s.onApplyObservable.add((function(e){e.setTextureFromPostProcess("leftSampler",s._passedProcess)})),s}return m(t,e),t.prototype.getClassName=function(){return"AnaglyphPostProcess"},t}(hl);function $c(e){e._rigCameras[0]._rigPostProcess=new qc(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new Jc(e.name+"_anaglyph",1,e._rigCameras)}a("BABYLON.AnaglyphPostProcess",Jc),qe.AddNodeConstructor("AnaglyphArcRotateCamera",(function(e,t,i){return function(){return new eu(e,0,0,1,V.Zero(),i.interaxial_distance,t)}}));var eu=function(e){function t(t,i,r,n,o,a,s){var l=e.call(this,t,i,r,n,o,s)||this;return l._setRigMode=function(){return $c(l)},l.interaxialDistance=a,l.setCameraRigMode($n.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:a}),l}return m(t,e),t.prototype.getClassName=function(){return"AnaglyphArcRotateCamera"},t}(Nc);qe.AddNodeConstructor("AnaglyphFreeCamera",(function(e,t,i){return function(){return new tu(e,V.Zero(),i.interaxial_distance,t)}}));var tu=function(e){function t(t,i,r,n){var o=e.call(this,t,i,n)||this;return o._setRigMode=function(){return $c(o)},o.interaxialDistance=r,o.setCameraRigMode($n.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:r}),o}return m(t,e),t.prototype.getClassName=function(){return"AnaglyphFreeCamera"},t}(Oc);qe.AddNodeConstructor("AnaglyphGamepadCamera",(function(e,t,i){return function(){return new iu(e,V.Zero(),i.interaxial_distance,t)}}));var iu=function(e){function t(t,i,r,n){var o=e.call(this,t,i,n)||this;return o._setRigMode=function(){return $c(o)},o.interaxialDistance=r,o.setCameraRigMode($n.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:r}),o}return m(t,e),t.prototype.getClassName=function(){return"AnaglyphGamepadCamera"},t}(Qc);qe.AddNodeConstructor("AnaglyphUniversalCamera",(function(e,t,i){return function(){return new ru(e,V.Zero(),i.interaxial_distance,t)}}));var ru=function(e){function t(t,i,r,n){var o=e.call(this,t,i,n)||this;return o._setRigMode=function(){return $c(o)},o.interaxialDistance=r,o.setCameraRigMode($n.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:r}),o}return m(t,e),t.prototype.getClassName=function(){return"AnaglyphUniversalCamera"},t}(Kc);li.ShadersStore.stereoscopicInterlacePixelShader="const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;useCamA=!useCamB;texCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);texCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\n#ifdef IS_STEREOSCOPIC_INTERLACED\nfloat rowNum=floor(vUV.y/stepSize.y);useCamA=mod(rowNum,2.0)==1.0;useCamB=mod(rowNum,2.0)==0.0;texCoord1=vec2(vUV.x,vUV.y);texCoord2=vec2(vUV.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;useCamA=!useCamB;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);texCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n#endif\nif (useCamB){frag1=texture2D(textureSampler,texCoord1).rgb;frag2=texture2D(textureSampler,texCoord2).rgb;}else if (useCamA){frag1=texture2D(camASampler ,texCoord1).rgb;frag2=texture2D(camASampler ,texCoord2).rgb;}else {discard;}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);}\n";var nu=function(e){function t(t,i,r,n,o,a,s){var l=e.call(this,t,"stereoscopicInterlace",["stepSize"],["camASampler"],1,i[1],o,a,s,n?"#define IS_STEREOSCOPIC_INTERLACED 1":r?"#define IS_STEREOSCOPIC_HORIZ 1":void 0)||this;return l._passedProcess=i[0]._rigPostProcess,l._stepSize=new U(1/l.width,1/l.height),l.onSizeChangedObservable.add((function(){l._stepSize=new U(1/l.width,1/l.height)})),l.onApplyObservable.add((function(e){e.setTextureFromPostProcess("camASampler",l._passedProcess),e.setFloat2("stepSize",l._stepSize.x,l._stepSize.y)})),l}return m(t,e),t.prototype.getClassName=function(){return"StereoscopicInterlacePostProcessI"},t}(hl),ou=function(e){function t(t,i,r,n,o,a){var s=e.call(this,t,"stereoscopicInterlace",["stepSize"],["camASampler"],1,i[1],n,o,a,r?"#define IS_STEREOSCOPIC_HORIZ 1":void 0)||this;return s._passedProcess=i[0]._rigPostProcess,s._stepSize=new U(1/s.width,1/s.height),s.onSizeChangedObservable.add((function(){s._stepSize=new U(1/s.width,1/s.height)})),s.onApplyObservable.add((function(e){e.setTextureFromPostProcess("camASampler",s._passedProcess),e.setFloat2("stepSize",s._stepSize.x,s._stepSize.y)})),s}return m(t,e),t.prototype.getClassName=function(){return"StereoscopicInterlacePostProcess"},t}(hl);function au(e){var t=e.cameraRigMode===$n.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||e.cameraRigMode===$n.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,i=e.cameraRigMode===$n.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;e.cameraRigMode===$n.RIG_MODE_STEREOSCOPIC_INTERLACED?(e._rigCameras[0]._rigPostProcess=new qc(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new nu(e.name+"_stereoInterlace",e._rigCameras,!1,!0)):(e._rigCameras[i?1:0].viewport=new Jn(0,0,t?.5:1,t?1:.5),e._rigCameras[i?0:1].viewport=new Jn(t?.5:0,t?0:.5,t?.5:1,t?1:.5))}qe.AddNodeConstructor("StereoscopicArcRotateCamera",(function(e,t,i){return function(){return new su(e,0,0,1,V.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)}}));var su=function(e){function t(t,i,r,n,o,a,s,l){var c=e.call(this,t,i,r,n,o,l)||this;return c._setRigMode=function(){return au(c)},c.interaxialDistance=a,c.isStereoscopicSideBySide=s,c.setCameraRigMode(s?$n.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:$n.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:a}),c}return m(t,e),t.prototype.getClassName=function(){return"StereoscopicArcRotateCamera"},t}(Nc);qe.AddNodeConstructor("StereoscopicFreeCamera",(function(e,t,i){return function(){return new lu(e,V.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)}}));var lu=function(e){function t(t,i,r,n,o){var a=e.call(this,t,i,o)||this;return a._setRigMode=function(){return au(a)},a.interaxialDistance=r,a.isStereoscopicSideBySide=n,a.setCameraRigMode(n?$n.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:$n.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:r}),a}return m(t,e),t.prototype.getClassName=function(){return"StereoscopicFreeCamera"},t}(Oc);qe.AddNodeConstructor("StereoscopicGamepadCamera",(function(e,t,i){return function(){return new cu(e,V.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)}}));var cu=function(e){function t(t,i,r,n,o){var a=e.call(this,t,i,o)||this;return a._setRigMode=function(){return au(a)},a.interaxialDistance=r,a.isStereoscopicSideBySide=n,a.setCameraRigMode(n?$n.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:$n.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:r}),a}return m(t,e),t.prototype.getClassName=function(){return"StereoscopicGamepadCamera"},t}(Qc);qe.AddNodeConstructor("StereoscopicFreeCamera",(function(e,t,i){return function(){return new uu(e,V.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)}}));var uu=function(e){function t(t,i,r,n,o){var a=e.call(this,t,i,o)||this;return a._setRigMode=function(){return au(a)},a.interaxialDistance=r,a.isStereoscopicSideBySide=n,a.setCameraRigMode(n?$n.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:$n.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:r}),a}return m(t,e),t.prototype.getClassName=function(){return"StereoscopicUniversalCamera"},t}(Kc),hu=function(e){function t(t,i,r,n,o){void 0===n&&(n=1),void 0===o&&(o=.065);var a=e.call(this,t,i,r)||this;return a._distanceBetweenEyes=o,a._distanceToProjectionPlane=n,a.setCameraRigMode($n.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL,{stereoHalfAngle:0}),a._cameraRigParams.stereoHalfAngle=0,a._cameraRigParams.interaxialDistance=o,a}return m(t,e),Object.defineProperty(t.prototype,"distanceBetweenEyes",{get:function(){return this._distanceBetweenEyes},set:function(e){this._distanceBetweenEyes=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"distanceToProjectionPlane",{get:function(){return this._distanceToProjectionPlane},set:function(e){this._distanceToProjectionPlane=e},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"StereoscopicUniversalCamera"},t.prototype.createRigCamera=function(e){var t=new Mc(e,V.Zero(),this.getScene()),i=new Fo("tm_"+e,this.getScene());return t.parent=i,i.setPivotMatrix(z.Identity(),!1),t.isRigCamera=!0,t.rigParent=this,t},t.prototype._updateRigCameras=function(){for(var e=0;e<this._rigCameras.length;e++){var t=this._rigCameras[e];t.minZ=this.minZ,t.maxZ=this.maxZ,t.fov=this.fov,t.upVector.copyFrom(this.upVector),t.rotationQuaternion?t.rotationQuaternion.copyFrom(this.rotationQuaternion):t.rotation.copyFrom(this.rotation),this._updateCamera(this._rigCameras[e],e)}},t.prototype._updateCamera=function(e,t){var i=this.distanceBetweenEyes/2,r=i/this.distanceToProjectionPlane;e.position.copyFrom(this.position),e.position.addInPlaceFromFloats(0===t?-i:i,0,-this._distanceToProjectionPlane);var n=e.parent,o=n.getPivotMatrix();o.setTranslationFromFloats(0===t?i:-i,0,0),o.setRowFromFloats(2,0===t?r:-r,0,1,0),n.setPivotMatrix(o,!1)},t.prototype._setRigMode=function(){this._rigCameras[0].viewport=new Jn(0,0,.5,1),this._rigCameras[1].viewport=new Jn(.5,0,.5,1);for(var e=0;e<this._rigCameras.length;e++)this._updateCamera(this._rigCameras[e],e)},t}(Kc);qe.AddNodeConstructor("VirtualJoysticksCamera",(function(e,t){return function(){return new du(e,V.Zero(),t)}}));var du=function(e){function t(t,i,r){var n=e.call(this,t,i,r)||this;return n.inputs.addVirtualJoystick(),n}return m(t,e),t.prototype.getClassName=function(){return"VirtualJoysticksCamera"},t}(Oc),pu=function(){function e(){this.compensateDistortion=!0,this.multiviewEnabled=!1}return Object.defineProperty(e.prototype,"aspectRatio",{get:function(){return this.hResolution/(2*this.vResolution)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"aspectRatioFov",{get:function(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"leftHMatrix",{get:function(){var e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return z.Translation(e,0,0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"rightHMatrix",{get:function(){var e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return z.Translation(-e,0,0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"leftPreViewMatrix",{get:function(){return z.Translation(.5*this.interpupillaryDistance,0,0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"rightPreViewMatrix",{get:function(){return z.Translation(-.5*this.interpupillaryDistance,0,0)},enumerable:!1,configurable:!0}),e.GetDefault=function(){var t=new e;return t.hResolution=1280,t.vResolution=800,t.hScreenSize=.149759993,t.vScreenSize=.0935999975,t.vScreenCenter=.0467999987,t.eyeToScreenDistance=.0410000011,t.lensSeparationDistance=.063500002,t.interpupillaryDistance=.064000003,t.distortionK=[1,.219999999,.239999995,0],t.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],t.postProcessScaleFactor=1.714605507808412,t.lensCenterOffset=.151976421,t},e}();li.ShadersStore.vrDistortionCorrectionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 LensCenter;uniform vec2 Scale;uniform vec2 ScaleIn;uniform vec4 HmdWarpParam;vec2 HmdWarp(vec2 in01) {vec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);return LensCenter+Scale*rvector;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 tc=HmdWarp(vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}";var fu=function(e){function t(t,i,r,n){var o=e.call(this,t,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,n.postProcessScaleFactor,i,Ja.BILINEAR_SAMPLINGMODE)||this;return o._isRightEye=r,o._distortionFactors=n.distortionK,o._postProcessScaleFactor=n.postProcessScaleFactor,o._lensCenterOffset=n.lensCenterOffset,o.adaptScaleToCurrentViewport=!0,o.onSizeChangedObservable.add((function(){o._scaleIn=new U(2,2/o.aspectRatio),o._scaleFactor=new U(1/o._postProcessScaleFactor*.5,1/o._postProcessScaleFactor*.5*o.aspectRatio),o._lensCenter=new U(o._isRightEye?.5-.5*o._lensCenterOffset:.5+.5*o._lensCenterOffset,.5)})),o.onApplyObservable.add((function(e){e.setFloat2("LensCenter",o._lensCenter.x,o._lensCenter.y),e.setFloat2("Scale",o._scaleFactor.x,o._scaleFactor.y),e.setFloat2("ScaleIn",o._scaleIn.x,o._scaleIn.y),e.setFloat4("HmdWarpParam",o._distortionFactors[0],o._distortionFactors[1],o._distortionFactors[2],o._distortionFactors[3])})),o}return m(t,e),t.prototype.getClassName=function(){return"VRDistortionCorrectionPostProcess"},t}(hl);li.ShadersStore.vrMultiviewToSingleviewPixelShader="precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}";var _u=function(e){function t(t,i){void 0===i&&(i=512);var r=e.call(this,"multiview rtt",i,t,!1,!0,u.TEXTURETYPE_UNSIGNED_INT,!1,void 0,!1,!1,!0,void 0,!0)||this;return r._renderTarget=r.getScene().getEngine().createMultiviewRenderTargetTexture(r.getRenderWidth(),r.getRenderHeight()),r._texture=r._renderTarget.texture,r._texture.isMultiview=!0,r._texture.format=u.TEXTUREFORMAT_RGBA,r.samples=r._getEngine().getCaps().maxSamples||r.samples,r._texture.samples=r._samples,r}return m(t,e),Object.defineProperty(t.prototype,"samples",{get:function(){return this._samples},set:function(e){this._samples=e},enumerable:!1,configurable:!0}),t.prototype._bindFrameBuffer=function(){this._renderTarget&&this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget)},t.prototype.getViewCount=function(){return 2},t}(Pl);function mu(e,t){var i=new Or(e,void 0,!0,t);return i.addUniform("viewProjection",16),i.addUniform("viewProjectionR",16),i.addUniform("view",16),i.addUniform("projection",16),i.addUniform("vEyePosition",4),i}Do.prototype.createMultiviewRenderTargetTexture=function(e,t,i,r){var n=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";var o=this._createHardwareRenderTargetWrapper(!1,!1,{width:e,height:t});o._framebuffer=n.createFramebuffer();var a=new Pi(this,Ti.Unknown,!0);return a.width=e,a.height=t,a.isMultiview=!0,i||(i=n.createTexture(),n.bindTexture(n.TEXTURE_2D_ARRAY,i),n.texStorage3D(n.TEXTURE_2D_ARRAY,1,n.RGBA8,e,t,2)),o._colorTextureArray=i,r||(r=n.createTexture(),n.bindTexture(n.TEXTURE_2D_ARRAY,r),n.texStorage3D(n.TEXTURE_2D_ARRAY,1,n.DEPTH24_STENCIL8,e,t,2)),o._depthStencilTextureArray=r,a.isReady=!0,o.setTextures(a),o._depthStencilTexture=a,o},Do.prototype.bindMultiviewFramebuffer=function(e){var t=e,i=this._gl,r=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw"Invalid multiview frame buffer";this.getCaps().oculusMultiview?(r.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,t.samples,0,2),r.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,t.samples,0,2)):(r.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),r.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,0,2))},Do.prototype.bindSpaceWarpFramebuffer=function(e){var t=e,i=this._gl,r=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw new Error("Invalid Space Warp framebuffer");r.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),r.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_ATTACHMENT,t._depthStencilTextureArray,0,0,2)},$n.prototype._useMultiviewToSingleView=!1,$n.prototype._multiviewTexture=null,$n.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?this._multiviewTexture.getRenderWidth()==e&&this._multiviewTexture.getRenderHeight()==t||(this._multiviewTexture.dispose(),this._multiviewTexture=new _u(this.getScene(),{width:e,height:t})):this._multiviewTexture=new _u(this.getScene(),{width:e,height:t})};var gu=pn.prototype.createSceneUniformBuffer;pn.prototype._transformMatrixR=z.Zero(),pn.prototype._multiviewSceneUbo=null,pn.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=mu(this.getEngine(),"scene_multiview")},pn.prototype.createSceneUniformBuffer=function(e){return this._multiviewSceneUbo?mu(this.getEngine(),e):gu.bind(this)(e)},pn.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,H.Matrix[0]),ln.GetRightPlaneToRef(H.Matrix[0],this._frustumPlanes[3])),this._multiviewSceneUbo&&(this._multiviewSceneUbo.updateMatrix("viewProjection",this.getTransformMatrix()),this._multiviewSceneUbo.updateMatrix("viewProjectionR",this._transformMatrixR),this._multiviewSceneUbo.updateMatrix("view",this._viewMatrix),this._multiviewSceneUbo.updateMatrix("projection",this._projectionMatrix))},pn.prototype._renderMultiviewToSingleView=function(e){e._resizeOrCreateMultiviewTexture(e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.width>0?e._rigPostProcess.width:this.getEngine().getRenderWidth(!0),e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.height>0?e._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),e.outputRenderTarget=e._multiviewTexture,this._renderForCamera(e),e.outputRenderTarget=null;for(var t=0;t<e._rigCameras.length;t++){var i=this.getEngine();this._activeCamera=e._rigCameras[t],i.setViewport(this._activeCamera.viewport),this.postProcessManager&&(this.postProcessManager._prepareFrame(),this.postProcessManager._finalizeFrame(this._activeCamera.isIntermediate))}};var vu=function(e){function t(t,i,r){var n=e.call(this,t,"vrMultiviewToSingleview",["imageIndex"],["multiviewSampler"],r,i,Ja.BILINEAR_SAMPLINGMODE)||this,o=null!=i?i:n.getCamera();return n.onSizeChangedObservable.add((function(){})),n.onApplyObservable.add((function(e){o._scene.activeCamera&&o._scene.activeCamera.isLeftCamera?e.setInt("imageIndex",0):e.setInt("imageIndex",1),e.setTexture("multiviewSampler",o._multiviewTexture)})),n}return m(t,e),t.prototype.getClassName=function(){return"VRMultiviewToSingleviewPostProcess"},t}(hl);function yu(e,t){var i=t.vrCameraMetrics||pu.GetDefault();e._rigCameras[0]._cameraRigParams.vrMetrics=i,e._rigCameras[0].viewport=new Jn(0,0,.5,1),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new z,e._rigCameras[0]._cameraRigParams.vrHMatrix=i.leftHMatrix,e._rigCameras[0]._cameraRigParams.vrPreViewMatrix=i.leftPreViewMatrix,e._rigCameras[0].getProjectionMatrix=e._rigCameras[0]._getVRProjectionMatrix,e._rigCameras[1]._cameraRigParams.vrMetrics=i,e._rigCameras[1].viewport=new Jn(.5,0,.5,1),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new z,e._rigCameras[1]._cameraRigParams.vrHMatrix=i.rightHMatrix,e._rigCameras[1]._cameraRigParams.vrPreViewMatrix=i.rightPreViewMatrix,e._rigCameras[1].getProjectionMatrix=e._rigCameras[1]._getVRProjectionMatrix,i.multiviewEnabled&&(e.getScene().getEngine().getCaps().multiview?(e._useMultiviewToSingleView=!0,e._rigPostProcess=new vu("VRMultiviewToSingleview",e,i.postProcessScaleFactor)):(ae.Warn("Multiview is not supported, falling back to standard rendering"),i.multiviewEnabled=!1)),i.compensateDistortion&&(e._rigCameras[0]._rigPostProcess=new fu("VR_Distort_Compensation_Left",e._rigCameras[0],!1,i),e._rigCameras[1]._rigPostProcess=new fu("VR_Distort_Compensation_Right",e._rigCameras[1],!0,i))}qe.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",(function(e,t){return function(){return new bu(e,0,0,1,V.Zero(),t)}}));var bu=function(e){function t(t,i,r,n,o,a,s,l){void 0===s&&(s=!0),void 0===l&&(l=pu.GetDefault());var c=e.call(this,t,i,r,n,o,a)||this;return c._setRigMode=function(e){return yu(c,e)},l.compensateDistortion=s,c.setCameraRigMode($n.RIG_MODE_VR,{vrCameraMetrics:l}),c.inputs.addVRDeviceOrientation(),c}return m(t,e),t.prototype.getClassName=function(){return"VRDeviceOrientationArcRotateCamera"},t}(Nc);qe.AddNodeConstructor("VRDeviceOrientationFreeCamera",(function(e,t){return function(){return new Tu(e,V.Zero(),t)}}));var Tu=function(e){function t(t,i,r,n,o){void 0===n&&(n=!0),void 0===o&&(o=pu.GetDefault());var a=e.call(this,t,i,r)||this;return a._setRigMode=function(e){return yu(a,e)},o.compensateDistortion=n,a.setCameraRigMode($n.RIG_MODE_VR,{vrCameraMetrics:o}),a}return m(t,e),t.prototype.getClassName=function(){return"VRDeviceOrientationFreeCamera"},t}(Fc);qe.AddNodeConstructor("VRDeviceOrientationGamepadCamera",(function(e,t){return function(){return new Eu(e,V.Zero(),t)}}));var Eu=function(e){function t(t,i,r,n,o){void 0===n&&(n=!0),void 0===o&&(o=pu.GetDefault());var a=e.call(this,t,i,r,n,o)||this;return a._setRigMode=function(e){return yu(a,e)},a.inputs.addGamepad(),a}return m(t,e),t.prototype.getClassName=function(){return"VRDeviceOrientationGamepadCamera"},t}(Tu),Su=function(){function e(){this.previousWorldMatrices={},this.previousBones={}}return e.AddUniforms=function(e){e.push("previousWorld","previousViewProjection","mPreviousBones")},e.AddSamplers=function(e){},e.prototype.bindForSubMesh=function(e,t,i,r,n){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&-1!==t.prePassRenderer.getIndex(u.PREPASS_VELOCITY_TEXTURE_TYPE)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=r.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());var o=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=o.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==o.frameId&&(this._lastUpdateFrameId=o.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=r.clone()}},e}(),xu=function(){function e(){}return Object.defineProperty(e,"DiffuseTextureEnabled",{get:function(){return this._DiffuseTextureEnabled},set:function(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"DetailTextureEnabled",{get:function(){return this._DetailTextureEnabled},set:function(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"DecalMapEnabled",{get:function(){return this._DecalMapEnabled},set:function(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"AmbientTextureEnabled",{get:function(){return this._AmbientTextureEnabled},set:function(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"OpacityTextureEnabled",{get:function(){return this._OpacityTextureEnabled},set:function(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"ReflectionTextureEnabled",{get:function(){return this._ReflectionTextureEnabled},set:function(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"EmissiveTextureEnabled",{get:function(){return this._EmissiveTextureEnabled},set:function(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"SpecularTextureEnabled",{get:function(){return this._SpecularTextureEnabled},set:function(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"BumpTextureEnabled",{get:function(){return this._BumpTextureEnabled},set:function(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"LightmapTextureEnabled",{get:function(){return this._LightmapTextureEnabled},set:function(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"RefractionTextureEnabled",{get:function(){return this._RefractionTextureEnabled},set:function(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"ColorGradingTextureEnabled",{get:function(){return this._ColorGradingTextureEnabled},set:function(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"FresnelEnabled",{get:function(){return this._FresnelEnabled},set:function(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_FresnelDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"ClearCoatTextureEnabled",{get:function(){return this._ClearCoatTextureEnabled},set:function(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"ClearCoatBumpTextureEnabled",{get:function(){return this._ClearCoatBumpTextureEnabled},set:function(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"ClearCoatTintTextureEnabled",{get:function(){return this._ClearCoatTintTextureEnabled},set:function(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"SheenTextureEnabled",{get:function(){return this._SheenTextureEnabled},set:function(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"AnisotropicTextureEnabled",{get:function(){return this._AnisotropicTextureEnabled},set:function(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"ThicknessTextureEnabled",{get:function(){return this._ThicknessTextureEnabled},set:function(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"RefractionIntensityTextureEnabled",{get:function(){return this._ThicknessTextureEnabled},set:function(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"TranslucencyIntensityTextureEnabled",{get:function(){return this._TranslucencyIntensityTextureEnabled},set:function(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"TranslucencyColorTextureEnabled",{get:function(){return this._TranslucencyColorTextureEnabled},set:function(e){this._TranslucencyColorTextureEnabled!==e&&(this._TranslucencyColorTextureEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),Object.defineProperty(e,"IridescenceTextureEnabled",{get:function(){return this._IridescenceTextureEnabled},set:function(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag))},enumerable:!1,configurable:!0}),e._DiffuseTextureEnabled=!0,e._DetailTextureEnabled=!0,e._DecalMapEnabled=!0,e._AmbientTextureEnabled=!0,e._OpacityTextureEnabled=!0,e._ReflectionTextureEnabled=!0,e._EmissiveTextureEnabled=!0,e._SpecularTextureEnabled=!0,e._BumpTextureEnabled=!0,e._LightmapTextureEnabled=!0,e._RefractionTextureEnabled=!0,e._ColorGradingTextureEnabled=!0,e._FresnelEnabled=!0,e._ClearCoatTextureEnabled=!0,e._ClearCoatBumpTextureEnabled=!0,e._ClearCoatTintTextureEnabled=!0,e._SheenTextureEnabled=!0,e._AnisotropicTextureEnabled=!0,e._ThicknessTextureEnabled=!0,e._RefractionIntensityTextureEnabled=!0,e._TranslucencyIntensityTextureEnabled=!0,e._TranslucencyColorTextureEnabled=!0,e._IridescenceTextureEnabled=!0,e}();li.IncludesShadersStore.decalFragmentDeclaration="#ifdef DECAL\nuniform vec4 vDecalInfos;\n#endif\n";li.IncludesShadersStore.defaultFragmentDeclaration="uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;uniform vec4 refractionRightColor;\n#endif\n#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D)\nuniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; \n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX)\nuniform mat4 reflectionMatrix;\n#endif\n#ifndef REFLECTIONMAP_SKYBOX\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include<decalFragmentDeclaration>\n#define ADDITIONAL_FRAGMENT_DECLARATION\n";li.IncludesShadersStore.sceneUboDeclaration="layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection;\n#ifdef MULTIVIEW\nmat4 viewProjectionR;\n#endif \nmat4 view;mat4 projection;vec4 vEyePosition;};\n";li.IncludesShadersStore.meshUboDeclaration="#ifdef WEBGL2\nuniform mat4 world;uniform float visibility;\n#else\nlayout(std140,column_major) uniform;uniform Mesh\n{mat4 world;float visibility;};\n#endif\n#define WORLD_UBO\n";li.IncludesShadersStore.defaultUboDeclaration="layout(std140,column_major) uniform;uniform Material\n{vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vReflectionInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 reflectionMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include<sceneUboDeclaration>\n#include<meshUboDeclaration>\n";li.IncludesShadersStore.prePassDeclaration="#ifdef PREPASS\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor;\n#ifdef PREPASS_DEPTH\nvarying highp vec3 vViewPos;\n#endif\n#ifdef PREPASS_VELOCITY\nvarying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition;\n#endif\n#endif\n";li.IncludesShadersStore.oitDeclaration="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out vec2 depth; \nlayout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor;\n#define MAX_DEPTH 99999.0\nhighp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler;\n#endif\n";li.IncludesShadersStore.mainUVVaryingDeclaration="#ifdef MAINUV{X}\nvarying vec2 vMainUV{X};\n#endif\n";li.IncludesShadersStore.helperFunctions="const float PI=3.1415926535897932384626433832795;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float HALF_MIN=5.96046448e-08; \nconst float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001;\n#define saturate(x) clamp(x,0.0,1.0)\n#define absEps(x) abs(x)+Epsilon\n#define maxEps(x) max(x,Epsilon)\n#define saturateEps(x) clamp(x,Epsilon,1.0)\nmat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);return outMatrix;}\nmat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;}\n#if USE_EXACT_SRGB_CONVERSIONS\nvec3 toLinearSpaceExact(vec3 color)\n{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));\n#else\nreturn\nvec3(\ncolor.r<=0.04045 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.04045 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.04045 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\nvec3 toGammaSpaceExact(vec3 color)\n{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055);\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));\n#else\nreturn\nvec3(\ncolor.r<=0.0031308 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.0031308 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.0031308 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\n#endif\nfloat toLinearSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,LinearEncodePowerApprox);\n#endif\n}\nvec3 toLinearSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3(LinearEncodePowerApprox));\n#endif\n}\nvec4 toLinearSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toLinearSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);\n#endif\n}\nfloat toGammaSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,GammaEncodePowerApprox);\n#endif\n}\nvec3 toGammaSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3(GammaEncodePowerApprox));\n#endif\n}\nvec4 toGammaSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toGammaSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);\n#endif\n}\nfloat square(float value)\n{return value*value;}\nvec3 square(vec3 value)\n{return value*value;}\nfloat pow5(float value) {float sq=value*value;return sq*sq*value;}\nfloat getLuminance(vec3 color)\n{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);}\nfloat getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}\nfloat dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;}\nconst float rgbdMaxRange=255.0;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(clamp(rgb,0.,1.),D); }\nvec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;}\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}\n";li.IncludesShadersStore.lightFragmentDeclaration="#ifdef LIGHT{X}\nuniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\n#else\nvec4 vLightSpecular{X}=vec4(0.);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\n#else\nuniform highp sampler2DArray shadowSampler{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);vec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};uniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X};\n#endif\n#endif\n";li.IncludesShadersStore.lightUboDeclaration="#ifdef LIGHT{X}\nuniform Light{X}\n{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;vec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;vec2 depthValues;} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\n#else\nuniform highp sampler2DArray shadowSampler{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);vec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif\n";li.IncludesShadersStore.lightsFragmentFunctions="struct lightingInfo\n{vec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.)\n{vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);}\nelse\n{lightVectorW=normalize(-lightData.xyz);}\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w)\n{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;float ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor;\n#endif\nreturn result;}\n#define inline\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}";li.IncludesShadersStore.shadowsFragmentFunctions="#ifdef SHADOWS\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}\n#endif\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);}\n#define inline\nfloat computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nreturn depth>shadow ? darkness : 1.0;}\n#define inline\nfloat computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0);\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);}\n#define inline\nfloat computeShadowWithESMCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return esm;}\n#define inline\nfloat computeShadowWithCloseESMCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return esm;}\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define inline\nfloat computeShadowCSM(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray shadowSampler,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);vec3 uvLayer=vec3(uv.x,uv.y,layer);float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uvLayer));\n#else\nfloat shadow=texture2D(shadowSampler,uvLayer).x;\n#endif\nreturn shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}\n#endif\n#define inline\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadow=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nreturn shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}}\n#define inline\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760);\n#ifndef SHADOWFLOAT\nif (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;\n#else\nif (TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\n#ifdef IS_NDC_HALF_ZRANGE\n#define ZINCLIP clipSpace.z\n#else\n#define ZINCLIP uvDepth.z\n#endif\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define GREATEST_LESS_THAN_ONE 0.99999994\n/* disable_uniformity_analysis */\n#define inline\nfloat computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.)\n);const vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n#define inline\nfloat computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i<searchTapCount; i ++) {blockerDepth=texture2D(depthSampler,vec3(uvDepth.xy+(lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse*PoissonSamplers32[i].xy),layer)).r;if (blockerDepth<depthMetric) {sumBlockerDepth+=blockerDepth;numBlocker++;}}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;float AAOffset=shadowMapSizeInverse*10.;float penumbraRatio=((depthMetric-avgBlockerDepth)*depthCorrection+AAOffset);vec4 filterRadius=vec4(penumbraRatio*lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse,0.,0.);float random=getRand(vPositionFromLight.xy);float rotationAngle=random*3.1415926;vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));float shadow=0.;for (int i=0; i<pcfTapCount; i++) {vec4 offset=vec4(poissonSamplers[i],0.);offset=vec4(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.,0.);shadow+=texture2D(shadowSampler,uvDepthLayer+offset*filterRadius);}\nshadow/=float(pcfTapCount);shadow=mix(shadow,1.,min((depthMetric-avgBlockerDepth)*depthCorrection*penumbraDarkness,1.));shadow=mix(darkness,1.,shadow);if (numBlocker<1.0) {return 1.0;}\nelse\n{return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i<searchTapCount; i ++) {blockerDepth=TEXTUREFUNC(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy),0.).r;if (blockerDepth<depthMetric) {sumBlockerDepth+=blockerDepth;numBlocker++;}}\nif (numBlocker<1.0) {return 1.0;}\nelse\n{float avgBlockerDepth=sumBlockerDepth/numBlocker;float AAOffset=shadowMapSizeInverse*10.;float penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);float filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;float random=getRand(vPositionFromLight.xy);float rotationAngle=random*3.1415926;vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));float shadow=0.;for (int i=0; i<pcfTapCount; i++) {vec3 offset=poissonSamplers[i];offset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);shadow+=TEXTUREFUNC(shadowSampler,uvDepth+offset*filterRadius,0.);}\nshadow/=float(pcfTapCount);shadow=mix(shadow,1.,depthMetric-avgBlockerDepth);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}}\n#define inline\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);}\n#define inline\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);}\n#define inline\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);}\n#define inline\nfloat computeShadowWithCSMPCSS16(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\n#define inline\nfloat computeShadowWithCSMPCSS32(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\n#define inline\nfloat computeShadowWithCSMPCSS64(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\n#endif\n#endif\n";li.IncludesShadersStore.samplerFragmentDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying vec2 v_VARYINGNAME_UV;\n#endif\nuniform sampler2D _SAMPLERNAME_Sampler;\n#endif\n";li.IncludesShadersStore.fresnelFunction="#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{float fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);}\n#endif\n";li.IncludesShadersStore.reflectionFunction="vec3 computeFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)\n{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0); }\nvec3 computeMirroredFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction)\n{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(1.0-s,t,0); }\nvec3 computeEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)\n{vec3 cameraToVertex=normalize(worldPos.xyz-eyePosition);vec3 r=normalize(reflect(cameraToVertex,worldNormal));r=vec3(reflectionMatrix*vec4(r,0));float lon=atan(r.z,r.x);float lat=acos(r.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0);}\nvec3 computeSphericalCoords(vec4 worldPos,vec3 worldNormal,mat4 view,mat4 reflectionMatrix)\n{vec3 viewDir=normalize(vec3(view*worldPos));vec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));vec3 r=reflect(viewDir,viewNormal);r=vec3(reflectionMatrix*vec4(r,0));r.z=r.z-1.0;float m=2.0*length(r);return vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);}\nvec3 computePlanarCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)\n{vec3 viewDir=worldPos.xyz-eyePosition;vec3 coords=normalize(reflect(viewDir,worldNormal));return vec3(reflectionMatrix*vec4(coords,1));}\nvec3 computeCubicCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix)\n{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;}\nvec3 computeCubicLocalCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix,vec3 reflectionSize,vec3 reflectionPosition)\n{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);coords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;}\nvec3 computeProjectionCoords(vec4 worldPos,mat4 view,mat4 reflectionMatrix)\n{return vec3(reflectionMatrix*(view*worldPos));}\nvec3 computeSkyBoxCoords(vec3 positionW,mat4 reflectionMatrix)\n{return vec3(reflectionMatrix*vec4(positionW,1.));}\n#ifdef REFLECTION\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);return computeFixedEquirectangularCoords(worldPos,worldNormal,direction);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nreturn computeEquirectangularCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nreturn computeSphericalCoords(worldPos,worldNormal,view,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nreturn computePlanarCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_CUBIC\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nreturn computeCubicLocalCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix,vReflectionSize,vReflectionPosition);\n#else\nreturn computeCubicCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix);\n#endif\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn computeProjectionCoords(worldPos,view,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn computeSkyBoxCoords(vPositionUVW,reflectionMatrix);\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\n";li.IncludesShadersStore.imageProcessingDeclaration="#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#if defined(VIGNETTE) || defined(DITHER)\nuniform vec2 vInverseScreenSize;\n#endif\n#ifdef VIGNETTE\nuniform vec4 vignetteSettings1;uniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;uniform vec4 vCameraColorCurveNeutral;uniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef DITHER\nuniform float ditherIntensity;\n#endif\n";li.IncludesShadersStore.imageProcessingFunctions="#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n/** \n* Polyfill for SAMPLE_TEXTURE_3D,which is unsupported in WebGL.\n* sampler3dSetting.x=textureOffset (0.5/textureSize).\n* sampler3dSetting.y=textureSize.\n*/\n#define inline\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{float sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);float sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;sliceUV.x+=sliceInteger*sliceSize;sliceUV=saturate(sliceUV);vec4 slice0Color=texture2D(colorTransform,sliceUV);sliceUV.x+=sliceSize;sliceUV=saturate(sliceUV);vec4 slice1Color=texture2D(colorTransform,sliceUV);vec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;}\n#endif\n#if TONEMAPPING==3\nconst float PBRNeutralStartCompression=0.8-0.04;const float PBRNeutralDesaturation=0.15;vec3 PBRNeutralToneMapping( vec3 color ) {float x=min(color.r,min(color.g,color.b));float offset=x<0.08 ? x-6.25*x*x : 0.04;color-=offset;float peak=max(color.r,max(color.g,color.b));if (peak<PBRNeutralStartCompression) return color;float d=1.-PBRNeutralStartCompression;float newPeak=1.-d*d/(peak+d-PBRNeutralStartCompression);color*=newPeak/peak;float g=1.-1./(PBRNeutralDesaturation*(peak-newPeak)+1.);return mix(color,newPeak*vec3(1,1,1),g);}\n#endif\n#if TONEMAPPING==2\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);const mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108, 1.10813,-0.07276),\nvec3(-0.07367,-0.00605, 1.07602)\n);vec3 RRTAndODTFit(vec3 v)\n{vec3 a=v*(v+0.0245786)-0.000090537;vec3 b=v*(0.983729*v+0.4329510)+0.238081;return a/b;}\nvec3 ACESFitted(vec3 color)\n{color=ACESInputMat*color;color=RRTAndODTFit(color);color=ACESOutputMat*color;color=saturate(color);return color;}\n#endif\n#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_DEFINITIONS\nvec4 applyImageProcessing(vec4 result) {\n#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATSTART\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;viewportXY=viewportXY*2.0-1.0;vec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);float vignetteTerm=dot(vignetteXY1,vignetteXY1);float vignette=pow(vignetteTerm,vignetteSettings2.w);vec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);result.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#if TONEMAPPING==3\nresult.rgb=PBRNeutralToneMapping(result.rgb);\n#elif TONEMAPPING==2\nresult.rgb=ACESFitted(result.rgb);\n#elif TONEMAPPING==1\nconst float tonemappingCalibration=1.590579;result.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\nresult.rgb=toGammaSpace(result.rgb);result.rgb=saturate(result.rgb);\n#ifdef CONTRAST\nvec3 resultHighContrast=result.rgb*result.rgb*(3.0-2.0*result.rgb);if (contrast<1.0) {result.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);} else {result.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);}\n#endif\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\nfloat luma=getLuminance(result.rgb);vec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));vec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;result.rgb*=colorCurve.rgb;result.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\n#ifdef DITHER\nfloat rand=getRand(gl_FragCoord.xy*vInverseScreenSize);float dither=mix(-ditherIntensity,ditherIntensity,rand);result.rgb=saturate(result.rgb+vec3(dither));\n#endif\n#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATEND\nreturn result;}";li.IncludesShadersStore.bumpFragmentMainFunctions="#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#if defined(WEBGL2) || defined(WEBGPU)\nmat4 toNormalMatrix(mat4 wMatrix)\n{mat4 ret=inverse(wMatrix);ret=transpose(ret);ret[0][3]=0.;ret[1][3]=0.;ret[2][3]=0.;ret[3]=vec4(0.,0.,0.,1.);return ret;}\n#else\nmat4 toNormalMatrix(mat4 m)\n{float\na00=m[0][0],a01=m[0][1],a02=m[0][2],a03=m[0][3],\na10=m[1][0],a11=m[1][1],a12=m[1][2],a13=m[1][3],\na20=m[2][0],a21=m[2][1],a22=m[2][2],a23=m[2][3],\na30=m[3][0],a31=m[3][1],a32=m[3][2],a33=m[3][3],\nb00=a00*a11-a01*a10,\nb01=a00*a12-a02*a10,\nb02=a00*a13-a03*a10,\nb03=a01*a12-a02*a11,\nb04=a01*a13-a03*a11,\nb05=a02*a13-a03*a12,\nb06=a20*a31-a21*a30,\nb07=a20*a32-a22*a30,\nb08=a20*a33-a23*a30,\nb09=a21*a32-a22*a31,\nb10=a21*a33-a23*a31,\nb11=a22*a33-a23*a32,\ndet=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;mat4 mi=mat4(\na11*b11-a12*b10+a13*b09,\na02*b10-a01*b11-a03*b09,\na31*b05-a32*b04+a33*b03,\na22*b04-a21*b05-a23*b03,\na12*b08-a10*b11-a13*b07,\na00*b11-a02*b08+a03*b07,\na32*b02-a30*b05-a33*b01,\na20*b05-a22*b02+a23*b01,\na10*b10-a11*b08+a13*b06,\na01*b08-a00*b10-a03*b06,\na30*b04-a31*b02+a33*b00,\na21*b02-a20*b04-a23*b00,\na11*b07-a10*b09-a12*b06,\na00*b09-a01*b07+a02*b06,\na31*b01-a30*b03-a32*b00,\na20*b03-a21*b01+a22*b00)/det;return mat4(mi[0][0],mi[1][0],mi[2][0],mi[3][0],\nmi[0][1],mi[1][1],mi[2][1],mi[3][1],\nmi[0][2],mi[1][2],mi[2][2],mi[3][2],\nmi[0][3],mi[1][3],mi[2][3],mi[3][3]);}\n#endif\n#endif\nvec3 perturbNormalBase(mat3 cotangentFrame,vec3 normal,float scale)\n{\n#ifdef NORMALXYSCALE\nnormal=normalize(normal*vec3(scale,scale,1.0));\n#endif\nreturn normalize(cotangentFrame*normal);}\nvec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float scale)\n{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);}\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv,vec2 tangentSpaceParams)\n{vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;float det=max(dot(tangent,tangent),dot(bitangent,bitangent));float invmax=det==0.0 ? 0.0 : inversesqrt(det);return mat3(tangent*invmax,bitangent*invmax,normal);}\n#endif\n";li.IncludesShadersStore.bumpFragmentFunctions="#if defined(BUMP)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump)\n#endif\n#if defined(DETAIL)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail)\n#endif\n#if defined(BUMP) && defined(PARALLAX)\nconst float minSamples=4.;const float maxSamples=15.;const int iMaxSamples=15;vec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {float parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;vec2 vOffsetDir=normalize(vViewDirCoT.xy);vec2 vMaxOffset=vOffsetDir*parallaxLimit;float numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));float stepSize=1.0/numSamples;float currRayHeight=1.0;vec2 vCurrOffset=vec2(0,0);vec2 vLastOffset=vec2(0,0);float lastSampledHeight=1.0;float currSampledHeight=1.0;bool keepWorking=true;for (int i=0; i<iMaxSamples; i++)\n{currSampledHeight=texture2D(bumpSampler,texCoord+vCurrOffset).w;if (!keepWorking)\n{}\nelse if (currSampledHeight>currRayHeight)\n{float delta1=currSampledHeight-currRayHeight;float delta2=(currRayHeight+stepSize)-lastSampledHeight;float ratio=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;}\nelse\n{currRayHeight-=stepSize;vLastOffset=vCurrOffset;\n#ifdef PARALLAX_RHS\nvCurrOffset-=stepSize*vMaxOffset;\n#else\nvCurrOffset+=stepSize*vMaxOffset;\n#endif\nlastSampledHeight=currSampledHeight;}}\nreturn vCurrOffset;}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{float height=texture2D(bumpSampler,vBumpUV).w;vec2 texCoordOffset=heightScale*viewDir.xy*height;\n#ifdef PARALLAX_RHS\nreturn texCoordOffset;\n#else\nreturn -texCoordOffset;\n#endif\n}\n#endif\n";li.IncludesShadersStore.clipPlaneFragmentDeclaration="#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nvarying float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nvarying float fClipDistance6;\n#endif\n";li.IncludesShadersStore.logDepthDeclaration="#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;varying float vFragmentDepth;\n#endif\n";li.IncludesShadersStore.fogFragmentDeclaration="#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;uniform vec3 vFogColor;varying vec3 vFogDistance;float CalcFogFactor()\n{float fogCoeff=1.0;float fogStart=vFogInfos.y;float fogEnd=vFogInfos.z;float fogDensity=vFogInfos.w;float fogDistance=length(vFogDistance);if (FOGMODE_LINEAR==vFogInfos.x)\n{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);}\nelse if (FOGMODE_EXP==vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDensity);}\nelse if (FOGMODE_EXP2==vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);}\nreturn clamp(fogCoeff,0.0,1.0);}\n#endif\n";li.IncludesShadersStore.clipPlaneFragment="#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nif (false) {}\n#endif\n#ifdef CLIPPLANE\nelse if (fClipDistance>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE2\nelse if (fClipDistance2>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE3\nelse if (fClipDistance3>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE4\nelse if (fClipDistance4>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE5\nelse if (fClipDistance5>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE6\nelse if (fClipDistance6>0.0)\n{discard;}\n#endif\n";li.IncludesShadersStore.bumpFragment="vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#elif defined(BUMP)\nfloat normalScale=vBumpInfos.y;\n#else\nfloat normalScale=1.0;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#elif defined(BUMP)\nvec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams);\n#else\nvec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.));\n#endif\n#elif defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nvec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.));\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef DETAIL\nvec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);vec2 detailNormalRG=detailColor.wy*2.0-1.0;float detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));vec3 detailNormal=vec3(detailNormalRG,detailNormalB);\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\n#define CUSTOM_FRAGMENT_BUMP_FRAGMENT\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3(normalMatrix)*normalW);\n#elif !defined(DETAIL)\nnormalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y);\n#else\nvec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0;\n#if DETAIL_NORMALBLENDMETHOD==0 \ndetailNormal.xy*=vDetailInfos.z;vec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z));\n#elif DETAIL_NORMALBLENDMETHOD==1 \ndetailNormal.xy*=vDetailInfos.z;bumpNormal+=vec3(0.0,0.0,1.0);detailNormal*=vec3(-1.0,-1.0,1.0);vec3 blendedNormal=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal;\n#endif\nnormalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y);\n#endif\n#elif defined(DETAIL)\ndetailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z);\n#endif\n";li.IncludesShadersStore.decalFragment="#ifdef DECAL\n#ifdef GAMMADECAL\ndecalColor.rgb=toLinearSpace(decalColor.rgb);\n#endif\n#ifdef DECAL_SMOOTHALPHA\ndecalColor.a*=decalColor.a;\n#endif\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a);\n#endif\n";li.IncludesShadersStore.depthPrePass="#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);return;\n#endif\n";li.IncludesShadersStore.lightFragment="#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(POINTLIGHT{X})\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(HEMILIGHT{X})\npreInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(DIRLIGHT{X})\npreInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#endif\npreInfo.NdotV=NdotV;\n#ifdef SPOTLIGHT{X}\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\n#elif defined(POINTLIGHT{X})\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\n#else\npreInfo.attenuation=1.0;\n#endif\n#ifdef HEMILIGHT{X}\npreInfo.roughness=roughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#ifdef IRIDESCENCE\npreInfo.iridescenceIntensity=iridescenceIntensity;\n#endif\n#ifdef HEMILIGHT{X}\ninfo.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround);\n#elif defined(SS_TRANSLUCENCY)\ninfo.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance);\n#else\ninfo.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb);\n#endif\n#ifdef SPECULARTERM\n#ifdef ANISOTROPIC\ninfo.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#else\ninfo.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#endif\n#endif\n#ifdef SHEEN\n#ifdef SHEEN_LINKWITHALBEDO\npreInfo.roughness=sheenOut.sheenIntensity;\n#else\n#ifdef HEMILIGHT{X}\npreInfo.roughness=sheenOut.sheenRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#endif\ninfo.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#endif\n#ifdef CLEARCOAT\n#ifdef HEMILIGHT{X}\npreInfo.roughness=clearcoatOut.clearCoatRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\ninfo.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb);\n#ifdef CLEARCOAT_TINT\nabsorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption;\n#ifdef SPECULARTERM\ninfo.specular*=absorption;\n#endif\n#endif\ninfo.diffuse*=info.clearCoat.w;\n#ifdef SPECULARTERM\ninfo.specular*=info.clearCoat.w;\n#endif\n#ifdef SHEEN\ninfo.sheen*=info.clearCoat.w;\n#endif\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nfor (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) \n{\n#ifdef SHADOWCSM_RIGHTHANDED{X}\ndiff{X}=viewFrustumZ{X}[i]+vPositionFromCamera{X}.z;\n#else\ndiff{X}=viewFrustumZ{X}[i]-vPositionFromCamera{X}.z;\n#endif\nif (diff{X}>=0.) {index{X}=i;break;}}\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nif (index{X}>=0)\n#endif\n{\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#else\nshadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#endif\n#else\nshadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}];\n#endif\n#ifndef SHADOWCSMNOBLEND{X}\nfloat frustumLength=frustumLengths{X}[index{X}];float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.)\n{index{X}+=1;float nextShadow=0.;\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nnextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#else\nnextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\n#endif\n#else\nnextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\nshadow=mix(nextShadow,shadow,diffRatio);\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio);\n#endif\n}\n#endif\n}\n#elif defined(SHADOWCLOSEESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;shadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\naggShadow+=shadow;numLights+=1.0;\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor.rgb*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef CLEARCOAT\n#ifndef LIGHTMAPNOSPECULAR{X}\nclearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef SHEEN\n#ifndef LIGHTMAPNOSPECULAR{X}\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#else\n#ifdef SHADOWCSMDEBUG{X}\ndiffuseBase+=info.diffuse*shadowDebug{X};\n#else \ndiffuseBase+=info.diffuse*shadow;\n#endif\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#ifdef CLEARCOAT\nclearCoatBase+=info.clearCoat.rgb*shadow;\n#endif\n#ifdef SHEEN\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#endif\n#endif\n";li.IncludesShadersStore.logDepthFragment="#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif\n";li.IncludesShadersStore.fogFragment="#ifdef FOG\nfloat fog=CalcFogFactor();\n#ifdef PBR\nfog=toLinearSpace(fog);\n#endif\ncolor.rgb=mix(vFogColor,color.rgb,fog);\n#endif\n";li.IncludesShadersStore.oitFragment="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\nfloat fragDepth=gl_FragCoord.z; \n#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS\nuint halfFloat=packHalf2x16(vec2(fragDepth));vec2 full=unpackHalf2x16(halfFloat);fragDepth=full.x;\n#endif\nivec2 fragCoord=ivec2(gl_FragCoord.xy);vec2 lastDepth=texelFetch(oitDepthSampler,fragCoord,0).rg;vec4 lastFrontColor=texelFetch(oitFrontColorSampler,fragCoord,0);depth.rg=vec2(-MAX_DEPTH);frontColor=lastFrontColor;backColor=vec4(0.0);\n#ifdef USE_REVERSE_DEPTHBUFFER\nfloat furthestDepth=-lastDepth.x;float nearestDepth=lastDepth.y;\n#else\nfloat nearestDepth=-lastDepth.x;float furthestDepth=lastDepth.y;\n#endif\nfloat alphaMultiplier=1.0-lastFrontColor.a;\n#ifdef USE_REVERSE_DEPTHBUFFER\nif (fragDepth>nearestDepth || fragDepth<furthestDepth) {\n#else\nif (fragDepth<nearestDepth || fragDepth>furthestDepth) {\n#endif\nreturn;}\n#ifdef USE_REVERSE_DEPTHBUFFER\nif (fragDepth<nearestDepth && fragDepth>furthestDepth) {\n#else\nif (fragDepth>nearestDepth && fragDepth<furthestDepth) {\n#endif\ndepth.rg=vec2(-fragDepth,fragDepth);return;}\n#endif\n";li.ShadersStore.defaultPixelShader="#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#include<prePassDeclaration>[SCENE_MRT_COUNT]\n#include<oitDeclaration>\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include<mainUVVaryingDeclaration>[1..7]\n#include<helperFunctions>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<samplerFragmentDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULARTERM)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular)\n#endif\n#include<fresnelFunction>\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentMainFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS)\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#if defined(DECAL) && !defined(DECAL_AFTER_DETAIL)\nvec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset);\n#include<decalFragment>(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_)\n#endif\n#include<depthPrePass>\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef DETAIL\nbaseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y);\n#endif\n#if defined(DECAL) && defined(DECAL_AFTER_DETAIL)\nvec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset);\n#include<decalFragment>(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_)\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);specularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef LIGHTMAP\nvec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);\n#ifdef RGBDLIGHTMAP\nlightmapColor.rgb=fromRGBD(lightmapColor);\n#endif\nlightmapColor.rgb*=vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\naggShadow=aggShadow/numLights;vec4 refractionColor=vec4(0.,0.,0.,1.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\n#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC\nrefractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition);\n#endif\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;vec4 refractionLookup=textureCube(refractionCubeSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=texture2D(refraction2DSampler,refractionCoords);\n#endif\n#ifdef RGBDREFRACTION\nrefractionColor.rgb=fromRGBD(refractionColor);\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor.rgb=toGammaSpace(refractionColor.rgb);\n#endif\nrefractionColor.rgb*=vRefractionInfos.x;\n#endif\nvec4 reflectionColor=vec4(0.,0.,0.,1.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nvReflectionUVW.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias);\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW);\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;reflectionColor=texture2D(reflection2DSampler,coords);\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor.rgb=toGammaSpace(reflectionColor.rgb);\n#endif\nreflectionColor.rgb*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);refractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n#ifdef ALPHATEST\n#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS\nif (alpha<alphaCutOff)\ndiscard;\n#endif\n#ifndef ALPHABLEND\nalpha=1.0;\n#endif\n#endif\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);emissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);diffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor.rgb,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+emissiveColor+refractionColor.rgb,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+refractionColor.rgb,alpha);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor.rgb;\n#else\ncolor.rgb+=lightmapColor.rgb;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color);\n#endif\n#endif\ncolor.a*=visibility;\n#ifdef PREMULTIPLYALPHA\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\n#ifdef PREPASS\nfloat writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0;gl_FragData[0]=color; \n#ifdef PREPASS_POSITION\ngl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);\n#endif\n#ifdef PREPASS_VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo);\n#endif\n#ifdef PREPASS_IRRADIANCE\ngl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); \n#endif\n#ifdef PREPASS_DEPTH\ngl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); \n#endif\n#ifdef PREPASS_NORMAL\n#ifdef PREPASS_NORMAL_WORLDSPACE\ngl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); \n#else\ngl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); \n#endif\n#endif\n#ifdef PREPASS_ALBEDO_SQRT\ngl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); \n#endif\n#ifdef PREPASS_REFLECTIVITY\n#if defined(SPECULARTERM)\n#if defined(SPECULAR)\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularMapColor))*writeGeometryInfo; \n#else\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularColor),1.0)*writeGeometryInfo;\n#endif\n#else\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(0.0,0.0,0.0,1.0)*writeGeometryInfo;\n#endif\n#endif\n#endif\n#if !defined(PREPASS) || defined(WEBGL2)\ngl_FragColor=color;\n#endif\n#include<oitFragment>\n#if ORDER_INDEPENDENT_TRANSPARENCY\nif (fragDepth==nearestDepth) {frontColor.rgb+=color.rgb*color.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-color.a);} else {backColor+=color;}\n#endif\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";li.IncludesShadersStore.decalVertexDeclaration="#ifdef DECAL\nuniform vec4 vDecalInfos;uniform mat4 decalMatrix;\n#endif\n";li.IncludesShadersStore.defaultVertexDeclaration="uniform mat4 viewProjection;uniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;uniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;uniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;uniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform mat4 bumpMatrix;\n#endif\n#ifdef REFLECTION\nuniform mat4 reflectionMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;uniform mat4 detailMatrix;\n#endif\n#include<decalVertexDeclaration>\n#define ADDITIONAL_VERTEX_DECLARATION\n";li.IncludesShadersStore.uvAttributeDeclaration="#ifdef UV{X}\nattribute vec2 uv{X};\n#endif\n";li.IncludesShadersStore.bonesDeclaration="#if NUM_BONE_INFLUENCERS>0\nattribute vec4 matricesIndices;attribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra;\n#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nuniform highp sampler2D boneSampler;uniform float boneTextureWidth;\n#else\nuniform mat4 mBones[BonesPerMesh];\n#endif\n#ifdef BONES_VELOCITY_ENABLED\nuniform mat4 mPreviousBones[BonesPerMesh];\n#endif\n#ifdef BONETEXTURE\n#define inline\nmat4 readMatrixFromRawSampler(sampler2D smp,float index)\n{float offset=index *4.0;float dx=1.0/boneTextureWidth;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));return mat4(m0,m1,m2,m3);}\n#endif\n#endif\n#endif\n";li.IncludesShadersStore.bakedVertexAnimationDeclaration="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform float bakedVertexAnimationTime;uniform vec2 bakedVertexAnimationTextureSizeInverted;uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture;\n#ifdef INSTANCES\nattribute vec4 bakedVertexAnimationSettingsInstanced;\n#endif\n#define inline\nmat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame)\n{float offset=index*4.0;float frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;float dx=bakedVertexAnimationTextureSizeInverted.x;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));return mat4(m0,m1,m2,m3);}\n#endif\n";li.IncludesShadersStore.instancesDeclaration="#ifdef INSTANCES\nattribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;\n#ifdef INSTANCESCOLOR\nattribute vec4 instanceColor;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform mat4 world;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nattribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3;\n#ifdef THIN_INSTANCES\nuniform mat4 previousWorld;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform mat4 world;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nuniform mat4 previousWorld;\n#endif\n#endif\n";li.IncludesShadersStore.prePassVertexDeclaration="#ifdef PREPASS\n#ifdef PREPASS_DEPTH\nvarying vec3 vViewPos;\n#endif\n#ifdef PREPASS_VELOCITY\nuniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#endif\n";li.IncludesShadersStore.samplerVertexDeclaration="#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0\nvarying vec2 v_VARYINGNAME_UV;\n#endif\n";li.IncludesShadersStore.bumpVertexDeclaration="#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n";li.IncludesShadersStore.clipPlaneVertexDeclaration="#ifdef CLIPPLANE\nuniform vec4 vClipPlane;varying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;varying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;varying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;varying float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nuniform vec4 vClipPlane5;varying float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nuniform vec4 vClipPlane6;varying float fClipDistance6;\n#endif\n";li.IncludesShadersStore.fogVertexDeclaration="#ifdef FOG\nvarying vec3 vFogDistance;\n#endif\n";li.IncludesShadersStore.lightVxFragmentDeclaration="#ifdef LIGHT{X}\nuniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\n#else\nvec4 vLightSpecular{X}=vec4(0.);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#elif defined(SHADOWCUBE{X})\n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};uniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#endif\n";li.IncludesShadersStore.lightVxUboDeclaration="#ifdef LIGHT{X}\nuniform Light{X}\n{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;vec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;vec2 depthValues;} light{X};\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#elif defined(SHADOWCUBE{X})\n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif\n";li.IncludesShadersStore.morphTargetsVertexGlobalDeclaration="#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#ifdef MORPHTARGETS_TEXTURE \nuniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform highp sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex)\n{ \nfloat y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV).xyz;}\n#endif\n#endif\n";li.IncludesShadersStore.morphTargetsVertexDeclaration="#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#ifdef MORPHTARGETS_UV\nattribute vec2 uv_{X};\n#endif\n#elif {X}==0\nuniform int morphTargetCount;\n#endif\n#endif\n";li.IncludesShadersStore.morphTargetsVertexGlobal="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nfloat vertexID;\n#endif\n#endif\n";li.IncludesShadersStore.morphTargetsVertex="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\n#if {X}==0\nfor (int i=0; i<NUM_MORPH_INFLUENCERS; i++) {if (i>=morphTargetCount) break;vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;positionUpdated+=(readVector3FromRawSampler(i,vertexID)-position)*morphTargetInfluences[i];vertexID+=1.0;\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(readVector3FromRawSampler(i,vertexID) -normal)*morphTargetInfluences[i];vertexID+=1.0;\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated+=(readVector3FromRawSampler(i,vertexID).xy-uv)*morphTargetInfluences[i];vertexID+=1.0;\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(readVector3FromRawSampler(i,vertexID) -tangent.xyz)*morphTargetInfluences[i];\n#endif\n}\n#endif\n#else\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}];\n#endif\n#endif\n#endif\n";li.IncludesShadersStore.instancesVertex="#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nmat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,previousWorld2,previousWorld3);\n#endif\n#ifdef THIN_INSTANCES\nfinalWorld=world*finalWorld;\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nfinalPreviousWorld=previousWorld*finalPreviousWorld;\n#endif\n#endif\n#else\nmat4 finalWorld=world;\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nmat4 finalPreviousWorld=previousWorld;\n#endif\n#endif\n";li.IncludesShadersStore.bonesVertex="#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\ninfluence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3];\n#endif\n#else\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\n#endif\nfinalWorld=finalWorld*influence;\n#endif\n#endif\n";li.IncludesShadersStore.bakedVertexAnimation="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\n#ifdef INSTANCES\n#define BVASNAME bakedVertexAnimationSettingsInstanced\n#else\n#define BVASNAME bakedVertexAnimationSettings\n#endif\nfloat VATStartFrame=BVASNAME.x;float VATEndFrame=BVASNAME.y;float VATOffsetFrame=BVASNAME.z;float VATSpeed=BVASNAME.w;float totalFrames=VATEndFrame-VATStartFrame+1.0;float time=bakedVertexAnimationTime*VATSpeed/totalFrames;float frameCorrection=time<1.0 ? 0.0 : 1.0;float numOfFrames=totalFrames-frameCorrection;float VATFrameNum=fract(time)*numOfFrames;VATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);VATFrameNum=floor(VATFrameNum);VATFrameNum+=VATStartFrame+frameCorrection;mat4 VATInfluence;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3];\n#endif\nfinalWorld=finalWorld*VATInfluence;}\n#endif\n";li.IncludesShadersStore.prePassVertex="#ifdef PREPASS_DEPTH\nvViewPos=(view*worldPos).rgb;\n#endif\n#if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*worldPos;\n#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);\n#else\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#endif\n";li.IncludesShadersStore.uvVariableDeclaration="#if !defined(UV{X}) && defined(MAINUV{X})\nvec2 uv{X}=vec2(0.,0.);\n#endif\n#ifdef MAINUV{X}\nvMainUV{X}=uv{X};\n#endif\n";li.IncludesShadersStore.samplerVertexImplementation="#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0\nif (v_INFONAME_==0.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));}\n#ifdef UV2\nelse if (v_INFONAME_==1.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2,1.0,0.0));}\n#endif\n#ifdef UV3\nelse if (v_INFONAME_==2.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));}\n#endif\n#ifdef UV4\nelse if (v_INFONAME_==3.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));}\n#endif\n#ifdef UV5\nelse if (v_INFONAME_==4.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));}\n#endif\n#ifdef UV6\nelse if (v_INFONAME_==5.)\n{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));}\n#endif\n#endif\n";li.IncludesShadersStore.bumpVertex="#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif\n";li.IncludesShadersStore.clipPlaneVertex="#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\n#endif\n#ifdef CLIPPLANE5\nfClipDistance5=dot(worldPos,vClipPlane5);\n#endif\n#ifdef CLIPPLANE6\nfClipDistance6=dot(worldPos,vClipPlane6);\n#endif\n";li.IncludesShadersStore.fogVertex="#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif\n";li.IncludesShadersStore.shadowsVertex="#ifdef SHADOWS\n#if defined(SHADOWCSM{X})\nvPositionFromCamera{X}=view*worldPos;for (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) {vPositionFromLight{X}[i]=lightMatrix{X}[i]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric{X}[i]=(-vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvDepthMetric{X}[i]=(vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n}\n#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric{X}=(-vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvDepthMetric{X}=(vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif\n#endif\n";li.IncludesShadersStore.vertexColorMixing="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvColor=vec4(1.0);\n#ifdef VERTEXCOLOR\n#ifdef VERTEXALPHA\nvColor*=color;\n#else\nvColor.rgb*=color.rgb;\n#endif\n#endif\n#ifdef INSTANCESCOLOR\nvColor*=instanceColor;\n#endif\n#endif\n";li.IncludesShadersStore.pointCloudVertex="#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n";li.IncludesShadersStore.logDepthVertex="#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;gl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif\n";li.ShadersStore.defaultVertexShader="#include<__decl__defaultVertex>\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#include<uvAttributeDeclaration>[2..7]\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<instancesDeclaration>\n#include<prePassVertexDeclaration>\n#include<mainUVVaryingDeclaration>[1..7]\n#include<samplerVertexDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse)\n#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)\n#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)\n#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)\n#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)\n#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)\n#if defined(SPECULARTERM)\n#include<samplerVertexDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular)\n#endif\n#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)\n#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertexGlobal>\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif\n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#endif\n#define CUSTOM_VERTEX_UPDATE_WORLDPOS\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\nvPositionW=vec3(worldPos);\n#include<prePassVertex>\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n#ifndef UV1\nvec2 uvUpdated=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uvUpdated;\n#endif\n#include<uvVariableDeclaration>[2..7]\n#include<samplerVertexImplementation>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)\n#if defined(SPECULARTERM)\n#include<samplerVertexImplementation>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x)\n#endif\n#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#include<vertexColorMixing>\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n";var Au=new RegExp("^([gimus]+)!"),Cu=function(){function e(e){this._plugins=[],this._activePlugins=[],this._activePluginsForExtraEvents=[],this._material=e,this._scene=e.getScene(),this._engine=this._scene.getEngine()}return e.prototype._addPlugin=function(t){for(var i=this,r=0;r<this._plugins.length;++r)if(this._plugins[r].name===t.name)return!1;if(this._material._uniformBufferLayoutBuilt)throw'The plugin "'.concat(t.name,'" can\'t be added to the material "').concat(this._material.name,'" because this material has already been used for rendering! Please add plugins to materials before any rendering with this material occurs.');var n=t.getClassName();e._MaterialPluginClassToMainDefine[n]||(e._MaterialPluginClassToMainDefine[n]="MATERIALPLUGIN_"+ ++e._MaterialPluginCounter),this._material._callbackPluginEventGeneric=function(e,t){return i._handlePluginEvent(e,t)},this._plugins.push(t),this._plugins.sort((function(e,t){return e.priority-t.priority})),this._codeInjectionPoints={};var o={};o[e._MaterialPluginClassToMainDefine[n]]={type:"boolean",default:!0};for(var a=0,s=this._plugins;a<s.length;a++){var l=s[a];l.collectDefines(o),this._collectPointNames("vertex",l.getCustomCode("vertex")),this._collectPointNames("fragment",l.getCustomCode("fragment"))}return this._defineNamesFromPlugins=o,!0},e.prototype._activatePlugin=function(e){-1===this._activePlugins.indexOf(e)&&(this._activePlugins.push(e),this._activePlugins.sort((function(e,t){return e.priority-t.priority})),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort((function(e,t){return e.priority-t.priority})),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))},e.prototype.getPlugin=function(e){for(var t=0;t<this._plugins.length;++t)if(this._plugins[t].name===e)return this._plugins[t];return null},e.prototype._handlePluginEventIsReadyForSubMesh=function(e){for(var t=!0,i=0,r=this._activePlugins;i<r.length;i++){var n=r[i];t=t&&n.isReadyForSubMesh(e.defines,this._scene,this._engine,e.subMesh)}e.isReadyForSubMesh=t},e.prototype._handlePluginEventPrepareDefinesBeforeAttributes=function(e){for(var t=0,i=this._activePlugins;t<i.length;t++)i[t].prepareDefinesBeforeAttributes(e.defines,this._scene,e.mesh)},e.prototype._handlePluginEventPrepareDefines=function(e){for(var t=0,i=this._activePlugins;t<i.length;t++)i[t].prepareDefines(e.defines,this._scene,e.mesh)},e.prototype._handlePluginEventHardBindForSubMesh=function(e){for(var t=0,i=this._activePluginsForExtraEvents;t<i.length;t++)i[t].hardBindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)},e.prototype._handlePluginEventBindForSubMesh=function(e){for(var t=0,i=this._activePlugins;t<i.length;t++)i[t].bindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)},e.prototype._handlePluginEventHasRenderTargetTextures=function(e){for(var t=!1,i=0,r=this._activePluginsForExtraEvents;i<r.length&&!(t=r[i].hasRenderTargetTextures());i++);e.hasRenderTargetTextures=t},e.prototype._handlePluginEventFillRenderTargetTextures=function(e){for(var t=0,i=this._activePluginsForExtraEvents;t<i.length;t++)i[t].fillRenderTargetTextures(e.renderTargets)},e.prototype._handlePluginEvent=function(e,t){var i,r,n,o;switch(e){case Vo.GetActiveTextures:for(var a=t,s=0,l=this._activePlugins;s<l.length;s++)(v=l[s]).getActiveTextures(a.activeTextures);break;case Vo.GetAnimatables:a=t;for(var c=0,u=this._activePlugins;c<u.length;c++)(v=u[c]).getAnimatables(a.animatables);break;case Vo.HasTexture:a=t;for(var h=!1,d=0,p=this._activePlugins;d<p.length&&!(h=(v=p[d]).hasTexture(a.texture));d++);a.hasTexture=h;break;case Vo.Disposed:a=t;for(var f=0,_=this._plugins;f<_.length;f++)(v=_[f]).dispose(a.forceDisposeTextures);break;case Vo.GetDefineNames:(a=t).defineNames=this._defineNamesFromPlugins;break;case Vo.PrepareEffect:a=t;for(var m=0,g=this._activePlugins;m<g.length;m++){var v=g[m];a.fallbackRank=v.addFallbacks(a.defines,a.fallbacks,a.fallbackRank),v.getAttributes(a.attributes,this._scene,a.mesh)}this._uniformList.length>0&&(i=a.uniforms).push.apply(i,this._uniformList),this._samplerList.length>0&&(r=a.samplers).push.apply(r,this._samplerList),this._uboList.length>0&&(n=a.uniformBuffersNames).push.apply(n,this._uboList),a.customCode=this._injectCustomCode(a,a.customCode);break;case Vo.PrepareUniformBuffer:a=t,this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];for(var y=0,b=this._plugins;y<b.length;y++){var T=(v=b[y]).getUniforms();if(T){if(T.ubo)for(var E=0,S=T.ubo;E<S.length;E++){var x=S[E];if(x.size&&x.type){var A=null!==(o=x.arraySize)&&void 0!==o?o:0;a.ubo.addUniform(x.name,x.size,A),this._uboDeclaration+="".concat(x.type," ").concat(x.name).concat(A>0?"[".concat(A,"]"):"",";\n")}this._uniformList.push(x.name)}T.vertex&&(this._vertexDeclaration+=T.vertex+"\n"),T.fragment&&(this._fragmentDeclaration+=T.fragment+"\n")}v.getSamplers(this._samplerList),v.getUniformBuffersNames(this._uboList)}}},e.prototype._collectPointNames=function(e,t){if(t)for(var i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0},e.prototype._injectCustomCode=function(e,t){var i=this;return function(r,n){var o,a;t&&(n=t(r,n)),i._uboDeclaration&&(n=n.replace("#define ADDITIONAL_UBO_DECLARATION",i._uboDeclaration)),i._vertexDeclaration&&(n=n.replace("#define ADDITIONAL_VERTEX_DECLARATION",i._vertexDeclaration)),i._fragmentDeclaration&&(n=n.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",i._fragmentDeclaration));var s=null===(o=i._codeInjectionPoints)||void 0===o?void 0:o[r];if(!s)return n;var l=null;for(var c in s){for(var u="",h=function(t){var n=null===(a=t.getCustomCode(r))||void 0===a?void 0:a[c];if(!n)return"continue";if(t.resolveIncludes){if(null===l){var o=pt.GLSL;l={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:i._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:i._engine.supportsUniformBuffers,shadersRepository:li.GetShadersRepository(o),includesShadersStore:li.GetIncludesShadersStore(o),version:void 0,platformName:i._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:i._engine.isNDCHalfZRange,useReverseDepthBuffer:i._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}l.isFragment="fragment"===r,oi(n,l,(function(e){return n=e}))}u+=n+"\n"},d=0,p=i._activePlugins;d<p.length;d++)h(p[d]);if(u.length>0)if("!"===c.charAt(0)){var f="g";if("!"===(c=c.substring(1)).charAt(0))f="",c=c.substring(1);else{var _=Au.exec(c);_&&_.length>=2&&(f=_[1],c=c.substring(f.length+1))}f.indexOf("g")<0&&(f+="g");for(var m=n,g=new RegExp(c,f),v=g.exec(m);null!==v;){for(var y=u,b=0;b<v.length;++b)y=y.replace("$"+b,v[b]);n=n.replace(v[0],y),v=g.exec(m)}}else{var T="#define "+c;n=n.replace(T,"\n"+u+"\n"+T)}}return n}},e._MaterialPluginClassToMainDefine={},e._MaterialPluginCounter=0,M.OnEnginesDisposedObservable.add((function(){Du()})),e}(),Ru=[],Pu=!1,Iu=null;function Mu(e,t){Pu||(Iu=Ca.OnEventObservable.add((function(e){for(var t=0,i=Ru;t<i.length;t++)(0,i[t][1])(e)}),Vo.Created),Pu=!0);var i=Ru.filter((function(t){var i=t[0];return t[1],i===e}));i.length>0?i[0][1]=t:Ru.push([e,t])}function Ou(e){for(var t=0;t<Ru.length;++t)if(Ru[t][0]===e)return Ru.splice(t,1),0===Ru.length&&Du(),!0;return!1}function Du(){Ru.length=0,Pu=!1,Ca.OnEventObservable.remove(Iu),Iu=null}var Nu=function(){function e(e,t,i,r,n,o,a){void 0===n&&(n=!0),void 0===o&&(o=!1),void 0===a&&(a=!1),this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=a,e.pluginManager||(e.pluginManager=new Cu(e),e.onDisposeObservable.add((function(){e.pluginManager=void 0}))),this._pluginDefineNames=r,this._pluginManager=e.pluginManager,n&&this._pluginManager._addPlugin(this),o&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[u.MATERIAL_AllDirtyFlag]}return e.prototype._enable=function(e){e&&this._pluginManager._activatePlugin(this)},e.prototype.getClassName=function(){return"MaterialPluginBase"},e.prototype.isReadyForSubMesh=function(e,t,i,r){return!0},e.prototype.hardBindForSubMesh=function(e,t,i,r){},e.prototype.bindForSubMesh=function(e,t,i,r){},e.prototype.dispose=function(e){},e.prototype.getCustomCode=function(e){return null},e.prototype.collectDefines=function(e){if(this._pluginDefineNames)for(var t=0,i=Object.keys(this._pluginDefineNames);t<i.length;t++){var r=i[t];if("_"!==r[0]){var n=typeof this._pluginDefineNames[r];e[r]={type:"number"===n?"number":"string"===n?"string":"boolean"===n?"boolean":"object",default:this._pluginDefineNames[r]}}}},e.prototype.prepareDefinesBeforeAttributes=function(e,t,i){},e.prototype.prepareDefines=function(e,t,i){},e.prototype.hasTexture=function(e){return!1},e.prototype.hasRenderTargetTextures=function(){return!1},e.prototype.fillRenderTargetTextures=function(e){},e.prototype.getActiveTextures=function(e){},e.prototype.getAnimatables=function(e){},e.prototype.addFallbacks=function(e,t,i){return i},e.prototype.getSamplers=function(e){},e.prototype.getAttributes=function(e,t,i){},e.prototype.getUniformBuffersNames=function(e){},e.prototype.getUniforms=function(){return{}},e.prototype.copyTo=function(e){Ke.Clone((function(){return e}),this)},e.prototype.serialize=function(){return Ke.Serialize(this)},e.prototype.parse=function(e,t,i){var r=this;Ke.Parse((function(){return r}),e,t,i)},v([Ie()],e.prototype,"name",void 0),v([Ie()],e.prototype,"priority",void 0),v([Ie()],e.prototype,"resolveIncludes",void 0),v([Ie()],e.prototype,"registerForExtraEvents",void 0),e}();a("BABYLON.MaterialPluginBase",Nu);var Fu=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.DETAIL=!1,t.DETAILDIRECTUV=0,t.DETAIL_NORMALBLENDMETHOD=0,t}return m(t,e),t}(Gs),Lu=function(e){function t(t,i){void 0===i&&(i=!0);var r=e.call(this,t,"DetailMap",140,new Fu,i)||this;return r._texture=null,r.diffuseBlendLevel=1,r.roughnessBlendLevel=1,r.bumpLevel=1,r._normalBlendMethod=Ca.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,r._isEnabled=!1,r.isEnabled=!1,r._internalMarkAllSubMeshesAsTexturesDirty=t._dirtyCallbacks[u.MATERIAL_TextureDirtyFlag],r}return m(t,e),t.prototype._markAllSubMeshesAsTexturesDirty=function(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()},t.prototype.isReadyForSubMesh=function(e,t,i){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&xu.DetailTextureEnabled&&!this._texture.isReady())},t.prototype.prepareDefines=function(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;var i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&xu.DetailTextureEnabled&&this._isEnabled?(ta(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1},t.prototype.bindForSubMesh=function(e,t){if(this._isEnabled){var i=this._material.isFrozen;e.useUbo&&i&&e.isSync||this._texture&&xu.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),ia(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&xu.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}},t.prototype.hasTexture=function(e){return this._texture===e},t.prototype.getActiveTextures=function(e){this._texture&&e.push(this._texture)},t.prototype.getAnimatables=function(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)},t.prototype.dispose=function(e){var t;e&&(null===(t=this._texture)||void 0===t||t.dispose())},t.prototype.getClassName=function(){return"DetailMapConfiguration"},t.prototype.getSamplers=function(e){e.push("detailSampler")},t.prototype.getUniforms=function(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}},v([Me("detailTexture"),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"texture",void 0),v([Ie()],t.prototype,"diffuseBlendLevel",void 0),v([Ie()],t.prototype,"roughnessBlendLevel",void 0),v([Ie()],t.prototype,"bumpLevel",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"normalBlendMethod",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"isEnabled",void 0),t}(Nu),wu={effect:null,subMesh:null},Bu=function(e){function t(t){var i=e.call(this,t)||this;return i.MAINUV1=!1,i.MAINUV2=!1,i.MAINUV3=!1,i.MAINUV4=!1,i.MAINUV5=!1,i.MAINUV6=!1,i.DIFFUSE=!1,i.DIFFUSEDIRECTUV=0,i.BAKED_VERTEX_ANIMATION_TEXTURE=!1,i.AMBIENT=!1,i.AMBIENTDIRECTUV=0,i.OPACITY=!1,i.OPACITYDIRECTUV=0,i.OPACITYRGB=!1,i.REFLECTION=!1,i.EMISSIVE=!1,i.EMISSIVEDIRECTUV=0,i.SPECULAR=!1,i.SPECULARDIRECTUV=0,i.BUMP=!1,i.BUMPDIRECTUV=0,i.PARALLAX=!1,i.PARALLAX_RHS=!1,i.PARALLAXOCCLUSION=!1,i.SPECULAROVERALPHA=!1,i.CLIPPLANE=!1,i.CLIPPLANE2=!1,i.CLIPPLANE3=!1,i.CLIPPLANE4=!1,i.CLIPPLANE5=!1,i.CLIPPLANE6=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.ALPHAFROMDIFFUSE=!1,i.POINTSIZE=!1,i.FOG=!1,i.SPECULARTERM=!1,i.DIFFUSEFRESNEL=!1,i.OPACITYFRESNEL=!1,i.REFLECTIONFRESNEL=!1,i.REFRACTIONFRESNEL=!1,i.EMISSIVEFRESNEL=!1,i.FRESNEL=!1,i.NORMAL=!1,i.TANGENT=!1,i.UV1=!1,i.UV2=!1,i.UV3=!1,i.UV4=!1,i.UV5=!1,i.UV6=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.BONETEXTURE=!1,i.BONES_VELOCITY_ENABLED=!1,i.INSTANCES=!1,i.THIN_INSTANCES=!1,i.INSTANCESCOLOR=!1,i.GLOSSINESS=!1,i.ROUGHNESS=!1,i.EMISSIVEASILLUMINATION=!1,i.LINKEMISSIVEWITHDIFFUSE=!1,i.REFLECTIONFRESNELFROMSPECULAR=!1,i.LIGHTMAP=!1,i.LIGHTMAPDIRECTUV=0,i.OBJECTSPACE_NORMALMAP=!1,i.USELIGHTMAPASSHADOWMAP=!1,i.REFLECTIONMAP_3D=!1,i.REFLECTIONMAP_SPHERICAL=!1,i.REFLECTIONMAP_PLANAR=!1,i.REFLECTIONMAP_CUBIC=!1,i.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,i.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,i.REFLECTIONMAP_PROJECTION=!1,i.REFLECTIONMAP_SKYBOX=!1,i.REFLECTIONMAP_EXPLICIT=!1,i.REFLECTIONMAP_EQUIRECTANGULAR=!1,i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,i.REFLECTIONMAP_OPPOSITEZ=!1,i.INVERTCUBICMAP=!1,i.LOGARITHMICDEPTH=!1,i.REFRACTION=!1,i.REFRACTIONMAP_3D=!1,i.REFLECTIONOVERALPHA=!1,i.TWOSIDEDLIGHTING=!1,i.SHADOWFLOAT=!1,i.MORPHTARGETS=!1,i.MORPHTARGETS_NORMAL=!1,i.MORPHTARGETS_TANGENT=!1,i.MORPHTARGETS_UV=!1,i.NUM_MORPH_INFLUENCERS=0,i.MORPHTARGETS_TEXTURE=!1,i.NONUNIFORMSCALING=!1,i.PREMULTIPLYALPHA=!1,i.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,i.ALPHABLEND=!0,i.PREPASS=!1,i.PREPASS_IRRADIANCE=!1,i.PREPASS_IRRADIANCE_INDEX=-1,i.PREPASS_ALBEDO_SQRT=!1,i.PREPASS_ALBEDO_SQRT_INDEX=-1,i.PREPASS_DEPTH=!1,i.PREPASS_DEPTH_INDEX=-1,i.PREPASS_NORMAL=!1,i.PREPASS_NORMAL_INDEX=-1,i.PREPASS_NORMAL_WORLDSPACE=!1,i.PREPASS_POSITION=!1,i.PREPASS_POSITION_INDEX=-1,i.PREPASS_VELOCITY=!1,i.PREPASS_VELOCITY_INDEX=-1,i.PREPASS_REFLECTIVITY=!1,i.PREPASS_REFLECTIVITY_INDEX=-1,i.SCENE_MRT_COUNT=0,i.RGBDLIGHTMAP=!1,i.RGBDREFLECTION=!1,i.RGBDREFRACTION=!1,i.IMAGEPROCESSING=!1,i.VIGNETTE=!1,i.VIGNETTEBLENDMODEMULTIPLY=!1,i.VIGNETTEBLENDMODEOPAQUE=!1,i.TONEMAPPING=0,i.CONTRAST=!1,i.COLORCURVES=!1,i.COLORGRADING=!1,i.COLORGRADING3D=!1,i.SAMPLER3DGREENDEPTH=!1,i.SAMPLER3DBGRMAP=!1,i.DITHER=!1,i.IMAGEPROCESSINGPOSTPROCESS=!1,i.SKIPFINALCOLORCLAMP=!1,i.MULTIVIEW=!1,i.ORDER_INDEPENDENT_TRANSPARENCY=!1,i.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,i.CAMERA_ORTHOGRAPHIC=!1,i.CAMERA_PERSPECTIVE=!1,i.IS_REFLECTION_LINEAR=!1,i.IS_REFRACTION_LINEAR=!1,i.EXPOSURE=!1,i.DECAL_AFTER_DETAIL=!1,i.rebuild(),i}return m(t,e),t.prototype.setReflectionMode=function(e){for(var t=0,i=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"];t<i.length;t++){var r=i[t];this[r]=r===e}},t}(Gs),Uu=function(e){function t(i,r){var n=e.call(this,i,r)||this;return n._diffuseTexture=null,n._ambientTexture=null,n._opacityTexture=null,n._reflectionTexture=null,n._emissiveTexture=null,n._specularTexture=null,n._bumpTexture=null,n._lightmapTexture=null,n._refractionTexture=null,n.ambientColor=new Z(0,0,0),n.diffuseColor=new Z(1,1,1),n.specularColor=new Z(1,1,1),n.emissiveColor=new Z(0,0,0),n.specularPower=64,n._useAlphaFromDiffuseTexture=!1,n._useEmissiveAsIllumination=!1,n._linkEmissiveWithDiffuse=!1,n._useSpecularOverAlpha=!1,n._useReflectionOverAlpha=!1,n._disableLighting=!1,n._useObjectSpaceNormalMap=!1,n._useParallax=!1,n._useParallaxOcclusion=!1,n.parallaxScaleBias=.05,n._roughness=0,n.indexOfRefraction=.98,n.invertRefractionY=!0,n.alphaCutOff=.4,n._useLightmapAsShadowmap=!1,n._useReflectionFresnelFromSpecular=!1,n._useGlossinessFromSpecularMapAlpha=!1,n._maxSimultaneousLights=4,n._invertNormalMapX=!1,n._invertNormalMapY=!1,n._twoSidedLighting=!1,n._applyDecalMapAfterDetailMap=!1,n._renderTargets=new ar(16),n._worldViewProjectionMatrix=z.Zero(),n._globalAmbientColor=new Z(0,0,0),n._cacheHasRenderTargetTextures=!1,n.detailMap=new Lu(n),n._attachImageProcessingConfiguration(null),n.prePassConfiguration=new Su,n.getRenderTargetTextures=function(){return n._renderTargets.reset(),t.ReflectionTextureEnabled&&n._reflectionTexture&&n._reflectionTexture.isRenderTarget&&n._renderTargets.push(n._reflectionTexture),t.RefractionTextureEnabled&&n._refractionTexture&&n._refractionTexture.isRenderTarget&&n._renderTargets.push(n._refractionTexture),n._eventInfo.renderTargets=n._renderTargets,n._callbackPluginEventFillRenderTargetTextures(n._eventInfo),n._renderTargets},n}return m(t,e),Object.defineProperty(t.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!1,configurable:!0}),t.prototype._attachImageProcessingConfiguration=function(e){var t=this;e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((function(){t._markAllSubMeshesAsImageProcessingDirty()}))))},Object.defineProperty(t.prototype,"isPrePassCapable",{get:function(){return!this.disableDepthWrite},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this._imageProcessingConfiguration.colorGradingTexture=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorCurves",{get:function(){return this._imageProcessingConfiguration.colorCurves},set:function(e){this._imageProcessingConfiguration.colorCurves=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"canRenderToMRT",{get:function(){return!0},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hasRenderTargetTextures",{get:function(){return!!(t.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||!!(t.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"StandardMaterial"},t.prototype.needAlphaBlending=function(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled)},t.prototype.needAlphaTesting=function(){return!!this._forceAlphaTest||this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===Ca.MATERIAL_ALPHATEST)},t.prototype._shouldUseAlphaFromDiffuseTexture=function(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==Ca.MATERIAL_OPAQUE},t.prototype._hasAlphaChannel=function(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||null!=this._opacityTexture},t.prototype.getAlphaTestTexture=function(){return this._diffuseTexture},t.prototype.isReadyForSubMesh=function(e,i,r){void 0===r&&(r=!1),this._uniformBufferLayoutBuilt||this.buildUniformLayout();var n=i._drawWrapper;if(n.effect&&this.isFrozen&&n._wasPreviouslyReady&&n._wasPreviouslyUsingInstances===r)return!0;i.materialDefines||(this._callbackPluginEventGeneric(Vo.GetDefineNames,this._eventInfo),i.materialDefines=new Bu(this._eventInfo.defineNames));var o=this.getScene(),a=i.materialDefines;if(this._isReadyForSubMesh(i))return!0;var s=o.getEngine();a._needNormals=pa(o,e,a,!0,this._maxSimultaneousLights,this._disableLighting),ba(o,a);var l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Ea(o,a,this.canRenderToMRT&&!l),Ta(o,a,l),a._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,a._needUVs=!1;for(var c=1;c<=u.MAX_SUPPORTED_UV_SETS;++c)a["MAINUV"+c]=!1;if(o.texturesEnabled){if(a.DIFFUSEDIRECTUV=0,a.BUMPDIRECTUV=0,a.AMBIENTDIRECTUV=0,a.OPACITYDIRECTUV=0,a.EMISSIVEDIRECTUV=0,a.SPECULARDIRECTUV=0,a.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&t.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;ta(this._diffuseTexture,a,"DIFFUSE")}else a.DIFFUSE=!1;if(this._ambientTexture&&t.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;ta(this._ambientTexture,a,"AMBIENT")}else a.AMBIENT=!1;if(this._opacityTexture&&t.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;ta(this._opacityTexture,a,"OPACITY"),a.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else a.OPACITY=!1;if(this._reflectionTexture&&t.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(a._needNormals=!0,a.REFLECTION=!0,a.ROUGHNESS=this._roughness>0,a.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,a.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===Ja.INVCUBIC_MODE,a.REFLECTIONMAP_3D=this._reflectionTexture.isCube,a.REFLECTIONMAP_OPPOSITEZ=a.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,a.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case Ja.EXPLICIT_MODE:a.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case Ja.PLANAR_MODE:a.setReflectionMode("REFLECTIONMAP_PLANAR");break;case Ja.PROJECTION_MODE:a.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case Ja.SKYBOX_MODE:a.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case Ja.SPHERICAL_MODE:a.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case Ja.EQUIRECTANGULAR_MODE:a.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case Ja.FIXED_EQUIRECTANGULAR_MODE:a.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case Ja.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:a.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case Ja.CUBIC_MODE:case Ja.INVCUBIC_MODE:default:a.setReflectionMode("REFLECTIONMAP_CUBIC")}a.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else a.REFLECTION=!1,a.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&t.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;ta(this._emissiveTexture,a,"EMISSIVE")}else a.EMISSIVE=!1;if(this._lightmapTexture&&t.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;ta(this._lightmapTexture,a,"LIGHTMAP"),a.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,a.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else a.LIGHTMAP=!1;if(this._specularTexture&&t.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;ta(this._specularTexture,a,"SPECULAR"),a.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else a.SPECULAR=!1;if(o.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&t.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;ta(this._bumpTexture,a,"BUMP"),a.PARALLAX=this._useParallax,a.PARALLAX_RHS=o.useRightHandedSystem,a.PARALLAXOCCLUSION=this._useParallaxOcclusion,a.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else a.BUMP=!1,a.PARALLAX=!1,a.PARALLAX_RHS=!1,a.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&t.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;a._needUVs=!0,a.REFRACTION=!0,a.REFRACTIONMAP_3D=this._refractionTexture.isCube,a.RGBDREFRACTION=this._refractionTexture.isRGBD,a.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize}else a.REFRACTION=!1;a.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else a.DIFFUSE=!1,a.AMBIENT=!1,a.OPACITY=!1,a.REFLECTION=!1,a.EMISSIVE=!1,a.LIGHTMAP=!1,a.BUMP=!1,a.REFRACTION=!1;a.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),a.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,a.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,a.SPECULAROVERALPHA=this._useSpecularOverAlpha,a.PREMULTIPLYALPHA=this.alphaMode===u.ALPHA_PREMULTIPLIED||this.alphaMode===u.ALPHA_PREMULTIPLIED_PORTERDUFF,a.ALPHATEST_AFTERALLALPHACOMPUTATIONS=null!==this.transparencyMode,a.ALPHABLEND=null===this.transparencyMode||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=a,this._eventInfo.subMesh=i,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(a._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(a),a.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,a.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}a._areFresnelDirty&&(t.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(a.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,a.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,a.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,a.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,a.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,a.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,a._needNormals=!0,a.FRESNEL=!0):a.FRESNEL=!1),da(e,o,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,a,this._applyDecalMapAfterDetailMap),_a(o,s,this,a,r,null,i.getRenderingMesh().hasThinInstances),this._eventInfo.defines=a,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),ya(e,a,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);var h=!1;if(a.isDirty){var d=a._areLightsDisposed;a.markAsProcessed();var p=new ll;a.REFLECTION&&p.addFallback(0,"REFLECTION"),a.SPECULAR&&p.addFallback(0,"SPECULAR"),a.BUMP&&p.addFallback(0,"BUMP"),a.PARALLAX&&p.addFallback(1,"PARALLAX"),a.PARALLAX_RHS&&p.addFallback(1,"PARALLAX_RHS"),a.PARALLAXOCCLUSION&&p.addFallback(0,"PARALLAXOCCLUSION"),a.SPECULAROVERALPHA&&p.addFallback(0,"SPECULAROVERALPHA"),a.FOG&&p.addFallback(1,"FOG"),a.POINTSIZE&&p.addFallback(0,"POINTSIZE"),a.LOGARITHMICDEPTH&&p.addFallback(0,"LOGARITHMICDEPTH"),ua(a,p,this._maxSimultaneousLights),a.SPECULARTERM&&p.addFallback(0,"SPECULARTERM"),a.DIFFUSEFRESNEL&&p.addFallback(1,"DIFFUSEFRESNEL"),a.OPACITYFRESNEL&&p.addFallback(2,"OPACITYFRESNEL"),a.REFLECTIONFRESNEL&&p.addFallback(3,"REFLECTIONFRESNEL"),a.EMISSIVEFRESNEL&&p.addFallback(4,"EMISSIVEFRESNEL"),a.FRESNEL&&p.addFallback(4,"FRESNEL"),a.MULTIVIEW&&p.addFallback(0,"MULTIVIEW");var f=[Nr.PositionKind];for(a.NORMAL&&f.push(Nr.NormalKind),a.TANGENT&&f.push(Nr.TangentKind),c=1;c<=u.MAX_SUPPORTED_UV_SETS;++c)a["UV"+c]&&f.push("uv".concat(1===c?"":c));a.VERTEXCOLOR&&f.push(Nr.ColorKind),la(f,e,a,p),ca(f,a),Zo(f,e,a),ra(f,0,a);var _="default",m=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","vRefractionPosition","vRefractionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth","morphTargetTextureInfo","morphTargetTextureIndices"],g=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],v=["Material","Scene","Mesh"],y={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:a.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=p,this._eventInfo.fallbackRank=0,this._eventInfo.defines=a,this._eventInfo.uniforms=m,this._eventInfo.attributes=f,this._eventInfo.samplers=g,this._eventInfo.uniformBuffersNames=v,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=y,this._callbackPluginEventGeneric(Vo.PrepareEffect,this._eventInfo),Su.AddUniforms(m),Su.AddSamplers(g),pr&&(pr.PrepareUniforms(m,a),pr.PrepareSamplers(g,a)),Aa({uniformsNames:m,uniformBuffersNames:v,samplers:g,defines:a,maxSimultaneousLights:this._maxSimultaneousLights}),Go(m);var b={};this.customShaderNameResolve&&(_=this.customShaderNameResolve(_,m,v,g,a,f,b));var T=a.toString(),E=i.effect,S=o.getEngine().createEffect(_,{attributes:f,uniformsNames:m,uniformBuffersNames:v,samplers:g,defines:T,fallbacks:p,onCompiled:this.onCompiled,onError:this.onError,indexParameters:y,processFinalCode:b.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:a.PREPASS},s);if(this._eventInfo.customCode=void 0,S)if(this._onEffectCreatedObservable&&(wu.effect=S,wu.subMesh=i,this._onEffectCreatedObservable.notifyObservers(wu)),this.allowShaderHotSwapping&&E&&!S.isReady()){if(S=E,a.markAsUnprocessed(),h=this.isFrozen,d)return a._areLightsDisposed=!0,!1}else o.resetCachedMaterial(),i.setEffect(S,a,this._materialContext)}return!(!i.effect||!i.effect.isReady()||(a._renderId=o.getRenderId(),n._wasPreviouslyReady=!h,n._wasPreviouslyUsingInstances=r,this._checkScenePerformancePriority(),0))},t.prototype.buildUniformLayout=function(){var t=this._uniformBuffer;t.addUniform("diffuseLeftColor",4),t.addUniform("diffuseRightColor",4),t.addUniform("opacityParts",4),t.addUniform("reflectionLeftColor",4),t.addUniform("reflectionRightColor",4),t.addUniform("refractionLeftColor",4),t.addUniform("refractionRightColor",4),t.addUniform("emissiveLeftColor",4),t.addUniform("emissiveRightColor",4),t.addUniform("vDiffuseInfos",2),t.addUniform("vAmbientInfos",2),t.addUniform("vOpacityInfos",2),t.addUniform("vReflectionInfos",2),t.addUniform("vReflectionPosition",3),t.addUniform("vReflectionSize",3),t.addUniform("vEmissiveInfos",2),t.addUniform("vLightmapInfos",2),t.addUniform("vSpecularInfos",2),t.addUniform("vBumpInfos",3),t.addUniform("diffuseMatrix",16),t.addUniform("ambientMatrix",16),t.addUniform("opacityMatrix",16),t.addUniform("reflectionMatrix",16),t.addUniform("emissiveMatrix",16),t.addUniform("lightmapMatrix",16),t.addUniform("specularMatrix",16),t.addUniform("bumpMatrix",16),t.addUniform("vTangentSpaceParams",2),t.addUniform("pointSize",1),t.addUniform("alphaCutOff",1),t.addUniform("refractionMatrix",16),t.addUniform("vRefractionInfos",4),t.addUniform("vRefractionPosition",3),t.addUniform("vRefractionSize",3),t.addUniform("vSpecularColor",4),t.addUniform("vEmissiveColor",3),t.addUniform("vDiffuseColor",4),t.addUniform("vAmbientColor",3),e.prototype.buildUniformLayout.call(this)},t.prototype.bindForSubMesh=function(e,i,r){var n,o=this.getScene(),a=r.materialDefines;if(a){var s=r.effect;if(s){this._activeEffect=s,i.getMeshUniformBuffer().bindToEffect(s,"Mesh"),i.transferToEffect(e),this._uniformBuffer.bindToEffect(s,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,o,i,e,this.isFrozen),this._eventInfo.subMesh=r,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),a.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));var l=this._mustRebind(o,s,r,i.visibility);na(i,s);var c=this._uniformBuffer;if(l){if(this.bindViewProjection(s),!c.useUbo||!this.isFrozen||!c.isSync||r._drawWrapper._forceRebindOnNextCall){if(t.FresnelEnabled&&a.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(c.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),c.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&c.updateColor4("opacityParts",new Z(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(c.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),c.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(c.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),c.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(c.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),c.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),o.texturesEnabled){if(this._diffuseTexture&&t.DiffuseTextureEnabled&&(c.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),ia(this._diffuseTexture,c,"diffuse")),this._ambientTexture&&t.AmbientTextureEnabled&&(c.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),ia(this._ambientTexture,c,"ambient")),this._opacityTexture&&t.OpacityTextureEnabled&&(c.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),ia(this._opacityTexture,c,"opacity")),this._hasAlphaChannel()&&c.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&t.ReflectionTextureEnabled&&(c.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),c.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){var u=this._reflectionTexture;c.updateVector3("vReflectionPosition",u.boundingBoxPosition),c.updateVector3("vReflectionSize",u.boundingBoxSize)}if(this._emissiveTexture&&t.EmissiveTextureEnabled&&(c.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),ia(this._emissiveTexture,c,"emissive")),this._lightmapTexture&&t.LightmapTextureEnabled&&(c.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),ia(this._lightmapTexture,c,"lightmap")),this._specularTexture&&t.SpecularTextureEnabled&&(c.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),ia(this._specularTexture,c,"specular")),this._bumpTexture&&o.getEngine().getCaps().standardDerivatives&&t.BumpTextureEnabled&&(c.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),ia(this._bumpTexture,c,"bump"),o._mirroredCameraPosition?c.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):c.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&t.RefractionTextureEnabled){var h=1;this._refractionTexture.isCube||(c.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(h=this._refractionTexture.depth)),c.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,h,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize&&(u=this._refractionTexture,c.updateVector3("vRefractionPosition",u.boundingBoxPosition),c.updateVector3("vRefractionSize",u.boundingBoxSize))}}this.pointsCloud&&c.updateFloat("pointSize",this.pointSize),a.SPECULARTERM&&c.updateColor4("vSpecularColor",this.specularColor,this.specularPower),c.updateColor3("vEmissiveColor",t.EmissiveTextureEnabled?this.emissiveColor:Z.BlackReadOnly),c.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),o.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),c.updateColor3("vAmbientColor",this._globalAmbientColor)}o.texturesEnabled&&(this._diffuseTexture&&t.DiffuseTextureEnabled&&s.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&t.AmbientTextureEnabled&&s.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&t.OpacityTextureEnabled&&s.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&t.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?s.setTexture("reflectionCubeSampler",this._reflectionTexture):s.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&t.EmissiveTextureEnabled&&s.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&t.LightmapTextureEnabled&&s.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&t.SpecularTextureEnabled&&s.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&o.getEngine().getCaps().standardDerivatives&&t.BumpTextureEnabled&&s.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&t.RefractionTextureEnabled&&(this._refractionTexture.isCube?s.setTexture("refractionCubeSampler",this._refractionTexture):s.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(i)&&this.getScene().depthPeelingRenderer.bind(s),this._eventInfo.subMesh=r,this._callbackPluginEventBindForSubMesh(this._eventInfo),Ho(s,this,o),this.bindEyePosition(s)}else o.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!l&&this.isFrozen||(o.lightsEnabled&&!this._disableLighting&&sa(o,i,s,a,this._maxSimultaneousLights),(o.fogEnabled&&i.applyFog&&o.fogMode!==pn.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||i.receiveShadows||a.PREPASS)&&this.bindView(s),Qo(o,i,s),a.NUM_MORPH_INFLUENCERS&&$o(i,s),a.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(n=i.bakedVertexAnimationManager)||void 0===n||n.bind(s,a.INSTANCES)),this.useLogarithmicDepth&&Ko(a,s,o),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(i,this._activeEffect,r),c.update()}}},t.prototype.getAnimatables=function(){var t=e.prototype.getAnimatables.call(this);return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&t.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&t.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&t.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&t.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&t.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&t.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&t.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&t.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&t.push(this._refractionTexture),t},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);return this._diffuseTexture&&t.push(this._diffuseTexture),this._ambientTexture&&t.push(this._ambientTexture),this._opacityTexture&&t.push(this._opacityTexture),this._reflectionTexture&&t.push(this._reflectionTexture),this._emissiveTexture&&t.push(this._emissiveTexture),this._specularTexture&&t.push(this._specularTexture),this._bumpTexture&&t.push(this._bumpTexture),this._lightmapTexture&&t.push(this._lightmapTexture),this._refractionTexture&&t.push(this._refractionTexture),t},t.prototype.hasTexture=function(t){return!!e.prototype.hasTexture.call(this,t)||this._diffuseTexture===t||this._ambientTexture===t||this._opacityTexture===t||this._reflectionTexture===t||this._emissiveTexture===t||this._specularTexture===t||this._bumpTexture===t||this._lightmapTexture===t||this._refractionTexture===t},t.prototype.dispose=function(t,i){var r,n,o,a,s,l,c,u,h;i&&(null===(r=this._diffuseTexture)||void 0===r||r.dispose(),null===(n=this._ambientTexture)||void 0===n||n.dispose(),null===(o=this._opacityTexture)||void 0===o||o.dispose(),null===(a=this._reflectionTexture)||void 0===a||a.dispose(),null===(s=this._emissiveTexture)||void 0===s||s.dispose(),null===(l=this._specularTexture)||void 0===l||l.dispose(),null===(c=this._bumpTexture)||void 0===c||c.dispose(),null===(u=this._lightmapTexture)||void 0===u||u.dispose(),null===(h=this._refractionTexture)||void 0===h||h.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e.prototype.dispose.call(this,t,i)},t.prototype.clone=function(e,i,r){var n=this;void 0===i&&(i=!0),void 0===r&&(r="");var o=Ke.Clone((function(){return new t(e,n.getScene())}),this,{cloneTexturesOnlyOnce:i});return o.name=e,o.id=e,this.stencil.copyTo(o.stencil),this._clonePlugins(o,r),o},t.Parse=function(e,i,r){var n=Ke.Parse((function(){return new t(e.name,i)}),e,i,r);return e.stencil&&n.stencil.parse(e.stencil,i,r),Ca._ParsePlugins(e,n,i,r),n},Object.defineProperty(t,"DiffuseTextureEnabled",{get:function(){return xu.DiffuseTextureEnabled},set:function(e){xu.DiffuseTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t,"DetailTextureEnabled",{get:function(){return xu.DetailTextureEnabled},set:function(e){xu.DetailTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t,"AmbientTextureEnabled",{get:function(){return xu.AmbientTextureEnabled},set:function(e){xu.AmbientTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t,"OpacityTextureEnabled",{get:function(){return xu.OpacityTextureEnabled},set:function(e){xu.OpacityTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t,"ReflectionTextureEnabled",{get:function(){return xu.ReflectionTextureEnabled},set:function(e){xu.ReflectionTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t,"EmissiveTextureEnabled",{get:function(){return xu.EmissiveTextureEnabled},set:function(e){xu.EmissiveTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t,"SpecularTextureEnabled",{get:function(){return xu.SpecularTextureEnabled},set:function(e){xu.SpecularTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t,"BumpTextureEnabled",{get:function(){return xu.BumpTextureEnabled},set:function(e){xu.BumpTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t,"LightmapTextureEnabled",{get:function(){return xu.LightmapTextureEnabled},set:function(e){xu.LightmapTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t,"RefractionTextureEnabled",{get:function(){return xu.RefractionTextureEnabled},set:function(e){xu.RefractionTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t,"ColorGradingTextureEnabled",{get:function(){return xu.ColorGradingTextureEnabled},set:function(e){xu.ColorGradingTextureEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t,"FresnelEnabled",{get:function(){return xu.FresnelEnabled},set:function(e){xu.FresnelEnabled=e},enumerable:!1,configurable:!0}),v([Me("diffuseTexture")],t.prototype,"_diffuseTexture",void 0),v([Pe("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"diffuseTexture",void 0),v([Me("ambientTexture")],t.prototype,"_ambientTexture",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"ambientTexture",void 0),v([Me("opacityTexture")],t.prototype,"_opacityTexture",void 0),v([Pe("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"opacityTexture",void 0),v([Me("reflectionTexture")],t.prototype,"_reflectionTexture",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionTexture",void 0),v([Me("emissiveTexture")],t.prototype,"_emissiveTexture",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"emissiveTexture",void 0),v([Me("specularTexture")],t.prototype,"_specularTexture",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"specularTexture",void 0),v([Me("bumpTexture")],t.prototype,"_bumpTexture",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"bumpTexture",void 0),v([Me("lightmapTexture")],t.prototype,"_lightmapTexture",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"lightmapTexture",void 0),v([Me("refractionTexture")],t.prototype,"_refractionTexture",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"refractionTexture",void 0),v([Oe("ambient")],t.prototype,"ambientColor",void 0),v([Oe("diffuse")],t.prototype,"diffuseColor",void 0),v([Oe("specular")],t.prototype,"specularColor",void 0),v([Oe("emissive")],t.prototype,"emissiveColor",void 0),v([Ie()],t.prototype,"specularPower",void 0),v([Ie("useAlphaFromDiffuseTexture")],t.prototype,"_useAlphaFromDiffuseTexture",void 0),v([Pe("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"useAlphaFromDiffuseTexture",void 0),v([Ie("useEmissiveAsIllumination")],t.prototype,"_useEmissiveAsIllumination",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useEmissiveAsIllumination",void 0),v([Ie("linkEmissiveWithDiffuse")],t.prototype,"_linkEmissiveWithDiffuse",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"linkEmissiveWithDiffuse",void 0),v([Ie("useSpecularOverAlpha")],t.prototype,"_useSpecularOverAlpha",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useSpecularOverAlpha",void 0),v([Ie("useReflectionOverAlpha")],t.prototype,"_useReflectionOverAlpha",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useReflectionOverAlpha",void 0),v([Ie("disableLighting")],t.prototype,"_disableLighting",void 0),v([Pe("_markAllSubMeshesAsLightsDirty")],t.prototype,"disableLighting",void 0),v([Ie("useObjectSpaceNormalMap")],t.prototype,"_useObjectSpaceNormalMap",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useObjectSpaceNormalMap",void 0),v([Ie("useParallax")],t.prototype,"_useParallax",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useParallax",void 0),v([Ie("useParallaxOcclusion")],t.prototype,"_useParallaxOcclusion",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useParallaxOcclusion",void 0),v([Ie()],t.prototype,"parallaxScaleBias",void 0),v([Ie("roughness")],t.prototype,"_roughness",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"roughness",void 0),v([Ie()],t.prototype,"indexOfRefraction",void 0),v([Ie()],t.prototype,"invertRefractionY",void 0),v([Ie()],t.prototype,"alphaCutOff",void 0),v([Ie("useLightmapAsShadowmap")],t.prototype,"_useLightmapAsShadowmap",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useLightmapAsShadowmap",void 0),v([De("diffuseFresnelParameters")],t.prototype,"_diffuseFresnelParameters",void 0),v([Pe("_markAllSubMeshesAsFresnelDirty")],t.prototype,"diffuseFresnelParameters",void 0),v([De("opacityFresnelParameters")],t.prototype,"_opacityFresnelParameters",void 0),v([Pe("_markAllSubMeshesAsFresnelAndMiscDirty")],t.prototype,"opacityFresnelParameters",void 0),v([De("reflectionFresnelParameters")],t.prototype,"_reflectionFresnelParameters",void 0),v([Pe("_markAllSubMeshesAsFresnelDirty")],t.prototype,"reflectionFresnelParameters",void 0),v([De("refractionFresnelParameters")],t.prototype,"_refractionFresnelParameters",void 0),v([Pe("_markAllSubMeshesAsFresnelDirty")],t.prototype,"refractionFresnelParameters",void 0),v([De("emissiveFresnelParameters")],t.prototype,"_emissiveFresnelParameters",void 0),v([Pe("_markAllSubMeshesAsFresnelDirty")],t.prototype,"emissiveFresnelParameters",void 0),v([Ie("useReflectionFresnelFromSpecular")],t.prototype,"_useReflectionFresnelFromSpecular",void 0),v([Pe("_markAllSubMeshesAsFresnelDirty")],t.prototype,"useReflectionFresnelFromSpecular",void 0),v([Ie("useGlossinessFromSpecularMapAlpha")],t.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useGlossinessFromSpecularMapAlpha",void 0),v([Ie("maxSimultaneousLights")],t.prototype,"_maxSimultaneousLights",void 0),v([Pe("_markAllSubMeshesAsLightsDirty")],t.prototype,"maxSimultaneousLights",void 0),v([Ie("invertNormalMapX")],t.prototype,"_invertNormalMapX",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"invertNormalMapX",void 0),v([Ie("invertNormalMapY")],t.prototype,"_invertNormalMapY",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"invertNormalMapY",void 0),v([Ie("twoSidedLighting")],t.prototype,"_twoSidedLighting",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"twoSidedLighting",void 0),v([Ie("applyDecalMapAfterDetailMap")],t.prototype,"_applyDecalMapAfterDetailMap",void 0),v([Pe("_markAllSubMeshesAsMiscDirty")],t.prototype,"applyDecalMapAfterDetailMap",void 0),t}(ws);a("BABYLON.StandardMaterial",Uu),pn.DefaultMaterialFactory=function(e){return new Uu("default material",e)},Er.prototype.createDynamicTexture=function(e,t,i,r){var n=new Pi(this,Ti.Dynamic);return n.baseWidth=e,n.baseHeight=t,i&&(e=this.needPOTTextures?ir(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?ir(t,this._caps.maxTextureSize):t),n.width=e,n.height=t,n.isReady=!1,n.generateMipMaps=i,n.samplingMode=r,this.updateTextureSamplingMode(r,n),this._internalTexturesCache.push(n),n},Er.prototype.updateDynamicTexture=function(e,t,i,r,n,o,a){if(void 0===r&&(r=!1),void 0===o&&(o=!1),void 0===a&&(a=!1),e){var s=this._gl,l=s.TEXTURE_2D,c=this._bindTextureDirectly(l,e,!0,o);this._unpackFlipY(void 0===i?e.invertY:i),r&&s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);var u=this._getWebGLTextureType(e.type),h=this._getInternalFormat(n||e.format),d=this._getRGBABufferInternalSizedFormat(e.type,h);s.texImage2D(l,0,d,h,u,t),e.generateMipMaps&&s.generateMipmap(l),c||this._bindTextureDirectly(l,null),r&&s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),n&&(e.format=n),e._dynamicTextureSource=t,e._premulAlpha=r,e.invertY=i||!1,e.isReady=!0}};var Vu,ku,Gu=function(e){function t(t,i,r,n,o,a,s){void 0===r&&(r=null),void 0===n&&(n=!1),void 0===o&&(o=u.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===a&&(a=u.TEXTUREFORMAT_RGBA);var l=e.call(this,null,r,!n,s,o,void 0,void 0,void 0,void 0,a)||this;l.name=t,l.wrapU=Ja.CLAMP_ADDRESSMODE,l.wrapV=Ja.CLAMP_ADDRESSMODE,l._generateMipMaps=n;var c=l._getEngine();if(!c)return l;i.getContext?(l._canvas=i,l._ownCanvas=!1,l._texture=c.createDynamicTexture(i.width,i.height,n,o)):(l._canvas=c.createCanvas(1,1),l._ownCanvas=!0,i.width||0===i.width?l._texture=c.createDynamicTexture(i.width,i.height,n,o):l._texture=c.createDynamicTexture(i,i,n,o));var h=l.getSize();return l._canvas.width!==h.width&&(l._canvas.width=h.width),l._canvas.height!==h.height&&(l._canvas.height=h.height),l._context=l._canvas.getContext("2d"),l}return m(t,e),t.prototype.getClassName=function(){return"DynamicTexture"},Object.defineProperty(t.prototype,"canRescale",{get:function(){return!0},enumerable:!1,configurable:!0}),t.prototype._recreate=function(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)},t.prototype.scale=function(e){var t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)},t.prototype.scaleTo=function(e,t){var i=this.getSize();i.width=e,i.height=t,this._recreate(i)},t.prototype.getContext=function(){return this._context},t.prototype.clear=function(e){var t=this.getSize();e&&(this._context.fillStyle=e),this._context.clearRect(0,0,t.width,t.height)},t.prototype.update=function(e,t,i){void 0===t&&(t=!1),void 0===i&&(i=!1),this._getEngine().updateDynamicTexture(this._texture,this._canvas,void 0===e||e,t,this._format||void 0,void 0,i)},t.prototype.drawText=function(e,t,i,r,n,o,a,s){void 0===s&&(s=!0);var l=this.getSize();if(o&&(this._context.fillStyle=o,this._context.fillRect(0,0,l.width,l.height)),this._context.font=r,null==t){var c=this._context.measureText(e);t=(l.width-c.width)/2}if(null==i){var u=parseInt(r.replace(/\D/g,""));i=l.height/2+u/3.65}this._context.fillStyle=n||"",this._context.fillText(e,t,i),s&&this.update(a)},t.prototype.dispose=function(){var t,i;e.prototype.dispose.call(this),this._ownCanvas&&(null===(i=null===(t=this._canvas)||void 0===t?void 0:t.remove)||void 0===i||i.call(t)),this._canvas=null,this._context=null},t.prototype.clone=function(){var e=this.getScene();if(!e)return this;var i=this.getSize(),r=new t(this.name,i,e,this._generateMipMaps);return r.hasAlpha=this.hasAlpha,r.level=this.level,r.wrapU=this.wrapU,r.wrapV=this.wrapV,r},t.prototype.serialize=function(){var i=this.getScene();i&&!i.isReady()&&ae.Warn("The scene must be ready before serializing the dynamic texture");var r=e.prototype.serialize.call(this);return t._IsCanvasElement(this._canvas)&&(r.base64String=this._canvas.toDataURL()),r.invertY=this._invertY,r.samplingMode=this.samplingMode,r},t._IsCanvasElement=function(e){return void 0!==e.toDataURL},t.prototype._rebuild=function(){this.update()},t}(Ja),zu=function(){function e(e,t,i,r,n){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this._createRenderTargetTextureProvider=n,this._rttWrapper=null}return Object.defineProperty(e.prototype,"isFixedFoveationSupported",{get:function(){return"XRWebGLLayer"==this.layerType&&"number"==typeof this.layer.fixedFoveation},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"fixedFoveation",{get:function(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null},set:function(e){if(this.isFixedFoveationSupported){var t=Math.max(0,Math.min(1,e||0));this.layer.fixedFoveation=t}},enumerable:!1,configurable:!0}),e.prototype.createRenderTargetTextureProvider=function(e){return this._rttWrapper=this._createRenderTargetTextureProvider(e),this._rttWrapper},e.prototype.dispose=function(){this._rttWrapper&&(this._rttWrapper.dispose(),this._rttWrapper=null)},e}(),Wu=function(){function e(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=new Array,this._engine=e.getEngine()}return e.prototype._createInternalTexture=function(e,t){var i=new Pi(this._engine,Ti.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new br(t,this._engine._gl),i.isReady=!0,i},e.prototype._createRenderTargetTexture=function(e,t,i,r,n,o){if(!this._engine)throw new Error("Engine is disposed");var a={width:e,height:t},s=o?new _u(this._scene,a):new Pl("XR renderTargetTexture",a,this._scene),l=s.renderTarget;if(l._samples=s.samples,!i&&r||(l._framebuffer=i),r)if(o)l._colorTextureArray=r;else{var c=this._createInternalTexture(a,r);l.setTexture(c,0),s._texture=c}return n&&(o?l._depthStencilTextureArray=n:l._depthStencilTexture=this._createInternalTexture(a,n)),s.disableRescaling(),this._renderTargetTextures.push(s),s},e.prototype._destroyRenderTargetTexture=function(e){this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(e),1),e.dispose()},e.prototype.getFramebufferDimensions=function(){return this._framebufferDimensions},e.prototype.dispose=function(){this._renderTargetTextures.forEach((function(e){return e.dispose()})),this._renderTargetTextures.length=0},e}(),Hu=function(e){function t(t){var i=e.call(this,(function(){return t.framebufferWidth}),(function(){return t.framebufferHeight}),t,"XRWebGLLayer",(function(e){return new Xu(e.scene,i)}))||this;return i.layer=t,i}return m(t,e),t}(zu),Xu=function(e){function t(t,i){var r=e.call(this,t,i)||this;return r.layerWrapper=i,r._layer=i.layer,r._framebufferDimensions={framebufferWidth:r._layer.framebufferWidth,framebufferHeight:r._layer.framebufferHeight},r}return m(t,e),t.prototype.trySetViewportForView=function(e,t){var i=this._layer.getViewport(t);if(!i)return!1;var r=this._framebufferDimensions.framebufferWidth,n=this._framebufferDimensions.framebufferHeight;return e.x=i.x/r,e.y=i.y/n,e.width=i.width/r,e.height=i.height/n,!0},t.prototype.getRenderTargetTextureForEye=function(e){var t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,r=this._layer.framebuffer;return this._rtt&&t===this._framebufferDimensions.framebufferWidth&&i===this._framebufferDimensions.framebufferHeight&&r===this._framebuffer||(this._rtt=this._createRenderTargetTexture(t,i,r),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=r),this._rtt},t.prototype.getRenderTargetTextureForView=function(e){return this.getRenderTargetTextureForEye(e.eye)},t}(Wu),ju=function(){function e(){}return e.GetDefaults=function(t){var i=new e;return i.canvasOptions={antialias:!0,depth:!0,stencil:!t||t.isStencilEnable,alpha:!0,framebufferScaleFactor:1},i.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",i},e}(),Yu=function(){function e(e,t){void 0===t&&(t=ju.GetDefaults());var i=this;if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new f,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce((function(){i._engine=null})),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{var r=document.createElement("canvas");r.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(r)}e.onXRSessionInit.add((function(){i._addCanvas()})),e.onXRSessionEnded.add((function(){i._removeCanvas()})),this._makeCanvasCompatibleAsync()}return e.prototype.dispose=function(){this._removeCanvas(),this._setManagedOutputCanvas(null)},e.prototype._makeCanvasCompatibleAsync=function(){var e=this;this._canvasCompatiblePromise=new Promise((function(t){e.canvasContext&&e.canvasContext.makeXRCompatible?e.canvasContext.makeXRCompatible().then((function(){t()})):t()}))},e.prototype.initializeXRLayerAsync=function(e){return y(this,void 0,void 0,(function(){var t,i=this;return b(this,(function(r){return t=function(){return i.xrLayer=new XRWebGLLayer(e,i.canvasContext,i._options.canvasOptions),i._xrLayerWrapper=new Hu(i.xrLayer),i.onXRLayerInitObservable.notifyObservers(i.xrLayer),i.xrLayer},[2,this._canvasCompatiblePromise.then((function(){}),(function(){rr.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.")})).then((function(){return t()}))]}))}))},e.prototype._addCanvas=function(){var e=this;this._canvas&&this._engine&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas),this.xrLayer?this._setCanvasSize(!0):this.onXRLayerInitObservable.addOnce((function(){e._setCanvasSize(!0)}))},e.prototype._removeCanvas=function(){this._canvas&&this._engine&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas),this._setCanvasSize(!1)},e.prototype._setCanvasSize=function(e,t){void 0===e&&(e=!0),void 0===t&&(t=this._xrLayerWrapper),this._canvas&&this._engine&&(e?t&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=t.getWidth()+"px",this._canvas.style.height=t.getHeight()+"px"):this._engine.setSize(t.getWidth(),t.getHeight())):this._originalCanvasSize&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=this._originalCanvasSize.width+"px",this._canvas.style.height=this._originalCanvasSize.height+"px"):this._engine.setSize(this._originalCanvasSize.width,this._originalCanvasSize.height)))},e.prototype._setManagedOutputCanvas=function(e){this._removeCanvas(),e?(this._originalCanvasSize={width:e.offsetWidth,height:e.offsetHeight},this._canvas=e,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)},e}(),Ku=function(e){function t(t){var i=e.call(this,(function(){return t.framebufferWidth}),(function(){return t.framebufferHeight}),t,"XRWebGLLayer",(function(e){return new Qu(e,i)}))||this;return i.layer=t,i}return m(t,e),t}(zu),Qu=function(e){function t(t,i){var r=e.call(this,t.scene,i)||this;return r.layerWrapper=i,r._nativeRTTProvider=navigator.xr.getNativeRenderTargetProvider(t.session,r._createRenderTargetTexture.bind(r),r._destroyRenderTargetTexture.bind(r)),r._nativeLayer=i.layer,r}return m(t,e),t.prototype.trySetViewportForView=function(e){return e.x=0,e.y=0,e.width=1,e.height=1,!0},t.prototype.getRenderTargetTextureForEye=function(e){return this._nativeRTTProvider.getRenderTargetForEye(e)},t.prototype.getRenderTargetTextureForView=function(e){return this._nativeRTTProvider.getRenderTargetForEye(e.eye)},t.prototype.getFramebufferDimensions=function(){return{framebufferWidth:this._nativeLayer.framebufferWidth,framebufferHeight:this._nativeLayer.framebufferHeight}},t}(Wu),qu=function(){function e(e){this._nativeRenderTarget=navigator.xr.getWebXRRenderTarget(e.scene.getEngine())}return e.prototype.initializeXRLayerAsync=function(e){return y(this,void 0,void 0,(function(){return b(this,(function(t){switch(t.label){case 0:return[4,this._nativeRenderTarget.initializeXRLayerAsync(e)];case 1:return t.sent(),this.xrLayer=this._nativeRenderTarget.xrLayer,[2,this.xrLayer]}}))}))},e.prototype.dispose=function(){},e}(),Zu=function(){function e(e){var t=this;this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new f,this.onXRReferenceSpaceChanged=new f,this.onXRSessionEnded=new f,this.onXRSessionInit=new f,this.onXRReferenceSpaceInitialized=new f,this.onXRReady=new f,this.inXRFrameLoop=!1,this.inXRSession=!1,this._worldScalingFactor=1,this.onWorldScaleFactorChangedObservable=new f(void 0,!0),this._engine=e.getEngine(),this._onEngineDisposedObserver=this._engine.onDisposeObservable.addOnce((function(){t._engine=null})),e.onDisposeObservable.addOnce((function(){t.dispose()}))}return Object.defineProperty(e.prototype,"worldScalingFactor",{get:function(){return this._worldScalingFactor},set:function(e){var t=this._worldScalingFactor;this._worldScalingFactor=e,this.onWorldScaleFactorChangedObservable.notifyObservers({previousScaleFactor:t,newScaleFactor:e})},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"referenceSpace",{get:function(){return this._referenceSpace},set:function(e){this._referenceSpace=e,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sessionMode",{get:function(){return this._sessionMode},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){var e;this.inXRSession&&this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),this.onWorldScaleFactorChangedObservable.clear(),null===(e=this._engine)||void 0===e||e.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null},e.prototype.exitXRAsync=function(){return y(this,void 0,void 0,(function(){return b(this,(function(e){switch(e.label){case 0:if(!this.session||!this.inXRSession)return[3,4];this.inXRSession=!1,e.label=1;case 1:return e.trys.push([1,3,,4]),[4,this.session.end()];case 2:return[2,e.sent()];case 3:return e.sent(),ae.Warn("Could not end XR session."),[3,4];case 4:return[2,Promise.resolve()]}}))}))},e.prototype.trySetViewportForView=function(e,t){var i;return(null===(i=this._baseLayerRTTProvider)||void 0===i?void 0:i.trySetViewportForView(e,t))||!1},e.prototype.getRenderTargetTextureForEye=function(e){var t;return(null===(t=this._baseLayerRTTProvider)||void 0===t?void 0:t.getRenderTargetTextureForEye(e))||null},e.prototype.getRenderTargetTextureForView=function(e){var t;return(null===(t=this._baseLayerRTTProvider)||void 0===t?void 0:t.getRenderTargetTextureForView(e))||null},e.prototype.getWebXRRenderTarget=function(e){var t=this.scene.getEngine();return this._xrNavigator.xr.native?new qu(this):((e=e||ju.GetDefaults(t)).canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new Yu(this,e))},e.prototype.initializeAsync=function(){return this._xrNavigator=navigator,this._xrNavigator.xr?Promise.resolve():Promise.reject("WebXR not available")},e.prototype.initializeSessionAsync=function(e,t){var i=this;return void 0===e&&(e="immersive-vr"),void 0===t&&(t={}),this._xrNavigator.xr.requestSession(e,t).then((function(t){return i.session=t,i._sessionMode=e,i.inXRSession=!0,i.onXRSessionInit.notifyObservers(t),i.session.addEventListener("end",(function(){var e;i.inXRSession=!1,i.onXRSessionEnded.notifyObservers(null),i._engine&&(i._engine.framebufferDimensionsObject=null,i._engine.restoreDefaultFramebuffer(),i._engine.customAnimationFrameRequester=null,i._engine._renderLoop()),i.isNative&&(null===(e=i._baseLayerRTTProvider)||void 0===e||e.dispose()),i._baseLayerRTTProvider=null,i._baseLayerWrapper=null}),{once:!0}),i.session}))},e.prototype.isSessionSupportedAsync=function(t){return e.IsSessionSupportedAsync(t)},e.prototype.resetReferenceSpace=function(){this.referenceSpace=this.baseReferenceSpace},e.prototype.runXRRenderLoop=function(){var e,t=this;this.inXRSession&&this._engine&&(this._engine.customAnimationFrameRequester={requestAnimationFrame:function(e){return t.session.requestAnimationFrame(e)},renderFunction:function(e,i){var r;if(t.inXRSession&&t._engine&&(t.currentFrame=i,t.currentTimestamp=e,i)){t.inXRFrameLoop=!0;var n=(null===(r=t._baseLayerRTTProvider)||void 0===r?void 0:r.getFramebufferDimensions())||null;t._engine.framebufferDimensionsObject!==n&&(t._engine.framebufferDimensionsObject=n),t.onXRFrameObservable.notifyObservers(i),t._engine._renderLoop(),t._engine.framebufferDimensionsObject=null,t.inXRFrameLoop=!1}}},this._engine.framebufferDimensionsObject=(null===(e=this._baseLayerRTTProvider)||void 0===e?void 0:e.getFramebufferDimensions())||null,this.onXRFrameObservable.addOnce((function(){t.onXRReady.notifyObservers(t)})),"undefined"!=typeof window&&window.cancelAnimationFrame&&window.cancelAnimationFrame(this._engine._frameHandler),this._engine._renderLoop())},e.prototype.setReferenceSpaceTypeAsync=function(e){var t=this;return void 0===e&&(e="local-floor"),this.session.requestReferenceSpace(e).then((function(e){return e}),(function(e){return ae.Error("XR.requestReferenceSpace failed for the following reason: "),ae.Error(e),ae.Log('Defaulting to universally-supported "viewer" reference space type.'),t.session.requestReferenceSpace("viewer").then((function(e){var i=new XRRigidTransform({x:0,y:-t.defaultHeightCompensation,z:0});return e.getOffsetReferenceSpace(i)}),(function(e){throw ae.Error(e),'XR initialization failed: required "viewer" reference space type not supported.'}))})).then((function(e){return t.session.requestReferenceSpace("viewer").then((function(i){return t.viewerReferenceSpace=i,e}))})).then((function(e){return t.referenceSpace=t.baseReferenceSpace=e,t.onXRReferenceSpaceInitialized.notifyObservers(e),t.referenceSpace}))},e.prototype.updateRenderStateAsync=function(e){return Promise.resolve(this.session.updateRenderState(e))},e.prototype._setBaseLayerWrapper=function(e){var t,i;this.isNative&&(null===(t=this._baseLayerRTTProvider)||void 0===t||t.dispose()),this._baseLayerWrapper=e,this._baseLayerRTTProvider=(null===(i=this._baseLayerWrapper)||void 0===i?void 0:i.createRenderTargetTextureProvider(this))||null},e.prototype._getBaseLayerWrapper=function(){return this._baseLayerWrapper},e.prototype.updateRenderState=function(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new Ku(e.baseLayer):new Hu(e.baseLayer)),this.session.updateRenderState(e)},e.IsSessionSupportedAsync=function(e){if(!navigator.xr)return Promise.resolve(!1);var t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then((function(e){var t=void 0===e||e;return Promise.resolve(t)})).catch((function(e){return ae.Warn(e),Promise.resolve(!1)})):Promise.resolve(!1)},Object.defineProperty(e.prototype,"isNative",{get:function(){var e;return null!==(e=this._xrNavigator.xr.native)&&void 0!==e&&e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentFrameRate",{get:function(){var e;return null===(e=this.session)||void 0===e?void 0:e.frameRate},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"supportedFrameRates",{get:function(){var e;return null===(e=this.session)||void 0===e?void 0:e.supportedFrameRates},enumerable:!1,configurable:!0}),e.prototype.updateTargetFrameRate=function(e){return this.session.updateTargetFrameRate(e)},e.prototype.runInXRFrame=function(e,t){void 0===t&&(t=!0),this.inXRFrameLoop?e():!this.inXRSession&&t||this.onXRFrameObservable.addOnce(e)},Object.defineProperty(e.prototype,"isFixedFoveationSupported",{get:function(){var e;return(null===(e=this._baseLayerWrapper)||void 0===e?void 0:e.isFixedFoveationSupported)||!1},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"fixedFoveation",{get:function(){var e;return(null===(e=this._baseLayerWrapper)||void 0===e?void 0:e.fixedFoveation)||null},set:function(e){var t=Math.max(0,Math.min(1,e||0));this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=t)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"enabledFeatures",{get:function(){var e,t;return null!==(t=null===(e=this.session)||void 0===e?void 0:e.enabledFeatures)&&void 0!==t?t:null},enumerable:!1,configurable:!0}),e}();!function(e){e[e.ENTERING_XR=0]="ENTERING_XR",e[e.EXITING_XR=1]="EXITING_XR",e[e.IN_XR=2]="IN_XR",e[e.NOT_IN_XR=3]="NOT_IN_XR"}(Vu||(Vu={})),function(e){e[e.NOT_TRACKING=0]="NOT_TRACKING",e[e.TRACKING_LOST=1]="TRACKING_LOST",e[e.TRACKING=2]="TRACKING"}(ku||(ku={})),Fa._GroundMeshParser=function(e,t){return Ju.Parse(e,t)};var Ju=function(e){function t(t,i){var r=e.call(this,t,i)||this;return r.generateOctree=!1,r}return m(t,e),t.prototype.getClassName=function(){return"GroundMesh"},Object.defineProperty(t.prototype,"subdivisions",{get:function(){return Math.min(this._subdivisionsX,this._subdivisionsY)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subdivisionsX",{get:function(){return this._subdivisionsX},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subdivisionsY",{get:function(){return this._subdivisionsY},enumerable:!1,configurable:!0}),t.prototype.optimize=function(e,t){void 0===t&&(t=32),this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e),this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)},t.prototype.getHeightAtCoordinates=function(e,t){var i=this.getWorldMatrix(),r=H.Matrix[5];i.invertToRef(r);var n=H.Vector3[8];if(V.TransformCoordinatesFromFloatsToRef(e,0,t,r,n),e=n.x,t=n.z,e<this._minX||e>=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());var o=this._getFacetAt(e,t),a=-(o.x*e+o.z*t+o.w)/o.y;return V.TransformCoordinatesFromFloatsToRef(0,a,0,i,n),n.y},t.prototype.getNormalAtCoordinates=function(e,t){var i=new V(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i},t.prototype.getNormalAtCoordinatesToRef=function(e,t,i){var r=this.getWorldMatrix(),n=H.Matrix[5];r.invertToRef(n);var o=H.Vector3[8];if(V.TransformCoordinatesFromFloatsToRef(e,0,t,n,o),e=o.x,t=o.z,e<this._minX||e>this._maxX||t<this._minZ||t>this._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());var a=this._getFacetAt(e,t);return V.TransformNormalFromFloatsToRef(a.x,a.y,a.z,r,i),this},t.prototype.updateCoordinateHeights=function(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this},t.prototype._getFacetAt=function(e,t){var i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),r=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),n=this._heightQuads[r*this._subdivisionsX+i];return t<n.slope.x*e+n.slope.y?n.facet1:n.facet2},t.prototype._initHeightQuads=function(){var e=this._subdivisionsX,t=this._subdivisionsY;this._heightQuads=new Array;for(var i=0;i<t;i++)for(var r=0;r<e;r++){var n={slope:U.Zero(),facet1:new k(0,0,0,0),facet2:new k(0,0,0,0)};this._heightQuads[i*e+r]=n}return this},t.prototype._computeHeightQuads=function(){var e=this.getVerticesData(Nr.PositionKind);if(!e)return this;for(var t=H.Vector3[3],i=H.Vector3[2],r=H.Vector3[1],n=H.Vector3[0],o=H.Vector3[4],a=H.Vector3[5],s=H.Vector3[6],l=H.Vector3[7],c=H.Vector3[8],u=0,h=0,d=0,p=0,f=0,_=0,m=0,g=this._subdivisionsX,v=this._subdivisionsY,y=0;y<v;y++)for(var b=0;b<g;b++){u=3*b,h=y*(g+1)*3,d=(y+1)*(g+1)*3,t.x=e[h+u],t.y=e[h+u+1],t.z=e[h+u+2],i.x=e[h+u+3],i.y=e[h+u+4],i.z=e[h+u+5],r.x=e[d+u],r.y=e[d+u+1],r.z=e[d+u+2],n.x=e[d+u+3],n.y=e[d+u+4],n.z=e[d+u+5],p=(n.z-t.z)/(n.x-t.x),f=t.z-p*t.x,i.subtractToRef(t,o),r.subtractToRef(t,a),n.subtractToRef(t,s),V.CrossToRef(s,a,l),V.CrossToRef(o,s,c),l.normalize(),c.normalize(),_=-(l.x*t.x+l.y*t.y+l.z*t.z),m=-(c.x*i.x+c.y*i.y+c.z*i.z);var T=this._heightQuads[y*g+b];T.slope.copyFromFloats(p,f),T.facet1.copyFromFloats(l.x,l.y,l.z,_),T.facet2.copyFromFloats(c.x,c.y,c.z,m)}return this},t.prototype.serialize=function(t){e.prototype.serialize.call(this,t),t.subdivisionsX=this._subdivisionsX,t.subdivisionsY=this._subdivisionsY,t.minX=this._minX,t.maxX=this._maxX,t.minZ=this._minZ,t.maxZ=this._maxZ,t.width=this._width,t.height=this._height},t.Parse=function(e,i){var r=new t(e.name,i);return r._subdivisionsX=e.subdivisionsX||1,r._subdivisionsY=e.subdivisionsY||1,r._minX=e.minX,r._maxX=e.maxX,r._minZ=e.minZ,r._maxZ=e.maxZ,r._width=e.width,r._height=e.height,r},t}(Fa);function $u(e){var t,i,r=[],n=[],o=[],a=[],s=e.width||1,l=e.height||1,c=0|(e.subdivisionsX||e.subdivisions||1),u=0|(e.subdivisionsY||e.subdivisions||1);for(t=0;t<=u;t++)for(i=0;i<=c;i++){var h=new V(i*s/c-s/2,0,(u-t)*l/u-l/2),d=new V(0,1,0);n.push(h.x,h.y,h.z),o.push(d.x,d.y,d.z),a.push(i/c,go.UseOpenGLOrientationForUV?t/u:1-t/u)}for(t=0;t<u;t++)for(i=0;i<c;i++)r.push(i+1+(t+1)*(c+1)),r.push(i+1+t*(c+1)),r.push(i+t*(c+1)),r.push(i+(t+1)*(c+1)),r.push(i+1+(t+1)*(c+1)),r.push(i+t*(c+1));var p=new _o;return p.indices=r,p.positions=n,p.normals=o,p.uvs=a,p}function eh(e){var t,i,r,n,o=void 0!==e.xmin&&null!==e.xmin?e.xmin:-1,a=void 0!==e.zmin&&null!==e.zmin?e.zmin:-1,s=void 0!==e.xmax&&null!==e.xmax?e.xmax:1,l=void 0!==e.zmax&&null!==e.zmax?e.zmax:1,c=e.subdivisions||{w:1,h:1},u=e.precision||{w:1,h:1},h=[],d=[],p=[],f=[];c.h=c.h<1?1:c.h,c.w=c.w<1?1:c.w,u.w=u.w<1?1:u.w,u.h=u.h<1?1:u.h;var _=(s-o)/c.w,m=(l-a)/c.h;function g(e,r,n,o){var a=d.length/3,s=u.w+1;for(t=0;t<u.h;t++)for(i=0;i<u.w;i++){var l=[a+i+t*s,a+(i+1)+t*s,a+(i+1)+(t+1)*s,a+i+(t+1)*s];h.push(l[1]),h.push(l[2]),h.push(l[3]),h.push(l[0]),h.push(l[1]),h.push(l[3])}var c=V.Zero(),_=new V(0,1,0);for(t=0;t<=u.h;t++)for(c.z=t*(o-r)/u.h+r,i=0;i<=u.w;i++)c.x=i*(n-e)/u.w+e,c.y=0,d.push(c.x,c.y,c.z),p.push(_.x,_.y,_.z),f.push(i/u.w,t/u.h)}for(r=0;r<c.h;r++)for(n=0;n<c.w;n++)g(o+n*_,a+r*m,o+(n+1)*_,a+(r+1)*m);var v=new _o;return v.indices=h,v.positions=d,v.normals=p,v.uvs=f,v}function th(e){var t,i,r=[],n=[],o=[],a=[],s=e.colorFilter||new Z(.3,.59,.11),l=e.alphaFilter||0,c=!1;if(e.minHeight>e.maxHeight){c=!0;var u=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=u}for(t=0;t<=e.subdivisions;t++)for(i=0;i<=e.subdivisions;i++){var h=new V(i*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-t)*e.height/e.subdivisions-e.height/2),d=4*(((h.x+e.width/2)/e.width*(e.bufferWidth-1)|0)+((1-(h.z+e.height/2)/e.height)*(e.bufferHeight-1)|0)*e.bufferWidth),p=e.buffer[d]/255,f=e.buffer[d+1]/255,_=e.buffer[d+2]/255,m=e.buffer[d+3]/255;c&&(p=1-p,f=1-f,_=1-_);var g=p*s.r+f*s.g+_*s.b;h.y=m>=l?e.minHeight+(e.maxHeight-e.minHeight)*g:e.minHeight-A,e.heightBuffer&&(e.heightBuffer[t*(e.subdivisions+1)+i]=h.y),n.push(h.x,h.y,h.z),o.push(0,0,0),a.push(i/e.subdivisions,1-t/e.subdivisions)}for(t=0;t<e.subdivisions;t++)for(i=0;i<e.subdivisions;i++){var v=i+1+(t+1)*(e.subdivisions+1),y=i+1+t*(e.subdivisions+1),b=i+t*(e.subdivisions+1),T=i+(t+1)*(e.subdivisions+1),E=n[3*v+1]>=e.minHeight,S=n[3*y+1]>=e.minHeight,x=n[3*b+1]>=e.minHeight;E&&S&&x&&(r.push(v),r.push(y),r.push(b)),n[3*T+1]>=e.minHeight&&E&&x&&(r.push(T),r.push(v),r.push(b))}_o.ComputeNormals(n,r,o);var C=new _o;return C.indices=r,C.positions=n,C.normals=o,C.uvs=a,C}function ih(e,t,i){void 0===t&&(t={});var r=new Ju(e,i);return r._setReady(!1),r._subdivisionsX=t.subdivisionsX||t.subdivisions||1,r._subdivisionsY=t.subdivisionsY||t.subdivisions||1,r._width=t.width||1,r._height=t.height||1,r._maxX=r._width/2,r._maxZ=r._height/2,r._minX=-r._maxX,r._minZ=-r._maxZ,$u(t).applyToMesh(r,t.updatable),r._setReady(!0),r}function rh(e,t,i){void 0===i&&(i=null);var r=new Fa(e,i);return eh(t).applyToMesh(r,t.updatable),r}function nh(e,t,i,r){void 0===i&&(i={}),void 0===r&&(r=null);var n=i.width||10,o=i.height||10,a=i.subdivisions||1,s=i.minHeight||0,l=i.maxHeight||1,c=i.colorFilter||new Z(.3,.59,.11),u=i.alphaFilter||0,h=i.updatable,d=i.onReady;r=r||M.LastCreatedScene;var p,f=new Ju(e,r);f._subdivisionsX=a,f._subdivisionsY=a,f._width=n,f._height=o,f._maxX=f._width/2,f._maxZ=f._height/2,f._minX=-f._maxX,f._minZ=-f._maxZ,f._setReady(!1),i.passHeightBufferInCallback&&(p=new Float32Array((a+1)*(a+1)));var _=function(e,t,i){th({width:n,height:o,subdivisions:a,minHeight:s,maxHeight:l,colorFilter:c,buffer:e,bufferWidth:t,bufferHeight:i,alphaFilter:u,heightBuffer:p}).applyToMesh(f,h),d&&d(f,p),f._setReady(!0)};return"string"==typeof t?rr.LoadImage(t,(function(e){var t=e.width,i=e.height;if(!r.isDisposed){var n=null==r?void 0:r.getEngine().resizeImageBitmap(e,t,i);_(n,t,i)}}),i.onError?i.onError:function(){},r.offlineProvider):_(t.data,t.width,t.height),f}var oh={CreateGround:ih,CreateGroundFromHeightMap:nh,CreateTiledGround:rh};function ah(e){for(var t=[],i=[],r=[],n=[],o=e.diameter||1,a=e.thickness||.5,s=0|(e.tessellation||16),l=0===e.sideOrientation?0:e.sideOrientation||_o.DEFAULTSIDE,c=s+1,u=0;u<=s;u++)for(var h=u/s,d=u*Math.PI*2/s-Math.PI/2,p=z.Translation(o/2,0,0).multiply(z.RotationY(d)),f=0;f<=s;f++){var _=1-f/s,m=f*Math.PI*2/s+Math.PI,g=Math.cos(m),v=Math.sin(m),y=new V(g,v,0),b=y.scale(a/2),T=new U(h,_);b=V.TransformCoordinates(b,p),y=V.TransformNormal(y,p),i.push(b.x,b.y,b.z),r.push(y.x,y.y,y.z),n.push(T.x,go.UseOpenGLOrientationForUV?1-T.y:T.y);var E=(u+1)%c,S=(f+1)%c;t.push(u*c+f),t.push(u*c+S),t.push(E*c+f),t.push(u*c+S),t.push(E*c+S),t.push(E*c+f)}_o._ComputeSides(l,i,t,r,n,e.frontUVs,e.backUVs);var x=new _o;return x.indices=t,x.positions=i,x.normals=r,x.uvs=n,x}function sh(e,t,i){void 0===t&&(t={});var r=new Fa(e,i);return t.sideOrientation=Fa._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,ah(t).applyToMesh(r,t.updatable),r}_o.CreateGround=$u,_o.CreateTiledGround=eh,_o.CreateGroundFromHeightMap=th,Fa.CreateGround=function(e,t,i,r,n,o){return ih(e,{width:t,height:i,subdivisions:r,updatable:o},n)},Fa.CreateTiledGround=function(e,t,i,r,n,o,a,s,l){return rh(e,{xmin:t,zmin:i,xmax:r,zmax:n,subdivisions:o,precision:a,updatable:l},s)},Fa.CreateGroundFromHeightMap=function(e,t,i,r,n,o,a,s,l,c,u){return nh(e,t,{width:i,height:r,subdivisions:n,minHeight:o,maxHeight:a,updatable:l,onReady:c,alphaFilter:u},s)};var lh={CreateTorus:sh};_o.CreateTorus=ah,Fa.CreateTorus=function(e,t,i,r,n,o,a){return sh(e,{diameter:t,thickness:i,tessellation:r,sideOrientation:a,updatable:o},n)};var ch,uh=function(e){function t(t,i){var r=e.call(this,i)||this;return r._getCamera=t,r}return m(t,e),t.prototype._getForwardRay=function(e){var t=this._getCamera();return t?t.getForwardRay(e):new hs(V.Zero(),V.Forward())},t}(function(){function e(t,i){if(void 0===i&&(i=null),this.scene=t,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=e._IdCounter++,i)this._gazeTracker=i.clone("gazeTracker");else{this._gazeTracker=sh("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},t),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;var r=new Uu("targetMat",t);r.specularColor=Z.Black(),r.emissiveColor=new Z(.7,.7,.7),r.backFaceCulling=!1,this._gazeTracker.material=r}}return e.prototype._getForwardRay=function(e){return new hs(V.Zero(),new V(0,0,e))},e.prototype._selectionPointerDown=function(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})},e.prototype._selectionPointerUp=function(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1},e.prototype._activatePointer=function(){this._activePointer=!0},e.prototype._deactivatePointer=function(){this._activePointer=!1},e.prototype._updatePointerDistance=function(e){void 0===e&&(e=100)},e.prototype.dispose=function(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()},e._IdCounter=0,e}()),hh=function(){},dh=function(){function e(t,i){void 0===i&&(i={});var r=this;if(this.webVROptions=i,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new f,this.onAfterEnteringVRObservable=new f,this.onExitingVRObservable=new f,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=e.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new V(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new V(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new Z(.2,.2,1),this._pickedGazeColor=new Z(0,0,1),this.onNewMeshSelected=new f,this.onNewMeshPicked=new f,this.onBeforeCameraTeleport=new f,this.onAfterCameraTeleport=new f,this.onSelectedMeshUnselected=new f,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=function(){r._moveButtonToBottomRight()},this._onFullscreenChange=function(){r._fullscreenVRpresenting=!!document.fullscreenElement,!r._fullscreenVRpresenting&&r._inputElement&&(r.exitVR(),!r._useCustomVRButton&&r._btnVR&&(r._btnVR.style.top=r._inputElement.offsetTop+r._inputElement.offsetHeight-70+"px",r._btnVR.style.left=r._inputElement.offsetLeft+r._inputElement.offsetWidth-100+"px",r._updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this._beforeRender=function(){r._scene.getEngine().isPointerLock||r.enableGazeEvenWhenNoPointerLock||(r._cameraGazer._gazeTracker.isVisible=!1)},this._onNewGamepadConnected=function(e){e.type!==ac.POSE_ENABLED&&(e.leftStick&&e.onleftstickchanged((function(e){r._teleportationInitialized&&r.teleportationEnabled&&(r._checkTeleportWithRay(e,r._cameraGazer),r._checkTeleportBackwards(e,r._cameraGazer))})),e.rightStick&&e.onrightstickchanged((function(e){r._teleportationInitialized&&r._checkRotate(e,r._cameraGazer)})),e.type===ac.XBOX&&(e.onbuttondown((function(e){r._interactionsEnabled&&e===Uc.A&&r._cameraGazer._selectionPointerDown()})),e.onbuttonup((function(e){r._interactionsEnabled&&e===Uc.A&&r._cameraGazer._selectionPointerUp()}))))},this._workingVector=V.Zero(),this._workingQuaternion=G.Identity(),this._workingMatrix=z.Identity(),ae.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"),this._scene=t,this._inputElement=t.getEngine().getInputElement(),"getVRDisplays"in navigator||void 0!==i.useXR||(i.useXR=!0),void 0===i.createFallbackVRDeviceOrientationFreeCamera&&(i.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===i.createDeviceOrientationCamera&&(i.createDeviceOrientationCamera=!0),void 0===i.laserToggle&&(i.laserToggle=!0),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new V(0,this._defaultHeight,0),i.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new Fc("deviceOrientationVRHelper",this._position.clone(),t),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof Mc&&this._scene.activeCamera.rotation)){var n=this._scene.activeCamera;n.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(n.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(G.RotationYawPitchRoll(n.rotation.y,n.rotation.x,n.rotation.z)),this._deviceOrientationCamera.rotation=n.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?Zu.IsSessionSupportedAsync("immersive-vr").then((function(e){e?(ae.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),t.createDefaultXRExperienceAsync({floorMeshes:i.floorMeshes||[]}).then((function(e){r.xr=e,r.xrTestDone=!0,r._cameraGazer=new uh((function(){return r.xr.baseExperience.camera}),t),r.xr.baseExperience.onStateChangedObservable.add((function(e){switch(e){case Vu.ENTERING_XR:r.onEnteringVRObservable.notifyObservers(r),r._interactionsEnabled||r.xr.pointerSelection.detach(),r.xr.pointerSelection.displayLaserPointer=r._displayLaserPointer;break;case Vu.EXITING_XR:r.onExitingVRObservable.notifyObservers(r),r._scene.getEngine().resize();break;case Vu.IN_XR:r._hasEnteredVR=!0;break;case Vu.NOT_IN_XR:r._hasEnteredVR=!1}}))}))):r._completeVRInit(t,i)})):this._completeVRInit(t,i)}return Object.defineProperty(e.prototype,"onEnteringVR",{get:function(){return this.onEnteringVRObservable},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onExitingVR",{get:function(){return this.onExitingVRObservable},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"teleportationTarget",{get:function(){return this._teleportationTarget},set:function(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"gazeTrackerMesh",{get:function(){return this._cameraGazer._gazeTracker},set:function(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker")},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"displayGaze",{get:function(){return this._displayGaze},set:function(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"displayLaserPointer",{get:function(){return this._displayLaserPointer},set:function(e){this._displayLaserPointer=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"deviceOrientationCamera",{get:function(){return this._deviceOrientationCamera},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentVRCamera",{get:function(){return this._scene.activeCamera},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"vrDeviceOrientationCamera",{get:function(){return this._vrDeviceOrientationCamera},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"vrButton",{get:function(){return this._btnVR},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"_teleportationRequestInitiated",{get:function(){return this._cameraGazer._teleportationRequestInitiated},enumerable:!1,configurable:!0}),e.prototype._completeVRInit=function(e,t){var i=this;if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new Tu("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new uh((function(){return i.currentVRCamera}),e),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";var r=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";r+=".babylonVRicon.vrdisplaypresenting { display: none; }";var n=document.createElement("style");n.appendChild(document.createTextNode(r)),document.getElementsByTagName("head")[0].appendChild(n),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",(function(){i.isInVRMode||i.enterVR()}));var o=this._scene.getEngine().getHostWindow();o&&(o.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),t.createFallbackVRDeviceOrientationFreeCamera&&this._displayVRButton(),this._onKeyDown=function(e){27===e.keyCode&&i.isInVRMode&&i.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add((function(){i._hasEnteredVR&&i.exitVROnDoubleTap&&(i.exitVR(),i._fullscreenVRpresenting&&i._scene.getEngine().exitFullscreen())}),Gr.POINTERDOUBLETAP,!1),e.onDisposeObservable.add((function(){i.dispose()})),this._updateButtonVisibility(),this._circleEase=new Pn,this._circleEase.setEasingMode(Rn.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add((function(t){i._interactionsEnabled&&e.activeCamera===i.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===Gr.POINTERDOWN?i._cameraGazer._selectionPointerDown():t.type===Gr.POINTERUP&&i._cameraGazer._selectionPointerUp())})),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))},Object.defineProperty(e.prototype,"isInVRMode",{get:function(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===Vu.IN_XR||this._fullscreenVRpresenting},enumerable:!1,configurable:!0}),e.prototype._moveButtonToBottomRight=function(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){var e=this._inputElement.getBoundingClientRect();this._btnVR.style.top=e.top+e.height-70+"px",this._btnVR.style.left=e.left+e.width-100+"px"}},e.prototype._displayVRButton=function(){this._useCustomVRButton||this._btnVRDisplayed||!this._btnVR||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)},e.prototype._updateButtonVisibility=function(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode&&(this._btnVR.className+=" vrdisplaypresenting"))},e.prototype.enterVR=function(){var e=this;if(this.xr)this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);else{if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){ae.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=G.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)),this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this._updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce((function(){e.onAfterEnteringVRObservable.notifyObservers({success:!0})}))),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(),this._interactionsEnabled&&this._scene.registerBeforeRender(this._beforeRender),this._hasEnteredVR=!0}},e.prototype.exitVR=function(){if(this.xr)this.xr.baseExperience.exitXRAsync();else if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){ae.Warn("Error in your custom logic onExitingVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this._updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this._beforeRender),this._cameraGazer._gazeTracker.isVisible=!1),this._scene.getEngine().resize(),this._hasEnteredVR=!1}},Object.defineProperty(e.prototype,"position",{get:function(){return this._position},set:function(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)},enumerable:!1,configurable:!0}),e.prototype.enableInteractions=function(){var e=this;if(!this._interactionsEnabled){if(this.xr)return void(this.xr.baseExperience.state===Vu.IN_XR&&this.xr.pointerSelection.attach());this.raySelectionPredicate=function(t){return t.isVisible&&(t.isPickable||t.name===e._floorMeshName)},this.meshSelectionPredicate=function(){return!0},this._raySelectionPredicate=function(t){return!!(e._isTeleportationFloor(t)||-1===t.name.indexOf("gazeTracker")&&-1===t.name.indexOf("teleportationTarget")&&-1===t.name.indexOf("torusTeleportation"))&&e.raySelectionPredicate(t)},this._interactionsEnabled=!0}},e.prototype._isTeleportationFloor=function(e){for(var t=0;t<this._floorMeshesCollection.length;t++)if(this._floorMeshesCollection[t].id===e.id)return!0;return!(!this._floorMeshName||e.name!==this._floorMeshName)},e.prototype.addFloorMesh=function(e){this._floorMeshesCollection&&(this._floorMeshesCollection.indexOf(e)>-1||this._floorMeshesCollection.push(e))},e.prototype.removeFloorMesh=function(e){if(this._floorMeshesCollection){var t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}},e.prototype.enableTeleportation=function(e){var t=this;if(void 0===e&&(e={}),!this._teleportationInitialized){if(this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){var i=e.floorMeshes||[];if(!i.length){var r=this._scene.getMeshByName(e.floorMeshName);r&&i.push(r)}if(this.xr)return i.forEach((function(e){t.xr.teleportation.addFloorMesh(e)})),void(this.xr.teleportation.attached||this.xr.teleportation.attach());if(!this.xrTestDone){var n=function(){t.xrTestDone&&(t._scene.unregisterBeforeRender(n),t.xr?t.xr.teleportation.attached||t.xr.teleportation.attach():t.enableTeleportation(e))};return void this._scene.registerBeforeRender(n)}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),void 0!==e.easingFunction&&(this._teleportationEasing=e.easingFunction);var o=new pr;o.vignetteColor=new J(0,0,0,0),o.vignetteEnabled=!0,this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&this._createTeleportationCircles()}},e.prototype._checkTeleportWithRay=function(e,t){this._teleportationRequestInitiated&&!t._teleportationRequestInitiated||(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)<this._padSensibilityDown&&(this._teleportActive&&this.teleportCamera(this._haloCenter),t._teleportationRequestInitiated=!1):e.y<-this._padSensibilityUp&&t._dpadPressed&&(t._activatePointer(),t._teleportationRequestInitiated=!0))},e.prototype._checkRotate=function(e,t){t._teleportationRequestInitiated||(t._rotationLeftAsked?e.x>-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.x<this._padSensibilityDown&&(t._rotationRightAsked=!1):e.x>this._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))},e.prototype._checkTeleportBackwards=function(e,t){if(!t._teleportationRequestInitiated)if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;var i=G.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),r=this.currentVRCamera.position;i.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,G.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),V.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);var n=new hs(r,this._workingVector),o=this._scene.pickWithRay(n,this._raySelectionPredicate);o&&o.pickedPoint&&o.pickedMesh&&this._isTeleportationFloor(o.pickedMesh)&&o.distance<5&&this.teleportCamera(o.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1},e.prototype._createTeleportationCircles=function(){this._teleportationTarget=ih("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;var e=new Gu("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;var t=e.getContext();t.beginPath(),t.arc(256,256,200,0,2*Math.PI,!1),t.fillStyle=this._teleportationFillColor,t.fill(),t.lineWidth=10,t.strokeStyle=this._teleportationBorderColor,t.stroke(),t.closePath(),e.update();var i=new Uu("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;var r=sh("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);r.isPickable=!1,r.parent=this._teleportationTarget;var n=new at("animationInnerCircle","position.y",30,at.ANIMATIONTYPE_FLOAT,at.ANIMATIONLOOPMODE_CYCLE),o=[];o.push({frame:0,value:0}),o.push({frame:30,value:.4}),o.push({frame:60,value:0}),n.setKeys(o);var a=new Un;a.setEasingMode(Rn.EASINGMODE_EASEINOUT),n.setEasingFunction(a),r.animations=[],r.animations.push(n),this._scene.beginAnimation(r,0,60,!0),this._hideTeleportationTarget()},e.prototype._hideTeleportationTarget=function(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))},e.prototype._rotateCamera=function(e){if(this.currentVRCamera instanceof Oc){e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];var t=G.FromRotationMatrix(z.RotationY(Math.PI/4*this._rotationAngle)),i=new at("animationRotation","rotationQuaternion",90,at.ANIMATIONTYPE_QUATERNION,at.ANIMATIONLOOPMODE_CONSTANT),r=[];r.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),r.push({frame:6,value:t}),i.setKeys(r),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];var n=new at("animationPP","vignetteWeight",90,at.ANIMATIONTYPE_FLOAT,at.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:0}),o.push({frame:3,value:4}),o.push({frame:6,value:0}),n.setKeys(o),n.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(n);var a=new at("animationPP2","vignetteStretch",90,at.ANIMATIONTYPE_FLOAT,at.ANIMATIONLOOPMODE_CONSTANT),s=[];s.push({frame:0,value:0}),s.push({frame:3,value:10}),s.push({frame:6,value:0}),a.setKeys(s),a.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(a),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}},e.prototype.teleportCamera=function(t){var i=this;if(this.currentVRCamera instanceof Oc){var r,n;if(this._workingVector.copyFrom(t),this.isInVRMode||(this._workingVector.y+=this._defaultHeight),this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this._teleportationMode==e.TELEPORTATIONMODE_CONSTANTSPEED){n=90;var o=V.Distance(this.currentVRCamera.position,this._workingVector);r=this._teleportationSpeed/o}else n=Math.round(90*this._teleportationTime/1e3),r=1;this.currentVRCamera.animations=[];var a=new at("animationCameraTeleportation","position",90,at.ANIMATIONTYPE_VECTOR3,at.ANIMATIONLOOPMODE_CONSTANT),s=[{frame:0,value:this.currentVRCamera.position},{frame:n,value:this._workingVector}];a.setKeys(s),a.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(a),this._postProcessMove.animations=[];var l=Math.round(n/2),c=new at("animationPP","vignetteWeight",90,at.ANIMATIONTYPE_FLOAT,at.ANIMATIONLOOPMODE_CONSTANT),u=[];u.push({frame:0,value:0}),u.push({frame:l,value:8}),u.push({frame:n,value:0}),c.setKeys(u),this._postProcessMove.animations.push(c);var h=new at("animationPP2","vignetteStretch",90,at.ANIMATIONTYPE_FLOAT,at.ANIMATIONLOOPMODE_CONSTANT),d=[];d.push({frame:0,value:0}),d.push({frame:l,value:10}),d.push({frame:n,value:0}),h.setKeys(d),this._postProcessMove.animations.push(h),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._scene.beginAnimation(this.currentVRCamera,0,n,!1,r,(function(){i.onAfterCameraTeleport.notifyObservers(i._workingVector)})),this._hideTeleportationTarget()}},e.prototype.setLaserColor=function(e,t){void 0===t&&(t=this._pickedLaserColor),this._pickedLaserColor=t},e.prototype.setLaserLightingState=function(e){void 0===e&&(e=!0)},e.prototype.setGazeColor=function(e,t){void 0===t&&(t=this._pickedGazeColor),this._pickedGazeColor=t},e.prototype.changeLaserColor=function(e){this.updateControllerLaserColor},e.prototype.changeGazeColor=function(e){this.updateGazeTrackerColor&&this._cameraGazer._gazeTracker.material&&(this._cameraGazer._gazeTracker.material.emissiveColor=e)},e.prototype.dispose=function(){this.isInVRMode&&this.exitVR(),this._postProcessMove&&this._postProcessMove.dispose(),this._vrDeviceOrientationCamera&&this._vrDeviceOrientationCamera.dispose(),!this._useCustomVRButton&&this._btnVR&&this._btnVR.parentNode&&document.body.removeChild(this._btnVR),this._deviceOrientationCamera&&this._scene.activeCamera!=this._deviceOrientationCamera&&this._deviceOrientationCamera.dispose(),this._cameraGazer&&this._cameraGazer.dispose(),this._teleportationTarget&&this._teleportationTarget.dispose(),this.xr&&this.xr.dispose(),this._floorMeshesCollection.length=0,document.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFullscreenChange),this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected),this._scene.unregisterBeforeRender(this._beforeRender)},e.prototype.getClassName=function(){return"VRExperienceHelper"},e.TELEPORTATIONMODE_CONSTANTTIME=0,e.TELEPORTATIONMODE_CONSTANTSPEED=1,e}(),ph=(ch={root:0,found:!1},function(e,t,i,r){ch.root=0,ch.found=!1;var n=t*t-4*e*i;if(n<0)return ch;var o=Math.sqrt(n),a=(-t-o)/(2*e),s=(-t+o)/(2*e);if(a>s){var l=s;s=a,a=l}return a>0&&a<r?(ch.root=a,ch.found=!0,ch):s>0&&s<r?(ch.root=s,ch.found=!0,ch):ch}),fh=function(){function e(){this._collisionPoint=V.Zero(),this._planeIntersectionPoint=V.Zero(),this._tempVector=V.Zero(),this._tempVector2=V.Zero(),this._tempVector3=V.Zero(),this._tempVector4=V.Zero(),this._edge=V.Zero(),this._baseToVertex=V.Zero(),this._destinationPoint=V.Zero(),this._slidePlaneNormal=V.Zero(),this._displacementVector=V.Zero(),this._radius=V.One(),this._retry=0,this._basePointWorld=V.Zero(),this._velocityWorld=V.Zero(),this._normalizedVelocity=V.Zero(),this._collisionMask=-1}return Object.defineProperty(e.prototype,"collisionMask",{get:function(){return this._collisionMask},set:function(e){this._collisionMask=isNaN(e)?-1:e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"slidePlaneNormal",{get:function(){return this._slidePlaneNormal},enumerable:!1,configurable:!0}),e.prototype._initialize=function(e,t,i){this._velocity=t,this._velocitySquaredLength=this._velocity.lengthSquared();var r=Math.sqrt(this._velocitySquaredLength);0===r||1===r?this._normalizedVelocity.copyFromFloats(t._x,t._y,t._z):t.scaleToRef(1/r,this._normalizedVelocity),this._basePoint=e,e.multiplyToRef(this._radius,this._basePointWorld),t.multiplyToRef(this._radius,this._velocityWorld),this._velocityWorldLength=this._velocityWorld.length(),this._epsilon=i,this.collisionFound=!1},e.prototype._checkPointInTriangle=function(e,t,i,r,n){t.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),V.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var o=V.Dot(this._tempVector4,n);return!(o<0)&&(r.subtractToRef(e,this._tempVector3),V.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),!((o=V.Dot(this._tempVector4,n))<0)&&(V.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),(o=V.Dot(this._tempVector4,n))>=0))},e.prototype._canDoCollision=function(e,t,i,r){var n=V.Distance(this._basePointWorld,e),o=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(n>this._velocityWorldLength+o+t||!function(e,t,i,r){return!(e.x>i.x+r||i.x-r>t.x||e.y>i.y+r||i.y-r>t.y||e.z>i.z+r||i.z-r>t.z)}(i,r,this._basePointWorld,this._velocityWorldLength+o))},e.prototype._testTriangle=function(t,i,r,n,o,a,s){var l,c=!1;i||(i=[]),i[t]||(i[t]=new sn(0,0,0,0),i[t].copyFromPoints(r,n,o));var u=i[t];if(a||u.isFrontFacingTo(this._normalizedVelocity,0)){var h=u.signedDistanceTo(this._basePoint),d=V.Dot(u.normal,this._velocity);if(!(e.DoubleSidedCheck&&d>1e-4)){if(0==d){if(Math.abs(h)>=1)return;c=!0,l=0}else{var p=(1-h)/d;if((l=(-1-h)/d)>p){var f=p;p=l,l=f}if(l>1||p<0)return;l<0&&(l=0),l>1&&(l=1)}this._collisionPoint.copyFromFloats(0,0,0);var _=!1,m=1;if(c||(this._basePoint.subtractToRef(u.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(l,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,r,n,o,u.normal)&&(_=!0,m=l,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!_){var g=this._velocitySquaredLength;this._basePoint.subtractToRef(r,this._tempVector);var v=2*V.Dot(this._velocity,this._tempVector),y=this._tempVector.lengthSquared()-1,b=ph(g,v,y,m);b.found&&(m=b.root,_=!0,this._collisionPoint.copyFrom(r)),this._basePoint.subtractToRef(n,this._tempVector),v=2*V.Dot(this._velocity,this._tempVector),y=this._tempVector.lengthSquared()-1,(b=ph(g,v,y,m)).found&&(m=b.root,_=!0,this._collisionPoint.copyFrom(n)),this._basePoint.subtractToRef(o,this._tempVector),v=2*V.Dot(this._velocity,this._tempVector),y=this._tempVector.lengthSquared()-1,(b=ph(g,v,y,m)).found&&(m=b.root,_=!0,this._collisionPoint.copyFrom(o)),n.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex);var T,E=this._edge.lengthSquared(),S=V.Dot(this._edge,this._velocity),x=V.Dot(this._edge,this._baseToVertex);g=E*-this._velocitySquaredLength+S*S,v=2*(E*V.Dot(this._velocity,this._baseToVertex)-S*x),y=E*(1-this._baseToVertex.lengthSquared())+x*x,(b=ph(g,v,y,m)).found&&(T=(S*b.root-x)/E)>=0&&T<=1&&(m=b.root,_=!0,this._edge.scaleInPlace(T),r.addToRef(this._edge,this._collisionPoint)),o.subtractToRef(n,this._edge),n.subtractToRef(this._basePoint,this._baseToVertex),E=this._edge.lengthSquared(),S=V.Dot(this._edge,this._velocity),x=V.Dot(this._edge,this._baseToVertex),g=E*-this._velocitySquaredLength+S*S,v=2*(E*V.Dot(this._velocity,this._baseToVertex)-S*x),y=E*(1-this._baseToVertex.lengthSquared())+x*x,(b=ph(g,v,y,m)).found&&(T=(S*b.root-x)/E)>=0&&T<=1&&(m=b.root,_=!0,this._edge.scaleInPlace(T),n.addToRef(this._edge,this._collisionPoint)),r.subtractToRef(o,this._edge),o.subtractToRef(this._basePoint,this._baseToVertex),E=this._edge.lengthSquared(),S=V.Dot(this._edge,this._velocity),x=V.Dot(this._edge,this._baseToVertex),g=E*-this._velocitySquaredLength+S*S,v=2*(E*V.Dot(this._velocity,this._baseToVertex)-S*x),y=E*(1-this._baseToVertex.lengthSquared())+x*x,(b=ph(g,v,y,m)).found&&(T=(S*b.root-x)/E)>=0&&T<=1&&(m=b.root,_=!0,this._edge.scaleInPlace(T),o.addToRef(this._edge,this._collisionPoint))}if(_){var A=m*m*this._velocitySquaredLength;(!this.collisionFound||A<this._nearestDistanceSquared)&&(s.collisionResponse&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this._nearestDistanceSquared=A,this._nearestDistance=Math.sqrt(A),this.collisionFound=!0),this.collidedMesh=s)}}}},e.prototype._collide=function(e,t,i,r,n,o,a,s,l,c){if(void 0===c&&(c=!1),c)if(i&&0!==i.length)for(p=r;p<n-2;p+=1){var u=i[p],h=i[p+1],d=i[p+2];4294967295!==d?(f=t[u],_=t[h],m=t[d],f&&_&&m&&((l?1:0)^p%2?this._testTriangle(p,e,f,_,m,a,s):this._testTriangle(p,e,_,f,m,a,s))):p+=2}else for(var p=0;p<t.length-2;p+=1){var f=t[p],_=t[p+1],m=t[p+2];f&&_&&m&&((l?1:0)^p%2?this._testTriangle(p,e,f,_,m,a,s):this._testTriangle(p,e,_,f,m,a,s))}else if(i&&0!==i.length)for(p=r;p<n;p+=3)f=t[i[p]-o],_=t[i[p+1]-o],m=t[i[p+2]-o],l?this._testTriangle(p,e,f,_,m,a,s):this._testTriangle(p,e,m,_,f,a,s);else for(p=0;p<t.length;p+=3){f=t[p],_=t[p+1],m=t[p+2];l?this._testTriangle(p,e,f,_,m,a,s):this._testTriangle(p,e,m,_,f,a,s)}},e.prototype._getResponse=function(e,t){e.addToRef(t,this._destinationPoint),t.scaleInPlace(this._nearestDistance/t.length()),this._basePoint.addToRef(t,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this._epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(sn.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,t)},e.DoubleSidedCheck=!1,e}(),_h=function(){function e(){this._scaledPosition=V.Zero(),this._scaledVelocity=V.Zero(),this._finalPosition=V.Zero()}return e.prototype.getNewPosition=function(e,t,i,r,n,o,a){e.divideToRef(i._radius,this._scaledPosition),t.divideToRef(i._radius,this._scaledVelocity),i.collidedMesh=null,i._retry=0,i._initialVelocity=this._scaledVelocity,i._initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,r,this._finalPosition,n),this._finalPosition.multiplyInPlace(i._radius),o(a,this._finalPosition,i.collidedMesh)},e.prototype.createCollider=function(){return new fh},e.prototype.init=function(e){this._scene=e},e.prototype._collideWithWorld=function(e,t,i,r,n,o){void 0===o&&(o=null);var a=10*Do.CollisionsEpsilon;if(i._retry>=r)n.copyFrom(e);else{var s=o?o.collisionMask:i.collisionMask;i._initialize(e,t,a);for(var l=o&&o.surroundingMeshes||this._scene.meshes,c=0;c<l.length;c++){var u=l[c];u.isEnabled()&&u.checkCollisions&&u.subMeshes&&u!==o&&s&u.collisionGroup&&u._checkCollision(i)}i.collisionFound?(0===t.x&&0===t.y&&0===t.z||i._getResponse(e,t),t.length()<=a?n.copyFrom(e):(i._retry++,this._collideWithWorld(e,t,i,r,n,o))):e.addToRef(t,n)}},e}();pn.CollisionCoordinatorFactory=function(){return new _h};var mh,gh=function(){function e(t,i,r,n){void 0===n&&(n="");var o,a,s,l=this;this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new f,this.onErrorObservable=new f,this.onBindObservable=new f,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=pt.WGSL,this.name=t,this._key=n,this._engine=r,this.uniqueId=e._UniqueIdSeed++,this.defines=null!==(o=i.defines)&&void 0!==o?o:"",this.onError=i.onError,this.onCompiled=i.onCompiled,this._entryPoint=null!==(a=i.entryPoint)&&void 0!==a?a:"main",this._shaderStore=li.GetShadersStore(this._shaderLanguage),this._shaderRepository=li.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=li.GetIncludesShadersStore(this._shaderLanguage);var c=ct()?this._engine.getHostDocument():null;s="string"==typeof t?t:t.computeSource?"source:"+t.computeSource:t.computeElement?(null==c?void 0:c.getElementById(t.computeElement))||t.computeElement:t.compute||t;var u={defines:this.defines.split("\n"),indexParameters:void 0,isFragment:!1,shouldUseHighPrecisionShader:!1,processor:null,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:this._shaderRepository,includesShadersStore:this._includeShaderStore,version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:null,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};this._loadShader(s,"Compute","",(function(e){qt(u),function(e,t,i,r){var n;(null===(n=t.processor)||void 0===n?void 0:n.preProcessShaderCode)&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),oi(e,t,(function(e){t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));var n=function(e,t,i){var r,n,o=e,a=t.defines,s=ni(t,i);return(null===(r=t.processor)||void 0===r?void 0:r.preProcessor)&&(o=t.processor.preProcessor(o,a,t.isFragment,t.processingContext)),o=ri(o,s,t),(null===(n=t.processor)||void 0===n?void 0:n.postProcessor)&&(o=t.processor.postProcessor(o,a,t.isFragment,t.processingContext,i?{drawBuffersExtensionDisabled:!i.getCaps().drawBuffersExtension}:{})),i._features.needShaderCodeInlining&&(o=i.inlineShaderCode(o)),o}(e,t,r);i(n,e)}))}(e,u,(function(r){l._rawComputeSourceCode=e,i.processFinalCode&&(r=i.processFinalCode(r));var n=Jt(r,"",u);l._useFinalCode(n.vertexCode,t)}),l._engine)}))}return e.prototype._useFinalCode=function(e,t){if(t){var i=t.computeElement||t.compute||t.spectorName||t;this._computeSourceCode="//#define SHADER_NAME compute:"+i+"\n"+e}else this._computeSourceCode=e;this._prepareEffect()},Object.defineProperty(e.prototype,"key",{get:function(){return this._key},enumerable:!1,configurable:!0}),e.prototype.isReady=function(){try{return this._isReadyInternal()}catch(e){return!1}},e.prototype._isReadyInternal=function(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady},e.prototype.getEngine=function(){return this._engine},e.prototype.getPipelineContext=function(){return this._pipelineContext},e.prototype.getCompilationError=function(){return this._compilationError},e.prototype.executeWhenCompiled=function(e){var t=this;this.isReady()?e(this):(this.onCompileObservable.add((function(t){e(t)})),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout((function(){t._checkIsReady(null)}),16))},e.prototype._checkIsReady=function(e){var t=this;try{if(this._isReadyInternal())return}catch(t){return void this._processCompilationErrors(t,e)}setTimeout((function(){t._checkIsReady(e)}),16)},e.prototype._loadShader=function(e,t,i,r){var n;"undefined"!=typeof HTMLElement&&e instanceof HTMLElement?r(dt(e)):"source:"!==e.substr(0,7)?"base64:"!==e.substr(0,7)?this._shaderStore[e+t+"Shader"]?r(this._shaderStore[e+t+"Shader"]):i&&this._shaderStore[e+i+"Shader"]?r(this._shaderStore[e+i+"Shader"]):(n="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:this._shaderRepository+e,this._engine._loadFile(n+"."+t.toLowerCase()+".fx",r)):r(window.atob(e.substr(7))):r(e.substr(7))},Object.defineProperty(e.prototype,"computeSourceCode",{get:function(){var e,t;return this._computeSourceCodeOverride?this._computeSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getComputeShaderCode())&&void 0!==t?t:this._computeSourceCode},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"rawComputeSourceCode",{get:function(){return this._rawComputeSourceCode},enumerable:!1,configurable:!0}),e.prototype._prepareEffect=function(){var e=this,t=this.defines,i=this._pipelineContext;this._isReady=!1;try{var r=this._engine;this._pipelineContext=r.createComputePipelineContext(),this._pipelineContext._name=this._key,r._prepareComputePipelineContext(this._pipelineContext,this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._computeSourceCode,this._rawComputeSourceCode,this._computeSourceCodeOverride?null:t,this._entryPoint),r._executeWhenComputeStateIsCompiled(this._pipelineContext,(function(t){t&&t.numErrors>0?e._processCompilationErrors(t,i):(e._compilationError="",e._isReady=!0,e.onCompiled&&e.onCompiled(e),e.onCompileObservable.notifyObservers(e),e.onCompileObservable.clear(),i&&e.getEngine()._deleteComputePipelineContext(i))})),this._pipelineContext.isAsync&&this._checkIsReady(i)}catch(e){this._processCompilationErrors(e,i)}},e.prototype._processCompilationErrors=function(t,i){var r;if(void 0===i&&(i=null),this._compilationError="",ae.Error("Unable to compile compute effect:"),this.defines&&ae.Error("Defines:\n"+this.defines),e.LogShaderCodeOnCompilationError){var n=null===(r=this._pipelineContext)||void 0===r?void 0:r._getComputeShaderCode();n&&(ae.Error("Compute code:"),ae.Error(n))}if("string"==typeof t)this._compilationError=t,ae.Error("Error: "+this._compilationError);else for(var o=0,a=t.messages;o<a.length;o++){var s=a[o],l="";void 0!==s.line&&(l+="Line "+s.line+", "),void 0!==s.offset&&(l+="Offset "+s.offset+", "),void 0!==s.length&&(l+="Length "+s.length+", "),l+=s.type+": "+s.text,this._compilationError&&(this._compilationError+="\n"),this._compilationError+=l,ae.Error(l)}i&&(this._pipelineContext=i,this._isReady=!0),this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)},e.prototype.dispose=function(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseComputeEffect(this)},e.RegisterShader=function(e,t){li.GetShadersStore(pt.WGSL)["".concat(e,"ComputeShader")]=t},e._UniqueIdSeed=0,e.LogShaderCodeOnCompilationError=!0,e}();!function(e){e[e.Texture=0]="Texture",e[e.StorageTexture=1]="StorageTexture",e[e.UniformBuffer=2]="UniformBuffer",e[e.StorageBuffer=3]="StorageBuffer",e[e.TextureWithoutSampler=4]="TextureWithoutSampler",e[e.Sampler=5]="Sampler",e[e.ExternalTexture=6]="ExternalTexture",e[e.DataBuffer=7]="DataBuffer"}(mh||(mh={})),Er.prototype.createComputeEffect=function(e,t){throw new Error("createComputeEffect: This engine does not support compute shaders!")},Er.prototype.createComputePipelineContext=function(){throw new Error("createComputePipelineContext: This engine does not support compute shaders!")},Er.prototype.createComputeContext=function(){},Er.prototype.computeDispatch=function(e,t,i,r,n,o,a){throw new Error("computeDispatch: This engine does not support compute shaders!")},Er.prototype.computeDispatchIndirect=function(e,t,i,r,n,o){throw new Error("computeDispatchIndirect: This engine does not support compute shaders!")},Er.prototype.areAllComputeEffectsReady=function(){return!0},Er.prototype.releaseComputeEffects=function(){},Er.prototype._prepareComputePipelineContext=function(e,t,i,r,n){},Er.prototype._rebuildComputeEffects=function(){},Mi.prototype._executeWhenComputeStateIsCompiled=function(e,t){t(null)},Er.prototype._releaseComputeEffect=function(e){},Er.prototype._deleteComputePipelineContext=function(e){};var vh=function(){function e(){this._gpuTimeInFrameId=-1,this.counter=new an}return e.prototype._addDuration=function(e,t){e<this._gpuTimeInFrameId||(this._gpuTimeInFrameId!==e?(this.counter._fetchResult(),this.counter.fetchNewFrame(),this.counter.addCount(t,!1),this._gpuTimeInFrameId=e):this.counter.addCount(t,!1))},e}(),yh=function(){function e(e,t,i,r){void 0===r&&(r={}),this._bindings={},this._samplers={},this._contextIsDirty=!1,this.fastMode=!1,this.onCompiled=null,this.onError=null,this.name=e,this._engine=t,this.uniqueId=cn.UniqueId,t.enableGPUTimingMeasurements&&(this.gpuTimeInFrame=new vh),this._engine.getCaps().supportComputeShaders?r.bindingsMapping?(this._context=t.createComputeContext(),this._shaderPath=i,this._options=g({bindingsMapping:{},defines:[]},r)):ae.Error("You must provide the binding mappings as browsers don't support reflection for wgsl shaders yet!"):ae.Error("This engine does not support compute shaders!")}return Object.defineProperty(e.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"shaderPath",{get:function(){return this._shaderPath},enumerable:!1,configurable:!0}),e.prototype.getClassName=function(){return"ComputeShader"},e.prototype.setTexture=function(e,t,i){void 0===i&&(i=!0);var r=this._bindings[e];this._bindings[e]={type:i?mh.Texture:mh.TextureWithoutSampler,object:t,indexInGroupEntries:null==r?void 0:r.indexInGroupEntries},this._contextIsDirty||(this._contextIsDirty=!r||r.object!==t||r.type!==this._bindings[e].type)},e.prototype.setStorageTexture=function(e,t){var i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:mh.StorageTexture,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}},e.prototype.setExternalTexture=function(e,t){var i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:mh.ExternalTexture,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}},e.prototype.setVideoTexture=function(e,t){return!!t.externalTexture&&(this.setExternalTexture(e,t.externalTexture),!0)},e.prototype.setUniformBuffer=function(t,i){var r=this._bindings[t];this._contextIsDirty||(this._contextIsDirty=!r||r.object!==i),this._bindings[t]={type:e._BufferIsDataBuffer(i)?mh.DataBuffer:mh.UniformBuffer,object:i,indexInGroupEntries:null==r?void 0:r.indexInGroupEntries}},e.prototype.setStorageBuffer=function(t,i){var r=this._bindings[t];this._contextIsDirty||(this._contextIsDirty=!r||r.object!==i),this._bindings[t]={type:e._BufferIsDataBuffer(i)?mh.DataBuffer:mh.StorageBuffer,object:i,indexInGroupEntries:null==r?void 0:r.indexInGroupEntries}},e.prototype.setTextureSampler=function(e,t){var i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||!t.compareSampler(i.object)),this._bindings[e]={type:mh.Sampler,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}},e.prototype.isReady=function(){var e=this._effect;for(var t in this._bindings){var i=this._bindings[t],r=i.type,n=i.object;switch(r){case mh.Texture:case mh.TextureWithoutSampler:case mh.StorageTexture:case mh.ExternalTexture:if(!n.isReady())return!1}}var o=[],a=this._shaderPath;if(this._options.defines)for(var s=0;s<this._options.defines.length;s++)o.push(this._options.defines[s]);var l=o.join("\n");return this._cachedDefines!==l&&(this._cachedDefines=l,e=this._engine.createComputeEffect(a,{defines:l,entryPoint:this._options.entryPoint,onCompiled:this.onCompiled,onError:this.onError}),this._effect=e),!!e.isReady()},e.prototype.dispatch=function(e,t,i){return!(!this.fastMode&&!this._checkContext()||(this._engine.computeDispatch(this._effect,this._context,this._bindings,e,t,i,this._options.bindingsMapping,this.gpuTimeInFrame),0))},e.prototype.dispatchIndirect=function(t,i){if(void 0===i&&(i=0),!this.fastMode&&!this._checkContext())return!1;var r=e._BufferIsDataBuffer(t)?t:t.getBuffer();return this._engine.computeDispatchIndirect(this._effect,this._context,this._bindings,r,i,this._options.bindingsMapping,this.gpuTimeInFrame),!0},e.prototype._checkContext=function(){var e;if(!this.isReady())return!1;for(var t in this._bindings){var i=this._bindings[t];if(!this._options.bindingsMapping[t])throw new Error("ComputeShader ('"+this.name+"'): No binding mapping has been provided for the property '"+t+"'");switch(i.type){case mh.Texture:var r=this._samplers[t],n=i.object;r&&n._texture&&r.compareSampler(n._texture)||(this._samplers[t]=(new Ri).setParameters(n.wrapU,n.wrapV,n.wrapR,n.anisotropicFilteringLevel,n._texture.samplingMode,null===(e=n._texture)||void 0===e?void 0:e._comparisonFunction),this._contextIsDirty=!0);break;case mh.ExternalTexture:this._contextIsDirty=!0;break;case mh.UniformBuffer:var o=i.object;o.getBuffer()!==i.buffer&&(i.buffer=o.getBuffer(),this._contextIsDirty=!0)}}return this._contextIsDirty&&(this._contextIsDirty=!1,this._context.clear()),!0},e.prototype.dispatchWhenReady=function(e,t,i,r){var n=this;return void 0===r&&(r=10),new Promise((function(o){var a=function(){n.dispatch(e,t,i)?o():setTimeout(a,r)};a()}))},e.prototype.serialize=function(){var e=Ke.Serialize(this);for(var t in e.options=this._options,e.shaderPath=this._shaderPath,e.bindings={},e.textures={},this._bindings){var i=this._bindings[t],r=i.object;switch(i.type){case mh.Texture:case mh.TextureWithoutSampler:case mh.StorageTexture:var n=r.serialize();n&&(e.textures[t]=n,e.bindings[t]={type:i.type});case mh.UniformBuffer:}}return e},e.Parse=function(t,i,r){var n=Ke.Parse((function(){return new e(t.name,i.getEngine(),t.shaderPath,t.options)}),t,i,r);for(var o in t.textures){var a=t.bindings[o],s=Ja.Parse(t.textures[o],i,r);a.type===mh.Texture?n.setTexture(o,s):a.type===mh.TextureWithoutSampler?n.setTexture(o,s,!1):n.setStorageTexture(o,s)}return n},e._BufferIsDataBuffer=function(e){return void 0!==e.underlyingResource},v([Ie()],e.prototype,"name",void 0),v([Ie()],e.prototype,"fastMode",void 0),e}();a("BABYLON.ComputeShader",yh);var bh=function(){function e(e,t,i,r,n,o){this.entries=[],this._boundingVectors=new Array,this._capacity=i,this._depth=r,this._maxDepth=n,this._creationFunc=o,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}return Object.defineProperty(e.prototype,"capacity",{get:function(){return this._capacity},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"minPoint",{get:function(){return this._minPoint},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"maxPoint",{get:function(){return this._maxPoint},enumerable:!1,configurable:!0}),e.prototype.addEntry=function(e){if(this.blocks)for(var t=0;t<this.blocks.length;t++)this.blocks[t].addEntry(e);else this._creationFunc(e,this),this.entries.length>this.capacity&&this._depth<this._maxDepth&&this.createInnerBlocks()},e.prototype.removeEntry=function(e){if(this.blocks)for(var t=0;t<this.blocks.length;t++)this.blocks[t].removeEntry(e);else{var i=this.entries.indexOf(e);i>-1&&this.entries.splice(i,1)}},e.prototype.addEntries=function(e){for(var t=0;t<e.length;t++){var i=e[t];this.addEntry(i)}},e.prototype.select=function(e,t,i){if(to.IsInFrustum(this._boundingVectors,e)){if(this.blocks){for(var r=0;r<this.blocks.length;r++)this.blocks[r].select(e,t,i);return}i?t.concat(this.entries):t.concatWithNoDuplicate(this.entries)}},e.prototype.intersects=function(e,t,i,r){if(to.IntersectsSphere(this._minPoint,this._maxPoint,e,t)){if(this.blocks){for(var n=0;n<this.blocks.length;n++)this.blocks[n].intersects(e,t,i,r);return}r?i.concat(this.entries):i.concatWithNoDuplicate(this.entries)}},e.prototype.intersectsRay=function(e,t){if(e.intersectsBoxMinMax(this._minPoint,this._maxPoint)){if(this.blocks){for(var i=0;i<this.blocks.length;i++)this.blocks[i].intersectsRay(e,t);return}t.concatWithNoDuplicate(this.entries)}},e.prototype.createInnerBlocks=function(){e._CreateBlocks(this._minPoint,this._maxPoint,this.entries,this._capacity,this._depth,this._maxDepth,this,this._creationFunc),this.entries.splice(0)},e._CreateBlocks=function(t,i,r,n,o,a,s,l){s.blocks=new Array;for(var c=new V((i.x-t.x)/2,(i.y-t.y)/2,(i.z-t.z)/2),u=0;u<2;u++)for(var h=0;h<2;h++)for(var d=0;d<2;d++){var p=new e(t.add(c.multiplyByFloats(u,h,d)),t.add(c.multiplyByFloats(u+1,h+1,d+1)),n,o+1,a,l);p.addEntries(r),s.blocks.push(p)}},e}(),Th=function(){function e(e,t,i){void 0===i&&(i=2),this.maxDepth=i,this.dynamicContent=[],this._maxBlockCapacity=t||64,this._selectionContent=new sr(1024),this._creationFunc=e}return e.prototype.update=function(e,t,i){bh._CreateBlocks(e,t,i,this._maxBlockCapacity,0,this.maxDepth,this,this._creationFunc)},e.prototype.addMesh=function(e){for(var t=0;t<this.blocks.length;t++)this.blocks[t].addEntry(e)},e.prototype.removeMesh=function(e){for(var t=0;t<this.blocks.length;t++)this.blocks[t].removeEntry(e)},e.prototype.select=function(e,t){this._selectionContent.reset();for(var i=0;i<this.blocks.length;i++)this.blocks[i].select(e,this._selectionContent,t);return t?this._selectionContent.concat(this.dynamicContent):this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent},e.prototype.intersects=function(e,t,i){this._selectionContent.reset();for(var r=0;r<this.blocks.length;r++)this.blocks[r].intersects(e,t,this._selectionContent,i);return i?this._selectionContent.concat(this.dynamicContent):this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent},e.prototype.intersectsRay=function(e){this._selectionContent.reset();for(var t=0;t<this.blocks.length;t++)this.blocks[t].intersectsRay(e,this._selectionContent);return this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent},e.CreationFuncForMeshes=function(e,t){var i=e.getBoundingInfo();!e.isBlocked&&i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},e.CreationFuncForSubMeshes=function(e,t){e.getBoundingInfo().boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},e}();pn.prototype.createOrUpdateSelectionOctree=function(e,t){void 0===e&&(e=64),void 0===t&&(t=2);var i=this._getComponent(Vr.NAME_OCTREE);i||(i=new Eh(this),this._addComponent(i)),this._selectionOctree||(this._selectionOctree=new Th(Th.CreationFuncForMeshes,e,t));var r=this.getWorldExtends();return this._selectionOctree.update(r.min,r.max,this.meshes),this._selectionOctree},Object.defineProperty(pn.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),Uo.prototype.createOrUpdateSubmeshesOctree=function(e,t){void 0===e&&(e=64),void 0===t&&(t=2);var i=this.getScene(),r=i._getComponent(Vr.NAME_OCTREE);r||(r=new Eh(i),i._addComponent(r)),this._submeshesOctree||(this._submeshesOctree=new Th(Th.CreationFuncForSubMeshes,e,t)),this.computeWorldMatrix(!0);var n=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(n.minimumWorld,n.maximumWorld,this.subMeshes),this._submeshesOctree};var Eh=function(){function e(e){var t=this;this.name=Vr.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new hs(V.Zero(),new V(1,1,1)),(e=e||M.LastCreatedScene)&&(this.scene=e,this.scene.getActiveMeshCandidates=function(){return t.getActiveMeshCandidates()},this.scene.getActiveSubMeshCandidates=function(e){return t.getActiveSubMeshCandidates(e)},this.scene.getCollidingSubMeshCandidates=function(e,i){return t.getCollidingSubMeshCandidates(e,i)},this.scene.getIntersectingSubMeshCandidates=function(e,i){return t.getIntersectingSubMeshCandidates(e,i)})}return e.prototype.register=function(){var e=this;this.scene.onMeshRemovedObservable.add((function(t){var i=e.scene.selectionOctree;if(null!=i){var r=i.dynamicContent.indexOf(t);-1!==r&&i.dynamicContent.splice(r,1)}})),this.scene.onMeshImportedObservable.add((function(t){var i=e.scene.selectionOctree;null!=i&&i.addMesh(t)}))},e.prototype.getActiveMeshCandidates=function(){var e;return(null===(e=this.scene._selectionOctree)||void 0===e?void 0:e.select(this.scene.frustumPlanes))||this.scene._getDefaultMeshCandidates()},e.prototype.getActiveSubMeshCandidates=function(e){return e._submeshesOctree&&e.useOctreeForRenderingSelection?e._submeshesOctree.select(this.scene.frustumPlanes):this.scene._getDefaultSubMeshCandidates(e)},e.prototype.getIntersectingSubMeshCandidates=function(e,t){return e._submeshesOctree&&e.useOctreeForPicking?(hs.TransformToRef(t,e.getWorldMatrix(),this._tempRay),e._submeshesOctree.intersectsRay(this._tempRay)):this.scene._getDefaultSubMeshCandidates(e)},e.prototype.getCollidingSubMeshCandidates=function(e,t){if(e._submeshesOctree&&e.useOctreeForCollisions){var i=t._velocityWorldLength+Math.max(t._radius.x,t._radius.y,t._radius.z);return e._submeshesOctree.intersects(t._basePointWorld,i)}return this.scene._getDefaultSubMeshCandidates(e)},e.prototype.rebuild=function(){},e.prototype.dispose=function(){},e}();function Sh(e){var t=e.height||2,i=0===e.diameterTop?0:e.diameterTop||e.diameter||1,r=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1;i=i||1e-5,r=r||1e-5;var n,o=0|(e.tessellation||24),a=0|(e.subdivisions||1),s=!!e.hasRings,l=!!e.enclose,c=0===e.cap?0:e.cap||Fa.CAP_ALL,u=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,h=0===e.sideOrientation?0:e.sideOrientation||_o.DEFAULTSIDE,d=e.faceUV||new Array(3),p=e.faceColors,f=2+(1+(1!==u&&l?2:0))*(s?a:1);for(n=0;n<f;n++)p&&void 0===p[n]&&(p[n]=new J(1,1,1,1));for(n=0;n<f;n++)d&&void 0===d[n]&&(d[n]=new k(0,0,1,1));var _,m,g,v,y,b,T=[],E=[],S=[],x=[],A=[],C=2*Math.PI*u/o,R=(r-i)/2/t,P=V.Zero(),I=V.Zero(),M=V.Zero(),O=V.Zero(),D=V.Zero(),N=_n.Y,F=1,L=1,w=0,B=0;for(v=0;v<=a;v++)for(g=((m=v/a)*(i-r)+r)/2,F=s&&0!==v&&v!==a?2:1,b=0;b<F;b++){for(s&&(L+=b),l&&(L+=2*b),y=0;y<=o;y++)_=y*C,P.x=Math.cos(-_)*g,P.y=-t/2+m*t,P.z=Math.sin(-_)*g,0===i&&v===a?(I.x=S[S.length-3*(o+1)],I.y=S[S.length-3*(o+1)+1],I.z=S[S.length-3*(o+1)+2]):(I.x=P.x,I.z=P.z,I.y=Math.sqrt(I.x*I.x+I.z*I.z)*R,I.normalize()),0===y&&(M.copyFrom(P),O.copyFrom(I)),E.push(P.x,P.y,P.z),S.push(I.x,I.y,I.z),B=s?w!==L?d[L].y:d[L].w:d[L].y+(d[L].w-d[L].y)*m,x.push(d[L].x+(d[L].z-d[L].x)*y/o,go.UseOpenGLOrientationForUV?1-B:B),p&&A.push(p[L].r,p[L].g,p[L].b,p[L].a);1!==u&&l&&(E.push(P.x,P.y,P.z),E.push(0,P.y,0),E.push(0,P.y,0),E.push(M.x,M.y,M.z),V.CrossToRef(N,I,D),D.normalize(),S.push(D.x,D.y,D.z,D.x,D.y,D.z),V.CrossToRef(O,N,D),D.normalize(),S.push(D.x,D.y,D.z,D.x,D.y,D.z),B=s?w!==L?d[L+1].y:d[L+1].w:d[L+1].y+(d[L+1].w-d[L+1].y)*m,x.push(d[L+1].x,go.UseOpenGLOrientationForUV?1-B:B),x.push(d[L+1].z,go.UseOpenGLOrientationForUV?1-B:B),B=s?w!==L?d[L+2].y:d[L+2].w:d[L+2].y+(d[L+2].w-d[L+2].y)*m,x.push(d[L+2].x,go.UseOpenGLOrientationForUV?1-B:B),x.push(d[L+2].z,go.UseOpenGLOrientationForUV?1-B:B),p&&(A.push(p[L+1].r,p[L+1].g,p[L+1].b,p[L+1].a),A.push(p[L+1].r,p[L+1].g,p[L+1].b,p[L+1].a),A.push(p[L+2].r,p[L+2].g,p[L+2].b,p[L+2].a),A.push(p[L+2].r,p[L+2].g,p[L+2].b,p[L+2].a))),w!==L&&(w=L)}var G=1!==u&&l?o+4:o;for(v=0,L=0;L<a;L++){var z=0,W=0,H=0,X=0;for(y=0;y<o;y++)z=v*(G+1)+y,W=(v+1)*(G+1)+y,H=v*(G+1)+(y+1),X=(v+1)*(G+1)+(y+1),T.push(z,W,H),T.push(X,H,W);1!==u&&l&&(T.push(z+2,W+2,H+2),T.push(X+2,H+2,W+2),T.push(z+4,W+4,H+4),T.push(X+4,H+4,W+4)),v=s?v+2:v+1}var j=function(e){var n=e?i/2:r/2;if(0!==n){var a,s,l,c=e?d[f-1]:d[0],h=null;p&&(h=e?p[f-1]:p[0]);var _=E.length/3,m=e?t/2:-t/2,g=new V(0,m,0);E.push(g.x,g.y,g.z),S.push(0,e?1:-1,0);var v=c.y+.5*(c.w-c.y);x.push(c.x+.5*(c.z-c.x),go.UseOpenGLOrientationForUV?1-v:v),h&&A.push(h.r,h.g,h.b,h.a);var y=new U(.5,.5);for(l=0;l<=o;l++){a=2*Math.PI*l*u/o;var b=Math.cos(-a),C=Math.sin(-a);s=new V(b*n,m,C*n);var R=new U(b*y.x+.5,C*y.y+.5);E.push(s.x,s.y,s.z),S.push(0,e?1:-1,0);var P=c.y+(c.w-c.y)*R.y;x.push(c.x+(c.z-c.x)*R.x,go.UseOpenGLOrientationForUV?1-P:P),h&&A.push(h.r,h.g,h.b,h.a)}for(l=0;l<o;l++)e?(T.push(_),T.push(_+(l+2)),T.push(_+(l+1))):(T.push(_),T.push(_+(l+1)),T.push(_+(l+2)))}};c!==Fa.CAP_START&&c!==Fa.CAP_ALL||j(!1),c!==Fa.CAP_END&&c!==Fa.CAP_ALL||j(!0),_o._ComputeSides(h,E,T,S,x,e.frontUVs,e.backUVs);var Y=new _o;return Y.indices=T,Y.positions=E,Y.normals=S,Y.uvs=x,p&&(Y.colors=A),Y}function xh(e,t,i){void 0===t&&(t={});var r=new Fa(e,i);return t.sideOrientation=Fa._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,Sh(t).applyToMesh(r,t.updatable),r}var Ah={CreateCylinder:xh};_o.CreateCylinder=Sh,Fa.CreateCylinder=function(e,t,i,r,n,o,a,s,l){return void 0!==a&&a instanceof pn||(void 0!==a&&(l=s||Fa.DEFAULTSIDE,s=a),a=o,o=1),xh(e,{height:t,diameterTop:i,diameterBottom:r,tessellation:n,subdivisions:o,sideOrientation:l,updatable:s},a)},qe.AddNodeConstructor("Light_Type_3",(function(e,t){return function(){return new Ch(e,V.Zero(),t)}}));var Ch=function(e){function t(t,i,r){var n=e.call(this,t,r)||this;return n.groundColor=new Z(0,0,0),n.direction=i||V.Up(),n}return m(t,e),t.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},t.prototype.getClassName=function(){return"HemisphericLight"},t.prototype.setDirectionToTarget=function(e){return this.direction=V.Normalize(e.subtract(V.Zero())),this.direction},t.prototype.getShadowGenerator=function(){return null},t.prototype.transferToEffect=function(e,t){var i=V.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",i.x,i.y,i.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this},t.prototype.transferToNodeMaterialEffect=function(e,t){var i=V.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this},t.prototype.computeWorldMatrix=function(){return this._worldMatrix||(this._worldMatrix=z.Identity()),this._worldMatrix},t.prototype.getTypeID=function(){return wa.LIGHTTYPEID_HEMISPHERICLIGHT},t.prototype.prepareLightSpecificDefines=function(e,t){e["HEMILIGHT"+t]=!0},v([Oe()],t.prototype,"groundColor",void 0),v([Fe()],t.prototype,"direction",void 0),t}(wa);a("BABYLON.HemisphericLight",Ch);var Rh,Ph,Ih=function(){function e(e,t){void 0===t&&(t=!0);var i=this;this.originalScene=e,this._pointerCaptures={},this._lastPointerEvents={},this._sharedGizmoLight=null,this._renderCamera=null,this.pickUtilitySceneFirst=!0,this.shouldRender=!0,this.onlyCheckPointerDownEvents=!0,this.processAllEvents=!1,this.pickingEnabled=!0,this.onPointerOutObservable=new f,this.utilityLayerScene=new pn(e.getEngine(),{virtual:!0}),this.utilityLayerScene.useRightHandedSystem=e.useRightHandedSystem,this.utilityLayerScene._allowPostProcessClearColor=!1,this.utilityLayerScene.postProcessesEnabled=!1,this.utilityLayerScene.detachControl(),t&&(this._originalPointerObserver=e.onPrePointerObservable.add((function(t){if(i.utilityLayerScene.activeCamera&&i.pickingEnabled&&(i.processAllEvents||t.type===Gr.POINTERMOVE||t.type===Gr.POINTERUP||t.type===Gr.POINTERDOWN||t.type===Gr.POINTERDOUBLETAP)){i.utilityLayerScene.pointerX=e.pointerX,i.utilityLayerScene.pointerY=e.pointerY;var r=t.event;if(e.isPointerCaptured(r.pointerId))i._pointerCaptures[r.pointerId]=!1;else{var n=function(r){var n=null;if(t.nearInteractionPickingInfo)n=t.nearInteractionPickingInfo.pickedMesh.getScene()==r?t.nearInteractionPickingInfo:new Fr;else if(r!==i.utilityLayerScene&&t.originalPickingInfo)n=t.originalPickingInfo;else{var o=null;i._renderCamera&&(o=r._activeCamera,r._activeCamera=i._renderCamera,t.ray=null),n=t.ray?r.pickWithRay(t.ray):r.pick(e.pointerX,e.pointerY),o&&(r._activeCamera=o)}return n},o=n(i.utilityLayerScene);if(!t.ray&&o&&(t.ray=o.ray),i.utilityLayerScene.onPrePointerObservable.notifyObservers(t),i.onlyCheckPointerDownEvents&&t.type!=Gr.POINTERDOWN)return t.skipOnPointerObservable||i.utilityLayerScene.onPointerObservable.notifyObservers(new Hr(t.type,t.event,o),t.type),void(t.type===Gr.POINTERUP&&i._pointerCaptures[r.pointerId]&&(i._pointerCaptures[r.pointerId]=!1));if(i.utilityLayerScene.autoClearDepthAndStencil||i.pickUtilitySceneFirst)o&&o.hit&&(t.skipOnPointerObservable||i.utilityLayerScene.onPointerObservable.notifyObservers(new Hr(t.type,t.event,o),t.type),t.skipOnPointerObservable=!0);else{var a=n(e),s=t.event;a&&o&&(0===o.distance&&a.pickedMesh?i.mainSceneTrackerPredicate&&i.mainSceneTrackerPredicate(a.pickedMesh)?(i._notifyObservers(t,a,s),t.skipOnPointerObservable=!0):t.type===Gr.POINTERDOWN?i._pointerCaptures[s.pointerId]=!0:t.type!==Gr.POINTERMOVE&&t.type!==Gr.POINTERUP||(i._lastPointerEvents[s.pointerId]&&(i.onPointerOutObservable.notifyObservers(s.pointerId),delete i._lastPointerEvents[s.pointerId]),i._notifyObservers(t,a,s)):!i._pointerCaptures[s.pointerId]&&(o.distance<a.distance||0===a.distance)?(i._notifyObservers(t,o,s),t.skipOnPointerObservable||(t.skipOnPointerObservable=o.distance>0)):!i._pointerCaptures[s.pointerId]&&o.distance>=a.distance&&(i.mainSceneTrackerPredicate&&i.mainSceneTrackerPredicate(a.pickedMesh)?(i._notifyObservers(t,a,s),t.skipOnPointerObservable=!0):(t.type!==Gr.POINTERMOVE&&t.type!==Gr.POINTERUP||i._lastPointerEvents[s.pointerId]&&(i.onPointerOutObservable.notifyObservers(s.pointerId),delete i._lastPointerEvents[s.pointerId]),i._notifyObservers(t,o,s))),t.type===Gr.POINTERUP&&i._pointerCaptures[s.pointerId]&&(i._pointerCaptures[s.pointerId]=!1))}}}})),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add((function(e){i.shouldRender&&e==i.getRenderCamera()&&i.render()})),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add((function(){i.dispose()})),this._updateCamera()}return e.prototype.getRenderCamera=function(e){if(this._renderCamera)return this._renderCamera;var t;return t=this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:this.originalScene.activeCamera,e&&t&&t.isRigCamera?t.rigParent:t},e.prototype.setRenderCamera=function(e){this._renderCamera=e},e.prototype._getSharedGizmoLight=function(){return this._sharedGizmoLight||(this._sharedGizmoLight=new Ch("shared gizmo light",new V(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=Z.Gray()),this._sharedGizmoLight},Object.defineProperty(e,"DefaultUtilityLayer",{get:function(){return null==e._DefaultUtilityLayer?e._CreateDefaultUtilityLayerFromScene(M.LastCreatedScene):e._DefaultUtilityLayer},enumerable:!1,configurable:!0}),e._CreateDefaultUtilityLayerFromScene=function(t){return e._DefaultUtilityLayer=new e(t),e._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce((function(){e._DefaultUtilityLayer=null})),e._DefaultUtilityLayer},Object.defineProperty(e,"DefaultKeepDepthUtilityLayer",{get:function(){return null==e._DefaultKeepDepthUtilityLayer&&(e._DefaultKeepDepthUtilityLayer=new e(M.LastCreatedScene),e._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,e._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce((function(){e._DefaultKeepDepthUtilityLayer=null}))),e._DefaultKeepDepthUtilityLayer},enumerable:!1,configurable:!0}),e.prototype._notifyObservers=function(e,t,i){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new Hr(e.type,e.event,t),e.type),this._lastPointerEvents[i.pointerId]=!0)},e.prototype.render=function(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){var e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}},e.prototype.dispose=function(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()},e.prototype._updateCamera=function(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()},e._DefaultUtilityLayer=null,e._DefaultKeepDepthUtilityLayer=null,e}();!function(e){e[e.Origin=0]="Origin",e[e.Pivot=1]="Pivot"}(Rh||(Rh={})),function(e){e[e.World=0]="World",e[e.Local=1]="Local"}(Ph||(Ph={}));var Mh,Oh=function(){function e(e){void 0===e&&(e=Ih.DefaultUtilityLayer);var t=this;this.gizmoLayer=e,this._attachedMesh=null,this._attachedNode=null,this._customRotationQuaternion=null,this._scaleRatio=1,this._isHovered=!1,this._customMeshSet=!1,this._updateGizmoRotationToMatchAttachedMesh=!0,this._updateGizmoPositionToMatchAttachedMesh=!0,this._anchorPoint=Rh.Origin,this._updateScale=!0,this._coordinatesMode=Ph.Local,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=z.RotationY(Math.PI),this._rootMesh=new Fa("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=G.Identity(),this._beforeRenderObserver=this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add((function(){t._update()}))}return Object.defineProperty(e.prototype,"scaleRatio",{get:function(){return this._scaleRatio},set:function(e){this._scaleRatio=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isHovered",{get:function(){return this._isHovered},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"attachedMesh",{get:function(){return this._attachedMesh},set:function(e){this._attachedMesh=e,e&&(this._attachedNode=e),this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"attachedNode",{get:function(){return this._attachedNode},set:function(e){this._attachedNode=e,this._attachedMesh=null,this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)},enumerable:!1,configurable:!0}),e.prototype.setCustomMesh=function(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._rootMesh.getChildMeshes().forEach((function(e){e.dispose()})),e.parent=this._rootMesh,this._customMeshSet=!0},Object.defineProperty(e.prototype,"additionalTransformNode",{get:function(){return this._additionalTransformNode},set:function(e){this._additionalTransformNode=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this._updateGizmoRotationToMatchAttachedMesh},set:function(e){this._updateGizmoRotationToMatchAttachedMesh=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"updateGizmoPositionToMatchAttachedMesh",{get:function(){return this._updateGizmoPositionToMatchAttachedMesh},set:function(e){this._updateGizmoPositionToMatchAttachedMesh=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"anchorPoint",{get:function(){return this._anchorPoint},set:function(e){this._anchorPoint=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"coordinatesMode",{get:function(){return this._coordinatesMode},set:function(e){this._coordinatesMode=e;var t=e==Ph.Local;this.updateGizmoRotationToMatchAttachedMesh=t,this.updateGizmoPositionToMatchAttachedMesh=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"updateScale",{get:function(){return this._updateScale},set:function(e){this._updateScale=e},enumerable:!1,configurable:!0}),e.prototype._attachedNodeChanged=function(e){},Object.defineProperty(e.prototype,"customRotationQuaternion",{get:function(){return this._customRotationQuaternion},set:function(e){this._customRotationQuaternion=e},enumerable:!1,configurable:!0}),e.prototype._update=function(){if(this.attachedNode){var t=this.attachedNode;if(this.attachedMesh&&(t=this.attachedMesh||this.attachedNode),this.updateGizmoPositionToMatchAttachedMesh)if(this.anchorPoint==Rh.Pivot&&t.getAbsolutePivotPoint){var i=t.getAbsolutePivotPoint();this._rootMesh.position.copyFrom(i)}else{var r=t.getWorldMatrix().getRow(3);i=r?r.toVector3():new V(0,0,0),this._rootMesh.position.copyFrom(i)}if(this.updateGizmoRotationToMatchAttachedMesh){var n=t._isMesh||"AbstractMesh"===t.getClassName()||"TransformNode"===t.getClassName()||"InstancedMesh"===t.getClassName()?t:void 0;t.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion,void 0,e.PreserveScaling?n:void 0),this._rootMesh.rotationQuaternion.normalize()}else this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1);if(this.updateScale){var o=this.gizmoLayer.utilityLayerScene.activeCamera,a=o.globalPosition;this._rootMesh.position.subtractToRef(a,H.Vector3[0]);var s=this.scaleRatio;if(o.mode==$n.ORTHOGRAPHIC_CAMERA)o.orthoTop&&o.orthoBottom&&(s*=o.orthoTop-o.orthoBottom);else{var l=o.getScene().useRightHandedSystem?V.RightHandedForwardReadOnly:V.LeftHandedForwardReadOnly,c=o.getDirection(l);s*=V.Dot(H.Vector3[0],c)}this._rootMesh.scaling.setAll(s),t._getWorldMatrixDeterminant()<0&&!e.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}this.additionalTransformNode&&(this._rootMesh.computeWorldMatrix(!0),this._rootMesh.getWorldMatrix().multiplyToRef(this.additionalTransformNode.getWorldMatrix(),H.Matrix[0]),H.Matrix[0].decompose(this._rootMesh.scaling,this._rootMesh.rotationQuaternion,this._rootMesh.position))},e.prototype._handlePivotMatrixInverse=function(e,t,i){if(e.isUsingPivotMatrix()&&!e.isUsingPostMultiplyPivotMatrix())return e.getPivotMatrix().invertToRef(H.Matrix[5]),void H.Matrix[5].multiplyToRef(t,i);i.copyFrom(t)},e.prototype._matrixChanged=function(){if(this._attachedNode)if(this._attachedNode._isCamera){var t=this._attachedNode,i=void 0,r=void 0;if(t.parent){var n=H.Matrix[1];t.parent._worldMatrix.invertToRef(n),this._attachedNode._worldMatrix.multiplyToRef(n,H.Matrix[0]),i=H.Matrix[0]}else i=this._attachedNode._worldMatrix;if(t.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(i,H.Matrix[1]),r=H.Matrix[1]):r=i,r.decompose(H.Vector3[1],H.Quaternion[0],H.Vector3[0]),"FreeCamera"===this._attachedNode.getClassName()||"FlyCamera"===this._attachedNode.getClassName()||"ArcFollowCamera"===this._attachedNode.getClassName()||"TargetCamera"===this._attachedNode.getClassName()||"TouchCamera"===this._attachedNode.getClassName()||"UniversalCamera"===this._attachedNode.getClassName()){var o=this._attachedNode;o.rotation=H.Quaternion[0].toEulerAngles(),o.rotationQuaternion&&(o.rotationQuaternion.copyFrom(H.Quaternion[0]),o.rotationQuaternion.normalize())}t.position.copyFrom(H.Vector3[0])}else if(this._attachedNode._isMesh||"AbstractMesh"===this._attachedNode.getClassName()||"TransformNode"===this._attachedNode.getClassName()||"InstancedMesh"===this._attachedNode.getClassName()){var a=this._attachedNode;if(a.parent){n=H.Matrix[0];var s=H.Matrix[1];a.parent.getWorldMatrix().invertToRef(n),this._attachedNode.getWorldMatrix().multiplyToRef(n,s);var l=H.Matrix[4];if(this._handlePivotMatrixInverse(a,s,l),l.decompose(H.Vector3[0],H.Quaternion[0],a.position,e.PreserveScaling?a:void 0,e.UseAbsoluteScaling),H.Quaternion[0].normalize(),a.isUsingPivotMatrix()){var c=H.Quaternion[1];G.RotationYawPitchRollToRef(a.rotation.y,a.rotation.x,a.rotation.z,c);var u=H.Matrix[2];z.ScalingToRef(a.scaling.x,a.scaling.y,a.scaling.z,u);var h=H.Matrix[2];c.toRotationMatrix(h);var d=a.getPivotMatrix(),p=H.Matrix[3];d.invertToRef(p),d.multiplyToRef(u,H.Matrix[4]),H.Matrix[4].multiplyToRef(h,H.Matrix[5]),H.Matrix[5].multiplyToRef(p,H.Matrix[6]),H.Matrix[6].getTranslationToRef(H.Vector3[1]),a.position.subtractInPlace(H.Vector3[1])}}else l=H.Matrix[4],this._handlePivotMatrixInverse(a,this._attachedNode._worldMatrix,l),l.decompose(H.Vector3[0],H.Quaternion[0],a.position,e.PreserveScaling?a:void 0,e.UseAbsoluteScaling);H.Vector3[0].scaleInPlace(1/a.scalingDeterminant),a.scaling.copyFrom(H.Vector3[0]),a.billboardMode||(a.rotationQuaternion?(a.rotationQuaternion.copyFrom(H.Quaternion[0]),a.rotationQuaternion.normalize()):a.rotation=H.Quaternion[0].toEulerAngles())}else if("Bone"===this._attachedNode.getClassName()){var f=this._attachedNode,_=f.getParent();if(_){var m=H.Matrix[0],g=H.Matrix[1];_.getFinalMatrix().invertToRef(m),f.getFinalMatrix().multiplyToRef(m,g),f.getLocalMatrix().copyFrom(g)}else f.getLocalMatrix().copyFrom(f.getFinalMatrix());f.markAsDirty()}else{var v=this._attachedNode;if(v.getTypeID){var y=v.getTypeID();if(y===wa.LIGHTTYPEID_DIRECTIONALLIGHT||y===wa.LIGHTTYPEID_SPOTLIGHT||y===wa.LIGHTTYPEID_POINTLIGHT){var b=v.parent;if(b){m=H.Matrix[0];var T=H.Matrix[1];b.getWorldMatrix().invertToRef(m),v.getWorldMatrix().multiplyToRef(m,T),T.decompose(void 0,H.Quaternion[0],H.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,H.Quaternion[0],H.Vector3[0]);v.position=new V(H.Vector3[0].x,H.Vector3[0].y,H.Vector3[0].z),v.direction&&(v.direction=new V(v.direction.x,v.direction.y,v.direction.z))}}}},e.prototype._setGizmoMeshMaterial=function(e,t){e&&e.forEach((function(e){e.material=t,e.color&&(e.color=t.diffuseColor)}))},e.GizmoAxisPointerObserver=function(e,t){var i=!1,r=e.utilityLayerScene.onPointerObservable.add((function(e){var r,n;if(e.pickInfo){if(e.type===Gr.POINTERMOVE){if(i)return;t.forEach((function(t){var i,r;if(t.colliderMeshes&&t.gizmoMeshes){var n=-1!=(null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(r=null==e?void 0:e.pickInfo)||void 0===r?void 0:r.pickedMesh)),o=t.dragBehavior.enabled?n||t.active?t.hoverMaterial:t.material:t.disableMaterial;t.gizmoMeshes.forEach((function(e){e.material=o,e.color&&(e.color=o.diffuseColor)}))}}))}e.type===Gr.POINTERDOWN&&t.has(null===(r=e.pickInfo.pickedMesh)||void 0===r?void 0:r.parent)&&(i=!0,t.get(null===(n=e.pickInfo.pickedMesh)||void 0===n?void 0:n.parent).active=!0,t.forEach((function(t){var i,r,n=(-1!=(null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(r=null==e?void 0:e.pickInfo)||void 0===r?void 0:r.pickedMesh))||t.active)&&t.dragBehavior.enabled?t.hoverMaterial:t.disableMaterial;t.gizmoMeshes.forEach((function(e){e.material=n,e.color&&(e.color=n.diffuseColor)}))}))),e.type===Gr.POINTERUP&&t.forEach((function(e){e.active=!1,i=!1,e.gizmoMeshes.forEach((function(t){t.material=e.dragBehavior.enabled?e.material:e.disableMaterial,t.color&&(t.color=e.material.diffuseColor)}))}))}}));return r},e.prototype.dispose=function(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)},e.PreserveScaling=!1,e.UseAbsoluteScaling=!0,e}(),Dh=function(e){function t(i,r,n,o,a,s,l){void 0===r&&(r=Z.Gray()),void 0===n&&(n=Ih.DefaultUtilityLayer),void 0===o&&(o=null),void 0===a&&(a=1),void 0===s&&(s=Z.Yellow()),void 0===l&&(l=Z.Gray());var c,u=this;(u=e.call(this,n)||this)._pointerObserver=null,u.snapDistance=0,u.onSnapObservable=new f,u._isEnabled=!0,u._parent=null,u._dragging=!1,u._parent=o,u._coloredMaterial=new Uu("",n.utilityLayerScene),u._coloredMaterial.diffuseColor=r,u._coloredMaterial.specularColor=r.subtract(new Z(.1,.1,.1)),u._hoverMaterial=new Uu("",n.utilityLayerScene),u._hoverMaterial.diffuseColor=s,u._disableMaterial=new Uu("",n.utilityLayerScene),u._disableMaterial.diffuseColor=l,u._disableMaterial.alpha=.4;var h=t._CreateArrow(n.utilityLayerScene,u._coloredMaterial,a),d=t._CreateArrow(n.utilityLayerScene,u._coloredMaterial,a+4,!0);u._gizmoMesh=new Fa("",n.utilityLayerScene),u._gizmoMesh.addChild(h),u._gizmoMesh.addChild(d),u._gizmoMesh.lookAt(u._rootMesh.position.add(i)),u._gizmoMesh.scaling.scaleInPlace(1/3),u._gizmoMesh.parent=u._rootMesh;var p=0,_={snapDistance:0};u.dragBehavior=new gs({dragAxis:i}),u.dragBehavior.moveAttached=!1,u.dragBehavior.updateDragPlane=!1,u._rootMesh.addBehavior(u.dragBehavior),u.dragBehavior.onDragObservable.add((function(e){if(u.attachedNode){var t=!1;if(0==u.snapDistance)u.attachedNode.getWorldMatrix().getTranslationToRef(H.Vector3[2]),H.Vector3[2].addInPlace(e.delta),u.dragBehavior.validateDrag(H.Vector3[2])&&(u.attachedNode.position&&u.attachedNode.position.addInPlaceFromFloats(e.delta.x,e.delta.y,e.delta.z),u.attachedNode.getWorldMatrix().addTranslationFromFloats(e.delta.x,e.delta.y,e.delta.z),u.attachedNode.updateCache(),t=!0);else if(p+=e.dragDistance,Math.abs(p)>u.snapDistance){var i=Math.floor(Math.abs(p)/u.snapDistance);p%=u.snapDistance,e.delta.normalizeToRef(H.Vector3[1]),H.Vector3[1].scaleInPlace(u.snapDistance*i),u.attachedNode.getWorldMatrix().getTranslationToRef(H.Vector3[2]),H.Vector3[2].addInPlace(H.Vector3[1]),u.dragBehavior.validateDrag(H.Vector3[2])&&(u.attachedNode.getWorldMatrix().addTranslationFromFloats(H.Vector3[1].x,H.Vector3[1].y,H.Vector3[1].z),u.attachedNode.updateCache(),_.snapDistance=u.snapDistance*i*Math.sign(p),u.onSnapObservable.notifyObservers(_),t=!0)}t&&u._matrixChanged()}})),u.dragBehavior.onDragStartObservable.add((function(){u._dragging=!0})),u.dragBehavior.onDragEndObservable.add((function(){u._dragging=!1}));var m=n._getSharedGizmoLight();m.includedOnlyMeshes=m.includedOnlyMeshes.concat(u._rootMesh.getChildMeshes(!1));var g={gizmoMeshes:h.getChildMeshes(),colliderMeshes:d.getChildMeshes(),material:u._coloredMaterial,hoverMaterial:u._hoverMaterial,disableMaterial:u._disableMaterial,active:!1,dragBehavior:u.dragBehavior};return null===(c=u._parent)||void 0===c||c.addToAxisCache(d,g),u._pointerObserver=n.utilityLayerScene.onPointerObservable.add((function(e){var t;if(!u._customMeshSet&&(u._isHovered=!(-1==g.colliderMeshes.indexOf(null===(t=null==e?void 0:e.pickInfo)||void 0===t?void 0:t.pickedMesh)),!u._parent)){var i=u.dragBehavior.enabled?u._isHovered||u._dragging?u._hoverMaterial:u._coloredMaterial:u._disableMaterial;u._setGizmoMeshMaterial(g.gizmoMeshes,i)}})),u.dragBehavior.onEnabledObservable.add((function(e){u._setGizmoMeshMaterial(g.gizmoMeshes,e?g.material:g.disableMaterial)})),u}return m(t,e),Object.defineProperty(t.prototype,"coloredMaterial",{get:function(){return this._coloredMaterial},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hoverMaterial",{get:function(){return this._hoverMaterial},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"disableMaterial",{get:function(){return this._disableMaterial},enumerable:!1,configurable:!0}),t._CreateArrow=function(e,t,i,r){void 0===i&&(i=1),void 0===r&&(r=!1);var n=new Fo("arrow",e),o=xh("cylinder",{diameterTop:0,height:.075,diameterBottom:.0375*(1+(i-1)/4),tessellation:96},e),a=xh("cylinder",{diameterTop:.005*i,height:.275,diameterBottom:.005*i,tessellation:96},e);return o.parent=n,o.material=t,o.rotation.x=Math.PI/2,o.position.z+=.3,a.parent=n,a.material=t,a.position.z+=.1375,a.rotation.x=Math.PI/2,r&&(a.visibility=0,o.visibility=0),n},t._CreateArrowInstance=function(e,t){for(var i=new Fo("arrow",e),r=0,n=t.getChildMeshes();r<n.length;r++){var o=n[r];o.createInstance(o.name).parent=i}return i},t.prototype._attachedNodeChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)},enumerable:!1,configurable:!0}),t.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((function(e){e&&e.dispose()})),e.prototype.dispose.call(this)},t}(Oh),Nh=function(){function e(t,i,r,n,o,a,s){if(void 0===i&&(i=1),void 0===r&&(r=2),void 0===s&&(s=1),this._scaleLinesFactor=4,this._instanced=!1,this.scene=null,this._scaleLines=1,t=t||M.LastCreatedScene){if(!n){var l=new Uu("xAxisMaterial",t);l.disableLighting=!0,l.emissiveColor=Z.Red().scale(.5),n=Dh._CreateArrow(t,l,s)}if(!o){var c=new Uu("yAxisMaterial",t);c.disableLighting=!0,c.emissiveColor=Z.Green().scale(.5),o=Dh._CreateArrow(t,c,s)}if(!a){var u=new Uu("zAxisMaterial",t);u.disableLighting=!0,u.emissiveColor=Z.Blue().scale(.5),a=Dh._CreateArrow(t,u,s)}this._xAxis=n,this._yAxis=o,this._zAxis=a,this.scaleLines=i,null!=r&&(e._SetRenderingGroupId(this._xAxis,r),e._SetRenderingGroupId(this._yAxis,r),e._SetRenderingGroupId(this._zAxis,r)),this.scene=t,this.update(new V,V.Right(),V.Up(),V.Forward())}}return Object.defineProperty(e.prototype,"scaleLines",{get:function(){return this._scaleLines},set:function(e){this._scaleLines=e,this._xAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor),this._yAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor),this._zAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"xAxis",{get:function(){return this._xAxis},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"yAxis",{get:function(){return this._yAxis},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"zAxis",{get:function(){return this._zAxis},enumerable:!1,configurable:!0}),e.prototype.update=function(e,t,i,r){this._xAxis.position.copyFrom(e),this._xAxis.setDirection(t),this._yAxis.position.copyFrom(e),this._yAxis.setDirection(i),this._zAxis.position.copyFrom(e),this._zAxis.setDirection(r)},e.prototype.createInstance=function(){var t=Dh._CreateArrowInstance(this.scene,this._xAxis),i=Dh._CreateArrowInstance(this.scene,this._yAxis),r=Dh._CreateArrowInstance(this.scene,this._zAxis),n=new e(this.scene,this.scaleLines,null,t,i,r);return n._instanced=!0,n},e.prototype.dispose=function(){this._xAxis&&this._xAxis.dispose(!1,!this._instanced),this._yAxis&&this._yAxis.dispose(!1,!this._instanced),this._zAxis&&this._zAxis.dispose(!1,!this._instanced),this.scene=null},e._SetRenderingGroupId=function(e,t){e.getChildMeshes().forEach((function(e){e.renderingGroupId=t}))},e}(),Fh=function(e){function t(t,i,r,n){void 0===n&&(n=1);var o=e.call(this,t,n)||this;return o.pos=V.Zero(),o.xaxis=V.Zero(),o.yaxis=V.Zero(),o.zaxis=V.Zero(),o.mesh=r,o.bone=i,o}return m(t,e),t.prototype.update=function(){if(this.mesh&&this.bone){var t=this.bone;t.getAbsolutePositionToRef(this.mesh,this.pos),t.getDirectionToRef(_n.X,this.mesh,this.xaxis),t.getDirectionToRef(_n.Y,this.mesh,this.yaxis),t.getDirectionToRef(_n.Z,this.mesh,this.zaxis),e.prototype.update.call(this,this.pos,this.xaxis,this.yaxis,this.zaxis)}},t.prototype.dispose=function(){this.mesh&&(this.mesh=null,this.bone=null,e.prototype.dispose.call(this))},t}(Nh);Object.defineProperty(pn.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new Lh(this)),this._debugLayer},enumerable:!0,configurable:!0}),function(e){e[e.Properties=0]="Properties",e[e.Debug=1]="Debug",e[e.Statistics=2]="Statistics",e[e.Tools=3]="Tools",e[e.Settings=4]="Settings"}(Mh||(Mh={}));var Lh=function(){function e(e){var t=this;this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||M.LastCreatedScene,this._scene&&this._scene.onDisposeObservable.add((function(){t._scene._debugLayer&&t._scene._debugLayer.hide()}))}return Object.defineProperty(e.prototype,"onPropertyChangedObservable",{get:function(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new f),this._onPropertyChangedObservable)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onSelectionChangedObservable",{get:function(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new f),this._onSelectionChangedObservable)},enumerable:!1,configurable:!0}),e.prototype._createInspector=function(t){if(!this.isVisible()){if(this._onPropertyChangedObservable){for(var i=0,r=this._onPropertyChangedObservable.observers;i<r.length;i++){var n=r[i];this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(n)}this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(var o=0,a=this._onSelectionChangedObservable.observers;o<a.length;o++)n=a[o],this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(n);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}var s=g(g({},e.Config),t);this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,s)}},e.prototype.select=function(e,t){this.BJSINSPECTOR&&(t&&("[object String]"==Object.prototype.toString.call(t)?this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t):this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(t)),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))},e.prototype._getGlobalInspector=function(){return"undefined"!=typeof INSPECTOR?INSPECTOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.Inspector?BABYLON:void 0},e.prototype.isVisible=function(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.IsVisible},e.prototype.hide=function(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.Hide()},e.prototype.setAsActiveScene=function(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector._SetNewScene(this._scene)},e.prototype.show=function(t){var i=this;return new Promise((function(r){if(void 0===i.BJSINSPECTOR){var n=t&&t.inspectorURL?t.inspectorURL:e.InspectorURL;rr.LoadBabylonScript(n,(function(){i._createInspector(t),r(i)}))}else i._createInspector(t),r(i)}))},e.InspectorURL="".concat(rr._DefaultCdnUrl,"/v").concat(Do.Version,"/inspector/babylon.inspector.bundle.js"),e.Config={overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,handleResize:!0,enablePopup:!0},e}();function wh(e){var t,i=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23],r=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],n=[],o=e.width||e.size||1,a=e.height||e.size||1,s=e.depth||e.size||1,l=e.wrap||!1,c=void 0===e.topBaseAt?1:e.topBaseAt,u=void 0===e.bottomBaseAt?0:e.bottomBaseAt,h=[2,0,3,1][c=(c+4)%4],d=[2,0,1,3][u=(u+4)%4],p=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(l){i=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],p=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1];for(var f=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],_=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]],m=[17,18,19,16],g=[22,23,20,21];h>0;)f.unshift(f.pop()),m.unshift(m.pop()),h--;for(;d>0;)_.unshift(_.pop()),g.unshift(g.pop()),d--;f=f.flat(),_=_.flat(),p=p.concat(f).concat(_),i.push(m[0],m[2],m[3],m[0],m[1],m[2]),i.push(g[0],g[2],g[3],g[0],g[1],g[2])}var v=[o/2,a/2,s/2];t=p.reduce((function(e,t,i){return e.concat(t*v[i%3])}),[]);for(var y=0===e.sideOrientation?0:e.sideOrientation||_o.DEFAULTSIDE,b=e.faceUV||new Array(6),T=e.faceColors,E=[],S=0;S<6;S++)void 0===b[S]&&(b[S]=new k(0,0,1,1)),T&&void 0===T[S]&&(T[S]=new J(1,1,1,1));for(var x=0;x<6;x++)if(n.push(b[x].z,go.UseOpenGLOrientationForUV?1-b[x].w:b[x].w),n.push(b[x].x,go.UseOpenGLOrientationForUV?1-b[x].w:b[x].w),n.push(b[x].x,go.UseOpenGLOrientationForUV?1-b[x].y:b[x].y),n.push(b[x].z,go.UseOpenGLOrientationForUV?1-b[x].y:b[x].y),T)for(var A=0;A<4;A++)E.push(T[x].r,T[x].g,T[x].b,T[x].a);_o._ComputeSides(y,t,i,r,n,e.frontUVs,e.backUVs);var C=new _o;if(C.indices=i,C.positions=t,C.normals=r,C.uvs=n,T){var R=y===_o.DOUBLESIDE?E.concat(E):E;C.colors=R}return C}function Bh(e){var t=e.width||e.size||1,i=e.height||e.size||1,r=e.depth||e.size||1,n=0|(e.widthSegments||e.segments||1),o=0|(e.heightSegments||e.segments||1),a=0|(e.depthSegments||e.segments||1),s=new z,l=new z,c=new z,u=$u({width:t,height:r,subdivisionsX:n,subdivisionsY:a});z.TranslationToRef(0,-i/2,0,l),z.RotationZToRef(Math.PI,s),s.multiplyToRef(l,c),u.transform(c);var h=$u({width:t,height:r,subdivisionsX:n,subdivisionsY:a});z.TranslationToRef(0,i/2,0,c),h.transform(c);var d=$u({width:i,height:r,subdivisionsX:o,subdivisionsY:a});z.TranslationToRef(-t/2,0,0,l),z.RotationZToRef(Math.PI/2,s),s.multiplyToRef(l,c),d.transform(c);var p=$u({width:i,height:r,subdivisionsX:o,subdivisionsY:a});z.TranslationToRef(t/2,0,0,l),z.RotationZToRef(-Math.PI/2,s),s.multiplyToRef(l,c),p.transform(c);var f=$u({width:t,height:i,subdivisionsX:n,subdivisionsY:o});z.TranslationToRef(0,0,-r/2,l),z.RotationXToRef(-Math.PI/2,s),s.multiplyToRef(l,c),f.transform(c);var _=$u({width:t,height:i,subdivisionsX:n,subdivisionsY:o});return z.TranslationToRef(0,0,r/2,l),z.RotationXToRef(Math.PI/2,s),s.multiplyToRef(l,c),_.transform(c),u.merge([h,p,d,f,_],!0),u}function Uh(e,t,i){void 0===t&&(t={}),void 0===i&&(i=null);var r=new Fa(e,i);return t.sideOrientation=Fa._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,wh(t).applyToMesh(r,t.updatable),r}var Vh={CreateBox:Uh};function kh(e){for(var t=0|(e.segments||32),i=e.diameterX||e.diameter||1,r=e.diameterY||e.diameter||1,n=e.diameterZ||e.diameter||1,o=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,a=e.slice&&e.slice<=0?1:e.slice||1,s=0===e.sideOrientation?0:e.sideOrientation||_o.DEFAULTSIDE,l=!!e.dedupTopBottomIndices,c=new V(i/2,r/2,n/2),u=2+t,h=2*u,d=[],p=[],f=[],_=[],m=0;m<=u;m++){for(var g=m/u,v=g*Math.PI*a,y=0;y<=h;y++){var b=y/h,T=b*Math.PI*2*o,E=z.RotationZ(-v),S=z.RotationY(T),x=V.TransformCoordinates(V.Up(),E),A=V.TransformCoordinates(x,S),C=A.multiply(c),R=A.divide(c).normalize();p.push(C.x,C.y,C.z),f.push(R.x,R.y,R.z),_.push(b,go.UseOpenGLOrientationForUV?1-g:g)}if(m>0)for(var P=p.length/3,I=P-2*(h+1);I+h+2<P;I++)l?(m>1&&(d.push(I),d.push(I+1),d.push(I+h+1)),(m<u||a<1)&&(d.push(I+h+1),d.push(I+1),d.push(I+h+2))):(d.push(I),d.push(I+1),d.push(I+h+1),d.push(I+h+1),d.push(I+1),d.push(I+h+2))}_o._ComputeSides(s,p,d,f,_,e.frontUVs,e.backUVs);var M=new _o;return M.indices=d,M.positions=p,M.normals=f,M.uvs=_,M}function Gh(e,t,i){void 0===t&&(t={}),void 0===i&&(i=null);var r=new Fa(e,i);return t.sideOrientation=Fa._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,kh(t).applyToMesh(r,t.updatable),r}_o.CreateBox=wh,Fa.CreateBox=function(e,t,i,r,n){return void 0===i&&(i=null),Uh(e,{size:t,sideOrientation:n,updatable:r},i)};var zh={CreateSphere:Gh};function Wh(e){void 0===e&&(e={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6});var t,i,r=0|Math.max(e.subdivisions?e.subdivisions:2,1),n=0|Math.max(e.tessellation?e.tessellation:16,3),o=Math.max(e.height?e.height:1,0),a=Math.max(e.radius?e.radius:.25,0),s=0|Math.max(e.capSubdivisions?e.capSubdivisions:6,1),l=n,c=r,u=Math.max(e.radiusTop?e.radiusTop:a,0),h=Math.max(e.radiusBottom?e.radiusBottom:a,0),d=o-(u+h),p=2*Math.PI,f=Math.max(e.topCapSubdivisions?e.topCapSubdivisions:s,1),_=Math.max(e.bottomCapSubdivisions?e.bottomCapSubdivisions:s,1),m=Math.acos((h-u)/o),g=[],v=[],y=[],b=[],T=0,E=[],S=.5*d,x=.5*Math.PI,A=V.Zero(),C=V.Zero(),R=Math.cos(m),P=Math.sin(m),I=new U(u*P,S+u*R).subtract(new U(h*P,h*R-S)).length(),M=u*m+I+h*(x-m),O=0;for(i=0;i<=f;i++){var D=[],N=x-m*(i/f);O+=u*m/f;var F=Math.cos(N),L=Math.sin(N),w=F*u;for(t=0;t<=l;t++){var B=(X=t/l)*p+0,k=Math.sin(B),G=Math.cos(B);C.x=w*k,C.y=S+L*u,C.z=w*G,v.push(C.x,C.y,C.z),A.set(F*k,L,F*G),y.push(A.x,A.y,A.z),b.push(X,go.UseOpenGLOrientationForUV?O/M:1-O/M),D.push(T),T++}E.push(D)}var W=o-u-h+R*u-R*h,H=P*(h-u)/W;for(i=1;i<=c;i++){for(D=[],O+=I/c,w=P*(i*(h-u)/c+u),t=0;t<=l;t++)B=(X=t/l)*p+0,k=Math.sin(B),G=Math.cos(B),C.x=w*k,C.y=S+R*u-i*W/c,C.z=w*G,v.push(C.x,C.y,C.z),A.set(k,H,G).normalize(),y.push(A.x,A.y,A.z),b.push(X,go.UseOpenGLOrientationForUV?O/M:1-O/M),D.push(T),T++;E.push(D)}for(i=1;i<=_;i++){for(D=[],N=x-m-(Math.PI-m)*(i/_),O+=h*m/_,F=Math.cos(N),L=Math.sin(N),w=F*h,t=0;t<=l;t++){var X;B=(X=t/l)*p+0,k=Math.sin(B),G=Math.cos(B),C.x=w*k,C.y=L*h-S,C.z=w*G,v.push(C.x,C.y,C.z),A.set(F*k,L,F*G),y.push(A.x,A.y,A.z),b.push(X,go.UseOpenGLOrientationForUV?O/M:1-O/M),D.push(T),T++}E.push(D)}for(t=0;t<l;t++)for(i=0;i<f+c+_;i++){var j=E[i][t],Y=E[i+1][t],K=E[i+1][t+1],Q=E[i][t+1];g.push(j),g.push(Y),g.push(Q),g.push(Y),g.push(K),g.push(Q)}if(g=g.reverse(),e.orientation&&!e.orientation.equals(V.Up())){var q=new z;e.orientation.clone().scale(.5*Math.PI).cross(V.Up()).toQuaternion().toRotationMatrix(q);for(var Z=V.Zero(),J=0;J<v.length;J+=3)Z.set(v[J],v[J+1],v[J+2]),V.TransformCoordinatesToRef(Z.clone(),q,Z),v[J]=Z.x,v[J+1]=Z.y,v[J+2]=Z.z}var $=new _o;return $.positions=v,$.normals=y,$.uvs=b,$.indices=g,$}function Hh(e,t,i){void 0===t&&(t={orientation:V.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6,updatable:!1}),void 0===i&&(i=null);var r=new Fa(e,i);return Wh(t).applyToMesh(r,t.updatable),r}_o.CreateSphere=kh,Fa.CreateSphere=function(e,t,i,r,n,o){return Gh(e,{segments:t,diameterX:i,diameterY:i,diameterZ:i,sideOrientation:o,updatable:n},r)};var Xh={CreateCapsule:Hh};function jh(e){var t=e.pathArray,i=e.closeArray||!1,r=e.closePath||!1,n=e.invertUV||!1,o=Math.floor(t[0].length/2),a=e.offset||o;a=a>o?o:Math.floor(a);var s,l,c,u,h=0===e.sideOrientation?0:e.sideOrientation||_o.DEFAULTSIDE,d=e.uvs,p=e.colors,f=[],_=[],m=[],g=[],v=[],y=[],b=[],T=[],E=[],S=[];if(t.length<2){var x=[],A=[];for(c=0;c<t[0].length-a;c++)x.push(t[0][c]),A.push(t[0][c+a]);t=[x,A]}var C,R,P,I,M,O=0,D=r?1:0,N=i?1:0;for(s=t[0].length,l=0;l<t.length+N;l++){for(b[l]=0,v[l]=[0],s=s<(R=(C=l===t.length?t[0]:t[l]).length)?s:R,u=0;u<R;)f.push(C[u].x,C[u].y,C[u].z),u>0&&(P=C[u].subtract(C[u-1]).length()+b[l],v[l].push(P),b[l]=P),u++;r&&(u--,f.push(C[0].x,C[0].y,C[0].z),P=C[u].subtract(C[0]).length()+b[l],v[l].push(P),b[l]=P),E[l]=R+D,S[l]=O,O+=R+D}var F,L,w=null,B=null;for(c=0;c<s+D;c++)for(T[c]=0,y[c]=[0],l=0;l<t.length-1+N;l++)I=t[l],M=l===t.length-1?t[0]:t[l+1],c===s?(w=I[0],B=M[0]):(w=I[c],B=M[c]),P=B.subtract(w).length()+T[c],y[c].push(P),T[c]=P;if(d)for(l=0;l<d.length;l++)g.push(d[l].x,go.UseOpenGLOrientationForUV?1-d[l].y:d[l].y);else for(l=0;l<t.length+N;l++)for(c=0;c<s+D;c++)F=0!=b[l]?v[l][c]/b[l]:0,L=0!=T[c]?y[c][l]/T[c]:0,n?g.push(L,F):g.push(F,go.UseOpenGLOrientationForUV?1-L:L);for(var U=0,V=E[l=0]-1,k=E[l+1]-1,G=V<k?V:k,z=S[1]-S[0],W=E.length-1;U<=G&&l<W;)_.push(U,U+z,U+1),_.push(U+z+1,U+1,U+z),(U+=1)===G&&(z=S[1+ ++l]-S[l],V=E[l]-1,k=E[l+1]-1,U=S[l],G=V<k?V+U:k+U);if(_o.ComputeNormals(f,_,m),r){var H=0,X=0;for(l=0;l<t.length;l++){H=3*S[l],X=l+1<t.length?3*(S[l+1]-1):m.length-3,m[H]=.5*(m[H]+m[X]),m[H+1]=.5*(m[H+1]+m[X+1]),m[H+2]=.5*(m[H+2]+m[X+2]);var j=Math.sqrt(m[H]*m[H]+m[H+1]*m[H+1]+m[H+2]*m[H+2]);m[H]/=j,m[H+1]/=j,m[H+2]/=j,m[X]=m[H],m[X+1]=m[H+1],m[X+2]=m[H+2]}}if(i)for(H=3*S[0],X=3*S[t.length],c=0;c<s+D;c++){m[H]=.5*(m[H]+m[X]),m[H+1]=.5*(m[H+1]+m[X+1]),m[H+2]=.5*(m[H+2]+m[X+2]);var Y=Math.sqrt(m[H]*m[H]+m[H+1]*m[H+1]+m[H+2]*m[H+2]);m[H]/=Y,m[H+1]/=Y,m[H+2]/=Y,m[X]=m[H],m[X+1]=m[H+1],m[X+2]=m[H+2],H+=3,X+=3}_o._ComputeSides(h,f,_,m,g,e.frontUVs,e.backUVs);var K=null;if(p){K=new Float32Array(4*p.length);for(var Q=0;Q<p.length;Q++)K[4*Q]=p[Q].r,K[4*Q+1]=p[Q].g,K[4*Q+2]=p[Q].b,K[4*Q+3]=p[Q].a}var q=new _o,Z=new Float32Array(f),J=new Float32Array(m),$=new Float32Array(g);return q.indices=_,q.positions=Z,q.normals=J,q.uvs=$,K&&q.set(K,Nr.ColorKind),r&&(q._idx=S),q}function Yh(e,t,i){void 0===i&&(i=null);var r=t.pathArray,n=t.closeArray,o=t.closePath,a=Fa._GetDefaultSideOrientation(t.sideOrientation),s=t.instance,l=t.updatable;if(s){var c=H.Vector3[0].setAll(Number.MAX_VALUE),u=H.Vector3[1].setAll(-Number.MAX_VALUE),h=s.getVerticesData(Nr.PositionKind);if(function(e){for(var t=r[0].length,i=s,n=0,o=i._originalBuilderSideOrientation===Fa.DOUBLESIDE?2:1,a=1;a<=o;++a)for(var l=0;l<r.length;++l){var h=r[l],d=h.length;t=t<d?t:d;for(var p=0;p<t;++p){var f=h[p];e[n]=f.x,e[n+1]=f.y,e[n+2]=f.z,c.minimizeInPlaceFromFloats(f.x,f.y,f.z),u.maximizeInPlaceFromFloats(f.x,f.y,f.z),n+=3}i._creationDataStorage&&i._creationDataStorage.closePath&&(f=h[0],e[n]=f.x,e[n+1]=f.y,e[n+2]=f.z,n+=3)}}(h),s.hasBoundingInfo?s.getBoundingInfo().reConstruct(c,u,s._worldMatrix):s.buildBoundingInfo(c,u,s._worldMatrix),s.updateVerticesData(Nr.PositionKind,h,!1,!1),t.colors){for(var d=s.getVerticesData(Nr.ColorKind),p=0,f=0;p<t.colors.length;p++,f+=4){var _=t.colors[p];d[f]=_.r,d[f+1]=_.g,d[f+2]=_.b,d[f+3]=_.a}s.updateVerticesData(Nr.ColorKind,d,!1,!1)}if(t.uvs){for(var m=s.getVerticesData(Nr.UVKind),g=0;g<t.uvs.length;g++)m[2*g]=t.uvs[g].x,m[2*g+1]=go.UseOpenGLOrientationForUV?1-t.uvs[g].y:t.uvs[g].y;s.updateVerticesData(Nr.UVKind,m,!1,!1)}if(!s.areNormalsFrozen||s.isFacetDataEnabled){var v=s.getIndices(),y=s.getVerticesData(Nr.NormalKind),b=s.isFacetDataEnabled?s.getFacetDataParameters():null;if(_o.ComputeNormals(h,v,y,b),s._creationDataStorage&&s._creationDataStorage.closePath)for(var T=0,E=0,S=0;S<r.length;S++)T=3*s._creationDataStorage.idx[S],E=S+1<r.length?3*(s._creationDataStorage.idx[S+1]-1):y.length-3,y[T]=.5*(y[T]+y[E]),y[T+1]=.5*(y[T+1]+y[E+1]),y[T+2]=.5*(y[T+2]+y[E+2]),y[E]=y[T],y[E+1]=y[T+1],y[E+2]=y[T+2];s.areNormalsFrozen||s.updateVerticesData(Nr.NormalKind,y,!1,!1)}return s}var x=new Fa(e,i);x._originalBuilderSideOrientation=a,x._creationDataStorage=new Ia;var A=jh(t);return o&&(x._creationDataStorage.idx=A._idx),x._creationDataStorage.closePath=o,x._creationDataStorage.closeArray=n,A.applyToMesh(x,l),x}Fa.CreateCapsule=function(e,t,i){return Hh(e,t,i)},_o.CreateCapsule=Wh;var Kh={CreateRibbon:Yh};function Qh(e){var t=[],i=[],r=[],n=[],o=e.radius||.5,a=e.tessellation||64,s=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,l=0===e.sideOrientation?0:e.sideOrientation||_o.DEFAULTSIDE;t.push(0,0,0),n.push(.5,.5);for(var c=2*Math.PI*s,u=1===s?c/a:c/(a-1),h=0,d=0;d<a;d++){var p=Math.cos(h),f=Math.sin(h),_=(p+1)/2,m=(1-f)/2;t.push(o*p,o*f,0),n.push(_,go.UseOpenGLOrientationForUV?1-m:m),h+=u}1===s&&(t.push(t[3],t[4],t[5]),n.push(n[2],go.UseOpenGLOrientationForUV?1-n[3]:n[3]));for(var g=t.length/3,v=1;v<g-1;v++)i.push(v+1,0,v);_o.ComputeNormals(t,i,r),_o._ComputeSides(l,t,i,r,n,e.frontUVs,e.backUVs);var y=new _o;return y.indices=i,y.positions=t,y.normals=r,y.uvs=n,y}function qh(e,t,i){void 0===t&&(t={}),void 0===i&&(i=null);var r=new Fa(e,i);return t.sideOrientation=Fa._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,Qh(t).applyToMesh(r,t.updatable),r}_o.CreateRibbon=jh,Fa.CreateRibbon=function(e,t,i,r,n,o,a,s,l){return void 0===i&&(i=!1),void 0===a&&(a=!1),Yh(e,{pathArray:t,closeArray:i,closePath:r,offset:n,updatable:a,sideOrientation:s,instance:l},o)};var Zh={CreateDisc:qh};function Jh(e){var t=e.pattern||Fa.NO_FLIP,i=e.tileWidth||e.tileSize||1,r=e.tileHeight||e.tileSize||1,n=e.alignHorizontal||0,o=e.alignVertical||0,a=e.width||e.size||1,s=Math.floor(a/i),l=a-s*i,c=e.height||e.size||1,u=Math.floor(c/r),h=c-u*r,d=i*s/2,p=r*u/2,f=0,_=0,m=0,g=0,v=0,y=0;if(l>0||h>0){switch(m=-d,g=-p,v=d,y=p,n){case Fa.CENTER:m-=l/=2,v+=l;break;case Fa.LEFT:v+=l,f=-l/2;break;case Fa.RIGHT:m-=l,f=l/2}switch(o){case Fa.CENTER:g-=h/=2,y+=h;break;case Fa.BOTTOM:y+=h,_=-h/2;break;case Fa.TOP:g-=h,_=h/2}}var b=[],T=[],E=[];E[0]=[0,0,1,0,1,1,0,1],E[1]=[0,0,1,0,1,1,0,1],t!==Fa.ROTATE_TILE&&t!==Fa.ROTATE_ROW||(E[1]=[1,1,0,1,0,0,1,0]),t!==Fa.FLIP_TILE&&t!==Fa.FLIP_ROW||(E[1]=[1,0,0,0,0,1,1,1]),t!==Fa.FLIP_N_ROTATE_TILE&&t!==Fa.FLIP_N_ROTATE_ROW||(E[1]=[0,1,1,1,1,0,0,0]);for(var S=[],x=[],A=[],C=0,R=0;R<u;R++)for(var P=0;P<s;P++)b.push(P*i-d+f,R*r-p+_,0),b.push((P+1)*i-d+f,R*r-p+_,0),b.push((P+1)*i-d+f,(R+1)*r-p+_,0),b.push(P*i-d+f,(R+1)*r-p+_,0),A.push(C,C+1,C+3,C+1,C+2,C+3),S=t===Fa.FLIP_TILE||t===Fa.ROTATE_TILE||t===Fa.FLIP_N_ROTATE_TILE?S.concat(E[(P%2+R%2)%2]):t===Fa.FLIP_ROW||t===Fa.ROTATE_ROW||t===Fa.FLIP_N_ROTATE_ROW?S.concat(E[R%2]):S.concat(E[0]),x.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1),C+=4;if(l>0||h>0){var I=h>0&&(o===Fa.CENTER||o===Fa.TOP),M=h>0&&(o===Fa.CENTER||o===Fa.BOTTOM),O=l>0&&(n===Fa.CENTER||n===Fa.RIGHT),D=l>0&&(n===Fa.CENTER||n===Fa.LEFT),N=[],F=void 0,L=void 0,w=void 0,B=void 0;if(I&&O&&(b.push(m+f,g+_,0),b.push(-d+f,g+_,0),b.push(-d+f,g+h+_,0),b.push(m+f,g+h+_,0),A.push(C,C+1,C+3,C+1,C+2,C+3),C+=4,N=[F=1-l/i,L=1-h/r,w=1,L,w,B=1,F,B],t===Fa.ROTATE_ROW&&(N=[1-F,1-L,1-w,1-L,1-w,1-B,1-F,1-B]),t===Fa.FLIP_ROW&&(N=[1-F,L,1-w,L,1-w,B,1-F,B]),t===Fa.FLIP_N_ROTATE_ROW&&(N=[F,1-L,w,1-L,w,1-B,F,1-B]),S=S.concat(N),x.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),I&&D&&(b.push(d+f,g+_,0),b.push(v+f,g+_,0),b.push(v+f,g+h+_,0),b.push(d+f,g+h+_,0),A.push(C,C+1,C+3,C+1,C+2,C+3),C+=4,N=[F=0,L=1-h/r,w=l/i,L,w,B=1,F,B],(t===Fa.ROTATE_ROW||t===Fa.ROTATE_TILE&&s%2==0)&&(N=[1-F,1-L,1-w,1-L,1-w,1-B,1-F,1-B]),(t===Fa.FLIP_ROW||t===Fa.FLIP_TILE&&s%2==0)&&(N=[1-F,L,1-w,L,1-w,B,1-F,B]),(t===Fa.FLIP_N_ROTATE_ROW||t===Fa.FLIP_N_ROTATE_TILE&&s%2==0)&&(N=[F,1-L,w,1-L,w,1-B,F,1-B]),S=S.concat(N),x.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),M&&O&&(b.push(m+f,p+_,0),b.push(-d+f,p+_,0),b.push(-d+f,y+_,0),b.push(m+f,y+_,0),A.push(C,C+1,C+3,C+1,C+2,C+3),C+=4,N=[F=1-l/i,L=0,w=1,L,w,B=h/r,F,B],(t===Fa.ROTATE_ROW&&u%2==1||t===Fa.ROTATE_TILE&&u%1==0)&&(N=[1-F,1-L,1-w,1-L,1-w,1-B,1-F,1-B]),(t===Fa.FLIP_ROW&&u%2==1||t===Fa.FLIP_TILE&&u%2==0)&&(N=[1-F,L,1-w,L,1-w,B,1-F,B]),(t===Fa.FLIP_N_ROTATE_ROW&&u%2==1||t===Fa.FLIP_N_ROTATE_TILE&&u%2==0)&&(N=[F,1-L,w,1-L,w,1-B,F,1-B]),S=S.concat(N),x.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),M&&D&&(b.push(d+f,p+_,0),b.push(v+f,p+_,0),b.push(v+f,y+_,0),b.push(d+f,y+_,0),A.push(C,C+1,C+3,C+1,C+2,C+3),C+=4,N=[F=0,L=0,w=l/i,L,w,B=h/r,F,B],(t===Fa.ROTATE_ROW&&u%2==1||t===Fa.ROTATE_TILE&&(u+s)%2==1)&&(N=[1-F,1-L,1-w,1-L,1-w,1-B,1-F,1-B]),(t===Fa.FLIP_ROW&&u%2==1||t===Fa.FLIP_TILE&&(u+s)%2==1)&&(N=[1-F,L,1-w,L,1-w,B,1-F,B]),(t===Fa.FLIP_N_ROTATE_ROW&&u%2==1||t===Fa.FLIP_N_ROTATE_TILE&&(u+s)%2==1)&&(N=[F,1-L,w,1-L,w,1-B,F,1-B]),S=S.concat(N),x.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),I){var U=[];for(F=0,L=1-h/r,w=1,B=1,U[0]=[F,L,w,L,w,B,F,B],U[1]=[F,L,w,L,w,B,F,B],t!==Fa.ROTATE_TILE&&t!==Fa.ROTATE_ROW||(U[1]=[1-F,1-L,1-w,1-L,1-w,1-B,1-F,1-B]),t!==Fa.FLIP_TILE&&t!==Fa.FLIP_ROW||(U[1]=[1-F,L,1-w,L,1-w,B,1-F,B]),t!==Fa.FLIP_N_ROTATE_TILE&&t!==Fa.FLIP_N_ROTATE_ROW||(U[1]=[F,1-L,w,1-L,w,1-B,F,1-B]),P=0;P<s;P++)b.push(P*i-d+f,g+_,0),b.push((P+1)*i-d+f,g+_,0),b.push((P+1)*i-d+f,g+h+_,0),b.push(P*i-d+f,g+h+_,0),A.push(C,C+1,C+3,C+1,C+2,C+3),C+=4,S=t===Fa.FLIP_TILE||t===Fa.ROTATE_TILE||t===Fa.FLIP_N_ROTATE_TILE?S.concat(U[(P+1)%2]):t===Fa.FLIP_ROW||t===Fa.ROTATE_ROW||t===Fa.FLIP_N_ROTATE_ROW?S.concat(U[1]):S.concat(U[0]),x.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(M){var V=[];for(F=0,L=0,w=1,B=h/r,V[0]=[F,L,w,L,w,B,F,B],V[1]=[F,L,w,L,w,B,F,B],t!==Fa.ROTATE_TILE&&t!==Fa.ROTATE_ROW||(V[1]=[1-F,1-L,1-w,1-L,1-w,1-B,1-F,1-B]),t!==Fa.FLIP_TILE&&t!==Fa.FLIP_ROW||(V[1]=[1-F,L,1-w,L,1-w,B,1-F,B]),t!==Fa.FLIP_N_ROTATE_TILE&&t!==Fa.FLIP_N_ROTATE_ROW||(V[1]=[F,1-L,w,1-L,w,1-B,F,1-B]),P=0;P<s;P++)b.push(P*i-d+f,y-h+_,0),b.push((P+1)*i-d+f,y-h+_,0),b.push((P+1)*i-d+f,y+_,0),b.push(P*i-d+f,y+_,0),A.push(C,C+1,C+3,C+1,C+2,C+3),C+=4,S=t===Fa.FLIP_TILE||t===Fa.ROTATE_TILE||t===Fa.FLIP_N_ROTATE_TILE?S.concat(V[(P+u)%2]):t===Fa.FLIP_ROW||t===Fa.ROTATE_ROW||t===Fa.FLIP_N_ROTATE_ROW?S.concat(V[u%2]):S.concat(V[0]),x.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(O){var k=[];for(F=1-l/i,L=0,w=1,B=1,k[0]=[F,L,w,L,w,B,F,B],k[1]=[F,L,w,L,w,B,F,B],t!==Fa.ROTATE_TILE&&t!==Fa.ROTATE_ROW||(k[1]=[1-F,1-L,1-w,1-L,1-w,1-B,1-F,1-B]),t!==Fa.FLIP_TILE&&t!==Fa.FLIP_ROW||(k[1]=[1-F,L,1-w,L,1-w,B,1-F,B]),t!==Fa.FLIP_N_ROTATE_TILE&&t!==Fa.FLIP_N_ROTATE_ROW||(k[1]=[F,1-L,w,1-L,w,1-B,F,1-B]),R=0;R<u;R++)b.push(m+f,R*r-p+_,0),b.push(m+l+f,R*r-p+_,0),b.push(m+l+f,(R+1)*r-p+_,0),b.push(m+f,(R+1)*r-p+_,0),A.push(C,C+1,C+3,C+1,C+2,C+3),C+=4,S=t===Fa.FLIP_TILE||t===Fa.ROTATE_TILE||t===Fa.FLIP_N_ROTATE_TILE?S.concat(k[(R+1)%2]):t===Fa.FLIP_ROW||t===Fa.ROTATE_ROW||t===Fa.FLIP_N_ROTATE_ROW?S.concat(k[R%2]):S.concat(k[0]),x.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(D){var G=[];for(F=0,L=0,w=l/r,B=1,G[0]=[F,L,w,L,w,B,F,B],G[1]=[F,L,w,L,w,B,F,B],t!==Fa.ROTATE_TILE&&t!==Fa.ROTATE_ROW||(G[1]=[1-F,1-L,1-w,1-L,1-w,1-B,1-F,1-B]),t!==Fa.FLIP_TILE&&t!==Fa.FLIP_ROW||(G[1]=[1-F,L,1-w,L,1-w,B,1-F,B]),t!==Fa.FLIP_N_ROTATE_TILE&&t!==Fa.FLIP_N_ROTATE_ROW||(G[1]=[F,1-L,w,1-L,w,1-B,F,1-B]),R=0;R<u;R++)b.push(v-l+f,R*r-p+_,0),b.push(v+f,R*r-p+_,0),b.push(v+f,(R+1)*r-p+_,0),b.push(v-l+f,(R+1)*r-p+_,0),A.push(C,C+1,C+3,C+1,C+2,C+3),C+=4,S=t===Fa.FLIP_TILE||t===Fa.ROTATE_TILE||t===Fa.FLIP_N_ROTATE_TILE?S.concat(G[(R+s)%2]):t===Fa.FLIP_ROW||t===Fa.ROTATE_ROW||t===Fa.FLIP_N_ROTATE_ROW?S.concat(G[R%2]):S.concat(G[0]),x.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}}var z=0===e.sideOrientation?0:e.sideOrientation||_o.DEFAULTSIDE;_o._ComputeSides(z,b,A,T,S,e.frontUVs,e.backUVs);var W=new _o;W.indices=A,W.positions=b,W.normals=T,W.uvs=S;var H=z===_o.DOUBLESIDE?x.concat(x):x;return W.colors=H,W}function $h(e,t,i){void 0===i&&(i=null);var r=new Fa(e,i);return t.sideOrientation=Fa._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,Jh(t).applyToMesh(r,t.updatable),r}_o.CreateDisc=Qh,Fa.CreateDisc=function(e,t,i,r,n,o){return void 0===r&&(r=null),qh(e,{radius:t,tessellation:i,sideOrientation:o,updatable:n},r)};var ed={CreateTiledPlane:$h};function td(e){for(var t=e.faceUV||new Array(6),i=e.faceColors,r=e.pattern||Fa.NO_FLIP,n=e.width||e.size||1,o=e.height||e.size||1,a=e.depth||e.size||1,s=e.tileWidth||e.tileSize||1,l=e.tileHeight||e.tileSize||1,c=e.alignHorizontal||0,u=e.alignVertical||0,h=0===e.sideOrientation?0:e.sideOrientation||_o.DEFAULTSIDE,d=0;d<6;d++)void 0===t[d]&&(t[d]=new k(0,0,1,1)),i&&void 0===i[d]&&(i[d]=new J(1,1,1,1));var p=n/2,f=o/2,_=a/2,m=[];for(d=0;d<2;d++)m[d]=Jh({pattern:r,tileWidth:s,tileHeight:l,width:n,height:o,alignVertical:u,alignHorizontal:c,sideOrientation:h});for(d=2;d<4;d++)m[d]=Jh({pattern:r,tileWidth:s,tileHeight:l,width:a,height:o,alignVertical:u,alignHorizontal:c,sideOrientation:h});var g=u;for(u===Fa.BOTTOM?g=Fa.TOP:u===Fa.TOP&&(g=Fa.BOTTOM),d=4;d<6;d++)m[d]=Jh({pattern:r,tileWidth:s,tileHeight:l,width:n,height:a,alignVertical:g,alignHorizontal:c,sideOrientation:h});var v=[],y=[],b=[],T=[],E=[],S=[],x=[],A=[],C=0,R=0;for(d=0;d<6;d++){var P=m[d].positions.length;S[d]=[],x[d]=[];for(var I=0;I<P/3;I++)S[d].push(new V(m[d].positions[3*I],m[d].positions[3*I+1],m[d].positions[3*I+2])),x[d].push(new V(m[d].normals[3*I],m[d].normals[3*I+1],m[d].normals[3*I+2]));C=m[d].uvs.length,A[d]=[];for(var M=0;M<C;M+=2)A[d][M]=t[d].x+(t[d].z-t[d].x)*m[d].uvs[M],A[d][M+1]=t[d].y+(t[d].w-t[d].y)*m[d].uvs[M+1],go.UseOpenGLOrientationForUV&&(A[d][M+1]=1-A[d][M+1]);if(b=b.concat(A[d]),T=T.concat(m[d].indices.map((function(e){return e+R}))),R+=S[d].length,i)for(var O=0;O<4;O++)E.push(i[d].r,i[d].g,i[d].b,i[d].a)}var D=new V(0,0,_),N=z.RotationY(Math.PI);v=S[0].map((function(e){return V.TransformNormal(e,N).add(D)})).map((function(e){return[e.x,e.y,e.z]})).reduce((function(e,t){return e.concat(t)}),[]),y=x[0].map((function(e){return V.TransformNormal(e,N)})).map((function(e){return[e.x,e.y,e.z]})).reduce((function(e,t){return e.concat(t)}),[]),v=v.concat(S[1].map((function(e){return e.subtract(D)})).map((function(e){return[e.x,e.y,e.z]})).reduce((function(e,t){return e.concat(t)}),[])),y=y.concat(x[1].map((function(e){return[e.x,e.y,e.z]})).reduce((function(e,t){return e.concat(t)}),[]));var F=new V(p,0,0),L=z.RotationY(-Math.PI/2);v=v.concat(S[2].map((function(e){return V.TransformNormal(e,L).add(F)})).map((function(e){return[e.x,e.y,e.z]})).reduce((function(e,t){return e.concat(t)}),[])),y=y.concat(x[2].map((function(e){return V.TransformNormal(e,L)})).map((function(e){return[e.x,e.y,e.z]})).reduce((function(e,t){return e.concat(t)}),[]));var w=z.RotationY(Math.PI/2);v=v.concat(S[3].map((function(e){return V.TransformNormal(e,w).subtract(F)})).map((function(e){return[e.x,e.y,e.z]})).reduce((function(e,t){return e.concat(t)}),[])),y=y.concat(x[3].map((function(e){return V.TransformNormal(e,w)})).map((function(e){return[e.x,e.y,e.z]})).reduce((function(e,t){return e.concat(t)}),[]));var B=new V(0,f,0),U=z.RotationX(Math.PI/2);v=v.concat(S[4].map((function(e){return V.TransformNormal(e,U).add(B)})).map((function(e){return[e.x,e.y,e.z]})).reduce((function(e,t){return e.concat(t)}),[])),y=y.concat(x[4].map((function(e){return V.TransformNormal(e,U)})).map((function(e){return[e.x,e.y,e.z]})).reduce((function(e,t){return e.concat(t)}),[]));var G=z.RotationX(-Math.PI/2);v=v.concat(S[5].map((function(e){return V.TransformNormal(e,G).subtract(B)})).map((function(e){return[e.x,e.y,e.z]})).reduce((function(e,t){return e.concat(t)}),[])),y=y.concat(x[5].map((function(e){return V.TransformNormal(e,G)})).map((function(e){return[e.x,e.y,e.z]})).reduce((function(e,t){return e.concat(t)}),[])),_o._ComputeSides(h,v,T,y,b);var W=new _o;if(W.indices=T,W.positions=v,W.normals=y,W.uvs=b,i){var H=h===_o.DOUBLESIDE?E.concat(E):E;W.colors=H}return W}function id(e,t,i){void 0===i&&(i=null);var r=new Fa(e,i);return t.sideOrientation=Fa._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,td(t).applyToMesh(r,t.updatable),r}_o.CreateTiledPlane=Jh;var rd={CreateTiledBox:id};function nd(e){var t,i,r=[],n=[],o=[],a=[],s=e.radius||2,l=e.tube||.5,c=e.radialSegments||32,u=e.tubularSegments||32,h=e.p||2,d=e.q||3,p=0===e.sideOrientation?0:e.sideOrientation||_o.DEFAULTSIDE,f=function(e){var t=Math.cos(e),i=Math.sin(e),r=d/h*e,n=Math.cos(r),o=s*(2+n)*.5*t,a=s*(2+n)*i*.5,l=s*Math.sin(r)*.5;return new V(o,a,l)};for(t=0;t<=c;t++){var _=t%c/c*2*h*Math.PI,m=f(_),g=f(_+.01),v=g.subtract(m),y=g.add(m),b=V.Cross(v,y);for(y=V.Cross(b,v),b.normalize(),y.normalize(),i=0;i<u;i++){var T=i%u/u*2*Math.PI,E=-l*Math.cos(T),S=l*Math.sin(T);n.push(m.x+E*y.x+S*b.x),n.push(m.y+E*y.y+S*b.y),n.push(m.z+E*y.z+S*b.z),a.push(t/c),a.push(go.UseOpenGLOrientationForUV?1-i/u:i/u)}}for(t=0;t<c;t++)for(i=0;i<u;i++){var x=(i+1)%u,A=t*u+i,C=(t+1)*u+i,R=(t+1)*u+x,P=t*u+x;r.push(P),r.push(C),r.push(A),r.push(P),r.push(R),r.push(C)}_o.ComputeNormals(n,r,o),_o._ComputeSides(p,n,r,o,a,e.frontUVs,e.backUVs);var I=new _o;return I.indices=r,I.positions=n,I.normals=o,I.uvs=a,I}function od(e,t,i){void 0===t&&(t={});var r=new Fa(e,i);return t.sideOrientation=Fa._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,nd(t).applyToMesh(r,t.updatable),r}_o.CreateTiledBox=td;var ad={CreateTorusKnot:od};_o.CreateTorusKnot=nd,Fa.CreateTorusKnot=function(e,t,i,r,n,o,a,s,l,c){return od(e,{radius:t,tube:i,radialSegments:r,tubularSegments:n,p:o,q:a,sideOrientation:c,updatable:l},s)};var sd={effect:null,subMesh:null},ld=function(e){function t(t,i,r,n,o){void 0===n&&(n={}),void 0===o&&(o=!0);var a=e.call(this,t,i,o)||this;return a._textures={},a._textureArrays={},a._externalTextures={},a._floats={},a._ints={},a._uints={},a._floatsArrays={},a._colors3={},a._colors3Arrays={},a._colors4={},a._colors4Arrays={},a._vectors2={},a._vectors3={},a._vectors4={},a._quaternions={},a._quaternionsArrays={},a._matrices={},a._matrixArrays={},a._matrices3x3={},a._matrices2x2={},a._vectors2Arrays={},a._vectors3Arrays={},a._vectors4Arrays={},a._uniformBuffers={},a._textureSamplers={},a._storageBuffers={},a._cachedWorldViewMatrix=new z,a._cachedWorldViewProjectionMatrix=new z,a._multiview=!1,a._materialHelperNeedsPreviousMatrices=!1,a._shaderPath=r,a._options=g({needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1},n),a}return m(t,e),Object.defineProperty(t.prototype,"shaderPath",{get:function(){return this._shaderPath},set:function(e){this._shaderPath=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isMultiview",{get:function(){return this._multiview},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"ShaderMaterial"},t.prototype.needAlphaBlending=function(){return this.alpha<1||this._options.needAlphaBlending},t.prototype.needAlphaTesting=function(){return this._options.needAlphaTesting},t.prototype._checkUniform=function(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)},t.prototype.setTexture=function(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this},t.prototype.setTextureArray=function(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this},t.prototype.setExternalTexture=function(e,t){return-1===this._options.externalTextures.indexOf(e)&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this},t.prototype.setFloat=function(e,t){return this._checkUniform(e),this._floats[e]=t,this},t.prototype.setInt=function(e,t){return this._checkUniform(e),this._ints[e]=t,this},t.prototype.setUInt=function(e,t){return this._checkUniform(e),this._uints[e]=t,this},t.prototype.setFloats=function(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this},t.prototype.setColor3=function(e,t){return this._checkUniform(e),this._colors3[e]=t,this},t.prototype.setColor3Array=function(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce((function(e,t){return t.toArray(e,e.length),e}),[]),this},t.prototype.setColor4=function(e,t){return this._checkUniform(e),this._colors4[e]=t,this},t.prototype.setColor4Array=function(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce((function(e,t){return t.toArray(e,e.length),e}),[]),this},t.prototype.setVector2=function(e,t){return this._checkUniform(e),this._vectors2[e]=t,this},t.prototype.setVector3=function(e,t){return this._checkUniform(e),this._vectors3[e]=t,this},t.prototype.setVector4=function(e,t){return this._checkUniform(e),this._vectors4[e]=t,this},t.prototype.setQuaternion=function(e,t){return this._checkUniform(e),this._quaternions[e]=t,this},t.prototype.setQuaternionArray=function(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce((function(e,t){return t.toArray(e,e.length),e}),[]),this},t.prototype.setMatrix=function(e,t){return this._checkUniform(e),this._matrices[e]=t,this},t.prototype.setMatrices=function(e,t){this._checkUniform(e);for(var i=new Float32Array(16*t.length),r=0;r<t.length;r++)t[r].copyToArray(i,16*r);return this._matrixArrays[e]=i,this},t.prototype.setMatrix3x3=function(e,t){return this._checkUniform(e),this._matrices3x3[e]=t,this},t.prototype.setMatrix2x2=function(e,t){return this._checkUniform(e),this._matrices2x2[e]=t,this},t.prototype.setArray2=function(e,t){return this._checkUniform(e),this._vectors2Arrays[e]=t,this},t.prototype.setArray3=function(e,t){return this._checkUniform(e),this._vectors3Arrays[e]=t,this},t.prototype.setArray4=function(e,t){return this._checkUniform(e),this._vectors4Arrays[e]=t,this},t.prototype.setUniformBuffer=function(e,t){return-1===this._options.uniformBuffers.indexOf(e)&&this._options.uniformBuffers.push(e),this._uniformBuffers[e]=t,this},t.prototype.setTextureSampler=function(e,t){return-1===this._options.samplerObjects.indexOf(e)&&this._options.samplerObjects.push(e),this._textureSamplers[e]=t,this},t.prototype.setStorageBuffer=function(e,t){return-1===this._options.storageBuffers.indexOf(e)&&this._options.storageBuffers.push(e),this._storageBuffers[e]=t,this},t.prototype.setDefine=function(e,t){var i=e.trimEnd()+" ",r=this.options.defines.findIndex((function(t){return t===e||t.startsWith(i)}));return r>=0&&this.options.defines.splice(r,1),("boolean"!=typeof t||t)&&this.options.defines.push(i+t),this},t.prototype.isReadyForSubMesh=function(e,t,i){return this.isReady(e,i,t)},t.prototype.isReady=function(e,t,i){var r,n,o,a,s=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){var l=s?i._drawWrapper:this._drawWrapper;if(l.effect&&l._wasPreviouslyReady&&l._wasPreviouslyUsingInstances===t)return!0}var c=this.getScene(),u=c.getEngine(),h=[],d=[],p=new ll,f=this._shaderPath,_=this._options.uniforms,m=this._options.uniformBuffers,g=this._options.samplers;u.getCaps().multiview&&c.activeCamera&&c.activeCamera.outputRenderTarget&&c.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,h.push("#define MULTIVIEW"),-1!==_.indexOf("viewProjection")&&-1===_.indexOf("viewProjectionR")&&_.push("viewProjectionR"));for(var v=0;v<this._options.defines.length;v++){var y=0===this._options.defines[v].indexOf("#define")?this._options.defines[v]:"#define ".concat(this._options.defines[v]);h.push(y)}for(v=0;v<this._options.attributes.length;v++)d.push(this._options.attributes[v]);if(e&&e.isVerticesDataPresent(Nr.ColorKind)&&(-1===d.indexOf(Nr.ColorKind)&&d.push(Nr.ColorKind),h.push("#define VERTEXCOLOR")),t&&(h.push("#define INSTANCES"),Jo(d,this._materialHelperNeedsPreviousMatrices),(null==e?void 0:e.hasThinInstances)&&(h.push("#define THIN_INSTANCES"),e&&e.isVerticesDataPresent(Nr.ColorInstanceKind)&&(d.push(Nr.ColorInstanceKind),h.push("#define INSTANCESCOLOR")))),e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton){d.push(Nr.MatricesIndicesKind),d.push(Nr.MatricesWeightsKind),e.numBoneInfluencers>4&&(d.push(Nr.MatricesIndicesExtraKind),d.push(Nr.MatricesWeightsExtraKind));var b=e.skeleton;h.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),p.addCPUSkinningFallback(0,e),b.isUsingTextureForMatrices?(h.push("#define BONETEXTURE"),-1===_.indexOf("boneTextureWidth")&&_.push("boneTextureWidth"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(h.push("#define BonesPerMesh "+(b.bones.length+1)),-1===_.indexOf("mBones")&&_.push("mBones"))}else h.push("#define NUM_BONE_INFLUENCERS 0");var T=0,E=e?e.morphTargetManager:null;if(E){var S=E.supportsUVs&&-1!==h.indexOf("#define UV1"),x=E.supportsTangents&&-1!==h.indexOf("#define TANGENT"),A=E.supportsNormals&&-1!==h.indexOf("#define NORMAL");for(T=E.numMaxInfluencers||E.numInfluencers,S&&h.push("#define MORPHTARGETS_UV"),x&&h.push("#define MORPHTARGETS_TANGENT"),A&&h.push("#define MORPHTARGETS_NORMAL"),T>0&&h.push("#define MORPHTARGETS"),E.isUsingTextureForTargets&&(h.push("#define MORPHTARGETS_TEXTURE"),-1===_.indexOf("morphTargetTextureIndices")&&_.push("morphTargetTextureIndices"),-1===this._options.samplers.indexOf("morphTargets")&&this._options.samplers.push("morphTargets")),h.push("#define NUM_MORPH_INFLUENCERS "+T),v=0;v<T;v++)d.push(Nr.PositionKind+v),A&&d.push(Nr.NormalKind+v),x&&d.push(Nr.TangentKind+v),S&&d.push(Nr.UVKind+"_"+v);T>0&&((_=_.slice()).push("morphTargetInfluences"),_.push("morphTargetCount"),_.push("morphTargetTextureInfo"),_.push("morphTargetTextureIndices"))}else h.push("#define NUM_MORPH_INFLUENCERS 0");if(e){var C=e.bakedVertexAnimationManager;C&&C.isEnabled&&(h.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===_.indexOf("bakedVertexAnimationSettings")&&_.push("bakedVertexAnimationSettings"),-1===_.indexOf("bakedVertexAnimationTextureSizeInverted")&&_.push("bakedVertexAnimationTextureSizeInverted"),-1===_.indexOf("bakedVertexAnimationTime")&&_.push("bakedVertexAnimationTime"),-1===this._options.samplers.indexOf("bakedVertexAnimationTexture")&&this._options.samplers.push("bakedVertexAnimationTexture")),ra(d,0,h)}for(var R in this._textures)if(!this._textures[R].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&h.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&(Go(_),zo(this,c,h)),c.fogEnabled&&(null==e?void 0:e.applyFog)&&c.fogMode!==pn.FOGMODE_NONE&&(h.push("#define FOG"),-1===_.indexOf("view")&&_.push("view"),-1===_.indexOf("vFogInfos")&&_.push("vFogInfos"),-1===_.indexOf("vFogColor")&&_.push("vFogColor")),this._useLogarithmicDepth&&(h.push("#define LOGARITHMICDEPTH"),-1===_.indexOf("logarithmicDepthConstant")&&_.push("logarithmicDepthConstant")),this.customShaderNameResolve&&(_=_.slice(),m=m.slice(),g=g.slice(),f=this.customShaderNameResolve(this.name,_,m,g,h,d));var P=s?i._getDrawWrapper(void 0,!0):this._drawWrapper,I=null!==(r=null==P?void 0:P.effect)&&void 0!==r?r:null,M=null!==(n=null==P?void 0:P.defines)&&void 0!==n?n:null,O=h.join("\n"),D=I;return M!==O&&(D=u.createEffect(f,{attributes:d,uniformsNames:_,uniformBuffersNames:m,samplers:g,defines:O,fallbacks:p,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:T},shaderLanguage:this._options.shaderLanguage},u),s?i.setEffect(D,O,this._materialContext):P&&P.setEffect(D,O),this._onEffectCreatedObservable&&(sd.effect=D,sd.subMesh=null!==(o=null!=i?i:null==e?void 0:e.subMeshes[0])&&void 0!==o?o:null,this._onEffectCreatedObservable.notifyObservers(sd))),P._wasPreviouslyUsingInstances=!!t,null!==(a=!(null==D?void 0:D.isReady()))&&void 0!==a&&!a&&(I!==D&&c.resetCachedMaterial(),P._wasPreviouslyReady=!0,!0)},t.prototype.bindOnlyWorldMatrix=function(e,t){var i=this.getScene(),r=null!=t?t:this.getEffect();r&&(-1!==this._options.uniforms.indexOf("world")&&r.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),r.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),r.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)),-1!==this._options.uniforms.indexOf("view")&&r.setMatrix("view",i.getViewMatrix()))},t.prototype.bindForSubMesh=function(e,t,i){var r;this.bind(e,t,null===(r=i._drawWrapperOverride)||void 0===r?void 0:r.effect,i)},t.prototype.bind=function(e,t,i,r){var n,o=r&&this._storeEffectOnSubMeshes,a=null!=i?i:o?r.effect:this.getEffect();if(a){var s=this.getScene();this._activeEffect=a,this.bindOnlyWorldMatrix(e,i);var l=this._options.uniformBuffers,c=!1;if(a&&l&&l.length>0&&s.getEngine().supportsUniformBuffers)for(var u=0;u<l.length;++u)switch(l[u]){case"Mesh":t&&(t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e));break;case"Scene":ea(a,s.getSceneUniformBuffer()),s.finalizeSceneUbo(),c=!0}var h=t&&o?this._mustRebind(s,a,r,t.visibility):s.getCachedMaterial()!==this;if(a&&h){var d;for(d in c||-1===this._options.uniforms.indexOf("view")||a.setMatrix("view",s.getViewMatrix()),c||-1===this._options.uniforms.indexOf("projection")||a.setMatrix("projection",s.getProjectionMatrix()),c||-1===this._options.uniforms.indexOf("viewProjection")||(a.setMatrix("viewProjection",s.getTransformMatrix()),this._multiview&&a.setMatrix("viewProjectionR",s._transformMatrixR)),s.activeCamera&&-1!==this._options.uniforms.indexOf("cameraPosition")&&a.setVector3("cameraPosition",s.activeCamera.globalPosition),na(t,a),Ho(a,this,s),this._useLogarithmicDepth&&Ko(o?r.materialDefines:a.defines,a,s),t&&Qo(s,t,a),this._textures)a.setTexture(d,this._textures[d]);for(d in this._textureArrays)a.setTextureArray(d,this._textureArrays[d]);for(d in this._ints)a.setInt(d,this._ints[d]);for(d in this._uints)a.setUInt(d,this._uints[d]);for(d in this._floats)a.setFloat(d,this._floats[d]);for(d in this._floatsArrays)a.setArray(d,this._floatsArrays[d]);for(d in this._colors3)a.setColor3(d,this._colors3[d]);for(d in this._colors3Arrays)a.setArray3(d,this._colors3Arrays[d]);for(d in this._colors4){var p=this._colors4[d];a.setFloat4(d,p.r,p.g,p.b,p.a)}for(d in this._colors4Arrays)a.setArray4(d,this._colors4Arrays[d]);for(d in this._vectors2)a.setVector2(d,this._vectors2[d]);for(d in this._vectors3)a.setVector3(d,this._vectors3[d]);for(d in this._vectors4)a.setVector4(d,this._vectors4[d]);for(d in this._quaternions)a.setQuaternion(d,this._quaternions[d]);for(d in this._matrices)a.setMatrix(d,this._matrices[d]);for(d in this._matrixArrays)a.setMatrices(d,this._matrixArrays[d]);for(d in this._matrices3x3)a.setMatrix3x3(d,this._matrices3x3[d]);for(d in this._matrices2x2)a.setMatrix2x2(d,this._matrices2x2[d]);for(d in this._vectors2Arrays)a.setArray2(d,this._vectors2Arrays[d]);for(d in this._vectors3Arrays)a.setArray3(d,this._vectors3Arrays[d]);for(d in this._vectors4Arrays)a.setArray4(d,this._vectors4Arrays[d]);for(d in this._quaternionsArrays)a.setArray4(d,this._quaternionsArrays[d]);for(d in this._uniformBuffers){var f=this._uniformBuffers[d].getBuffer();f&&a.bindUniformBuffer(f,d)}var _=s.getEngine(),m=_.setExternalTexture;if(m)for(d in this._externalTextures)m.call(_,d,this._externalTextures[d]);var g=_.setTextureSampler;if(g)for(d in this._textureSamplers)g.call(_,d,this._textureSamplers[d]);var v=_.setStorageBuffer;if(v)for(d in this._storageBuffers)v.call(_,d,this._storageBuffers[d])}if(a&&t&&(h||!this.isFrozen)){var y=t.morphTargetManager;y&&y.numInfluencers>0&&$o(t,a);var b=t.bakedVertexAnimationManager;if(b&&b.isEnabled){var T=o?r._drawWrapper:this._drawWrapper;null===(n=t.bakedVertexAnimationManager)||void 0===n||n.bind(a,!!T._wasPreviouslyUsingInstances)}}this._afterBind(t,a,r)}},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);for(var i in this._textures)t.push(this._textures[i]);for(var r in this._textureArrays)for(var n=this._textureArrays[r],o=0;o<n.length;o++)t.push(n[o]);return t},t.prototype.hasTexture=function(t){if(e.prototype.hasTexture.call(this,t))return!0;for(var i in this._textures)if(this._textures[i]===t)return!0;for(var r in this._textureArrays)for(var n=this._textureArrays[r],o=0;o<n.length;o++)if(n[o]===t)return!0;return!1},t.prototype.clone=function(e){var i=this,r=Ke.Clone((function(){return new t(e,i.getScene(),i._shaderPath,i._options,i._storeEffectOnSubMeshes)}),this);for(var n in r.name=e,r.id=e,"object"==typeof r._shaderPath&&(r._shaderPath=g({},r._shaderPath)),this._options=g({},this._options),Object.keys(this._options).forEach((function(e){var t=i._options[e];Array.isArray(t)&&(i._options[e]=t.slice(0))})),this.stencil.copyTo(r.stencil),this._textures)r.setTexture(n,this._textures[n]);for(var n in this._textureArrays)r.setTextureArray(n,this._textureArrays[n]);for(var n in this._externalTextures)r.setExternalTexture(n,this._externalTextures[n]);for(var n in this._ints)r.setInt(n,this._ints[n]);for(var n in this._uints)r.setUInt(n,this._uints[n]);for(var n in this._floats)r.setFloat(n,this._floats[n]);for(var n in this._floatsArrays)r.setFloats(n,this._floatsArrays[n]);for(var n in this._colors3)r.setColor3(n,this._colors3[n]);for(var n in this._colors3Arrays)r._colors3Arrays[n]=this._colors3Arrays[n];for(var n in this._colors4)r.setColor4(n,this._colors4[n]);for(var n in this._colors4Arrays)r._colors4Arrays[n]=this._colors4Arrays[n];for(var n in this._vectors2)r.setVector2(n,this._vectors2[n]);for(var n in this._vectors3)r.setVector3(n,this._vectors3[n]);for(var n in this._vectors4)r.setVector4(n,this._vectors4[n]);for(var n in this._quaternions)r.setQuaternion(n,this._quaternions[n]);for(var n in this._quaternionsArrays)r._quaternionsArrays[n]=this._quaternionsArrays[n];for(var n in this._matrices)r.setMatrix(n,this._matrices[n]);for(var n in this._matrixArrays)r._matrixArrays[n]=this._matrixArrays[n].slice();for(var n in this._matrices3x3)r.setMatrix3x3(n,this._matrices3x3[n]);for(var n in this._matrices2x2)r.setMatrix2x2(n,this._matrices2x2[n]);for(var n in this._vectors2Arrays)r.setArray2(n,this._vectors2Arrays[n]);for(var n in this._vectors3Arrays)r.setArray3(n,this._vectors3Arrays[n]);for(var n in this._vectors4Arrays)r.setArray4(n,this._vectors4Arrays[n]);for(var n in this._uniformBuffers)r.setUniformBuffer(n,this._uniformBuffers[n]);for(var n in this._textureSamplers)r.setTextureSampler(n,this._textureSamplers[n]);for(var n in this._storageBuffers)r.setStorageBuffer(n,this._storageBuffers[n]);return r},t.prototype.dispose=function(t,i,r){if(i){var n;for(n in this._textures)this._textures[n].dispose();for(n in this._textureArrays)for(var o=this._textureArrays[n],a=0;a<o.length;a++)o[a].dispose()}this._textures={},e.prototype.dispose.call(this,t,i,r)},t.prototype.serialize=function(){var e,t=Ke.Serialize(this);for(e in t.customType="BABYLON.ShaderMaterial",t.uniqueId=this.uniqueId,t.options=this._options,t.shaderPath=this._shaderPath,t.storeEffectOnSubMeshes=this._storeEffectOnSubMeshes,t.stencil=this.stencil.serialize(),t.textures={},this._textures)t.textures[e]=this._textures[e].serialize();for(e in t.textureArrays={},this._textureArrays){t.textureArrays[e]=[];for(var i=this._textureArrays[e],r=0;r<i.length;r++)t.textureArrays[e].push(i[r].serialize())}for(e in t.ints={},this._ints)t.ints[e]=this._ints[e];for(e in t.uints={},this._uints)t.uints[e]=this._uints[e];for(e in t.floats={},this._floats)t.floats[e]=this._floats[e];for(e in t.floatsArrays={},this._floatsArrays)t.floatsArrays[e]=this._floatsArrays[e];for(e in t.colors3={},this._colors3)t.colors3[e]=this._colors3[e].asArray();for(e in t.colors3Arrays={},this._colors3Arrays)t.colors3Arrays[e]=this._colors3Arrays[e];for(e in t.colors4={},this._colors4)t.colors4[e]=this._colors4[e].asArray();for(e in t.colors4Arrays={},this._colors4Arrays)t.colors4Arrays[e]=this._colors4Arrays[e];for(e in t.vectors2={},this._vectors2)t.vectors2[e]=this._vectors2[e].asArray();for(e in t.vectors3={},this._vectors3)t.vectors3[e]=this._vectors3[e].asArray();for(e in t.vectors4={},this._vectors4)t.vectors4[e]=this._vectors4[e].asArray();for(e in t.quaternions={},this._quaternions)t.quaternions[e]=this._quaternions[e].asArray();for(e in t.matrices={},this._matrices)t.matrices[e]=this._matrices[e].asArray();for(e in t.matrixArray={},this._matrixArrays)t.matrixArray[e]=this._matrixArrays[e];for(e in t.matrices3x3={},this._matrices3x3)t.matrices3x3[e]=this._matrices3x3[e];for(e in t.matrices2x2={},this._matrices2x2)t.matrices2x2[e]=this._matrices2x2[e];for(e in t.vectors2Arrays={},this._vectors2Arrays)t.vectors2Arrays[e]=this._vectors2Arrays[e];for(e in t.vectors3Arrays={},this._vectors3Arrays)t.vectors3Arrays[e]=this._vectors3Arrays[e];for(e in t.vectors4Arrays={},this._vectors4Arrays)t.vectors4Arrays[e]=this._vectors4Arrays[e];for(e in t.quaternionsArrays={},this._quaternionsArrays)t.quaternionsArrays[e]=this._quaternionsArrays[e];return t},t.Parse=function(e,i,r){var n,o=Ke.Parse((function(){return new t(e.name,i,e.shaderPath,e.options,e.storeEffectOnSubMeshes)}),e,i,r);for(n in e.stencil&&o.stencil.parse(e.stencil,i,r),e.textures)o.setTexture(n,Ja.Parse(e.textures[n],i,r));for(n in e.textureArrays){for(var a=e.textureArrays[n],s=[],l=0;l<a.length;l++)s.push(Ja.Parse(a[l],i,r));o.setTextureArray(n,s)}for(n in e.ints)o.setInt(n,e.ints[n]);for(n in e.uints)o.setUInt(n,e.uints[n]);for(n in e.floats)o.setFloat(n,e.floats[n]);for(n in e.floatsArrays)o.setFloats(n,e.floatsArrays[n]);for(n in e.colors3)o.setColor3(n,Z.FromArray(e.colors3[n]));for(n in e.colors3Arrays){var c=e.colors3Arrays[n].reduce((function(e,t,i){return i%3==0?e.push([t]):e[e.length-1].push(t),e}),[]).map((function(e){return Z.FromArray(e)}));o.setColor3Array(n,c)}for(n in e.colors4)o.setColor4(n,J.FromArray(e.colors4[n]));for(n in e.colors4Arrays)c=e.colors4Arrays[n].reduce((function(e,t,i){return i%4==0?e.push([t]):e[e.length-1].push(t),e}),[]).map((function(e){return J.FromArray(e)})),o.setColor4Array(n,c);for(n in e.vectors2)o.setVector2(n,U.FromArray(e.vectors2[n]));for(n in e.vectors3)o.setVector3(n,V.FromArray(e.vectors3[n]));for(n in e.vectors4)o.setVector4(n,k.FromArray(e.vectors4[n]));for(n in e.quaternions)o.setQuaternion(n,G.FromArray(e.quaternions[n]));for(n in e.matrices)o.setMatrix(n,z.FromArray(e.matrices[n]));for(n in e.matrixArray)o._matrixArrays[n]=new Float32Array(e.matrixArray[n]);for(n in e.matrices3x3)o.setMatrix3x3(n,e.matrices3x3[n]);for(n in e.matrices2x2)o.setMatrix2x2(n,e.matrices2x2[n]);for(n in e.vectors2Arrays)o.setArray2(n,e.vectors2Arrays[n]);for(n in e.vectors3Arrays)o.setArray3(n,e.vectors3Arrays[n]);for(n in e.vectors4Arrays)o.setArray4(n,e.vectors4Arrays[n]);for(n in e.quaternionsArrays)o.setArray4(n,e.quaternionsArrays[n]);return o},t.ParseFromFileAsync=function(e,t,i,r){var n=this;return void 0===r&&(r=""),new Promise((function(o,a){var s=new Je;s.addEventListener("readystatechange",(function(){if(4==s.readyState)if(200==s.status){var t=JSON.parse(s.responseText),l=n.Parse(t,i||M.LastCreatedScene,r);e&&(l.name=e),o(l)}else a("Unable to load the ShaderMaterial")})),s.open("GET",t),s.send()}))},t.ParseFromSnippetAsync=function(e,t,i){var r=this;return void 0===i&&(i=""),new Promise((function(n,o){var a=new Je;a.addEventListener("readystatechange",(function(){if(4==a.readyState)if(200==a.status){var s=JSON.parse(JSON.parse(a.responseText).jsonPayload),l=JSON.parse(s.shaderMaterial),c=r.Parse(l,t||M.LastCreatedScene,i);c.snippetId=e,n(c)}else o("Unable to load the snippet "+e)})),a.open("GET",r.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()}))},t.SnippetUrl=u.SnippetUrl,t.CreateFromSnippetAsync=t.ParseFromSnippetAsync,t}(ws);a("BABYLON.ShaderMaterial",ld);li.ShadersStore.colorPixelShader="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\n#define VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n#include<fogFragment>(color,gl_FragColor)\n#define CUSTOM_FRAGMENT_MAIN_END\n}";li.ShadersStore.colorVertexShader="attribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#ifdef FOG\nuniform mat4 view;\n#endif\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<vertexColorMixing>\n#define CUSTOM_VERTEX_MAIN_END\n}",Fa._LinesMeshParser=function(e,t){return cd.Parse(e,t)};var cd=function(e){function t(t,i,r,n,o,a,s,l){void 0===i&&(i=null),void 0===r&&(r=null),void 0===n&&(n=null);var c=e.call(this,t,i,r,n,o)||this;c.useVertexColor=a,c.useVertexAlpha=s,c.color=new Z(1,1,1),c.alpha=1,n&&(c.color=n.color.clone(),c.alpha=n.alpha,c.useVertexColor=n.useVertexColor,c.useVertexAlpha=n.useVertexAlpha),c.intersectionThreshold=.1;var u={attributes:[Nr.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:[],useClipPlane:null};return!1===s?u.needAlphaBlending=!1:u.defines.push("#define VERTEXALPHA"),a?(u.defines.push("#define VERTEXCOLOR"),u.attributes.push(Nr.ColorKind)):(u.uniforms.push("color"),c._color4=new J),l?c.material=l:(c.material=new ld("colorShader",c.getScene(),"color",u,!1),c.material.doNotSerialize=!0),c}return m(t,e),t.prototype._isShaderMaterial=function(e){return"ShaderMaterial"===e.getClassName()},t.prototype.isReady=function(){return!!this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage||this.hasThinInstances)&&e.prototype.isReady.call(this)},t.prototype.getClassName=function(){return"LinesMesh"},Object.defineProperty(t.prototype,"material",{get:function(){return this._lineMaterial},set:function(e){this._lineMaterial=e,this._lineMaterial.fillMode=Ca.LineListDrawMode},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"checkCollisions",{get:function(){return!1},set:function(e){},enumerable:!1,configurable:!0}),t.prototype._bind=function(e,t){if(!this._geometry)return this;var i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){var r=this.color,n=r.r,o=r.g,a=r.b;this._color4.set(n,o,a,this.alpha),this._lineMaterial.setColor4("color",this._color4)}return this},t.prototype._draw=function(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;var r=this.getScene().getEngine();return this._unIndexed?r.drawArraysType(Ca.LineListDrawMode,e.verticesStart,e.verticesCount,i):r.drawElementsType(Ca.LineListDrawMode,e.indexStart,e.indexCount,i),this},t.prototype.dispose=function(t,i,r){void 0===i&&(i=!1),r||this._lineMaterial.dispose(!1,!1,!0),e.prototype.dispose.call(this,t)},t.prototype.clone=function(e,i,r){return void 0===i&&(i=null),new t(e,this.getScene(),i,this,r)},t.prototype.createInstance=function(e){var t=new ud(e,this);if(this.instancedBuffers)for(var i in t.instancedBuffers={},this.instancedBuffers)t.instancedBuffers[i]=this.instancedBuffers[i];return t},t.prototype.serialize=function(t){e.prototype.serialize.call(this,t),t.color=this.color.asArray(),t.alpha=this.alpha},t.Parse=function(e,i){var r=new t(e.name,i);return r.color=Z.FromArray(e.color),r.alpha=e.alpha,r},t}(Fa),ud=function(e){function t(t,i){var r=e.call(this,t,i)||this;return r.intersectionThreshold=i.intersectionThreshold,r}return m(t,e),t.prototype.getClassName=function(){return"InstancedLinesMesh"},t}(La);function hd(e){for(var t=[],i=[],r=e.lines,n=e.colors,o=[],a=0,s=0;s<r.length;s++)for(var l=r[s],c=0;c<l.length;c++){var u=l[c],h=u.x,d=u.y,p=u.z;if(i.push(h,d,p),n){var f=n[s][c],_=f.r,m=f.g,g=f.b,v=f.a;o.push(_,m,g,v)}c>0&&(t.push(a-1),t.push(a)),a++}var y=new _o;return y.indices=t,y.positions=i,n&&(y.colors=o),y}function dd(e){var t,i,r=e.dashSize||3,n=e.gapSize||1,o=e.dashNb||200,a=e.points,s=[],l=[],c=V.Zero(),u=0,h=0,d=0,p=0,f=0;for(f=0;f<a.length-1;f++)a[f+1].subtractToRef(a[f],c),u+=c.length();for(i=r*(t=u/o)/(r+n),f=0;f<a.length-1;f++){a[f+1].subtractToRef(a[f],c),h=Math.floor(c.length()/t),c.normalize();for(var _=0;_<h;_++)d=t*_,s.push(a[f].x+d*c.x,a[f].y+d*c.y,a[f].z+d*c.z),s.push(a[f].x+(d+i)*c.x,a[f].y+(d+i)*c.y,a[f].z+(d+i)*c.z),l.push(p,p+1),p+=2}var m=new _o;return m.positions=s,m.indices=l,m}function pd(e,t,i){void 0===i&&(i=null);var r=t.instance,n=t.lines,o=t.colors;if(r){var a=r.getVerticesData(Nr.PositionKind),s=void 0,l=void 0;o&&(s=r.getVerticesData(Nr.ColorKind));for(var c=0,u=0,h=0;h<n.length;h++)for(var d=n[h],p=0;p<d.length;p++)a[c]=d[p].x,a[c+1]=d[p].y,a[c+2]=d[p].z,o&&s&&(l=o[h],s[u]=l[p].r,s[u+1]=l[p].g,s[u+2]=l[p].b,s[u+3]=l[p].a,u+=4),c+=3;return r.updateVerticesData(Nr.PositionKind,a,!1,!1),o&&s&&r.updateVerticesData(Nr.ColorKind,s,!1,!1),r}var f=new cd(e,i,null,void 0,void 0,!!o,t.useVertexAlpha,t.material);return hd(t).applyToMesh(f,t.updatable),f}function fd(e,t,i){void 0===i&&(i=null);var r=t.colors?[t.colors]:null;return pd(e,{lines:[t.points],updatable:t.updatable,instance:t.instance,colors:r,useVertexAlpha:t.useVertexAlpha,material:t.material},i)}function _d(e,t,i){void 0===i&&(i=null);var r=t.points,n=t.instance,o=t.gapSize||1,a=t.dashSize||3;if(n)return(t.dashNb||t.dashSize||t.gapSize||t.useVertexAlpha||t.material)&&ae.Warn("You have used an option other than points with the instance option. Please be aware that these other options will be ignored."),n.updateMeshPositions((function(e){var t,i,o=V.Zero(),a=e.length/6,s=0,l=0,c=0,u=0,h=0,d=0;for(h=0;h<r.length-1;h++)r[h+1].subtractToRef(r[h],o),s+=o.length();t=s/a;var p=n._creationDataStorage.dashSize;for(i=p*t/(p+n._creationDataStorage.gapSize),h=0;h<r.length-1;h++)for(r[h+1].subtractToRef(r[h],o),l=Math.floor(o.length()/t),o.normalize(),d=0;d<l&&u<e.length;)c=t*d,e[u]=r[h].x+c*o.x,e[u+1]=r[h].y+c*o.y,e[u+2]=r[h].z+c*o.z,e[u+3]=r[h].x+(c+i)*o.x,e[u+4]=r[h].y+(c+i)*o.y,e[u+5]=r[h].z+(c+i)*o.z,u+=6,d++;for(;u<e.length;)e[u]=r[h].x,e[u+1]=r[h].y,e[u+2]=r[h].z,u+=3}),!1),n;var s=new cd(e,i,null,void 0,void 0,void 0,t.useVertexAlpha,t.material);return dd(t).applyToMesh(s,t.updatable),s._creationDataStorage=new Ia,s._creationDataStorage.dashSize=a,s._creationDataStorage.gapSize=o,s}var md={CreateDashedLines:_d,CreateLineSystem:pd,CreateLines:fd};_o.CreateLineSystem=hd,_o.CreateDashedLines=dd,Fa.CreateLines=function(e,t,i,r,n){return void 0===i&&(i=null),void 0===r&&(r=!1),void 0===n&&(n=null),fd(e,{points:t,updatable:r,instance:n},i)},Fa.CreateDashedLines=function(e,t,i,r,n,o,a,s){return void 0===o&&(o=null),_d(e,{points:t,dashSize:i,gapSize:r,dashNb:n,updatable:a,instance:s},o)};var gd=function(e){function t(t,i){var r=e.call(this,t.x,t.y)||this;return r.index=i,r}return m(t,e),t}(U),vd=function(){function e(){this.elements=[]}return e.prototype.add=function(e){var t=this,i=[];return e.forEach((function(e){var r=new gd(e,t.elements.length);i.push(r),t.elements.push(r)})),i},e.prototype.computeBounds=function(){var e=new U(this.elements[0].x,this.elements[0].y),t=new U(this.elements[0].x,this.elements[0].y);return this.elements.forEach((function(i){i.x<e.x?e.x=i.x:i.x>t.x&&(t.x=i.x),i.y<e.y?e.y=i.y:i.y>t.y&&(t.y=i.y)})),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}},e}(),yd=function(){function e(){}return e.Rectangle=function(e,t,i,r){return[new U(e,t),new U(i,t),new U(i,r),new U(e,r)]},e.Circle=function(e,t,i,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=32);for(var n=[],o=0,a=2*Math.PI/r,s=0;s<r;s++)n.push(new U(t+Math.cos(o)*e,i+Math.sin(o)*e)),o-=a;return n},e.Parse=function(e){var t,i=e.split(/[^-+eE.\d]+/).map(parseFloat).filter((function(e){return!isNaN(e)})),r=[];for(t=0;t<(2147483646&i.length);t+=2)r.push(new U(i[t],i[t+1]));return r},e.StartingAt=function(e,t){return xn.StartingAt(e,t)},e}(),bd=function(){function e(e,t,i,r){var n;void 0===r&&(r=earcut),this._points=new vd,this._outlinepoints=new vd,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=r,this._name=e,this._scene=i||M.LastCreatedScene,n=t instanceof xn?t.getPoints():t,this._addToepoint(n),this._points.add(n),this._outlinepoints.add(n),void 0===this.bjsEarcut&&ae.Warn("Earcut was not found, the polygon will not be built.")}return e.prototype._addToepoint=function(e){for(var t=0,i=e;t<i.length;t++){var r=i[t];this._epoints.push(r.x,r.y)}},e.prototype.addHole=function(e){this._points.add(e);var t=new vd;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this},e.prototype.build=function(e,t,i){void 0===e&&(e=!1),void 0===t&&(t=0),void 0===i&&(i=2);var r=new Fa(this._name,this._scene),n=this.buildVertexData(t,i);return r.setVerticesData(Nr.PositionKind,n.positions,e),r.setVerticesData(Nr.NormalKind,n.normals,e),r.setVerticesData(Nr.UVKind,n.uvs,e),r.setIndices(n.indices),r},e.prototype.buildVertexData=function(e,t){var i=this;void 0===e&&(e=0),void 0===t&&(t=2);var r=new _o,n=[],o=[],a=[],s=this._points.computeBounds();this._points.elements.forEach((function(e){n.push(0,1,0),o.push(e.x,0,e.y),a.push((e.x-s.min.x)/s.width,(e.y-s.min.y)/s.height)}));for(var l=[],c=this.bjsEarcut(this._epoints,this._eholes,2),u=0;u<c.length;u++)l.push(c[u]);if(e>0){var h=o.length/3;this._points.elements.forEach((function(t){n.push(0,-1,0),o.push(t.x,-e,t.y),a.push(1-(t.x-s.min.x)/s.width,1-(t.y-s.min.y)/s.height)}));var d=l.length;for(u=0;u<d;u+=3){var p=l[u+0],f=l[u+1],_=l[u+2];l.push(_+h),l.push(f+h),l.push(p+h)}this._addSide(o,n,a,l,s,this._outlinepoints,e,!1,t),this._holes.forEach((function(r){i._addSide(o,n,a,l,s,r,e,!0,t)}))}return r.indices=l,r.positions=o,r.normals=n,r.uvs=a,r},e.prototype._addSide=function(e,t,i,r,n,o,a,s,l){for(var c=e.length/3,u=0,h=0;h<o.elements.length;h++){var d=o.elements[h],p=o.elements[(h+1)%o.elements.length];e.push(d.x,0,d.y),e.push(d.x,-a,d.y),e.push(p.x,0,p.y),e.push(p.x,-a,p.y);var f=o.elements[(h+o.elements.length-1)%o.elements.length],_=o.elements[(h+2)%o.elements.length],m=new V(-(p.y-d.y),0,p.x-d.x),g=new V(-(d.y-f.y),0,d.x-f.x),v=new V(-(_.y-p.y),0,_.x-p.x);s||(m=m.scale(-1),g=g.scale(-1),v=v.scale(-1));var y=m.normalizeToNew(),b=g.normalizeToNew(),T=v.normalizeToNew(),E=V.Dot(b,y);b=E>l?E<A-1?new V(d.x,0,d.y).subtract(new V(p.x,0,p.y)).normalize():g.add(m).normalize():y;var S=V.Dot(v,m);T=S>l?S<A-1?new V(p.x,0,p.y).subtract(new V(d.x,0,d.y)).normalize():v.add(m).normalize():y,i.push(u/n.width,0),i.push(u/n.width,1),u+=m.length(),i.push(u/n.width,0),i.push(u/n.width,1),t.push(b.x,b.y,b.z),t.push(b.x,b.y,b.z),t.push(T.x,T.y,T.z),t.push(T.x,T.y,T.z),s?(r.push(c),r.push(c+2),r.push(c+1),r.push(c+1),r.push(c+2),r.push(c+3)):(r.push(c),r.push(c+1),r.push(c+2),r.push(c+1),r.push(c+3),r.push(c+2)),c+=4}},e}();function Td(e,t,i,r,n,o,a){for(var s=i||new Array(3),l=r,c=[],u=a||!1,h=0;h<3;h++)void 0===s[h]&&(s[h]=new k(0,0,1,1)),l&&void 0===l[h]&&(l[h]=new J(1,1,1,1));var d=e.getVerticesData(Nr.PositionKind),p=e.getVerticesData(Nr.NormalKind),f=e.getVerticesData(Nr.UVKind),_=e.getIndices(),m=d.length/9,g=0,v=0,y=0,b=0,T=[0];if(u)for(var E=m;E<d.length/3;E+=4)v=d[3*(E+2)]-d[3*E],y=d[3*(E+2)+2]-d[3*E+2],b+=Math.sqrt(v*v+y*y),T.push(b);for(var S=0,x=0,A=0;A<p.length;A+=3)Math.abs(p[A+1])<.001&&(x=1),Math.abs(p[A+1]-1)<.001&&(x=0),Math.abs(p[A+1]+1)<.001&&(x=2),S=A/3,1===x?(g=S-m,f[2*S]=g%4<1.5?u?s[x].x+(s[x].z-s[x].x)*T[Math.floor(g/4)]/b:s[x].x:u?s[x].x+(s[x].z-s[x].x)*T[Math.floor(g/4)+1]/b:s[x].z,f[2*S+1]=g%2==0?go.UseOpenGLOrientationForUV?1-s[x].w:s[x].w:go.UseOpenGLOrientationForUV?1-s[x].y:s[x].y):(f[2*S]=(1-f[2*S])*s[x].x+f[2*S]*s[x].z,f[2*S+1]=(1-f[2*S+1])*s[x].y+f[2*S+1]*s[x].w,go.UseOpenGLOrientationForUV&&(f[2*S+1]=1-f[2*S+1])),l&&c.push(l[x].r,l[x].g,l[x].b,l[x].a);_o._ComputeSides(t,d,_,p,f,n,o);var C=new _o;if(C.indices=_,C.positions=d,C.normals=p,C.uvs=f,l){var R=t===_o.DOUBLESIDE?c.concat(c):c;C.colors=R}return C}function Ed(e,t,i,r){void 0===i&&(i=null),void 0===r&&(r=earcut),t.sideOrientation=Fa._GetDefaultSideOrientation(t.sideOrientation);for(var n=t.shape,o=t.holes||[],a=t.depth||0,s=t.smoothingThreshold||2,l=[],c=[],u=0;u<n.length;u++)l[u]=new U(n[u].x,n[u].z);l[0].equalsWithEpsilon(l[l.length-1],1e-8)&&l.pop();for(var h=new bd(e,l,i||M.LastCreatedScene,r),d=0;d<o.length;d++){c=[];for(var p=0;p<o[d].length;p++)c.push(new U(o[d][p].x,o[d][p].z));h.addHole(c)}var f=h.build(!1,a,s);return f._originalBuilderSideOrientation=t.sideOrientation,Td(f,t.sideOrientation,t.faceUV,t.faceColors,t.frontUVs,t.backUVs,t.wrap).applyToMesh(f,t.updatable),f}function Sd(e,t,i,r){return void 0===i&&(i=null),void 0===r&&(r=earcut),Ed(e,t,i,r)}var xd={ExtrudePolygon:Sd,CreatePolygon:Ed};function Ad(e,t,i){void 0===i&&(i=null);var r=t.path,n=t.shape,o=t.scale||1,a=t.rotation||0,s=0===t.cap?0:t.cap||Fa.NO_CAP,l=t.updatable,c=Fa._GetDefaultSideOrientation(t.sideOrientation),u=t.instance||null,h=t.invertUV||!1,d=t.closeShape||!1;return Rd(e,n,r,o,a,null,null,t.closePath||!1,d,s,!1,i,!!l,c,u,h,t.frontUVs||null,t.backUVs||null,t.firstNormal||null,!!t.adjustFrame)}function Cd(e,t,i){void 0===i&&(i=null);var r=t.path,n=t.shape,o=t.scaleFunction||function(){return 1},a=t.rotationFunction||function(){return 0},s=t.closePath||t.ribbonCloseArray||!1,l=t.closeShape||t.ribbonClosePath||!1,c=0===t.cap?0:t.cap||Fa.NO_CAP,u=t.updatable,h=t.firstNormal||null,d=t.adjustFrame||!1;return Rd(e,n,r,null,null,o,a,s,l,c,!0,i,!!u,Fa._GetDefaultSideOrientation(t.sideOrientation),t.instance||null,t.invertUV||!1,t.frontUVs||null,t.backUVs||null,h,d)}function Rd(e,t,i,r,n,o,a,s,l,c,u,h,d,p,f,_,m,g,v,y){var b,T,E=function(e,t,i,r,n,o,a,s,l,c,u){var h=i.getTangents(),d=i.getNormals(),p=i.getBinormals(),f=i.getDistances();if(u)for(var _=0;_<h.length;_++)if(0==h[_].x&&0==h[_].y&&0==h[_].z&&h[_].copyFrom(h[_-1]),0==d[_].x&&0==d[_].y&&0==d[_].z&&d[_].copyFrom(d[_-1]),0==p[_].x&&0==p[_].y&&0==p[_].z&&p[_].copyFrom(p[_-1]),_>0){var m=h[_-1];V.Dot(m,h[_])<0&&h[_].scaleInPlace(-1),m=d[_-1],V.Dot(m,d[_])<0&&d[_].scaleInPlace(-1),m=p[_-1],V.Dot(m,p[_])<0&&p[_].scaleInPlace(-1)}var g=0,v=c&&s?s:function(){return null!==o?o:0},y=c&&a?a:function(){return null!==n?n:1},b=l===Fa.NO_CAP||l===Fa.CAP_END?0:2,T=H.Matrix[0];for(_=0;_<t.length;_++){var E=[],S=v(_,f[_]),x=y(_,f[_]);z.RotationAxisToRef(h[_],g,T);for(var A=0;A<e.length;A++){var C=h[_].scale(e[A].z).add(d[_].scale(e[A].x)).add(p[_].scale(e[A].y)),R=V.Zero();V.TransformCoordinatesToRef(C,T,R),R.scaleInPlace(x).addInPlace(t[_]),E[A]=R}r[b]=E,g+=S,b++}var P=function(e){var t,i=Array(),r=V.Zero();for(t=0;t<e.length;t++)r.addInPlace(e[t]);for(r.scaleInPlace(1/e.length),t=0;t<e.length;t++)i.push(r);return i};switch(l){case Fa.NO_CAP:break;case Fa.CAP_START:r[0]=P(r[2]),r[1]=r[2];break;case Fa.CAP_END:r[b]=r[b-1],r[b+1]=P(r[b-1]);break;case Fa.CAP_ALL:r[0]=P(r[2]),r[1]=r[2],r[b]=r[b-1],r[b+1]=P(r[b-1])}return r};if(f){var S=f._creationDataStorage;return b=v?S.path3D.update(i,v):S.path3D.update(i),Yh("",{pathArray:T=E(t,i,S.path3D,S.pathArray,r,n,o,a,S.cap,u,y),closeArray:!1,closePath:!1,offset:0,updatable:!1,sideOrientation:0,instance:f},h||void 0)}c=c<0||c>3?0:c;var x=Yh(e,{pathArray:T=E(t,i,b=v?new An(i,v):new An(i),new Array,r,n,o,a,c,u,y),closeArray:s,closePath:l,updatable:d,sideOrientation:p,invertUV:_,frontUVs:m||void 0,backUVs:g||void 0},h);return x._creationDataStorage.pathArray=T,x._creationDataStorage.path3D=b,x._creationDataStorage.cap=c,x}_o.CreatePolygon=Td,Fa.CreatePolygon=function(e,t,i,r,n,o,a){return void 0===a&&(a=earcut),Ed(e,{shape:t,holes:r,updatable:n,sideOrientation:o},i,a)},Fa.ExtrudePolygon=function(e,t,i,r,n,o,a,s){return void 0===s&&(s=earcut),Sd(e,{shape:t,holes:n,depth:i,updatable:o,sideOrientation:a},r,s)};var Pd={ExtrudeShape:Ad,ExtrudeShapeCustom:Cd};function Id(e,t,i){void 0===i&&(i=null);var r,n,o=t.arc?t.arc<=0||t.arc>1?1:t.arc:1,a=void 0===t.closed||t.closed,s=t.shape,l=t.radius||1,c=t.tessellation||64,u=t.clip||0,h=t.updatable,d=Fa._GetDefaultSideOrientation(t.sideOrientation),p=t.cap||Fa.NO_CAP,f=2*Math.PI,_=[],m=t.invertUV||!1,g=0,v=0,y=f/c*o;for(g=0;g<=c-u;g++){for(n=[],p!=Fa.CAP_START&&p!=Fa.CAP_ALL||(n.push(new V(0,s[0].y,0)),n.push(new V(Math.cos(g*y)*s[0].x*l,s[0].y,Math.sin(g*y)*s[0].x*l))),v=0;v<s.length;v++)r=new V(Math.cos(g*y)*s[v].x*l,s[v].y,Math.sin(g*y)*s[v].x*l),n.push(r);p!=Fa.CAP_END&&p!=Fa.CAP_ALL||(n.push(new V(Math.cos(g*y)*s[s.length-1].x*l,s[s.length-1].y,Math.sin(g*y)*s[s.length-1].x*l)),n.push(new V(0,s[s.length-1].y,0))),_.push(n)}return Yh(e,{pathArray:_,closeArray:a,sideOrientation:d,updatable:h,invertUV:m,frontUVs:t.frontUVs,backUVs:t.backUVs},i)}Fa.ExtrudeShape=function(e,t,i,r,n,o,a,s,l,c){return void 0===a&&(a=null),Ad(e,{shape:t,path:i,scale:r,rotation:n,cap:0===o?0:o||Fa.NO_CAP,sideOrientation:l,instance:c,updatable:s},a)},Fa.ExtrudeShapeCustom=function(e,t,i,r,n,o,a,s,l,c,u,h){return Cd(e,{shape:t,path:i,scaleFunction:r,rotationFunction:n,ribbonCloseArray:o,ribbonClosePath:a,cap:0===s?0:s||Fa.NO_CAP,sideOrientation:u,instance:h,updatable:c},l)};var Md={CreateLathe:Id};function Od(e,t,i){void 0===i&&(i=null);var r=t.path,n=t.instance,o=1;void 0!==t.radius?o=t.radius:n&&(o=n._creationDataStorage.radius);var a=t.tessellation||64,s=t.radiusFunction||null,l=t.cap||Fa.NO_CAP,c=t.invertUV||!1,u=t.updatable,h=Fa._GetDefaultSideOrientation(t.sideOrientation);t.arc=t.arc&&(t.arc<=0||t.arc>1)?1:t.arc||1;var d,p,f=function(e,t,i,r,n,o,a,s){for(var l,c,u,h,d=t.getTangents(),p=t.getNormals(),f=t.getDistances(),_=2*Math.PI/n*s,m=o||function(){return r},g=H.Matrix[0],v=a===Fa.NO_CAP||a===Fa.CAP_END?0:2,y=0;y<e.length;y++){c=m(y,f[y]),l=Array(),u=p[y];for(var b=0;b<n;b++)z.RotationAxisToRef(d[y],_*b,g),h=l[b]?l[b]:V.Zero(),V.TransformCoordinatesToRef(u,g,h),h.scaleInPlace(c).addInPlace(e[y]),l[b]=h;i[v]=l,v++}var T=function(t,i){for(var r=Array(),n=0;n<t;n++)r.push(e[i]);return r};switch(a){case Fa.NO_CAP:break;case Fa.CAP_START:i[0]=T(n,0),i[1]=i[2].slice(0);break;case Fa.CAP_END:i[v]=i[v-1].slice(0),i[v+1]=T(n,e.length-1);break;case Fa.CAP_ALL:i[0]=T(n,0),i[1]=i[2].slice(0),i[v]=i[v-1].slice(0),i[v+1]=T(n,e.length-1)}return i};if(n){var _=n._creationDataStorage,m=t.arc||_.arc;return n=Yh("",{pathArray:p=f(r,d=_.path3D.update(r),_.pathArray,o,_.tessellation,s,_.cap,m),instance:n}),_.path3D=d,_.pathArray=p,_.arc=m,_.radius=o,n}l=l<0||l>3?0:l;var g=Yh(e,{pathArray:p=f(r,d=new An(r),new Array,o,a,s,l,t.arc),closePath:!0,closeArray:!1,updatable:u,sideOrientation:h,invertUV:c,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return g._creationDataStorage.pathArray=p,g._creationDataStorage.path3D=d,g._creationDataStorage.tessellation=a,g._creationDataStorage.cap=l,g._creationDataStorage.arc=t.arc,g._creationDataStorage.radius=o,g}Fa.CreateLathe=function(e,t,i,r,n,o,a){return Id(e,{shape:t,radius:i,tessellation:r,sideOrientation:a,updatable:o},n)};var Dd={CreateTube:Od};function Nd(e){var t=[];t[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},t[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},t[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},t[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},t[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},t[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},t[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},t[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},t[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},t[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},t[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},t[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},t[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},t[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},t[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};var i,r,n,o,a,s,l=e.type&&(e.type<0||e.type>=t.length)?0:e.type||0,c=e.size,u=e.sizeX||c||1,h=e.sizeY||c||1,d=e.sizeZ||c||1,p=e.custom||t[l],f=p.face.length,_=e.faceUV||new Array(f),m=e.faceColors,g=void 0===e.flat||e.flat,v=0===e.sideOrientation?0:e.sideOrientation||_o.DEFAULTSIDE,y=[],b=[],T=[],E=[],S=[],x=0,A=0,C=[],R=0,P=0;if(g)for(P=0;P<f;P++)m&&void 0===m[P]&&(m[P]=new J(1,1,1,1)),_&&void 0===_[P]&&(_[P]=new k(0,0,1,1));if(g)for(P=0;P<f;P++){var I=p.face[P].length;for(n=2*Math.PI/I,o=.5*Math.tan(n/2),a=.5,R=0;R<I;R++)y.push(p.vertex[p.face[P][R]][0]*u,p.vertex[p.face[P][R]][1]*h,p.vertex[p.face[P][R]][2]*d),C.push(x),x++,i=_[P].x+(_[P].z-_[P].x)*(.5+o),r=_[P].y+(_[P].w-_[P].y)*(a-.5),E.push(i,go.UseOpenGLOrientationForUV?1-r:r),s=o*Math.cos(n)-a*Math.sin(n),a=o*Math.sin(n)+a*Math.cos(n),o=s,m&&S.push(m[P].r,m[P].g,m[P].b,m[P].a);for(R=0;R<I-2;R++)b.push(C[0+A],C[R+2+A],C[R+1+A]);A+=I}else{for(R=0;R<p.vertex.length;R++)y.push(p.vertex[R][0]*u,p.vertex[R][1]*h,p.vertex[R][2]*d),E.push(0,go.UseOpenGLOrientationForUV?1:0);for(P=0;P<f;P++)for(R=0;R<p.face[P].length-2;R++)b.push(p.face[P][0],p.face[P][R+2],p.face[P][R+1])}_o.ComputeNormals(y,b,T),_o._ComputeSides(v,y,b,T,E,e.frontUVs,e.backUVs);var M=new _o;return M.positions=y,M.indices=b,M.normals=T,M.uvs=E,m&&g&&(M.colors=S),M}function Fd(e,t,i){void 0===t&&(t={}),void 0===i&&(i=null);var r=new Fa(e,i);return t.sideOrientation=Fa._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,Nd(t).applyToMesh(r,t.updatable),r}Fa.CreateTube=function(e,t,i,r,n,o,a,s,l,c){return Od(e,{path:t,radius:i,tessellation:r,radiusFunction:n,arc:1,cap:o,updatable:s,sideOrientation:l,instance:c},a)};var Ld={CreatePolyhedron:Fd};_o.CreatePolyhedron=Nd,Fa.CreatePolyhedron=function(e,t,i){return Fd(e,t,i)};var wd=new V(1,0,0),Bd=new V(-1,0,0),Ud=new V(0,1,0),Vd=new V(0,-1,0),kd=new V(0,0,1),Gd=new V(0,0,-1),zd=function(){function e(e,t,i,r,n,o,a,s,l){void 0===e&&(e=V.Zero()),void 0===t&&(t=V.Up()),void 0===i&&(i=U.Zero()),void 0===r&&(r=0),void 0===n&&(n=0),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null),void 0===l&&(l=null),this.position=e,this.normal=t,this.uv=i,this.vertexIdx=r,this.vertexIdxForBones=n,this.localPositionOverride=o,this.localNormalOverride=a,this.matrixIndicesOverride=s,this.matrixWeightsOverride=l}return e.prototype.clone=function(){var t,i,r,n;return new e(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,null===(t=this.localPositionOverride)||void 0===t?void 0:t.slice(),null===(i=this.localNormalOverride)||void 0===i?void 0:i.slice(),null===(r=this.matrixIndicesOverride)||void 0===r?void 0:r.slice(),null===(n=this.matrixWeightsOverride)||void 0===n?void 0:n.slice())},e}();function Wd(e,t,i){var r,n,o,a,s=!!t.skeleton,l=i.localMode||s,c=null!==t.overrideMaterialSideOrientation&&void 0!==t.overrideMaterialSideOrientation,u=t.getIndices(),h=s?t.getPositionData(!0,!0):t.getVerticesData(Nr.PositionKind),d=s?t.getNormalsData(!0,!0):t.getVerticesData(Nr.NormalKind),p=l?s?t.getVerticesData(Nr.PositionKind):h:null,f=l?s?t.getVerticesData(Nr.NormalKind):d:null,_=t.getVerticesData(Nr.UVKind),m=s?t.getVerticesData(Nr.MatricesIndicesKind):null,g=s?t.getVerticesData(Nr.MatricesWeightsKind):null,v=s?t.getVerticesData(Nr.MatricesIndicesExtraKind):null,y=s?t.getVerticesData(Nr.MatricesWeightsExtraKind):null,b=i.position||V.Zero(),T=i.normal||V.Up(),E=i.size||V.One(),S=i.angle||0;if(!T){var x=new V(0,0,1),A=t.getScene().activeCamera,C=V.TransformCoordinates(x,A.getWorldMatrix());T=A.globalPosition.subtract(C)}var R=-Math.atan2(T.z,T.x)-Math.PI/2,P=Math.sqrt(T.x*T.x+T.z*T.z),I=Math.atan2(T.y,P),M=new _o;M.indices=[],M.positions=[],M.normals=[],M.uvs=[],M.matricesIndices=s?[]:null,M.matricesWeights=s?[]:null,M.matricesIndicesExtra=v?[]:null,M.matricesWeightsExtra=y?[]:null;var O=0,D=function(e,t){var r=new zd;if(!u||!h||!d)return r;var n=u[e];if(r.vertexIdx=3*n,r.vertexIdxForBones=4*n,r.position=new V(h[3*n],h[3*n+1],h[3*n+2]),V.TransformCoordinatesToRef(r.position,t,r.position),r.normal=new V(d[3*n],d[3*n+1],d[3*n+2]),V.TransformNormalToRef(r.normal,t,r.normal),i.captureUVS&&_){var o=_[2*n+1];r.uv=new U(_[2*n],go.UseOpenGLOrientationForUV?1-o:o)}return r},N=[0,0,0,0],F=function(e,t){if(0===e.length)return e;var i=.5*Math.abs(V.Dot(E,t)),r=function(e,t,i,r){for(var n=0;n<r;++n)if(e[i+n]===t)return i+n;return-1},n=function(e,n){var o,a,s,l,c,u,h,d,_,v,y,b,T,E,S,x,A=V.GetClipFactor(e.position,n.position,t,i),C=N,R=N;if(m&&g){var P=e.matrixIndicesOverride?0:e.vertexIdxForBones,I=null!==(o=e.matrixIndicesOverride)&&void 0!==o?o:m,M=null!==(a=e.matrixWeightsOverride)&&void 0!==a?a:g,O=n.matrixIndicesOverride?0:n.vertexIdxForBones,D=null!==(s=n.matrixIndicesOverride)&&void 0!==s?s:m,F=null!==(l=n.matrixWeightsOverride)&&void 0!==l?l:g;C=[0,0,0,0],R=[0,0,0,0];for(var L=0,w=0;w<4;++w)if(M[P+w]>0){var B=r(D,I[P+w],O,4);C[L]=I[P+w],R[L]=j.Lerp(M[P+w],B>=0?F[B]:0,A),L++}for(w=0;w<4&&L<4;++w){var k=D[O+w];-1===r(I,k,P,4)&&(C[L]=k,R[L]=j.Lerp(0,F[O+w],A),L++)}var G=R[0]+R[1]+R[2]+R[3];R[0]/=G,R[1]/=G,R[2]/=G,R[3]/=G}var z=e.localPositionOverride?e.localPositionOverride[0]:null!==(c=null==p?void 0:p[e.vertexIdx])&&void 0!==c?c:0,W=e.localPositionOverride?e.localPositionOverride[1]:null!==(u=null==p?void 0:p[e.vertexIdx+1])&&void 0!==u?u:0,H=e.localPositionOverride?e.localPositionOverride[2]:null!==(h=null==p?void 0:p[e.vertexIdx+2])&&void 0!==h?h:0,X=n.localPositionOverride?n.localPositionOverride[0]:null!==(d=null==p?void 0:p[n.vertexIdx])&&void 0!==d?d:0,Y=n.localPositionOverride?n.localPositionOverride[1]:null!==(_=null==p?void 0:p[n.vertexIdx+1])&&void 0!==_?_:0,K=n.localPositionOverride?n.localPositionOverride[2]:null!==(v=null==p?void 0:p[n.vertexIdx+2])&&void 0!==v?v:0,Q=e.localNormalOverride?e.localNormalOverride[0]:null!==(y=null==f?void 0:f[e.vertexIdx])&&void 0!==y?y:0,q=e.localNormalOverride?e.localNormalOverride[1]:null!==(b=null==f?void 0:f[e.vertexIdx+1])&&void 0!==b?b:0,Z=e.localNormalOverride?e.localNormalOverride[2]:null!==(T=null==f?void 0:f[e.vertexIdx+2])&&void 0!==T?T:0,J=Q+((n.localNormalOverride?n.localNormalOverride[0]:null!==(E=null==f?void 0:f[n.vertexIdx])&&void 0!==E?E:0)-Q)*A,$=q+((n.localNormalOverride?n.localNormalOverride[1]:null!==(S=null==f?void 0:f[n.vertexIdx+1])&&void 0!==S?S:0)-q)*A,ee=Z+((n.localNormalOverride?n.localNormalOverride[2]:null!==(x=null==f?void 0:f[n.vertexIdx+2])&&void 0!==x?x:0)-Z)*A,te=Math.sqrt(J*J+$*$+ee*ee);return new zd(V.Lerp(e.position,n.position,A),V.Lerp(e.normal,n.normal,A).normalize(),U.Lerp(e.uv,n.uv,A),-1,-1,p?[z+(X-z)*A,W+(Y-W)*A,H+(K-H)*A]:null,f?[J/te,$/te,ee/te]:null,C,R)},o=null;e.length>3&&(o=[]);for(var a=0;a<e.length;a+=3){var s=null,l=null,c=null,u=null,h=V.Dot(e[a].position,t)-i>0,d=V.Dot(e[a+1].position,t)-i>0,_=V.Dot(e[a+2].position,t)-i>0;switch((h?1:0)+(d?1:0)+(_?1:0)){case 0:e.length>3?(o.push(e[a]),o.push(e[a+1]),o.push(e[a+2])):o=e;break;case 1:if(o=null!=o?o:new Array,h&&(s=e[a+1],l=e[a+2],c=n(e[a],s),u=n(e[a],l)),d){s=e[a],l=e[a+2],c=n(e[a+1],s),u=n(e[a+1],l),o.push(c),o.push(l.clone()),o.push(s.clone()),o.push(l.clone()),o.push(c.clone()),o.push(u);break}_&&(s=e[a],l=e[a+1],c=n(e[a+2],s),u=n(e[a+2],l)),s&&l&&c&&u&&(o.push(s.clone()),o.push(l.clone()),o.push(c),o.push(u),o.push(c.clone()),o.push(l.clone()));break;case 2:o=null!=o?o:new Array,h||(l=n(s=e[a].clone(),e[a+1]),c=n(s,e[a+2]),o.push(s),o.push(l),o.push(c)),d||(l=n(s=e[a+1].clone(),e[a+2]),c=n(s,e[a]),o.push(s),o.push(l),o.push(c)),_||(l=n(s=e[a+2].clone(),e[a]),c=n(s,e[a+1]),o.push(s),o.push(l),o.push(c))}}return o},L=t instanceof Fa?t:null,w=null==L?void 0:L._thinInstanceDataStorage.matrixData,B=(null==L?void 0:L.thinInstanceCount)||1,k=H.Matrix[0];k.copyFrom(z.IdentityReadOnly);for(var G=0;G<B;++G){if((null==L?void 0:L.hasThinInstances)&&w){var W=16*G;k.setRowFromFloats(0,w[W+0],w[W+1],w[W+2],w[W+3]),k.setRowFromFloats(1,w[W+4],w[W+5],w[W+6],w[W+7]),k.setRowFromFloats(2,w[W+8],w[W+9],w[W+10],w[W+11]),k.setRowFromFloats(3,w[W+12],w[W+13],w[W+14],w[W+15])}for(var X=z.RotationYawPitchRoll(R,I,S).multiply(z.Translation(b.x,b.y,b.z)),Y=z.Invert(X),K=t.getWorldMatrix(),Q=k.multiply(K).multiply(Y),q=new Array(3),Z=0;Z<u.length;Z+=3){var J=q;if(J[0]=D(Z,Q),c&&l?(J[1]=D(Z+2,Q),J[2]=D(Z+1,Q)):(J[1]=D(Z+1,Q),J[2]=D(Z+2,Q)),!(i.cullBackFaces&&-J[0].normal.z<=0&&-J[1].normal.z<=0&&-J[2].normal.z<=0)&&(J=F(J,wd))&&(J=F(J,Bd))&&(J=F(J,Ud))&&(J=F(J,Vd))&&(J=F(J,kd))&&(J=F(J,Gd)))for(var $=0;$<J.length;$++){var ee=J[$];if(M.indices.push(O),l?(ee.localPositionOverride?(M.positions[3*O]=ee.localPositionOverride[0],M.positions[3*O+1]=ee.localPositionOverride[1],M.positions[3*O+2]=ee.localPositionOverride[2]):p&&(M.positions[3*O]=p[ee.vertexIdx],M.positions[3*O+1]=p[ee.vertexIdx+1],M.positions[3*O+2]=p[ee.vertexIdx+2]),ee.localNormalOverride?(M.normals[3*O]=ee.localNormalOverride[0],M.normals[3*O+1]=ee.localNormalOverride[1],M.normals[3*O+2]=ee.localNormalOverride[2]):f&&(M.normals[3*O]=f[ee.vertexIdx],M.normals[3*O+1]=f[ee.vertexIdx+1],M.normals[3*O+2]=f[ee.vertexIdx+2])):(ee.position.toArray(M.positions,3*O),ee.normal.toArray(M.normals,3*O)),M.matricesIndices&&M.matricesWeights&&(ee.matrixIndicesOverride?(M.matricesIndices[4*O]=ee.matrixIndicesOverride[0],M.matricesIndices[4*O+1]=ee.matrixIndicesOverride[1],M.matricesIndices[4*O+2]=ee.matrixIndicesOverride[2],M.matricesIndices[4*O+3]=ee.matrixIndicesOverride[3]):(m&&(M.matricesIndices[4*O]=m[ee.vertexIdxForBones],M.matricesIndices[4*O+1]=m[ee.vertexIdxForBones+1],M.matricesIndices[4*O+2]=m[ee.vertexIdxForBones+2],M.matricesIndices[4*O+3]=m[ee.vertexIdxForBones+3]),v&&M.matricesIndicesExtra&&(M.matricesIndicesExtra[4*O]=v[ee.vertexIdxForBones],M.matricesIndicesExtra[4*O+1]=v[ee.vertexIdxForBones+1],M.matricesIndicesExtra[4*O+2]=v[ee.vertexIdxForBones+2],M.matricesIndicesExtra[4*O+3]=v[ee.vertexIdxForBones+3])),ee.matrixWeightsOverride?(M.matricesWeights[4*O]=ee.matrixWeightsOverride[0],M.matricesWeights[4*O+1]=ee.matrixWeightsOverride[1],M.matricesWeights[4*O+2]=ee.matrixWeightsOverride[2],M.matricesWeights[4*O+3]=ee.matrixWeightsOverride[3]):(g&&(M.matricesWeights[4*O]=g[ee.vertexIdxForBones],M.matricesWeights[4*O+1]=g[ee.vertexIdxForBones+1],M.matricesWeights[4*O+2]=g[ee.vertexIdxForBones+2],M.matricesWeights[4*O+3]=g[ee.vertexIdxForBones+3]),y&&M.matricesWeightsExtra&&(M.matricesWeightsExtra[4*O]=y[ee.vertexIdxForBones],M.matricesWeightsExtra[4*O+1]=y[ee.vertexIdxForBones+1],M.matricesWeightsExtra[4*O+2]=y[ee.vertexIdxForBones+2],M.matricesWeightsExtra[4*O+3]=y[ee.vertexIdxForBones+3]))),i.captureUVS)ee.uv.toArray(M.uvs,2*O);else{M.uvs.push(.5+ee.position.x/E.x);var te=.5+ee.position.y/E.y;M.uvs.push(go.UseOpenGLOrientationForUV?1-te:te)}O++}}}0===M.indices.length&&(M.indices=null),0===M.positions.length&&(M.positions=null),0===M.normals.length&&(M.normals=null),0===M.uvs.length&&(M.uvs=null),0===(null===(r=M.matricesIndices)||void 0===r?void 0:r.length)&&(M.matricesIndices=null),0===(null===(n=M.matricesWeights)||void 0===n?void 0:n.length)&&(M.matricesWeights=null),0===(null===(o=M.matricesIndicesExtra)||void 0===o?void 0:o.length)&&(M.matricesIndicesExtra=null),0===(null===(a=M.matricesWeightsExtra)||void 0===a?void 0:a.length)&&(M.matricesWeightsExtra=null);var ie=new Fa(e,t.getScene());return M.applyToMesh(ie),l?(ie.skeleton=t.skeleton,ie.parent=t):(ie.position=b.clone(),ie.rotation=new V(I,R,S)),ie.computeWorldMatrix(!0),ie.refreshBoundingInfo(!0,!0),ie}var Hd={CreateDecal:Wd};Fa.CreateDecal=function(e,t,i,r,n,o){return Wd(e,t,{position:i,normal:r,size:n,angle:o})};var Xd=function(){function e(e,t){void 0===e&&(e=0),void 0===t&&(t=0),this.x=e,this.y=t,e!==Math.floor(e)&&(Math.floor(e),ae.Warn("x is not an integer, floor(x) used")),t!==Math.floor(t)&&(Math.floor(t),ae.Warn("y is not an integer, floor(y) used"))}return e.prototype.clone=function(){return new e(this.x,this.y)},e.prototype.rotate60About=function(e){var t=this.x;return this.x=e.x+e.y-this.y,this.y=t+this.y-e.x,this},e.prototype.rotateNeg60About=function(e){var t=this.x;return this.x=t+this.y-e.y,this.y=e.x+e.y-t,this},e.prototype.rotate120=function(e,t){e!==Math.floor(e)&&(Math.floor(e),ae.Warn("m not an integer only floor(m) used")),t!==Math.floor(t)&&(Math.floor(t),ae.Warn("n not an integer only floor(n) used"));var i=this.x;return this.x=e-i-this.y,this.y=t+i,this},e.prototype.rotateNeg120=function(e,t){e!==Math.floor(e)&&(Math.floor(e),ae.Warn("m is not an integer, floor(m) used")),t!==Math.floor(t)&&(Math.floor(t),ae.Warn("n is not an integer, floor(n) used"));var i=this.x;return this.x=this.y-t,this.y=e+t-i-this.y,this},e.prototype.toCartesianOrigin=function(e,t){var i=V.Zero();return i.x=e.x+2*this.x*t+this.y*t,i.y=e.y+Math.sqrt(3)*this.y*t,i},e.Zero=function(){return new e(0,0)},e}(),jd=function(){function e(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new Yd("icosahedron","Regular",[[0,x,-1],[-x,1,0],[-1,0,-x],[1,0,-x],[x,1,0],[0,x,1],[-1,0,x],[-x,-1,0],[0,-x,-1],[x,-1,0],[1,0,x],[0,-x,1]],[[0,2,1],[0,3,2],[0,4,3],[0,5,4],[0,1,5],[7,6,1],[8,7,2],[9,8,3],[10,9,4],[6,10,5],[2,7,1],[3,8,2],[4,9,3],[5,10,4],[1,6,5],[11,6,7],[11,7,8],[11,8,9],[11,9,10],[11,10,6]])}return e.prototype.setIndices=function(){var e,t,i,r,n,o,a,s=12,l={},c=this.m,u=this.n,h=c;0!==u&&(h=j.HCF(c,u)),e=c/h,t=u/h;var d,p,f,_=Xd.Zero(),m=new Xd(c,u),g=new Xd(-u,c+u),v=Xd.Zero(),y=Xd.Zero(),b=Xd.Zero(),T=[],E=[],S=this.vertByDist,x=function(e,t,i,r){p=t+"|"+r,(d=e+"|"+i)in l||p in l?d in l&&!(p in l)?l[p]=l[d]:p in l&&!(d in l)&&(l[d]=l[p]):(l[d]=s,l[p]=s,s++),S[i][0]>2?E[l[d]]=[-S[i][0],S[i][1],l[d]]:E[l[d]]=[T[S[i][0]],S[i][1],l[d]]};this.IDATA.edgematch=[[1,"B"],[2,"B"],[3,"B"],[4,"B"],[0,"B"],[10,"O",14,"A"],[11,"O",10,"A"],[12,"O",11,"A"],[13,"O",12,"A"],[14,"O",13,"A"],[0,"O"],[1,"O"],[2,"O"],[3,"O"],[4,"O"],[19,"B",5,"A"],[15,"B",6,"A"],[16,"B",7,"A"],[17,"B",8,"A"],[18,"B",9,"A"]];for(var A=0;A<20;A++){if(n=(T=this.IDATA.face[A])[2],o=T[1],a=T[0],f=_.x+"|"+_.y,(d=A+"|"+f)in l||(l[d]=n,E[n]=[T[S[f][0]],S[f][1]]),f=m.x+"|"+m.y,(d=A+"|"+f)in l||(l[d]=o,E[o]=[T[S[f][0]],S[f][1]]),f=g.x+"|"+g.y,(d=A+"|"+f)in l||(l[d]=a,E[a]=[T[S[f][0]],S[f][1]]),i=this.IDATA.edgematch[A][0],"B"===(r=this.IDATA.edgematch[A][1]))for(var C=1;C<h;C++)y.x=c-C*(e+t),y.y=u+C*e,b.x=-C*t,b.y=C*(e+t),x(A,i,f=y.x+"|"+y.y,b.x+"|"+b.y);if("O"===r)for(C=1;C<h;C++)b.x=-C*t,b.y=C*(e+t),v.x=C*e,v.y=C*t,x(A,i,f=b.x+"|"+b.y,v.x+"|"+v.y);if(i=this.IDATA.edgematch[A][2],(r=this.IDATA.edgematch[A][3])&&"A"===r)for(C=1;C<h;C++)v.x=C*e,v.y=C*t,y.x=c-(h-C)*(e+t),y.y=u+(h-C)*e,x(A,i,f=v.x+"|"+v.y,y.x+"|"+y.y);for(C=0;C<this.vertices.length;C++)f=this.vertices[C].x+"|"+this.vertices[C].y,(d=A+"|"+f)in l||(l[d]=s++,S[f][0]>2?E[l[d]]=[-S[f][0],S[f][1],l[d]]:E[l[d]]=[T[S[f][0]],S[f][1],l[d]])}this.closestTo=E,this.vecToidx=l},e.prototype.calcCoeffs=function(){var e=this.m,t=this.n,i=Math.sqrt(3)/3,r=e*e+t*t+e*t;this.coau=(e+t)/r,this.cobu=-t/r,this.coav=-i*(e-t)/r,this.cobv=i*(2*e+t)/r},e.prototype.createInnerFacets=function(){for(var e=this.m,t=this.n,i=0;i<t+e+1;i++)for(var r=this.min[i];r<this.max[i]+1;r++)r<this.max[i]&&r<this.max[i+1]+1&&this.innerFacets.push(["|"+r+"|"+i,"|"+r+"|"+(i+1),"|"+(r+1)+"|"+i]),i>0&&r<this.max[i-1]&&r+1<this.max[i]+1&&this.innerFacets.push(["|"+r+"|"+i,"|"+(r+1)+"|"+i,"|"+(r+1)+"|"+(i-1)])},e.prototype.edgeVecsABOB=function(){for(var e=this.m,t=this.n,i=new Xd(-t,e+t),r=1;r<e+t;r++){var n=new Xd(this.min[r],r),o=new Xd(this.min[r-1],r-1),a=new Xd(this.min[r+1],r+1),s=n.clone(),l=o.clone(),c=a.clone();s.rotate60About(i),l.rotate60About(i),c.rotate60About(i);var u=new Xd(this.max[s.y],s.y),h=new Xd(this.max[s.y-1],s.y-1),d=new Xd(this.max[s.y-1]-1,s.y-1);s.x===u.x&&s.y===u.y||(s.x!==h.x?(this.vertexTypes.push([1,0,0]),this.isoVecsABOB.push([n,h,d]),this.vertexTypes.push([1,0,0]),this.isoVecsABOB.push([n,d,u])):s.y===c.y?(this.vertexTypes.push([1,1,0]),this.isoVecsABOB.push([n,o,h]),this.vertexTypes.push([1,0,1]),this.isoVecsABOB.push([n,h,a])):(this.vertexTypes.push([1,1,0]),this.isoVecsABOB.push([n,o,h]),this.vertexTypes.push([1,0,0]),this.isoVecsABOB.push([n,h,u])))}},e.prototype.mapABOBtoOBOA=function(){for(var e=new Xd(0,0),t=0;t<this.isoVecsABOB.length;t++){for(var i=[],r=0;r<3;r++)e.x=this.isoVecsABOB[t][r].x,e.y=this.isoVecsABOB[t][r].y,0===this.vertexTypes[t][r]&&e.rotateNeg120(this.m,this.n),i.push(e.clone());this.isoVecsOBOA.push(i)}},e.prototype.mapABOBtoBAOA=function(){for(var e=new Xd(0,0),t=0;t<this.isoVecsABOB.length;t++){for(var i=[],r=0;r<3;r++)e.x=this.isoVecsABOB[t][r].x,e.y=this.isoVecsABOB[t][r].y,1===this.vertexTypes[t][r]&&e.rotate120(this.m,this.n),i.push(e.clone());this.isoVecsBAOA.push(i)}},e.prototype.MapToFace=function(e,t){for(var i,r=this.IDATA.face[e],n=r[2],o=r[1],a=r[0],s=V.FromArray(this.IDATA.vertex[n]),l=V.FromArray(this.IDATA.vertex[o]),c=V.FromArray(this.IDATA.vertex[a]),u=l.subtract(s),h=c.subtract(s),d=u.scale(this.coau).add(h.scale(this.cobu)),p=u.scale(this.coav).add(h.scale(this.cobv)),f=[],_=H.Vector3[0],m=0;m<this.cartesian.length;m++)_=d.scale(this.cartesian[m].x).add(p.scale(this.cartesian[m].y)).add(s),f[m]=[_.x,_.y,_.z],i=e+"|"+this.vertices[m].x+"|"+this.vertices[m].y,t.vertex[this.vecToidx[i]]=[_.x,_.y,_.z]},e.prototype.build=function(e,t){var i=[],r=Xd.Zero(),n=new Xd(e,t),o=new Xd(-t,e+t);i.push(r,n,o);for(var a=t;a<e+1;a++)for(var s=0;s<e+1-a;s++)i.push(new Xd(s,a));if(t>0){for(var l=j.HCF(e,t),c=e/l,u=t/l,h=1;h<l;h++)i.push(new Xd(h*c,h*u)),i.push(new Xd(-h*u,h*(c+u))),i.push(new Xd(e-h*(c+u),t+h*c));for(var d=e/t,p=1;p<t;p++)for(var f=0;f<p*d;f++)i.push(new Xd(f,p)),i.push(new Xd(f,p).rotate120(e,t)),i.push(new Xd(f,p).rotateNeg120(e,t))}i.sort((function(e,t){return e.x-t.x})),i.sort((function(e,t){return e.y-t.y}));var _=new Array(e+t+1),m=new Array(e+t+1);for(h=0;h<_.length;h++)_[h]=1/0,m[h]=-1/0;var g=0,v=0,y=i.length;for(h=0;h<y;h++)v=i[h].x,_[g=i[h].y]=Math.min(v,_[g]),m[g]=Math.max(v,m[g]);var b=function(i,r){var n=i.clone();return"A"===r&&n.rotateNeg120(e,t),"B"===r&&n.rotate120(e,t),n.x<0?n.y:n.x+n.y},T=[],E=[],S=[],x=[],A={},C=[],R=-1,P=-1;for(h=0;h<y;h++)T[h]=i[h].toCartesianOrigin(new Xd(0,0),.5),E[h]=b(i[h],"O"),S[h]=b(i[h],"A"),x[h]=b(i[h],"B"),E[h]===S[h]&&S[h]===x[h]?(R=3,P=E[h]):E[h]===S[h]?(R=4,P=E[h]):S[h]===x[h]?(R=5,P=S[h]):x[h]===E[h]&&(R=6,P=E[h]),E[h]<S[h]&&E[h]<x[h]&&(R=2,P=E[h]),S[h]<E[h]&&S[h]<x[h]&&(R=1,P=S[h]),x[h]<S[h]&&x[h]<E[h]&&(R=0,P=x[h]),C.push([R,P,i[h].x,i[h].y]);C.sort((function(e,t){return e[2]-t[2]})),C.sort((function(e,t){return e[3]-t[3]})),C.sort((function(e,t){return e[1]-t[1]})),C.sort((function(e,t){return e[0]-t[0]}));for(var I=0;I<C.length;I++)A[C[I][2]+"|"+C[I][3]]=[C[I][0],C[I][1],I];return this.m=e,this.n=t,this.vertices=i,this.vertByDist=A,this.cartesian=T,this.min=_,this.max=m,this},e}(),Yd=function(e,t,i,r){this.name=e,this.category=t,this.vertex=i,this.face=r},Kd=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.prototype.innerToData=function(e,t){for(var i=0;i<t.innerFacets.length;i++)this.face.push(t.innerFacets[i].map((function(i){return t.vecToidx[e+i]})))},t.prototype.mapABOBtoDATA=function(e,t){for(var i=t.IDATA.edgematch[e][0],r=0;r<t.isoVecsABOB.length;r++){for(var n=[],o=0;o<3;o++)0===t.vertexTypes[r][o]?n.push(e+"|"+t.isoVecsABOB[r][o].x+"|"+t.isoVecsABOB[r][o].y):n.push(i+"|"+t.isoVecsABOB[r][o].x+"|"+t.isoVecsABOB[r][o].y);this.face.push([t.vecToidx[n[0]],t.vecToidx[n[1]],t.vecToidx[n[2]]])}},t.prototype.mapOBOAtoDATA=function(e,t){for(var i=t.IDATA.edgematch[e][0],r=0;r<t.isoVecsOBOA.length;r++){for(var n=[],o=0;o<3;o++)1===t.vertexTypes[r][o]?n.push(e+"|"+t.isoVecsOBOA[r][o].x+"|"+t.isoVecsOBOA[r][o].y):n.push(i+"|"+t.isoVecsOBOA[r][o].x+"|"+t.isoVecsOBOA[r][o].y);this.face.push([t.vecToidx[n[0]],t.vecToidx[n[1]],t.vecToidx[n[2]]])}},t.prototype.mapBAOAtoDATA=function(e,t){for(var i=t.IDATA.edgematch[e][2],r=0;r<t.isoVecsBAOA.length;r++){for(var n=[],o=0;o<3;o++)1===t.vertexTypes[r][o]?n.push(e+"|"+t.isoVecsBAOA[r][o].x+"|"+t.isoVecsBAOA[r][o].y):n.push(i+"|"+t.isoVecsBAOA[r][o].x+"|"+t.isoVecsBAOA[r][o].y);this.face.push([t.vecToidx[n[0]],t.vecToidx[n[1]],t.vecToidx[n[2]]])}},t.prototype.orderData=function(e){for(var t=[],i=0;i<13;i++)t[i]=[];var r=e.closestTo;for(i=0;i<r.length;i++)r[i][0]>-1?r[i][1]>0&&t[r[i][0]].push([i,r[i][1]]):t[12].push([i,r[i][0]]);var n=[];for(i=0;i<12;i++)n[i]=i;var o=12;for(i=0;i<12;i++){t[i].sort((function(e,t){return e[1]-t[1]}));for(var a=0;a<t[i].length;a++)n[t[i][a][0]]=o++}for(a=0;a<t[12].length;a++)n[t[12][a][0]]=o++;for(i=0;i<this.vertex.length;i++)this.vertex[i].push(n[i]);for(this.vertex.sort((function(e,t){return e[3]-t[3]})),i=0;i<this.vertex.length;i++)this.vertex[i].pop();for(i=0;i<this.face.length;i++)for(a=0;a<this.face[i].length;a++)this.face[i][a]=n[this.face[i][a]];this.sharedNodes=t[12].length,this.poleNodes=this.vertex.length-this.sharedNodes},t.prototype.setOrder=function(e,t){var i=[],r=[],n=t.pop();r.push(n);var o=this.face[n].indexOf(e);o=(o+2)%3;var a=this.face[n][o];i.push(a);for(var s=0;t.length>0;)n=t[s],this.face[n].indexOf(a)>-1?(o=(this.face[n].indexOf(a)+1)%3,a=this.face[n][o],i.push(a),r.push(n),t.splice(s,1),s=0):s++;return this.adjacentFaces.push(i),r},t.prototype.toGoldbergPolyhedronData=function(){var e=this,t=new Yd("GeoDual","Goldberg",[],[]);t.name="GD dual";for(var i=this.vertex.length,r=new Array(i),n=0;n<i;n++)r[n]=[];for(var o=0;o<this.face.length;o++)for(var a=0;a<3;a++)r[this.face[o][a]].push(o);var s=0,l=0,c=0,u=[],h=[];this.adjacentFaces=[];for(var d=0;d<r.length;d++)t.face[d]=this.setOrder(d,r[d].concat([])),r[d].forEach((function(i){s=0,l=0,c=0,u=e.face[i];for(var r=0;r<3;r++)h=e.vertex[u[r]],s+=h[0],l+=h[1],c+=h[2];t.vertex[i]=[s/3,l/3,c/3]}));return t},t.BuildGeodesicData=function(e){var i=new t("Geodesic-m-n","Geodesic",[[0,x,-1],[-x,1,0],[-1,0,-x],[1,0,-x],[x,1,0],[0,x,1],[-1,0,x],[-x,-1,0],[0,-x,-1],[x,-1,0],[1,0,x],[0,-x,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(var r=0;r<e.IDATA.face.length;r++)e.MapToFace(r,i),i.innerToData(r,e),"B"===e.IDATA.edgematch[r][1]&&i.mapABOBtoDATA(r,e),"O"===e.IDATA.edgematch[r][1]&&i.mapOBOAtoDATA(r,e),"A"===e.IDATA.edgematch[r][3]&&i.mapBAOAtoDATA(r,e);return i.orderData(e),i.vertex=i.vertex.map((function(e){var t=e[0],i=e[1],r=e[2],n=Math.sqrt(t*t+i*i+r*r);return e[0]*=1/n,e[1]*=1/n,e[2]*=1/n,e})),i},t}(Yd);function Qd(e,t,i){void 0===i&&(i=null);var r=t.m||1;r!==Math.floor(r)&&(Math.floor(r),ae.Warn("m not an integer only floor(m) used"));var n=t.n||0;if(n!==Math.floor(n)&&(Math.floor(n),ae.Warn("n not an integer only floor(n) used")),n>r){var o=n;n=r,r=o,ae.Warn("n > m therefore m and n swapped")}var a=new jd;return a.build(r,n),Fd(e,{custom:Kd.BuildGeodesicData(a),size:t.size,sizeX:t.sizeX,sizeY:t.sizeY,sizeZ:t.sizeZ,faceUV:t.faceUV,faceColors:t.faceColors,flat:t.flat,updatable:t.updatable,sideOrientation:t.sideOrientation,frontUVs:t.frontUVs,backUVs:t.backUVs},i)}Fa._GoldbergMeshParser=function(e,t){return qd.Parse(e,t)};var qd=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]},t}return m(t,e),t.prototype.relatedGoldbergFace=function(e,t){return void 0===t?(e>this.goldbergData.nbUnsharedFaces-1&&(ae.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(ae.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(ae.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)},t.prototype._changeGoldbergFaceColors=function(e){for(var t=0;t<e.length;t++)for(var i=e[t][0],r=e[t][1],n=e[t][2],o=i;o<r+1;o++)this.goldbergData.faceColors[o]=n;var a=[];for(o=0;o<12;o++)for(t=0;t<5;t++)a.push(this.goldbergData.faceColors[o].r,this.goldbergData.faceColors[o].g,this.goldbergData.faceColors[o].b,this.goldbergData.faceColors[o].a);for(o=12;o<this.goldbergData.faceColors.length;o++)for(t=0;t<6;t++)a.push(this.goldbergData.faceColors[o].r,this.goldbergData.faceColors[o].g,this.goldbergData.faceColors[o].b,this.goldbergData.faceColors[o].a);return a},t.prototype.setGoldbergFaceColors=function(e){var t=this._changeGoldbergFaceColors(e);this.setVerticesData(Nr.ColorKind,t)},t.prototype.updateGoldbergFaceColors=function(e){var t=this._changeGoldbergFaceColors(e);this.updateVerticesData(Nr.ColorKind,t)},t.prototype._changeGoldbergFaceUVs=function(e){for(var t=this.getVerticesData(Nr.UVKind),i=0;i<e.length;i++){for(var r=e[i][0],n=e[i][1],o=e[i][2],a=e[i][3],s=e[i][4],l=[],c=[],u=void 0,h=void 0,d=0;d<5;d++)u=o.x+a*Math.cos(s+d*Math.PI/2.5),h=o.y+a*Math.sin(s+d*Math.PI/2.5),u<0&&(u=0),u>1&&(u=1),l.push(u,h);for(d=0;d<6;d++)u=o.x+a*Math.cos(s+d*Math.PI/3),h=o.y+a*Math.sin(s+d*Math.PI/3),u<0&&(u=0),u>1&&(u=1),c.push(u,h);for(var p=r;p<Math.min(12,n+1);p++)for(d=0;d<5;d++)t[10*p+2*d]=l[2*d],t[10*p+2*d+1]=l[2*d+1];for(p=Math.max(12,r);p<n+1;p++)for(d=0;d<6;d++)t[12*p-24+2*d]=c[2*d],t[12*p-23+2*d]=c[2*d+1]}return t},t.prototype.setGoldbergFaceUVs=function(e){var t=this._changeGoldbergFaceUVs(e);this.setVerticesData(Nr.UVKind,t)},t.prototype.updateGoldbergFaceUVs=function(e){var t=this._changeGoldbergFaceUVs(e);this.updateVerticesData(Nr.UVKind,t)},t.prototype.placeOnGoldbergFaceAt=function(e,t,i){var r=V.RotationFromAxis(this.goldbergData.faceXaxis[t],this.goldbergData.faceYaxis[t],this.goldbergData.faceZaxis[t]);e.rotation=r,e.position=this.goldbergData.faceCenters[t].add(this.goldbergData.faceXaxis[t].scale(i.x)).add(this.goldbergData.faceYaxis[t].scale(i.y)).add(this.goldbergData.faceZaxis[t].scale(i.z))},t.prototype.serialize=function(t){e.prototype.serialize.call(this,t),t.type="GoldbergMesh";var i={};if(i.adjacentFaces=this.goldbergData.adjacentFaces,i.nbSharedFaces=this.goldbergData.nbSharedFaces,i.nbUnsharedFaces=this.goldbergData.nbUnsharedFaces,i.nbFaces=this.goldbergData.nbFaces,i.nbFacesAtPole=this.goldbergData.nbFacesAtPole,this.goldbergData.faceColors){i.faceColors=[];for(var r=0,n=this.goldbergData.faceColors;r<n.length;r++){var o=n[r];i.faceColors.push(o.asArray())}}if(this.goldbergData.faceCenters){i.faceCenters=[];for(var a=0,s=this.goldbergData.faceCenters;a<s.length;a++){var l=s[a];i.faceCenters.push(l.asArray())}}if(this.goldbergData.faceZaxis){i.faceZaxis=[];for(var c=0,u=this.goldbergData.faceZaxis;c<u.length;c++)l=u[c],i.faceZaxis.push(l.asArray())}if(this.goldbergData.faceYaxis){i.faceYaxis=[];for(var h=0,d=this.goldbergData.faceYaxis;h<d.length;h++)l=d[h],i.faceYaxis.push(l.asArray())}if(this.goldbergData.faceXaxis){i.faceXaxis=[];for(var p=0,f=this.goldbergData.faceXaxis;p<f.length;p++)l=f[p],i.faceXaxis.push(l.asArray())}t.goldbergData=i},t.Parse=function(e,i){var r=e.goldbergData;r.faceColors=r.faceColors.map((function(e){return J.FromArray(e)})),r.faceCenters=r.faceCenters.map((function(e){return V.FromArray(e)})),r.faceZaxis=r.faceZaxis.map((function(e){return V.FromArray(e)})),r.faceXaxis=r.faceXaxis.map((function(e){return V.FromArray(e)})),r.faceYaxis=r.faceYaxis.map((function(e){return V.FromArray(e)}));var n=new t(e.name,i);return n.goldbergData=r,n},t}(Fa);function Zd(e,t){for(var i=e.size,r=e.sizeX||i||1,n=e.sizeY||i||1,o=e.sizeZ||i||1,a=0===e.sideOrientation?0:e.sideOrientation||_o.DEFAULTSIDE,s=[],l=[],c=[],u=[],h=1/0,d=-1/0,p=1/0,f=-1/0,_=0;_<t.vertex.length;_++)h=Math.min(h,t.vertex[_][0]*r),d=Math.max(d,t.vertex[_][0]*r),p=Math.min(p,t.vertex[_][1]*n),f=Math.max(f,t.vertex[_][1]*n);for(var m=0,g=0;g<t.face.length;g++){var v=t.face[g],y=V.FromArray(t.vertex[v[0]]),b=V.FromArray(t.vertex[v[2]]),T=V.FromArray(t.vertex[v[1]]),E=b.subtract(y),S=T.subtract(y),x=V.Cross(S,E).normalize();for(_=0;_<v.length;_++){c.push(x.x,x.y,x.z);var A=t.vertex[v[_]];s.push(A[0]*r,A[1]*n,A[2]*o);var C=(A[1]*n-p)/(f-p);u.push((A[0]*r-h)/(d-h),go.UseOpenGLOrientationForUV?1-C:C)}for(_=0;_<v.length-2;_++)l.push(m,m+_+2,m+_+1);m+=v.length}_o._ComputeSides(a,s,l,c,u);var R=new _o;return R.positions=s,R.indices=l,R.normals=c,R.uvs=u,R}function Jd(e,t,i){void 0===i&&(i=null);var r=t.size,n=t.sizeX||r||1,o=t.sizeY||r||1,a=t.sizeZ||r||1,s=t.m||1;s!==Math.floor(s)&&(Math.floor(s),ae.Warn("m not an integer only floor(m) used"));var l=t.n||0;if(l!==Math.floor(l)&&(Math.floor(l),ae.Warn("n not an integer only floor(n) used")),l>s){var c=l;l=s,s=c,ae.Warn("n > m therefore m and n swapped")}var u=new jd;u.build(s,l);var h=Kd.BuildGeodesicData(u),d=h.toGoldbergPolyhedronData(),p=new qd(e,i);t.sideOrientation=Fa._GetDefaultSideOrientation(t.sideOrientation),p._originalBuilderSideOrientation=t.sideOrientation,Zd(t,d).applyToMesh(p,t.updatable),p.goldbergData.nbSharedFaces=h.sharedNodes,p.goldbergData.nbUnsharedFaces=h.poleNodes,p.goldbergData.adjacentFaces=h.adjacentFaces,p.goldbergData.nbFaces=p.goldbergData.nbSharedFaces+p.goldbergData.nbUnsharedFaces,p.goldbergData.nbFacesAtPole=(p.goldbergData.nbUnsharedFaces-12)/12;for(var f=0;f<h.vertex.length;f++)p.goldbergData.faceCenters.push(V.FromArray(h.vertex[f])),p.goldbergData.faceCenters[f].x*=n,p.goldbergData.faceCenters[f].y*=o,p.goldbergData.faceCenters[f].z*=a,p.goldbergData.faceColors.push(new J(1,1,1,1));for(f=0;f<d.face.length;f++){var _=d.face[f],m=V.FromArray(d.vertex[_[0]]),g=V.FromArray(d.vertex[_[2]]),v=V.FromArray(d.vertex[_[1]]),y=g.subtract(m),b=v.subtract(m),T=V.Cross(b,y).normalize(),E=V.Cross(b,T).normalize();p.goldbergData.faceXaxis.push(b.normalize()),p.goldbergData.faceYaxis.push(T),p.goldbergData.faceZaxis.push(E)}return p}var $d=function(){function e(e){this._paths=[],this._tempPaths=[],this._holes=[],this._resolution=e}return e.prototype.moveTo=function(e,t){this._currentPath=new xn(e,t),this._tempPaths.push(this._currentPath)},e.prototype.lineTo=function(e,t){this._currentPath.addLineTo(e,t)},e.prototype.quadraticCurveTo=function(e,t,i,r){this._currentPath.addQuadraticCurveTo(e,t,i,r,this._resolution)},e.prototype.bezierCurveTo=function(e,t,i,r,n,o){this._currentPath.addBezierCurveTo(e,t,i,r,n,o,this._resolution)},e.prototype.extractHoles=function(){for(var e=0,t=this._tempPaths;e<t.length;e++){var i=t[e];i.area()>0?this._holes.push(i):this._paths.push(i)}if(!this._paths.length&&this._holes.length){var r=this._holes;this._holes=this._paths,this._paths=r}this._tempPaths.length=0},Object.defineProperty(e.prototype,"paths",{get:function(){return this._paths},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"holes",{get:function(){return this._holes},enumerable:!1,configurable:!0}),e}();function ep(e,t,i,r,n,o){var a=o.glyphs[e]||o.glyphs["?"];if(!a)return null;var s=new $d(n);if(a.o)for(var l=a.o.split(" "),c=0,u=l.length;c<u;)switch(l[c++]){case"m":var h=parseInt(l[c++])*t+i,d=parseInt(l[c++])*t+r;s.moveTo(h,d);break;case"l":h=parseInt(l[c++])*t+i,d=parseInt(l[c++])*t+r,s.lineTo(h,d);break;case"q":var p=parseInt(l[c++])*t+i,f=parseInt(l[c++])*t+r,_=parseInt(l[c++])*t+i,m=parseInt(l[c++])*t+r;s.quadraticCurveTo(_,m,p,f);break;case"b":p=parseInt(l[c++])*t+i,f=parseInt(l[c++])*t+r,_=parseInt(l[c++])*t+i,m=parseInt(l[c++])*t+r;var g=parseInt(l[c++])*t+i,v=parseInt(l[c++])*t+r;s.bezierCurveTo(_,m,g,v,p,f)}return s.extractHoles(),{offsetX:a.ha*t,shapePath:s}}function tp(e,t,i,r){for(var n=Array.from(e),o=t/r.resolution,a=(r.boundingBox.yMax-r.boundingBox.yMin+r.underlineThickness)*o,s=[],l=0,c=0,u=0;u<n.length;u++){var h=n[u];if("\n"===h)l=0,c-=a;else{var d=ep(h,o,l,c,i,r);d&&(l+=d.offsetX,s.push(d.shapePath))}}return s}function ip(e,t,i,r,n,o){var a,s;void 0===r&&(r={size:50,resolution:8,depth:1}),void 0===n&&(n=null),void 0===o&&(o=earcut);for(var l=[],c=0,u=0,h=tp(t,r.size||50,r.resolution||8,i);u<h.length;u++){var d=h[u];if(d.paths.length)for(var p=d.holes.slice(),f=0,_=d.paths;f<_.length;f++){for(var m=_[f],g=[],v=[],y=0,b=m.getPoints();y<b.length;y++){var T=b[y];v.push(new V(T.x,0,T.y))}for(var E=0,S=p.slice();E<S.length;E++){for(var x=(N=S[E]).getPoints(),A=!1,C=0,R=x;C<R.length;C++)if(T=R[C],m.isPointInside(T)){A=!0;break}if(A){for(var P=[],I=0,M=x;I<M.length;I++)T=M[I],P.push(new V(T.x,0,T.y));g.push(P),p.splice(p.indexOf(N),1)}}if(!g.length&&p.length)for(var O=0,D=p;O<D.length;O++){P=[];for(var N,F=0,L=(N=D[O]).getPoints();F<L.length;F++)T=L[F],P.push(new V(T.x,0,T.y));g.push(P)}var w=Sd(e,{shape:v,holes:g.length?g:void 0,depth:r.depth||1,faceUV:r.faceUV||(null===(a=r.perLetterFaceUV)||void 0===a?void 0:a.call(r,c)),faceColors:r.faceColors||(null===(s=r.perLetterFaceColors)||void 0===s?void 0:s.call(r,c)),sideOrientation:Fa._GetDefaultSideOrientation(r.sideOrientation||Fa.DOUBLESIDE)},n,o);l.push(w),c++}}var B=Fa.MergeMeshes(l,!0,!0);if(B){var U=B.getBoundingInfo().boundingBox;B.position.x+=-(U.minimumWorld.x+U.maximumWorld.x)/2,B.position.y+=-(U.minimumWorld.y+U.maximumWorld.y)/2,B.position.z+=-(U.minimumWorld.z+U.maximumWorld.z)/2+U.extendSize.z,B.name=e;var k=new Fo("pivot",n);k.rotation.x=-Math.PI/2,B.parent=k,B.bakeCurrentTransformIntoVertices(),B.parent=null,k.dispose()}return B}var rp={CreateBox:Uh,CreateTiledBox:id,CreateSphere:Gh,CreateDisc:qh,CreateIcoSphere:Bl,CreateRibbon:Yh,CreateCylinder:xh,CreateTorus:sh,CreateTorusKnot:od,CreateLineSystem:pd,CreateLines:fd,CreateDashedLines:_d,ExtrudeShape:Ad,ExtrudeShapeCustom:Cd,CreateLathe:Id,CreateTiledPlane:$h,CreatePlane:fs,CreateGround:ih,CreateTiledGround:rh,CreateGroundFromHeightMap:nh,CreatePolygon:Ed,ExtrudePolygon:Sd,CreateTube:Od,CreatePolyhedron:Fd,CreateGeodesic:Qd,CreateGoldberg:Jd,CreateDecal:Wd,CreateCapsule:Hh,CreateText:ip},np=function(){function e(e){if(this._impostors=[],this._meshes=[],this._bodies=[],this._inertiaBodies=[],this._constraints=[],this._bodyMeshes=[],this._inertiaMeshes=[],this._constraintMeshes=[],this._numMeshes=0,this._numBodies=0,this._numInertiaBodies=0,this._numConstraints=0,this._debugMeshMeshes=new Array,this._constraintAxesSize=.4,this._scene=e||M.LastCreatedScene,this._scene){var t=this._scene.getPhysicsEngine();t&&(this._physicsEnginePlugin=t.getPhysicsPlugin()),this._utilityLayer=new Ih(this._scene,!1),this._utilityLayer.pickUtilitySceneFirst=!1,this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil=!0}}return e.prototype._updateDebugMeshes=function(){var e=this._physicsEnginePlugin;1===(null==e?void 0:e.getPluginVersion())?this._updateDebugMeshesV1():this._updateDebugMeshesV2()},e.prototype._updateDebugMeshesV1=function(){for(var e=this._physicsEnginePlugin,t=0;t<this._numMeshes;t++){var i=this._impostors[t];if(i)if(i.isDisposed)this.hideImpostor(this._impostors[t--]);else{if(i.type===Ds.MeshImpostor)continue;var r=this._meshes[t];r&&e&&e.syncMeshWithImpostor(r,i)}}},e.prototype._updateDebugMeshesV2=function(){for(var e=this._physicsEnginePlugin,t=0;t<this._numBodies;t++){var i=this._bodies[t],r=this._bodyMeshes[t];i&&r&&e.syncTransform(i,r)}},e.prototype._updateInertiaMeshes=function(){for(var e=0;e<this._numInertiaBodies;e++){var t=this._inertiaBodies[e],i=this._inertiaMeshes[e];t&&i&&this._updateDebugInertia(t,i)}},e.prototype._updateDebugInertia=function(e,t){var i,r=z.Identity(),n=z.Identity(),o=z.Identity();if(e._pluginDataInstances.length){for(var a=t,s=a._thinInstanceDataStorage.matrixData,l=e.transformNode._thinInstanceDataStorage.matrixData,c=0;c<e._pluginDataInstances.length;c++){var u=e.getMassProperties(c);this._getMeshDebugInertiaMatrixToRef(u,r),z.FromArrayToRef(l,16*c,n),r.multiplyToRef(n,o),o.copyToArray(s,16*c)}a.thinInstanceBufferUpdated("matrix")}else{if(u=e.getMassProperties(),this._getMeshDebugInertiaMatrixToRef(u,r),null===(i=e.transformNode.rotationQuaternion)||void 0===i||i.toRotationMatrix(n),n.setTranslation(e.transformNode.position),e.transformNode.parent){var h=e.transformNode.parent.computeWorldMatrix(!0);n.multiplyToRef(h,n)}r.multiplyToRef(n,r),r.decomposeToTransformNode(t)}},e.prototype._updateDebugConstraints=function(){for(var e=0;e<this._numConstraints;e++){var t=this._constraints[e],i=this._constraintMeshes[e];t&&i&&this._updateDebugConstraint(t,i)}},e.prototype._makeScalingUnitInPlace=function(e){Math.abs(e.x-1)>A&&(e.x=1*Math.sign(e.x)),Math.abs(e.y-1)>A&&(e.y=1*Math.sign(e.y)),Math.abs(e.z-1)>A&&(e.z=1*Math.sign(e.z))},e.prototype._updateDebugConstraint=function(e,t){var i=this;if(e._initOptions){var r=e._initOptions,n=r.pivotA,o=r.pivotB,a=r.axisA,s=r.axisB,l=r.perpAxisA,c=r.perpAxisB;n&&o&&a&&s&&l&&c&&t.getDescendants(!0).forEach((function(e){var t=e.getDescendants(!0)[0],r=e.getDescendants(!0)[1],u=t.metadata,h=u.parentBody,d=u.parentBodyIndex,p=r.metadata,f=p.childBody,_=p.childBodyIndex,m=i._getTransformFromBodyToRef(h,H.Matrix[0],d),g=i._getTransformFromBodyToRef(f,H.Matrix[1],_);m.decomposeToTransformNode(t),i._makeScalingUnitInPlace(t.scaling),g.decomposeToTransformNode(r),i._makeScalingUnitInPlace(r.scaling);var v=t.getDescendants(!0)[0];v.position.copyFrom(n);var y=r.getDescendants(!0)[0];y.position.copyFrom(o),G.FromRotationMatrixToRef(z.FromXYZAxesToRef(a,l,V.CrossToRef(a,l,H.Vector3[0]),H.Matrix[0]),v.rotationQuaternion),G.FromRotationMatrixToRef(z.FromXYZAxesToRef(s,c,V.CrossToRef(s,c,H.Vector3[1]),H.Matrix[1]),y.rotationQuaternion)}))}},e.prototype.showImpostor=function(e,t){var i=this;if(!this._scene)return null;for(var r=0;r<this._numMeshes;r++)if(this._impostors[r]==e)return null;var n=this._getDebugMesh(e,t);return n&&(this._impostors[this._numMeshes]=e,this._meshes[this._numMeshes]=n,0===this._numMeshes&&(this._renderFunction=function(){return i._updateDebugMeshes()},this._scene.registerBeforeRender(this._renderFunction)),this._numMeshes++),n},e.prototype.showBody=function(e){var t=this;if(!this._scene)return null;for(var i=0;i<this._numBodies;i++)if(this._bodies[i]==e)return null;var r=this._getDebugBodyMesh(e);return r&&(this._bodies[this._numBodies]=e,this._bodyMeshes[this._numBodies]=r,0===this._numBodies&&(this._renderFunction=function(){return t._updateDebugMeshes()},this._scene.registerBeforeRender(this._renderFunction)),this._numBodies++),r},e.prototype.showInertia=function(e){var t=this;if(!this._scene)return null;for(var i=0;i<this._numInertiaBodies;i++)if(this._inertiaBodies[i]==e)return null;var r=this._getDebugInertiaMesh(e);return r&&(this._inertiaBodies[this._numInertiaBodies]=e,this._inertiaMeshes[this._numInertiaBodies]=r,0===this._numInertiaBodies&&(this._inertiaRenderFunction=function(){return t._updateInertiaMeshes()},this._scene.registerBeforeRender(this._inertiaRenderFunction)),this._numInertiaBodies++),r},e.prototype.showConstraint=function(e){var t=this;if(!this._scene)return null;for(var i=0;i<this._numConstraints;i++)if(this._constraints[i]==e)return null;var r=this._getDebugConstraintMesh(e);return r&&(this._constraints[this._numConstraints]=e,this._constraintMeshes[this._numConstraints]=r,0===this._numConstraints&&(this._constraintRenderFunction=function(){return t._updateDebugConstraints()},this._scene.registerBeforeRender(this._constraintRenderFunction)),this._numConstraints++),r},e.prototype.hideImpostor=function(e){if(e&&this._scene&&this._utilityLayer){for(var t=!1,i=this._utilityLayer.utilityLayerScene,r=0;r<this._numMeshes;r++)if(this._impostors[r]==e){var n=this._meshes[r];if(!n)continue;i.removeMesh(n),n.dispose();var o=this._debugMeshMeshes.indexOf(n);o>-1&&this._debugMeshMeshes.splice(o,1),this._numMeshes--,this._numMeshes>0?(this._meshes[r]=this._meshes[this._numMeshes],this._impostors[r]=this._impostors[this._numMeshes],this._meshes[this._numMeshes]=null,this._impostors[this._numMeshes]=null):(this._meshes[0]=null,this._impostors[0]=null),t=!0;break}t&&0===this._numMeshes&&this._scene.unregisterBeforeRender(this._renderFunction)}},e.prototype.hideBody=function(e){if(e&&this._scene&&this._utilityLayer){for(var t=!1,i=this._utilityLayer.utilityLayerScene,r=0;r<this._numBodies;r++)if(this._bodies[r]===e){var n=this._bodyMeshes[r];if(!n)continue;i.removeMesh(n),n.dispose(),this._numBodies--,this._numBodies>0?(this._bodyMeshes[r]=this._bodyMeshes[this._numBodies],this._bodies[r]=this._bodies[this._numBodies],this._bodyMeshes[this._numBodies]=null,this._bodies[this._numBodies]=null):(this._bodyMeshes[0]=null,this._bodies[0]=null),t=!0;break}t&&0===this._numBodies&&this._scene.unregisterBeforeRender(this._renderFunction)}},e.prototype.hideInertia=function(e){if(e&&this._scene&&this._utilityLayer){for(var t=!1,i=this._utilityLayer.utilityLayerScene,r=0;r<this._numInertiaBodies;r++)if(this._inertiaBodies[r]===e){var n=this._inertiaMeshes[r];if(!n)continue;i.removeMesh(n),n.dispose(),this._inertiaBodies.splice(r,1),this._inertiaMeshes.splice(r,1),this._numInertiaBodies--,t=!0;break}t&&0===this._numInertiaBodies&&this._scene.unregisterBeforeRender(this._inertiaRenderFunction)}},e.prototype.hideConstraint=function(e){if(e&&this._scene&&this._utilityLayer){for(var t=!1,i=this._utilityLayer.utilityLayerScene,r=0;r<this._numConstraints;r++)if(this._constraints[r]===e){var n=this._constraintMeshes[r];if(!n)continue;i.removeMesh(n),n.dispose(),this._constraints.splice(r,1),this._constraintMeshes.splice(r,1),this._numConstraints--,this._numConstraints>0?(this._constraints[r]=this._constraints[this._numConstraints],this._constraintMeshes[r]=this._constraintMeshes[this._numConstraints],this._constraints[this._numConstraints]=null,this._constraintMeshes[this._numConstraints]=null):(this._constraints[0]=null,this._constraintMeshes[0]=null),t=!0;break}t&&0===this._numConstraints&&this._scene.unregisterBeforeRender(this._constraintRenderFunction)}},e.prototype._getDebugMaterial=function(e){return this._debugMaterial||(this._debugMaterial=new Uu("",e),this._debugMaterial.wireframe=!0,this._debugMaterial.emissiveColor=Z.White(),this._debugMaterial.disableLighting=!0),this._debugMaterial},e.prototype._getDebugInertiaMaterial=function(e){return this._debugInertiaMaterial||(this._debugInertiaMaterial=new Uu("",e),this._debugInertiaMaterial.disableLighting=!0,this._debugInertiaMaterial.alpha=0),this._debugInertiaMaterial},e.prototype._getDebugBoxMesh=function(e){return this._debugBoxMesh||(this._debugBoxMesh=Uh("physicsBodyBoxViewMesh",{size:1},e),this._debugBoxMesh.rotationQuaternion=G.Identity(),this._debugBoxMesh.material=this._getDebugMaterial(e),this._debugBoxMesh.setEnabled(!1)),this._debugBoxMesh.createInstance("physicsBodyBoxViewInstance")},e.prototype._getDebugSphereMesh=function(e){return this._debugSphereMesh||(this._debugSphereMesh=Gh("physicsBodySphereViewMesh",{diameter:1},e),this._debugSphereMesh.rotationQuaternion=G.Identity(),this._debugSphereMesh.material=this._getDebugMaterial(e),this._debugSphereMesh.setEnabled(!1)),this._debugSphereMesh.createInstance("physicsBodySphereViewInstance")},e.prototype._getDebugCapsuleMesh=function(e){return this._debugCapsuleMesh||(this._debugCapsuleMesh=Hh("physicsBodyCapsuleViewMesh",{height:1},e),this._debugCapsuleMesh.rotationQuaternion=G.Identity(),this._debugCapsuleMesh.material=this._getDebugMaterial(e),this._debugCapsuleMesh.setEnabled(!1)),this._debugCapsuleMesh.createInstance("physicsBodyCapsuleViewInstance")},e.prototype._getDebugCylinderMesh=function(e){return this._debugCylinderMesh||(this._debugCylinderMesh=xh("physicsBodyCylinderViewMesh",{diameterTop:1,diameterBottom:1,height:1},e),this._debugCylinderMesh.rotationQuaternion=G.Identity(),this._debugCylinderMesh.material=this._getDebugMaterial(e),this._debugCylinderMesh.setEnabled(!1)),this._debugCylinderMesh.createInstance("physicsBodyCylinderViewInstance")},e.prototype._getDebugMeshMesh=function(e,t){var i=new Fa(e.name,t,null,e);return i.setParent(e),i.position=V.Zero(),i.material=this._getDebugMaterial(t),this._debugMeshMeshes.push(i),i},e.prototype._getDebugMesh=function(e,t){var i=this;if(!this._utilityLayer)return null;if(t&&t.parent&&t.parent.physicsImpostor)return null;var r=null,n=this._utilityLayer.utilityLayerScene;if(!e.physicsBody)return ae.Warn("Unable to get physicsBody of impostor. It might be initialized later by its parent's impostor."),null;switch(e.type){case Ds.BoxImpostor:r=this._getDebugBoxMesh(n),e.getBoxSizeToRef(r.scaling);break;case Ds.SphereImpostor:r=this._getDebugSphereMesh(n);var o=e.getRadius();r.scaling.x=2*o,r.scaling.y=2*o,r.scaling.z=2*o;break;case Ds.CapsuleImpostor:r=this._getDebugCapsuleMesh(n);var a=e.object.getBoundingInfo();r.scaling.x=2*(a.boundingBox.maximum.x-a.boundingBox.minimum.x)*e.object.scaling.x,r.scaling.y=(a.boundingBox.maximum.y-a.boundingBox.minimum.y)*e.object.scaling.y,r.scaling.z=2*(a.boundingBox.maximum.z-a.boundingBox.minimum.z)*e.object.scaling.z;break;case Ds.MeshImpostor:t&&(r=this._getDebugMeshMesh(t,n));break;case Ds.NoImpostor:t?t.getChildMeshes().filter((function(e){return e.physicsImpostor?1:0})).forEach((function(e){if(e.physicsImpostor&&"Mesh"===e.getClassName()){var t=e.getBoundingInfo(),o=t.boundingBox.minimum,a=t.boundingBox.maximum;switch(e.physicsImpostor.type){case Ds.BoxImpostor:(r=i._getDebugBoxMesh(n)).position.copyFrom(o),r.position.addInPlace(a),r.position.scaleInPlace(.5);break;case Ds.SphereImpostor:r=i._getDebugSphereMesh(n);break;case Ds.CylinderImpostor:r=i._getDebugCylinderMesh(n);break;default:r=null}r&&(r.scaling.x=a.x-o.x,r.scaling.y=a.y-o.y,r.scaling.z=a.z-o.z,r.parent=e)}})):ae.Warn("No target mesh parameter provided for NoImpostor. Skipping."),r=null;break;case Ds.CylinderImpostor:r=this._getDebugCylinderMesh(n),a=e.object.getBoundingInfo(),r.scaling.x=(a.boundingBox.maximum.x-a.boundingBox.minimum.x)*e.object.scaling.x,r.scaling.y=(a.boundingBox.maximum.y-a.boundingBox.minimum.y)*e.object.scaling.y,r.scaling.z=(a.boundingBox.maximum.z-a.boundingBox.minimum.z)*e.object.scaling.z}return r},e.prototype._getDebugBodyMesh=function(e){if(!this._utilityLayer)return null;var t=this._utilityLayer.utilityLayerScene,i=new Fa("custom",t),r=new _o,n=e.getGeometry();if(r.positions=n.positions,r.indices=n.indices,r.applyToMesh(i),e._pluginDataInstances){var o=new Float32Array(16*e._pluginDataInstances.length);i.thinInstanceSetBuffer("matrix",o,16,!1)}return i.material=this._getDebugMaterial(t),i},e.prototype._getMeshDebugInertiaMatrixToRef=function(e,t){var i,r,n,o=null!==(i=e.inertiaOrientation)&&void 0!==i?i:G.Identity(),a=null!==(r=e.inertia)&&void 0!==r?r:V.Zero(),s=null!==(n=e.centerOfMass)&&void 0!==n?n:V.Zero(),l=6*(a.x-a.y+a.z),c=Math.sqrt(Math.max(l,0)),u=12*a.x-l,h=Math.sqrt(Math.max(u,0)),d=12*a.z-l,p=Math.sqrt(Math.max(d,0)),f=H.Vector3[0];f.set(p,c,h);var _=z.ScalingToRef(f.x,f.y,f.z,H.Matrix[0]),m=o.toRotationMatrix(H.Matrix[1]),g=z.TranslationToRef(s.x,s.y,s.z,H.Matrix[2]);return _.multiplyToRef(m,t),t.multiplyToRef(g,t),t},e.prototype._getDebugInertiaMesh=function(e){if(!this._utilityLayer)return null;var t=this._utilityLayer.utilityLayerScene,i=rp.CreateBox("custom",{size:1},t),r=z.Identity();if(e._pluginDataInstances.length){for(var n=new Float32Array(16*e._pluginDataInstances.length),o=0;o<e._pluginDataInstances.length;++o){var a=e.getMassProperties(o);this._getMeshDebugInertiaMatrixToRef(a,r),r.copyToArray(n,16*o)}i.thinInstanceSetBuffer("matrix",n,16,!1)}else a=e.getMassProperties(),this._getMeshDebugInertiaMatrixToRef(a,r),r.decomposeToTransformNode(i);return i.enableEdgesRendering(),i.edgesWidth=2,i.edgesColor=new J(1,0,1,1),i.material=this._getDebugInertiaMaterial(t),i},e.prototype._getTransformFromBodyToRef=function(e,t,i){var r=e.transformNode;return i&&i>=0?z.FromArrayToRef(r._thinInstanceDataStorage.matrixData,i,t):t.copyFrom(r.getWorldMatrix())},e.prototype._getDebugConstraintMesh=function(e){if(!this._utilityLayer)return null;var t=this._utilityLayer.utilityLayerScene;if(!e._initOptions)return null;var i=e._initOptions,r=i.pivotA,n=i.pivotB,o=i.axisA,a=i.axisB,s=i.perpAxisA,l=i.perpAxisB;if(!(r&&n&&o&&a&&s&&l))return null;for(var c=new Fa("parentingDebugConstraint",t),u=0,h=e.getBodiesUsingConstraint();u<h.length;u++){var d=h[u],p=new Fo("parentOfPair",t);p.parent=c;var f=d.parentBody,_=d.parentBodyIndex,m=d.childBody,g=d.childBodyIndex,v=this._getTransformFromBodyToRef(f,H.Matrix[0],_),y=this._getTransformFromBodyToRef(m,H.Matrix[1],g),b=new Fo("parentCoordSystem",t);b.parent=p,b.metadata={parentBody:f,parentBodyIndex:_},v.decomposeToTransformNode(b);var T=new Fo("childCoordSystem",t);T.parent=p,T.metadata={childBody:m,childBodyIndex:g},y.decomposeToTransformNode(T);var E=G.FromRotationMatrix(z.FromXYZAxesToRef(o,s,o.cross(s),H.Matrix[0])),S=G.FromRotationMatrix(z.FromXYZAxesToRef(a,l,a.cross(l),H.Matrix[0])),x=r,A=n,C=new Fo("constraint_parent",t);C.position.copyFrom(x),C.rotationQuaternion=E,C.parent=b;var R=new Fo("constraint_child",t);R.parent=T,R.position.copyFrom(A),R.rotationQuaternion=S;var P=new Nh(t,this._constraintAxesSize);P.xAxis.parent=C,P.yAxis.parent=C,P.zAxis.parent=C;var I=new Nh(t,this._constraintAxesSize);I.xAxis.parent=R,I.yAxis.parent=R,I.zAxis.parent=R}return c},e.prototype.dispose=function(){for(var e=this._numMeshes-1;e>=0;e--)this.hideImpostor(this._impostors[0]);for(e=this._numBodies-1;e>=0;e--)this.hideBody(this._bodies[0]);for(e=this._numInertiaBodies-1;e>=0;e--)this.hideInertia(this._inertiaBodies[0]);this._debugBoxMesh&&this._debugBoxMesh.dispose(),this._debugSphereMesh&&this._debugSphereMesh.dispose(),this._debugCylinderMesh&&this._debugCylinderMesh.dispose(),this._debugMaterial&&this._debugMaterial.dispose(),this._impostors.length=0,this._scene=null,this._physicsEnginePlugin=null,this._utilityLayer&&(this._utilityLayer.dispose(),this._utilityLayer=null)},e}(),op=function(){function e(e){this.ray=e}return e.CreateAndShow=function(t,i,r){var n=new e(t);return n.show(i,r),n},e.prototype.show=function(e,t){var i=this;if(!this._renderFunction&&this.ray){var r=this.ray;this._renderFunction=function(){return i._render()},this._scene=e,this._renderPoints=[r.origin,r.origin.add(r.direction.scale(r.length))],this._renderLine=fd("ray",{points:this._renderPoints,updatable:!0},e),this._renderLine.isPickable=!1,this._renderFunction&&this._scene.registerBeforeRender(this._renderFunction)}t&&this._renderLine&&this._renderLine.color.copyFrom(t)},e.prototype.hide=function(){this._renderFunction&&this._scene&&(this._scene.unregisterBeforeRender(this._renderFunction),this._scene=null,this._renderFunction=null,this._renderLine&&(this._renderLine.dispose(),this._renderLine=null),this._renderPoints=[])},e.prototype._render=function(){var e,t=this.ray;if(t){var i=this._renderPoints[1],r=Math.min(t.length,1e6);i.copyFrom(t.direction),i.scaleInPlace(r),i.addInPlace(t.origin),this._renderPoints[0].copyFrom(t.origin),fd("ray",{points:this._renderPoints,updatable:!0,instance:this._renderLine},this._scene),null===(e=this._renderLine)||void 0===e||e.refreshBoundingInfo()}},e.prototype.attachToMesh=function(e,t,i,r){var n=this;this._attachedToMesh=e;var o=this.ray;o&&(o.direction||(o.direction=V.Zero()),o.origin||(o.origin=V.Zero()),r&&(o.length=r),i||(i=V.Zero()),t||(t=new V(0,0,-1)),this._scene||(this._scene=e.getScene()),this._meshSpaceDirection?(this._meshSpaceDirection.copyFrom(t),this._meshSpaceOrigin.copyFrom(i)):(this._meshSpaceDirection=t.clone(),this._meshSpaceOrigin=i.clone()),this._onAfterRenderObserver||(this._onAfterRenderObserver=this._scene.onBeforeRenderObservable.add((function(){return n._updateToMesh()})),this._onAfterStepObserver=this._scene.onAfterStepObservable.add((function(){return n._updateToMesh()}))),this._attachedToMesh.computeWorldMatrix(!0),this._updateToMesh())},e.prototype.detachFromMesh=function(){this._attachedToMesh&&this._scene&&(this._onAfterRenderObserver&&(this._scene.onBeforeRenderObservable.remove(this._onAfterRenderObserver),this._scene.onAfterStepObservable.remove(this._onAfterStepObserver)),this._attachedToMesh=null,this._onAfterRenderObserver=null,this._onAfterStepObserver=null,this._scene=null)},e.prototype._updateToMesh=function(){var e=this.ray;this._attachedToMesh&&e&&(this._attachedToMesh.isDisposed()?this.detachFromMesh():(this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection,e.direction),V.TransformCoordinatesToRef(this._meshSpaceOrigin,this._attachedToMesh.getWorldMatrix(),e.origin)))},e.prototype.dispose=function(){this.hide(),this.detachFromMesh(),this.ray=null},e}(),ap=function(){function e(t,i,r,n,o,a){var s,l,c,u,h,d,p,f,_,m,g,v,y,b;if(void 0===n&&(n=!0),void 0===o&&(o=3),void 0===a&&(a={}),this.skeleton=t,this.mesh=i,this.autoUpdateBonesMatrices=n,this.renderingGroupId=o,this.options=a,this.color=Z.White(),this._debugLines=new Array,this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=r,this._ready=!1,a.pauseAnimations=null===(s=a.pauseAnimations)||void 0===s||s,a.returnToRest=null!==(l=a.returnToRest)&&void 0!==l&&l,a.displayMode=null!==(c=a.displayMode)&&void 0!==c?c:e.DISPLAY_LINES,a.displayOptions=null!==(u=a.displayOptions)&&void 0!==u?u:{},a.displayOptions.midStep=null!==(h=a.displayOptions.midStep)&&void 0!==h?h:.235,a.displayOptions.midStepFactor=null!==(d=a.displayOptions.midStepFactor)&&void 0!==d?d:.155,a.displayOptions.sphereBaseSize=null!==(p=a.displayOptions.sphereBaseSize)&&void 0!==p?p:.15,a.displayOptions.sphereScaleUnit=null!==(f=a.displayOptions.sphereScaleUnit)&&void 0!==f?f:2,a.displayOptions.sphereFactor=null!==(_=a.displayOptions.sphereFactor)&&void 0!==_?_:.865,a.displayOptions.spurFollowsChild=null!==(m=a.displayOptions.spurFollowsChild)&&void 0!==m&&m,a.displayOptions.showLocalAxes=null!==(g=a.displayOptions.showLocalAxes)&&void 0!==g&&g,a.displayOptions.localAxesSize=null!==(v=a.displayOptions.localAxesSize)&&void 0!==v?v:.075,a.computeBonesUsingShaders=null===(y=a.computeBonesUsingShaders)||void 0===y||y,a.useAllBones=null===(b=a.useAllBones)||void 0===b||b,this._boneIndices=new Set,!a.useAllBones){var T=null==i?void 0:i.getVerticesData(Nr.MatricesIndicesKind),E=null==i?void 0:i.getVerticesData(Nr.MatricesWeightsKind);if(T&&E)for(var S=0;S<T.length;++S){var x=T[S];0!==E[S]&&this._boneIndices.add(x)}}this._utilityLayer=new Ih(this._scene,!1),this._utilityLayer.pickUtilitySceneFirst=!1,this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil=!0;var A=this.options.displayMode||0;A>e.DISPLAY_SPHERE_AND_SPURS&&(A=e.DISPLAY_LINES),this.displayMode=A,this.update(),this._bindObs()}return e.CreateBoneWeightShader=function(e,t){var i,r,n,o,a,s,l=e.skeleton,c=null!==(i=e.colorBase)&&void 0!==i?i:Z.Black(),u=null!==(r=e.colorZero)&&void 0!==r?r:Z.Blue(),h=null!==(n=e.colorQuarter)&&void 0!==n?n:Z.Green(),d=null!==(o=e.colorHalf)&&void 0!==o?o:Z.Yellow(),p=null!==(a=e.colorFull)&&void 0!==a?a:Z.Red(),f=null!==(s=e.targetBoneIndex)&&void 0!==s?s:0;Ei.ShadersStore["boneWeights:"+l.name+"VertexShader"]="precision highp float;\n\n attribute vec3 position;\n attribute vec2 uv;\n\n uniform mat4 view;\n uniform mat4 projection;\n uniform mat4 worldViewProjection;\n\n #include<bonesDeclaration>\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include<bakedVertexAnimationDeclaration>\n\n #include<instancesDeclaration>\n\n varying vec3 vColor;\n\n uniform vec3 colorBase;\n uniform vec3 colorZero;\n uniform vec3 colorQuarter;\n uniform vec3 colorHalf;\n uniform vec3 colorFull;\n\n uniform float targetBoneIndex;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include<instancesVertex>\n #include<bonesVertex>\n #include<bakedVertexAnimation>\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n vec3 color = colorBase;\n float totalWeight = 0.;\n if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){\n totalWeight += matricesWeights[0];\n }\n if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){\n totalWeight += matricesWeights[1];\n }\n if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){\n totalWeight += matricesWeights[2];\n }\n if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){\n totalWeight += matricesWeights[3];\n }\n\n color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight));\n color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight));\n color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight));\n color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight));\n vColor = color;\n\n gl_Position = projection * view * worldPos;\n }",Ei.ShadersStore["boneWeights:"+l.name+"FragmentShader"]="\n precision highp float;\n varying vec3 vPosition;\n\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4(vColor, 1.0);\n gl_FragColor = color;\n }\n ";var _=new ld("boneWeight:"+l.name,t,{vertex:"boneWeights:"+l.name,fragment:"boneWeights:"+l.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return _.setColor3("colorBase",c),_.setColor3("colorZero",u),_.setColor3("colorQuarter",h),_.setColor3("colorHalf",d),_.setColor3("colorFull",p),_.setFloat("targetBoneIndex",f),_.getClassName=function(){return"BoneWeightShader"},_.transparencyMode=Ca.MATERIAL_OPAQUE,_},e.CreateSkeletonMapShader=function(t,i){var r,n=t.skeleton,o=null!==(r=t.colorMap)&&void 0!==r?r:[{color:new Z(1,.38,.18),location:0},{color:new Z(.59,.18,1),location:.2},{color:new Z(.59,1,.18),location:.4},{color:new Z(1,.87,.17),location:.6},{color:new Z(1,.17,.42),location:.8},{color:new Z(.17,.68,1),location:1}],a=n.bones.length+1,s=e._CreateBoneMapColorBuffer(a,o,i),l=new ld("boneWeights:"+n.name,i,{vertexSource:"precision highp float;\n\n attribute vec3 position;\n attribute vec2 uv;\n\n uniform mat4 view;\n uniform mat4 projection;\n uniform mat4 worldViewProjection;\n uniform float colorMap["+4*n.bones.length+"];\n\n #include<bonesDeclaration>\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include<bakedVertexAnimationDeclaration>\n #include<instancesDeclaration>\n\n varying vec3 vColor;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include<instancesVertex>\n #include<bonesVertex>\n #include<bakedVertexAnimation>\n\n vec3 color = vec3(0.);\n bool first = true;\n\n for (int i = 0; i < 4; i++) {\n int boneIdx = int(matricesIndices[i]);\n float boneWgt = matricesWeights[i];\n\n vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]);\n\n if (boneWgt > 0.) {\n if (first) {\n first = false;\n color = c;\n } else {\n color = mix(color, c, boneWgt);\n }\n }\n }\n\n vColor = color;\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n gl_Position = projection * view * worldPos;\n }",fragmentSource:"\n precision highp float;\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4( vColor, 1.0 );\n gl_FragColor = color;\n }\n "},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorMap"]});return l.setFloats("colorMap",s),l.getClassName=function(){return"SkeletonMapShader"},l.transparencyMode=Ca.MATERIAL_OPAQUE,l},e._CreateBoneMapColorBuffer=function(e,t,i){var r=new Gu("temp",{width:e,height:1},i,!1),n=r.getContext(),o=n.createLinearGradient(0,0,e,0);t.forEach((function(e){o.addColorStop(e.location,e.color.toHexString())})),n.fillStyle=o,n.fillRect(0,0,e,1),r.update();for(var a=[],s=n.getImageData(0,0,e,1).data,l=1/255,c=0;c<s.length;c++)a.push(s[c]*l);return r.dispose(),a},Object.defineProperty(e.prototype,"scene",{get:function(){return this._scene},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"utilityLayer",{get:function(){return this._utilityLayer},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isReady",{get:function(){return this._ready},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"ready",{set:function(e){this._ready=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"debugMesh",{get:function(){return this._debugMesh},set:function(e){this._debugMesh=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"displayMode",{get:function(){return this.options.displayMode||e.DISPLAY_LINES},set:function(t){t>e.DISPLAY_SPHERE_AND_SPURS&&(t=e.DISPLAY_LINES),this.options.displayMode=t},enumerable:!1,configurable:!0}),e.prototype._bindObs=function(){var t=this;this.displayMode===e.DISPLAY_LINES&&(this._obs=this.scene.onBeforeRenderObservable.add((function(){t._displayLinesUpdate()})))},e.prototype.update=function(){switch(this.displayMode){case e.DISPLAY_LINES:this._displayLinesUpdate();break;case e.DISPLAY_SPHERES:this._buildSpheresAndSpurs(!0);break;case e.DISPLAY_SPHERE_AND_SPURS:this._buildSpheresAndSpurs(!1)}this._buildLocalAxes()},Object.defineProperty(e.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this.isEnabled!==e&&(this._isEnabled=e,this.debugMesh&&this.debugMesh.setEnabled(e),e&&!this._obs?this._bindObs():!e&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))},enumerable:!1,configurable:!0}),e.prototype._getBonePosition=function(e,t,i,r,n,o){void 0===r&&(r=0),void 0===n&&(n=0),void 0===o&&(o=0);var a=H.Matrix[0],s=t.getParent();if(a.copyFrom(t.getLocalMatrix()),0!==r||0!==n||0!==o){var l=H.Matrix[1];z.IdentityToRef(l),l.setTranslationFromFloats(r,n,o),l.multiplyToRef(a,a)}s&&a.multiplyToRef(s.getAbsoluteMatrix(),a),a.multiplyToRef(i,a),e.x=a.m[12],e.y=a.m[13],e.z=a.m[14]},e.prototype._getLinesForBonesWithLength=function(e,t){var i,r,n=e.length;t?(i=t.getWorldMatrix(),r=t.position):(i=new z,r=e[0].position);for(var o=0,a=0;a<n;a++){var s=e[a],l=this._debugLines[o];-1!==s._index&&(this._boneIndices.has(s.getIndex())||this.options.useAllBones)&&(l||(l=[V.Zero(),V.Zero()],this._debugLines[o]=l),this._getBonePosition(l[0],s,i),this._getBonePosition(l[1],s,i,0,s.length,0),l[0].subtractInPlace(r),l[1].subtractInPlace(r),o++)}},e.prototype._getLinesForBonesNoLength=function(e){var t,i,r=e.length,n=0,o=this.mesh;o?(t=o,i=o.position):(t=new Fo(""),i=e[0].position);for(var a=r-1;a>=0;a--){var s=e[a],l=s.getParent();if(l&&(this._boneIndices.has(s.getIndex())||this.options.useAllBones)){var c=this._debugLines[n];c||(c=[V.Zero(),V.Zero()],this._debugLines[n]=c),s.getAbsolutePositionToRef(t,c[0]),l.getAbsolutePositionToRef(t,c[1]),c[0].subtractInPlace(i),c[1].subtractInPlace(i),n++}}o||t.dispose()},e.prototype._revert=function(e){this.options.pauseAnimations&&(this.scene.animationsEnabled=e,this.utilityLayer.utilityLayerScene.animationsEnabled=e)},e.prototype._getAbsoluteBindPoseToRef=function(e,t){null!==e&&-1!==e._index?(this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBindMatrix().multiplyToRef(t,t)):t.copyFrom(z.Identity())},e.prototype._createSpur=function(e,t,i,r,n,o){for(var a=i.subtract(e),s=a.length(),l=a.normalize().scale(s),c=n.midStep||.165,u=n.midStepFactor||.215,h=l.scale(c),d=Cd("skeletonViewer",{shape:[new V(1,-1,0),new V(1,1,0),new V(-1,1,0),new V(-1,-1,0),new V(1,-1,0)],path:[V.Zero(),h,l],scaleFunction:function(e){switch(e){case 0:case 2:return 0;case 1:return s*u}return 0},sideOrientation:Fa.DEFAULTSIDE,updatable:!1},o),p=d.getTotalVertices(),f=[],_=[],m=0;m<p;m++)f.push(1,0,0,0),r&&n.spurFollowsChild&&m>9?_.push(r.getIndex(),0,0,0):_.push(t.getIndex(),0,0,0);return d.position=e.clone(),d.setVerticesData(Nr.MatricesWeightsKind,f,!1),d.setVerticesData(Nr.MatricesIndicesKind,_,!1),d.convertToFlatShadedMesh(),d},e.prototype._getBoundingSphereForBone=function(e){if(!this.mesh)return null;var t=this.mesh.getVerticesData(Nr.PositionKind),i=this.mesh.getIndices(),r=this.mesh.getVerticesData(Nr.MatricesWeightsKind),n=this.mesh.getVerticesData(Nr.MatricesIndicesKind);if(!(t&&i&&r&&n))return null;for(var o=new V(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new V(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),s=0,l=0;l<i.length;++l)for(var c=i[l],u=0;u<4;++u){var h=n[4*c+u],d=r[4*c+u];if(h===e&&d>1e-5){V.FromArrayToRef(t,3*c,H.Vector3[0]),o.minimizeInPlace(H.Vector3[0]),a.maximizeInPlace(H.Vector3[0]),s++;break}}return s>1?{center:V.Center(o,a),radius:V.Distance(o,a)/2}:null},e.prototype._buildSpheresAndSpurs=function(e){var t,i,r,n=this;void 0===e&&(e=!0),this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;var o=null===(i=this.utilityLayer)||void 0===i?void 0:i.utilityLayerScene,a=this.skeleton.bones,s=[],l=[],c=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,o.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices();for(var u=Number.NEGATIVE_INFINITY,h=this.options.displayOptions||{},d=function(t){var i=a[t];if(-1===i._index||!p._boneIndices.has(i.getIndex())&&!p.options.useAllBones)return"continue";var r=new z;p._getAbsoluteBindPoseToRef(i,r);var c=new V;if(r.decompose(void 0,void 0,c),i.children.length>0)i.children.forEach((function(t){var a=new z;t.getLocalMatrix().multiplyToRef(r,a);var s=new V;a.decompose(void 0,void 0,s);var d=V.Distance(c,s);d>u&&(u=d),e||l.push(n._createSpur(c,i,s,t,h,o))}));else{var d=p._getBoundingSphereForBone(i.getIndex());if(d&&(d.radius>u&&(u=d.radius),!e)){var f=void 0,_=i.getParent();_?(p._getAbsoluteBindPoseToRef(_,r),r.decompose(void 0,void 0,H.Vector3[0]),f=c.subtract(H.Vector3[0]).normalize().scale(d.radius).add(c)):f=d.center.subtract(c).normalize().scale(d.radius).add(c),l.push(p._createSpur(c,i,f,null,h,o))}}for(var m=Gh("skeletonViewer",{segments:6,diameter:h.sphereBaseSize||.2,updatable:!0},o),g=m.getTotalVertices(),v=[],y=[],b=0;b<g;b++)v.push(1,0,0,0),y.push(i.getIndex(),0,0,0);m.setVerticesData(Nr.MatricesWeightsKind,v,!1),m.setVerticesData(Nr.MatricesIndicesKind,y,!1),m.position=c.clone(),s.push([m,i])},p=this,f=0;f<a.length;f++)d(f);var _=h.sphereScaleUnit||2,m=h.sphereFactor||.85,g=[];for(f=0;f<s.length;f++){for(var v=(t=s[f])[0],y=t[1],b=1/(_/u),T=0,E=y;E.getParent()&&-1!==E.getParent().getIndex();)T++,E=E.getParent();v.scaling.scaleInPlace(b*Math.pow(m,T)),g.push(v)}this.debugMesh=Fa.MergeMeshes(g.concat(l),!0,!0),this.debugMesh&&(this.debugMesh.renderingGroupId=this.renderingGroupId,this.debugMesh.skeleton=this.skeleton,this.debugMesh.parent=this.mesh,this.debugMesh.computeBonesUsingShaders=null===(r=this.options.computeBonesUsingShaders)||void 0===r||r,this.debugMesh.alwaysSelectAsActiveMesh=!0),this.utilityLayer._getSharedGizmoLight().intensity=.7,this._revert(c),this.ready=!0}catch(e){ae.Error(e),this._revert(c),this.dispose()}},e.prototype._buildLocalAxes=function(){var e;this._localAxes&&this._localAxes.dispose(),this._localAxes=null;var t=this.options.displayOptions||{};if(t.showLocalAxes){var i=this._utilityLayer.utilityLayerScene,r=t.localAxesSize||.075,n=[],o=[],a=new J(1,0,0,1),s=new J(0,1,0,1),l=new J(0,0,1,1),c=[],u=[];for(var h in this.skeleton.bones){var d=this.skeleton.bones[h];if(-1!==d._index&&(this._boneIndices.has(d.getIndex())||this.options.useAllBones)){var p=new z,f=new V;this._getAbsoluteBindPoseToRef(d,p),p.decompose(void 0,H.Quaternion[0],f);var _=new z;H.Quaternion[0].toRotationMatrix(_);var m=V.TransformCoordinates(new V(0+r,0,0),_),g=V.TransformCoordinates(new V(0,0+r,0),_),v=V.TransformCoordinates(new V(0,0,0+r),_),y=[[f,f.add(m)],[f,f.add(g)],[f,f.add(v)]],b=[[a,a],[s,s],[l,l]];n.push.apply(n,y),o.push.apply(o,b);for(var T=0;T<6;T++)c.push(1,0,0,0),u.push(d.getIndex(),0,0,0)}}this._localAxes=pd("localAxes",{lines:n,colors:o,updatable:!0},i),this._localAxes.setVerticesData(Nr.MatricesWeightsKind,c,!1),this._localAxes.setVerticesData(Nr.MatricesIndicesKind,u,!1),this._localAxes.skeleton=this.skeleton,this._localAxes.renderingGroupId=this.renderingGroupId+1,this._localAxes.parent=this.mesh,this._localAxes.computeBonesUsingShaders=null===(e=this.options.computeBonesUsingShaders)||void 0===e||e}},e.prototype._displayLinesUpdate=function(){if(this._utilityLayer){this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices(),void 0===this.skeleton.bones[0].length?this._getLinesForBonesNoLength(this.skeleton.bones):this._getLinesForBonesWithLength(this.skeleton.bones,this.mesh);var e=this._utilityLayer.utilityLayerScene;e&&(this._debugMesh?pd("",{lines:this._debugLines,updatable:!0,instance:this._debugMesh},e):(this._debugMesh=pd("",{lines:this._debugLines,updatable:!0,instance:null},e),this._debugMesh.renderingGroupId=this.renderingGroupId),this.mesh?this._debugMesh.position.copyFrom(this.mesh.position):this._debugMesh.position.copyFrom(this.skeleton.bones[0].position),this._debugMesh.color=this.color)}},e.prototype.changeDisplayMode=function(e){var t=!!this.isEnabled;this.displayMode!==e&&(this.isEnabled=!1,this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this.displayMode=e,this.update(),this._bindObs(),this.isEnabled=t)},e.prototype.changeDisplayOptions=function(e,t){var i=!!this.isEnabled;this.options.displayOptions[e]=t,this.isEnabled=!1,this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this.update(),this._bindObs(),this.isEnabled=i},e.prototype.dispose=function(){this.isEnabled=!1,this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null),this._utilityLayer&&(this._utilityLayer.dispose(),this._utilityLayer=null),this.ready=!1},e.DISPLAY_LINES=0,e.DISPLAY_SPHERES=1,e.DISPLAY_SPHERE_AND_SPURS=2,e}(),sp=function(){function e(e,t){this._oldPosition=new V(Number.NaN,Number.NaN,Number.NaN),this._oldDirection=new V(Number.NaN,Number.NaN,Number.NaN),this._transparency=.3,this._showLines=!0,this._showPlanes=!0,this._scene=e.getScene(),this._light=e,this._camera=t,this._inverseViewMatrix=z.Identity(),this._lightHelperFrustumMeshes=[],this._createGeometry(),this.show(),this.update()}return Object.defineProperty(e.prototype,"transparency",{get:function(){return this._transparency},set:function(e){this._transparency=e;for(var t=6;t<12;++t)this._lightHelperFrustumMeshes[t].material.alpha=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"showLines",{get:function(){return this._showLines},set:function(e){if(this._showLines!==e){this._showLines=e;for(var t=0;t<6;++t)this._lightHelperFrustumMeshes[t].setEnabled(e)}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"showPlanes",{get:function(){return this._showPlanes},set:function(e){if(this._showPlanes!==e){this._showPlanes=e;for(var t=6;t<12;++t)this._lightHelperFrustumMeshes[t].setEnabled(e)}},enumerable:!1,configurable:!0}),e.prototype.show=function(){var e=this;this._lightHelperFrustumMeshes.forEach((function(t,i){t.setEnabled(i<6&&e._showLines||i>=6&&e._showPlanes)})),this._oldPosition.set(Number.NaN,Number.NaN,Number.NaN),this._visible=!0},e.prototype.hide=function(){this._lightHelperFrustumMeshes.forEach((function(e){e.setEnabled(!1)})),this._visible=!1},e.prototype.update=function(){var e,t,i,r,n,o;if(this._visible&&(!this._oldPosition.equals(this._light.position)||!this._oldDirection.equals(this._light.direction)||this._oldAutoCalc!==this._light.autoCalcShadowZBounds||this._oldMinZ!==this._light.shadowMinZ||this._oldMaxZ!==this._light.shadowMaxZ)){this._oldPosition.copyFrom(this._light.position),this._oldDirection.copyFrom(this._light.direction),this._oldAutoCalc=this._light.autoCalcShadowZBounds,this._oldMinZ=this._light.shadowMinZ,this._oldMaxZ=this._light.shadowMaxZ,H.Vector3[0].set(this._light.orthoLeft,this._light.orthoBottom,void 0!==this._light.shadowMinZ?this._light.shadowMinZ:this._camera.minZ),H.Vector3[1].set(this._light.orthoRight,this._light.orthoTop,void 0!==this._light.shadowMaxZ?this._light.shadowMaxZ:this._camera.maxZ);var a=this._getInvertViewMatrix();H.Vector3[2].copyFromFloats(H.Vector3[1].x,H.Vector3[1].y,H.Vector3[0].z),H.Vector3[3].copyFromFloats(H.Vector3[1].x,H.Vector3[0].y,H.Vector3[0].z),H.Vector3[4].copyFromFloats(H.Vector3[0].x,H.Vector3[0].y,H.Vector3[0].z),H.Vector3[5].copyFromFloats(H.Vector3[0].x,H.Vector3[1].y,H.Vector3[0].z),V.TransformCoordinatesToRef(H.Vector3[2],a,H.Vector3[2]),V.TransformCoordinatesToRef(H.Vector3[3],a,H.Vector3[3]),V.TransformCoordinatesToRef(H.Vector3[4],a,H.Vector3[4]),V.TransformCoordinatesToRef(H.Vector3[5],a,H.Vector3[5]),H.Vector3[6].copyFromFloats(H.Vector3[1].x,H.Vector3[1].y,H.Vector3[1].z),H.Vector3[7].copyFromFloats(H.Vector3[1].x,H.Vector3[0].y,H.Vector3[1].z),H.Vector3[8].copyFromFloats(H.Vector3[0].x,H.Vector3[0].y,H.Vector3[1].z),H.Vector3[9].copyFromFloats(H.Vector3[0].x,H.Vector3[1].y,H.Vector3[1].z),V.TransformCoordinatesToRef(H.Vector3[6],a,H.Vector3[6]),V.TransformCoordinatesToRef(H.Vector3[7],a,H.Vector3[7]),V.TransformCoordinatesToRef(H.Vector3[8],a,H.Vector3[8]),V.TransformCoordinatesToRef(H.Vector3[9],a,H.Vector3[9]),fd("nearlines",{updatable:!0,points:this._nearLinesPoints,instance:this._lightHelperFrustumMeshes[0]},this._scene),fd("farlines",{updatable:!0,points:this._farLinesPoints,instance:this._lightHelperFrustumMeshes[1]},this._scene),fd("trlines",{updatable:!0,points:this._trLinesPoints,instance:this._lightHelperFrustumMeshes[2]},this._scene),fd("brlines",{updatable:!0,points:this._brLinesPoints,instance:this._lightHelperFrustumMeshes[3]},this._scene),fd("tllines",{updatable:!0,points:this._tlLinesPoints,instance:this._lightHelperFrustumMeshes[4]},this._scene),fd("bllines",{updatable:!0,points:this._blLinesPoints,instance:this._lightHelperFrustumMeshes[5]},this._scene),H.Vector3[2].toArray(this._nearPlaneVertices,0),H.Vector3[3].toArray(this._nearPlaneVertices,3),H.Vector3[4].toArray(this._nearPlaneVertices,6),H.Vector3[5].toArray(this._nearPlaneVertices,9),null===(e=this._lightHelperFrustumMeshes[6].geometry)||void 0===e||e.updateVerticesDataDirectly("position",this._nearPlaneVertices,0),H.Vector3[6].toArray(this._farPlaneVertices,0),H.Vector3[7].toArray(this._farPlaneVertices,3),H.Vector3[8].toArray(this._farPlaneVertices,6),H.Vector3[9].toArray(this._farPlaneVertices,9),null===(t=this._lightHelperFrustumMeshes[7].geometry)||void 0===t||t.updateVerticesDataDirectly("position",this._farPlaneVertices,0),H.Vector3[2].toArray(this._rightPlaneVertices,0),H.Vector3[6].toArray(this._rightPlaneVertices,3),H.Vector3[7].toArray(this._rightPlaneVertices,6),H.Vector3[3].toArray(this._rightPlaneVertices,9),null===(i=this._lightHelperFrustumMeshes[8].geometry)||void 0===i||i.updateVerticesDataDirectly("position",this._rightPlaneVertices,0),H.Vector3[5].toArray(this._leftPlaneVertices,0),H.Vector3[9].toArray(this._leftPlaneVertices,3),H.Vector3[8].toArray(this._leftPlaneVertices,6),H.Vector3[4].toArray(this._leftPlaneVertices,9),null===(r=this._lightHelperFrustumMeshes[9].geometry)||void 0===r||r.updateVerticesDataDirectly("position",this._leftPlaneVertices,0),H.Vector3[2].toArray(this._topPlaneVertices,0),H.Vector3[6].toArray(this._topPlaneVertices,3),H.Vector3[9].toArray(this._topPlaneVertices,6),H.Vector3[5].toArray(this._topPlaneVertices,9),null===(n=this._lightHelperFrustumMeshes[10].geometry)||void 0===n||n.updateVerticesDataDirectly("position",this._topPlaneVertices,0),H.Vector3[3].toArray(this._bottomPlaneVertices,0),H.Vector3[7].toArray(this._bottomPlaneVertices,3),H.Vector3[8].toArray(this._bottomPlaneVertices,6),H.Vector3[4].toArray(this._bottomPlaneVertices,9),null===(o=this._lightHelperFrustumMeshes[11].geometry)||void 0===o||o.updateVerticesDataDirectly("position",this._bottomPlaneVertices,0)}},e.prototype.dispose=function(){this._lightHelperFrustumMeshes.forEach((function(e){var t;null===(t=e.material)||void 0===t||t.dispose(),e.dispose()})),this._rootNode.dispose()},e.prototype._createGeometry=function(){var e=this;this._rootNode=new Fo("directionalLightHelperRoot_"+this._light.name,this._scene),this._rootNode.parent=this._light.parent,this._nearLinesPoints=[H.Vector3[0],H.Vector3[1],H.Vector3[2],H.Vector3[3],H.Vector3[4]];var t=fd("nearlines",{updatable:!0,points:this._nearLinesPoints},this._scene);t.parent=this._rootNode,t.alwaysSelectAsActiveMesh=!0,this._farLinesPoints=[H.Vector3[5],H.Vector3[6],H.Vector3[7],H.Vector3[8],H.Vector3[9]];var i=fd("farlines",{updatable:!0,points:this._farLinesPoints},this._scene);i.parent=this._rootNode,i.alwaysSelectAsActiveMesh=!0,this._trLinesPoints=[H.Vector3[10],H.Vector3[11]];var r=fd("trlines",{updatable:!0,points:this._trLinesPoints},this._scene);r.parent=this._rootNode,r.alwaysSelectAsActiveMesh=!0,this._brLinesPoints=[H.Vector3[12],H.Vector3[0]];var n=fd("brlines",{updatable:!0,points:this._brLinesPoints},this._scene);n.parent=this._rootNode,n.alwaysSelectAsActiveMesh=!0,this._tlLinesPoints=[H.Vector3[1],H.Vector3[2]];var o=fd("tllines",{updatable:!0,points:this._tlLinesPoints},this._scene);o.parent=this._rootNode,o.alwaysSelectAsActiveMesh=!0,this._blLinesPoints=[H.Vector3[3],H.Vector3[4]];var a=fd("bllines",{updatable:!0,points:this._blLinesPoints},this._scene);a.parent=this._rootNode,a.alwaysSelectAsActiveMesh=!0,this._lightHelperFrustumMeshes.push(t,i,r,n,o,a);var s=function(t,i,r){var n=new Fa(t+"plane",e._scene),o=new Uu(t+"PlaneMat",e._scene);n.material=o,n.parent=e._rootNode,n.alwaysSelectAsActiveMesh=!0,o.emissiveColor=i,o.alpha=e.transparency,o.backFaceCulling=!1,o.disableLighting=!0;var a=new _o;a.positions=r,a.indices=[0,1,2,0,2,3],a.applyToMesh(n,!0),e._lightHelperFrustumMeshes.push(n)};this._nearPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._farPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._rightPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._leftPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._topPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._bottomPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],s("near",new Z(1,0,0),this._nearPlaneVertices),s("far",new Z(.3,0,0),this._farPlaneVertices),s("right",new Z(0,1,0),this._rightPlaneVertices),s("left",new Z(0,.3,0),this._leftPlaneVertices),s("top",new Z(0,0,1),this._topPlaneVertices),s("bottom",new Z(0,0,.3),this._bottomPlaneVertices),this._nearLinesPoints[0]=H.Vector3[2],this._nearLinesPoints[1]=H.Vector3[3],this._nearLinesPoints[2]=H.Vector3[4],this._nearLinesPoints[3]=H.Vector3[5],this._nearLinesPoints[4]=H.Vector3[2],this._farLinesPoints[0]=H.Vector3[6],this._farLinesPoints[1]=H.Vector3[7],this._farLinesPoints[2]=H.Vector3[8],this._farLinesPoints[3]=H.Vector3[9],this._farLinesPoints[4]=H.Vector3[6],this._trLinesPoints[0]=H.Vector3[2],this._trLinesPoints[1]=H.Vector3[6],this._brLinesPoints[0]=H.Vector3[3],this._brLinesPoints[1]=H.Vector3[7],this._tlLinesPoints[0]=H.Vector3[4],this._tlLinesPoints[1]=H.Vector3[8],this._blLinesPoints[0]=H.Vector3[5],this._blLinesPoints[1]=H.Vector3[9]},e.prototype._getInvertViewMatrix=function(){return z.LookAtLHToRef(this._light.position,this._light.position.add(this._light.direction),V.UpReadOnly,this._inverseViewMatrix),this._inverseViewMatrix.invertToRef(this._inverseViewMatrix),this._inverseViewMatrix},e}(),lp=function(){this.renderWidth=512,this.renderHeight=256,this.textureSize=512,this.deterministicLockstep=!1,this.lockstepMaxSteps=4},cp=function(t){function i(i){void 0===i&&(i=new lp);var r=t.call(this,null)||this;void 0===i.deterministicLockstep&&(i.deterministicLockstep=!1),void 0!==i.timeStep&&(r._timeStep=i.timeStep),void 0===i.lockstepMaxSteps&&(i.lockstepMaxSteps=4),r._options=i,I.SetMatrixPrecision(!!i.useHighPrecisionMatrix),r._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:512,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!1,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:0,uintIndices:!1,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloat:!1,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!1,textureLOD:!1,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!1,instancedArrays:!1,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,maxMSAASamples:1,blendMinMax:!1,canUseGLInstanceID:!1,canUseGLVertexID:!1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:128,disableMorphTargetTexture:!1},r._features={forceBitmapOverHTMLImageElement:!1,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!1,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1},ae.Log("Babylon.js v".concat(Do.Version," - Null engine"));var n="undefined"!=typeof self?self:void 0!==e.g?e.g:window;return"undefined"==typeof URL&&(n.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(n.Blob=function(){}),r}return m(i,t),i.prototype.isDeterministicLockStep=function(){return this._options.deterministicLockstep},i.prototype.getLockstepMaxSteps=function(){return this._options.lockstepMaxSteps},i.prototype.getHardwareScalingLevel=function(){return 1},i.prototype.createVertexBuffer=function(e){var t=new vr;return t.references=1,t},i.prototype.createIndexBuffer=function(e){var t=new vr;return t.references=1,t},i.prototype.clear=function(e,t,i,r){void 0===r&&(r=!1)},i.prototype.getRenderWidth=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._options.renderWidth},i.prototype.getRenderHeight=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._options.renderHeight},i.prototype.setViewport=function(e,t,i){this._cachedViewport=e},i.prototype.createShaderProgram=function(e,t,i,r,n){return{__SPECTOR_rebuildProgram:null}},i.prototype.getUniforms=function(e,t){return[]},i.prototype.getAttributes=function(e,t){return[]},i.prototype.bindSamplers=function(e){this._currentEffect=null},i.prototype.enableEffect=function(e){e=null!==e&&fr(e)?e.effect:e,this._currentEffect=e,e&&(e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))},i.prototype.setState=function(e,t,i,r,n,o,a){void 0===t&&(t=0),void 0===r&&(r=!1),void 0===a&&(a=0)},i.prototype.setIntArray=function(e,t){return!0},i.prototype.setIntArray2=function(e,t){return!0},i.prototype.setIntArray3=function(e,t){return!0},i.prototype.setIntArray4=function(e,t){return!0},i.prototype.setFloatArray=function(e,t){return!0},i.prototype.setFloatArray2=function(e,t){return!0},i.prototype.setFloatArray3=function(e,t){return!0},i.prototype.setFloatArray4=function(e,t){return!0},i.prototype.setArray=function(e,t){return!0},i.prototype.setArray2=function(e,t){return!0},i.prototype.setArray3=function(e,t){return!0},i.prototype.setArray4=function(e,t){return!0},i.prototype.setMatrices=function(e,t){return!0},i.prototype.setMatrix3x3=function(e,t){return!0},i.prototype.setMatrix2x2=function(e,t){return!0},i.prototype.setFloat=function(e,t){return!0},i.prototype.setFloat2=function(e,t,i){return!0},i.prototype.setFloat3=function(e,t,i,r){return!0},i.prototype.setBool=function(e,t){return!0},i.prototype.setFloat4=function(e,t,i,r,n){return!0},i.prototype.setAlphaMode=function(e,t){void 0===t&&(t=!1),this._alphaMode!==e&&(this.alphaState.alphaBlend=e!==u.ALPHA_DISABLE,t||this.setDepthWrite(e===u.ALPHA_DISABLE),this._alphaMode=e)},i.prototype.bindBuffers=function(e,t,i){},i.prototype.wipeCaches=function(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this.depthCullingState.reset(),this.alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)},i.prototype.draw=function(e,t,i,r){},i.prototype.drawElementsType=function(e,t,i,r){},i.prototype.drawArraysType=function(e,t,i,r){},i.prototype._createTexture=function(){return{}},i.prototype._releaseTexture=function(e){},i.prototype.createTexture=function(e,t,i,r,n,o,a,s,l,c,h,d){void 0===n&&(n=u.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null),void 0===l&&(l=null),void 0===c&&(c=null),void 0===h&&(h=null);var p=new Pi(this,Ti.Url),f=String(e);return p.url=f,p.generateMipMaps=!t,p.samplingMode=n,p.invertY=i,p.baseWidth=this._options.textureSize,p.baseHeight=this._options.textureSize,p.width=this._options.textureSize,p.height=this._options.textureSize,c&&(p.format=c),p.isReady=!0,o&&setTimeout((function(){o(p)})),this._internalTexturesCache.push(p),p},i.prototype._createHardwareRenderTargetWrapper=function(e,t,i){var r=new cl(e,t,i,this);return this._renderTargetWrapperCache.push(r),r},i.prototype.createRenderTargetTexture=function(e,t){var i=this._createHardwareRenderTargetWrapper(!1,!1,e),r={};void 0!==t&&"object"==typeof t?(r.generateMipMaps=t.generateMipMaps,r.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,r.generateStencilBuffer=r.generateDepthBuffer&&t.generateStencilBuffer,r.type=void 0===t.type?u.TEXTURETYPE_UNSIGNED_INT:t.type,r.samplingMode=void 0===t.samplingMode?u.TEXTURE_TRILINEAR_SAMPLINGMODE:t.samplingMode):(r.generateMipMaps=t,r.generateDepthBuffer=!0,r.generateStencilBuffer=!1,r.type=u.TEXTURETYPE_UNSIGNED_INT,r.samplingMode=u.TEXTURE_TRILINEAR_SAMPLINGMODE);var n=new Pi(this,Ti.RenderTarget),o=e.width||e,a=e.height||e;return i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=!!r.generateStencilBuffer,n.baseWidth=o,n.baseHeight=a,n.width=o,n.height=a,n.isReady=!0,n.samples=1,n.generateMipMaps=!!r.generateMipMaps,n.samplingMode=r.samplingMode,n.type=r.type,this._internalTexturesCache.push(n),i},i.prototype.createRenderTargetCubeTexture=function(e,t){var i=this._createHardwareRenderTargetWrapper(!1,!0,e),r=g({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:u.TEXTURETYPE_UNSIGNED_INT,samplingMode:u.TEXTURE_TRILINEAR_SAMPLINGMODE,format:u.TEXTUREFORMAT_RGBA},t);r.generateStencilBuffer=r.generateDepthBuffer&&r.generateStencilBuffer,(r.type!==u.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(r.type!==u.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(r.samplingMode=u.TEXTURE_NEAREST_SAMPLINGMODE),i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=!!r.generateStencilBuffer;var n=new Pi(this,Ti.RenderTarget);return n.baseWidth=e,n.baseHeight=e,n.width=e,n.height=e,n.isReady=!0,n.isCube=!0,n.samples=1,n.generateMipMaps=!!r.generateMipMaps,n.samplingMode=r.samplingMode,n.type=r.type,this._internalTexturesCache.push(n),i},i.prototype.updateTextureSamplingMode=function(e,t){t.samplingMode=e},i.prototype.createRawTexture=function(e,t,i,r,n,o,a,s,l,c,h){void 0===s&&(s=null),void 0===l&&(l=u.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=0),void 0===h&&(h=!1);var d=new Pi(this,Ti.Raw);return d.baseWidth=t,d.baseHeight=i,d.width=t,d.height=i,d.format=r,d.generateMipMaps=n,d.samplingMode=a,d.invertY=o,d._compression=s,d.type=l,d._useSRGBBuffer=h,this._doNotHandleContextLost||(d._bufferView=e),d},i.prototype.updateRawTexture=function(e,t,i,r,n,o,a){void 0===n&&(n=null),void 0===o&&(o=u.TEXTURETYPE_UNSIGNED_INT),void 0===a&&(a=!1),e&&(e._bufferView=t,e.format=i,e.invertY=r,e._compression=n,e.type=o,e._useSRGBBuffer=a)},i.prototype.bindFramebuffer=function(e,t,i,r,n){this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._currentFramebuffer=null,this._cachedViewport&&!n&&this.setViewport(this._cachedViewport,i,r)},i.prototype.unBindFramebuffer=function(e,t,i){void 0===t&&(t=!1),this._currentRenderTarget=null,i&&i(),this._currentFramebuffer=null},i.prototype.createDynamicVertexBuffer=function(e){var t=new vr;return t.references=1,t.capacity=1,t},i.prototype.updateDynamicTexture=function(e,t,i,r,n){void 0===r&&(r=!1)},i.prototype.areAllEffectsReady=function(){return!0},i.prototype.getError=function(){return 0},i.prototype._getUnpackAlignement=function(){return 1},i.prototype._unpackFlipY=function(e){},i.prototype.updateDynamicIndexBuffer=function(e,t,i){void 0===i&&(i=0)},i.prototype.updateDynamicVertexBuffer=function(e,t,i,r){},i.prototype._bindTextureDirectly=function(e,t){return this._boundTexturesCache[this._activeChannel]!==t&&(this._boundTexturesCache[this._activeChannel]=t,!0)},i.prototype._bindTexture=function(e,t){e<0||this._bindTextureDirectly(0,t)},i.prototype._deleteBuffer=function(e){},i.prototype.releaseEffects=function(){},i.prototype.displayLoadingUI=function(){},i.prototype.hideLoadingUI=function(){},Object.defineProperty(i.prototype,"loadingUIText",{set:function(e){},enumerable:!1,configurable:!0}),i.prototype._uploadCompressedDataToTextureDirectly=function(e,t,i,r,n,o,a){void 0===o&&(o=0),void 0===a&&(a=0)},i.prototype._uploadDataToTextureDirectly=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0)},i.prototype._uploadArrayBufferViewToTexture=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0)},i.prototype._uploadImageToTexture=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0)},i}(Do);Mi.prototype._partialLoadFile=function(e,t,i,r,n){void 0===n&&(n=null),this._loadFile(e,(function(e){i[t]=e,i._internalCount++,6===i._internalCount&&r(i)}),void 0,void 0,!0,(function(e,t){n&&e&&n(e.status+" "+e.statusText,t)}))},Mi.prototype._cascadeLoadFiles=function(e,t,i,r){void 0===r&&(r=null);var n=[];n._internalCount=0;for(var o=0;o<6;o++)this._partialLoadFile(i[o],o,n,t,r)},Mi.prototype._cascadeLoadImgs=function(e,t,i,r,n,o){void 0===n&&(n=null);var a=[];a._internalCount=0;for(var s=0;s<6;s++)this._partialLoadImg(r[s],s,a,e,t,i,n,o)},Mi.prototype._partialLoadImg=function(e,t,i,r,n,o,a,s){void 0===a&&(a=null);var l=Qi();Bi(e,(function(e){i[t]=e,i._internalCount++,r&&r.removePendingData(l),6===i._internalCount&&o&&o(n,i)}),(function(e,t){r&&r.removePendingData(l),a&&a(e,t)}),r?r.offlineProvider:null,s),r&&r.addPendingData(l)},Mi.prototype.createCubeTextureBase=function(e,t,i,r,n,o,a,s,l,c,u,h,d,p,f){var _=this;void 0===n&&(n=null),void 0===o&&(o=null),void 0===s&&(s=null),void 0===l&&(l=!1),void 0===c&&(c=0),void 0===u&&(u=0),void 0===h&&(h=null),void 0===d&&(d=null),void 0===p&&(p=null),void 0===f&&(f=!1);var m=h||new Pi(this,Ti.Cube);m.isCube=!0,m.url=e,m.generateMipMaps=!r,m._lodGenerationScale=c,m._lodGenerationOffset=u,m._useSRGBBuffer=!!f&&this._caps.supportSRGBBuffers&&(this.version>1||this.isWebGPU||!!r),m!==h&&(m.label=e.substring(0,60)),this._doNotHandleContextLost||(m._extension=s,m._files=i);var g=e;this._transformTextureUrl&&!h&&(e=this._transformTextureUrl(e));for(var v=e.split("?")[0],y=v.lastIndexOf("."),b=s||(y>-1?v.substring(y).toLowerCase():""),T=null,E=0,S=Mi._TextureLoaders;E<S.length;E++){var x=S[E];if(x.canLoad(b)){T=x;break}}if(T){var A=function(e){d&&d(m,e),T.loadCubeData(e,m,l,n,o)};i&&6===i.length?T.supportCascades?this._cascadeLoadFiles(t,(function(e){return A(e.map((function(e){return new Uint8Array(e)})))}),i,o):o?o("Textures type does not support cascades."):ae.Warn("Texture loader does not support cascades."):this._loadFile(e,(function(e){return A(new Uint8Array(e))}),void 0,void 0,!0,(function(h,v){e===g?o&&h&&o(h.status+" "+h.statusText,v):(ae.Warn("Failed to load ".concat(e,", falling back to the ").concat(g)),_.createCubeTextureBase(g,t,i,!!r,n,o,a,s,l,c,u,m,d,p,f))}))}else{if(!i||0===i.length)throw new Error("Cannot load cubemap because files were not defined, or the correct loader was not found.");this._cascadeLoadImgs(t,m,(function(e,t){p&&p(e,t)}),i,o)}return this._internalTexturesCache.push(m),m};var up=function(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=Uo.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=Uo.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE,this.forceRenderingWhenOccluded=!1};Mi.prototype.getGPUFrameTimeCounter=function(){return null},Mi.prototype.captureGPUFrameTime=function(e){},Mi.prototype.createQuery=function(){return null},Mi.prototype.deleteQuery=function(e){return this},Mi.prototype.isQueryResultAvailable=function(e){return!1},Mi.prototype.getQueryResult=function(e){return 0},Mi.prototype.beginOcclusionQuery=function(e,t){return!1},Mi.prototype.endOcclusionQuery=function(e){return this},Object.defineProperty(Uo.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(e){this._occlusionDataStorage.isOcclusionQueryInProgress=e},enumerable:!1,configurable:!0}),Object.defineProperty(Uo.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new up),this.__occlusionDataStorage},enumerable:!1,configurable:!0}),Object.defineProperty(Uo.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(e){this._occlusionDataStorage.isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(Uo.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(e){this._occlusionDataStorage.occlusionQueryAlgorithmType=e},enumerable:!0,configurable:!0}),Object.defineProperty(Uo.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(e){this._occlusionDataStorage.occlusionType=e},enumerable:!0,configurable:!0}),Object.defineProperty(Uo.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(e){this._occlusionDataStorage.occlusionRetryCount=e},enumerable:!0,configurable:!0}),Object.defineProperty(Uo.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(e){this._occlusionDataStorage.forceRenderingWhenOccluded=e},enumerable:!0,configurable:!0}),Uo.prototype._checkOcclusionQuery=function(){var e=this._occlusionDataStorage;if(e.occlusionType===Uo.OCCLUSION_TYPE_NONE)return e.isOccluded=!1,!1;var t=this.getEngine();if(!t.getCaps().supportOcclusionQuery)return e.isOccluded=!1,!1;if(!t.isQueryResultAvailable)return e.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&null!==this._occlusionQuery&&void 0!==this._occlusionQuery)if(t.isQueryResultAvailable(this._occlusionQuery)){var i=t.getQueryResult(this._occlusionQuery);e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=!(i>0)}else{if(e.occlusionInternalRetryCounter++,!(-1!==e.occlusionRetryCount&&e.occlusionInternalRetryCounter>e.occlusionRetryCount))return e.occlusionType!==Uo.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded;e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=e.occlusionType!==Uo.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded}var r=this.getScene();if(r.getBoundingBoxRenderer){var n=r.getBoundingBoxRenderer();null===this._occlusionQuery&&(this._occlusionQuery=t.createQuery()),this._occlusionQuery&&t.beginOcclusionQuery(e.occlusionQueryAlgorithmType,this._occlusionQuery)&&(n.renderOcclusionBoundingBox(this),t.endOcclusionQuery(e.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return e.isOccluded},Mi.prototype.setAlphaEquation=function(e){if(this._alphaEquation!==e){switch(e){case u.ALPHA_EQUATION_ADD:this._alphaState.setAlphaEquationParameters(u.GL_ALPHA_EQUATION_ADD,u.GL_ALPHA_EQUATION_ADD);break;case u.ALPHA_EQUATION_SUBSTRACT:this._alphaState.setAlphaEquationParameters(u.GL_ALPHA_EQUATION_SUBTRACT,u.GL_ALPHA_EQUATION_SUBTRACT);break;case u.ALPHA_EQUATION_REVERSE_SUBTRACT:this._alphaState.setAlphaEquationParameters(u.GL_ALPHA_EQUATION_REVERSE_SUBTRACT,u.GL_ALPHA_EQUATION_REVERSE_SUBTRACT);break;case u.ALPHA_EQUATION_MAX:this._alphaState.setAlphaEquationParameters(u.GL_ALPHA_EQUATION_MAX,u.GL_ALPHA_EQUATION_MAX);break;case u.ALPHA_EQUATION_MIN:this._alphaState.setAlphaEquationParameters(u.GL_ALPHA_EQUATION_MIN,u.GL_ALPHA_EQUATION_MIN);break;case u.ALPHA_EQUATION_DARKEN:this._alphaState.setAlphaEquationParameters(u.GL_ALPHA_EQUATION_MIN,u.GL_ALPHA_EQUATION_ADD)}this._alphaEquation=e}},Mi.prototype._debugPushGroup=function(e,t){},Mi.prototype._debugPopGroup=function(e){},Mi.prototype._debugInsertMarker=function(e,t){},Mi.prototype._debugFlushPendingCommands=function(){};var hp=function(){this._timeElapsedQueryEnded=!1};Do.prototype.createQuery=function(){var e=this._gl.createQuery();if(!e)throw new Error("Unable to create Occlusion Query");return e},Do.prototype.deleteQuery=function(e){return this._gl.deleteQuery(e),this},Do.prototype.isQueryResultAvailable=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT_AVAILABLE)},Do.prototype.getQueryResult=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT)},Do.prototype.beginOcclusionQuery=function(e,t){var i=this._getGlAlgorithmType(e);return this._gl.beginQuery(i,t),!0},Do.prototype.endOcclusionQuery=function(e){var t=this._getGlAlgorithmType(e);return this._gl.endQuery(t),this},Do.prototype._createTimeQuery=function(){var e=this.getCaps().timerQuery;return e.createQueryEXT?e.createQueryEXT():this.createQuery()},Do.prototype._deleteTimeQuery=function(e){var t=this.getCaps().timerQuery;t.deleteQueryEXT?t.deleteQueryEXT(e):this.deleteQuery(e)},Do.prototype._getTimeQueryResult=function(e){var t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT):this.getQueryResult(e)},Do.prototype._getTimeQueryAvailability=function(e){var t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT):this.isQueryResultAvailable(e)},Do.prototype.startTimeQuery=function(){var e=this.getCaps(),t=e.timerQuery;if(!t)return null;var i=new hp;if(this._gl.getParameter(t.GPU_DISJOINT_EXT),e.canUseTimestampForTimerQuery)i._startTimeQuery=this._createTimeQuery(),i._startTimeQuery&&t.queryCounterEXT(i._startTimeQuery,t.TIMESTAMP_EXT);else{if(this._currentNonTimestampToken)return this._currentNonTimestampToken;i._timeElapsedQuery=this._createTimeQuery(),i._timeElapsedQuery&&(t.beginQueryEXT?t.beginQueryEXT(t.TIME_ELAPSED_EXT,i._timeElapsedQuery):this._gl.beginQuery(t.TIME_ELAPSED_EXT,i._timeElapsedQuery)),this._currentNonTimestampToken=i}return i},Do.prototype.endTimeQuery=function(e){var t=this.getCaps(),i=t.timerQuery;if(!i||!e)return-1;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery)return-1;e._endTimeQuery||(e._endTimeQuery=this._createTimeQuery(),e._endTimeQuery&&i.queryCounterEXT(e._endTimeQuery,i.TIMESTAMP_EXT))}else if(!e._timeElapsedQueryEnded){if(!e._timeElapsedQuery)return-1;i.endQueryEXT?i.endQueryEXT(i.TIME_ELAPSED_EXT):(this._gl.endQuery(i.TIME_ELAPSED_EXT),this._currentNonTimestampToken=null),e._timeElapsedQueryEnded=!0}var r=this._gl.getParameter(i.GPU_DISJOINT_EXT),n=!1;if(e._endTimeQuery?n=this._getTimeQueryAvailability(e._endTimeQuery):e._timeElapsedQuery&&(n=this._getTimeQueryAvailability(e._timeElapsedQuery)),n&&!r){var o=0;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery||!e._endTimeQuery)return-1;var a=this._getTimeQueryResult(e._startTimeQuery);o=this._getTimeQueryResult(e._endTimeQuery)-a,this._deleteTimeQuery(e._startTimeQuery),this._deleteTimeQuery(e._endTimeQuery),e._startTimeQuery=null,e._endTimeQuery=null}else{if(!e._timeElapsedQuery)return-1;o=this._getTimeQueryResult(e._timeElapsedQuery),this._deleteTimeQuery(e._timeElapsedQuery),e._timeElapsedQuery=null,e._timeElapsedQueryEnded=!1}return o}return-1},Do.prototype._captureGPUFrameTime=!1,Do.prototype._gpuFrameTime=new an,Do.prototype.getGPUFrameTimeCounter=function(){return this._gpuFrameTime},Do.prototype.captureGPUFrameTime=function(e){var t=this;e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,e?(this._onBeginFrameObserver=this.onBeginFrameObservable.add((function(){t._gpuFrameTimeToken||(t._gpuFrameTimeToken=t.startTimeQuery())})),this._onEndFrameObserver=this.onEndFrameObservable.add((function(){if(t._gpuFrameTimeToken){var e=t.endTimeQuery(t._gpuFrameTimeToken);e>-1&&(t._gpuFrameTimeToken=null,t._gpuFrameTime.fetchNewFrame(),t._gpuFrameTime.addCount(e,!0))}}))):(this.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))},Do.prototype._getGlAlgorithmType=function(e){return e===Uo.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED};var dp=!0;Do.prototype.createTransformFeedback=function(){var e=this._gl.createTransformFeedback();if(!e)throw new Error("Unable to create Transform Feedback");return e},Do.prototype.deleteTransformFeedback=function(e){this._gl.deleteTransformFeedback(e)},Do.prototype.bindTransformFeedback=function(e){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,e)},Do.prototype.beginTransformFeedback=function(e){void 0===e&&(e=!0),this._gl.beginTransformFeedback(e?this._gl.POINTS:this._gl.TRIANGLES)},Do.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},Do.prototype.setTranformFeedbackVaryings=function(e,t){this._gl.transformFeedbackVaryings(e,t,this._gl.INTERLEAVED_ATTRIBS)},Do.prototype.bindTransformFeedbackBuffer=function(e){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e?e.underlyingResource:null)},Er.prototype.updateVideoTexture=function(e,t,i){if(e&&!e._isDisabled){var r=this._getInternalFormat(e.format),n=this._getRGBABufferInternalSizedFormat(u.TEXTURETYPE_UNSIGNED_BYTE,e.format),o=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,n,r,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,n,r,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=this.createCanvas(e.width,e.height);var a=e._workingCanvas.getContext("2d");if(!a)throw new Error("Unable to get 2d context");e._workingContext=a,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.clearRect(0,0,e.width,e.height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,n,r,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),o||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}}},Er.prototype.restoreSingleAttachment=function(){var e=this._gl;this.bindAttachments([e.BACK])},Er.prototype.restoreSingleAttachmentForRenderTarget=function(){var e=this._gl;this.bindAttachments([e.COLOR_ATTACHMENT0])},Er.prototype.buildTextureLayout=function(e){for(var t=this._gl,i=[],r=0;r<e.length;r++)e[r]?i.push(t["COLOR_ATTACHMENT"+r]):i.push(t.NONE);return i},Er.prototype.bindAttachments=function(e){this._gl.drawBuffers(e)},Er.prototype.unBindMultiColorAttachmentFramebuffer=function(e,t,i){void 0===t&&(t=!1),this._currentRenderTarget=null;var r=this._gl,n=e._attachments,o=n.length;if(e._MSAAFramebuffer){r.bindFramebuffer(r.READ_FRAMEBUFFER,e._MSAAFramebuffer),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,e._framebuffer);for(var a=0;a<o;a++){for(var s=e.textures[a],l=0;l<o;l++)n[l]=r.NONE;n[a]=r[this.webGLVersion>1?"COLOR_ATTACHMENT"+a:"COLOR_ATTACHMENT"+a+"_WEBGL"],r.readBuffer(n[a]),r.drawBuffers(n),r.blitFramebuffer(0,0,s.width,s.height,0,0,s.width,s.height,r.COLOR_BUFFER_BIT,r.NEAREST)}for(a=0;a<o;a++)n[a]=r[this.webGLVersion>1?"COLOR_ATTACHMENT"+a:"COLOR_ATTACHMENT"+a+"_WEBGL"];r.drawBuffers(n)}for(a=0;a<o;a++)!(null==(s=e.textures[a])?void 0:s.generateMipMaps)||t||(null==s?void 0:s.isCube)||(null==s?void 0:s.is3D)||(this._bindTextureDirectly(r.TEXTURE_2D,s,!0),r.generateMipmap(r.TEXTURE_2D),this._bindTextureDirectly(r.TEXTURE_2D,null));i&&(e._MSAAFramebuffer&&this._bindUnboundFramebuffer(e._framebuffer),i()),this._bindUnboundFramebuffer(null)},Er.prototype.createMultipleRenderTarget=function(e,t,i){var r,n;void 0===i&&(i=!0);var o=!1,a=!0,s=!1,l=!1,c=u.TEXTUREFORMAT_DEPTH16,h=1,d=u.TEXTURETYPE_UNSIGNED_INT,p=u.TEXTURE_TRILINEAR_SAMPLINGMODE,f=u.TEXTUREFORMAT_RGBA,_=u.TEXTURE_2D,m=[],g=[],v=[],y=[],b=[],T=[],E=[],S=[],x=this._createHardwareRenderTargetWrapper(!0,!1,e);void 0!==t&&(o=void 0!==t.generateMipMaps&&t.generateMipMaps,a=void 0===t.generateDepthBuffer||t.generateDepthBuffer,s=void 0!==t.generateStencilBuffer&&t.generateStencilBuffer,l=void 0!==t.generateDepthTexture&&t.generateDepthTexture,h=t.textureCount||1,t.types&&(m=t.types),t.samplingModes&&(g=t.samplingModes),t.useSRGBBuffers&&(v=t.useSRGBBuffers),t.formats&&(y=t.formats),t.targetTypes&&(b=t.targetTypes),t.faceIndex&&(T=t.faceIndex),t.layerIndex&&(E=t.layerIndex),t.layerCounts&&(S=t.layerCounts),this.webGLVersion>1&&(t.depthTextureFormat===u.TEXTUREFORMAT_DEPTH24_STENCIL8||t.depthTextureFormat===u.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||t.depthTextureFormat===u.TEXTUREFORMAT_DEPTH24||t.depthTextureFormat===u.TEXTUREFORMAT_DEPTH32_FLOAT||t.depthTextureFormat===u.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8)&&(c=t.depthTextureFormat)),x.label=null!==(r=null==t?void 0:t.label)&&void 0!==r?r:"MultiRenderTargetWrapper";var A=this._gl,C=A.createFramebuffer();this._bindUnboundFramebuffer(C);var R=e.width||e,P=e.height||e,I=[],M=[],O=this.webGLVersion>1&&l&&(t.depthTextureFormat===u.TEXTUREFORMAT_DEPTH24_STENCIL8||t.depthTextureFormat===u.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||t.depthTextureFormat===u.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8),D=this._setupFramebufferDepthAttachments(!O&&s,!l&&a,R,P);x._framebuffer=C,x._depthStencilBuffer=D,x._generateDepthBuffer=!l&&a,x._generateStencilBuffer=!O&&s,x._attachments=M;for(var N=0;N<h;N++){var F=g[N]||p,L=m[N]||d,w=v[N]||!1,B=y[N]||f,U=b[N]||_,V=null!==(n=S[N])&&void 0!==n?n:1;(L!==u.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(L!==u.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(F=u.TEXTURE_NEAREST_SAMPLINGMODE);var k=this._getSamplingParameters(F,o);L!==u.TEXTURETYPE_FLOAT||this._caps.textureFloat||(L=u.TEXTURETYPE_UNSIGNED_INT,ae.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),w=w&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU);var G=this.webGLVersion>1,z=A[G?"COLOR_ATTACHMENT"+N:"COLOR_ATTACHMENT"+N+"_WEBGL"];if(M.push(z),-1!==U){var W=new Pi(this,Ti.MultiRenderTarget);I[N]=W,A.activeTexture(A["TEXTURE"+N]),A.bindTexture(U,W._hardwareTexture.underlyingResource),A.texParameteri(U,A.TEXTURE_MAG_FILTER,k.mag),A.texParameteri(U,A.TEXTURE_MIN_FILTER,k.min),A.texParameteri(U,A.TEXTURE_WRAP_S,A.CLAMP_TO_EDGE),A.texParameteri(U,A.TEXTURE_WRAP_T,A.CLAMP_TO_EDGE);var H=this._getRGBABufferInternalSizedFormat(L,B,w),X=this._getInternalFormat(B),j=this._getWebGLTextureType(L);if(!G||U!==u.TEXTURE_2D_ARRAY&&U!==u.TEXTURE_3D)if(U===u.TEXTURE_CUBE_MAP){for(var Y=0;Y<6;Y++)A.texImage2D(A.TEXTURE_CUBE_MAP_POSITIVE_X+Y,0,H,R,P,0,X,j,null);W.isCube=!0}else A.texImage2D(A.TEXTURE_2D,0,H,R,P,0,X,j,null);else U===u.TEXTURE_2D_ARRAY?W.is2DArray=!0:W.is3D=!0,W.baseDepth=W.depth=V,A.texImage3D(U,0,H,R,P,V,0,X,j,null);o&&A.generateMipmap(U),this._bindTextureDirectly(U,null),W.baseWidth=R,W.baseHeight=P,W.width=R,W.height=P,W.isReady=!0,W.samples=1,W.generateMipMaps=o,W.samplingMode=F,W.type=L,W._useSRGBBuffer=w,W.format=B,this._internalTexturesCache.push(W)}}if(l&&this._caps.depthTextureExtension){var K=new Pi(this,Ti.Depth),Q=u.TEXTURETYPE_UNSIGNED_SHORT,q=A.DEPTH_COMPONENT16,Z=A.DEPTH_COMPONENT,J=A.UNSIGNED_SHORT,$=A.DEPTH_ATTACHMENT;this.webGLVersion<2?q=A.DEPTH_COMPONENT:c===u.TEXTUREFORMAT_DEPTH32_FLOAT?(Q=u.TEXTURETYPE_FLOAT,J=A.FLOAT,q=A.DEPTH_COMPONENT32F):c===u.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8?(Q=u.TEXTURETYPE_UNSIGNED_INT,J=A.FLOAT_32_UNSIGNED_INT_24_8_REV,q=A.DEPTH32F_STENCIL8,Z=A.DEPTH_STENCIL,$=A.DEPTH_STENCIL_ATTACHMENT):c===u.TEXTUREFORMAT_DEPTH24?(Q=u.TEXTURETYPE_UNSIGNED_INT,J=A.UNSIGNED_INT,q=A.DEPTH_COMPONENT24,$=A.DEPTH_ATTACHMENT):c!==u.TEXTUREFORMAT_DEPTH24_STENCIL8&&c!==u.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||(Q=u.TEXTURETYPE_UNSIGNED_INT_24_8,J=A.UNSIGNED_INT_24_8,q=A.DEPTH24_STENCIL8,Z=A.DEPTH_STENCIL,$=A.DEPTH_STENCIL_ATTACHMENT),A.activeTexture(A.TEXTURE0),A.bindTexture(A.TEXTURE_2D,K._hardwareTexture.underlyingResource),A.texParameteri(A.TEXTURE_2D,A.TEXTURE_MAG_FILTER,A.NEAREST),A.texParameteri(A.TEXTURE_2D,A.TEXTURE_MIN_FILTER,A.NEAREST),A.texParameteri(A.TEXTURE_2D,A.TEXTURE_WRAP_S,A.CLAMP_TO_EDGE),A.texParameteri(A.TEXTURE_2D,A.TEXTURE_WRAP_T,A.CLAMP_TO_EDGE),A.texImage2D(A.TEXTURE_2D,0,q,R,P,0,Z,J,null),A.framebufferTexture2D(A.FRAMEBUFFER,$,A.TEXTURE_2D,K._hardwareTexture.underlyingResource,0),K.baseWidth=R,K.baseHeight=P,K.width=R,K.height=P,K.isReady=!0,K.samples=1,K.generateMipMaps=o,K.samplingMode=u.TEXTURE_NEAREST_SAMPLINGMODE,K.format=c,K.type=Q,I[h]=K,this._internalTexturesCache.push(K)}return x.setTextures(I),i&&A.drawBuffers(M),this._bindUnboundFramebuffer(null),x.setLayerAndFaceIndices(E,T),this.resetTextureCache(),x},Er.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t,i){if(void 0===i&&(i=!0),this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;var r=e._attachments.length;if(0===r)return 1;var n=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples);var o=!!e._depthStencilBuffer;if(o&&(n.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(n.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),t>1&&"function"==typeof n.renderbufferStorageMultisample){var a=n.createFramebuffer();if(!a)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=a,this._bindUnboundFramebuffer(a);for(var s=[],l=0;l<r;l++)(u=(c=e.textures[l])._hardwareTexture).releaseMSAARenderBuffers();for(l=0;l<r;l++){var c,u=(c=e.textures[l])._hardwareTexture,h=n[this.webGLVersion>1?"COLOR_ATTACHMENT"+l:"COLOR_ATTACHMENT"+l+"_WEBGL"],d=this._createRenderBuffer(c.width,c.height,t,-1,this._getRGBABufferInternalSizedFormat(c.type,c.format,c._useSRGBBuffer),h);if(!d)throw new Error("Unable to create multi sampled framebuffer");u.addMSAARenderBuffer(d),c.samples=t,s.push(h)}i&&n.drawBuffers(s)}else this._bindUnboundFramebuffer(e._framebuffer);return o&&(e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t)),this._bindUnboundFramebuffer(null),t},Er.prototype._createDepthStencilCubeTexture=function(e,t){var i=new Pi(this,Ti.DepthStencil);if(i.isCube=!0,1===this.webGLVersion)return ae.Error("Depth cube texture is not supported by WebGL 1."),i;var r=g({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},t),n=this._gl;this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,i,!0),this._setupDepthStencilTexture(i,e,r.generateStencil,r.bilinearFiltering,r.comparisonFunction);for(var o=0;o<6;o++)r.generateStencil?n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+o,0,n.DEPTH24_STENCIL8,e,e,0,n.DEPTH_STENCIL,n.UNSIGNED_INT_24_8,null):n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+o,0,n.DEPTH_COMPONENT24,e,e,0,n.DEPTH_COMPONENT,n.UNSIGNED_INT,null);return this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(i),i},Er.prototype._setCubeMapTextureParams=function(e,t,i){var r=this._gl;r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,t?r.LINEAR_MIPMAP_LINEAR:r.LINEAR),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),e.samplingMode=t?u.TEXTURE_TRILINEAR_SAMPLINGMODE:u.TEXTURE_LINEAR_LINEAR,t&&this.getCaps().textureMaxLevel&&void 0!==i&&i>0&&(r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAX_LEVEL,i),e._maxLodLevel=i),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null)},Er.prototype.createCubeTexture=function(e,t,i,r,n,o,a,s,l,c,u,h,d,p){var f=this;void 0===n&&(n=null),void 0===o&&(o=null),void 0===s&&(s=null),void 0===l&&(l=!1),void 0===c&&(c=0),void 0===u&&(u=0),void 0===h&&(h=null),void 0===p&&(p=!1);var _=this._gl;return this.createCubeTextureBase(e,t,i,!!r,n,o,a,s,l,c,u,h,(function(e){return f._bindTextureDirectly(_.TEXTURE_CUBE_MAP,e,!0)}),(function(e,t){var i=f.needPOTTextures?ir(t[0].width,f._caps.maxCubemapTextureSize):t[0].width,o=i,s=[_.TEXTURE_CUBE_MAP_POSITIVE_X,_.TEXTURE_CUBE_MAP_POSITIVE_Y,_.TEXTURE_CUBE_MAP_POSITIVE_Z,_.TEXTURE_CUBE_MAP_NEGATIVE_X,_.TEXTURE_CUBE_MAP_NEGATIVE_Y,_.TEXTURE_CUBE_MAP_NEGATIVE_Z];f._bindTextureDirectly(_.TEXTURE_CUBE_MAP,e,!0),f._unpackFlipY(!1);var l=a?f._getInternalFormat(a,e._useSRGBBuffer):e._useSRGBBuffer?f._glSRGBExtensionValues.SRGB8_ALPHA8:_.RGBA,c=a?f._getInternalFormat(a):_.RGBA;e._useSRGBBuffer&&1===f.webGLVersion&&(c=l);for(var u=0;u<s.length;u++)if(t[u].width!==i||t[u].height!==o){if(f._prepareWorkingCanvas(),!f._workingCanvas||!f._workingContext)return void ae.Warn("Cannot create canvas to resize texture.");f._workingCanvas.width=i,f._workingCanvas.height=o,f._workingContext.drawImage(t[u],0,0,t[u].width,t[u].height,0,0,i,o),_.texImage2D(s[u],0,l,c,_.UNSIGNED_BYTE,f._workingCanvas)}else _.texImage2D(s[u],0,l,c,_.UNSIGNED_BYTE,t[u]);r||_.generateMipmap(_.TEXTURE_CUBE_MAP),f._setCubeMapTextureParams(e,!r),e.width=i,e.height=o,e.isReady=!0,a&&(e.format=a),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),n&&n()}),!!p)};var pp=function(){},fp=new f,_p=new f;function mp(e){if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some((function(t){var i="\\b"+t+"\\b";return e&&(e===t||e.match(new RegExp(i,"g")))})))return e;var t=e.lastIndexOf("."),i=e.lastIndexOf("?"),r=i>-1?e.substring(i,e.length):"";return(t>-1?e.substring(0,t):e)+this._textureFormatInUse+r}Object.defineProperty(Do.prototype,"onBeforeViewRenderObservable",{get:function(){return fp}}),Object.defineProperty(Do.prototype,"onAfterViewRenderObservable",{get:function(){return _p}}),Object.defineProperty(Do.prototype,"inputElement",{get:function(){return this._inputElement},set:function(e){var t;this._inputElement!==e&&(this._inputElement=e,null===(t=this._onEngineViewChanged)||void 0===t||t.call(this))}}),Do.prototype.getInputElement=function(){return this.inputElement||this.getRenderingCanvas()},Do.prototype.registerView=function(e,t,i){var r=this;this.views||(this.views=[]);for(var n=0,o=this.views;n<o.length;n++){var a=o[n];if(a.target===e)return a}var s=this.getRenderingCanvas();s&&(e.width=s.width,e.height=s.height);var l={target:e,camera:t,clearBeforeCopy:i,enabled:!0,id:(1e5*Math.random()).toFixed()};return this.views.push(l),t&&!Array.isArray(t)&&t.onDisposeObservable.add((function(){r.unRegisterView(e)})),l},Do.prototype.unRegisterView=function(e){if(!this.views||0===this.views.length)return this;for(var t=0,i=this.views;t<i.length;t++){var r=i[t];if(r.target===e){var n=this.views.indexOf(r);-1!==n&&this.views.splice(n,1);break}}return this},Do.prototype._renderViewStep=function(e){var t=e.target,i=t.getContext("2d");if(!i)return!0;var r=this.getRenderingCanvas();fp.notifyObservers(e);var n=e.camera,o=null,a=null,s=null;if(n&&(o=(s=Array.isArray(n)?n[0].getScene():n.getScene()).activeCamera,a=s.activeCameras,this.activeView=e,Array.isArray(n)?s.activeCameras=n:(s.activeCamera=n,s.activeCameras=null)),e.customResize)e.customResize(t);else{var l=Math.floor(t.clientWidth/this._hardwareScalingLevel),c=Math.floor(t.clientHeight/this._hardwareScalingLevel),u=l!==t.width||r.width!==t.width||c!==t.height||r.height!==t.height;t.clientWidth&&t.clientHeight&&u&&(t.width=l,t.height=c,this.setSize(l,c))}return!(!r.width||!r.height||(this._renderFrame(),this.flushFramebuffer(),e.clearBeforeCopy&&i.clearRect(0,0,r.width,r.height),i.drawImage(r,0,0),s&&(s.activeCameras=a,s.activeCamera=o),_p.notifyObservers(e),0))},Do.prototype._renderViews=function(){if(!this.views||0===this.views.length)return!1;var e;if(!this.getRenderingCanvas())return!1;for(var t=0,i=this.views;t<i.length;t++){var r=i[t];if(r.enabled)if(r.target!==this.inputElement){if(!this._renderViewStep(r))return!1}else e=r}return!(e&&!this._renderViewStep(e)||(this.activeView=null,0))},Object.defineProperty(Do.prototype,"texturesSupported",{get:function(){var e=[];return this._caps.astc&&e.push("-astc.ktx"),this._caps.s3tc&&e.push("-dxt.ktx"),this._caps.pvrtc&&e.push("-pvrtc.ktx"),this._caps.etc2&&e.push("-etc2.ktx"),this._caps.etc1&&e.push("-etc1.ktx"),e},enumerable:!0,configurable:!0}),Object.defineProperty(Do.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0}),Do.prototype.setCompressedTextureExclusions=function(e){this._excludedCompressedTextures=e},Do.prototype.setTextureFormatToUse=function(e){for(var t=this.texturesSupported,i=0,r=t.length;i<r;i++)for(var n=0,o=e.length;n<o;n++)if(t[i]===e[n].toLowerCase())return this._transformTextureUrl=mp.bind(this),this._textureFormatInUse=t[i];return this._textureFormatInUse="",this._transformTextureUrl=null,null};var gp=function(){function e(){var t=this,i=new ArrayBuffer(e.DEFAULT_BUFFER_SIZE);this._uint32s=new Uint32Array(i),this._int32s=new Int32Array(i),this._float32s=new Float32Array(i),this._length=e.DEFAULT_BUFFER_SIZE/4,this._position=0,this._nativeDataStream=new _native.NativeDataStream((function(){t._flush()}))}return e.prototype.writeUint32=function(e){this._flushIfNecessary(1),this._uint32s[this._position++]=e},e.prototype.writeInt32=function(e){this._flushIfNecessary(1),this._int32s[this._position++]=e},e.prototype.writeFloat32=function(e){this._flushIfNecessary(1),this._float32s[this._position++]=e},e.prototype.writeUint32Array=function(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._uint32s.set(e,this._position),this._position+=e.length},e.prototype.writeInt32Array=function(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._int32s.set(e,this._position),this._position+=e.length},e.prototype.writeFloat32Array=function(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._float32s.set(e,this._position),this._position+=e.length},e.prototype.writeNativeData=function(e){this._flushIfNecessary(e.length),this._uint32s.set(e,this._position),this._position+=e.length},e.prototype.writeBoolean=function(e){this.writeUint32(e?1:0)},e.prototype._flushIfNecessary=function(e){this._position+e>this._length&&this._flush()},e.prototype._flush=function(){this._nativeDataStream.writeBuffer(this._uint32s.buffer,this._position),this._position=0},e.DEFAULT_BUFFER_SIZE=65536,e}(),vp=[Math.sqrt(1/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(3/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(15/(4*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(5/(16*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(15/(16*Math.PI))],yp=[function(){return 1},function(e){return e.y},function(e){return e.z},function(e){return e.x},function(e){return e.x*e.y},function(e){return e.y*e.z},function(e){return 3*e.z*e.z-1},function(e){return e.x*e.z},function(e){return e.x*e.x-e.y*e.y}],bp=function(e,t){return vp[e]*yp[e](t)},Tp=[Math.PI,2*Math.PI/3,2*Math.PI/3,2*Math.PI/3,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4],Ep=function(){function e(){this.preScaled=!1,this.l00=V.Zero(),this.l1_1=V.Zero(),this.l10=V.Zero(),this.l11=V.Zero(),this.l2_2=V.Zero(),this.l2_1=V.Zero(),this.l20=V.Zero(),this.l21=V.Zero(),this.l22=V.Zero()}return e.prototype.addLight=function(e,t,i){H.Vector3[0].set(t.r,t.g,t.b);var r=H.Vector3[0],n=H.Vector3[1];r.scaleToRef(i,n),n.scaleToRef(bp(0,e),H.Vector3[2]),this.l00.addInPlace(H.Vector3[2]),n.scaleToRef(bp(1,e),H.Vector3[2]),this.l1_1.addInPlace(H.Vector3[2]),n.scaleToRef(bp(2,e),H.Vector3[2]),this.l10.addInPlace(H.Vector3[2]),n.scaleToRef(bp(3,e),H.Vector3[2]),this.l11.addInPlace(H.Vector3[2]),n.scaleToRef(bp(4,e),H.Vector3[2]),this.l2_2.addInPlace(H.Vector3[2]),n.scaleToRef(bp(5,e),H.Vector3[2]),this.l2_1.addInPlace(H.Vector3[2]),n.scaleToRef(bp(6,e),H.Vector3[2]),this.l20.addInPlace(H.Vector3[2]),n.scaleToRef(bp(7,e),H.Vector3[2]),this.l21.addInPlace(H.Vector3[2]),n.scaleToRef(bp(8,e),H.Vector3[2]),this.l22.addInPlace(H.Vector3[2])},e.prototype.scaleInPlace=function(e){this.l00.scaleInPlace(e),this.l1_1.scaleInPlace(e),this.l10.scaleInPlace(e),this.l11.scaleInPlace(e),this.l2_2.scaleInPlace(e),this.l2_1.scaleInPlace(e),this.l20.scaleInPlace(e),this.l21.scaleInPlace(e),this.l22.scaleInPlace(e)},e.prototype.convertIncidentRadianceToIrradiance=function(){this.l00.scaleInPlace(Tp[0]),this.l1_1.scaleInPlace(Tp[1]),this.l10.scaleInPlace(Tp[2]),this.l11.scaleInPlace(Tp[3]),this.l2_2.scaleInPlace(Tp[4]),this.l2_1.scaleInPlace(Tp[5]),this.l20.scaleInPlace(Tp[6]),this.l21.scaleInPlace(Tp[7]),this.l22.scaleInPlace(Tp[8])},e.prototype.convertIrradianceToLambertianRadiance=function(){this.scaleInPlace(1/Math.PI)},e.prototype.preScaleForRendering=function(){this.preScaled=!0,this.l00.scaleInPlace(vp[0]),this.l1_1.scaleInPlace(vp[1]),this.l10.scaleInPlace(vp[2]),this.l11.scaleInPlace(vp[3]),this.l2_2.scaleInPlace(vp[4]),this.l2_1.scaleInPlace(vp[5]),this.l20.scaleInPlace(vp[6]),this.l21.scaleInPlace(vp[7]),this.l22.scaleInPlace(vp[8])},e.prototype.updateFromArray=function(e){return V.FromArrayToRef(e[0],0,this.l00),V.FromArrayToRef(e[1],0,this.l1_1),V.FromArrayToRef(e[2],0,this.l10),V.FromArrayToRef(e[3],0,this.l11),V.FromArrayToRef(e[4],0,this.l2_2),V.FromArrayToRef(e[5],0,this.l2_1),V.FromArrayToRef(e[6],0,this.l20),V.FromArrayToRef(e[7],0,this.l21),V.FromArrayToRef(e[8],0,this.l22),this},e.prototype.updateFromFloatsArray=function(e){return V.FromFloatsToRef(e[0],e[1],e[2],this.l00),V.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),V.FromFloatsToRef(e[6],e[7],e[8],this.l10),V.FromFloatsToRef(e[9],e[10],e[11],this.l11),V.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),V.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),V.FromFloatsToRef(e[18],e[19],e[20],this.l20),V.FromFloatsToRef(e[21],e[22],e[23],this.l21),V.FromFloatsToRef(e[24],e[25],e[26],this.l22),this},e.FromArray=function(t){return(new e).updateFromArray(t)},e.FromPolynomial=function(t){var i=new e;return i.l00=t.xx.scale(.376127).add(t.yy.scale(.376127)).add(t.zz.scale(.376126)),i.l1_1=t.y.scale(.977204),i.l10=t.z.scale(.977204),i.l11=t.x.scale(.977204),i.l2_2=t.xy.scale(1.16538),i.l2_1=t.yz.scale(1.16538),i.l20=t.zz.scale(1.34567).subtract(t.xx.scale(.672834)).subtract(t.yy.scale(.672834)),i.l21=t.zx.scale(1.16538),i.l22=t.xx.scale(1.16538).subtract(t.yy.scale(1.16538)),i.l1_1.scaleInPlace(-1),i.l11.scaleInPlace(-1),i.l2_1.scaleInPlace(-1),i.l21.scaleInPlace(-1),i.scaleInPlace(Math.PI),i},e}(),Sp=function(){function e(){this.x=V.Zero(),this.y=V.Zero(),this.z=V.Zero(),this.xx=V.Zero(),this.yy=V.Zero(),this.zz=V.Zero(),this.xy=V.Zero(),this.yz=V.Zero(),this.zx=V.Zero()}return Object.defineProperty(e.prototype,"preScaledHarmonics",{get:function(){return this._harmonics||(this._harmonics=Ep.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics},enumerable:!1,configurable:!0}),e.prototype.addAmbient=function(e){H.Vector3[0].copyFromFloats(e.r,e.g,e.b);var t=H.Vector3[0];this.xx.addInPlace(t),this.yy.addInPlace(t),this.zz.addInPlace(t)},e.prototype.scaleInPlace=function(e){this.x.scaleInPlace(e),this.y.scaleInPlace(e),this.z.scaleInPlace(e),this.xx.scaleInPlace(e),this.yy.scaleInPlace(e),this.zz.scaleInPlace(e),this.yz.scaleInPlace(e),this.zx.scaleInPlace(e),this.xy.scaleInPlace(e)},e.prototype.updateFromHarmonics=function(e){return this._harmonics=e,this.x.copyFrom(e.l11),this.x.scaleInPlace(1.02333).scaleInPlace(-1),this.y.copyFrom(e.l1_1),this.y.scaleInPlace(1.02333).scaleInPlace(-1),this.z.copyFrom(e.l10),this.z.scaleInPlace(1.02333),this.xx.copyFrom(e.l00),H.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),H.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(H.Vector3[0]).addInPlace(H.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(H.Vector3[0]).subtractInPlace(H.Vector3[1]),this.zz.copyFrom(e.l00),H.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(H.Vector3[0]),this.yz.copyFrom(e.l2_1),this.yz.scaleInPlace(.858086).scaleInPlace(-1),this.zx.copyFrom(e.l21),this.zx.scaleInPlace(.858086).scaleInPlace(-1),this.xy.copyFrom(e.l2_2),this.xy.scaleInPlace(.858086),this.scaleInPlace(1/Math.PI),this},e.FromHarmonics=function(t){return(new e).updateFromHarmonics(t)},e.FromArray=function(t){var i=new e;return V.FromArrayToRef(t[0],0,i.x),V.FromArrayToRef(t[1],0,i.y),V.FromArrayToRef(t[2],0,i.z),V.FromArrayToRef(t[3],0,i.xx),V.FromArrayToRef(t[4],0,i.yy),V.FromArrayToRef(t[5],0,i.zz),V.FromArrayToRef(t[6],0,i.yz),V.FromArrayToRef(t[7],0,i.zx),V.FromArrayToRef(t[8],0,i.xy),i},e}();li.ShadersStore.rgbdDecodePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include<helperFunctions>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}";li.ShadersStore.lodPixelShader="#extension GL_EXT_shader_texture_lod : enable\nprecision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform sampler2D textureSampler;uniform float lod;uniform vec2 texSize;uniform bool gamma;void main(void)\n{gl_FragColor=textureLod(textureSampler,vUV,lod);if (!gamma) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";var xp,Ap;function Cp(e,t,i,r){void 0===r&&(r=!0);var n=e.getScene(),o=n.getEngine(),a=new Pl("resized"+e.name,{width:t,height:i},n,!e.noMipmap,!0,e._texture.type,!1,e.samplingMode,!1);a.wrapU=e.wrapU,a.wrapV=e.wrapV,a.uOffset=e.uOffset,a.vOffset=e.vOffset,a.uScale=e.uScale,a.vScale=e.vScale,a.uAng=e.uAng,a.vAng=e.vAng,a.wAng=e.wAng,a.coordinatesIndex=e.coordinatesIndex,a.level=e.level,a.anisotropicFilteringLevel=e.anisotropicFilteringLevel,a._texture.isReady=!1,e.wrapU=Ja.CLAMP_ADDRESSMODE,e.wrapV=Ja.CLAMP_ADDRESSMODE;var s=new qc("pass",1,null,r?Ja.BILINEAR_SAMPLINGMODE:Ja.NEAREST_SAMPLINGMODE,o,!1,u.TEXTURETYPE_UNSIGNED_INT);return s.externalTextureSamplerBinding=!0,s.getEffect().executeWhenCompiled((function(){s.onApply=function(t){t.setTexture("textureSampler",e)};var t=a.renderTarget;t&&(n.postProcessManager.directRender([s],t),o.unBindFramebuffer(t),a.disposeFramebufferObjects(),s.dispose(),a.getInternalTexture().isReady=!0)})),a}function Rp(e,t,i,r,n,o,a,s){var l=t.getEngine();return t.isReady=!1,n=null!=n?n:t.samplingMode,r=null!=r?r:t.type,o=null!=o?o:t.format,a=null!=a?a:t.width,s=null!=s?s:t.height,-1===r&&(r=u.TEXTURETYPE_UNSIGNED_BYTE),new Promise((function(c){var h=new hl("postprocess",e,null,null,1,null,n,l,!1,void 0,r,void 0,null,!1,o);h.externalTextureSamplerBinding=!0;var d=l.createRenderTargetTexture({width:a,height:s},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:n,type:r,format:o});h.getEffect().executeWhenCompiled((function(){h.onApply=function(e){e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([h],d,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(t),h&&h.dispose(),d._swapAndDie(t),t.type=r,t.format=u.TEXTUREFORMAT_RGBA,t.isReady=!0,c(t)}))}))}function Pp(e){xp||(xp=new Float32Array(1),Ap=new Int32Array(xp.buffer)),xp[0]=e;var t=Ap[0],i=t>>16&32768,r=t>>12&2047,n=t>>23&255;return n<103?i:n>142?(i|=31744,i|=(255==n?0:1)&&8388607&t):n<113?i|=((r|=2048)>>114-n)+(r>>113-n&1):(i|=n-112<<10|r>>1,i+=1&r)}function Ip(e){var t=(32768&e)>>15,i=(31744&e)>>10,r=1023&e;return 0===i?(t?-1:1)*Math.pow(2,-14)*(r/Math.pow(2,10)):31==i?r?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,i-15)*(1+r/Math.pow(2,10))}li.ShadersStore.lodCubePixelShader="precision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform samplerCube textureSampler;uniform float lod;uniform bool gamma;void main(void)\n{vec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x),lod);\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x),lod);\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x),lod);\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x),lod);\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001),lod);\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001),lod);\n#endif\nif (!gamma) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";var Mp=function(e,t,i,r,n){return y(void 0,void 0,void 0,(function(){var o,a,s,l,c,u,h,d,p;return b(this,(function(f){switch(f.label){case 0:return o=e.getScene(),a=o.getEngine(),e.isCube?(l=["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"],s=new hl("lodCube","lodCube",["lod","gamma"],null,1,null,Ja.NEAREST_NEAREST_MIPNEAREST,a,!1,l[r])):s=new hl("lod","lod",["lod","gamma"],null,1,null,Ja.NEAREST_NEAREST_MIPNEAREST,a),[4,new Promise((function(e){s.getEffect().executeWhenCompiled((function(){e(0)}))}))];case 1:f.sent(),c=new Pl("temp",{width:t,height:i},o,!1),s.onApply=function(t){t.setTexture("textureSampler",e),t.setFloat("lod",n),t.setBool("gamma",e.gammaSpace)},u=e.getInternalTexture(),f.label=2;case 2:return f.trys.push([2,,6,7]),c.renderTarget&&u?(h=u.samplingMode,0!==n?e.updateSamplingMode(Ja.NEAREST_NEAREST_MIPNEAREST):e.updateSamplingMode(Ja.NEAREST_NEAREST),o.postProcessManager.directRender([s],c.renderTarget,!0),e.updateSamplingMode(h),[4,a.readPixels(0,0,t,i)]):[3,4];case 3:return d=f.sent(),p=new Uint8Array(d.buffer,0,d.byteLength),a.unBindFramebuffer(c.renderTarget),[2,p];case 4:throw Error("Render to texture failed.");case 5:return[3,7];case 6:return c.dispose(),s.dispose(),[7];case 7:return[2]}}))}))};function Op(e,t,i,r,n){return void 0===r&&(r=0),void 0===n&&(n=0),y(this,void 0,void 0,(function(){return b(this,(function(o){switch(o.label){case 0:return e.isReady()||!e._texture?[3,2]:[4,new Promise((function(t,i){null!==e._texture?e._texture.onLoadedObservable.addOnce((function(){t(0)})):i(0)}))];case 1:o.sent(),o.label=2;case 2:return[4,Mp(e,t,i,r,n)];case 3:return[2,o.sent()]}}))}))}var Dp={CreateResizedCopy:Cp,ApplyPostProcess:Rp,ToHalfFloat:Pp,FromHalfFloat:Ip,GetTextureDataAsync:Op},Np=function(){function e(){}return e.ExpandRGBDTexture=function(e){var t=e._texture;if(t&&e.isRGBD){var i=t.getEngine(),r=i.getCaps(),n=t.isReady,o=!1;r.textureHalfFloatRender&&r.textureHalfFloatLinearFiltering?(o=!0,t.type=u.TEXTURETYPE_HALF_FLOAT):r.textureFloatRender&&r.textureFloatLinearFiltering&&(o=!0,t.type=u.TEXTURETYPE_FLOAT),o&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);var a=function(){var r=new hl("rgbdDecode","rgbdDecode",null,null,1,null,u.TEXTURE_TRILINEAR_SAMPLINGMODE,i,!1,void 0,t.type,void 0,null,!1);r.externalTextureSamplerBinding=!0;var n=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:u.TEXTUREFORMAT_RGBA});r.getEffect().executeWhenCompiled((function(){r.onApply=function(e){e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([r],n,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),r&&r.dispose(),n._swapAndDie(t),t.isReady=!0}))};o&&(n?a():e.onLoadObservable.addOnce(a))}},e.EncodeTextureToRGBD=function(e,t,i){return void 0===i&&(i=u.TEXTURETYPE_UNSIGNED_BYTE),Rp("rgbdEncode",e,t,i,u.TEXTURE_NEAREST_SAMPLINGMODE,u.TEXTUREFORMAT_RGBA)},e}(),Fp=function(e,t,i,r){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=r},Lp=function(){function e(){}return e.ConvertCubeMapTextureToSphericalPolynomial=function(e){var t,i=this;if(!e.isCube)return null;null===(t=e.getScene())||void 0===t||t.getEngine().flushFramebuffer();var r,n,o=e.getSize().width,a=e.readPixels(0,void 0,void 0,!1),s=e.readPixels(1,void 0,void 0,!1);e.isRenderTarget?(r=e.readPixels(3,void 0,void 0,!1),n=e.readPixels(2,void 0,void 0,!1)):(r=e.readPixels(2,void 0,void 0,!1),n=e.readPixels(3,void 0,void 0,!1));var l=e.readPixels(4,void 0,void 0,!1),c=e.readPixels(5,void 0,void 0,!1),h=e.gammaSpace,d=u.TEXTUREFORMAT_RGBA,p=u.TEXTURETYPE_UNSIGNED_INT;return e.textureType!=u.TEXTURETYPE_FLOAT&&e.textureType!=u.TEXTURETYPE_HALF_FLOAT||(p=u.TEXTURETYPE_FLOAT),new Promise((function(e){Promise.all([s,a,r,n,l,c]).then((function(t){var r=t[0],n=t[1],a=t[2],s=t[3],l=t[4],c=t[5],u={size:o,right:n,left:r,up:a,down:s,front:l,back:c,format:d,type:p,gammaSpace:h};e(i.ConvertCubeMapToSphericalPolynomial(u))}))}))},e._AreaElement=function(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))},e.ConvertCubeMapToSphericalPolynomial=function(e){for(var t=new Ep,i=0,r=2/e.size,n=r,o=.5*r,a=o-1,s=0;s<6;s++)for(var l=this._FileFaces[s],c=e[l.name],h=a,d=e.format===u.TEXTUREFORMAT_RGBA?4:3,p=0;p<e.size;p++){for(var f=a,_=0;_<e.size;_++){var m=l.worldAxisForFileX.scale(f).add(l.worldAxisForFileY.scale(h)).add(l.worldAxisForNormal);m.normalize();var g=this._AreaElement(f-o,h-o)-this._AreaElement(f-o,h+o)-this._AreaElement(f+o,h-o)+this._AreaElement(f+o,h+o),v=c[p*e.size*d+_*d+0],y=c[p*e.size*d+_*d+1],b=c[p*e.size*d+_*d+2];isNaN(v)&&(v=0),isNaN(y)&&(y=0),isNaN(b)&&(b=0),e.type===u.TEXTURETYPE_UNSIGNED_INT&&(v/=255,y/=255,b/=255),e.gammaSpace&&(v=Math.pow(j.Clamp(v),S),y=Math.pow(j.Clamp(y),S),b=Math.pow(j.Clamp(b),S));var T=this.MAX_HDRI_VALUE;if(this.PRESERVE_CLAMPED_COLORS){var E=Math.max(v,y,b);if(E>T){var x=T/E;v*=x,y*=x,b*=x}}else v=j.Clamp(v,0,T),y=j.Clamp(y,0,T),b=j.Clamp(b,0,T);var A=new Z(v,y,b);t.addLight(m,A,g),i+=g,f+=r}h+=n}var C=4*Math.PI*6/6/i;return t.scaleInPlace(C),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),Sp.FromHarmonics(t)},e._FileFaces=[new Fp("right",new V(1,0,0),new V(0,0,-1),new V(0,-1,0)),new Fp("left",new V(-1,0,0),new V(0,0,1),new V(0,-1,0)),new Fp("up",new V(0,1,0),new V(1,0,0),new V(0,0,1)),new Fp("down",new V(0,-1,0),new V(1,0,0),new V(0,0,-1)),new Fp("front",new V(0,0,1),new V(1,0,0),new V(0,-1,0)),new Fp("back",new V(0,0,-1),new V(-1,0,0),new V(0,-1,0))],e.MAX_HDRI_VALUE=4096,e.PRESERVE_CLAMPED_COLORS=!1,e}();Ya.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(Ya.prototype,"sphericalPolynomial",{get:function(){var e=this;if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;if(this._texture.isReady)return this._texture._sphericalPolynomialPromise||(this._texture._sphericalPolynomialPromise=Lp.ConvertCubeMapTextureToSphericalPolynomial(this),null===this._texture._sphericalPolynomialPromise?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then((function(t){e._texture._sphericalPolynomial=t,e._texture._sphericalPolynomialComputed=!0}))),null}return null},set:function(e){this._texture&&(this._texture._sphericalPolynomial=e)},enumerable:!0,configurable:!0});li.ShadersStore.rgbdEncodePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include<helperFunctions>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}";var wp="image/png",Bp=2,Up=[134,22,135,150,246,214,150,54];function Vp(e){for(var t=new DataView(e.buffer,e.byteOffset,e.byteLength),i=0,r=0;r<Up.length;r++)if(t.getUint8(i++)!==Up[r])return ae.Error("Not a babylon environment map"),null;for(var n="",o=0;o=t.getUint8(i++);)n+=String.fromCharCode(o);var a=JSON.parse(n);return(a=kp(a)).specular&&(a.specular.specularDataPosition=i,a.specular.lodGenerationScale=a.specular.lodGenerationScale||.8),a}function kp(e){if(e.version>Bp)throw new Error('Unsupported babylon environment map version "'.concat(e.version,'". Latest supported version is "').concat(Bp,'".'));return 2===e.version?e:e=g(g({},e),{version:2,imageType:wp})}function Gp(e,t){var i,r;return void 0===t&&(t={}),y(this,void 0,void 0,(function(){var n,o,a,s,l,c,h,d,p,f,_,m,g,v,y,T,E,S,x,A,C,R,P,I,M,O,D,N,F,L,w,B,U;return b(this,(function(b){switch(b.label){case 0:if(!(n=e.getInternalTexture()))return[2,Promise.reject("The cube texture is invalid.")];if(o=null!==(i=t.imageType)&&void 0!==i?i:wp,a=n.getEngine(),e.textureType!==u.TEXTURETYPE_HALF_FLOAT&&e.textureType!==u.TEXTURETYPE_FLOAT&&e.textureType!==u.TEXTURETYPE_UNSIGNED_BYTE&&e.textureType!==u.TEXTURETYPE_UNSIGNED_INT&&e.textureType!==u.TEXTURETYPE_UNSIGNED_INTEGER&&-1!==e.textureType)return[2,Promise.reject("The cube texture should allow HDR (Full Float or Half Float).")];if(s=u.TEXTURETYPE_FLOAT,!a.getCaps().textureFloatRender&&(s=u.TEXTURETYPE_HALF_FLOAT,!a.getCaps().textureHalfFloatRender))return[2,Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.")];e.sphericalPolynomial,l=null===(r=e.getInternalTexture())||void 0===r?void 0:r._sphericalPolynomialPromise,c=n.width,h=new pn(a),d={},a.flushFramebuffer(),p=j.ILog2(n.width),w=0,b.label=1;case 1:if(!(w<=p))return[3,9];f=Math.pow(2,p-w),B=0,b.label=2;case 2:return B<6?[4,e.readPixels(B,w,void 0,!1)]:[3,8];case 3:if((_=b.sent())&&_.byteLength===_.length){for(m=new Float32Array(4*_.byteLength),g=0;g<_.byteLength;g++)m[g]=_[g]/255,m[g]=Math.pow(m[g],2.2);_=m}else if(_&&e.gammaSpace)for(v=_,y=0;y<v.length;y++)v[y]=Math.pow(v[y],2.2);return T=a.createRawTexture(_,f,f,u.TEXTUREFORMAT_RGBA,!1,!0,u.TEXTURE_NEAREST_SAMPLINGMODE,null,s),[4,Np.EncodeTextureToRGBD(T,h,s)];case 4:return b.sent(),[4,a._readTexturePixels(T,f,f)];case 5:return E=b.sent(),[4,Rl.DumpDataAsync(f,f,E,o,void 0,!1,!0,t.imageQuality)];case 6:S=b.sent(),d[6*w+B]=S,T.dispose(),b.label=7;case 7:return B++,[3,2];case 8:return w++,[3,1];case 9:return h.dispose(),l?[4,l]:[3,11];case 10:b.sent(),b.label=11;case 11:for(x={version:Bp,width:c,imageType:o,irradiance:zp(e),specular:{mipmaps:[],lodGenerationScale:e.lodGenerationScale}},A=0,w=0;w<=p;w++)for(B=0;B<6;B++)C=d[6*w+B].byteLength,x.specular.mipmaps.push({length:C,position:A}),A+=C;for(R=JSON.stringify(x),P=new ArrayBuffer(R.length+1),I=new Uint8Array(P),w=0,M=R.length;w<M;w++)I[w]=R.charCodeAt(w);for(I[R.length]=0,O=Up.length+A+P.byteLength,D=new ArrayBuffer(O),N=new Uint8Array(D),F=new DataView(D),L=0,w=0;w<Up.length;w++)F.setUint8(L++,Up[w]);for(N.set(new Uint8Array(P),L),L+=P.byteLength,w=0;w<=p;w++)for(B=0;B<6;B++)U=d[6*w+B],N.set(new Uint8Array(U),L),L+=U.byteLength;return[2,D]}}))}))}function zp(e){var t=e.sphericalPolynomial;return null==t?null:{x:[t.x.x,t.x.y,t.x.z],y:[t.y.x,t.y.y,t.y.z],z:[t.z.x,t.z.y,t.z.z],xx:[t.xx.x,t.xx.y,t.xx.z],yy:[t.yy.x,t.yy.y,t.yy.z],zz:[t.zz.x,t.zz.y,t.zz.z],yz:[t.yz.x,t.yz.y,t.yz.z],zx:[t.zx.x,t.zx.y,t.zx.z],xy:[t.xy.x,t.xy.y,t.xy.z]}}function Wp(e,t){var i=(t=kp(t)).specular,r=j.Log2(t.width);if(r=Math.round(r)+1,i.mipmaps.length!==6*r)throw new Error('Unsupported specular mipmaps number "'.concat(i.mipmaps.length,'"'));for(var n=new Array(r),o=0;o<r;o++){n[o]=new Array(6);for(var a=0;a<6;a++){var s=i.mipmaps[6*o+a];n[o][a]=new Uint8Array(e.buffer,e.byteOffset+i.specularDataPosition+s.position,s.length)}}return n}function Hp(e,t,i){var r=(i=kp(i)).specular;return r?(e._lodGenerationScale=r.lodGenerationScale,jp(e,Wp(t,i),i.imageType)):Promise.resolve()}function Xp(e,t,i,r,n,o,a,s,l,c,h){return new Promise((function(d,p){if(i){var f=t.createTexture(null,!0,!0,null,u.TEXTURE_NEAREST_SAMPLINGMODE,null,(function(e){p(e)}),e);r.getEffect().executeWhenCompiled((function(){r.externalTextureSamplerBinding=!0,r.onApply=function(i){i._bindTexture("textureSampler",f),i.setFloat2("scale",1,t._features.needsInvertingBitmap&&e instanceof ImageBitmap?-1:1)},t.scenes.length&&(t.scenes[0].postProcessManager.directRender([r],c,!0,o,a),t.restoreDefaultFramebuffer(),f.dispose(),URL.revokeObjectURL(n),d())}))}else{if(t._uploadImageToTexture(h,e,o,a),s){var _=l[a];_&&t._uploadImageToTexture(_._texture,e,o,0)}d()}}))}function jp(e,t,i){if(void 0===i&&(i=wp),!rr.IsExponentOfTwo(e.width))throw new Error("Texture size must be a power of two");var r=j.ILog2(e.width)+1,n=e.getEngine(),o=!1,a=!1,s=null,l=null,c=null,h=n.getCaps();if(e.format=u.TEXTUREFORMAT_RGBA,e.type=u.TEXTURETYPE_UNSIGNED_INT,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,n.updateTextureSamplingMode(u.TEXTURE_TRILINEAR_SAMPLINGMODE,e),h.textureLOD?n._features.supportRenderAndCopyToLodForFloatTextures?h.textureHalfFloatRender&&h.textureHalfFloatLinearFiltering?(o=!0,e.type=u.TEXTURETYPE_HALF_FLOAT):h.textureFloatRender&&h.textureFloatLinearFiltering&&(o=!0,e.type=u.TEXTURETYPE_FLOAT):o=!1:(o=!1,a=!0,c={}),o)s=new hl("rgbdDecode","rgbdDecode",null,null,1,null,u.TEXTURE_TRILINEAR_SAMPLINGMODE,n,!1,void 0,e.type,void 0,null,!1),e._isRGBD=!1,e.invertY=!1,l=n.createRenderTargetCubeTexture(e.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:u.TEXTURE_TRILINEAR_SAMPLINGMODE,type:e.type,format:u.TEXTUREFORMAT_RGBA});else if(e._isRGBD=!0,e.invertY=!0,a)for(var d=e._lodGenerationScale,p=e._lodGenerationOffset,f=0;f<3;f++){var _=(r-1)*d+p,m=p+(_-p)*(1-f/2),g=Math.round(Math.min(Math.max(m,0),_)),v=new Pi(n,Ti.Temp);v.isCube=!0,v.invertY=!0,v.generateMipMaps=!1,n.updateTextureSamplingMode(u.TEXTURE_LINEAR_LINEAR,v);var y=new Ya(null);switch(y._isCube=!0,y._texture=v,c[g]=y,f){case 0:e._lodTextureLow=y;break;case 1:e._lodTextureMid=y;break;case 2:e._lodTextureHigh=y}}var b=[],T=function(r){for(var u=function(u){var h=t[r][u],d=new Blob([h],{type:i}),p=URL.createObjectURL(d),f=void 0;if(n._features.forceBitmapOverHTMLImageElement)f=n.createImageBitmap(d,{premultiplyAlpha:"none"}).then((function(t){return Xp(t,n,o,s,p,u,r,a,c,l,e)}));else{var _=new Image;_.src=p,f=new Promise((function(t,i){_.onload=function(){Xp(_,n,o,s,p,u,r,a,c,l,e).then((function(){return t()})).catch((function(e){i(e)}))},_.onerror=function(e){i(e)}}))}b.push(f)},h=0;h<6;h++)u(h)};for(f=0;f<t.length;f++)T(f);if(t.length<r){var E=void 0,S=Math.pow(2,r-1-t.length),x=S*S*4;switch(e.type){case u.TEXTURETYPE_UNSIGNED_INT:E=new Uint8Array(x);break;case u.TEXTURETYPE_HALF_FLOAT:E=new Uint16Array(x);break;case u.TEXTURETYPE_FLOAT:E=new Float32Array(x)}for(f=t.length;f<r;f++)for(var A=0;A<6;A++)n._uploadArrayBufferViewToTexture(e,E,A,f)}return Promise.all(b).then((function(){l&&(n._releaseTexture(e),l._swapAndDie(e)),s&&s.dispose(),a&&(e._lodTextureHigh&&e._lodTextureHigh._texture&&(e._lodTextureHigh._texture.isReady=!0),e._lodTextureMid&&e._lodTextureMid._texture&&(e._lodTextureMid._texture.isReady=!0),e._lodTextureLow&&e._lodTextureLow._texture&&(e._lodTextureLow._texture.isReady=!0))}))}function Yp(e,t){var i=(t=kp(t)).irradiance;if(i){var r=new Sp;V.FromArrayToRef(i.x,0,r.x),V.FromArrayToRef(i.y,0,r.y),V.FromArrayToRef(i.z,0,r.z),V.FromArrayToRef(i.xx,0,r.xx),V.FromArrayToRef(i.yy,0,r.yy),V.FromArrayToRef(i.zz,0,r.zz),V.FromArrayToRef(i.yz,0,r.yz),V.FromArrayToRef(i.zx,0,r.zx),V.FromArrayToRef(i.xy,0,r.xy),e._sphericalPolynomial=r}}function Kp(e,t,i,r,n){var o=jp(e.getEngine().createRawCubeTexture(null,e.width,e.format,e.type,e.generateMipMaps,e.invertY,e.samplingMode,e._compression),t).then((function(){return e}));return e.onRebuildCallback=function(e){return{proxy:o,isReady:!0,isAsync:!0}},e._source=Ti.CubeRawRGBD,e._bufferViewArrayArray=t,e._lodGenerationScale=r,e._lodGenerationOffset=n,e._sphericalPolynomial=i,jp(e,t).then((function(){return e.isReady=!0,e}))}var Qp={GetEnvInfo:Vp,CreateEnvTextureAsync:Gp,CreateImageDataArrayBufferViews:Wp,UploadEnvLevelsAsync:Hp,UploadLevelsAsync:jp,UploadEnvSpherical:Yp};function qp(e,t,i,r){for(var n=r,o=0,a="";n<i.length;){var s=i.charAt(n);if(a)s===a?'"'===a||"'"===a?"\\"!==i.charAt(n-1)&&(a=""):a="":"*/"===a&&"*"===s&&n+1<i.length&&("/"===i.charAt(n+1)&&(a=""),""===a&&n++);else switch(s){case e:o++;break;case t:o--;break;case'"':case"'":case"`":a=s;break;case"/":if(n+1<i.length){var l=i.charAt(n+1);"/"===l?a="\n":"*"===l&&(a="*/")}}if(n++,0===o)break}return 0===o?n-1:-1}function Zp(e,t){for(;t<e.length;){var i=e[t];if(" "!==i&&"\n"!==i&&"\r"!==i&&"\t"!==i&&"\n"!==i&&" "!==i)break;t++}return t}function Jp(e){var t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95==t}function $p(e){for(var t=0,i="",r=!1,n=[];t<e.length;){var o=e.charAt(t);if(i)o===i?'"'===i||"'"===i?("\\"!==e.charAt(t-1)&&(i=""),n.push(o)):(i="",r=!1):"*/"===i&&"*"===o&&t+1<e.length?("/"===e.charAt(t+1)&&(i=""),""===i&&(r=!1,t++)):r||n.push(o);else{switch(o){case'"':case"'":case"`":i=o;break;case"/":if(t+1<e.length){var a=e.charAt(t+1);"/"===a?(i="\n",r=!0):"*"===a&&(i="*/",r=!0)}}r||n.push(o)}t++}return n.join("")}function ef(e,t,i,r){for(;t>=0&&e.charAt(t)!==i&&(!r||e.charAt(t)!==r);)t--;return t}var tf=function(){function e(e,t){void 0===t&&(t=20),this.debug=!1,this._sourceCode=e,this._numMaxIterations=t,this._functionDescr=[],this.inlineToken="#define inline"}return Object.defineProperty(e.prototype,"code",{get:function(){return this._sourceCode},enumerable:!1,configurable:!0}),e.prototype.processCode=function(){this.debug&&ae.Log("Start inlining process (code size=".concat(this._sourceCode.length,")...")),this._collectFunctions(),this._processInlining(this._numMaxIterations),this.debug&&ae.Log("End of inlining process.")},e.prototype._collectFunctions=function(){for(var t,i=0;i<this._sourceCode.length;){var r=this._sourceCode.indexOf(this.inlineToken,i);if(r<0)break;var n=this._sourceCode.indexOf("(",r+this.inlineToken.length);if(n<0)this.debug&&ae.Warn("Could not find the opening parenthesis after the token. startIndex=".concat(i)),i=r+this.inlineToken.length;else{var o=e._RegexpFindFunctionNameAndType.exec(this._sourceCode.substring(r+this.inlineToken.length,n));if(o){var a=(t=[o[3],o[4]])[0],s=t[1],l=qp("(",")",this._sourceCode,n);if(l<0)this.debug&&ae.Warn("Could not extract the parameters the function '".concat(s,"' (type=").concat(a,"). funcParamsStartIndex=").concat(n)),i=r+this.inlineToken.length;else{var c=this._sourceCode.substring(n+1,l),u=Zp(this._sourceCode,l+1);if(u!==this._sourceCode.length){var h=qp("{","}",this._sourceCode,u);if(h<0)this.debug&&ae.Warn("Could not extract the body of the function '".concat(s,"' (type=").concat(a,"). funcBodyStartIndex=").concat(u)),i=r+this.inlineToken.length;else{for(var d=this._sourceCode.substring(u,h+1),p=$p(c).split(","),f=[],_=0;_<p.length;++_){var m=p[_].trim(),g=m.lastIndexOf(" ");g>=0&&f.push(m.substring(g+1))}"void"!==a&&f.push("return"),this._functionDescr.push({name:s,type:a,parameters:f,body:d,callIndex:0}),i=h+1;var v=r>0?this._sourceCode.substring(0,r):"",y=h+1<this._sourceCode.length-1?this._sourceCode.substring(h+1):"";this._sourceCode=v+y,i-=h+1-r}}else this.debug&&ae.Warn("Could not extract the body of the function '".concat(s,"' (type=").concat(a,"). funcParamsEndIndex=").concat(l)),i=r+this.inlineToken.length}}else this.debug&&ae.Warn("Could not extract the name/type of the function from: ".concat(this._sourceCode.substring(r+this.inlineToken.length,n))),i=r+this.inlineToken.length}}this.debug&&ae.Log("Collect functions: ".concat(this._functionDescr.length," functions found. functionDescr=").concat(this._functionDescr))},e.prototype._processInlining=function(e){for(void 0===e&&(e=20);e-- >=0&&this._replaceFunctionCallsByCode(););return this.debug&&ae.Log("numMaxIterations is ".concat(e," after inlining process")),e>=0},e.prototype._replaceFunctionCallsByCode=function(){for(var e=!1,t=0,i=this._functionDescr;t<i.length;t++)for(var r=i[t],n=r.name,o=r.type,a=r.parameters,s=r.body,l=0;l<this._sourceCode.length;){var c=this._sourceCode.indexOf(n,l);if(c<0)break;if(0===c||Jp(this._sourceCode.charAt(c-1)))l=c+n.length;else{var u=Zp(this._sourceCode,c+n.length);if(u!==this._sourceCode.length&&"("===this._sourceCode.charAt(u)){var h=qp("(",")",this._sourceCode,u);if(h<0)this.debug&&ae.Warn("Could not extract the parameters of the function call. Function '".concat(n,"' (type=").concat(o,"). callParamsStartIndex=").concat(u)),l=c+n.length;else{var d=this._sourceCode.substring(u+1,h),p=function(e){for(var t=[],i=0,r=0;i<e.length;){if("("===e.charAt(i)){var n=qp("(",")",e,i);if(n<0)return null;i=n}else","===e.charAt(i)&&(t.push(e.substring(r,i)),r=i+1);i++}return r<i&&t.push(e.substring(r,i)),t}($p(d));if(null!==p){for(var f=[],_=0;_<p.length;++_){var m=p[_].trim();f.push(m)}var g="void"!==o?n+"_"+r.callIndex++:null;if(g&&f.push(g+" ="),f.length===a.length){l=h+1;var v=this._replaceNames(s,a,f),y=c>0?this._sourceCode.substring(0,c):"",b=h+1<this._sourceCode.length-1?this._sourceCode.substring(h+1):"";if(g){var T=ef(this._sourceCode,c-1,"\n","{");y=this._sourceCode.substring(0,T+1);var E=this._sourceCode.substring(T+1,c);this._sourceCode=y+o+" "+g+";\n"+v+"\n"+E+g+b,this.debug&&ae.Log("Replace function call by code. Function '".concat(n,"' (type=").concat(o,"). injectDeclarationIndex=").concat(T,", call parameters=").concat(f))}else this._sourceCode=y+v+b,l+=v.length-(h+1-c),this.debug&&ae.Log("Replace function call by code. Function '".concat(n,"' (type=").concat(o,"). functionCallIndex=").concat(c,", call parameters=").concat(f));e=!0}else this.debug&&ae.Warn("Invalid function call: not the same number of parameters for the call than the number expected by the function. Function '".concat(n,"' (type=").concat(o,"). function parameters=").concat(a,", call parameters=").concat(f)),l=c+n.length}else this.debug&&ae.Warn("Invalid function call: can't extract the parameters of the function call. Function '".concat(n,"' (type=").concat(o,"). callParamsStartIndex=").concat(u,", callParams=")+d),l=c+n.length}}else l=c+n.length}}return e},e.prototype._replaceNames=function(e,t,i){for(var r=function(r){var n=new RegExp(t[r].replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),o=t[r].length,a=i[r];e=e.replace(n,(function(i){for(var n=[],s=1;s<arguments.length;s++)n[s-1]=arguments[s];var l=n[0];return Jp(e.charAt(l-1))||Jp(e.charAt(l+o))?t[r]:a}))},n=0;n<t.length;++n)r(n);return e},e._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/,e}(),rf=function(){function e(e,t){this.isCompiled=!1,this._valueCache={},this._engine=e,this.isAsync=t}return Object.defineProperty(e.prototype,"isReady",{get:function(){if(this.compilationError){var e=this.compilationError.message;throw new Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}return this.isCompiled},enumerable:!1,configurable:!0}),e.prototype._getVertexShaderCode=function(){return null},e.prototype._getFragmentShaderCode=function(){return null},e.prototype._fillEffectInformation=function(e,t,i,r,n,o,a,s){var l,c=this._engine;if(c.supportsUniformBuffers)for(var u in t)e.bindUniformBlock(u,t[u]);for(this._engine.getUniforms(this,i).forEach((function(e,t){r[i[t]]=e})),this._uniforms=r,l=0;l<n.length;l++)null==e.getUniform(n[l])&&(n.splice(l,1),l--);n.forEach((function(e,t){o[e]=t})),s.push.apply(s,c.getAttributes(this,a))},e.prototype.setEngine=function(e){this._engine=e},e.prototype.dispose=function(){this._uniforms={}},e.prototype._cacheMatrix=function(e,t){var i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)},e.prototype._cacheFloat2=function(e,t,i){var r=this._valueCache[e];if(!r)return r=[t,i],this._valueCache[e]=r,!0;var n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),n},e.prototype._cacheFloat3=function(e,t,i,r){var n=this._valueCache[e];if(!n)return n=[t,i,r],this._valueCache[e]=n,!0;var o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==r&&(n[2]=r,o=!0),o},e.prototype._cacheFloat4=function(e,t,i,r,n){var o=this._valueCache[e];if(!o)return o=[t,i,r,n],this._valueCache[e]=o,!0;var a=!1;return o[0]!==t&&(o[0]=t,a=!0),o[1]!==i&&(o[1]=i,a=!0),o[2]!==r&&(o[2]=r,a=!0),o[3]!==n&&(o[3]=n,a=!0),a},e.prototype.setInt=function(e,t){var i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)},e.prototype.setInt2=function(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))},e.prototype.setInt3=function(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this._engine.setInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))},e.prototype.setInt4=function(e,t,i,r,n){this._cacheFloat4(e,t,i,r,n)&&(this._engine.setInt4(this._uniforms[e],t,i,r,n)||(this._valueCache[e]=null))},e.prototype.setIntArray=function(e,t){this._valueCache[e]=null,this._engine.setIntArray(this._uniforms[e],t)},e.prototype.setIntArray2=function(e,t){this._valueCache[e]=null,this._engine.setIntArray2(this._uniforms[e],t)},e.prototype.setIntArray3=function(e,t){this._valueCache[e]=null,this._engine.setIntArray3(this._uniforms[e],t)},e.prototype.setIntArray4=function(e,t){this._valueCache[e]=null,this._engine.setIntArray4(this._uniforms[e],t)},e.prototype.setUInt=function(e,t){var i=this._valueCache[e];void 0!==i&&i===t||this._engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)},e.prototype.setUInt2=function(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))},e.prototype.setUInt3=function(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this._engine.setUInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))},e.prototype.setUInt4=function(e,t,i,r,n){this._cacheFloat4(e,t,i,r,n)&&(this._engine.setUInt4(this._uniforms[e],t,i,r,n)||(this._valueCache[e]=null))},e.prototype.setUIntArray=function(e,t){this._valueCache[e]=null,this._engine.setUIntArray(this._uniforms[e],t)},e.prototype.setUIntArray2=function(e,t){this._valueCache[e]=null,this._engine.setUIntArray2(this._uniforms[e],t)},e.prototype.setUIntArray3=function(e,t){this._valueCache[e]=null,this._engine.setUIntArray3(this._uniforms[e],t)},e.prototype.setUIntArray4=function(e,t){this._valueCache[e]=null,this._engine.setUIntArray4(this._uniforms[e],t)},e.prototype.setFloatArray=function(e,t){this._valueCache[e]=null,this._engine.setFloatArray(this._uniforms[e],t)},e.prototype.setFloatArray2=function(e,t){this._valueCache[e]=null,this._engine.setFloatArray2(this._uniforms[e],t)},e.prototype.setFloatArray3=function(e,t){this._valueCache[e]=null,this._engine.setFloatArray3(this._uniforms[e],t)},e.prototype.setFloatArray4=function(e,t){this._valueCache[e]=null,this._engine.setFloatArray4(this._uniforms[e],t)},e.prototype.setArray=function(e,t){this._valueCache[e]=null,this._engine.setArray(this._uniforms[e],t)},e.prototype.setArray2=function(e,t){this._valueCache[e]=null,this._engine.setArray2(this._uniforms[e],t)},e.prototype.setArray3=function(e,t){this._valueCache[e]=null,this._engine.setArray3(this._uniforms[e],t)},e.prototype.setArray4=function(e,t){this._valueCache[e]=null,this._engine.setArray4(this._uniforms[e],t)},e.prototype.setMatrices=function(e,t){t&&(this._valueCache[e]=null,this._engine.setMatrices(this._uniforms[e],t))},e.prototype.setMatrix=function(e,t){this._cacheMatrix(e,t)&&(this._engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))},e.prototype.setMatrix3x3=function(e,t){this._valueCache[e]=null,this._engine.setMatrix3x3(this._uniforms[e],t)},e.prototype.setMatrix2x2=function(e,t){this._valueCache[e]=null,this._engine.setMatrix2x2(this._uniforms[e],t)},e.prototype.setFloat=function(e,t){var i=this._valueCache[e];void 0!==i&&i===t||this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)},e.prototype.setBool=function(e,t){var i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t?1:0)&&(this._valueCache[e]=t?1:0)},e.prototype.setVector2=function(e,t){this._cacheFloat2(e,t.x,t.y)&&(this._engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))},e.prototype.setFloat2=function(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))},e.prototype.setVector3=function(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this._engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))},e.prototype.setFloat3=function(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this._engine.setFloat3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))},e.prototype.setVector4=function(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))},e.prototype.setQuaternion=function(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))},e.prototype.setFloat4=function(e,t,i,r,n){this._cacheFloat4(e,t,i,r,n)&&(this._engine.setFloat4(this._uniforms[e],t,i,r,n)||(this._valueCache[e]=null))},e.prototype.setColor3=function(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this._engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))},e.prototype.setColor4=function(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))},e.prototype.setDirectColor4=function(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))},e}(),nf=function(e){function t(t,i,r,n){var o=e.call(this,t,i,r,n)||this;return o.__framebuffer=null,o.__framebufferDepthStencil=null,o._engine=n,o}return m(t,e),Object.defineProperty(t.prototype,"_framebuffer",{get:function(){return this.__framebuffer},set:function(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_framebufferDepthStencil",{get:function(){return this.__framebufferDepthStencil},set:function(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e},enumerable:!1,configurable:!0}),t.prototype.dispose=function(t){void 0===t&&(t=!1),this._framebuffer=null,this._framebufferDepthStencil=null,e.prototype.dispose.call(this,t)},t}(cl),of=function(){function e(e,t){this._engine=t,this.set(e)}return Object.defineProperty(e.prototype,"underlyingResource",{get:function(){return this._nativeTexture},enumerable:!1,configurable:!0}),e.prototype.setUsage=function(){},e.prototype.set=function(e){this._nativeTexture=e},e.prototype.reset=function(){this._nativeTexture=null},e.prototype.release=function(){this._nativeTexture&&this._engine.deleteTexture(this._nativeTexture),this.reset()},e}();function af(e,t){switch(e){case u.TEXTUREFORMAT_DEPTH16:return _native.Engine.TEXTURE_FORMAT_D16;case u.TEXTUREFORMAT_DEPTH24:return _native.Engine.TEXTURE_FORMAT_D24;case u.TEXTUREFORMAT_DEPTH24_STENCIL8:return _native.Engine.TEXTURE_FORMAT_D24S8;case u.TEXTUREFORMAT_DEPTH32_FLOAT:return _native.Engine.TEXTURE_FORMAT_D32F;case u.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM:return _native.Engine.TEXTURE_FORMAT_BC7;case u.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT:return _native.Engine.TEXTURE_FORMAT_BC6H;case u.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5:return _native.Engine.TEXTURE_FORMAT_BC3;case u.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3:return _native.Engine.TEXTURE_FORMAT_BC2;case u.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1:case u.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1:return _native.Engine.TEXTURE_FORMAT_BC1;case u.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4:return _native.Engine.TEXTURE_FORMAT_ASTC4x4;case u.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL:return _native.Engine.TEXTURE_FORMAT_ETC1;case u.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2:return _native.Engine.TEXTURE_FORMAT_ETC2;case u.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC:return _native.Engine.TEXTURE_FORMAT_ETC2A;case u.TEXTUREFORMAT_RGB:switch(t){case u.TEXTURETYPE_UNSIGNED_BYTE:return _native.Engine.TEXTURE_FORMAT_RGB8;case u.TEXTURETYPE_BYTE:return _native.Engine.TEXTURE_FORMAT_RGB8S;case u.TEXTURETYPE_INT:return _native.Engine.TEXTURE_FORMAT_RGB8I;case u.TEXTURETYPE_UNSIGNED_INTEGER:return _native.Engine.TEXTURE_FORMAT_RGB8U}break;case u.TEXTUREFORMAT_RGBA:switch(t){case u.TEXTURETYPE_UNSIGNED_BYTE:return _native.Engine.TEXTURE_FORMAT_RGBA8;case u.TEXTURETYPE_FLOAT:return _native.Engine.TEXTURE_FORMAT_RGBA32F;case u.TEXTURETYPE_HALF_FLOAT:return _native.Engine.TEXTURE_FORMAT_RGBA16F;case u.TEXTURETYPE_BYTE:return _native.Engine.TEXTURE_FORMAT_RGBA8S;case u.TEXTURETYPE_SHORT:return _native.Engine.TEXTURE_FORMAT_RGBA16I;case u.TEXTURETYPE_UNSIGNED_SHORT:return _native.Engine.TEXTURE_FORMAT_RGBA16U;case u.TEXTURETYPE_INT:return _native.Engine.TEXTURE_FORMAT_RGBA32I;case u.TEXTURETYPE_UNSIGNED_INTEGER:return _native.Engine.TEXTURE_FORMAT_RGBA32U}break;case u.TEXTUREFORMAT_R:switch(t){case u.TEXTURETYPE_UNSIGNED_BYTE:return _native.Engine.TEXTURE_FORMAT_R8;case u.TEXTURETYPE_FLOAT:return _native.Engine.TEXTURE_FORMAT_R32F;case u.TEXTURETYPE_HALF_FLOAT:return _native.Engine.TEXTURE_FORMAT_R16F;case u.TEXTURETYPE_BYTE:return _native.Engine.TEXTURE_FORMAT_R8S;case u.TEXTURETYPE_SHORT:return _native.Engine.TEXTURE_FORMAT_R16S;case u.TEXTURETYPE_UNSIGNED_SHORT:return _native.Engine.TEXTURE_FORMAT_R16U;case u.TEXTURETYPE_INT:return _native.Engine.TEXTURE_FORMAT_R32I;case u.TEXTURETYPE_UNSIGNED_INTEGER:return _native.Engine.TEXTURE_FORMAT_R32U}break;case u.TEXTUREFORMAT_RG:switch(t){case u.TEXTURETYPE_UNSIGNED_BYTE:return _native.Engine.TEXTURE_FORMAT_RG8;case u.TEXTURETYPE_FLOAT:return _native.Engine.TEXTURE_FORMAT_RG32F;case u.TEXTURETYPE_HALF_FLOAT:return _native.Engine.TEXTURE_FORMAT_RG16F;case u.TEXTURETYPE_BYTE:return _native.Engine.TEXTURE_FORMAT_RG8S;case u.TEXTURETYPE_SHORT:return _native.Engine.TEXTURE_FORMAT_RG16S;case u.TEXTURETYPE_UNSIGNED_SHORT:return _native.Engine.TEXTURE_FORMAT_RG16U;case u.TEXTURETYPE_INT:return _native.Engine.TEXTURE_FORMAT_RG32I;case u.TEXTURETYPE_UNSIGNED_INTEGER:return _native.Engine.TEXTURE_FORMAT_RG32U}break;case u.TEXTUREFORMAT_BGRA:if(t===u.TEXTURETYPE_UNSIGNED_BYTE)return _native.Engine.TEXTURE_FORMAT_BGRA8}throw new bt("Unsupported texture format or type: format ".concat(e,", type ").concat(t,"."),yt.UnsupportedTextureError)}function sf(e){switch(e){case u.TEXTURE_NEAREST_NEAREST:return _native.Engine.TEXTURE_NEAREST_NEAREST;case u.TEXTURE_LINEAR_LINEAR:return _native.Engine.TEXTURE_LINEAR_LINEAR;case u.TEXTURE_LINEAR_LINEAR_MIPLINEAR:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;case u.TEXTURE_NEAREST_NEAREST_MIPNEAREST:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;case u.TEXTURE_NEAREST_LINEAR_MIPNEAREST:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;case u.TEXTURE_NEAREST_LINEAR_MIPLINEAR:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;case u.TEXTURE_NEAREST_LINEAR:return _native.Engine.TEXTURE_NEAREST_LINEAR;case u.TEXTURE_NEAREST_NEAREST_MIPLINEAR:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;case u.TEXTURE_LINEAR_NEAREST_MIPNEAREST:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;case u.TEXTURE_LINEAR_NEAREST_MIPLINEAR:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;case u.TEXTURE_LINEAR_LINEAR_MIPNEAREST:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;case u.TEXTURE_LINEAR_NEAREST:return _native.Engine.TEXTURE_LINEAR_NEAREST;default:throw new Error("Unsupported sampling mode: ".concat(e,"."))}}function lf(e){switch(e){case u.TEXTURE_WRAP_ADDRESSMODE:return _native.Engine.ADDRESS_MODE_WRAP;case u.TEXTURE_CLAMP_ADDRESSMODE:return _native.Engine.ADDRESS_MODE_CLAMP;case u.TEXTURE_MIRROR_ADDRESSMODE:return _native.Engine.ADDRESS_MODE_MIRROR;default:throw new Error("Unexpected wrap mode: "+e+".")}}function cf(e){switch(e){case Nr.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case Nr.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case Nr.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case Nr.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case Nr.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw new Error("Unsupported attribute type: ".concat(e,"."))}}var uf,hf=new f;function df(){return new Promise((function(e){"undefined"==typeof _native?hf.addOnce((function(t){return e(t)})):e(_native)}))}function pf(e,t){return y(this,void 0,void 0,(function(){return b(this,(function(i){switch(i.label){case 0:return[4,df()];case 1:return i.sent()[e]=t,[2]}}))}))}"undefined"==typeof self||Object.prototype.hasOwnProperty.call(self,"_native")||Object.defineProperty(self,"_native",{get:function(){return uf},set:function(e){(uf=e)&&hf.notifyObservers(uf)}});var ff=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t}(vr),_f=function(){function e(e){this._engine=e,this._pending=new Array,this._isCommandBufferScopeActive=!1,this._commandStream=mf._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}return e.prototype.beginCommandScope=function(){if(this._isCommandBufferScopeActive)throw new Error("Command scope already active.");this._isCommandBufferScopeActive=!0},e.prototype.endCommandScope=function(){if(!this._isCommandBufferScopeActive)throw new Error("Command scope is not active.");this._isCommandBufferScopeActive=!1,this._submit()},e.prototype.startEncodingCommand=function(e){this._commandStream.writeNativeData(e)},e.prototype.encodeCommandArgAsUInt32=function(e){this._commandStream.writeUint32(e)},e.prototype.encodeCommandArgAsUInt32s=function(e){this._commandStream.writeUint32Array(e)},e.prototype.encodeCommandArgAsInt32=function(e){this._commandStream.writeInt32(e)},e.prototype.encodeCommandArgAsInt32s=function(e){this._commandStream.writeInt32Array(e)},e.prototype.encodeCommandArgAsFloat32=function(e){this._commandStream.writeFloat32(e)},e.prototype.encodeCommandArgAsFloat32s=function(e){this._commandStream.writeFloat32Array(e)},e.prototype.encodeCommandArgAsNativeData=function(e){this._commandStream.writeNativeData(e),this._pending.push(e)},e.prototype.finishEncodingCommand=function(){this._isCommandBufferScopeActive||this._submit()},e.prototype._submit=function(){this._engine.submitCommands(),this._pending.length=0},e}(),mf=function(e){function t(i){void 0===i&&(i={});var r=e.call(this,null,!1,void 0,i.adaptToDeviceRatio)||this;if(r._engine=new _native.Engine,r._camera=_native.Camera?new _native.Camera:null,r._commandBufferEncoder=new _f(r._engine),r._boundBuffersVertexArray=null,r._currentDepthTest=_native.Engine.DEPTH_TEST_LEQUAL,r._stencilTest=!1,r._stencilMask=255,r._stencilFunc=u.ALWAYS,r._stencilFuncRef=0,r._stencilFuncMask=255,r._stencilOpStencilFail=u.KEEP,r._stencilOpDepthFail=u.KEEP,r._stencilOpStencilDepthPass=u.REPLACE,r._zOffset=0,r._zOffsetUnits=0,r._depthWrite=!0,_native.Engine.PROTOCOL_VERSION!==t.PROTOCOL_VERSION)throw new Error("Protocol version mismatch: ".concat(_native.Engine.PROTOCOL_VERSION," (Native) !== ").concat(t.PROTOCOL_VERSION," (JS)"));r._engine.setDeviceLostCallback&&r._engine.setDeviceLostCallback((function(){r.onContextLostObservable.notifyObservers(r),r._contextWasLost=!0,r._restoreEngineAfterContextLost()})),r._webGLVersion=2,r.disableUniformBuffers=!0,r._shaderPlatformName="NATIVE",r._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_SIZE,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!0,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!0,textureFloatLinearFiltering:!0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:16,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1,parallelShaderCompile:{COMPLETION_STATUS_KHR:0}},r._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!0,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1},rr.Log("Babylon Native (v"+Do.Version+") launched"),rr.LoadScript=function(e,t,i,r){rr.LoadFile(e,(function(e){Function(e).apply(null),t&&t()}),void 0,void 0,!1,(function(e,t){i&&i("LoadScript Error",t)}))},"undefined"==typeof URL&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(window.Blob=function(e){return e}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function e(){var t=isNaN(arguments[0])?1:Number(arguments[0]);return t?Array.prototype.reduce.call(this,(function(i,r){return Array.isArray(r)?i.push.apply(i,e.call(r,t-1)):i.push(r),i}),[]):Array.prototype.slice.call(this)},writable:!0});var n=window&&window.devicePixelRatio||1;r._hardwareScalingLevel=i.adaptToDeviceRatio?1/n:1,r._engine.setHardwareScalingLevel(r._hardwareScalingLevel),r._lastDevicePixelRatio=n,r.resize();var o=r.getDepthFunction();return o&&r.setDepthFunction(o),r._shaderProcessor=new gr,r.onNewSceneAddedObservable.add((function(e){var t=e.render;e.render=function(){for(var i=[],n=0;n<arguments.length;n++)i[n]=arguments[n];r._commandBufferEncoder.beginCommandScope(),t.apply(e,i),r._commandBufferEncoder.endCommandScope()}})),r}return m(t,e),t.prototype.setHardwareScalingLevel=function(t){e.prototype.setHardwareScalingLevel.call(this,t),this._engine.setHardwareScalingLevel(t)},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()},t._createNativeDataStream=function(){return new gp},t.prototype._queueNewFrame=function(e,t){return t.requestAnimationFrame&&t!==window?t.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0},t.prototype._restoreEngineAfterContextLost=function(){this._clearEmptyResources();var e=this._depthCullingState.depthTest,t=this._depthCullingState.depthFunc,i=this._depthCullingState.depthMask,r=this._stencilState.stencilTest;this._rebuildGraphicsResources(),this._depthCullingState.depthTest=e,this._depthCullingState.depthFunc=t,this._depthCullingState.depthMask=i,this._stencilState.stencilTest=r,this._flagContextRestored()},t.prototype._bindUnboundFramebuffer=function(e){this._currentFramebuffer!==e&&(this._currentFramebuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer),this._commandBufferEncoder.finishEncodingCommand()),e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()),this._currentFramebuffer=e)},t.prototype.getHostDocument=function(){return null},t.prototype.clear=function(e,t,i,r){if(void 0===r&&(r=!1),this.useReverseDepthBuffer)throw new Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(t&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(i?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(r?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()},t.prototype.createIndexBuffer=function(e,t,i){var r=this._normalizeIndexData(e),n=new ff;return n.references=1,n.is32Bits=4===r.BYTES_PER_ELEMENT,r.byteLength&&(n.nativeIndexBuffer=this._engine.createIndexBuffer(r.buffer,r.byteOffset,r.byteLength,n.is32Bits,null!=t&&t)),n},t.prototype.createVertexBuffer=function(e,t,i){var r=ArrayBuffer.isView(e)?e:new Float32Array(e),n=new ff;return n.references=1,r.byteLength&&(n.nativeVertexBuffer=this._engine.createVertexBuffer(r.buffer,r.byteOffset,r.byteLength,null!=t&&t)),n},t.prototype._recordVertexArrayObject=function(e,t,i,r,n){i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);for(var o=r.getAttributesNames(),a=0;a<o.length;a++){var s=r.getAttributeLocation(a);if(s>=0){var l=o[a],c=null;if(n&&(c=n[l]),c||(c=t[l]),c){var u=c.getBuffer();u&&u.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,u.nativeVertexBuffer,s,c.byteOffset,c.byteStride,c.getSize(),cf(c.type),c.normalized,c.getInstanceDivisor())}}}},t.prototype.bindBuffers=function(e,t,i){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,t,i),this.bindVertexArrayObject(this._boundBuffersVertexArray)},t.prototype.recordVertexArrayObject=function(e,t,i,r){var n=this._engine.createVertexArray();return this._recordVertexArrayObject(n,e,t,i,r),n},t.prototype._deleteVertexArray=function(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()},t.prototype.bindVertexArrayObject=function(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()},t.prototype.releaseVertexArrayObject=function(e){this._deleteVertexArray(e)},t.prototype.getAttributes=function(e,t){var i=e;return this._engine.getAttributes(i.program,t)},t.prototype.drawElementsType=function(e,t,i,r){this._drawCalls.addCount(1,!1),r&&_native.Engine.COMMAND_DRAWINDEXEDINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXEDINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r)):(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i)),this._commandBufferEncoder.finishEncodingCommand()},t.prototype.drawArraysType=function(e,t,i,r){this._drawCalls.addCount(1,!1),r&&_native.Engine.COMMAND_DRAWINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r)):(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i)),this._commandBufferEncoder.finishEncodingCommand()},t.prototype.createPipelineContext=function(){var e=!(!this._caps.parallelShaderCompile||!this._engine.createProgramAsync);return new rf(this,e)},t.prototype.createMaterialContext=function(){},t.prototype.createDrawContext=function(){},t.prototype._preparePipelineContext=function(e,t,i,r,n,o,a,s){r?this.createRawShaderProgram():this.createShaderProgram(e,t,i,s)},t.prototype._executeWhenRenderingStateIsCompiled=function(e,t){var i=e;if(i.isAsync)if(i.onCompiled){var r=i.onCompiled;i.onCompiled=function(){r(),t()}}else i.onCompiled=t;else t()},t.prototype.createRawShaderProgram=function(){throw new Error("Not Supported")},t.prototype.createShaderProgram=function(e,t,i,r){var n=this,o=e;this.onBeforeShaderCompilationObservable.notifyObservers(this);var a=new tf(t);a.processCode(),t=a.code;var s=new tf(i);s.processCode(),i=s.code,t=Er._ConcatenateShader(t,r),i=Er._ConcatenateShader(i,r);var l=function(){var e;o.isCompiled=!0,null===(e=o.onCompiled)||void 0===e||e.call(o),n.onAfterShaderCompilationObservable.notifyObservers(n)};if(e.isAsync)o.program=this._engine.createProgramAsync(t,i,l,(function(e){o.compilationError=e}));else try{o.program=this._engine.createProgram(t,i),l()}catch(e){var c=null==e?void 0:e.message;throw new Error("SHADER ERROR"+("string"==typeof c?"\n"+c:""))}return o.program},t.prototype.inlineShaderCode=function(e){var t=new tf(e);return t.debug=!1,t.processCode(),t.code},t.prototype._setProgram=function(e){this._currentProgram!==e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand(),this._currentProgram=e)},t.prototype._deletePipelineContext=function(e){var t=e;t&&t.program&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(t.program),this._commandBufferEncoder.finishEncodingCommand())},t.prototype.getUniforms=function(e,t){var i=e;return this._engine.getUniforms(i.program,t)},t.prototype.bindUniformBlock=function(e,t,i){throw new Error("Not Implemented")},t.prototype.bindSamplers=function(e){var t=e.getPipelineContext();this._setProgram(t.program);for(var i=e.getSamplers(),r=0;r<i.length;r++){var n=e.getUniform(i[r]);n&&(this._boundUniforms[r]=n)}this._currentEffect=null},t.prototype.getRenderWidth=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._engine.getRenderWidth()},t.prototype.getRenderHeight=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._engine.getRenderHeight()},t.prototype.setViewport=function(e,t,i){this._cachedViewport=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETVIEWPORT),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.x),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.y),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.width),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.height),this._commandBufferEncoder.finishEncodingCommand()},t.prototype.enableScissor=function(e,t,i,r){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR),this._commandBufferEncoder.encodeCommandArgAsFloat32(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand()},t.prototype.disableScissor=function(){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR),this._commandBufferEncoder.encodeCommandArgAsFloat32(0),this._commandBufferEncoder.encodeCommandArgAsFloat32(0),this._commandBufferEncoder.encodeCommandArgAsFloat32(0),this._commandBufferEncoder.encodeCommandArgAsFloat32(0),this._commandBufferEncoder.finishEncodingCommand()},t.prototype.setState=function(e,t,i,r,n,o,a){var s,l;void 0===t&&(t=0),void 0===r&&(r=!1),void 0===a&&(a=0),this._zOffset=t,this._zOffsetUnits=a,0!==this._zOffset&&rr.Warn("zOffset is not supported in Native engine."),this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTATE),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(a),this._commandBufferEncoder.encodeCommandArgAsUInt32(null===(l=null!==(s=this.cullBackFaces)&&void 0!==s?s:n)||void 0===l||l?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(r?1:0),this._commandBufferEncoder.finishEncodingCommand()},t.prototype.getInputElementClientRect=function(){return{bottom:this.getRenderHeight(),height:this.getRenderHeight(),left:0,right:this.getRenderWidth(),top:0,width:this.getRenderWidth(),x:0,y:0,toJSON:function(){}}},t.prototype.setZOffset=function(e){e!==this._zOffset&&(this._zOffset=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())},t.prototype.getZOffset=function(){return this._zOffset},t.prototype.setZOffsetUnits=function(e){e!==this._zOffsetUnits&&(this._zOffsetUnits=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())},t.prototype.getZOffsetUnits=function(){return this._zOffsetUnits},t.prototype.setDepthBuffer=function(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?this._currentDepthTest:_native.Engine.DEPTH_TEST_ALWAYS),this._commandBufferEncoder.finishEncodingCommand()},t.prototype.getDepthWrite=function(){return this._depthWrite},t.prototype.getDepthFunction=function(){switch(this._currentDepthTest){case _native.Engine.DEPTH_TEST_NEVER:return u.NEVER;case _native.Engine.DEPTH_TEST_ALWAYS:return u.ALWAYS;case _native.Engine.DEPTH_TEST_GREATER:return u.GREATER;case _native.Engine.DEPTH_TEST_GEQUAL:return u.GEQUAL;case _native.Engine.DEPTH_TEST_NOTEQUAL:return u.NOTEQUAL;case _native.Engine.DEPTH_TEST_EQUAL:return u.EQUAL;case _native.Engine.DEPTH_TEST_LESS:return u.LESS;case _native.Engine.DEPTH_TEST_LEQUAL:return u.LEQUAL}return null},t.prototype.setDepthFunction=function(e){var t=0;switch(e){case u.NEVER:t=_native.Engine.DEPTH_TEST_NEVER;break;case u.ALWAYS:t=_native.Engine.DEPTH_TEST_ALWAYS;break;case u.GREATER:t=_native.Engine.DEPTH_TEST_GREATER;break;case u.GEQUAL:t=_native.Engine.DEPTH_TEST_GEQUAL;break;case u.NOTEQUAL:t=_native.Engine.DEPTH_TEST_NOTEQUAL;break;case u.EQUAL:t=_native.Engine.DEPTH_TEST_EQUAL;break;case u.LESS:t=_native.Engine.DEPTH_TEST_LESS;break;case u.LEQUAL:t=_native.Engine.DEPTH_TEST_LEQUAL}this._currentDepthTest=t,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest),this._commandBufferEncoder.finishEncodingCommand()},t.prototype.setDepthWrite=function(e){this._depthWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()},t.prototype.setColorWrite=function(e){this._colorWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()},t.prototype.getColorWrite=function(){return this._colorWrite},t.prototype.applyStencil=function(){this._setStencil(this._stencilMask,function(e){switch(e){case u.KEEP:return _native.Engine.STENCIL_OP_FAIL_S_KEEP;case u.ZERO:return _native.Engine.STENCIL_OP_FAIL_S_ZERO;case u.REPLACE:return _native.Engine.STENCIL_OP_FAIL_S_REPLACE;case u.INCR:return _native.Engine.STENCIL_OP_FAIL_S_INCR;case u.DECR:return _native.Engine.STENCIL_OP_FAIL_S_DECR;case u.INVERT:return _native.Engine.STENCIL_OP_FAIL_S_INVERT;case u.INCR_WRAP:return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT;case u.DECR_WRAP:return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT;default:throw new Error("Unsupported stencil OpFail mode: ".concat(e,"."))}}(this._stencilOpStencilFail),function(e){switch(e){case u.KEEP:return _native.Engine.STENCIL_OP_FAIL_Z_KEEP;case u.ZERO:return _native.Engine.STENCIL_OP_FAIL_Z_ZERO;case u.REPLACE:return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE;case u.INCR:return _native.Engine.STENCIL_OP_FAIL_Z_INCR;case u.DECR:return _native.Engine.STENCIL_OP_FAIL_Z_DECR;case u.INVERT:return _native.Engine.STENCIL_OP_FAIL_Z_INVERT;case u.INCR_WRAP:return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT;case u.DECR_WRAP:return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT;default:throw new Error("Unsupported stencil depthFail mode: ".concat(e,"."))}}(this._stencilOpDepthFail),function(e){switch(e){case u.KEEP:return _native.Engine.STENCIL_OP_PASS_Z_KEEP;case u.ZERO:return _native.Engine.STENCIL_OP_PASS_Z_ZERO;case u.REPLACE:return _native.Engine.STENCIL_OP_PASS_Z_REPLACE;case u.INCR:return _native.Engine.STENCIL_OP_PASS_Z_INCR;case u.DECR:return _native.Engine.STENCIL_OP_PASS_Z_DECR;case u.INVERT:return _native.Engine.STENCIL_OP_PASS_Z_INVERT;case u.INCR_WRAP:return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT;case u.DECR_WRAP:return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT;default:throw new Error("Unsupported stencil opPass mode: ".concat(e,"."))}}(this._stencilOpStencilDepthPass),function(e){switch(e){case u.LESS:return _native.Engine.STENCIL_TEST_LESS;case u.LEQUAL:return _native.Engine.STENCIL_TEST_LEQUAL;case u.EQUAL:return _native.Engine.STENCIL_TEST_EQUAL;case u.GEQUAL:return _native.Engine.STENCIL_TEST_GEQUAL;case u.GREATER:return _native.Engine.STENCIL_TEST_GREATER;case u.NOTEQUAL:return _native.Engine.STENCIL_TEST_NOTEQUAL;case u.NEVER:return _native.Engine.STENCIL_TEST_NEVER;case u.ALWAYS:return _native.Engine.STENCIL_TEST_ALWAYS;default:throw new Error("Unsupported stencil func mode: ".concat(e,"."))}}(this._stencilFunc),this._stencilFuncRef)},t.prototype._setStencil=function(e,t,i,r,n,o){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),this._commandBufferEncoder.encodeCommandArgAsUInt32(o),this._commandBufferEncoder.finishEncodingCommand()},t.prototype.setStencilBuffer=function(e){this._stencilTest=e,e?this.applyStencil():this._setStencil(255,_native.Engine.STENCIL_OP_FAIL_S_KEEP,_native.Engine.STENCIL_OP_FAIL_Z_KEEP,_native.Engine.STENCIL_OP_PASS_Z_KEEP,_native.Engine.STENCIL_TEST_ALWAYS,0)},t.prototype.getStencilBuffer=function(){return this._stencilTest},t.prototype.getStencilOperationPass=function(){return this._stencilOpStencilDepthPass},t.prototype.setStencilOperationPass=function(e){this._stencilOpStencilDepthPass=e,this.applyStencil()},t.prototype.setStencilMask=function(e){this._stencilMask=e,this.applyStencil()},t.prototype.setStencilFunction=function(e){this._stencilFunc=e,this.applyStencil()},t.prototype.setStencilFunctionReference=function(e){this._stencilFuncRef=e,this.applyStencil()},t.prototype.setStencilFunctionMask=function(e){this._stencilFuncMask=e},t.prototype.setStencilOperationFail=function(e){this._stencilOpStencilFail=e,this.applyStencil()},t.prototype.setStencilOperationDepthFail=function(e){this._stencilOpDepthFail=e,this.applyStencil()},t.prototype.getStencilMask=function(){return this._stencilMask},t.prototype.getStencilFunction=function(){return this._stencilFunc},t.prototype.getStencilFunctionReference=function(){return this._stencilFuncRef},t.prototype.getStencilFunctionMask=function(){return this._stencilFuncMask},t.prototype.getStencilOperationFail=function(){return this._stencilOpStencilFail},t.prototype.getStencilOperationDepthFail=function(){return this._stencilOpDepthFail},t.prototype.setAlphaConstants=function(e,t,i,r){throw new Error("Setting alpha blend constant color not yet implemented.")},t.prototype.setAlphaMode=function(e,t){if(void 0===t&&(t=!1),this._alphaMode!==e){var i=function(e){switch(e){case u.ALPHA_DISABLE:return _native.Engine.ALPHA_DISABLE;case u.ALPHA_ADD:return _native.Engine.ALPHA_ADD;case u.ALPHA_COMBINE:return _native.Engine.ALPHA_COMBINE;case u.ALPHA_SUBTRACT:return _native.Engine.ALPHA_SUBTRACT;case u.ALPHA_MULTIPLY:return _native.Engine.ALPHA_MULTIPLY;case u.ALPHA_MAXIMIZED:return _native.Engine.ALPHA_MAXIMIZED;case u.ALPHA_ONEONE:return _native.Engine.ALPHA_ONEONE;case u.ALPHA_PREMULTIPLIED:return _native.Engine.ALPHA_PREMULTIPLIED;case u.ALPHA_PREMULTIPLIED_PORTERDUFF:return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;case u.ALPHA_INTERPOLATE:return _native.Engine.ALPHA_INTERPOLATE;case u.ALPHA_SCREENMODE:return _native.Engine.ALPHA_SCREENMODE;default:throw new Error("Unsupported alpha mode: ".concat(e,"."))}}(e);this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t||this.setDepthWrite(e===u.ALPHA_DISABLE),this._alphaMode=e}},t.prototype.getAlphaMode=function(){return this._alphaMode},t.prototype.setInt=function(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)},t.prototype.setIntArray=function(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)},t.prototype.setIntArray2=function(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)},t.prototype.setIntArray3=function(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)},t.prototype.setIntArray4=function(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)},t.prototype.setFloatArray=function(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)},t.prototype.setFloatArray2=function(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)},t.prototype.setFloatArray3=function(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)},t.prototype.setFloatArray4=function(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)},t.prototype.setArray=function(e,t){return!!e&&this.setFloatArray(e,new Float32Array(t))},t.prototype.setArray2=function(e,t){return!!e&&this.setFloatArray2(e,new Float32Array(t))},t.prototype.setArray3=function(e,t){return!!e&&this.setFloatArray3(e,new Float32Array(t))},t.prototype.setArray4=function(e,t){return!!e&&this.setFloatArray4(e,new Float32Array(t))},t.prototype.setMatrices=function(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)},t.prototype.setMatrix3x3=function(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)},t.prototype.setMatrix2x2=function(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)},t.prototype.setFloat=function(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)},t.prototype.setFloat2=function(e,t,i){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.finishEncodingCommand(),!0)},t.prototype.setFloat3=function(e,t,i,r){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand(),!0)},t.prototype.setFloat4=function(e,t,i,r,n){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.encodeCommandArgAsFloat32(n),this._commandBufferEncoder.finishEncodingCommand(),!0)},t.prototype.setColor3=function(e,t){return!!e&&(this.setFloat3(e,t.r,t.g,t.b),!0)},t.prototype.setColor4=function(e,t,i){return!!e&&(this.setFloat4(e,t.r,t.g,t.b,i),!0)},t.prototype.wipeCaches=function(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)},t.prototype._createTexture=function(){return this._engine.createTexture()},t.prototype._deleteTexture=function(e){e&&this._engine.deleteTexture(e)},t.prototype.updateDynamicTexture=function(e,t,i,r,n){if(void 0===r&&(r=!1),void 0===r&&(r=!1),e&&e._hardwareTexture){var o=t.getCanvasTexture(),a=e._hardwareTexture.underlyingResource;this._engine.copyTexture(a,o),e.isReady=!0}},t.prototype.createDynamicTexture=function(e,t,i,r){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,u.TEXTUREFORMAT_RGBA,!1,!1,r)},t.prototype.createVideoElement=function(e){return this._camera?this._camera.createVideo(e):null},t.prototype.updateVideoTexture=function(e,t,i){if(e&&e._hardwareTexture&&this._camera){var r=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(r,t,i)}},t.prototype.createRawTexture=function(e,t,i,r,n,o,a,s,l,c,h){void 0===s&&(s=null),void 0===l&&(l=u.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=0),void 0===h&&(h=!1);var d=new Pi(this,Ti.Raw);if(d.format=r,d.generateMipMaps=n,d.samplingMode=a,d.invertY=o,d.baseWidth=t,d.baseHeight=i,d.width=d.baseWidth,d.height=d.baseHeight,d._compression=s,d.type=l,d._useSRGBBuffer=this._getUseSRGBBuffer(h,!n),this.updateRawTexture(d,e,r,o,s,l,d._useSRGBBuffer),d._hardwareTexture){var p=d._hardwareTexture.underlyingResource,f=sf(a);this._setTextureSampling(p,f)}return this._internalTexturesCache.push(d),d},t.prototype.createRawTexture2DArray=function(e,t,i,r,n,o,a,s,l,c){void 0===l&&(l=null),void 0===c&&(c=u.TEXTURETYPE_UNSIGNED_INT);var h=new Pi(this,Ti.Raw2DArray);if(h.baseWidth=t,h.baseHeight=i,h.baseDepth=r,h.width=t,h.height=i,h.depth=r,h.format=n,h.type=c,h.generateMipMaps=o,h.samplingMode=s,h.is2DArray=!0,h._hardwareTexture){var d=h._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(d,e,t,i,r,af(n,c),o,a);var p=sf(s);this._setTextureSampling(d,p)}return h.isReady=!0,this._internalTexturesCache.push(h),h},t.prototype.updateRawTexture=function(e,t,i,r,n,o,a){if(void 0===n&&(n=null),void 0===o&&(o=u.TEXTURETYPE_UNSIGNED_INT),void 0===a&&(a=!1),e){if(t&&e._hardwareTexture){var s=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(s,t,e.width,e.height,af(i,o),e.generateMipMaps,e.invertY)}e.isReady=!0}},t.prototype.createTexture=function(e,t,i,r,n,o,a,s,l,c,h,d,p,f,_){var m=this;void 0===n&&(n=u.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null),void 0===l&&(l=null),void 0===c&&(c=null),void 0===h&&(h=null),void 0===_&&(_=!1);var g="data:"===(e=e||"").substr(0,5),v=g&&-1!==e.indexOf(";base64,"),y=l||new Pi(this,Ti.Url),b=e;!this._transformTextureUrl||v||l||s||(e=this._transformTextureUrl(e));for(var T=e.lastIndexOf("."),E=h||(T>-1?e.substring(T).toLowerCase():""),S=null,x=0,A=Mi._TextureLoaders;x<A.length;x++){var C=A[x];if(C.canLoad(E)){S=C;break}}r&&r.addPendingData(y),y.url=e,y.generateMipMaps=!t,y.samplingMode=n,y.invertY=i,y._useSRGBBuffer=this._getUseSRGBBuffer(_,t),this.doNotHandleContextLost||(y._buffer=s);var R=null;if(o&&!l&&(R=y.onLoadedObservable.add(o)),l||this._internalTexturesCache.push(y),S)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");var P=function(e){if(y._hardwareTexture){var o=y._hardwareTexture.underlyingResource;m._engine.loadTexture(o,e,!t,i,y._useSRGBBuffer,(function(){y.baseWidth=m._engine.getTextureWidth(o),y.baseHeight=m._engine.getTextureHeight(o),y.width=y.baseWidth,y.height=y.baseHeight,y.isReady=!0;var e=sf(n);m._setTextureSampling(o,e),r&&r.removePendingData(y),y.onLoadedObservable.notifyObservers(y),y.onLoadedObservable.clear()}),(function(){throw new Error("Could not load a native texture.")}))}else r&&r.removePendingData(y)};if(g&&s)if(s instanceof ArrayBuffer)P(new Uint8Array(s));else if(ArrayBuffer.isView(s))P(s);else{if("string"!=typeof s)throw new Error("Unsupported buffer type");P(new Uint8Array(rr.DecodeBase64(s)))}else v?P(new Uint8Array(rr.DecodeBase64(e))):this._loadFile(e,(function(e){return P(new Uint8Array(e))}),void 0,void 0,!0,(function(i,l){var u;u="Unable to load "+(i&&i.responseURL,l),r&&r.removePendingData(y),e===b?(R&&y.onLoadedObservable.remove(R),M.UseFallbackTexture&&m.createTexture(M.FallbackTexture,t,y.invertY,r,n,null,a,s,y),a&&a((u||"Unknown error")+(M.UseFallbackTexture?" - Fallback texture was used":""),void 0)):(ae.Warn("Failed to load ".concat(e,", falling back to ").concat(b)),m.createTexture(b,t,y.invertY,r,n,o,a,s,y,c,h,d,p))}));return y},t.prototype.wrapNativeTexture=function(e,t,i){void 0===t&&(t=!1),void 0===i&&(i=u.TEXTURE_TRILINEAR_SAMPLINGMODE);var r=new of(e,this._engine),n=new Pi(this,Ti.Unknown,!0);return n._hardwareTexture=r,n.baseWidth=this._engine.getTextureWidth(e),n.baseHeight=this._engine.getTextureHeight(e),n.width=n.baseWidth,n.height=n.baseHeight,n.isReady=!0,n.useMipMaps=t,this.updateTextureSamplingMode(i,n),n},t.prototype.wrapWebGLTexture=function(){throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")},t.prototype._createDepthStencilTexture=function(e,t,i){var r,n,o=t.generateStencil||!1,a=t.samples||1,s=i,l=new Pi(this,Ti.DepthStencil),c=null!==(r=e.width)&&void 0!==r?r:e,u=null!==(n=e.height)&&void 0!==n?n:e,h=this._engine.createFrameBuffer(l._hardwareTexture.underlyingResource,c,u,o,!0,a);return s._framebufferDepthStencil=h,l},t.prototype._releaseFramebufferObjects=function(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())},t.prototype._createImageBitmapFromSource=function(e,t){var i=this;return new Promise((function(t,r){var n=i.createCanvasImage();n.onload=function(){try{var e=i._engine.createImageBitmap(n);t(e)}catch(e){r("Error loading image ".concat(n.src," with exception: ").concat(e))}},n.onerror=function(e){r("Error loading image ".concat(n.src," with exception: ").concat(e))},n.src=e}))},t.prototype.createImageBitmap=function(e,t){var i=this;return new Promise((function(t,r){if(Array.isArray(e)){var n=e;if(n.length){var o=i._engine.createImageBitmap(n[0]);if(o)return void t(o)}}r("Unsupported data for createImageBitmap.")}))},t.prototype.resizeImageBitmap=function(e,t,i){return this._engine.resizeImageBitmap(e,t,i)},t.prototype.createCubeTexture=function(e,t,i,r,n,o,a,s,l,c,h,d,p,f){var _=this;void 0===n&&(n=null),void 0===o&&(o=null),void 0===s&&(s=null),void 0===l&&(l=!1),void 0===c&&(c=0),void 0===h&&(h=0),void 0===d&&(d=null),void 0===f&&(f=!1);var m=d||new Pi(this,Ti.Cube);m.isCube=!0,m.url=e,m.generateMipMaps=!r,m._lodGenerationScale=c,m._lodGenerationOffset=h,m._useSRGBBuffer=this._getUseSRGBBuffer(f,!!r),this._doNotHandleContextLost||(m._extension=s,m._files=i);var g=e.lastIndexOf(".");if(".env"===(s||(g>-1?e.substring(g).toLowerCase():""))){if(i&&6===i.length)throw new Error("Multi-file loading not allowed on env files.");this._loadFile(e,(function(e){!function(e){var t=Vp(e);m.width=t.width,m.height=t.width,Yp(m,t);var i=t.specular;if(!i)throw new Error("Nothing else parsed so far");m._lodGenerationScale=i.lodGenerationScale;var r=Wp(e,t);m.format=u.TEXTUREFORMAT_RGBA,m.type=u.TEXTURETYPE_UNSIGNED_INT,m.generateMipMaps=!0,m.getEngine().updateTextureSamplingMode(Ja.TRILINEAR_SAMPLINGMODE,m),m._isRGBD=!0,m.invertY=!0,_._engine.loadCubeTextureWithMips(m._hardwareTexture.underlyingResource,r,!1,m._useSRGBBuffer,(function(){m.isReady=!0,n&&n()}),(function(){throw new Error("Could not load a native cube texture.")}))}(new Uint8Array(e,0,e.byteLength))}),void 0,void 0,!0,(function(e,t){o&&e&&o(e.status+" "+e.statusText,t)}))}else{if(!i||6!==i.length)throw new Error("Cannot load cubemap because 6 files were not defined");var v=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(v.map((function(e){return _._loadFileAsync(e,void 0,!0).then((function(e){return new Uint8Array(e,0,e.byteLength)}))}))).then((function(e){return new Promise((function(t,i){_._engine.loadCubeTexture(m._hardwareTexture.underlyingResource,e,!r,!0,m._useSRGBBuffer,t,i)}))})).then((function(){m.isReady=!0,n&&n()}),(function(e){o&&o("Failed to load cubemap: ".concat(e.message),e)}))}return this._internalTexturesCache.push(m),m},t.prototype._createHardwareTexture=function(){return new of(this._createTexture(),this._engine)},t.prototype._createHardwareRenderTargetWrapper=function(e,t,i){var r=new nf(e,t,i,this);return this._renderTargetWrapperCache.push(r),r},t.prototype._createInternalTexture=function(e,t,i,r){var n,o,a;void 0===i&&(i=!0),void 0===r&&(r=Ti.Unknown);var s,l=!1,c=u.TEXTURETYPE_UNSIGNED_INT,h=u.TEXTURE_TRILINEAR_SAMPLINGMODE,d=u.TEXTUREFORMAT_RGBA,p=!1,f=1;void 0!==t&&"object"==typeof t?(l=!!t.generateMipMaps,c=void 0===t.type?u.TEXTURETYPE_UNSIGNED_INT:t.type,h=void 0===t.samplingMode?u.TEXTURE_TRILINEAR_SAMPLINGMODE:t.samplingMode,d=void 0===t.format?u.TEXTUREFORMAT_RGBA:t.format,p=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,f=null!==(n=t.samples)&&void 0!==n?n:1,s=t.label):l=!!t,p=this._getUseSRGBBuffer(p,!l),(c!==u.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(c!==u.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(h=u.TEXTURE_NEAREST_SAMPLINGMODE),c!==u.TEXTURETYPE_FLOAT||this._caps.textureFloat||(c=u.TEXTURETYPE_UNSIGNED_INT,ae.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));var _=new Pi(this,r),m=null!==(o=e.width)&&void 0!==o?o:e,g=null!==(a=e.height)&&void 0!==a?a:e,v=e.layers||0;if(0!==v)throw new Error("Texture layers are not supported in Babylon Native");var y=_._hardwareTexture.underlyingResource,b=af(d,c);return this._engine.initializeTexture(y,m,g,l,b,!0,p,f),this._setTextureSampling(y,sf(h)),_._useSRGBBuffer=p,_.baseWidth=m,_.baseHeight=g,_.width=m,_.height=g,_.depth=v,_.isReady=!0,_.samples=f,_.generateMipMaps=l,_.samplingMode=h,_.type=c,_.format=d,_.label=s,this._internalTexturesCache.push(_),_},t.prototype.createRenderTargetTexture=function(e,t){var i,r,n,o,a=this._createHardwareRenderTargetWrapper(!1,!1,e),s=!0,l=!1,c=!1,u=void 0,h=1;void 0!==t&&"object"==typeof t&&(s=null===(i=t.generateDepthBuffer)||void 0===i||i,l=!!t.generateStencilBuffer,c=!!t.noColorAttachment,u=t.colorAttachment,h=null!==(r=t.samples)&&void 0!==r?r:1);var d=u||(c?null:this._createInternalTexture(e,t,!0,Ti.RenderTarget)),p=null!==(n=e.width)&&void 0!==n?n:e,f=null!==(o=e.height)&&void 0!==o?o:e,_=this._engine.createFrameBuffer(d?d._hardwareTexture.underlyingResource:null,p,f,l,s,h);return a._framebuffer=_,a._generateDepthBuffer=s,a._generateStencilBuffer=l,a._samples=h,a.setTextures(d),a},t.prototype.updateRenderTargetTextureSampleCount=function(e,t){return ae.Warn("Updating render target sample count is not currently supported"),e.samples},t.prototype.updateTextureSamplingMode=function(e,t){if(t._hardwareTexture){var i=sf(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e},t.prototype.bindFramebuffer=function(e,t,i,r,n){var o=e;if(this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,t)throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(i||r)throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");o._framebufferDepthStencil?this._bindUnboundFramebuffer(o._framebufferDepthStencil):this._bindUnboundFramebuffer(o._framebuffer)},t.prototype.unBindFramebuffer=function(e,t,i){void 0===t&&(t=!1),this._currentRenderTarget=null,i&&i(),this._bindUnboundFramebuffer(null)},t.prototype.createDynamicVertexBuffer=function(e){return this.createVertexBuffer(e,!0)},t.prototype.updateDynamicIndexBuffer=function(e,t,i){void 0===i&&(i=0);var r=e,n=this._normalizeIndexData(t);r.is32Bits=4===n.BYTES_PER_ELEMENT,this._engine.updateDynamicIndexBuffer(r.nativeIndexBuffer,n.buffer,n.byteOffset,n.byteLength,i)},t.prototype.updateDynamicVertexBuffer=function(e,t,i,r){void 0===i&&(i=0);var n=e,o=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,a=new Uint8Array(o.buffer,o.byteOffset,null!=r?r:o.byteLength);this._engine.updateDynamicVertexBuffer(n.nativeVertexBuffer,a.buffer,a.byteOffset,a.byteLength,i)},t.prototype._setTexture=function(e,t,i,r){void 0===i&&(i=!1),void 0===r&&(r=!1);var n,o=this._boundUniforms[e];if(!o)return!1;if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._boundTexturesCache[e]=null),!1;if(t.video)this._activeChannel=e,t.update();else if(t.delayLoadState===u.DELAYLOADSTATE_NOTLOADED)return t.delayLoad(),!1;return n=r?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,this._activeChannel=e,!(!n||!n._hardwareTexture||(this._setTextureWrapMode(n._hardwareTexture.underlyingResource,lf(t.wrapU),lf(t.wrapV),lf(t.wrapR)),this._updateAnisotropicLevel(t),this._setTextureCore(o,n._hardwareTexture.underlyingResource),0))},t.prototype._setTextureSampling=function(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.finishEncodingCommand()},t.prototype._setTextureWrapMode=function(e,t,i,r){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.finishEncodingCommand()},t.prototype._setTextureCore=function(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),this._commandBufferEncoder.finishEncodingCommand()},t.prototype._updateAnisotropicLevel=function(e){var t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;t&&t._hardwareTexture&&t._cachedAnisotropicFilteringLevel!==i&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),this._commandBufferEncoder.encodeCommandArgAsNativeData(t._hardwareTexture.underlyingResource),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t._cachedAnisotropicFilteringLevel=i)},t.prototype._bindTexture=function(e,t){var i=this._boundUniforms[e];if(i&&t&&t._hardwareTexture){var r=t._hardwareTexture.underlyingResource;this._setTextureCore(i,r)}},t.prototype._deleteBuffer=function(e){e.nativeIndexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeIndexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeIndexBuffer),e.nativeVertexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeVertexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeVertexBuffer)},t.prototype.createCanvas=function(e,t){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");var i=new _native.Canvas;return i.width=e,i.height=t,i},t.prototype.createCanvasImage=function(){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");return new _native.Image},t.prototype.updateTextureData=function(e,t,i,r,n,o,a,s,l){throw void 0===a&&(a=0),void 0===s&&(s=0),void 0===l&&(l=!1),new Error("updateTextureData not implemented.")},t.prototype._uploadCompressedDataToTextureDirectly=function(e,t,i,r,n,o,a){throw void 0===o&&(o=0),void 0===a&&(a=0),new Error("_uploadCompressedDataToTextureDirectly not implemented.")},t.prototype._uploadDataToTextureDirectly=function(e,t,i,r){throw void 0===i&&(i=0),void 0===r&&(r=0),new Error("_uploadDataToTextureDirectly not implemented.")},t.prototype._uploadArrayBufferViewToTexture=function(e,t,i,r){throw void 0===i&&(i=0),void 0===r&&(r=0),new Error("_uploadArrayBufferViewToTexture not implemented.")},t.prototype._uploadImageToTexture=function(e,t,i,r){throw void 0===i&&(i=0),void 0===r&&(r=0),new Error("_uploadArrayBufferViewToTexture not implemented.")},t.prototype.getFontOffset=function(e){return{ascent:0,height:0,descent:0}},t.prototype.flushFramebuffer=function(){},t.prototype._readTexturePixels=function(e,t,i,r,n,o,a,s,l,c){var u,h,d,p;if(void 0!==r&&-1!==r)throw new Error("Reading cubemap faces is not supported, but faceIndex is ".concat(r,"."));return this._engine.readTexture(null===(u=e._hardwareTexture)||void 0===u?void 0:u.underlyingResource,null!=n?n:0,null!=l?l:0,null!=c?c:0,t,i,null!==(h=null==o?void 0:o.buffer)&&void 0!==h?h:null,null!==(d=null==o?void 0:o.byteOffset)&&void 0!==d?d:0,null!==(p=null==o?void 0:o.byteLength)&&void 0!==p?p:0).then((function(e){return o||(o=new Uint8Array(e)),o}))},t.PROTOCOL_VERSION=8,t}(Do);mf._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new r_:new gp};var gf,vf,yf,bf,Tf,Ef,Sf,xf,Af,Cf,Rf,Pf,If,Mf,Of,Df,Nf,Ff,Lf,wf,Bf,Uf,Vf,kf,Gf,zf,Wf,Hf,Xf,jf,Yf,Kf,Qf,qf,Zf,Jf,$f,e_,t_,i_,r_=function(e){function t(){return e.call(this)||this}return m(t,e),t.prototype.writeUint32=function(t){e.prototype.writeUint32.call(this,_native.NativeDataStream.VALIDATION_UINT_32),e.prototype.writeUint32.call(this,t)},t.prototype.writeInt32=function(t){e.prototype.writeUint32.call(this,_native.NativeDataStream.VALIDATION_INT_32),e.prototype.writeInt32.call(this,t)},t.prototype.writeFloat32=function(t){e.prototype.writeUint32.call(this,_native.NativeDataStream.VALIDATION_FLOAT_32),e.prototype.writeFloat32.call(this,t)},t.prototype.writeUint32Array=function(t){e.prototype.writeUint32.call(this,_native.NativeDataStream.VALIDATION_UINT_32_ARRAY),e.prototype.writeUint32Array.call(this,t)},t.prototype.writeInt32Array=function(t){e.prototype.writeUint32.call(this,_native.NativeDataStream.VALIDATION_INT_32_ARRAY),e.prototype.writeInt32Array.call(this,t)},t.prototype.writeFloat32Array=function(t){e.prototype.writeUint32.call(this,_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY),e.prototype.writeFloat32Array.call(this,t)},t.prototype.writeNativeData=function(t){e.prototype.writeUint32.call(this,_native.NativeDataStream.VALIDATION_NATIVE_DATA),e.prototype.writeNativeData.call(this,t)},t.prototype.writeBoolean=function(t){e.prototype.writeUint32.call(this,_native.NativeDataStream.VALIDATION_BOOLEAN),e.prototype.writeBoolean.call(this,t)},t}(gp);!function(e){e.LowPower="low-power",e.HighPerformance="high-performance"}(gf||(gf={})),function(e){e.DepthClipControl="depth-clip-control",e.Depth32FloatStencil8="depth32float-stencil8",e.TextureCompressionBC="texture-compression-bc",e.TextureCompressionETC2="texture-compression-etc2",e.TextureCompressionASTC="texture-compression-astc",e.TimestampQuery="timestamp-query",e.IndirectFirstInstance="indirect-first-instance",e.ShaderF16="shader-f16",e.RG11B10UFloatRenderable="rg11b10ufloat-renderable",e.BGRA8UnormStorage="bgra8unorm-storage",e.Float32Filterable="float32-filterable"}(vf||(vf={})),function(e){e.Unmapped="unmapped",e.Pending="pending",e.Mapped="mapped"}(yf||(yf={})),function(e){e[e.MapRead=1]="MapRead",e[e.MapWrite=2]="MapWrite",e[e.CopySrc=4]="CopySrc",e[e.CopyDst=8]="CopyDst",e[e.Index=16]="Index",e[e.Vertex=32]="Vertex",e[e.Uniform=64]="Uniform",e[e.Storage=128]="Storage",e[e.Indirect=256]="Indirect",e[e.QueryResolve=512]="QueryResolve"}(bf||(bf={})),function(e){e[e.Read=1]="Read",e[e.Write=2]="Write"}(Tf||(Tf={})),function(e){e.E1d="1d",e.E2d="2d",e.E3d="3d"}(Ef||(Ef={})),function(e){e[e.CopySrc=1]="CopySrc",e[e.CopyDst=2]="CopyDst",e[e.TextureBinding=4]="TextureBinding",e[e.StorageBinding=8]="StorageBinding",e[e.RenderAttachment=16]="RenderAttachment"}(Sf||(Sf={})),function(e){e.E1d="1d",e.E2d="2d",e.E2dArray="2d-array",e.Cube="cube",e.CubeArray="cube-array",e.E3d="3d"}(xf||(xf={})),function(e){e.All="all",e.StencilOnly="stencil-only",e.DepthOnly="depth-only"}(Af||(Af={})),function(e){e.R8Unorm="r8unorm",e.R8Snorm="r8snorm",e.R8Uint="r8uint",e.R8Sint="r8sint",e.R16Uint="r16uint",e.R16Sint="r16sint",e.R16Float="r16float",e.RG8Unorm="rg8unorm",e.RG8Snorm="rg8snorm",e.RG8Uint="rg8uint",e.RG8Sint="rg8sint",e.R32Uint="r32uint",e.R32Sint="r32sint",e.R32Float="r32float",e.RG16Uint="rg16uint",e.RG16Sint="rg16sint",e.RG16Float="rg16float",e.RGBA8Unorm="rgba8unorm",e.RGBA8UnormSRGB="rgba8unorm-srgb",e.RGBA8Snorm="rgba8snorm",e.RGBA8Uint="rgba8uint",e.RGBA8Sint="rgba8sint",e.BGRA8Unorm="bgra8unorm",e.BGRA8UnormSRGB="bgra8unorm-srgb",e.RGB9E5UFloat="rgb9e5ufloat",e.RGB10A2UINT="rgb10a2uint",e.RGB10A2Unorm="rgb10a2unorm",e.RG11B10UFloat="rg11b10ufloat",e.RG32Uint="rg32uint",e.RG32Sint="rg32sint",e.RG32Float="rg32float",e.RGBA16Uint="rgba16uint",e.RGBA16Sint="rgba16sint",e.RGBA16Float="rgba16float",e.RGBA32Uint="rgba32uint",e.RGBA32Sint="rgba32sint",e.RGBA32Float="rgba32float",e.Stencil8="stencil8",e.Depth16Unorm="depth16unorm",e.Depth24Plus="depth24plus",e.Depth24PlusStencil8="depth24plus-stencil8",e.Depth32Float="depth32float",e.BC1RGBAUnorm="bc1-rgba-unorm",e.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",e.BC2RGBAUnorm="bc2-rgba-unorm",e.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",e.BC3RGBAUnorm="bc3-rgba-unorm",e.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",e.BC4RUnorm="bc4-r-unorm",e.BC4RSnorm="bc4-r-snorm",e.BC5RGUnorm="bc5-rg-unorm",e.BC5RGSnorm="bc5-rg-snorm",e.BC6HRGBUFloat="bc6h-rgb-ufloat",e.BC6HRGBFloat="bc6h-rgb-float",e.BC7RGBAUnorm="bc7-rgba-unorm",e.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",e.ETC2RGB8Unorm="etc2-rgb8unorm",e.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",e.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",e.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",e.ETC2RGBA8Unorm="etc2-rgba8unorm",e.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",e.EACR11Unorm="eac-r11unorm",e.EACR11Snorm="eac-r11snorm",e.EACRG11Unorm="eac-rg11unorm",e.EACRG11Snorm="eac-rg11snorm",e.ASTC4x4Unorm="astc-4x4-unorm",e.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",e.ASTC5x4Unorm="astc-5x4-unorm",e.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",e.ASTC5x5Unorm="astc-5x5-unorm",e.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",e.ASTC6x5Unorm="astc-6x5-unorm",e.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",e.ASTC6x6Unorm="astc-6x6-unorm",e.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",e.ASTC8x5Unorm="astc-8x5-unorm",e.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",e.ASTC8x6Unorm="astc-8x6-unorm",e.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",e.ASTC8x8Unorm="astc-8x8-unorm",e.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",e.ASTC10x5Unorm="astc-10x5-unorm",e.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",e.ASTC10x6Unorm="astc-10x6-unorm",e.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",e.ASTC10x8Unorm="astc-10x8-unorm",e.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",e.ASTC10x10Unorm="astc-10x10-unorm",e.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",e.ASTC12x10Unorm="astc-12x10-unorm",e.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",e.ASTC12x12Unorm="astc-12x12-unorm",e.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",e.Depth32FloatStencil8="depth32float-stencil8"}(Cf||(Cf={})),function(e){e.ClampToEdge="clamp-to-edge",e.Repeat="repeat",e.MirrorRepeat="mirror-repeat"}(Rf||(Rf={})),function(e){e.Nearest="nearest",e.Linear="linear"}(Pf||(Pf={})),function(e){e.Nearest="nearest",e.Linear="linear"}(If||(If={})),function(e){e.Never="never",e.Less="less",e.Equal="equal",e.LessEqual="less-equal",e.Greater="greater",e.NotEqual="not-equal",e.GreaterEqual="greater-equal",e.Always="always"}(Mf||(Mf={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Compute=4]="Compute"}(Of||(Of={})),function(e){e.Uniform="uniform",e.Storage="storage",e.ReadOnlyStorage="read-only-storage"}(Df||(Df={})),function(e){e.Filtering="filtering",e.NonFiltering="non-filtering",e.Comparison="comparison"}(Nf||(Nf={})),function(e){e.Float="float",e.UnfilterableFloat="unfilterable-float",e.Depth="depth",e.Sint="sint",e.Uint="uint"}(Ff||(Ff={})),function(e){e.WriteOnly="write-only",e.ReadOnly="read-only",e.ReadWrite="read-write"}(Lf||(Lf={})),function(e){e.Error="error",e.Warning="warning",e.Info="info"}(wf||(wf={})),function(e){e.Validation="validation",e.Internal="internal"}(Bf||(Bf={})),function(e){e.Auto="auto"}(Uf||(Uf={})),function(e){e.PointList="point-list",e.LineList="line-list",e.LineStrip="line-strip",e.TriangleList="triangle-list",e.TriangleStrip="triangle-strip"}(Vf||(Vf={})),function(e){e.CCW="ccw",e.CW="cw"}(kf||(kf={})),function(e){e.None="none",e.Front="front",e.Back="back"}(Gf||(Gf={})),function(e){e[e.Red=1]="Red",e[e.Green=2]="Green",e[e.Blue=4]="Blue",e[e.Alpha=8]="Alpha",e[e.All=15]="All"}(zf||(zf={})),function(e){e.Zero="zero",e.One="one",e.Src="src",e.OneMinusSrc="one-minus-src",e.SrcAlpha="src-alpha",e.OneMinusSrcAlpha="one-minus-src-alpha",e.Dst="dst",e.OneMinusDst="one-minus-dst",e.DstAlpha="dst-alpha",e.OneMinusDstAlpha="one-minus-dst-alpha",e.SrcAlphaSaturated="src-alpha-saturated",e.Constant="constant",e.OneMinusConstant="one-minus-constant"}(Wf||(Wf={})),function(e){e.Add="add",e.Subtract="subtract",e.ReverseSubtract="reverse-subtract",e.Min="min",e.Max="max"}(Hf||(Hf={})),function(e){e.Keep="keep",e.Zero="zero",e.Replace="replace",e.Invert="invert",e.IncrementClamp="increment-clamp",e.DecrementClamp="decrement-clamp",e.IncrementWrap="increment-wrap",e.DecrementWrap="decrement-wrap"}(Xf||(Xf={})),function(e){e.Uint16="uint16",e.Uint32="uint32"}(jf||(jf={})),function(e){e.Uint8x2="uint8x2",e.Uint8x4="uint8x4",e.Sint8x2="sint8x2",e.Sint8x4="sint8x4",e.Unorm8x2="unorm8x2",e.Unorm8x4="unorm8x4",e.Snorm8x2="snorm8x2",e.Snorm8x4="snorm8x4",e.Uint16x2="uint16x2",e.Uint16x4="uint16x4",e.Sint16x2="sint16x2",e.Sint16x4="sint16x4",e.Unorm16x2="unorm16x2",e.Unorm16x4="unorm16x4",e.Snorm16x2="snorm16x2",e.Snorm16x4="snorm16x4",e.Float16x2="float16x2",e.Float16x4="float16x4",e.Float32="float32",e.Float32x2="float32x2",e.Float32x3="float32x3",e.Float32x4="float32x4",e.Uint32="uint32",e.Uint32x2="uint32x2",e.Uint32x3="uint32x3",e.Uint32x4="uint32x4",e.Sint32="sint32",e.Sint32x2="sint32x2",e.Sint32x3="sint32x3",e.Sint32x4="sint32x4",e.UNORM10x10x10x2="unorm10-10-10-2"}(Yf||(Yf={})),function(e){e.Vertex="vertex",e.Instance="instance"}(Kf||(Kf={})),function(e){e.Beginning="beginning",e.End="end"}(Qf||(Qf={})),function(e){e.Beginning="beginning",e.End="end"}(qf||(qf={})),function(e){e.Load="load",e.Clear="clear"}(Zf||(Zf={})),function(e){e.Store="store",e.Discard="discard"}(Jf||(Jf={})),function(e){e.Occlusion="occlusion",e.Timestamp="timestamp"}($f||($f={})),function(e){e.Opaque="opaque",e.Premultiplied="premultiplied"}(e_||(e_={})),function(e){e.Unknown="unknown",e.Destroyed="destroyed"}(t_||(t_={})),function(e){e.Validation="validation",e.OutOfMemory="out-of-memory",e.Internal="internal"}(i_||(i_={}));var n_=function(){function e(){this.shaderLanguage=pt.GLSL,this.vertexBufferKindToNumberOfComponents={}}return e.prototype._addUniformToLeftOverUBO=function(e,t,i){var r,n;e=(r=this._getArraySize(e,t,i))[0],t=r[1],n=r[2];for(var o=0;o<this._webgpuProcessingContext.leftOverUniforms.length;o++)if(this._webgpuProcessingContext.leftOverUniforms[o].name===e)return;this._webgpuProcessingContext.leftOverUniforms.push({name:e,type:t,length:n})},e.prototype._buildLeftOverUBO=function(){if(!this._webgpuProcessingContext.leftOverUniforms.length)return"";var t=e.LeftOvertUBOName,i=this._webgpuProcessingContext.availableBuffers[t];return i||(i={binding:this._webgpuProcessingContext.getNextFreeUBOBinding()},this._webgpuProcessingContext.availableBuffers[t]=i,this._addBufferBindingDescription(t,i,Df.Uniform,!0),this._addBufferBindingDescription(t,i,Df.Uniform,!1)),this._generateLeftOverUBOCode(t,i)},e.prototype._collectBindingNames=function(){for(var e=0;e<this._webgpuProcessingContext.bindGroupLayoutEntries.length;e++){var t=this._webgpuProcessingContext.bindGroupLayoutEntries[e];if(void 0!==t)for(var i=0;i<t.length;i++){var r=this._webgpuProcessingContext.bindGroupLayoutEntries[e][i],n=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[e][r.binding].name,o=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[e][r.binding].nameInArrayOfTexture;r&&(r.texture||r.externalTexture||r.storageTexture?this._webgpuProcessingContext.textureNames.push(o):r.sampler?this._webgpuProcessingContext.samplerNames.push(n):r.buffer&&this._webgpuProcessingContext.bufferNames.push(n))}else this._webgpuProcessingContext.bindGroupLayoutEntries[e]=[]}},e.prototype._preCreateBindGroupEntries=function(){for(var e=this._webgpuProcessingContext.bindGroupEntries,t=0;t<this._webgpuProcessingContext.bindGroupLayoutEntries.length;t++){for(var i=this._webgpuProcessingContext.bindGroupLayoutEntries[t],r=[],n=0;n<i.length;n++){var o=this._webgpuProcessingContext.bindGroupLayoutEntries[t][n];o.sampler||o.texture||o.storageTexture||o.externalTexture?r.push({binding:o.binding,resource:void 0}):o.buffer&&r.push({binding:o.binding,resource:{buffer:void 0,offset:0,size:0}})}e[t]=r}},e.prototype._addTextureBindingDescription=function(e,t,i,r,n,o){var a,s=(a=t.textures[i]).groupIndex,l=a.bindingIndex;if(this._webgpuProcessingContext.bindGroupLayoutEntries[s]||(this._webgpuProcessingContext.bindGroupLayoutEntries[s]=[],this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s]=[]),!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s][l]){var c;c=null===r?this._webgpuProcessingContext.bindGroupLayoutEntries[s].push({binding:l,visibility:0,externalTexture:{}}):n?this._webgpuProcessingContext.bindGroupLayoutEntries[s].push({binding:l,visibility:0,storageTexture:{access:Lf.WriteOnly,format:n,viewDimension:r}}):this._webgpuProcessingContext.bindGroupLayoutEntries[s].push({binding:l,visibility:0,texture:{sampleType:t.sampleType,viewDimension:r,multisampled:!1}});var u=t.isTextureArray?e+i:e;this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s][l]={name:e,index:c-1,nameInArrayOfTexture:u}}l=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s][l].index,this._webgpuProcessingContext.bindGroupLayoutEntries[s][l].visibility|=o?Of.Vertex:Of.Fragment},e.prototype._addSamplerBindingDescription=function(e,t,i){var r,n=(r=t.binding).groupIndex,o=r.bindingIndex;if(this._webgpuProcessingContext.bindGroupLayoutEntries[n]||(this._webgpuProcessingContext.bindGroupLayoutEntries[n]=[],this._webgpuProcessingContext.bindGroupLayoutEntryInfo[n]=[]),!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[n][o]){var a=this._webgpuProcessingContext.bindGroupLayoutEntries[n].push({binding:o,visibility:0,sampler:{type:t.type}});this._webgpuProcessingContext.bindGroupLayoutEntryInfo[n][o]={name:e,index:a-1}}o=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[n][o].index,this._webgpuProcessingContext.bindGroupLayoutEntries[n][o].visibility|=i?Of.Vertex:Of.Fragment},e.prototype._addBufferBindingDescription=function(e,t,i,r){var n,o=(n=t.binding).groupIndex,a=n.bindingIndex;if(this._webgpuProcessingContext.bindGroupLayoutEntries[o]||(this._webgpuProcessingContext.bindGroupLayoutEntries[o]=[],this._webgpuProcessingContext.bindGroupLayoutEntryInfo[o]=[]),!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[o][a]){var s=this._webgpuProcessingContext.bindGroupLayoutEntries[o].push({binding:a,visibility:0,buffer:{type:i}});this._webgpuProcessingContext.bindGroupLayoutEntryInfo[o][a]={name:e,index:s-1}}a=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[o][a].index,this._webgpuProcessingContext.bindGroupLayoutEntries[o][a].visibility|=r?Of.Vertex:Of.Fragment},e.prototype._injectStartingAndEndingCode=function(e,t,i,r){var n=e.indexOf(t);if(n<0)return ae.Error('No "main" function found in shader code! Processing aborted.'),e;if(i){for(;n++<e.length&&"{"!=e.charAt(n););if(n<e.length){var o=e.substring(0,n+1),a=e.substring(n+1);e=o+i+a}}if(r){var s=e.lastIndexOf("}");e=e.substring(0,s),e+=r+"\n}"}return e},e.AutoSamplerSuffix="Sampler",e.LeftOvertUBOName="LeftOver",e.InternalsUBOName="Internals",e.UniformSizes={bool:1,int:1,float:1,vec2:2,ivec2:2,uvec2:2,vec3:3,ivec3:3,uvec3:3,vec4:4,ivec4:4,uvec4:4,mat2:4,mat3:12,mat4:16,i32:1,u32:1,f32:1,mat2x2:4,mat3x3:12,mat4x4:16,mat2x2f:4,mat3x3f:12,mat4x4f:16,vec2i:2,vec3i:3,vec4i:4,vec2u:2,vec3u:3,vec4u:4,vec2f:2,vec3f:3,vec4f:4,vec2h:1,vec3h:2,vec4h:2},e._SamplerFunctionByWebGLSamplerType={sampler2D:"sampler2D",sampler2DArray:"sampler2DArray",sampler2DShadow:"sampler2DShadow",sampler2DArrayShadow:"sampler2DArrayShadow",samplerCube:"samplerCube",sampler3D:"sampler3D"},e._TextureTypeByWebGLSamplerType={sampler2D:"texture2D",sampler2DArray:"texture2DArray",sampler2DShadow:"texture2D",sampler2DArrayShadow:"texture2DArray",samplerCube:"textureCube",samplerCubeArray:"textureCubeArray",sampler3D:"texture3D"},e._GpuTextureViewDimensionByWebGPUTextureType={textureCube:xf.Cube,textureCubeArray:xf.CubeArray,texture2D:xf.E2d,texture2DArray:xf.E2dArray,texture3D:xf.E3d},e._SamplerTypeByWebGLSamplerType={sampler2DShadow:"samplerShadow",sampler2DArrayShadow:"samplerShadow"},e._IsComparisonSamplerByWebGPUSamplerType={samplerShadow:!0,samplerArrayShadow:!0,sampler:!1},e}(),o_=function(){function e(e,t){this.bindGroupLayouts={},this._name="unnamed",this.shaderProcessingContext=e,this._leftOverUniformsByName={},this.engine=t,this.vertexBufferKindToType={}}return Object.defineProperty(e.prototype,"isAsync",{get:function(){return!1},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isReady",{get:function(){return!!this.stages},enumerable:!1,configurable:!0}),e.prototype._handlesSpectorRebuildCallback=function(){},e.prototype._fillEffectInformation=function(e,t,i,r,n,o,a,s){var l=this.engine;l._doNotHandleContextLost&&(e._fragmentSourceCode="",e._vertexSourceCode="");var c,u=this.shaderProcessingContext.availableTextures;for(c=0;c<n.length;c++){var h=n[c],d=u[n[c]];null==d||null==d?(n.splice(c,1),c--):o[h]=c}for(var p=0,f=l.getAttributes(this,a);p<f.length;p++){var _=f[p];s.push(_)}this.buildUniformLayout();var m=[],g=[];for(c=0;c<a.length;c++){var v=s[c];v>=0&&(m.push(a[c]),g.push(v))}this.shaderProcessingContext.attributeNamesFromEffect=m,this.shaderProcessingContext.attributeLocationsFromEffect=g},e.prototype.buildUniformLayout=function(){if(this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer=new Or(this.engine,void 0,void 0,"leftOver-"+this._name);for(var e=0,t=this.shaderProcessingContext.leftOverUniforms;e<t.length;e++){var i=t[e],r=i.type.replace(/^(.*?)(<.*>)?$/,"$1"),n=n_.UniformSizes[r];this.uniformBuffer.addUniform(i.name,n,i.length),this._leftOverUniformsByName[i.name]=i.type}this.uniformBuffer.create()}},e.prototype.setEngine=function(e){this.engine=e},e.prototype.dispose=function(){this.uniformBuffer&&this.uniformBuffer.dispose()},e.prototype.setInt=function(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt(e,t)},e.prototype.setInt2=function(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt2(e,t,i)},e.prototype.setInt3=function(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt3(e,t,i,r)},e.prototype.setInt4=function(e,t,i,r,n){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt4(e,t,i,r,n)},e.prototype.setIntArray=function(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateIntArray(e,t)},e.prototype.setIntArray2=function(e,t){this.setIntArray(e,t)},e.prototype.setIntArray3=function(e,t){this.setIntArray(e,t)},e.prototype.setIntArray4=function(e,t){this.setIntArray(e,t)},e.prototype.setUInt=function(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt(e,t)},e.prototype.setUInt2=function(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt2(e,t,i)},e.prototype.setUInt3=function(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt3(e,t,i,r)},e.prototype.setUInt4=function(e,t,i,r,n){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt4(e,t,i,r,n)},e.prototype.setUIntArray=function(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUIntArray(e,t)},e.prototype.setUIntArray2=function(e,t){this.setUIntArray(e,t)},e.prototype.setUIntArray3=function(e,t){this.setUIntArray(e,t)},e.prototype.setUIntArray4=function(e,t){this.setUIntArray(e,t)},e.prototype.setArray=function(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateArray(e,t)},e.prototype.setArray2=function(e,t){this.setArray(e,t)},e.prototype.setArray3=function(e,t){this.setArray(e,t)},e.prototype.setArray4=function(e,t){this.setArray(e,t)},e.prototype.setMatrices=function(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrices(e,t)},e.prototype.setMatrix=function(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix(e,t)},e.prototype.setMatrix3x3=function(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix3x3(e,t)},e.prototype.setMatrix2x2=function(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix2x2(e,t)},e.prototype.setFloat=function(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat(e,t)},e.prototype.setVector2=function(e,t){this.setFloat2(e,t.x,t.y)},e.prototype.setFloat2=function(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat2(e,t,i)},e.prototype.setVector3=function(e,t){this.setFloat3(e,t.x,t.y,t.z)},e.prototype.setFloat3=function(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat3(e,t,i,r)},e.prototype.setVector4=function(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)},e.prototype.setQuaternion=function(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)},e.prototype.setFloat4=function(e,t,i,r,n){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat4(e,t,i,r,n)},e.prototype.setColor3=function(e,t){this.setFloat3(e,t.r,t.g,t.b)},e.prototype.setColor4=function(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)},e.prototype.setDirectColor4=function(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)},e.prototype._getVertexShaderCode=function(){var e;return null===(e=this.sources)||void 0===e?void 0:e.vertex},e.prototype._getFragmentShaderCode=function(){var e;return null===(e=this.sources)||void 0===e?void 0:e.fragment},e}(),a_={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4},s_=function(){function e(e){this.shaderLanguage=e,this._attributeNextLocation=0,this._varyingNextLocation=0,this.freeGroupIndex=0,this.freeBindingIndex=0,this.availableVaryings={},this.availableAttributes={},this.availableBuffers={},this.availableTextures={},this.availableSamplers={},this.orderedAttributes=[],this.bindGroupLayoutEntries=[],this.bindGroupLayoutEntryInfo=[],this.bindGroupEntries=[],this.bufferNames=[],this.textureNames=[],this.samplerNames=[],this.leftOverUniforms=[],this._findStartingGroupBinding()}return Object.defineProperty(e,"KnownUBOs",{get:function(){return e._SimplifiedKnownBindings?e._SimplifiedKnownUBOs:e._KnownUBOs},enumerable:!1,configurable:!0}),e.prototype._findStartingGroupBinding=function(){var t=e.KnownUBOs,i=[];for(var r in t){var n=t[r].binding;-1!==n.groupIndex&&(void 0===i[n.groupIndex]?i[n.groupIndex]=n.bindingIndex:i[n.groupIndex]=Math.max(i[n.groupIndex],n.bindingIndex))}this.freeGroupIndex=i.length-1,0===this.freeGroupIndex?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=i[i.length-1]+1},e.prototype.getAttributeNextLocation=function(e,t){var i;void 0===t&&(t=0);var r=this._attributeNextLocation;return this._attributeNextLocation+=(null!==(i=a_[e])&&void 0!==i?i:1)*(t||1),r},e.prototype.getVaryingNextLocation=function(e,t){var i;void 0===t&&(t=0);var r=this._varyingNextLocation;return this._varyingNextLocation+=(null!==(i=a_[e])&&void 0!==i?i:1)*(t||1),r},e.prototype.getNextFreeUBOBinding=function(){return this._getNextFreeBinding(1)},e.prototype._getNextFreeBinding=function(e){if(this.freeBindingIndex>65536-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),4===this.freeGroupIndex)throw"Too many textures or UBOs have been declared and it is not supported in WebGPU.";var t={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=e,t},e._SimplifiedKnownBindings=!0,e._SimplifiedKnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:-1,bindingIndex:-1}},Light1:{binding:{groupIndex:-1,bindingIndex:-1}},Light2:{binding:{groupIndex:-1,bindingIndex:-1}},Light3:{binding:{groupIndex:-1,bindingIndex:-1}},Light4:{binding:{groupIndex:-1,bindingIndex:-1}},Light5:{binding:{groupIndex:-1,bindingIndex:-1}},Light6:{binding:{groupIndex:-1,bindingIndex:-1}},Light7:{binding:{groupIndex:-1,bindingIndex:-1}},Light8:{binding:{groupIndex:-1,bindingIndex:-1}},Light9:{binding:{groupIndex:-1,bindingIndex:-1}},Light10:{binding:{groupIndex:-1,bindingIndex:-1}},Light11:{binding:{groupIndex:-1,bindingIndex:-1}},Light12:{binding:{groupIndex:-1,bindingIndex:-1}},Light13:{binding:{groupIndex:-1,bindingIndex:-1}},Light14:{binding:{groupIndex:-1,bindingIndex:-1}},Light15:{binding:{groupIndex:-1,bindingIndex:-1}},Light16:{binding:{groupIndex:-1,bindingIndex:-1}},Light17:{binding:{groupIndex:-1,bindingIndex:-1}},Light18:{binding:{groupIndex:-1,bindingIndex:-1}},Light19:{binding:{groupIndex:-1,bindingIndex:-1}},Light20:{binding:{groupIndex:-1,bindingIndex:-1}},Light21:{binding:{groupIndex:-1,bindingIndex:-1}},Light22:{binding:{groupIndex:-1,bindingIndex:-1}},Light23:{binding:{groupIndex:-1,bindingIndex:-1}},Light24:{binding:{groupIndex:-1,bindingIndex:-1}},Light25:{binding:{groupIndex:-1,bindingIndex:-1}},Light26:{binding:{groupIndex:-1,bindingIndex:-1}},Light27:{binding:{groupIndex:-1,bindingIndex:-1}},Light28:{binding:{groupIndex:-1,bindingIndex:-1}},Light29:{binding:{groupIndex:-1,bindingIndex:-1}},Light30:{binding:{groupIndex:-1,bindingIndex:-1}},Light31:{binding:{groupIndex:-1,bindingIndex:-1}},Material:{binding:{groupIndex:-1,bindingIndex:-1}},Mesh:{binding:{groupIndex:-1,bindingIndex:-1}},Internals:{binding:{groupIndex:-1,bindingIndex:-1}}},e._KnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:1,bindingIndex:0}},Light1:{binding:{groupIndex:1,bindingIndex:1}},Light2:{binding:{groupIndex:1,bindingIndex:2}},Light3:{binding:{groupIndex:1,bindingIndex:3}},Light4:{binding:{groupIndex:1,bindingIndex:4}},Light5:{binding:{groupIndex:1,bindingIndex:5}},Light6:{binding:{groupIndex:1,bindingIndex:6}},Light7:{binding:{groupIndex:1,bindingIndex:7}},Light8:{binding:{groupIndex:1,bindingIndex:8}},Light9:{binding:{groupIndex:1,bindingIndex:9}},Light10:{binding:{groupIndex:1,bindingIndex:10}},Light11:{binding:{groupIndex:1,bindingIndex:11}},Light12:{binding:{groupIndex:1,bindingIndex:12}},Light13:{binding:{groupIndex:1,bindingIndex:13}},Light14:{binding:{groupIndex:1,bindingIndex:14}},Light15:{binding:{groupIndex:1,bindingIndex:15}},Light16:{binding:{groupIndex:1,bindingIndex:16}},Light17:{binding:{groupIndex:1,bindingIndex:17}},Light18:{binding:{groupIndex:1,bindingIndex:18}},Light19:{binding:{groupIndex:1,bindingIndex:19}},Light20:{binding:{groupIndex:1,bindingIndex:20}},Light21:{binding:{groupIndex:1,bindingIndex:21}},Light22:{binding:{groupIndex:1,bindingIndex:22}},Light23:{binding:{groupIndex:1,bindingIndex:23}},Light24:{binding:{groupIndex:1,bindingIndex:24}},Light25:{binding:{groupIndex:1,bindingIndex:25}},Light26:{binding:{groupIndex:1,bindingIndex:26}},Light27:{binding:{groupIndex:1,bindingIndex:27}},Light28:{binding:{groupIndex:1,bindingIndex:28}},Light29:{binding:{groupIndex:1,bindingIndex:29}},Light30:{binding:{groupIndex:1,bindingIndex:30}},Light31:{binding:{groupIndex:1,bindingIndex:31}},Material:{binding:{groupIndex:2,bindingIndex:0}},Mesh:{binding:{groupIndex:2,bindingIndex:1}},Internals:{binding:{groupIndex:2,bindingIndex:2}}},e}(),l_=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._missingVaryings=[],t._textureArrayProcessing=[],t._vertexIsGLES3=!1,t._fragmentIsGLES3=!1,t.shaderLanguage=pt.GLSL,t.parseGLES3=!0,t}return m(t,e),t.prototype._getArraySize=function(e,t,i){var r=0,n=e.indexOf("["),o=e.indexOf("]");if(n>0&&o>0){var a=e.substring(n+1,o);r=+a,isNaN(r)&&(r=+i[a.trim()]),e=e.substr(0,n)}return[e,t,r]},t.prototype.initializeShaders=function(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0},t.prototype.preProcessShaderCode=function(e,t){var i="// Internals UBO\nuniform ".concat(n_.InternalsUBOName," {\nfloat yFactor_;\nfloat textureOutputHeight_;\n};\n"),r=-1!==e.indexOf("// Internals UBO");return t?(this._fragmentIsGLES3=-1!==e.indexOf("#version 3"),this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),r?e:i+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=-1!==e.indexOf("#version 3"),this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),r?e:i+e)},t.prototype.varyingCheck=function(e,t){return(t&&this._fragmentIsGLES3?/(flat\s)?\s*\bin\b/:!t&&this._vertexIsGLES3?/(flat\s)?\s*\bout\b/:/(flat\s)?\s*\bvarying\b/).test(e)},t.prototype.varyingProcessor=function(e,t,i){var r;this._preProcessors=i;var n=(t&&this._fragmentIsGLES3?/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:!t&&this._vertexIsGLES3?/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==n){var o,a=null!==(r=n[1])&&void 0!==r?r:"",s=n[2],l=n[3];t?(o=this._webgpuProcessingContext.availableVaryings[l],this._missingVaryings[o]="",void 0===o&&ae.Warn('Invalid fragment shader: The varying named "'.concat(l,'" is not declared in the vertex shader! This declaration will be ignored.'))):(o=this._webgpuProcessingContext.getVaryingNextLocation(s,this._getArraySize(l,s,i)[2]),this._webgpuProcessingContext.availableVaryings[l]=o,this._missingVaryings[o]="layout(location = ".concat(o,") ").concat(a," in ").concat(s," ").concat(l,";")),e=e.replace(n[0],void 0===o?"":"layout(location = ".concat(o,") ").concat(a," ").concat(t?"in":"out"," ").concat(s," ").concat(l,";"))}return e},t.prototype.attributeProcessor=function(e,t){this._preProcessors=t;var i=(this._vertexIsGLES3?/\s*in\s+(\S+)\s+(\S+)\s*;/gm:/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==i){var r=i[1],n=i[2],o=this._webgpuProcessingContext.getAttributeNextLocation(r,this._getArraySize(n,r,t)[2]);this._webgpuProcessingContext.availableAttributes[n]=o,this._webgpuProcessingContext.orderedAttributes[o]=n;var a=this.vertexBufferKindToNumberOfComponents[n];if(void 0!==a){var s=a<0?-1===a?"int":"ivec"+-a:1===a?"uint":"uvec"+a,l="_int_".concat(n,"_");e=e.replace(i[0],"layout(location = ".concat(o,") in ").concat(s," ").concat(l,"; ").concat(r," ").concat(n," = ").concat(r,"(").concat(l,");"))}else e=e.replace(i[0],"layout(location = ".concat(o,") in ").concat(r," ").concat(n,";"))}return e},t.prototype.uniformProcessor=function(e,t,i){var r,n;this._preProcessors=i;var o=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==o){var a=o[1],s=o[2];if(0===a.indexOf("sampler")||1===a.indexOf("sampler")){var l=0;s=(r=this._getArraySize(s,a,i))[0],a=r[1],l=r[2];var c=this._webgpuProcessingContext.availableTextures[s];if(!c){c={autoBindSampler:!0,isTextureArray:l>0,isStorageTexture:!1,textures:[],sampleType:Ff.Float};for(var u=0;u<(l||1);++u)c.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}var h=null!==(n=n_._SamplerTypeByWebGLSamplerType[a])&&void 0!==n?n:"sampler",d=!!n_._IsComparisonSamplerByWebGPUSamplerType[h],p=d?Nf.Comparison:Nf.Filtering,f=s+n_.AutoSamplerSuffix,_=this._webgpuProcessingContext.availableSamplers[f];_||(_={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:p});var m="u"===a.charAt(0)?"u":"i"===a.charAt(0)?"i":"";m&&(a=a.substr(1));var g=d?Ff.Depth:"u"===m?Ff.Uint:"i"===m?Ff.Sint:Ff.Float;c.sampleType=g;var v=l>0,y=_.binding.groupIndex,b=_.binding.bindingIndex,T=n_._SamplerFunctionByWebGLSamplerType[a],E=n_._TextureTypeByWebGLSamplerType[a],S=n_._GpuTextureViewDimensionByWebGPUTextureType[E];if(v){var x=[];for(x.push("layout(set = ".concat(y,", binding = ").concat(b,") uniform ").concat(m).concat(h," ").concat(f,";")),e="\n",u=0;u<l;++u){var A=c.textures[u].groupIndex,C=c.textures[u].bindingIndex;x.push("layout(set = ".concat(A,", binding = ").concat(C,") uniform ").concat(E," ").concat(s,"Texture").concat(u,";")),e+="".concat(u>0?"\n":"","#define ").concat(s).concat(u," ").concat(m).concat(T,"(").concat(s,"Texture").concat(u,", ").concat(f,")")}e=x.join("\n")+e,this._textureArrayProcessing.push(s)}else l=1,e="layout(set = ".concat(y,", binding = ").concat(b,") uniform ").concat(h," ").concat(f,";\n layout(set = ").concat(c.textures[0].groupIndex,", binding = ").concat(c.textures[0].bindingIndex,") uniform ").concat(m).concat(E," ").concat(s,"Texture;\n #define ").concat(s," ").concat(m).concat(T,"(").concat(s,"Texture, ").concat(f,")");for(this._webgpuProcessingContext.availableTextures[s]=c,this._webgpuProcessingContext.availableSamplers[f]=_,this._addSamplerBindingDescription(f,_,!t),u=0;u<l;++u)this._addTextureBindingDescription(s,c,u,S,null,!t)}else this._addUniformToLeftOverUBO(s,a,i),e=""}return e},t.prototype.uniformBufferProcessor=function(e,t){var i=/uniform\s+(\w+)/gm.exec(e);if(null!==i){var r=i[1],n=this._webgpuProcessingContext.availableBuffers[r];if(!n){var o=s_.KnownUBOs[r];n={binding:o&&-1!==o.binding.groupIndex?o.binding:this._webgpuProcessingContext.getNextFreeUBOBinding()},this._webgpuProcessingContext.availableBuffers[r]=n}this._addBufferBindingDescription(r,n,Df.Uniform,!t),e=e.replace("uniform","layout(set = ".concat(n.binding.groupIndex,", binding = ").concat(n.binding.bindingIndex,") uniform"))}return e},t.prototype.postProcessor=function(e,t,i,r,n){var o=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){var a=e.indexOf("gl_FragCoord")>=0,s=a?"vec4 glFragCoord_;\n":"",l=-1!==e.search(/layout *\(location *= *0\) *out/g);if(e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/gl_FragCoord/g,"glFragCoord_"),this._fragmentIsGLES3){var c=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);null!==c&&(e=e.substring(0,c.index)+"layout(location = 0) "+e.substring(c.index))}else e=e.replace(/void\s+?main\s*\(/g,(o||l?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");e=(e=e.replace(/dFdy/g,"(-yFactor_)*dFdy")).replace("##INJECTCODE##",s),a&&(e=this._injectStartingAndEndingCode(e,"void main","\n glFragCoord_ = gl_FragCoord;\n if (yFactor_ == 1.) {\n glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y;\n }\n "))}else if(e=(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex")).replace(/gl_VertexID/g,"gl_VertexIndex"),-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;if(!i){var u=e.lastIndexOf("}");e=e.substring(0,u),e+="gl_Position.y *= yFactor_;\n",e+="}"}return e},t.prototype._applyTextureArrayProcessing=function(e,t){for(var i=new RegExp(t+"\\s*\\[(.+)?\\]","gm"),r=i.exec(e);null!==r;){var n=r[1],o=+n;this._preProcessors&&isNaN(o)&&(o=+this._preProcessors[n.trim()]),e=e.replace(r[0],t+o),r=i.exec(e)}return e},t.prototype._generateLeftOverUBOCode=function(e,t){for(var i="layout(set = ".concat(t.binding.groupIndex,", binding = ").concat(t.binding.bindingIndex,") uniform ").concat(e," {\n "),r=0,n=this._webgpuProcessingContext.leftOverUniforms;r<n.length;r++){var o=n[r];o.length>0?i+=" ".concat(o.type," ").concat(o.name,"[").concat(o.length,"];\n"):i+=" ".concat(o.type," ").concat(o.name,";\n")}return i+"};\n\n"},t.prototype.finalizeShaders=function(e,t){for(var i=0;i<this._textureArrayProcessing.length;++i){var r=this._textureArrayProcessing[i];e=this._applyTextureArrayProcessing(e,r),t=this._applyTextureArrayProcessing(t,r)}for(i=0;i<this._missingVaryings.length;++i){var n=this._missingVaryings[i];n&&n.length>0&&(t=n+"\n"+t)}var o=this._buildLeftOverUBO();return e=o+e,t=o+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}},t}(n_);li.IncludesShadersStoreWGSL.bonesDeclaration="#if NUM_BONE_INFLUENCERS>0\nattribute matricesIndices : vec4<f32>;attribute matricesWeights : vec4<f32>;\n#if NUM_BONE_INFLUENCERS>4\nattribute matricesIndicesExtra : vec4<f32>;attribute matricesWeightsExtra : vec4<f32>;\n#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nvar boneSampler : texture_2d<f32>;uniform boneTextureWidth : f32;\n#else\nuniform mBones : array<mat4x4,BonesPerMesh>;\n#ifdef BONES_VELOCITY_ENABLED\nuniform mPreviousBones : array<mat4x4,BonesPerMesh>;\n#endif\n#endif\n#ifdef BONETEXTURE\nfn readMatrixFromRawSampler(smp : texture_2d<f32>,index : f32)->mat4x4<f32>\n{let offset=i32(index) *4; \nlet m0=textureLoad(smp,vec2<i32>(offset+0,0),0);let m1=textureLoad(smp,vec2<i32>(offset+1,0),0);let m2=textureLoad(smp,vec2<i32>(offset+2,0),0);let m3=textureLoad(smp,vec2<i32>(offset+3,0),0);return mat4x4<f32>(m0,m1,m2,m3);}\n#endif\n#endif\n#endif\n";li.IncludesShadersStoreWGSL.bonesVertex="#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nvar influence : mat4x4<f32>;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3];\n#endif \n#else \ninfluence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];\n#endif \n#endif\nfinalWorld=finalWorld*influence;\n#endif\n#endif\n";li.IncludesShadersStoreWGSL.bakedVertexAnimationDeclaration="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2<f32>;uniform bakedVertexAnimationSettings: vec4<f32>;var bakedVertexAnimationTexture : texture_2d<f32>;\n#ifdef INSTANCES\nattribute bakedVertexAnimationSettingsInstanced : vec4<f32>;\n#endif\nfn readMatrixFromRawSamplerVAT(smp : texture_2d<f32>,index : f32,frame : f32)->mat4x4<f32>\n{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2<i32>(offset+0,frameUV),0);let m1=textureLoad(smp,vec2<i32>(offset+1,frameUV),0);let m2=textureLoad(smp,vec2<i32>(offset+2,frameUV),0);let m3=textureLoad(smp,vec2<i32>(offset+3,frameUV),0);return mat4x4<f32>(m0,m1,m2,m3);}\n#endif\n";li.IncludesShadersStoreWGSL.bakedVertexAnimation="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\n#ifdef INSTANCES\nlet VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w;\n#else\nlet VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;\n#endif\nlet totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4<f32>;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3];\n#endif\nfinalWorld=finalWorld*VATInfluence;}\n#endif\n";li.IncludesShadersStoreWGSL.clipPlaneFragment="#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nif (false) {}\n#endif\n#ifdef CLIPPLANE\nelse if (fragmentInputs.fClipDistance>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE2\nelse if (fragmentInputs.fClipDistance2>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE3\nelse if (fragmentInputs.fClipDistance3>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE4\nelse if (fragmentInputs.fClipDistance4>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE5\nelse if (fragmentInputs.fClipDistance5>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE6\nelse if (fragmentInputs.fClipDistance6>0.0)\n{discard;}\n#endif\n";li.IncludesShadersStoreWGSL.clipPlaneFragmentDeclaration="#ifdef CLIPPLANE\nvarying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nvarying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nvarying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nvarying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nvarying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nvarying fClipDistance6: f32;\n#endif\n";li.IncludesShadersStoreWGSL.clipPlaneVertex="#ifdef CLIPPLANE\nvertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nvertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nvertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nvertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4);\n#endif\n#ifdef CLIPPLANE5\nvertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5);\n#endif\n#ifdef CLIPPLANE6\nvertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6);\n#endif\n";li.IncludesShadersStoreWGSL.clipPlaneVertexDeclaration="#ifdef CLIPPLANE\nuniform vClipPlane: vec4<f32>;varying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nuniform vClipPlane2: vec4<f32>;varying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nuniform vClipPlane3: vec4<f32>;varying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nuniform vClipPlane4: vec4<f32>;varying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nuniform vClipPlane5: vec4<f32>;varying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nuniform vClipPlane6: vec4<f32>;varying fClipDistance6: f32;\n#endif\n";li.IncludesShadersStoreWGSL.instancesDeclaration="#ifdef INSTANCES\nattribute world0 : vec4<f32>;attribute world1 : vec4<f32>;attribute world2 : vec4<f32>;attribute world3 : vec4<f32>;\n#ifdef INSTANCESCOLOR\nattribute instanceColor : vec4<f32>;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform world : mat4x4<f32>;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nattribute previousWorld0 : vec4<f32>;attribute previousWorld1 : vec4<f32>;attribute previousWorld2 : vec4<f32>;attribute previousWorld3 : vec4<f32>;\n#ifdef THIN_INSTANCES\nuniform previousWorld : mat4x4<f32>;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform world : mat4x4<f32>;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nuniform previousWorld : mat4x4<f32>;\n#endif\n#endif\n";li.IncludesShadersStoreWGSL.instancesVertex="#ifdef INSTANCES\nvar finalWorld=mat4x4<f32>(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=mat4x4<f32>(previousWorld0,previousWorld1,previousWorld2,previousWorld3);\n#endif\n#ifdef THIN_INSTANCES\n#if !defined(WORLD_UBO)\nfinalWorld=uniforms.world*finalWorld;\n#else\nfinalWorld=mesh.world*finalWorld;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nfinalPreviousWorld=previousWorld*finalPreviousWorld;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nvar finalWorld=uniforms.world;\n#else\nvar finalWorld=mesh.world;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=previousWorld;\n#endif\n#endif\n";li.IncludesShadersStoreWGSL.helperFunctions="const PI: f32=3.1415926535897932384626433832795;const RECIPROCAL_PI: f32=0.3183098861837907;const RECIPROCAL_PI2: f32=0.15915494309189535;const HALF_MIN: f32=5.96046448e-08; \nconst LinearEncodePowerApprox: f32=2.2;const GammaEncodePowerApprox: f32=1.0/LinearEncodePowerApprox;const LuminanceEncodeApprox: vec3<f32>=vec3<f32> (0.2126,0.7152,0.0722);const Epsilon:f32=0.0000001;\n#define saturate(x) clamp(x,0.0,1.0)\nfn transposeMat3(inMatrix: mat3x3f)->mat3x3f {let i0: vec3<f32>=inMatrix[0];let i1: vec3<f32>=inMatrix[1];let i2: vec3<f32>=inMatrix[2];let outMatrix:mat3x3f=mat3x3f(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);return outMatrix;}\nfn inverseMat3(inMatrix: mat3x3f)->mat3x3f {let a00: f32=inMatrix[0][0];let a01: f32=inMatrix[0][1];let a02: f32=inMatrix[0][2];let a10: f32=inMatrix[1][0];let a11: f32=inMatrix[1][1];let a12: f32=inMatrix[1][2];let a20: f32=inMatrix[2][0];let a21: f32=inMatrix[2][1];let a22: f32=inMatrix[2][2];let b01: f32=a22*a11-a12*a21;let b11: f32=-a22*a10+a12*a20;let b21: f32=a21*a10-a11*a20;let det: f32=a00*b01+a01*b11+a02*b21;return mat3x3f(b01/det,(-a22*a01+a02*a21)/det,(a12*a01-a02*a11)/det,\nb11/det,(a22*a00-a02*a20)/det,(-a12*a00+a02*a10)/det,\nb21/det,(-a21*a00+a01*a20)/det,(a11*a00-a01*a10)/det);}\n#if USE_EXACT_SRGB_CONVERSIONS\nfn toLinearSpaceExact(color: vec3<f32>)->vec3<f32>\n{let nearZeroSection: vec3<f32>=0.0773993808*color;let remainingSection: vec3<f32>=pow(0.947867299*(color+vec3<f32>(0.055)),vec3<f32>(2.4));return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3<f32>(0.04045)));}\nfn toGammaSpaceExact(color: vec3<f32>)->vec3<f32>\n{let nearZeroSection: vec3<f32>=12.92*color;let remainingSection: vec3<f32>=1.055*pow(color,vec3<f32>(0.41666))-vec3<f32>(0.055);return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3<f32>(0.0031308)));}\n#endif\nfn toLinearSpace(color: vec4<f32>)->vec4<f32>\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4<f32>(toLinearSpaceExact(color.rgb),color.a);\n#else\nreturn vec4<f32>(pow(color.rgb,vec3<f32>(LinearEncodePowerApprox)),color.a);\n#endif\n}\nfn toLinearSpaceVec3(color: vec3<f32>)->vec3<f32>\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3<f32>(LinearEncodePowerApprox));\n#endif\n}\nfn toGammaSpace(color: vec4<f32>)->vec4<f32>\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4<f32>(toGammaSpaceExact(color.rgb),color.a);\n#else\nreturn vec4<f32>(pow(color.rgb,vec3<f32>(GammaEncodePowerApprox)),color.a);\n#endif\n}\nfn toGammaSpaceVec3(color: vec3<f32>)->vec3<f32>\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3<f32>(GammaEncodePowerApprox));\n#endif\n}\nfn square(value: vec3<f32>)->vec3<f32>\n{return value*value;}\nfn pow5(value: f32)->f32 {let sq: f32=value*value;return sq*sq*value;}\nfn getLuminance(color: vec3<f32>)->f32\n{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);}\nfn getRand(seed: vec2<f32>)->f32 {return fract(sin(dot(seed.xy ,vec2<f32>(12.9898,78.233)))*43758.5453);}\nfn dither(seed: vec2<f32>,varianceAmount: f32)->f32 {let rand: f32=getRand(seed);let normVariance: f32=varianceAmount/255.0;let dither: f32=mix(-normVariance,normVariance,rand);return dither;}\nconst rgbdMaxRange: f32=255.0;fn toRGBD(color: vec3<f32>)->vec4<f32> {let maxRGB: f32=max(max(color.r,max(color.g,color.b)),Epsilon);var D: f32 =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);var rgb: vec3<f32> =color.rgb*D;rgb=toGammaSpaceVec3(rgb);return vec4<f32>(clamp(rgb,vec3<f32>(0.,0.,0.),vec3<f32>(1.,1.,1.)),D); }\nfn fromRGBD(rgbd: vec4<f32>)->vec3<f32> {let rgb=toLinearSpaceVec3(rgbd.rgb);return rgb/rgbd.a;}\nfn parallaxCorrectNormal(vertexPos: vec3<f32>,origVec: vec3<f32>,cubeSize: vec3<f32>,cubePos: vec3<f32>)->vec3<f32> {let invOrigVec: vec3<f32>=vec3<f32>(1.0,1.0,1.0)/origVec;let halfSize: vec3<f32>=cubeSize*0.5;let intersecAtMaxPlane: vec3<f32>=(cubePos+halfSize-vertexPos)*invOrigVec;let intersecAtMinPlane: vec3<f32>=(cubePos-halfSize-vertexPos)*invOrigVec;let largestIntersec: vec3<f32>=max(intersecAtMaxPlane,intersecAtMinPlane);let distance: f32=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);let intersectPositionWS: vec3<f32>=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}\n";li.IncludesShadersStoreWGSL.fresnelFunction="#ifdef FRESNEL\nfn computeFresnelTerm(viewDirection: vec3f,worldNormal: vec3f,bias: f32,power: f32)->f32\n{let fresnelTerm: f32=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);}\n#endif\n";li.IncludesShadersStoreWGSL.meshUboDeclaration="struct Mesh {world : mat4x4<f32>,\nvisibility : f32,};var<uniform> mesh : Mesh;\n#define WORLD_UBO\n";li.IncludesShadersStoreWGSL.morphTargetsVertex="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\n#if {X}==0\nfor (var i=0; i<$NUM_MORPH_INFLUENCERS$; i=i+1) {if (i>=uniforms.morphTargetCount) {break;}\nvertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n}\n#endif\n#else\npositionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\n#endif\n#endif\n#endif\n";li.IncludesShadersStoreWGSL.morphTargetsVertexDeclaration="#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute position{X} : vec3<f32>;\n#ifdef MORPHTARGETS_NORMAL\nattribute normal{X} : vec3<f32>;\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute tangent{X} : vec3<f32>;\n#endif\n#ifdef MORPHTARGETS_UV\nattribute uv_{X} : vec2<f32>;\n#endif\n#elif {X}==0\nuniform morphTargetCount: i32;\n#endif\n#endif\n";li.IncludesShadersStoreWGSL.morphTargetsVertexGlobal="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nvar vertexID : f32;\n#endif\n#endif\n";li.IncludesShadersStoreWGSL.morphTargetsVertexGlobalDeclaration="#ifdef MORPHTARGETS\nuniform morphTargetInfluences : array<f32,NUM_MORPH_INFLUENCERS>;\n#ifdef MORPHTARGETS_TEXTURE \nuniform morphTargetTextureIndices : array<f32,NUM_MORPH_INFLUENCERS>;uniform morphTargetTextureInfo : vec3<f32>;var morphTargets : texture_2d_array<f32>;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3<f32>\n{ \nlet y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2<f32>((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;}\n#endif\n#endif\n";li.IncludesShadersStoreWGSL.sceneUboDeclaration="struct Scene {viewProjection : mat4x4<f32>,\n#ifdef MULTIVIEW\nviewProjectionR : mat4x4<f32>,\n#endif \nview : mat4x4<f32>,\nprojection : mat4x4<f32>,\nvEyePosition : vec4<f32>,};var<uniform> scene : Scene;\n";var c_,u_,h_={texture_1d:xf.E1d,texture_2d:xf.E2d,texture_2d_array:xf.E2dArray,texture_3d:xf.E3d,texture_cube:xf.Cube,texture_cube_array:xf.CubeArray,texture_multisampled_2d:xf.E2d,texture_depth_2d:xf.E2d,texture_depth_2d_array:xf.E2dArray,texture_depth_cube:xf.Cube,texture_depth_cube_array:xf.CubeArray,texture_depth_multisampled_2d:xf.E2d,texture_storage_1d:xf.E1d,texture_storage_2d:xf.E2d,texture_storage_2d_array:xf.E2dArray,texture_storage_3d:xf.E3d,texture_external:null},d_=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.shaderLanguage=pt.WGSL,t.uniformRegexp=/uniform\s+(\w+)\s*:\s*(.+)\s*;/,t.textureRegexp=/var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,t.noPrecision=!0,t}return m(t,e),t.prototype._getArraySize=function(e,t,i){var r=0,n=t.lastIndexOf(">");if(t.indexOf("array")>=0&&n>0){for(var o=n;o>0&&" "!==t.charAt(o)&&","!==t.charAt(o);)o--;var a=t.substring(o+1,n);for(r=+a,isNaN(r)&&(r=+i[a.trim()]);o>0&&(" "===t.charAt(o)||","===t.charAt(o));)o--;t=t.substring(t.indexOf("<")+1,o+1)}return[e,t,r]},t.prototype.initializeShaders=function(e){this._webgpuProcessingContext=e,this._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]},t.prototype.preProcessShaderCode=function(e){var t="struct ".concat(n_.InternalsUBOName," {\n yFactor_: f32,\n textureOutputHeight_: f32,\n};\nvar<uniform> ").concat("internals"," : ").concat(n_.InternalsUBOName,";\n");return-1!==e.indexOf(t)?e:t+$p(e)},t.prototype.varyingCheck=function(e,t){return/(flat|linear|perspective)?\s*(center|centroid|sample)?\s*\bvarying\b/.test(e)},t.prototype.varyingProcessor=function(e,t,i){var r,n,o=/\s*(flat|linear|perspective)?\s*(center|centroid|sample)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==o){var a,s=null!==(r=o[1])&&void 0!==r?r:"perspective",l=null!==(n=o[2])&&void 0!==n?n:"center",c=o[4],u=o[3],h="flat"===s?"@interpolate(".concat(s,")"):"@interpolate(".concat(s,", ").concat(l,")");t?void 0===(a=this._webgpuProcessingContext.availableVaryings[u])&&ae.Warn('Invalid fragment shader: The varying named "'.concat(u,'" is not declared in the vertex shader! This declaration will be ignored.')):(a=this._webgpuProcessingContext.getVaryingNextLocation(c,this._getArraySize(u,c,i)[2]),this._webgpuProcessingContext.availableVaryings[u]=a,this._varyingsWGSL.push(" @location(".concat(a,") ").concat(h," ").concat(u," : ").concat(c,",")),this._varyingNamesWGSL.push(u)),e=""}return e},t.prototype.attributeProcessor=function(e,t){var i=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==i){var r=i[2],n=i[1],o=this._webgpuProcessingContext.getAttributeNextLocation(r,this._getArraySize(n,r,t)[2]);this._webgpuProcessingContext.availableAttributes[n]=o,this._webgpuProcessingContext.orderedAttributes[o]=n;var a=this.vertexBufferKindToNumberOfComponents[n];if(void 0!==a){var s=a<0?-1===a?"i32":"vec"+-a+"<i32>":1===a?"u32":"vec"+a+"<u32>",l="_int_".concat(n,"_");this._attributesInputWGSL.push("@location(".concat(o,") ").concat(l," : ").concat(s,",")),this._attributesWGSL.push("".concat(n," : ").concat(r,",")),this._attributesConversionCodeWGSL.push("vertexInputs.".concat(n," = ").concat(r,"(vertexInputs_.").concat(l,");")),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push("@location(".concat(o,") ").concat(n," : ").concat(r,",")),this._attributesWGSL.push("".concat(n," : ").concat(r,",")),this._attributesConversionCodeWGSL.push("vertexInputs.".concat(n," = vertexInputs_.").concat(n,";"));e=""}return e},t.prototype.uniformProcessor=function(e,t,i){var r=this.uniformRegexp.exec(e);if(null!==r){var n=r[2],o=r[1];this._addUniformToLeftOverUBO(o,n,i),e=""}return e},t.prototype.textureProcessor=function(e,t,i){var r=this.textureRegexp.exec(e);if(null!==r){var n=r[1],o=r[2],a=!!r[3],s=r[4],l=s.indexOf("storage")>0,c=r[6],u=l?c.substring(0,c.indexOf(",")).trim():null,h=a?this._getArraySize(n,o,i)[2]:0,d=this._webgpuProcessingContext.availableTextures[n];if(d)h=d.textures.length;else{d={isTextureArray:h>0,isStorageTexture:l,textures:[],sampleType:Ff.Float},h=h||1;for(var p=0;p<h;++p)d.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}this._webgpuProcessingContext.availableTextures[n]=d;var f=s.indexOf("depth")>0,_=h_[s],m=f?Ff.Depth:"u32"===c?Ff.Uint:"i32"===c?Ff.Sint:Ff.Float;if(d.sampleType=m,void 0===_)throw"Can't get the texture dimension corresponding to the texture function \"".concat(s,'"!');for(p=0;p<h;++p){var g=d.textures[p],v=g.groupIndex,y=g.bindingIndex;0===p&&(e="@group(".concat(v,") @binding(").concat(y,") ").concat(e)),this._addTextureBindingDescription(n,d,p,_,u,!t)}}return e},t.prototype.postProcessor=function(e,t){for(var i={},r=0,n=t;r<n.length;r++){var o=n[r].split(/ +/);i[o[1]]=o.length>2?o[2]:""}return e.replace(/\$(\w+)\$/g,(function(e,t){var r;return null!==(r=i[t])&&void 0!==r?r:t}))},t.prototype.finalizeShaders=function(e,t){var i=t.indexOf("fragmentInputs.position")>=0?"\n if (internals.yFactor_ == 1.) {\n fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y;\n }\n ":"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);var r=this._buildLeftOverUBO();t=r+t,e=(e=r+e).replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);var n="struct VertexInputs {\n @builtin(vertex_index) vertexIndex : u32,\n @builtin(instance_index) instanceIndex : u32,\n";this._attributesInputWGSL.length>0&&(n+=this._attributesInputWGSL.join("\n")),n+="\n};\nvar<private> vertexInputs"+(this._hasNonFloatAttribute?"_":"")+" : VertexInputs;\n",this._hasNonFloatAttribute&&(n+="struct VertexInputs_ {\n vertexIndex : u32, instanceIndex : u32,\n",n+=this._attributesWGSL.join("\n"),n+="\n};\nvar<private> vertexInputs : VertexInputs_;\n");var o="struct FragmentInputs {\n @builtin(position) position : vec4<f32>,\n";this._varyingsWGSL.length>0&&(o+=this._varyingsWGSL.join("\n")),e=n+(o+="\n};\nvar<private> vertexOutputs : FragmentInputs;\n")+e;var a="\n vertexInputs".concat(this._hasNonFloatAttribute?"_":""," = input;\n");this._hasNonFloatAttribute&&(a+="vertexInputs.vertexIndex = vertexInputs_.vertexIndex;\nvertexInputs.instanceIndex = vertexInputs_.instanceIndex;\n",a+=this._attributesConversionCodeWGSL.join("\n"),a+="\n"),e=this._injectStartingAndEndingCode(e,"fn main",a," vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;\n return vertexOutputs;"),t=t.replace(/#define /g,"//#define "),t=(t=this._processStridedUniformArrays(t)).replace(/dpdy/g,"(-internals.yFactor_)*dpdy");var s="struct FragmentInputs {\n @builtin(position) position : vec4<f32>,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(s+=this._varyingsWGSL.join("\n")),s+="\n};\nvar<private> fragmentInputs : FragmentInputs;\n";for(var l="struct FragmentOutputs {\n @location(0) color : vec4<f32>,\n",c=!1,u=0;!(c||(u=t.indexOf("fragmentOutputs.fragDepth",u))<0);){var h=u;for(c=!0;u>1&&"\n"!==t.charAt(u);){if("/"===t.charAt(u)&&"/"===t.charAt(u-1)){c=!1;break}u--}u=h+25}c&&(l+=" @builtin(frag_depth) fragDepth: f32,\n"),t=s+(l+="};\nvar<private> fragmentOutputs : FragmentOutputs;\n")+t;var d=" fragmentInputs = input;\n "+i;return t=this._injectStartingAndEndingCode(t,"fn main",d," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}},t.prototype._generateLeftOverUBOCode=function(e,t){for(var i="",r="struct ".concat(e," {\n"),n=0,o=this._webgpuProcessingContext.leftOverUniforms;n<o.length;n++){var a=o[n],s=a.type.replace(/^(.*?)(<.*>)?$/,"$1"),l=n_.UniformSizes[s];if(a.length>0)if(l<=2){var c="".concat(e,"_").concat(this._stridedUniformArrays.length,"_strided_arr");i+="struct ".concat(c," {\n @size(16)\n el: ").concat(s,",\n }"),this._stridedUniformArrays.push(a.name),r+=" @align(16) ".concat(a.name," : array<").concat(c,", ").concat(a.length,">,\n")}else r+=" ".concat(a.name," : array<").concat(a.type,", ").concat(a.length,">,\n");else r+=" ".concat(a.name," : ").concat(a.type,",\n")}return r+="};\n",(r="".concat(i,"\n").concat(r))+"@group(".concat(t.binding.groupIndex,") @binding(").concat(t.binding.bindingIndex,") var<uniform> ").concat("uniforms"," : ").concat(e,";\n")},t.prototype._processSamplers=function(e,t){for(var i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;;){var r=i.exec(e);if(null===r)break;var n=r[1],o=r[2],a=n.indexOf(n_.AutoSamplerSuffix)===n.length-n_.AutoSamplerSuffix.length?n.substring(0,n.indexOf(n_.AutoSamplerSuffix)):null,s="sampler_comparison"===o?Nf.Comparison:Nf.Filtering;if(a){var l=this._webgpuProcessingContext.availableTextures[a];l&&(l.autoBindSampler=!0)}var c=this._webgpuProcessingContext.availableSamplers[n];c||(c={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:s},this._webgpuProcessingContext.availableSamplers[n]=c),this._addSamplerBindingDescription(n,c,t);var u=e.substring(0,r.index),h="@group(".concat(c.binding.groupIndex,") @binding(").concat(c.binding.bindingIndex,") "),d=e.substring(r.index);e=u+h+d,i.lastIndex+=h.length}return e},t.prototype._processCustomBuffers=function(e,t){for(var i,r=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;;){var n=r.exec(e);if(null===n)break;var o=n[1],a=n[3],s=n[4],l=n[5],c=this._webgpuProcessingContext.availableBuffers[s];if(!c){var u="uniform"===o?s_.KnownUBOs[l]:null,h=void 0;u?(s=l,-1===(h=u.binding).groupIndex&&((h=null===(i=this._webgpuProcessingContext.availableBuffers[s])||void 0===i?void 0:i.binding)||(h=this._webgpuProcessingContext.getNextFreeUBOBinding()))):h=this._webgpuProcessingContext.getNextFreeUBOBinding(),c={binding:h},this._webgpuProcessingContext.availableBuffers[s]=c}this._addBufferBindingDescription(s,this._webgpuProcessingContext.availableBuffers[s],"read_write"===a?Df.Storage:"storage"===o?Df.ReadOnlyStorage:Df.Uniform,t);var d=c.binding.groupIndex,p=c.binding.bindingIndex,f=e.substring(0,n.index),_="@group(".concat(d,") @binding(").concat(p,") "),m=e.substring(n.index);e=f+_+m,r.lastIndex+=_.length}return e},t.prototype._processStridedUniformArrays=function(e){for(var t=0,i=this._stridedUniformArrays;t<i.length;t++){var r=i[t];e=e.replace(new RegExp("".concat(r,"\\s*\\[(.*)\\]"),"g"),"".concat(r,"[$1].el"))}return e},t}(n_),p_=function(){function e(){}return e.ComputeNumMipmapLevels=function(e,t){return j.ILog2(Math.max(e,t))+1},e.GetTextureTypeFromFormat=function(e){switch(e){case Cf.R8Unorm:case Cf.R8Snorm:case Cf.R8Uint:case Cf.R8Sint:case Cf.RG8Unorm:case Cf.RG8Snorm:case Cf.RG8Uint:case Cf.RG8Sint:case Cf.RGBA8Unorm:case Cf.RGBA8UnormSRGB:case Cf.RGBA8Snorm:case Cf.RGBA8Uint:case Cf.RGBA8Sint:case Cf.BGRA8Unorm:case Cf.BGRA8UnormSRGB:case Cf.RGB10A2UINT:case Cf.RGB10A2Unorm:case Cf.RGB9E5UFloat:case Cf.RG11B10UFloat:case Cf.BC7RGBAUnorm:case Cf.BC7RGBAUnormSRGB:case Cf.BC6HRGBUFloat:case Cf.BC6HRGBFloat:case Cf.BC5RGUnorm:case Cf.BC5RGSnorm:case Cf.BC3RGBAUnorm:case Cf.BC3RGBAUnormSRGB:case Cf.BC2RGBAUnorm:case Cf.BC2RGBAUnormSRGB:case Cf.BC4RUnorm:case Cf.BC4RSnorm:case Cf.BC1RGBAUnorm:case Cf.BC1RGBAUnormSRGB:case Cf.ETC2RGB8Unorm:case Cf.ETC2RGB8UnormSRGB:case Cf.ETC2RGB8A1Unorm:case Cf.ETC2RGB8A1UnormSRGB:case Cf.ETC2RGBA8Unorm:case Cf.ETC2RGBA8UnormSRGB:case Cf.EACR11Unorm:case Cf.EACR11Snorm:case Cf.EACRG11Unorm:case Cf.EACRG11Snorm:case Cf.ASTC4x4Unorm:case Cf.ASTC4x4UnormSRGB:case Cf.ASTC5x4Unorm:case Cf.ASTC5x4UnormSRGB:case Cf.ASTC5x5Unorm:case Cf.ASTC5x5UnormSRGB:case Cf.ASTC6x5Unorm:case Cf.ASTC6x5UnormSRGB:case Cf.ASTC6x6Unorm:case Cf.ASTC6x6UnormSRGB:case Cf.ASTC8x5Unorm:case Cf.ASTC8x5UnormSRGB:case Cf.ASTC8x6Unorm:case Cf.ASTC8x6UnormSRGB:case Cf.ASTC8x8Unorm:case Cf.ASTC8x8UnormSRGB:case Cf.ASTC10x5Unorm:case Cf.ASTC10x5UnormSRGB:case Cf.ASTC10x6Unorm:case Cf.ASTC10x6UnormSRGB:case Cf.ASTC10x8Unorm:case Cf.ASTC10x8UnormSRGB:case Cf.ASTC10x10Unorm:case Cf.ASTC10x10UnormSRGB:case Cf.ASTC12x10Unorm:case Cf.ASTC12x10UnormSRGB:case Cf.ASTC12x12Unorm:case Cf.ASTC12x12UnormSRGB:case Cf.Stencil8:return u.TEXTURETYPE_UNSIGNED_BYTE;case Cf.R16Uint:case Cf.R16Sint:case Cf.RG16Uint:case Cf.RG16Sint:case Cf.RGBA16Uint:case Cf.RGBA16Sint:case Cf.Depth16Unorm:return u.TEXTURETYPE_UNSIGNED_SHORT;case Cf.R16Float:case Cf.RG16Float:case Cf.RGBA16Float:return u.TEXTURETYPE_HALF_FLOAT;case Cf.R32Uint:case Cf.R32Sint:case Cf.RG32Uint:case Cf.RG32Sint:case Cf.RGBA32Uint:case Cf.RGBA32Sint:return u.TEXTURETYPE_UNSIGNED_INTEGER;case Cf.R32Float:case Cf.RG32Float:case Cf.RGBA32Float:case Cf.Depth32Float:case Cf.Depth32FloatStencil8:case Cf.Depth24Plus:case Cf.Depth24PlusStencil8:return u.TEXTURETYPE_FLOAT}return u.TEXTURETYPE_UNSIGNED_BYTE},e.GetBlockInformationFromFormat=function(e){switch(e){case Cf.R8Unorm:case Cf.R8Snorm:case Cf.R8Uint:case Cf.R8Sint:return{width:1,height:1,length:1};case Cf.R16Uint:case Cf.R16Sint:case Cf.R16Float:case Cf.RG8Unorm:case Cf.RG8Snorm:case Cf.RG8Uint:case Cf.RG8Sint:return{width:1,height:1,length:2};case Cf.R32Uint:case Cf.R32Sint:case Cf.R32Float:case Cf.RG16Uint:case Cf.RG16Sint:case Cf.RG16Float:case Cf.RGBA8Unorm:case Cf.RGBA8UnormSRGB:case Cf.RGBA8Snorm:case Cf.RGBA8Uint:case Cf.RGBA8Sint:case Cf.BGRA8Unorm:case Cf.BGRA8UnormSRGB:case Cf.RGB9E5UFloat:case Cf.RGB10A2UINT:case Cf.RGB10A2Unorm:case Cf.RG11B10UFloat:return{width:1,height:1,length:4};case Cf.RG32Uint:case Cf.RG32Sint:case Cf.RG32Float:case Cf.RGBA16Uint:case Cf.RGBA16Sint:case Cf.RGBA16Float:return{width:1,height:1,length:8};case Cf.RGBA32Uint:case Cf.RGBA32Sint:case Cf.RGBA32Float:return{width:1,height:1,length:16};case Cf.Stencil8:throw"No fixed size for Stencil8 format!";case Cf.Depth16Unorm:return{width:1,height:1,length:2};case Cf.Depth24Plus:throw"No fixed size for Depth24Plus format!";case Cf.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case Cf.Depth32Float:return{width:1,height:1,length:4};case Cf.Depth32FloatStencil8:return{width:1,height:1,length:5};case Cf.BC7RGBAUnorm:case Cf.BC7RGBAUnormSRGB:case Cf.BC6HRGBUFloat:case Cf.BC6HRGBFloat:case Cf.BC5RGUnorm:case Cf.BC5RGSnorm:case Cf.BC3RGBAUnorm:case Cf.BC3RGBAUnormSRGB:case Cf.BC2RGBAUnorm:case Cf.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case Cf.BC4RUnorm:case Cf.BC4RSnorm:case Cf.BC1RGBAUnorm:case Cf.BC1RGBAUnormSRGB:case Cf.ETC2RGB8Unorm:case Cf.ETC2RGB8UnormSRGB:case Cf.ETC2RGB8A1Unorm:case Cf.ETC2RGB8A1UnormSRGB:case Cf.EACR11Unorm:case Cf.EACR11Snorm:return{width:4,height:4,length:8};case Cf.ETC2RGBA8Unorm:case Cf.ETC2RGBA8UnormSRGB:case Cf.EACRG11Unorm:case Cf.EACRG11Snorm:case Cf.ASTC4x4Unorm:case Cf.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case Cf.ASTC5x4Unorm:case Cf.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case Cf.ASTC5x5Unorm:case Cf.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case Cf.ASTC6x5Unorm:case Cf.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case Cf.ASTC6x6Unorm:case Cf.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case Cf.ASTC8x5Unorm:case Cf.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case Cf.ASTC8x6Unorm:case Cf.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case Cf.ASTC8x8Unorm:case Cf.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case Cf.ASTC10x5Unorm:case Cf.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case Cf.ASTC10x6Unorm:case Cf.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case Cf.ASTC10x8Unorm:case Cf.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case Cf.ASTC10x10Unorm:case Cf.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case Cf.ASTC12x10Unorm:case Cf.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case Cf.ASTC12x12Unorm:case Cf.ASTC12x12UnormSRGB:return{width:12,height:12,length:16}}return{width:1,height:1,length:4}},e.IsHardwareTexture=function(e){return!!e.release},e.IsInternalTexture=function(e){return!!e.dispose},e.IsImageBitmap=function(e){return void 0!==e.close},e.IsImageBitmapArray=function(e){return Array.isArray(e)&&void 0!==e[0].close},e.IsCompressedFormat=function(e){switch(e){case Cf.BC7RGBAUnormSRGB:case Cf.BC7RGBAUnorm:case Cf.BC6HRGBFloat:case Cf.BC6HRGBUFloat:case Cf.BC5RGSnorm:case Cf.BC5RGUnorm:case Cf.BC4RSnorm:case Cf.BC4RUnorm:case Cf.BC3RGBAUnormSRGB:case Cf.BC3RGBAUnorm:case Cf.BC2RGBAUnormSRGB:case Cf.BC2RGBAUnorm:case Cf.BC1RGBAUnormSRGB:case Cf.BC1RGBAUnorm:case Cf.ETC2RGB8Unorm:case Cf.ETC2RGB8UnormSRGB:case Cf.ETC2RGB8A1Unorm:case Cf.ETC2RGB8A1UnormSRGB:case Cf.ETC2RGBA8Unorm:case Cf.ETC2RGBA8UnormSRGB:case Cf.EACR11Unorm:case Cf.EACR11Snorm:case Cf.EACRG11Unorm:case Cf.EACRG11Snorm:case Cf.ASTC4x4Unorm:case Cf.ASTC4x4UnormSRGB:case Cf.ASTC5x4Unorm:case Cf.ASTC5x4UnormSRGB:case Cf.ASTC5x5Unorm:case Cf.ASTC5x5UnormSRGB:case Cf.ASTC6x5Unorm:case Cf.ASTC6x5UnormSRGB:case Cf.ASTC6x6Unorm:case Cf.ASTC6x6UnormSRGB:case Cf.ASTC8x5Unorm:case Cf.ASTC8x5UnormSRGB:case Cf.ASTC8x6Unorm:case Cf.ASTC8x6UnormSRGB:case Cf.ASTC8x8Unorm:case Cf.ASTC8x8UnormSRGB:case Cf.ASTC10x5Unorm:case Cf.ASTC10x5UnormSRGB:case Cf.ASTC10x6Unorm:case Cf.ASTC10x6UnormSRGB:case Cf.ASTC10x8Unorm:case Cf.ASTC10x8UnormSRGB:case Cf.ASTC10x10Unorm:case Cf.ASTC10x10UnormSRGB:case Cf.ASTC12x10Unorm:case Cf.ASTC12x10UnormSRGB:case Cf.ASTC12x12Unorm:case Cf.ASTC12x12UnormSRGB:return!0}return!1},e.GetWebGPUTextureFormat=function(e,t,i){switch(void 0===i&&(i=!1),t){case u.TEXTUREFORMAT_DEPTH16:return Cf.Depth16Unorm;case u.TEXTUREFORMAT_DEPTH24:return Cf.Depth24Plus;case u.TEXTUREFORMAT_DEPTH24_STENCIL8:return Cf.Depth24PlusStencil8;case u.TEXTUREFORMAT_DEPTH32_FLOAT:return Cf.Depth32Float;case u.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8:return Cf.Depth32FloatStencil8;case u.TEXTUREFORMAT_STENCIL8:return Cf.Stencil8;case u.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM:return i?Cf.BC7RGBAUnormSRGB:Cf.BC7RGBAUnorm;case u.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT:return Cf.BC6HRGBUFloat;case u.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT:return Cf.BC6HRGBFloat;case u.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5:return i?Cf.BC3RGBAUnormSRGB:Cf.BC3RGBAUnorm;case u.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3:return i?Cf.BC2RGBAUnormSRGB:Cf.BC2RGBAUnorm;case u.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1:case u.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1:return i?Cf.BC1RGBAUnormSRGB:Cf.BC1RGBAUnorm;case u.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4:return i?Cf.ASTC4x4UnormSRGB:Cf.ASTC4x4Unorm;case u.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL:case u.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2:return i?Cf.ETC2RGB8UnormSRGB:Cf.ETC2RGB8Unorm;case u.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC:return i?Cf.ETC2RGBA8UnormSRGB:Cf.ETC2RGBA8Unorm}switch(e){case u.TEXTURETYPE_BYTE:switch(t){case u.TEXTUREFORMAT_RED:return Cf.R8Snorm;case u.TEXTUREFORMAT_RG:return Cf.RG8Snorm;case u.TEXTUREFORMAT_RGB:throw"RGB format not supported in WebGPU";case u.TEXTUREFORMAT_RED_INTEGER:return Cf.R8Sint;case u.TEXTUREFORMAT_RG_INTEGER:return Cf.RG8Sint;case u.TEXTUREFORMAT_RGB_INTEGER:throw"RGB_INTEGER format not supported in WebGPU";case u.TEXTUREFORMAT_RGBA_INTEGER:return Cf.RGBA8Sint;default:return Cf.RGBA8Snorm}case u.TEXTURETYPE_UNSIGNED_BYTE:switch(t){case u.TEXTUREFORMAT_RED:return Cf.R8Unorm;case u.TEXTUREFORMAT_RG:return Cf.RG8Unorm;case u.TEXTUREFORMAT_RGB:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case u.TEXTUREFORMAT_RGBA:return i?Cf.RGBA8UnormSRGB:Cf.RGBA8Unorm;case u.TEXTUREFORMAT_BGRA:return i?Cf.BGRA8UnormSRGB:Cf.BGRA8Unorm;case u.TEXTUREFORMAT_RED_INTEGER:return Cf.R8Uint;case u.TEXTUREFORMAT_RG_INTEGER:return Cf.RG8Uint;case u.TEXTUREFORMAT_RGB_INTEGER:throw"RGB_INTEGER format not supported in WebGPU";case u.TEXTUREFORMAT_RGBA_INTEGER:return Cf.RGBA8Uint;case u.TEXTUREFORMAT_ALPHA:throw"TEXTUREFORMAT_ALPHA format not supported in WebGPU";case u.TEXTUREFORMAT_LUMINANCE:throw"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";case u.TEXTUREFORMAT_LUMINANCE_ALPHA:throw"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";default:return Cf.RGBA8Unorm}case u.TEXTURETYPE_SHORT:switch(t){case u.TEXTUREFORMAT_RED_INTEGER:return Cf.R16Sint;case u.TEXTUREFORMAT_RG_INTEGER:return Cf.RG16Sint;case u.TEXTUREFORMAT_RGB_INTEGER:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case u.TEXTUREFORMAT_RGBA_INTEGER:default:return Cf.RGBA16Sint}case u.TEXTURETYPE_UNSIGNED_SHORT:switch(t){case u.TEXTUREFORMAT_RED_INTEGER:return Cf.R16Uint;case u.TEXTUREFORMAT_RG_INTEGER:return Cf.RG16Uint;case u.TEXTUREFORMAT_RGB_INTEGER:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case u.TEXTUREFORMAT_RGBA_INTEGER:default:return Cf.RGBA16Uint}case u.TEXTURETYPE_INT:switch(t){case u.TEXTUREFORMAT_RED_INTEGER:return Cf.R32Sint;case u.TEXTUREFORMAT_RG_INTEGER:return Cf.RG32Sint;case u.TEXTUREFORMAT_RGB_INTEGER:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case u.TEXTUREFORMAT_RGBA_INTEGER:default:return Cf.RGBA32Sint}case u.TEXTURETYPE_UNSIGNED_INTEGER:switch(t){case u.TEXTUREFORMAT_RED_INTEGER:return Cf.R32Uint;case u.TEXTUREFORMAT_RG_INTEGER:return Cf.RG32Uint;case u.TEXTUREFORMAT_RGB_INTEGER:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";case u.TEXTUREFORMAT_RGBA_INTEGER:default:return Cf.RGBA32Uint}case u.TEXTURETYPE_FLOAT:switch(t){case u.TEXTUREFORMAT_RED:return Cf.R32Float;case u.TEXTUREFORMAT_RG:return Cf.RG32Float;case u.TEXTUREFORMAT_RGB:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case u.TEXTUREFORMAT_RGBA:default:return Cf.RGBA32Float}case u.TEXTURETYPE_HALF_FLOAT:switch(t){case u.TEXTUREFORMAT_RED:return Cf.R16Float;case u.TEXTUREFORMAT_RG:return Cf.RG16Float;case u.TEXTUREFORMAT_RGB:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case u.TEXTUREFORMAT_RGBA:default:return Cf.RGBA16Float}case u.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case u.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:switch(t){case u.TEXTUREFORMAT_RGBA:return Cf.RG11B10UFloat;case u.TEXTUREFORMAT_RGBA_INTEGER:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV";default:return Cf.RG11B10UFloat}case u.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:switch(t){case u.TEXTUREFORMAT_RGBA:return Cf.RGB9E5UFloat;case u.TEXTUREFORMAT_RGBA_INTEGER:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV";default:return Cf.RGB9E5UFloat}case u.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:throw"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";case u.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:throw"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";case u.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:switch(t){case u.TEXTUREFORMAT_RGBA:return Cf.RGB10A2Unorm;case u.TEXTUREFORMAT_RGBA_INTEGER:return Cf.RGB10A2UINT;default:return Cf.RGB10A2Unorm}}return i?Cf.RGBA8UnormSRGB:Cf.RGBA8Unorm},e.GetNumChannelsFromWebGPUTextureFormat=function(e){switch(e){case Cf.R8Unorm:case Cf.R8Snorm:case Cf.R8Uint:case Cf.R8Sint:case Cf.BC4RUnorm:case Cf.BC4RSnorm:case Cf.R16Uint:case Cf.R16Sint:case Cf.Depth16Unorm:case Cf.R16Float:case Cf.R32Uint:case Cf.R32Sint:case Cf.R32Float:case Cf.Depth32Float:case Cf.Stencil8:case Cf.Depth24Plus:case Cf.EACR11Unorm:case Cf.EACR11Snorm:return 1;case Cf.RG8Unorm:case Cf.RG8Snorm:case Cf.RG8Uint:case Cf.RG8Sint:case Cf.Depth32FloatStencil8:case Cf.BC5RGUnorm:case Cf.BC5RGSnorm:case Cf.RG16Uint:case Cf.RG16Sint:case Cf.RG16Float:case Cf.RG32Uint:case Cf.RG32Sint:case Cf.RG32Float:case Cf.Depth24PlusStencil8:case Cf.EACRG11Unorm:case Cf.EACRG11Snorm:return 2;case Cf.RGB9E5UFloat:case Cf.RG11B10UFloat:case Cf.BC6HRGBUFloat:case Cf.BC6HRGBFloat:case Cf.ETC2RGB8Unorm:case Cf.ETC2RGB8UnormSRGB:return 3;case Cf.RGBA8Unorm:case Cf.RGBA8UnormSRGB:case Cf.RGBA8Snorm:case Cf.RGBA8Uint:case Cf.RGBA8Sint:case Cf.BGRA8Unorm:case Cf.BGRA8UnormSRGB:case Cf.RGB10A2UINT:case Cf.RGB10A2Unorm:case Cf.BC7RGBAUnorm:case Cf.BC7RGBAUnormSRGB:case Cf.BC3RGBAUnorm:case Cf.BC3RGBAUnormSRGB:case Cf.BC2RGBAUnorm:case Cf.BC2RGBAUnormSRGB:case Cf.BC1RGBAUnorm:case Cf.BC1RGBAUnormSRGB:case Cf.RGBA16Uint:case Cf.RGBA16Sint:case Cf.RGBA16Float:case Cf.RGBA32Uint:case Cf.RGBA32Sint:case Cf.RGBA32Float:case Cf.ETC2RGB8A1Unorm:case Cf.ETC2RGB8A1UnormSRGB:case Cf.ETC2RGBA8Unorm:case Cf.ETC2RGBA8UnormSRGB:case Cf.ASTC4x4Unorm:case Cf.ASTC4x4UnormSRGB:case Cf.ASTC5x4Unorm:case Cf.ASTC5x4UnormSRGB:case Cf.ASTC5x5Unorm:case Cf.ASTC5x5UnormSRGB:case Cf.ASTC6x5Unorm:case Cf.ASTC6x5UnormSRGB:case Cf.ASTC6x6Unorm:case Cf.ASTC6x6UnormSRGB:case Cf.ASTC8x5Unorm:case Cf.ASTC8x5UnormSRGB:case Cf.ASTC8x6Unorm:case Cf.ASTC8x6UnormSRGB:case Cf.ASTC8x8Unorm:case Cf.ASTC8x8UnormSRGB:case Cf.ASTC10x5Unorm:case Cf.ASTC10x5UnormSRGB:case Cf.ASTC10x6Unorm:case Cf.ASTC10x6UnormSRGB:case Cf.ASTC10x8Unorm:case Cf.ASTC10x8UnormSRGB:case Cf.ASTC10x10Unorm:case Cf.ASTC10x10UnormSRGB:case Cf.ASTC12x10Unorm:case Cf.ASTC12x10UnormSRGB:case Cf.ASTC12x12Unorm:case Cf.ASTC12x12UnormSRGB:return 4}throw"Unknown format ".concat(e,"!")},e.HasStencilAspect=function(e){switch(e){case Cf.Stencil8:case Cf.Depth32FloatStencil8:case Cf.Depth24PlusStencil8:return!0}return!1},e.HasDepthAndStencilAspects=function(e){switch(e){case Cf.Depth32FloatStencil8:case Cf.Depth24PlusStencil8:return!0}return!1},e.GetDepthFormatOnly=function(e){switch(e){case Cf.Depth16Unorm:return Cf.Depth16Unorm;case Cf.Depth24Plus:case Cf.Depth24PlusStencil8:return Cf.Depth24Plus;case Cf.Depth32Float:case Cf.Depth32FloatStencil8:return Cf.Depth32Float}return e},e.GetSample=function(e){return e>1?4:1},e}(),f_=function(){function e(e){void 0===e&&(e=null),this._originalFormatIsRGB=!1,this.format=Cf.RGBA8Unorm,this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}return Object.defineProperty(e.prototype,"underlyingResource",{get:function(){return this._webgpuTexture},enumerable:!1,configurable:!0}),e.prototype.getMSAATexture=function(e){var t,i;return void 0===e&&(e=0),null!==(i=null===(t=this._webgpuMSAATexture)||void 0===t?void 0:t[e])&&void 0!==i?i:null},e.prototype.setMSAATexture=function(e,t){void 0===t&&(t=-1),this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),-1===t&&(t=this._webgpuMSAATexture.length),this._webgpuMSAATexture[t]=e},e.prototype.releaseMSAATexture=function(){if(this._webgpuMSAATexture){for(var e=0,t=this._webgpuMSAATexture;e<t.length;e++){var i=t[e];null==i||i.destroy()}this._webgpuMSAATexture=null}},e.prototype.set=function(e){this._webgpuTexture=e},e.prototype.setUsage=function(e,t,i,r,n,o,a,s){var l=xf.E2d,c=1;r?(l=i?xf.CubeArray:xf.Cube,c=6*(s||1)):n?(l=xf.E3d,c=1):i&&(l=xf.E2dArray,c=s);var u=p_.GetDepthFormatOnly(this.format),h=p_.HasDepthAndStencilAspects(this.format)?Af.DepthOnly:Af.All;this.createView({label:"TextureView".concat(n?"3D":r?"Cube":"2D").concat(i?"_Array"+c:"","_").concat(o,"x").concat(a,"_").concat(t?"wmips":"womips","_").concat(this.format,"_").concat(l),format:u,dimension:l,mipLevelCount:t?j.ILog2(Math.max(o,a))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:c,aspect:h})},e.prototype.createView=function(e,t){if(void 0===t&&(t=!1),this.view=this._webgpuTexture.createView(e),t&&e){var i=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=i}},e.prototype.reset=function(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null},e.prototype.release=function(){var e,t;null===(e=this._webgpuTexture)||void 0===e||e.destroy(),this.releaseMSAATexture(),null===(t=this._copyInvertYTempTexture)||void 0===t||t.destroy(),this.reset()},e}(),__="\n #extension GL_EXT_samplerless_texture_functions : enable\n\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) out flat ivec2 vTextureSize;\n #endif\n\n void main() {\n #ifdef INVERTY\n vTextureSize = textureSize(img, 0);\n #endif\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",m_=__;!function(e){e[e.MipMap=0]="MipMap",e[e.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",e[e.Clear=2]="Clear",e[e.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"}(c_||(c_={})),function(e){e[e.DontInvertY=0]="DontInvertY",e[e.InvertY=1]="InvertY"}(u_||(u_={}));var g_,v_,y_=[{vertex:"\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(location = 0) out vec2 vTex;\n\n void main() {\n vTex = tex[gl_VertexIndex];\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n layout(set = 0, binding = 0) uniform sampler imgSampler;\n layout(set = 0, binding = 1) uniform texture2D img;\n\n layout(location = 0) in vec2 vTex;\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = texture(sampler2D(img, imgSampler), vTex);\n }\n "},{vertex:__,fragment:"\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n "},{vertex:"\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n\n void main() {\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n layout(set = 0, binding = 0) uniform Uniforms {\n uniform vec4 color;\n };\n\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = color;\n }\n "},{vertex:m_,fragment:"\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n layout(set = 0, binding = 1) uniform Params {\n float ofstX;\n float ofstY;\n float width;\n float height;\n };\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) {\n discard;\n }\n if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) {\n discard;\n }\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n "}],b_={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2uint:22,rgb10a2unorm:23,rg32uint:24,rg32sint:25,rg32float:26,rgba16uint:27,rgba16sint:28,rgba16float:29,rgba32uint:30,rgba32sint:31,rgba32float:32,stencil8:33,depth16unorm:34,depth24plus:35,"depth24plus-stencil8":36,depth32float:37,"depth32float-stencil8":38},T_=function(){function e(e,t,i,r,n,o){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._engine=e,this._device=t,this._glslang=i,this._tintWASM=r,this._bufferManager=n,-1!==o.indexOf(vf.RG11B10UFloatRenderable)){var a=Object.keys(b_);b_[Cf.RG11B10UFloat]=b_[a[a.length-1]]+1}this._mipmapSampler=t.createSampler({minFilter:Pf.Linear}),this._videoSampler=t.createSampler({minFilter:Pf.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(16,bf.Uniform|bf.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline(Cf.RGBA8Unorm),this._getVideoPipeline(Cf.RGBA8Unorm)}return e.prototype._getPipeline=function(e,t,i){void 0===t&&(t=c_.MipMap);var r=t===c_.MipMap?1:t===c_.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===c_.Clear?8:t===c_.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);var n=this._pipelines[e][r];if(!n){var o="#version 450\n";t!==c_.InvertYPremultiplyAlpha&&t!==c_.InvertYPremultiplyAlphaWithOfst||(i.invertY&&(o+="#define INVERTY\n"),i.premultiplyAlpha&&(o+="#define PREMULTIPLYALPHA\n"));var a=this._compiledShaders[r];if(!a){var s=this._glslang.compileGLSL(o+y_[t].vertex,"vertex"),l=this._glslang.compileGLSL(o+y_[t].fragment,"fragment");this._tintWASM&&(s=this._tintWASM.convertSpirV2WGSL(s),l=this._tintWASM.convertSpirV2WGSL(l));var c=this._device.createShaderModule({code:s}),u=this._device.createShaderModule({code:l});a=this._compiledShaders[r]=[c,u]}var h=this._device.createRenderPipeline({layout:Uf.Auto,vertex:{module:a[0],entryPoint:"main"},fragment:{module:a[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Vf.TriangleStrip,stripIndexFormat:jf.Uint16}});n=this._pipelines[e][r]=[h,h.getBindGroupLayout(0)]}return n},e.prototype._getVideoPipeline=function(e,t){void 0===t&&(t=u_.DontInvertY);var i=t===u_.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);var r=this._videoPipelines[e][i];if(!r){var n=this._videoCompiledShaders[i];if(!n){var o=this._device.createShaderModule({code:"\n struct VertexOutput {\n @builtin(position) Position : vec4<f32>,\n @location(0) fragUV : vec2<f32>\n }\n\n @vertex\n fn main(\n @builtin(vertex_index) VertexIndex : u32\n ) -> VertexOutput {\n var pos = array<vec2<f32>, 4>(\n vec2(-1.0, 1.0),\n vec2( 1.0, 1.0),\n vec2(-1.0, -1.0),\n vec2( 1.0, -1.0)\n );\n var tex = array<vec2<f32>, 4>(\n vec2(0.0, 0.0),\n vec2(1.0, 0.0),\n vec2(0.0, 1.0),\n vec2(1.0, 1.0)\n );\n\n var output: VertexOutput;\n\n output.Position = vec4<f32>(pos[VertexIndex], 0.0, 1.0);\n output.fragUV = tex[VertexIndex];\n\n return output;\n }\n "}),a=this._device.createShaderModule({code:0===i?"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2<f32>\n ) -> @location(0) vec4<f32> {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV);\n }\n ":"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2<f32>\n ) -> @location(0) vec4<f32> {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2<f32>(fragUV.x, 1.0 - fragUV.y));\n }\n "});n=this._videoCompiledShaders[i]=[o,a]}var s=this._device.createRenderPipeline({label:"BabylonWebGPUDevice".concat(this._engine.uniqueId,"_CopyVideoToTexture_").concat(e,"_").concat(0===i?"DontInvertY":"InvertY"),layout:Uf.Auto,vertex:{module:n[0],entryPoint:"main"},fragment:{module:n[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Vf.TriangleStrip,stripIndexFormat:jf.Uint16}});r=this._videoPipelines[e][i]=[s,s.getBindGroupLayout(0)]}return r},e.prototype.setCommandEncoder=function(e){this._commandEncoderForCreation=e},e.prototype.copyVideoToTexture=function(e,t,i,r,n){var o,a,s,l;void 0===r&&(r=!1);var c=void 0===n,u=this._getVideoPipeline(i,r?u_.InvertY:u_.DontInvertY),h=u[0],d=u[1];c&&(n=this._device.createCommandEncoder({})),null===(a=(o=n).pushDebugGroup)||void 0===a||a.call(o,"copy video to texture - invertY=".concat(r));var p=t._hardwareTexture,f={label:"BabylonWebGPUDevice".concat(this._engine.uniqueId,"_copyVideoToTexture_").concat(i,"_").concat(r?"InvertY":"DontInvertY").concat(t.label?"_"+t.label:""),colorAttachments:[{view:p.underlyingResource.createView({format:i,dimension:xf.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:Af.All}),loadOp:Zf.Load,storeOp:Jf.Store}]},_=n.beginRenderPass(f),m={layout:d,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},g=this._device.createBindGroup(m);_.setPipeline(h),_.setBindGroup(0,g),_.draw(4,1,0,0),_.end(),null===(l=(s=n).popDebugGroup)||void 0===l||l.call(s),c&&(this._device.queue.submit([n.finish()]),n=null)},e.prototype.invertYPreMultiplyAlpha=function(e,t,i,r,n,o,a,s,l,c,u,h,d,p,f){var _,m,g,v,y,b;void 0===n&&(n=!1),void 0===o&&(o=!1),void 0===a&&(a=0),void 0===s&&(s=0),void 0===l&&(l=1),void 0===c&&(c=0),void 0===u&&(u=0),void 0===h&&(h=0),void 0===d&&(d=0);var T,E=0!==h,S=void 0===p,x=this._getPipeline(r,E?c_.InvertYPremultiplyAlphaWithOfst:c_.InvertYPremultiplyAlpha,{invertY:n,premultiplyAlpha:o}),A=x[0],C=x[1];if(a=Math.max(a,0),S&&(p=this._device.createCommandEncoder({})),null===(m=(_=p).pushDebugGroup)||void 0===m||m.call(_,"internal process texture - invertY=".concat(n," premultiplyAlpha=").concat(o)),p_.IsHardwareTexture(e)?(T=e.underlyingResource,n&&!o&&1===l&&0===a||(e=void 0)):(T=e,e=void 0),T){E&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([c,u,h,d]),0,16);var R=e,P=null!==(g=null==R?void 0:R._copyInvertYTempTexture)&&void 0!==g?g:this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,r,1,p,Sf.CopySrc|Sf.RenderAttachment|Sf.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),I=null!==(v=null==R?void 0:R._copyInvertYRenderPassDescr)&&void 0!==v?v:{label:"BabylonWebGPUDevice".concat(this._engine.uniqueId,"_invertYPreMultiplyAlpha_").concat(r,"_").concat(n?"InvertY":"DontInvertY","_").concat(o?"PremultiplyAlpha":"DontPremultiplyAlpha"),colorAttachments:[{view:P.createView({format:r,dimension:xf.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:Zf.Load,storeOp:Jf.Store}]},M=p.beginRenderPass(I),O=E?null==R?void 0:R._copyInvertYBindGroupWithOfst:null==R?void 0:R._copyInvertYBindGroup;if(!O){var D={layout:C,entries:[{binding:0,resource:T.createView({format:r,dimension:xf.E2d,baseMipLevel:s,mipLevelCount:1,arrayLayerCount:l,baseArrayLayer:a})}]};E&&D.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),O=this._device.createBindGroup(D)}M.setPipeline(A),M.setBindGroup(0,O),M.draw(4,1,0,0),M.end(),p.copyTextureToTexture({texture:P},{texture:T,mipLevel:s,origin:{x:0,y:0,z:a}},{width:t,height:i,depthOrArrayLayers:1}),R?(R._copyInvertYTempTexture=P,R._copyInvertYRenderPassDescr=I,E?R._copyInvertYBindGroupWithOfst=O:R._copyInvertYBindGroup=O):this._deferredReleaseTextures.push([P,null]),null===(b=(y=p).popDebugGroup)||void 0===b||b.call(y),S&&(this._device.queue.submit([p.finish()]),p=null)}},e.prototype.copyWithInvertY=function(e,t,i,r){var n,o,a,s,l=void 0===r,c=this._getPipeline(t,c_.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1}),u=c[0],h=c[1];l&&(r=this._device.createCommandEncoder({})),null===(o=(n=r).pushDebugGroup)||void 0===o||o.call(n,"internal copy texture with invertY");var d=r.beginRenderPass(i),p=this._device.createBindGroup({layout:h,entries:[{binding:0,resource:e}]});d.setPipeline(u),d.setBindGroup(0,p),d.draw(4,1,0,0),d.end(),null===(s=(a=r).popDebugGroup)||void 0===s||s.call(a),l&&(this._device.queue.submit([r.finish()]),r=null)},e.prototype.createTexture=function(e,t,i,r,n,o,a,s,l,c,u,h){void 0===t&&(t=!1),void 0===i&&(i=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===o&&(o=!1),void 0===a&&(a=Cf.RGBA8Unorm),void 0===s&&(s=1),void 0===c&&(c=-1),void 0===u&&(u=0),s=p_.GetSample(s);var d=e.layers||1,p={width:e.width,height:e.height,depthOrArrayLayers:d},f=b_[a]?Sf.RenderAttachment:0,_=p_.IsCompressedFormat(a),m=t?p_.ComputeNumMipmapLevels(e.width,e.height):1,g=c>=0?c:Sf.CopySrc|Sf.CopyDst|Sf.TextureBinding;u|=t&&!_?Sf.CopySrc|f:0,_||o||(u|=f|Sf.CopyDst);var v=this._device.createTexture({label:"BabylonWebGPUDevice".concat(this._engine.uniqueId,"_Texture").concat(o?"3D":"2D","_").concat(h?h+"_":"").concat(p.width,"x").concat(p.height,"x").concat(p.depthOrArrayLayers,"_").concat(t?"wmips":"womips","_").concat(a,"_samples").concat(s),size:p,dimension:o?Ef.E3d:Ef.E2d,format:a,usage:g|u,sampleCount:s,mipLevelCount:m});return p_.IsImageBitmap(e)&&(this.updateTexture(e,v,e.width,e.height,d,a,0,0,r,n,0,0),t&&i&&this.generateMipmaps(v,a,m,0,o,l)),v},e.prototype.createCubeTexture=function(e,t,i,r,n,o,a,s,l,c,u){void 0===t&&(t=!1),void 0===i&&(i=!1),void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===o&&(o=Cf.RGBA8Unorm),void 0===a&&(a=1),void 0===l&&(l=-1),void 0===c&&(c=0),a=p_.GetSample(a);var h=p_.IsImageBitmapArray(e)?e[0].width:e.width,d=p_.IsImageBitmapArray(e)?e[0].height:e.height,p=b_[o]?Sf.RenderAttachment:0,f=p_.IsCompressedFormat(o),_=t?p_.ComputeNumMipmapLevels(h,d):1,m=l>=0?l:Sf.CopySrc|Sf.CopyDst|Sf.TextureBinding;c|=t&&!f?Sf.CopySrc|p:0,f||(c|=p|Sf.CopyDst);var g=this._device.createTexture({label:"BabylonWebGPUDevice".concat(this._engine.uniqueId,"_TextureCube_").concat(u?u+"_":"").concat(h,"x").concat(d,"x6_").concat(t?"wmips":"womips","_").concat(o,"_samples").concat(a),size:{width:h,height:d,depthOrArrayLayers:6},dimension:Ef.E2d,format:o,usage:m|c,sampleCount:a,mipLevelCount:_});return p_.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,g,h,d,o,r,n,0,0),t&&i&&this.generateCubeMipmaps(g,o,_,s)),g},e.prototype.generateCubeMipmaps=function(e,t,i,r){var n,o,a,s,l=void 0===r;l&&(r=this._device.createCommandEncoder({})),null===(o=(n=r).pushDebugGroup)||void 0===o||o.call(n,"create cube mipmaps - ".concat(i," levels"));for(var c=0;c<6;++c)this.generateMipmaps(e,t,i,c,!1,r);null===(s=(a=r).popDebugGroup)||void 0===s||s.call(a),l&&(this._device.queue.submit([r.finish()]),r=null)},e.prototype.generateMipmaps=function(e,t,i,r,n,o){var a,s,l,c,u,h,d,p;void 0===r&&(r=0),void 0===n&&(n=!1);var f,_=void 0===o,m=this._getPipeline(t),g=m[0],v=m[1];if(r=Math.max(r,0),_&&(o=this._device.createCommandEncoder({})),null===(s=(a=o).pushDebugGroup)||void 0===s||s.call(a,"create mipmaps for face #".concat(r," - ").concat(i," levels")),p_.IsHardwareTexture(e)?(f=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(f=e,e=void 0),f){for(var y=e,b=1;b<i;++b){var T=null!==(c=null===(l=null==y?void 0:y._mipmapGenRenderPassDescr[r])||void 0===l?void 0:l[b-1])&&void 0!==c?c:{label:"BabylonWebGPUDevice".concat(this._engine.uniqueId,"_generateMipmaps_").concat(t,"_faceIndex").concat(r,"_level").concat(b),colorAttachments:[{view:f.createView({format:t,dimension:n?xf.E3d:xf.E2d,baseMipLevel:b,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:r}),loadOp:Zf.Load,storeOp:Jf.Store}]};y&&(y._mipmapGenRenderPassDescr[r]=y._mipmapGenRenderPassDescr[r]||[],y._mipmapGenRenderPassDescr[r][b-1]=T);var E=o.beginRenderPass(T),S=null!==(h=null===(u=null==y?void 0:y._mipmapGenBindGroup[r])||void 0===u?void 0:u[b-1])&&void 0!==h?h:this._device.createBindGroup({layout:v,entries:[{binding:0,resource:this._mipmapSampler},{binding:1,resource:f.createView({format:t,dimension:n?xf.E3d:xf.E2d,baseMipLevel:b-1,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:r})}]});y&&(y._mipmapGenBindGroup[r]=y._mipmapGenBindGroup[r]||[],y._mipmapGenBindGroup[r][b-1]=S),E.setPipeline(g),E.setBindGroup(0,S),E.draw(4,1,0,0),E.end()}null===(p=(d=o).popDebugGroup)||void 0===p||p.call(d),_&&(this._device.queue.submit([o.finish()]),o=null)}},e.prototype.createGPUTextureForInternalTexture=function(e,t,i,r,n){var o,a;e._hardwareTexture||(e._hardwareTexture=new f_),void 0===t&&(t=e.width),void 0===i&&(i=e.height),void 0===r&&(r=e.depth);var s=e._hardwareTexture,l=!!((null!=n?n:0)&u.TEXTURE_CREATIONFLAG_STORAGE);s.format=p_.GetWebGPUTextureFormat(e.type,e.format,e._useSRGBBuffer),s.textureUsages=e._source===Ti.RenderTarget||e.source===Ti.MultiRenderTarget?Sf.TextureBinding|Sf.CopySrc|Sf.RenderAttachment:e._source===Ti.DepthStencil?Sf.TextureBinding|Sf.RenderAttachment:-1,s.textureAdditionalUsages=l?Sf.StorageBinding:0;var c,h=e.generateMipMaps,d=r||1;if(c=null!==e._maxLodLevel?e._maxLodLevel:h?p_.ComputeNumMipmapLevels(t,i):1,e.isCube){var p=this.createCubeTexture({width:t,height:i},e.generateMipMaps,e.generateMipMaps,e.invertY,!1,s.format,1,this._commandEncoderForCreation,s.textureUsages,s.textureAdditionalUsages,e.label);s.set(p);var f=e.is3D?1:d,_=p_.GetDepthFormatOnly(s.format),m=p_.HasDepthAndStencilAspects(s.format)?Af.DepthOnly:Af.All,g=e.is2DArray?xf.CubeArray:xf.Cube;s.createView({label:"BabylonWebGPUDevice".concat(this._engine.uniqueId,"_TextureViewCube").concat(e.is2DArray?"_Array"+f:"","_").concat(t,"x").concat(i,"_").concat(h?"wmips":"womips","_").concat(_,"_").concat(g,"_").concat(m,"_").concat(null!==(o=e.label)&&void 0!==o?o:"noname"),format:_,dimension:g,mipLevelCount:c,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:6,aspect:m},l)}else p=this.createTexture({width:t,height:i,layers:d},e.generateMipMaps,e.generateMipMaps,e.invertY,!1,e.is3D,s.format,1,this._commandEncoderForCreation,s.textureUsages,s.textureAdditionalUsages,e.label),s.set(p),f=e.is3D?1:d,_=p_.GetDepthFormatOnly(s.format),m=p_.HasDepthAndStencilAspects(s.format)?Af.DepthOnly:Af.All,g=e.is2DArray?xf.E2dArray:e.is3D?Ef.E3d:xf.E2d,s.createView({label:"BabylonWebGPUDevice".concat(this._engine.uniqueId,"_TextureView").concat(e.is3D?"3D":"2D").concat(e.is2DArray?"_Array"+f:"","_").concat(t,"x").concat(i).concat(e.is3D?"x"+d:"","_").concat(h?"wmips":"womips","_").concat(_,"_").concat(g,"_").concat(m,"_").concat(null!==(a=e.label)&&void 0!==a?a:"noname"),format:_,dimension:g,mipLevelCount:c,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:f,aspect:m},l);return e.width=e.baseWidth=t,e.height=e.baseHeight=i,e.depth=e.baseDepth=r,this.createMSAATexture(e,e.samples),s},e.prototype.createMSAATexture=function(e,t,i,r){void 0===i&&(i=!0),void 0===r&&(r=-1);var n=e._hardwareTexture;if(i&&(null==n||n.releaseMSAATexture()),n&&!((null!=t?t:1)<=1)){var o=e.width,a=e.height,s=this.createTexture({width:o,height:a,layers:1},!1,!1,!1,!1,!1,n.format,t,this._commandEncoderForCreation,Sf.RenderAttachment,0,e.label?"MSAA"+e.label:void 0);n.setMSAATexture(s,r)}},e.prototype.updateCubeTextures=function(e,t,i,r,n,o,a,s,l){void 0===o&&(o=!1),void 0===a&&(a=!1),void 0===s&&(s=0),void 0===l&&(l=0);for(var c=[0,3,1,4,2,5],u=0;u<c.length;++u){var h=e[c[u]];this.updateTexture(h,t,i,r,1,n,u,0,o,a,s,l)}},e.prototype.updateTexture=function(e,t,i,r,n,o,a,s,l,c,u,h,d){void 0===a&&(a=0),void 0===s&&(s=0),void 0===l&&(l=!1),void 0===c&&(c=!1),void 0===u&&(u=0),void 0===h&&(h=0);var p=p_.IsInternalTexture(t)?t._hardwareTexture.underlyingResource:t,f=p_.GetBlockInformationFromFormat(o),_=p_.IsInternalTexture(t)?t._hardwareTexture:t,m={texture:p,origin:{x:u,y:h,z:Math.max(a,0)},mipLevel:s,premultipliedAlpha:c},g={width:Math.ceil(i/f.width)*f.width,height:Math.ceil(r/f.height)*f.height,depthOrArrayLayers:n||1};if(void 0!==e.byteLength){var v=Math.ceil(i/f.width)*f.length;if(256*Math.ceil(v/256)===v){var y=this._device.createCommandEncoder({}),b=this._bufferManager.createRawBuffer(e.byteLength,bf.MapWrite|bf.CopySrc,!0,"TempBufferForUpdateTexture"+(p?"_"+p.label:"")),T=b.getMappedRange();new Uint8Array(T).set(e),b.unmap(),y.copyBufferToTexture({buffer:b,offset:0,bytesPerRow:v,rowsPerImage:r},m,g),this._device.queue.submit([y.finish()]),this._bufferManager.releaseBuffer(b)}else this._device.queue.writeTexture(m,e,{offset:0,bytesPerRow:v,rowsPerImage:r},g);if(l||c){if(!p_.IsInternalTexture(t))throw"updateTexture: Can't process the texture data because a GPUTexture was provided instead of an InternalTexture!";var E=0===u&&0===h&&i===t.width&&r===t.height;this.invertYPreMultiplyAlpha(_,t.width,t.height,o,l,c,a,s,n||1,u,h,E?0:i,E?0:r,void 0,d)}}else if(l)if(m.premultipliedAlpha=!1,p_.IsInternalTexture(t)&&0===u&&0===h&&i===t.width&&r===t.height)this._device.queue.copyExternalImageToTexture({source:e},m,g),this.invertYPreMultiplyAlpha(_,i,r,o,l,c,a,s,n||1,0,0,0,0,void 0,d);else{y=this._device.createCommandEncoder({});var S=this.createTexture({width:i,height:r,layers:1},!1,!1,!1,!1,!1,o,1,y,Sf.CopySrc|Sf.TextureBinding,void 0,"TempTextureForUpdateTexture");this._deferredReleaseTextures.push([S,null]),g.depthOrArrayLayers=1,this._device.queue.copyExternalImageToTexture({source:e},{texture:S},g),g.depthOrArrayLayers=n||1,this.invertYPreMultiplyAlpha(S,i,r,o,l,c,a,s,n||1,0,0,0,0,y,d),y.copyTextureToTexture({texture:S},m,g),this._device.queue.submit([y.finish()])}else this._device.queue.copyExternalImageToTexture({source:e},m,g)},e.prototype.readPixels=function(e,t,i,r,n,o,a,s,l,c){void 0===a&&(a=0),void 0===s&&(s=0),void 0===l&&(l=null),void 0===c&&(c=!1);var u=p_.GetBlockInformationFromFormat(o),h=Math.ceil(r/u.width)*u.length,d=256*Math.ceil(h/256),p=d*n,f=this._bufferManager.createRawBuffer(p,bf.MapRead|bf.CopyDst,void 0,"TempBufferForReadPixels"+(e.label?"_"+e.label:"")),_=this._device.createCommandEncoder({});return _.copyTextureToBuffer({texture:e,mipLevel:s,origin:{x:t,y:i,z:Math.max(a,0)}},{buffer:f,offset:0,bytesPerRow:d},{width:r,height:n,depthOrArrayLayers:1}),this._device.queue.submit([_.finish()]),this._bufferManager.readDataFromBuffer(f,p,r,n,h,d,p_.GetTextureTypeFromFormat(o),0,l,!0,c)},e.prototype.releaseTexture=function(e){if(p_.IsInternalTexture(e)){var t=e._hardwareTexture,i=e._irradianceTexture;this._deferredReleaseTextures.push([t,i])}else this._deferredReleaseTextures.push([e,null])},e.prototype.destroyDeferredTextures=function(){for(var e=0;e<this._deferredReleaseTextures.length;++e){var t=this._deferredReleaseTextures[e],i=t[0],r=t[1];i&&(p_.IsHardwareTexture(i)?i.release():i.destroy()),null==r||r.dispose()}this._deferredReleaseTextures.length=0},e}(),E_=function(e){function t(t,i){void 0===i&&(i=0);var r=e.call(this)||this;return r.engineId=-1,r.capacity=i,r._buffer=t,r}return m(t,e),Object.defineProperty(t.prototype,"underlyingResource",{get:function(){return this._buffer},enumerable:!1,configurable:!0}),t}(vr),S_=function(){function e(e,t){this._deferredReleaseBuffers=[],this._engine=e,this._device=t}return e._IsGPUBuffer=function(e){return void 0===e.underlyingResource},e._FlagsToString=function(e,t){void 0===t&&(t="");for(var i=t,r=0;r<=9;++r)e&1<<r&&(i&&(i+="_"),i+=bf[1<<r]);return i},e.prototype.createRawBuffer=function(t,i,r,n){void 0===r&&(r=!1);var o=void 0!==t.byteLength?t.byteLength+3&-4:t+3&-4,a={label:"BabylonWebGPUDevice"+this._engine.uniqueId+"_"+e._FlagsToString(i,null!=n?n:"Buffer")+"_size"+o,mappedAtCreation:r,size:o,usage:i};return this._device.createBuffer(a)},e.prototype.createBuffer=function(e,t,i){var r=void 0!==e.byteLength,n=this.createRawBuffer(e,t,void 0,i),o=new E_(n);return o.references=1,o.capacity=r?e.byteLength:e,o.engineId=this._engine.uniqueId,r&&this.setSubData(o,0,e),o},e.prototype.setRawData=function(e,t,i,r,n){this._device.queue.writeBuffer(e,t,i.buffer,r,n)},e.prototype.setSubData=function(e,t,i,r,n){void 0===r&&(r=0),void 0===n&&(n=0);var o=e.underlyingResource;n=n||i.byteLength,n=Math.min(n,e.capacity-t);var a=i.byteOffset+r,s=a+n,l=n+3&-4;if(l!==n){var c=new Uint8Array(i.buffer.slice(a,s));(i=new Uint8Array(l)).set(c),r=0,a=0,s=l,n=l}for(var u=15728640,h=0;s-(a+h)>u;)this._device.queue.writeBuffer(o,t+h,i.buffer,a+h,u),h+=u;this._device.queue.writeBuffer(o,t+h,i.buffer,a+h,n-h)},e.prototype._getHalfFloatAsFloatRGBAArrayBuffer=function(e,t,i){i||(i=new Float32Array(e));for(var r=new Uint16Array(t);e--;)i[e]=Ip(r[e]);return i},e.prototype.readDataFromBuffer=function(e,t,i,r,n,o,a,s,l,c,h){var d=this;void 0===a&&(a=u.TEXTURETYPE_UNSIGNED_BYTE),void 0===s&&(s=0),void 0===l&&(l=null),void 0===c&&(c=!0),void 0===h&&(h=!1);var p=a===u.TEXTURETYPE_FLOAT?2:a===u.TEXTURETYPE_HALF_FLOAT?1:0,f=this._engine.uniqueId;return new Promise((function(i,u){e.mapAsync(Tf.Read,s,t).then((function(){var u=e.getMappedRange(s,t),f=l;if(h)f=null===f?To(a,t,!0,u):To(a,f.buffer,void 0,u);else if(null===f)switch(p){case 0:(f=new Uint8Array(t)).set(new Uint8Array(u));break;case 1:f=d._getHalfFloatAsFloatRGBAArrayBuffer(t/2,u);break;case 2:(f=new Float32Array(t/4)).set(new Float32Array(u))}else switch(p){case 0:(f=new Uint8Array(f.buffer)).set(new Uint8Array(u));break;case 1:f=d._getHalfFloatAsFloatRGBAArrayBuffer(t/2,u,l);break;case 2:(f=new Float32Array(f.buffer)).set(new Float32Array(u))}if(n!==o){1!==p||h||(n*=2,o*=2);for(var _=new Uint8Array(f.buffer),m=n,g=0,v=1;v<r;++v){g=v*o;for(var y=0;y<n;++y)_[m++]=_[g++]}f=0===p||h?new Uint8Array(_.buffer,0,m):new Float32Array(_.buffer,0,m/4)}e.unmap(),c&&d.releaseBuffer(e),i(f)}),(function(e){d._engine.isDisposed||d._engine.uniqueId!==f?i(new Uint8Array):u(e)}))}))},e.prototype.releaseBuffer=function(t){return e._IsGPUBuffer(t)?(this._deferredReleaseBuffers.push(t),!0):(t.references--,0===t.references&&(this._deferredReleaseBuffers.push(t.underlyingResource),!0))},e.prototype.destroyDeferredBuffers=function(){for(var e=0;e<this._deferredReleaseBuffers.length;++e)this._deferredReleaseBuffers[e].destroy();this._deferredReleaseBuffers.length=0},e}(),x_=[0,0,3,7,0,2,6,2,4,1,5,3,1],A_=[0,64,32,96,16,80,48,112,8],C_=[0,128,128,0,0,0,0,128,0,0,0,0,128],R_=function(){function e(e){this._samplers={},this._device=e,this.disabled=!1}return e.GetSamplerHashCode=function(e){var t,i,r,n=e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1;return x_[e.samplingMode]+A_[(e._comparisonFunction||514)-512+1]+C_[e.samplingMode]+((null!==(t=e._cachedWrapU)&&void 0!==t?t:1)<<8)+((null!==(i=e._cachedWrapV)&&void 0!==i?i:1)<<10)+((null!==(r=e._cachedWrapR)&&void 0!==r?r:1)<<12)+((e.useMipMaps?1:0)<<14)+(n<<15)},e._GetSamplerFilterDescriptor=function(e,t){var i,r,n,o,a,s=e.useMipMaps;switch(e.samplingMode){case u.TEXTURE_LINEAR_LINEAR_MIPNEAREST:i=Pf.Linear,r=Pf.Linear,n=Pf.Nearest,s||(o=a=0);break;case u.TEXTURE_LINEAR_LINEAR_MIPLINEAR:case u.TEXTURE_TRILINEAR_SAMPLINGMODE:i=Pf.Linear,r=Pf.Linear,s?n=Pf.Linear:(n=Pf.Nearest,o=a=0);break;case u.TEXTURE_NEAREST_NEAREST_MIPLINEAR:i=Pf.Nearest,r=Pf.Nearest,s?n=Pf.Linear:(n=Pf.Nearest,o=a=0);break;case u.TEXTURE_NEAREST_NEAREST_MIPNEAREST:i=Pf.Nearest,r=Pf.Nearest,n=Pf.Nearest,s||(o=a=0);break;case u.TEXTURE_NEAREST_LINEAR_MIPNEAREST:i=Pf.Nearest,r=Pf.Linear,n=Pf.Nearest,s||(o=a=0);break;case u.TEXTURE_NEAREST_LINEAR_MIPLINEAR:i=Pf.Nearest,r=Pf.Linear,s?n=Pf.Linear:(n=Pf.Nearest,o=a=0);break;case u.TEXTURE_NEAREST_LINEAR:i=Pf.Nearest,r=Pf.Linear,n=Pf.Nearest,o=a=0;break;case u.TEXTURE_NEAREST_NEAREST:case u.TEXTURE_NEAREST_SAMPLINGMODE:i=Pf.Nearest,r=Pf.Nearest,n=Pf.Nearest,o=a=0;break;case u.TEXTURE_LINEAR_NEAREST_MIPNEAREST:i=Pf.Linear,r=Pf.Nearest,n=Pf.Nearest,s||(o=a=0);break;case u.TEXTURE_LINEAR_NEAREST_MIPLINEAR:i=Pf.Linear,r=Pf.Nearest,s?n=Pf.Linear:(n=Pf.Nearest,o=a=0);break;case u.TEXTURE_LINEAR_LINEAR:case u.TEXTURE_BILINEAR_SAMPLINGMODE:i=Pf.Linear,r=Pf.Linear,n=Pf.Nearest,o=a=0;break;case u.TEXTURE_LINEAR_NEAREST:i=Pf.Linear,r=Pf.Nearest,n=Pf.Nearest,o=a=0;break;default:i=Pf.Nearest,r=Pf.Nearest,n=Pf.Nearest,o=a=0}return t>1&&(0!==o||0!==a)&&n!==Pf.Nearest?{magFilter:Pf.Linear,minFilter:Pf.Linear,mipmapFilter:Pf.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:r,mipmapFilter:n,lodMinClamp:o,lodMaxClamp:a}},e._GetWrappingMode=function(e){switch(e){case u.TEXTURE_WRAP_ADDRESSMODE:return Rf.Repeat;case u.TEXTURE_CLAMP_ADDRESSMODE:return Rf.ClampToEdge;case u.TEXTURE_MIRROR_ADDRESSMODE:return Rf.MirrorRepeat}return Rf.Repeat},e._GetSamplerWrappingDescriptor=function(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}},e._GetSamplerDescriptor=function(t,i){var r=t.useMipMaps&&t._cachedAnisotropicFilteringLevel&&t._cachedAnisotropicFilteringLevel>1?4:1,n=this._GetSamplerFilterDescriptor(t,r);return g(g(g({label:i},n),this._GetSamplerWrappingDescriptor(t)),{compare:t._comparisonFunction?e.GetCompareFunction(t._comparisonFunction):void 0,maxAnisotropy:n.anisotropyEnabled?r:1})},e.GetCompareFunction=function(e){switch(e){case u.ALWAYS:return Mf.Always;case u.EQUAL:return Mf.Equal;case u.GREATER:return Mf.Greater;case u.GEQUAL:return Mf.GreaterEqual;case u.LESS:return Mf.Less;case u.LEQUAL:return Mf.LessEqual;case u.NEVER:return Mf.Never;case u.NOTEQUAL:return Mf.NotEqual;default:return Mf.Less}},e.prototype.getSampler=function(t,i,r,n){if(void 0===i&&(i=!1),void 0===r&&(r=0),this.disabled)return this._device.createSampler(e._GetSamplerDescriptor(t,n));i?r=0:0===r&&(r=e.GetSamplerHashCode(t));var o=i?void 0:this._samplers[r];return o||(o=this._device.createSampler(e._GetSamplerDescriptor(t,n)),i||(this._samplers[r]=o)),o},e}();!function(e){e[e.StencilReadMask=0]="StencilReadMask",e[e.StencilWriteMask=1]="StencilWriteMask",e[e.DepthBias=2]="DepthBias",e[e.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",e[e.DepthStencilState=4]="DepthStencilState",e[e.MRTAttachments1=5]="MRTAttachments1",e[e.MRTAttachments2=6]="MRTAttachments2",e[e.RasterizationState=7]="RasterizationState",e[e.ColorStates=8]="ColorStates",e[e.ShaderStage=9]="ShaderStage",e[e.TextureStage=10]="TextureStage",e[e.VertexState=11]="VertexState",e[e.NumStates=12]="NumStates"}(v_||(v_={}));var P_={0:1,1:2,768:3,769:4,770:5,771:6,772:7,773:8,774:9,775:10,776:11,32769:12,32770:13,32771:12,32772:13},I_={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7},M_=((g_={})[Nr.PositionKind]=!0,g_[Nr.NormalKind]=!0,g_[Nr.TangentKind]=!0,g_[Nr.UVKind]=!0,g_[Nr.UV2Kind]=!0,g_[Nr.UV3Kind]=!0,g_[Nr.UV4Kind]=!0,g_[Nr.UV5Kind]=!0,g_[Nr.UV6Kind]=!0,g_[Nr.ColorKind]=!0,g_[Nr.ColorInstanceKind]=!0,g_[Nr.MatricesIndicesKind]=!0,g_[Nr.MatricesWeightsKind]=!0,g_[Nr.MatricesIndicesExtraKind]=!0,g_[Nr.MatricesWeightsExtraKind]=!0,g_),O_=function(){function e(e,t){this.mrtTextureCount=0,this._device=e,this._useTextureStage=!0,this._states=new Array(30),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=t,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=e.limits.maxVertexBufferArrayStride||2048,this.reset()}return e._IsSignedType=function(e){switch(e){case Nr.BYTE:case Nr.SHORT:case Nr.INT:case Nr.FLOAT:return!0;case Nr.UNSIGNED_BYTE:case Nr.UNSIGNED_SHORT:case Nr.UNSIGNED_INT:return!1;default:throw new Error("Invalid type '".concat(e,"'"))}},e.prototype.reset=function(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=[Cf.BGRA8Unorm],this.setColorFormat(Cf.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(Cf.Depth24PlusStencil8),this.setStencilEnabled(!1),this.resetStencilState(),this.setBuffers(null,null,null),this._setTextureState(0)},Object.defineProperty(e.prototype,"colorFormats",{get:function(){return this._mrtAttachments1>0?this._mrtFormats:this._webgpuColorFormat},enumerable:!1,configurable:!0}),e.prototype.getRenderPipeline=function(t,i,r,n){if(void 0===n&&(n=0),r=p_.GetSample(r),this.disabled){var o=e._GetTopology(t);return this._setVertexState(i),this._setTextureState(n),this._parameter.pipeline=this._createRenderPipeline(i,o,r),e.NumCacheMiss++,e._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(i.uniqueId),this._setRasterizationState(t,r),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(i),this._setTextureState(n),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,e.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return e.NumCacheHitWithHash++,this._parameter.pipeline;var a=e._GetTopology(t);return this._parameter.pipeline=this._createRenderPipeline(i,a,r),this._setRenderPipeline(this._parameter),e.NumCacheMiss++,e._NumPipelineCreationCurrentFrame++,this._parameter.pipeline},e.prototype.endFrame=function(){e.NumPipelineCreationLastFrame=e._NumPipelineCreationCurrentFrame,e._NumPipelineCreationCurrentFrame=0},e.prototype.setAlphaToCoverage=function(e){this._alphaToCoverageEnabled=e},e.prototype.setFrontFace=function(e){this._frontFace=e},e.prototype.setCullEnabled=function(e){this._cullEnabled=e},e.prototype.setCullFace=function(e){this._cullFace=e},e.prototype.setClampDepth=function(e){this._clampDepth=e},e.prototype.resetDepthCullingState=function(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,u.ALWAYS)},e.prototype.setDepthCullingState=function(e,t,i,r,n,o,a,s){this._depthWriteEnabled=a,this._depthTestEnabled=o,this._depthCompare=(null!=s?s:u.ALWAYS)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(r),this.setDepthBias(n)},e.prototype.setDepthBias=function(e){this._depthBias!==e&&(this._depthBias=e,this._states[v_.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,v_.DepthBias))},e.prototype.setDepthBiasSlopeScale=function(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[v_.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,v_.DepthBiasSlopeScale))},e.prototype.setColorFormat=function(e){this._webgpuColorFormat[0]=e,this._colorFormat=b_[null!=e?e:""]},e.prototype.setMRTAttachments=function(e){this.mrtAttachments=e;for(var t=0,i=0;i<e.length;++i)0!==e[i]&&(t+=1<<i);this._mrtEnabledMask!==t&&(this._mrtEnabledMask=t,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,v_.MRTAttachments1))},e.prototype.setMRT=function(e,t){var i,r;if((t=null!=t?t:e.length)>10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;for(var n=[0,0],o=0,a=0,s=0,l=0;l<t;++l){var c=e[l],u=null==c?void 0:c._hardwareTexture;this._mrtFormats[s]=null!==(i=null==u?void 0:u.format)&&void 0!==i?i:this._webgpuColorFormat[0],n[o]+=b_[null!==(r=this._mrtFormats[s])&&void 0!==r?r:""]<<a,s++,(a+=6)>=32&&(a=0,o++)}this._mrtFormats.length=s,this._mrtAttachments1===n[0]&&this._mrtAttachments2===n[1]||(this._mrtAttachments1=n[0],this._mrtAttachments2=n[1],this._states[v_.MRTAttachments1]=n[0],this._states[v_.MRTAttachments2]=n[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,v_.MRTAttachments1))},e.prototype.setAlphaBlendEnabled=function(e){this._alphaBlendEnabled=e},e.prototype.setAlphaBlendFactors=function(e,t){this._alphaBlendFuncParams=e,this._alphaBlendEqParams=t},e.prototype.setWriteMask=function(e){this._writeMask=e},e.prototype.setDepthStencilFormat=function(e){this._webgpuDepthStencilFormat=e,this._depthStencilFormat=void 0===e?0:b_[e]},e.prototype.setDepthTestEnabled=function(e){this._depthTestEnabled=e},e.prototype.setDepthWriteEnabled=function(e){this._depthWriteEnabled=e},e.prototype.setDepthCompare=function(e){this._depthCompare=(null!=e?e:u.ALWAYS)-512},e.prototype.setStencilEnabled=function(e){this._stencilEnabled=e},e.prototype.setStencilCompare=function(e){this._stencilFrontCompare=(null!=e?e:u.ALWAYS)-512},e.prototype.setStencilDepthFailOp=function(e){this._stencilFrontDepthFailOp=null===e?1:I_[e]},e.prototype.setStencilPassOp=function(e){this._stencilFrontPassOp=null===e?2:I_[e]},e.prototype.setStencilFailOp=function(e){this._stencilFrontFailOp=null===e?1:I_[e]},e.prototype.setStencilReadMask=function(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[v_.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,v_.StencilReadMask))},e.prototype.setStencilWriteMask=function(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[v_.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,v_.StencilWriteMask))},e.prototype.resetStencilState=function(){this.setStencilState(!1,u.ALWAYS,u.KEEP,u.REPLACE,u.KEEP,255,255)},e.prototype.setStencilState=function(e,t,i,r,n,o,a){this._stencilEnabled=e,this._stencilFrontCompare=(null!=t?t:u.ALWAYS)-512,this._stencilFrontDepthFailOp=null===i?1:I_[i],this._stencilFrontPassOp=null===r?2:I_[r],this._stencilFrontFailOp=null===n?1:I_[n],this.setStencilReadMask(o),this.setStencilWriteMask(a)},e.prototype.setBuffers=function(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t},e._GetTopology=function(e){switch(e){case u.MATERIAL_TriangleFillMode:return Vf.TriangleList;case u.MATERIAL_PointFillMode:return Vf.PointList;case u.MATERIAL_WireFrameFillMode:return Vf.LineList;case u.MATERIAL_PointListDrawMode:return Vf.PointList;case u.MATERIAL_LineListDrawMode:return Vf.LineList;case u.MATERIAL_LineLoopDrawMode:throw"LineLoop is an unsupported fillmode in WebGPU";case u.MATERIAL_LineStripDrawMode:return Vf.LineStrip;case u.MATERIAL_TriangleStripDrawMode:return Vf.TriangleStrip;case u.MATERIAL_TriangleFanDrawMode:throw"TriangleFan is an unsupported fillmode in WebGPU";default:return Vf.TriangleList}},e._GetAphaBlendOperation=function(e){switch(e){case u.GL_ALPHA_EQUATION_ADD:return Hf.Add;case u.GL_ALPHA_EQUATION_SUBTRACT:return Hf.Subtract;case u.GL_ALPHA_EQUATION_REVERSE_SUBTRACT:return Hf.ReverseSubtract;case u.GL_ALPHA_EQUATION_MIN:return Hf.Min;case u.GL_ALPHA_EQUATION_MAX:return Hf.Max;default:return Hf.Add}},e._GetAphaBlendFactor=function(e){switch(e){case 0:return Wf.Zero;case 1:return Wf.One;case u.GL_ALPHA_FUNCTION_SRC:return Wf.Src;case u.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR:return Wf.OneMinusSrc;case u.GL_ALPHA_FUNCTION_SRC_ALPHA:return Wf.SrcAlpha;case u.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA:return Wf.OneMinusSrcAlpha;case u.GL_ALPHA_FUNCTION_DST_ALPHA:return Wf.DstAlpha;case u.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA:return Wf.OneMinusDstAlpha;case u.GL_ALPHA_FUNCTION_DST_COLOR:return Wf.Dst;case u.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR:return Wf.OneMinusDst;case u.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED:return Wf.SrcAlphaSaturated;case u.GL_ALPHA_FUNCTION_CONSTANT_COLOR:return Wf.Constant;case u.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR:return Wf.OneMinusConstant;case u.GL_ALPHA_FUNCTION_CONSTANT_ALPHA:return Wf.Constant;case u.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA:return Wf.OneMinusConstant;default:return Wf.One}},e._GetCompareFunction=function(e){switch(e){case 0:return Mf.Never;case 1:return Mf.Less;case 2:return Mf.Equal;case 3:return Mf.LessEqual;case 4:return Mf.Greater;case 5:return Mf.NotEqual;case 6:return Mf.GreaterEqual;case 7:return Mf.Always}return Mf.Never},e._GetStencilOpFunction=function(e){switch(e){case 0:return Xf.Zero;case 1:return Xf.Keep;case 2:return Xf.Replace;case 3:return Xf.IncrementClamp;case 4:return Xf.DecrementClamp;case 5:return Xf.Invert;case 6:return Xf.IncrementWrap;case 7:return Xf.DecrementWrap}return Xf.Keep},e._GetVertexInputDescriptorFormat=function(e){var t=e.type,i=e.normalized,r=e.getSize();switch(t){case Nr.BYTE:switch(r){case 1:case 2:return i?Yf.Snorm8x2:Yf.Sint8x2;case 3:case 4:return i?Yf.Snorm8x4:Yf.Sint8x4}break;case Nr.UNSIGNED_BYTE:switch(r){case 1:case 2:return i?Yf.Unorm8x2:Yf.Uint8x2;case 3:case 4:return i?Yf.Unorm8x4:Yf.Uint8x4}break;case Nr.SHORT:switch(r){case 1:case 2:return i?Yf.Snorm16x2:Yf.Sint16x2;case 3:case 4:return i?Yf.Snorm16x4:Yf.Sint16x4}break;case Nr.UNSIGNED_SHORT:switch(r){case 1:case 2:return i?Yf.Unorm16x2:Yf.Uint16x2;case 3:case 4:return i?Yf.Unorm16x4:Yf.Uint16x4}break;case Nr.INT:switch(r){case 1:return Yf.Sint32;case 2:return Yf.Sint32x2;case 3:return Yf.Sint32x3;case 4:return Yf.Sint32x4}break;case Nr.UNSIGNED_INT:switch(r){case 1:return Yf.Uint32;case 2:return Yf.Uint32x2;case 3:return Yf.Uint32x3;case 4:return Yf.Uint32x4}break;case Nr.FLOAT:switch(r){case 1:return Yf.Float32;case 2:return Yf.Float32x2;case 3:return Yf.Float32x3;case 4:return Yf.Float32x4}}throw new Error("Invalid Format '".concat(e.getKind(),"' - type=").concat(t,", normalized=").concat(i,", size=").concat(r))},e.prototype._getAphaBlendState=function(){return this._alphaBlendEnabled?{srcFactor:e._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:e._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:e._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null},e.prototype._getColorBlendState=function(){return this._alphaBlendEnabled?{srcFactor:e._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:e._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:e._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null},e.prototype._setShaderStage=function(e){this._shaderId!==e&&(this._shaderId=e,this._states[v_.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,v_.ShaderStage))},e.prototype._setRasterizationState=function(e,t){var i=this._frontFace-1+((this._cullEnabled?this._cullFace:0)<<1)+((this._clampDepth?1:0)<<3)+((this._alphaToCoverageEnabled?1:0)<<4)+(e<<5)+(t<<8);this._rasterizationState!==i&&(this._rasterizationState=i,this._states[v_.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,v_.RasterizationState))},e.prototype._setColorStates=function(){var e=((this._writeMask?1:0)<<22)+(this._colorFormat<<23)+((this._depthWriteEnabled?1:0)<<29);this._alphaBlendEnabled&&(e+=(0|(null===this._alphaBlendFuncParams[0]?2:P_[this._alphaBlendFuncParams[0]]))+((null===this._alphaBlendFuncParams[1]?2:P_[this._alphaBlendFuncParams[1]])<<4)+((null===this._alphaBlendFuncParams[2]?2:P_[this._alphaBlendFuncParams[2]])<<8)+((null===this._alphaBlendFuncParams[3]?2:P_[this._alphaBlendFuncParams[3]])<<12)+((null===this._alphaBlendEqParams[0]?1:this._alphaBlendEqParams[0]-32773)<<16)+((null===this._alphaBlendEqParams[1]?1:this._alphaBlendEqParams[1]-32773)<<19)),e!==this._colorStates&&(this._colorStates=e,this._states[v_.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,v_.ColorStates))},e.prototype._setDepthStencilState=function(){var e=this._stencilEnabled?this._stencilFrontCompare+(this._stencilFrontDepthFailOp<<3)+(this._stencilFrontPassOp<<6)+(this._stencilFrontFailOp<<9):591,t=this._depthStencilFormat+((this._depthTestEnabled?this._depthCompare:7)<<6)+(e<<10);this._depthStencilState!==t&&(this._depthStencilState=t,this._states[v_.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,v_.DepthStencilState))},e.prototype._setVertexState=function(e){for(var t,i,r,n=this._statesLength,o=v_.VertexState,a=e._pipelineContext,s=a.shaderProcessingContext.attributeNamesFromEffect,l=a.shaderProcessingContext.attributeLocationsFromEffect,c=0,u=0;u<s.length;u++){var h=l[u],d=null!==(t=this._overrideVertexBuffers&&this._overrideVertexBuffers[s[u]])&&void 0!==t?t:this._vertexBuffers[s[u]];d||(d=this._emptyVertexBuffer);var p=null===(i=d.effectiveBuffer)||void 0===i?void 0:i.underlyingResource;if(void 0===d._validOffsetRange){var f=d.effectiveByteOffset,_=d.getSize(!0),m=d.effectiveByteStride;d._validOffsetRange=f+_<=this._kMaxVertexBufferStride&&0===m||0!==m&&f+_<=m}r&&r===p&&d._validOffsetRange||(this.vertexBuffers[c++]=d,r=d._validOffsetRange?p:null);var g=d.hashCode+(h<<7);this._isDirty=this._isDirty||this._states[o]!==g,this._states[o++]=g}this.vertexBuffers.length=c,this._statesLength=o,this._isDirty=this._isDirty||o!==n,this._isDirty&&(this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,v_.VertexState))},e.prototype._setTextureState=function(e){this._textureState!==e&&(this._textureState=e,this._states[v_.TextureStage]=this._textureState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,v_.TextureStage))},e.prototype._createPipelineLayout=function(e){if(this._useTextureStage)return this._createPipelineLayoutWithTextureStage(e);for(var t=[],i=e.shaderProcessingContext.bindGroupLayoutEntries,r=0;r<i.length;r++){var n=i[r];t[r]=this._device.createBindGroupLayout({entries:n})}return e.bindGroupLayouts[0]=t,this._device.createPipelineLayout({bindGroupLayouts:t})},e.prototype._createPipelineLayoutWithTextureStage=function(e){for(var t,i=e.shaderProcessingContext,r=i.bindGroupLayoutEntries,n=1,o=0;o<r.length;o++)for(var a=r[o],s=0;s<a.length;s++){var l=r[o][s];if(l.texture){var c=i.bindGroupLayoutEntryInfo[o][l.binding].name,u=i.availableTextures[c],h=u.autoBindSampler?i.availableSamplers[c+n_.AutoSamplerSuffix]:null,d=u.sampleType,p=null!==(t=null==h?void 0:h.type)&&void 0!==t?t:Nf.Filtering;if(this._textureState&n&&d!==Ff.Depth&&(u.autoBindSampler&&(p=Nf.NonFiltering),d=Ff.UnfilterableFloat),l.texture.sampleType=d,h){var f=i.bindGroupLayoutEntryInfo[h.binding.groupIndex][h.binding.bindingIndex].index;r[h.binding.groupIndex][f].sampler.type=p}n<<=1}}var _=[];for(o=0;o<r.length;++o)_[o]=this._device.createBindGroupLayout({entries:r[o]});return e.bindGroupLayouts[this._textureState]=_,this._device.createPipelineLayout({bindGroupLayouts:_})},e.prototype._getVertexInputDescriptor=function(t){for(var i,r,n,o,a=[],s=t._pipelineContext,l=s.shaderProcessingContext.attributeNamesFromEffect,c=s.shaderProcessingContext.attributeLocationsFromEffect,u=0;u<l.length;u++){var h=c[u],d=null!==(i=this._overrideVertexBuffers&&this._overrideVertexBuffers[l[u]])&&void 0!==i?i:this._vertexBuffers[l[u]];d||(d=this._emptyVertexBuffer);var p=null===(r=d.effectiveBuffer)||void 0===r?void 0:r.underlyingResource,f=d.effectiveByteOffset,_=!d._validOffsetRange;if(!n||!o||n!==p||_){var m={arrayStride:d.effectiveByteStride,stepMode:d.getIsInstanced()?Kf.Instance:Kf.Vertex,attributes:[]};a.push(m),o=m.attributes,_&&(f=0,p=null)}o.push({shaderLocation:h,offset:f,format:e._GetVertexInputDescriptorFormat(d)}),n=p}return a},e.prototype._processNonFloatVertexBuffers=function(t,i){var r=t.engine._getShaderProcessor(t.shaderProcessingContext.shaderLanguage),n=!1;for(var o in this._vertexBuffers){var a=this._vertexBuffers[o];if(a&&M_[o]){var s=a.normalized?Nr.FLOAT:a.type,l=t.vertexBufferKindToType[o];(s!==Nr.FLOAT&&void 0===l||void 0!==l&&l!==s)&&(n=!0,t.vertexBufferKindToType[o]=s,s!==Nr.FLOAT&&(r.vertexBufferKindToNumberOfComponents[o]=Nr.DeduceStride(o),e._IsSignedType(s)&&(r.vertexBufferKindToNumberOfComponents[o]*=-1)))}}n&&i._processShaderCode(r,!0)},e.prototype._createRenderPipeline=function(t,i,r){var n,o,a,s=t._pipelineContext,l=this._getVertexInputDescriptor(t),c=this._createPipelineLayout(s),u=[],h=this._getAphaBlendState(),d=this._getColorBlendState();if(this._processNonFloatVertexBuffers(s,t),this._mrtAttachments1>0)for(var p=0;p<this._mrtFormats.length;++p){var f=this._mrtFormats[p];if(f){var _={format:f,writeMask:this._mrtEnabledMask&1<<p?this._writeMask:0};h&&d&&(_.blend={alpha:h,color:d}),u.push(_)}else u.push(null)}else this._webgpuColorFormat[0]?(_={format:this._webgpuColorFormat[0],writeMask:this._writeMask},h&&d&&(_.blend={alpha:h,color:d}),u.push(_)):u.push(null);var m={compare:e._GetCompareFunction(this._stencilEnabled?this._stencilFrontCompare:7),depthFailOp:e._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontDepthFailOp:1),failOp:e._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontFailOp:1),passOp:e._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontPassOp:1)},g=void 0;i!==Vf.LineStrip&&i!==Vf.TriangleStrip||(g=!this._indexBuffer||this._indexBuffer.is32Bits?jf.Uint32:jf.Uint16);var v=!!this._webgpuDepthStencilFormat&&p_.HasStencilAspect(this._webgpuDepthStencilFormat);return this._device.createRenderPipeline({label:"RenderPipeline_".concat(null!==(o=null===(n=u[0])||void 0===n?void 0:n.format)&&void 0!==o?o:"nooutput","_").concat(null!==(a=this._webgpuDepthStencilFormat)&&void 0!==a?a:"nodepth","_samples").concat(r,"_textureState").concat(this._textureState),layout:c,vertex:{module:s.stages.vertexStage.module,entryPoint:s.stages.vertexStage.entryPoint,buffers:l},primitive:{topology:i,stripIndexFormat:g,frontFace:1===this._frontFace?kf.CCW:kf.CW,cullMode:this._cullEnabled?2===this._cullFace?Gf.Front:Gf.Back:Gf.None},fragment:s.stages.fragmentStage?{module:s.stages.fragmentStage.module,entryPoint:s.stages.fragmentStage.entryPoint,targets:u}:void 0,multisample:{count:r},depthStencil:void 0===this._webgpuDepthStencilFormat?void 0:{depthWriteEnabled:this._depthWriteEnabled,depthCompare:this._depthTestEnabled?e._GetCompareFunction(this._depthCompare):Mf.Always,format:this._webgpuDepthStencilFormat,stencilFront:this._stencilEnabled&&v?m:void 0,stencilBack:this._stencilEnabled&&v?m:void 0,stencilReadMask:this._stencilEnabled&&v?this._stencilReadMask:void 0,stencilWriteMask:this._stencilEnabled&&v?this._stencilWriteMask:void 0,depthBias:this._depthBias,depthBiasClamp:this._depthBiasClamp,depthBiasSlopeScale:this._depthBiasSlopeScale}})},e.NumCacheHitWithoutHash=0,e.NumCacheHitWithHash=0,e.NumCacheMiss=0,e.NumPipelineCreationLastFrame=0,e._NumPipelineCreationCurrentFrame=0,e}(),D_=function(){function e(){this.values={}}return e.prototype.count=function(){var e=0,t=this.pipeline?1:0;for(var i in this.values){var r=this.values[i].count();e+=r[0],t+=r[1],e++}return[e,t]},e}(),N_=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.GetNodeCounts=function(){var e=t._Cache.count();return{nodeCount:e[0],pipelineCount:e[1]}},t._GetPipelines=function(e,i,r,n){if(e.pipeline){var o=r.slice();o.length=n,i.push(o)}for(var a in e.values){var s=e.values[a];r[n]=parseInt(a),t._GetPipelines(s,i,r,n+1)}},t.GetPipelines=function(){var e=[];return t._GetPipelines(t._Cache,e,[],0),e},t.ResetCache=function(){t._Cache=new D_},t.prototype.reset=function(){this._nodeStack=[],this._nodeStack[0]=t._Cache,e.prototype.reset.call(this)},t.prototype._getRenderPipeline=function(e){for(var t=this._nodeStack[this._stateDirtyLowestIndex],i=this._stateDirtyLowestIndex;i<this._statesLength;++i){var r=t.values[this._states[i]];r||(r=new D_,t.values[this._states[i]]=r),t=r,this._nodeStack[i+1]=t}e.token=t,e.pipeline=t.pipeline},t.prototype._setRenderPipeline=function(e){e.token.pipeline=e.pipeline},t._Cache=new D_,t}(O_),F_=function(e){function t(t){var i=e.call(this,!1)||this;return i._cache=t,i.reset(),i}return m(t,e),Object.defineProperty(t.prototype,"func",{get:function(){return this._func},set:function(e){this._func!==e&&(this._func=e,this._cache.setStencilCompare(e))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"funcMask",{get:function(){return this._funcMask},set:function(e){this._funcMask!==e&&(this._funcMask=e,this._cache.setStencilReadMask(e))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"opStencilFail",{get:function(){return this._opStencilFail},set:function(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._cache.setStencilFailOp(e))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"opDepthFail",{get:function(){return this._opDepthFail},set:function(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._cache.setStencilDepthFailOp(e))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"opStencilDepthPass",{get:function(){return this._opStencilDepthPass},set:function(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._cache.setStencilPassOp(e))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"mask",{get:function(){return this._mask},set:function(e){this._mask!==e&&(this._mask=e,this._cache.setStencilWriteMask(e))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"enabled",{get:function(){return this._enabled},set:function(e){this._enabled!==e&&(this._enabled=e,this._cache.setStencilEnabled(e))},enumerable:!1,configurable:!0}),t.prototype.reset=function(){e.prototype.reset.call(this),this._cache.resetStencilState()},t.prototype.apply=function(){var e,t=null===(e=this.stencilMaterial)||void 0===e?void 0:e.enabled;this.enabled=t?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.enabled&&(this.func=t?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=t?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=t?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=t?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=t?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=t?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=t?this.stencilMaterial.mask:this.stencilGlobal.mask)},t}(xi),L_=function(e){function t(t){var i=e.call(this,!1)||this;return i._cache=t,i.reset(),i}return m(t,e),Object.defineProperty(t.prototype,"zOffset",{get:function(){return this._zOffset},set:function(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0,this._cache.setDepthBiasSlopeScale(e))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"zOffsetUnits",{get:function(){return this._zOffsetUnits},set:function(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0,this._cache.setDepthBias(e))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cullFace",{get:function(){return this._cullFace},set:function(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0,this._cache.setCullFace(null!=e?e:1))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cull",{get:function(){return this._cull},set:function(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0,this._cache.setCullEnabled(!!e))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"depthFunc",{get:function(){return this._depthFunc},set:function(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0,this._cache.setDepthCompare(e))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"depthMask",{get:function(){return this._depthMask},set:function(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0,this._cache.setDepthWriteEnabled(e))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"depthTest",{get:function(){return this._depthTest},set:function(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0,this._cache.setDepthTestEnabled(e))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"frontFace",{get:function(){return this._frontFace},set:function(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0,this._cache.setFrontFace(null!=e?e:2))},enumerable:!1,configurable:!0}),t.prototype.reset=function(){e.prototype.reset.call(this),this._cache.resetDepthCullingState()},t.prototype.apply=function(){},t}(Si),w_=function(){function e(e){this.useMipMaps=!1,this.type=u.TEXTURETYPE_UNDEFINED,this.format=u.TEXTUREFORMAT_UNDEFINED,this._video=e,this.uniqueId=Pi._Counter++}return e.IsExternalTexture=function(e){return void 0!==e.underlyingResource},e.prototype.getClassName=function(){return"ExternalTexture"},Object.defineProperty(e.prototype,"underlyingResource",{get:function(){return this._video},enumerable:!1,configurable:!0}),e.prototype.isReady=function(){return this._video.readyState>=this._video.HAVE_CURRENT_DATA},e.prototype.dispose=function(){},e}(),B_=function(){function e(){this.uniqueId=e._Counter++,this.updateId=0,this.textureState=0,this.reset()}return Object.defineProperty(e.prototype,"forceBindGroupCreation",{get:function(){return this._numExternalTextures>0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hasFloatOrDepthTextures",{get:function(){return this._numFloatOrDepthTextures>0},enumerable:!1,configurable:!0}),e.prototype.reset=function(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatOrDepthTextures=0,this._numExternalTextures=0},e.prototype.setSampler=function(e,t){var i=this.samplers[e],r=-1;i?r=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?R_.GetSamplerHashCode(t):0;var n=r!==i.hashCode;n&&this.updateId++,this.isDirty||(this.isDirty=n)},e.prototype.setTexture=function(e,t){var i,r,n,o=this.textures[e],a=-1;o?a=null!==(r=null===(i=o.texture)||void 0===i?void 0:i.uniqueId)&&void 0!==r?r:-1:this.textures[e]=o={texture:t,isFloatOrDepthTexture:!1,isExternalTexture:!1},o.isExternalTexture&&this._numExternalTextures--,o.isFloatOrDepthTexture&&this._numFloatOrDepthTextures--,t?(o.isFloatOrDepthTexture=t.type===u.TEXTURETYPE_FLOAT||t.format>=u.TEXTUREFORMAT_DEPTH24_STENCIL8&&t.format<=u.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8,o.isExternalTexture=w_.IsExternalTexture(t),o.isFloatOrDepthTexture&&this._numFloatOrDepthTextures++,o.isExternalTexture&&this._numExternalTextures++):(o.isFloatOrDepthTexture=!1,o.isExternalTexture=!1),o.texture=t;var s=a!==(null!==(n=null==t?void 0:t.uniqueId)&&void 0!==n?n:-1);s&&this.updateId++,this.isDirty||(this.isDirty=s)},e._Counter=0,e}(),U_=function(){function e(t){this._bufferManager=t,this.uniqueId=e._Counter++,this._useInstancing=!1,this._currentInstanceCount=0,this.reset()}return e.prototype.isDirty=function(e){return this._isDirty||this._materialContextUpdateId!==e},e.prototype.resetIsDirty=function(e){this._isDirty=!1,this._materialContextUpdateId=e},Object.defineProperty(e.prototype,"useInstancing",{get:function(){return this._useInstancing},set:function(e){this._useInstancing!==e&&(e?(this.indirectDrawBuffer=this._bufferManager.createRawBuffer(20,bf.CopyDst|bf.Indirect|bf.Storage,void 0,"IndirectDrawBuffer"),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this.indirectDrawBuffer&&this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this._useInstancing=e,this._currentInstanceCount=-1)},enumerable:!1,configurable:!0}),e.prototype.reset=function(){this.buffers={},this._isDirty=!0,this._materialContextUpdateId=0,this.fastBundle=void 0,this.bindGroups=void 0},e.prototype.setBuffer=function(e,t){var i;this._isDirty||(this._isDirty=(null==t?void 0:t.uniqueId)!==(null===(i=this.buffers[e])||void 0===i?void 0:i.uniqueId)),this.buffers[e]=t},e.prototype.setIndirectData=function(e,t,i){t!==this._currentInstanceCount&&this.indirectDrawBuffer&&this._indirectDrawData&&(this._currentInstanceCount=t,this._indirectDrawData[0]=e,this._indirectDrawData[1]=t,this._indirectDrawData[2]=i,this._bufferManager.setRawData(this.indirectDrawBuffer,0,this._indirectDrawData,0,20))},e.prototype.dispose=function(){this.indirectDrawBuffer&&(this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this.fastBundle=void 0,this.bindGroups=void 0,this.buffers=void 0},e._Counter=0,e}(),V_=function(){this.values={}},k_=function(){function e(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}return Object.defineProperty(e,"Statistics",{get:function(){return{totalCreated:e.NumBindGroupsCreatedTotal,lastFrameCreated:e.NumBindGroupsCreatedLastFrame,lookupLastFrame:e.NumBindGroupsLookupLastFrame,noLookupLastFrame:e.NumBindGroupsNoLookupLastFrame}},enumerable:!1,configurable:!0}),e.ResetCache=function(){e._Cache=new V_,e.NumBindGroupsCreatedTotal=0,e.NumBindGroupsCreatedLastFrame=0,e.NumBindGroupsLookupLastFrame=0,e.NumBindGroupsNoLookupLastFrame=0,e._NumBindGroupsCreatedCurrentFrame=0,e._NumBindGroupsLookupCurrentFrame=0,e._NumBindGroupsNoLookupCurrentFrame=0},e.prototype.endFrame=function(){e.NumBindGroupsCreatedLastFrame=e._NumBindGroupsCreatedCurrentFrame,e.NumBindGroupsLookupLastFrame=e._NumBindGroupsLookupCurrentFrame,e.NumBindGroupsNoLookupLastFrame=e._NumBindGroupsNoLookupCurrentFrame,e._NumBindGroupsCreatedCurrentFrame=0,e._NumBindGroupsLookupCurrentFrame=0,e._NumBindGroupsNoLookupCurrentFrame=0},e.prototype.getBindGroups=function(t,i,r){var n,o,a,s,l,c,u,h,d,p,f=void 0,_=e._Cache,m=this.disabled||r.forceBindGroupCreation;if(!m){if(!i.isDirty(r.updateId)&&!r.isDirty)return e._NumBindGroupsNoLookupCurrentFrame++,i.bindGroups;for(var g=0,v=t.shaderProcessingContext.bufferNames;g<v.length;g++){var y=v[g],b=null!==(o=null===(n=i.buffers[y])||void 0===n?void 0:n.uniqueId)&&void 0!==o?o:0;(R=_.values[b])||(R=new V_,_.values[b]=R),_=R}for(var T=0,E=t.shaderProcessingContext.samplerNames;T<E.length;T++){var S=E[T],x=null!==(s=null===(a=r.samplers[S])||void 0===a?void 0:a.hashCode)&&void 0!==s?s:0;(R=_.values[x])||(R=new V_,_.values[x]=R),_=R}for(var A=0,C=t.shaderProcessingContext.textureNames;A<C.length;A++){var R,P=C[A],I=null!==(u=null===(c=null===(l=r.textures[P])||void 0===l?void 0:l.texture)||void 0===c?void 0:c.uniqueId)&&void 0!==u?u:0;(R=_.values[I])||(R=new V_,_.values[I]=R),_=R}f=_.bindGroups}if(i.resetIsDirty(r.updateId),r.isDirty=!1,f)return i.bindGroups=f,e._NumBindGroupsLookupCurrentFrame++,f;f=[],i.bindGroups=f,m||(_.bindGroups=f),e.NumBindGroupsCreatedTotal++,e._NumBindGroupsCreatedCurrentFrame++;for(var M=t.bindGroupLayouts[r.textureState],O=0;O<t.shaderProcessingContext.bindGroupLayoutEntries.length;O++){for(var D=t.shaderProcessingContext.bindGroupLayoutEntries[O],N=t.shaderProcessingContext.bindGroupEntries[O],F=0;F<D.length;F++){var L=t.shaderProcessingContext.bindGroupLayoutEntries[O][F],w=t.shaderProcessingContext.bindGroupLayoutEntryInfo[O][L.binding],B=null!==(h=w.nameInArrayOfTexture)&&void 0!==h?h:w.name;if(L.sampler)if(k=r.samplers[B]){var U=k.sampler;if(!U){this._engine.dbgSanityChecks&&ae.Error("Trying to bind a null sampler! entry=".concat(JSON.stringify(L),", name=").concat(B,", bindingInfo=").concat(JSON.stringify(k,(function(e,t){return"texture"===e?"<no dump>":t})),", materialContext.uniqueId=").concat(r.uniqueId),50);continue}N[F].resource=this._cacheSampler.getSampler(U,!1,k.hashCode,U.label)}else ae.Error('Sampler "'.concat(B,'" could not be bound. entry=').concat(JSON.stringify(L),", materialContext=").concat(JSON.stringify(r,(function(e,t){return"texture"===e||"sampler"===e?"<no dump>":t}))),50);else if(L.texture||L.storageTexture)if(k=r.textures[B]){if(this._engine.dbgSanityChecks&&null===k.texture){ae.Error("Trying to bind a null texture! entry=".concat(JSON.stringify(L),", bindingInfo=").concat(JSON.stringify(k,(function(e,t){return"texture"===e?"<no dump>":t})),", materialContext.uniqueId=").concat(r.uniqueId),50);continue}var V=k.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!V||L.texture&&!V.view||L.storageTexture&&!V.viewForWriting)){ae.Error("Trying to bind a null gpu texture or view! entry=".concat(JSON.stringify(L),", name=").concat(B,", bindingInfo=").concat(JSON.stringify(k,(function(e,t){return"texture"===e?"<no dump>":t})),", isReady=").concat(null===(d=k.texture)||void 0===d?void 0:d.isReady,", materialContext.uniqueId=").concat(r.uniqueId),50);continue}N[F].resource=L.storageTexture?V.viewForWriting:V.view}else ae.Error('Texture "'.concat(B,'" could not be bound. entry=').concat(JSON.stringify(L),", materialContext=").concat(JSON.stringify(r,(function(e,t){return"texture"===e||"sampler"===e?"<no dump>":t}))),50);else if(L.externalTexture){var k;if(k=r.textures[B]){if(this._engine.dbgSanityChecks&&null===k.texture){ae.Error("Trying to bind a null external texture! entry=".concat(JSON.stringify(L),", name=").concat(B,", bindingInfo=").concat(JSON.stringify(k,(function(e,t){return"texture"===e?"<no dump>":t})),", materialContext.uniqueId=").concat(r.uniqueId),50);continue}var G=k.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!G){ae.Error("Trying to bind a null gpu external texture! entry=".concat(JSON.stringify(L),", name=").concat(B,", bindingInfo=").concat(JSON.stringify(k,(function(e,t){return"texture"===e?"<no dump>":t})),", isReady=").concat(null===(p=k.texture)||void 0===p?void 0:p.isReady,", materialContext.uniqueId=").concat(r.uniqueId),50);continue}N[F].resource=this._device.importExternalTexture({source:G})}else ae.Error('Texture "'.concat(B,'" could not be bound. entry=').concat(JSON.stringify(L),", materialContext=").concat(JSON.stringify(r,(function(e,t){return"texture"===e||"sampler"===e?"<no dump>":t}))),50)}else if(L.buffer){var z=i.buffers[B];if(z){var W=z.underlyingResource;N[F].resource.buffer=W,N[F].resource.size=z.capacity}else ae.Error("Can't find buffer \"".concat(B,'". entry=').concat(JSON.stringify(L),", buffers=").concat(JSON.stringify(i.buffers),", drawContext.uniqueId=").concat(i.uniqueId),50)}}var H=M[O];f[O]=this._device.createBindGroup({layout:H,entries:N})}return f},e.NumBindGroupsCreatedTotal=0,e.NumBindGroupsCreatedLastFrame=0,e.NumBindGroupsLookupLastFrame=0,e.NumBindGroupsNoLookupLastFrame=0,e._Cache=new V_,e._NumBindGroupsCreatedCurrentFrame=0,e._NumBindGroupsLookupCurrentFrame=0,e._NumBindGroupsNoLookupCurrentFrame=0,e}();li.ShadersStoreWGSL.clearQuadVertexShader="uniform depthValue: f32;const pos=array(\nvec2f(-1.0,1.0),\nvec2f(1.0,1.0),\nvec2f(-1.0,-1.0),\nvec2f(1.0,-1.0)\n);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.position=vec4f(pos[input.vertexIndex],uniforms.depthValue,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";li.ShadersStoreWGSL.clearQuadPixelShader="uniform color: vec4f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=uniforms.color;}\n";var G_=function(){function e(e,t,i){this._bindGroups={},this._bundleCache={},this._keyTemp=[],this._device=e,this._engine=t,this._cacheRenderPipeline=new N_(this._device,i),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"],void 0,void 0,void 0,void 0,void 0,void 0,pt.WGSL)}return e.prototype.setDepthStencilFormat=function(e){this._depthTextureFormat=e,this._cacheRenderPipeline.setDepthStencilFormat(e)},e.prototype.setColorFormat=function(e){this._cacheRenderPipeline.setColorFormat(e)},e.prototype.setMRTAttachments=function(e,t,i){this._cacheRenderPipeline.setMRT(t,i),this._cacheRenderPipeline.setMRTAttachments(e)},e.prototype.clear=function(e,t,i,r,n){var o,a,s;void 0===n&&(n=1);var l,c=null,h=!!this._engine._currentRenderTarget;if(e)s=e;else{var d=0;this._keyTemp.length=0;for(var p=0;p<this._cacheRenderPipeline.colorFormats.length;++p)this._keyTemp[d++]=b_[null!==(o=this._cacheRenderPipeline.colorFormats[p])&&void 0!==o?o:""];var f=b_[null!==(a=this._depthTextureFormat)&&void 0!==a?a:0];if(this._keyTemp[d]=(t?t.r+256*t.g+256*t.b*256+256*t.a*256*256:0)+(i?Math.pow(2,32):0)+(r?Math.pow(2,33):0)+(this._engine.useReverseDepthBuffer?Math.pow(2,34):0)+(h?Math.pow(2,35):0)+(n>1?Math.pow(2,36):0)+f*Math.pow(2,37),l=this._keyTemp.join("_"),c=this._bundleCache[l])return c;s=this._device.createRenderBundleEncoder({label:"clearQuadRenderBundle",colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:p_.GetSample(n)})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!r&&!!this._depthTextureFormat&&p_.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(r?255:0),this._cacheRenderPipeline.setStencilCompare(r?u.ALWAYS:u.NEVER),this._cacheRenderPipeline.setStencilPassOp(r?u.REPLACE:u.KEEP),this._cacheRenderPipeline.setWriteMask(t?15:0);var _=this._cacheRenderPipeline.getRenderPipeline(u.MATERIAL_TriangleStripDrawMode,this._effect,n),m=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),m.uniformBuffer.update();var g=h?this._engine._ubInvertY:this._engine._ubDontInvertY,v=m.uniformBuffer.getBuffer(),y=v.uniqueId+"-"+g.uniqueId,b=this._bindGroups[y];if(!b){var T=m.bindGroupLayouts[0];(b=this._bindGroups[y]=[]).push(this._device.createBindGroup({label:"clearQuadBindGroup0-".concat(y),layout:T[0],entries:[]})),s_._SimplifiedKnownBindings||b.push(this._device.createBindGroup({label:"clearQuadBindGroup1-".concat(y),layout:T[1],entries:[]})),b.push(this._device.createBindGroup({label:"clearQuadBindGroup".concat(s_._SimplifiedKnownBindings?1:2,"-").concat(y),layout:T[s_._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:g.underlyingResource,size:g.capacity}},{binding:1,resource:{buffer:v.underlyingResource,size:v.capacity}}]}))}for(s.setPipeline(_),p=0;p<b.length;++p)s.setBindGroup(p,b[p]);return s.draw(4,1,0,0),e||(c=s.finish(),this._bundleCache[l]=c),c},e}(),z_=function(){function e(e,t,i,r){this.x=Math.floor(e),this.y=Math.floor(t),this.w=Math.floor(i),this.h=Math.floor(r)}return e.prototype.run=function(e){e.setViewport(this.x,this.y,this.w,this.h,0,1)},e.prototype.clone=function(){return new e(this.x,this.y,this.w,this.h)},e}(),W_=function(){function e(e,t,i,r){this.x=e,this.y=t,this.w=i,this.h=r}return e.prototype.run=function(e){e.setScissorRect(this.x,this.y,this.w,this.h)},e.prototype.clone=function(){return new e(this.x,this.y,this.w,this.h)},e}(),H_=function(){function e(e){this.ref=e}return e.prototype.run=function(e){e.setStencilReference(this.ref)},e.prototype.clone=function(){return new e(this.ref)},e}(),X_=function(){function e(e){this.color=e}return e.prototype.run=function(e){e.setBlendConstant(this.color)},e.prototype.clone=function(){return new e(this.color)},e}(),j_=function(){function e(e){this.query=e}return e.prototype.run=function(e){e.beginOcclusionQuery(this.query)},e.prototype.clone=function(){return new e(this.query)},e}(),Y_=function(){function e(){}return e.prototype.run=function(e){e.endOcclusionQuery()},e.prototype.clone=function(){return new e},e}(),K_=function(){function e(){this.bundles=[]}return e.prototype.run=function(e){e.executeBundles(this.bundles)},e.prototype.clone=function(){var t=new e;return t.bundles=this.bundles,t},e}(),Q_=function(){function e(e){this.numDrawCalls=0,this._device=e,this._list=new Array(10),this._listLength=0}return e.prototype.addBundle=function(e){if(!this._currentItemIsBundle){var t=new K_;this._list[this._listLength++]=t,this._currentBundleList=t.bundles,this._currentItemIsBundle=!0}e&&this._currentBundleList.push(e)},e.prototype._finishBundle=function(){this._currentItemIsBundle&&this._bundleEncoder&&(this._currentBundleList.push(this._bundleEncoder.finish()),this._bundleEncoder=void 0,this._currentItemIsBundle=!1)},e.prototype.addItem=function(e){this._finishBundle(),this._list[this._listLength++]=e,this._currentItemIsBundle=!1},e.prototype.getBundleEncoder=function(e,t,i){return this._currentItemIsBundle||(this.addBundle(),this._bundleEncoder=this._device.createRenderBundleEncoder({colorFormats:e,depthStencilFormat:t,sampleCount:p_.GetSample(i)})),this._bundleEncoder},e.prototype.close=function(){this._finishBundle()},e.prototype.run=function(e){this.close();for(var t=0;t<this._listLength;++t)this._list[t].run(e)},e.prototype.reset=function(){this._listLength=0,this._currentItemIsBundle=!1,this.numDrawCalls=0},e.prototype.clone=function(){this.close();var t=new e(this._device);t._list=new Array(this._listLength),t._listLength=this._listLength,t.numDrawCalls=this.numDrawCalls;for(var i=0;i<this._listLength;++i)t._list[i]=this._list[i].clone();return t},e}(),q_=function(){function e(e,t,i,r,n,o,a){void 0===o&&(o=!0),this._dstBuffers=[],this._engine=e,this._device=r,this._bufferManager=n,this._count=t,this._canUseMultipleBuffers=o,this._querySet=r.createQuerySet({label:null!=a?a:"QuerySet",type:i,count:t}),this._queryBuffer=n.createRawBuffer(8*t,bf.QueryResolve|bf.CopySrc,void 0,"QueryBuffer"),o||this._dstBuffers.push(this._bufferManager.createRawBuffer(8*this._count,bf.MapRead|bf.CopyDst,void 0,"QueryBufferNoMultipleBuffers"))}return Object.defineProperty(e.prototype,"querySet",{get:function(){return this._querySet},enumerable:!1,configurable:!0}),e.prototype._getBuffer=function(e,t){if(!this._canUseMultipleBuffers&&0===this._dstBuffers.length)return null;var i,r=this._device.createCommandEncoder();return 0===this._dstBuffers.length?i=this._bufferManager.createRawBuffer(8*this._count,bf.MapRead|bf.CopyDst,void 0,"QueryBufferAdditionalBuffer"):(i=this._dstBuffers[this._dstBuffers.length-1],this._dstBuffers.length--),r.resolveQuerySet(this._querySet,e,t,this._queryBuffer,0),r.copyBufferToBuffer(this._queryBuffer,0,i,0,8*t),this._device.queue.submit([r.finish()]),i},e.prototype.readValues=function(e,t){return void 0===e&&(e=0),void 0===t&&(t=1),y(this,void 0,void 0,(function(){var i,r,n=this;return b(this,(function(o){return null===(i=this._getBuffer(e,t))?[2,null]:(r=this._engine.uniqueId,[2,i.mapAsync(Tf.Read).then((function(){var e=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),n._dstBuffers[n._dstBuffers.length]=i,e}),(function(e){if(n._engine.isDisposed||n._engine.uniqueId!==r)return null;throw e}))])}))}))},e.prototype.readValue=function(e){return void 0===e&&(e=0),y(this,void 0,void 0,(function(){var t,i,r=this;return b(this,(function(n){return null===(t=this._getBuffer(e,1))?[2,null]:(i=this._engine.uniqueId,[2,t.mapAsync(Tf.Read).then((function(){var e=new BigUint64Array(t.getMappedRange()),i=Number(e[0]);return t.unmap(),r._dstBuffers[r._dstBuffers.length]=t,i}),(function(e){if(r._engine.isDisposed||r._engine.uniqueId!==i)return 0;throw e}))])}))}))},e.prototype.readTwoValuesAndSubtract=function(e){return void 0===e&&(e=0),y(this,void 0,void 0,(function(){var t,i,r=this;return b(this,(function(n){return null===(t=this._getBuffer(e,2))?[2,null]:(i=this._engine.uniqueId,[2,t.mapAsync(Tf.Read).then((function(){var e=new BigUint64Array(t.getMappedRange()),i=Number(e[1]-e[0]);return t.unmap(),r._dstBuffers[r._dstBuffers.length]=t,i}),(function(e){if(r._engine.isDisposed||r._engine.uniqueId!==i)return 0;throw e}))])}))}))},e.prototype.dispose=function(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(var e=0;e<this._dstBuffers.length;++e)this._bufferManager.releaseBuffer(this._dstBuffers[e])},e}(),Z_=function(){function e(e,t,i){this._enabled=!1,this._gpuFrameTimeCounter=new an,this._measureDurationState=0,this._engine=e,this._device=t,this._bufferManager=i}return Object.defineProperty(e.prototype,"gpuFrameTimeCounter",{get:function(){return this._gpuFrameTimeCounter},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"enable",{get:function(){return this._enabled},set:function(e){if(this._enabled!==e)if(this._enabled=e,this._measureDurationState=0,e)try{this._measureDuration=new J_(this._engine,this._device,this._bufferManager,2e3,"QuerySet_TimestampQuery")}catch(e){return this._enabled=!1,void ae.Error("Could not create a WebGPUDurationMeasure!\nError: "+e.message+"\nMake sure timestamp query is supported and enabled in your browser.")}else this._measureDuration.dispose()},enumerable:!1,configurable:!0}),e.prototype.startFrame=function(e){this._enabled&&0===this._measureDurationState&&(this._measureDuration.start(e),this._measureDurationState=1)},e.prototype.endFrame=function(e){var t=this;1===this._measureDurationState&&(this._measureDurationState=2,this._measureDuration.stop(e).then((function(e){null!==e&&e>=0&&(t._gpuFrameTimeCounter.fetchNewFrame(),t._gpuFrameTimeCounter.addCount(e,!0)),t._measureDurationState=0})))},e.prototype.startPass=function(e,t){this._enabled?this._measureDuration.startPass(e,t):e.timestampWrites=void 0},e.prototype.endPass=function(e,t){if(this._enabled&&t){var i=this._engine.frameId;this._measureDuration.stopPass(e).then((function(e){t._addDuration(i,null!==e&&e>0?e:0)}))}},e.prototype.dispose=function(){var e;null===(e=this._measureDuration)||void 0===e||e.dispose()},e}(),J_=function(){function e(e,t,i,r,n){void 0===r&&(r=2),this._count=r,this._querySet=new q_(e,r,$f.Timestamp,t,i,!0,n)}return e.prototype.start=function(e){var t;null===(t=e.writeTimestamp)||void 0===t||t.call(e,this._querySet.querySet,0)},e.prototype.stop=function(e){var t;return y(this,void 0,void 0,(function(){return b(this,(function(i){return null===(t=e.writeTimestamp)||void 0===t||t.call(e,this._querySet.querySet,1),[2,e.writeTimestamp?this._querySet.readTwoValuesAndSubtract(0):0]}))}))},e.prototype.startPass=function(e,t){if(t+3>this._count)throw new Error("WebGPUDurationMeasure: index out of range ("+t+")");e.timestampWrites={querySet:this._querySet.querySet,beginningOfPassWriteIndex:t+2,endOfPassWriteIndex:t+3}},e.prototype.stopPass=function(e){return y(this,void 0,void 0,(function(){return b(this,(function(t){return[2,this._querySet.readTwoValuesAndSubtract(e+2)]}))}))},e.prototype.dispose=function(){this._querySet.dispose()},e}(),$_=function(){function e(e,t,i,r,n){void 0===r&&(r=50),void 0===n&&(n=100),this._availableIndices=[],this._frameQuerySetIsDirty=-1,this._queryFrameId=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=n,this._allocateNewIndices(r)}return Object.defineProperty(e.prototype,"querySet",{get:function(){return this._querySet.querySet},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hasQueries",{get:function(){return this._currentTotalIndices!==this._availableIndices.length},enumerable:!1,configurable:!0}),e.prototype.canBeginQuery=function(e){if(this._frameQuerySetIsDirty===this._engine.frameId||this._queryFrameId[e]===this._engine.frameId)return!1;var t=void 0!==this._engine._getCurrentRenderPassWrapper().renderPassDescriptor.occlusionQuerySet;return t&&(this._queryFrameId[e]=this._engine.frameId),t},e.prototype.createQuery=function(){0===this._availableIndices.length&&this._allocateNewIndices();var e=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,e},e.prototype.deleteQuery=function(e){this._availableIndices[this._availableIndices.length]=e},e.prototype.isQueryResultAvailable=function(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e<this._lastBuffer.length},e.prototype.getQueryResult=function(e){var t,i;return Number(null!==(i=null===(t=this._lastBuffer)||void 0===t?void 0:t[e])&&void 0!==i?i:-1)},e.prototype._retrieveQueryBuffer=function(){var e=this;this._lastBuffer&&this._frameLastBuffer===this._engine.frameId||this._frameLastBuffer!==this._engine.frameId&&(this._frameLastBuffer=this._engine.frameId,this._querySet.readValues(0,this._currentTotalIndices).then((function(t){e._lastBuffer=t})))},e.prototype._allocateNewIndices=function(e){e=null!=e?e:this._countIncrement,this._delayQuerySetDispose();for(var t=0;t<e;++t)this._availableIndices.push(this._currentTotalIndices+t);this._currentTotalIndices+=e,this._querySet=new q_(this._engine,this._currentTotalIndices,$f.Occlusion,this._device,this._bufferManager,!1,"QuerySet_OcclusionQuery_count_"+this._currentTotalIndices),this._frameQuerySetIsDirty=this._engine.frameId},e.prototype._delayQuerySetDispose=function(){var e=this._querySet;e&&setTimeout((function(){return e.dispose}),1e3)},e.prototype.dispose=function(){var e;null===(e=this._querySet)||void 0===e||e.dispose(),this._availableIndices.length=0},e}(),em=function(){function e(){}return e.prototype.initTwgsl=function(t){return y(this,void 0,void 0,(function(){var i;return b(this,(function(r){switch(r.label){case 0:return e._Twgsl?[2]:(t=t||{},(t=g(g({},e._TWgslDefaultOptions),t)).twgsl?(e._Twgsl=t.twgsl,[2,Promise.resolve()]):t.jsPath&&t.wasmPath?[4,rr.LoadBabylonScriptAsync(t.jsPath)]:[3,2]);case 1:r.sent(),r.label=2;case 2:return self.twgsl?(i=e,[4,self.twgsl(rr.GetBabylonScriptURL(t.wasmPath))]):[3,4];case 3:return i._Twgsl=r.sent(),[2,Promise.resolve()];case 4:return[2,Promise.reject("twgsl is not available.")]}}))}))},e.prototype.convertSpirV2WGSL=function(t,i){void 0===i&&(i=!1);var r=e._Twgsl.convertSpirV2WGSL(t,e.DisableUniformityAnalysis||i);return e.ShowWGSLShaderCode&&(ae.Log(r),ae.Log("***********************************************")),e.DisableUniformityAnalysis||i?"diagnostic(off, derivative_uniformity);\n"+r:r},e._TWgslDefaultOptions={jsPath:"".concat(rr._DefaultCdnUrl,"/twgsl/twgsl.js"),wasmPath:"".concat(rr._DefaultCdnUrl,"/twgsl/twgsl.wasm")},e.ShowWGSLShaderCode=!1,e.DisableUniformityAnalysis=!1,e._Twgsl=null,e}(),tm=function(){function e(e,t,i){this._record=!1,this._play=!1,this._playBundleListIndex=0,this._allBundleLists=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i}return Object.defineProperty(e.prototype,"enabled",{get:function(){return this._enabled},set:function(e){this._allBundleLists.length=0,this._record=this._enabled=e,this._play=!1,e&&(this._modeSaved=this._mode,this._mode=u.SNAPSHOTRENDERING_STANDARD)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"play",{get:function(){return this._play},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"record",{get:function(){return this._record},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"mode",{get:function(){return this._mode},set:function(e){this._record?this._modeSaved=e:this._mode=e},enumerable:!1,configurable:!0}),e.prototype.endRenderPass=function(e){if(!this._record&&!this._play)return!1;var t;if(this._record)t=this._bundleList.clone(),this._allBundleLists.push(t),this._bundleList.reset();else{if(this._playBundleListIndex>=this._allBundleLists.length)throw new Error("Invalid playBundleListIndex! Your snapshot is no longer valid for the current frame, you should recreate a new one. playBundleListIndex=".concat(this._playBundleListIndex,", allBundleLists.length=").concat(this._allBundleLists.length,"}"));t=this._allBundleLists[this._playBundleListIndex++]}return t.run(e),this._mode===u.SNAPSHOTRENDERING_FAST&&this._engine._reportDrawCall(t.numDrawCalls),!0},e.prototype.endFrame=function(){this._record&&(this._record=!1,this._play=!0,this._mode=this._modeSaved),this._playBundleListIndex=0},e.prototype.reset=function(){this.enabled=!1,this.enabled=!0},e}();li.ShadersStoreWGSL.postprocessVertexShader="attribute position: vec2<f32>;uniform scale: vec2<f32>;varying vUV: vec2<f32>;const madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";var im=function(e){function t(t){return e.call(this,t)||this}return m(t,e),t}(w_),rm={label:"TextureView_SwapChain_ResolveTarget",dimension:Ef.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},nm={label:"TextureView_SwapChain",dimension:Ef.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},om="/* disable_uniformity_analysis */",am=new J,sm=function(e){function t(t,i){void 0===i&&(i={});var r,n,o=this;return(o=e.call(this,null===(r=i.antialias)||void 0===r||r,i)||this).uniqueId=-1,o._uploadEncoderDescriptor={label:"upload"},o._renderEncoderDescriptor={label:"render"},o._clearDepthValue=1,o._clearReverseDepthValue=0,o._clearStencilValue=0,o._defaultSampleCount=4,o._glslang=null,o._tintWASM=null,o._adapterInfo={vendor:"",architecture:"",device:"",description:""},o._timestampIndex=0,o._compiledComputeEffects={},o._counters={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},o.countersLastFrame={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},o.numMaxUncapturedErrors=20,o.scenes=[],o._virtualScenes=new Array,o._commandBuffers=[null,null],o._currentRenderPass=null,o._mainRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},o._rttRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},o._pendingDebugCommands=[],o._currentOverrideVertexBuffers=null,o._currentIndexBuffer=null,o._colorWriteLocal=!0,o._forceEnableEffect=!1,o.dbgShowShaderCode=!1,o.dbgSanityChecks=!0,o.dbgVerboseLogsForFirstFrames=!1,o.dbgVerboseLogsNumFrames=10,o.dbgLogIfNotDrawWrapper=!0,o.dbgShowEmptyEnableEffectCalls=!0,o._snapshotRenderingMode=u.SNAPSHOTRENDERING_STANDARD,o.isNDCHalfZRange=!0,o.hasOriginBottomLeft=!1,o._viewportsCurrent={x:0,y:0,w:0,h:0},o._scissorsCurrent={x:0,y:0,w:0,h:0},o._scissorCached={x:0,y:0,z:0,w:0},o._stencilRefsCurrent=-1,o._blendColorsCurrent=[null,null,null,null],o._performanceMonitor=new yo,o._name="WebGPU",o._drawCalls=new an,i.deviceDescriptor=i.deviceDescriptor||{},i.enableGPUDebugMarkers=null!==(n=i.enableGPUDebugMarkers)&&void 0!==n&&n,ae.Log("Babylon.js v".concat(Do.Version," - ").concat(o.description," engine")),navigator.gpu?(i.swapChainFormat=i.swapChainFormat||navigator.gpu.getPreferredCanvasFormat(),o._isWebGPU=!0,o._shaderPlatformName="WEBGPU",o._renderingCanvas=t,o._options=i,o._mainPassSampleCount=i.antialias?o._defaultSampleCount:1,navigator&&navigator.userAgent&&o._setupMobileChecks(),o._sharedInit(o._renderingCanvas),o._shaderProcessor=new l_,o._shaderProcessorWGSL=new d_,o):(ae.Error("WebGPU is not supported by your browser."),o)}return m(t,e),Object.defineProperty(t.prototype,"snapshotRenderingMode",{get:function(){return this._snapshotRendering.mode},set:function(e){this._snapshotRendering.mode=e},enumerable:!1,configurable:!0}),t.prototype.snapshotRenderingReset=function(){this._snapshotRendering.reset()},Object.defineProperty(t.prototype,"snapshotRendering",{get:function(){return this._snapshotRendering.enabled},set:function(e){this._snapshotRendering.enabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"disableCacheSamplers",{get:function(){return!!this._cacheSampler&&this._cacheSampler.disabled},set:function(e){this._cacheSampler&&(this._cacheSampler.disabled=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"disableCacheRenderPipelines",{get:function(){return!!this._cacheRenderPipeline&&this._cacheRenderPipeline.disabled},set:function(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"disableCacheBindGroups",{get:function(){return!!this._cacheBindGroups&&this._cacheBindGroups.disabled},set:function(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)},enumerable:!1,configurable:!0}),t.prototype.areAllEffectsReady=function(){return!0},t.prototype.getFontOffset=function(e){return xo(e)},Object.defineProperty(t,"IsSupportedAsync",{get:function(){return navigator.gpu?navigator.gpu.requestAdapter().then((function(e){return!!e}),(function(){return!1})).catch((function(){return!1})):Promise.resolve(!1)},enumerable:!1,configurable:!0}),Object.defineProperty(t,"IsSupported",{get:function(){return ae.Warn("You must call IsSupportedAsync for WebGPU!"),!1},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"supportsUniformBuffers",{get:function(){return!0},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"supportedExtensions",{get:function(){return this._adapterSupportedExtensions},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"enabledExtensions",{get:function(){return this._deviceEnabledExtensions},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"supportedLimits",{get:function(){return this._adapterSupportedLimits},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"currentLimits",{get:function(){return this._deviceLimits},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"description",{get:function(){return this.name+this.version},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"version",{get:function(){return 1},enumerable:!1,configurable:!0}),t.prototype.getInfo=function(){return{vendor:this._adapterInfo.vendor||"unknown vendor",renderer:this._adapterInfo.architecture||"unknown renderer",version:this._adapterInfo.description||"unknown version"}},Object.defineProperty(t.prototype,"compatibilityMode",{get:function(){return this._compatibilityMode},set:function(e){this._compatibilityMode=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"enableGPUTimingMeasurements",{get:function(){return this._timestampQuery.enable},set:function(e){this._timestampQuery.enable!==e&&(this.gpuTimeInFrameForMainPass=e?new vh:void 0,this._timestampQuery.enable=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"currentSampleCount",{get:function(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount},enumerable:!1,configurable:!0}),t.CreateAsync=function(e,i){void 0===i&&(i={});var r=new t(e,i);return new Promise((function(e){r.initAsync(i.glslangOptions,i.twgslOptions).then((function(){return e(r)}))}))},t.prototype.initAsync=function(e,i){var r,n=this;return this.uniqueId=t._InstanceId++,this._glslangOptions=e,this._twgslOptions=i,this._initGlslang(null!=e?e:null===(r=this._options)||void 0===r?void 0:r.glslangOptions).then((function(e){var r;return n._glslang=e,n._tintWASM=t.UseTWGSL?new em:null,n._tintWASM?n._tintWASM.initTwgsl(null!=i?i:null===(r=n._options)||void 0===r?void 0:r.twgslOptions).then((function(){return navigator.gpu.requestAdapter(n._options)})):navigator.gpu.requestAdapter(n._options)})).then((function(e){var t,i,r;if(e){n._adapter=e,n._adapterSupportedExtensions=[],null===(t=n._adapter.features)||void 0===t||t.forEach((function(e){return n._adapterSupportedExtensions.push(e)})),n._adapterSupportedLimits=n._adapter.limits,n._adapter.requestAdapterInfo().then((function(e){n._adapterInfo=e}));var o=null!==(i=n._options.deviceDescriptor)&&void 0!==i?i:{},a=null!==(r=null==o?void 0:o.requiredFeatures)&&void 0!==r?r:n._options.enableAllFeatures?n._adapterSupportedExtensions:void 0;if(a){for(var s=[],l=0,c=a;l<c.length;l++){var u=c[l];-1!==n._adapterSupportedExtensions.indexOf(u)&&s.push(u)}o.requiredFeatures=s}if(n._options.setMaximumLimits&&!o.requiredLimits)for(var h in o.requiredLimits={},n._adapterSupportedLimits)"minSubgroupSize"!==h&&"maxSubgroupSize"!==h&&(o.requiredLimits[h]=n._adapterSupportedLimits[h]);return o.label="BabylonWebGPUDevice".concat(n.uniqueId),n._adapter.requestDevice(o)}throw"Could not retrieve a WebGPU adapter (adapter is null)."})).then((function(e){var t,i;n._device=e,n._deviceEnabledExtensions=[],null===(t=n._device.features)||void 0===t||t.forEach((function(e){return n._deviceEnabledExtensions.push(e)})),n._deviceLimits=e.limits;var r=-1;n._device.addEventListener("uncapturederror",(function(e){++r<n.numMaxUncapturedErrors?ae.Warn("WebGPU uncaptured error (".concat(r+1,"): ").concat(e.error," - ").concat(e.error.message)):r++===n.numMaxUncapturedErrors&&ae.Warn("WebGPU uncaptured error: too many warnings (".concat(n.numMaxUncapturedErrors,"), no more warnings will be reported to the console for this engine."))})),n._doNotHandleContextLost||null===(i=n._device.lost)||void 0===i||i.then((function(e){n._isDisposed||(n._contextWasLost=!0,ae.Warn("WebGPU context lost. "+e),n.onContextLostObservable.notifyObservers(n),n._restoreEngineAfterContextLost((function(){return y(n,void 0,void 0,(function(){var e,t,i,r,n,o,a,s,l,c;return b(this,(function(u){switch(u.label){case 0:return e=this.snapshotRenderingMode,t=this.snapshotRendering,i=this.disableCacheSamplers,r=this.disableCacheRenderPipelines,n=this.disableCacheBindGroups,o=this.enableGPUTimingMeasurements,[4,this.initAsync(null!==(a=this._glslangOptions)&&void 0!==a?a:null===(s=this._options)||void 0===s?void 0:s.glslangOptions,null!==(l=this._twgslOptions)&&void 0!==l?l:null===(c=this._options)||void 0===c?void 0:c.twgslOptions)];case 1:return u.sent(),this.snapshotRenderingMode=e,this.snapshotRendering=t,this.disableCacheSamplers=i,this.disableCacheRenderPipelines=r,this.disableCacheBindGroups=n,this.enableGPUTimingMeasurements=o,this._currentRenderPass=null,[2]}}))}))})))}))})).then((function(){n._bufferManager=new S_(n,n._device),n._textureHelper=new T_(n,n._device,n._glslang,n._tintWASM,n._bufferManager,n._deviceEnabledExtensions),n._cacheSampler=new R_(n._device),n._cacheBindGroups=new k_(n._device,n._cacheSampler,n),n._timestampQuery=new Z_(n,n._device,n._bufferManager),n._occlusionQuery=n._device.createQuerySet?new $_(n,n._device,n._bufferManager):void 0,n._bundleList=new Q_(n._device),n._snapshotRendering=new tm(n,n._snapshotRenderingMode,n._bundleList),n._ubInvertY=n._bufferManager.createBuffer(new Float32Array([-1,0]),bf.Uniform|bf.CopyDst,"UBInvertY"),n._ubDontInvertY=n._bufferManager.createBuffer(new Float32Array([1,0]),bf.Uniform|bf.CopyDst,"UBDontInvertY"),n.dbgVerboseLogsForFirstFrames&&void 0===n._count&&(n._count=0,ae.Log(["%c frame #"+n._count+" - begin","background: #ffff00"])),n._uploadEncoder=n._device.createCommandEncoder(n._uploadEncoderDescriptor),n._renderEncoder=n._device.createCommandEncoder(n._renderEncoderDescriptor),n._initializeLimits(),n._emptyVertexBuffer=new Nr(n,[0],"",{stride:1,offset:0,size:1,label:"EmptyVertexBuffer"}),n._cacheRenderPipeline=new N_(n._device,n._emptyVertexBuffer),n._depthCullingState=new L_(n._cacheRenderPipeline),n._stencilStateComposer=new F_(n._cacheRenderPipeline),n._stencilStateComposer.stencilGlobal=n._stencilState,n._depthCullingState.depthTest=!0,n._depthCullingState.depthFunc=u.LEQUAL,n._depthCullingState.depthMask=!0,n._textureHelper.setCommandEncoder(n._uploadEncoder),n._clearQuad=new G_(n._device,n,n._emptyVertexBuffer),n._defaultDrawContext=n.createDrawContext(),n._currentDrawContext=n._defaultDrawContext,n._defaultMaterialContext=n.createMaterialContext(),n._currentMaterialContext=n._defaultMaterialContext,n._initializeContextAndSwapChain(),n._initializeMainAttachments(),n.resize()})).catch((function(e){throw ae.Error("A fatal error occurred during WebGPU creation/initialization."),e}))},t.prototype._initGlslang=function(e){return e=e||{},(e=g(g({},t._GLSLslangDefaultOptions),e)).glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?rr.LoadBabylonScriptAsync(e.jsPath).then((function(){return self.glslang(rr.GetBabylonScriptURL(e.wasmPath))})):Promise.reject("gslang is not available.")},t.prototype._initializeLimits=function(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:2*this._deviceLimits.maxSampledTexturesPerShaderStage,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf(vf.TextureCompressionASTC)>=0||void 0,s3tc:this._deviceEnabledExtensions.indexOf(vf.TextureCompressionBC)>=0||void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(vf.TextureCompressionETC2)>=0||void 0,bptc:this._deviceEnabledExtensions.indexOf(vf.TextureCompressionBC)>=0||void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:this._deviceEnabledExtensions.indexOf(vf.RG11B10UFloatRenderable)>=0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(vf.Float32Filterable)>=0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:"undefined"!=typeof BigUint64Array&&-1!==this._deviceEnabledExtensions.indexOf(vf.TimestampQuery)||void 0,supportOcclusionQuery:"undefined"!=typeof BigUint64Array,canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!0,texture2DArrayMaxLayerCount:this._deviceLimits.maxTextureArrayLayers,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_collectUbosUpdatedInFrame:!1}},t.prototype._initializeContextAndSwapChain=function(){if(!this._renderingCanvas)throw"The rendering canvas has not been set!";this._context=this._renderingCanvas.getContext("webgpu"),this._configureContext(),this._colorFormat=this._options.swapChainFormat,this._mainRenderPassWrapper.colorAttachmentGPUTextures=[new f_],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat,this._setColorFormat(this._mainRenderPassWrapper)},t.prototype._initializeMainAttachments=function(){if(this._bufferManager){this.flushFramebuffer(),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};var e,t=new Float32Array([this.getRenderHeight(!0)]);if(this._bufferManager.setSubData(this._ubInvertY,4,t),this._bufferManager.setSubData(this._ubDontInvertY,4,t),this._options.antialias){var i={label:"Texture_MainColor_".concat(this._mainTextureExtends.width,"x").concat(this._mainTextureExtends.height,"_antialiasing"),size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:Ef.E2d,format:this._options.swapChainFormat,usage:Sf.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(i),e=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:Ef.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new J(0,0,0,1),loadOp:Zf.Clear,storeOp:Jf.Store}]}else e=[{view:void 0,clearValue:new J(0,0,0,1),loadOp:Zf.Clear,storeOp:Jf.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?Cf.Depth24PlusStencil8:Cf.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper);var r={label:"Texture_MainDepthStencil_".concat(this._mainTextureExtends.width,"x").concat(this._mainTextureExtends.height),size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:Ef.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:Sf.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(r);var n={view:this._depthTexture.createView({label:"TextureView_MainDepthStencil_".concat(this._mainTextureExtends.width,"x").concat(this._mainTextureExtends.height),dimension:Ef.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:Zf.Clear,depthStoreOp:Jf.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?Zf.Clear:void 0,stencilStoreOp:this.isStencilEnable?Jf.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:e,depthStencilAttachment:n}}},t.prototype._sharedInit=function(t){e.prototype._sharedInit.call(this,t),Eo(this,t,this._creationOptions)},t.prototype._configureContext=function(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:Sf.RenderAttachment|Sf.CopySrc,alphaMode:this.premultipliedAlpha?e_.Premultiplied:e_.Opaque})},t.prototype.resizeImageBitmap=function(e,t,i){return Co(this,e,t,i)},t.prototype._createImageBitmapFromSource=function(e,t){return Ao(this,e,t)},t.prototype.switchFullscreen=function(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)},t.prototype.enterFullscreen=function(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&Ro(this._renderingCanvas))},t.prototype.exitFullscreen=function(){this.isFullscreen&&Po()},t.prototype.enterPointerlock=function(){this._renderingCanvas&&Io(this._renderingCanvas)},t.prototype.exitPointerlock=function(){Mo()},t.prototype._rebuildBuffers=function(){e.prototype._rebuildBuffers.call(this);for(var t=0,i=this._storageBuffers;t<i.length;t++){var r=i[t];r.getBuffer().engineId!==this.uniqueId&&r._rebuild()}},t.prototype._restoreEngineAfterContextLost=function(t){N_.ResetCache(),k_.ResetCache();var i=function(e){for(var t,i=0,r=e;i<r.length;i++){for(var n=r[i],o=0,a=n.meshes;o<a.length;o++){var s=a[o].subMeshes;if(s)for(var l=0,c=s;l<c.length;l++)c[l]._drawWrappers=[]}for(var u=0,h=n.materials;u<h.length;u++)null===(t=h[u]._materialContext)||void 0===t||t.reset()}};i(this.scenes),i(this._virtualScenes);for(var r=[],n=0,o=this._uniformBuffers;n<o.length;n++){var a=o[n];a.name.indexOf("leftOver")<0&&r.push(a)}this._uniformBuffers=r,e.prototype._restoreEngineAfterContextLost.call(this,t)},t.prototype.setDepthStencilTexture=function(e,t,i,r){void 0!==e&&(i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,r):this._setTexture(e,null,void 0,void 0,r))},t.prototype.setTextureFromPostProcess=function(e,t,i){var r,n=null;t&&(t._forcedOutputTexture?n=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(n=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,null!==(r=null==n?void 0:n.texture)&&void 0!==r?r:null,i)},t.prototype.setTextureFromPostProcessOutput=function(e,t,i){var r,n;this._bindTexture(e,null!==(n=null===(r=null==t?void 0:t._outputTexture)||void 0===r?void 0:r.texture)&&void 0!==n?n:null,i)},t.prototype.setSize=function(t,i,r){return void 0===r&&(r=!1),!!e.prototype.setSize.call(this,t,i,r)&&(this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&ae.Log(["frame #"+this._count+" - setSize -",t,i])),this._initializeMainAttachments(),this.snapshotRendering&&this.snapshotRenderingReset(),!0)},t.prototype._getShaderProcessor=function(e){return e===pt.WGSL?this._shaderProcessorWGSL:this._shaderProcessor},t.prototype._getShaderProcessingContext=function(e){return new s_(e)},t.prototype._currentPassIsMainPass=function(){return null===this._currentRenderTarget},t.prototype._getCurrentRenderPass=function(){return this._currentRenderTarget&&!this._currentRenderPass?this._startRenderTargetRenderPass(this._currentRenderTarget,!1,null,!1,!1):this._currentRenderPass||this._startMainRenderPass(!1),this._currentRenderPass},t.prototype._getCurrentRenderPassWrapper=function(){return this._currentRenderTarget?this._rttRenderPassWrapper:this._mainRenderPassWrapper},t.prototype.applyStates=function(){this._stencilStateComposer.apply(),this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend)},t.prototype.wipeCaches=function(e){this.preventCacheWipeBetweenFrames&&!e||(this._forceEnableEffect=!0,this._currentIndexBuffer=null,this._currentOverrideVertexBuffers=null,this._cacheRenderPipeline.setBuffers(null,null,null),e&&(this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=u.LEQUAL,this._alphaState.reset(),this._alphaMode=u.ALPHA_ADD,this._alphaEquation=u.ALPHA_DISABLE,this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters),this._cacheRenderPipeline.setAlphaBlendEnabled(!1),this.setColorWrite(!0)),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)},t.prototype.setColorWrite=function(e){this._colorWriteLocal=e,this._cacheRenderPipeline.setWriteMask(e?15:0)},t.prototype.getColorWrite=function(){return this._colorWriteLocal},t.prototype._mustUpdateViewport=function(){var e=this._viewportCached.x,t=this._viewportCached.y,i=this._viewportCached.z,r=this._viewportCached.w,n=this._viewportsCurrent.x!==e||this._viewportsCurrent.y!==t||this._viewportsCurrent.w!==i||this._viewportsCurrent.h!==r;return n&&(this._viewportsCurrent.x=this._viewportCached.x,this._viewportsCurrent.y=this._viewportCached.y,this._viewportsCurrent.w=this._viewportCached.z,this._viewportsCurrent.h=this._viewportCached.w),n},t.prototype._applyViewport=function(e){var t=Math.floor(this._viewportCached.x),i=Math.floor(this._viewportCached.z),r=Math.floor(this._viewportCached.w),n=Math.floor(this._viewportCached.y);this._currentRenderTarget||(n=this.getRenderHeight(!0)-n-r),e?e.addItem(new z_(t,n,i,r)):this._getCurrentRenderPass().setViewport(t,n,i,r,0,1),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&ae.Log(["frame #"+this._count+" - viewport applied - (",this._viewportCached.x,this._viewportCached.y,this._viewportCached.z,this._viewportCached.w,") current pass is main pass="+this._currentPassIsMainPass()]))},t.prototype._viewport=function(e,t,i,r){this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=r},t.prototype._mustUpdateScissor=function(){var e=this._scissorCached.x,t=this._scissorCached.y,i=this._scissorCached.z,r=this._scissorCached.w,n=this._scissorsCurrent.x!==e||this._scissorsCurrent.y!==t||this._scissorsCurrent.w!==i||this._scissorsCurrent.h!==r;return n&&(this._scissorsCurrent.x=this._scissorCached.x,this._scissorsCurrent.y=this._scissorCached.y,this._scissorsCurrent.w=this._scissorCached.z,this._scissorsCurrent.h=this._scissorCached.w),n},t.prototype._applyScissor=function(e){var t=this._currentRenderTarget?this._scissorCached.y:this.getRenderHeight()-this._scissorCached.w-this._scissorCached.y;e?e.addItem(new W_(this._scissorCached.x,t,this._scissorCached.z,this._scissorCached.w)):this._getCurrentRenderPass().setScissorRect(this._scissorCached.x,t,this._scissorCached.z,this._scissorCached.w),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&ae.Log(["frame #"+this._count+" - scissor applied - (",this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w,") current pass is main pass="+this._currentPassIsMainPass()]))},t.prototype._scissorIsActive=function(){return 0!==this._scissorCached.x||0!==this._scissorCached.y||0!==this._scissorCached.z||0!==this._scissorCached.w},t.prototype.enableScissor=function(e,t,i,r){this._scissorCached.x=e,this._scissorCached.y=t,this._scissorCached.z=i,this._scissorCached.w=r},t.prototype.disableScissor=function(){this._scissorCached.x=this._scissorCached.y=this._scissorCached.z=this._scissorCached.w=0,this._scissorsCurrent.x=this._scissorsCurrent.y=this._scissorsCurrent.w=this._scissorsCurrent.h=0},t.prototype._mustUpdateStencilRef=function(){var e=this._stencilStateComposer.funcRef!==this._stencilRefsCurrent;return e&&(this._stencilRefsCurrent=this._stencilStateComposer.funcRef),e},t.prototype._applyStencilRef=function(e){var t,i;e?e.addItem(new H_(null!==(t=this._stencilStateComposer.funcRef)&&void 0!==t?t:0)):this._getCurrentRenderPass().setStencilReference(null!==(i=this._stencilStateComposer.funcRef)&&void 0!==i?i:0)},t.prototype._mustUpdateBlendColor=function(){var e=this._alphaState._blendConstants,t=e[0]!==this._blendColorsCurrent[0]||e[1]!==this._blendColorsCurrent[1]||e[2]!==this._blendColorsCurrent[2]||e[3]!==this._blendColorsCurrent[3];return t&&(this._blendColorsCurrent[0]=e[0],this._blendColorsCurrent[1]=e[1],this._blendColorsCurrent[2]=e[2],this._blendColorsCurrent[3]=e[3]),t},t.prototype._applyBlendColor=function(e){e?e.addItem(new X_(this._alphaState._blendConstants.slice())):this._getCurrentRenderPass().setBlendConstant(this._alphaState._blendConstants)},t.prototype._resetRenderPassStates=function(){this._viewportsCurrent.x=this._viewportsCurrent.y=this._viewportsCurrent.w=this._viewportsCurrent.h=0,this._scissorsCurrent.x=this._scissorsCurrent.y=this._scissorsCurrent.w=this._scissorsCurrent.h=0,this._stencilRefsCurrent=-1,this._blendColorsCurrent[0]=this._blendColorsCurrent[1]=this._blendColorsCurrent[2]=this._blendColorsCurrent[3]=null},t.prototype.clear=function(e,t,i,r){void 0===r&&(r=!1),e&&void 0===e.a&&(e.a=1);var n=this._scissorIsActive();this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&ae.Log(["frame #"+this._count+" - clear - backBuffer=",t," depth=",i," stencil=",r," scissor is active=",n])),this._currentRenderTarget?n?(this._currentRenderPass||this._startRenderTargetRenderPass(this._currentRenderTarget,!1,t?e:null,i,r),this._applyScissor(this.compatibilityMode?null:this._bundleList),this._clearFullQuad(t?e:null,i,r)):(this._currentRenderPass&&this._endCurrentRenderPass(),this._startRenderTargetRenderPass(this._currentRenderTarget,!0,t?e:null,i,r)):(this._currentRenderPass&&n||this._startMainRenderPass(!n,t?e:null,i,r),n&&(this._applyScissor(this.compatibilityMode?null:this._bundleList),this._clearFullQuad(t?e:null,i,r)))},t.prototype._clearFullQuad=function(e,t,i){var r,n,o=this.compatibilityMode?this._getCurrentRenderPass():null;this._clearQuad.setColorFormat(this._colorFormat),this._clearQuad.setDepthStencilFormat(this._depthTextureFormat),this._clearQuad.setMRTAttachments(null!==(r=this._cacheRenderPipeline.mrtAttachments)&&void 0!==r?r:[],null!==(n=this._cacheRenderPipeline.mrtTextureArray)&&void 0!==n?n:[],this._cacheRenderPipeline.mrtTextureCount),this.compatibilityMode?o.setStencilReference(this._clearStencilValue):this._bundleList.addItem(new H_(this._clearStencilValue));var a=this._clearQuad.clear(o,e,t,i,this.currentSampleCount);this.compatibilityMode?this._applyStencilRef(null):(this._bundleList.addBundle(a),this._applyStencilRef(this._bundleList),this._reportDrawCall())},t.prototype.createVertexBuffer=function(e,t,i){var r;return r=e instanceof Array?new Float32Array(e):e instanceof ArrayBuffer?new Uint8Array(e):e,this._bufferManager.createBuffer(r,bf.Vertex|bf.CopyDst,i)},t.prototype.createDynamicVertexBuffer=function(e,t){return this.createVertexBuffer(e,void 0,t)},t.prototype.createIndexBuffer=function(e,t,i){var r,n=!0;e instanceof Uint32Array||e instanceof Int32Array?r=e:e instanceof Uint16Array?(r=e,n=!1):e.length>65535?r=new Uint32Array(e):(r=new Uint16Array(e),n=!1);var o=this._bufferManager.createBuffer(r,bf.Index|bf.CopyDst,i);return o.is32Bits=n,o},t.prototype.updateDynamicIndexBuffer=function(e,t,i){void 0===i&&(i=0);var r,n=e;r=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._bufferManager.setSubData(n,i,r)},t.prototype.updateDynamicVertexBuffer=function(e,t,i,r){var n,o=e;void 0===i&&(i=0),void 0===r?r=(n=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t).byteLength:n=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,this._bufferManager.setSubData(o,i,n,0,r)},t.prototype._createBuffer=function(e,t,i){var r;r=e instanceof Array?new Float32Array(e):e instanceof ArrayBuffer?new Uint8Array(e):e;var n=0;return t&u.BUFFER_CREATIONFLAG_READ&&(n|=bf.CopySrc),t&u.BUFFER_CREATIONFLAG_WRITE&&(n|=bf.CopyDst),t&u.BUFFER_CREATIONFLAG_UNIFORM&&(n|=bf.Uniform),t&u.BUFFER_CREATIONFLAG_VERTEX&&(n|=bf.Vertex),t&u.BUFFER_CREATIONFLAG_INDEX&&(n|=bf.Index),t&u.BUFFER_CREATIONFLAG_STORAGE&&(n|=bf.Storage),t&u.BUFFER_CREATIONFLAG_INDIRECT&&(n|=bf.Indirect),this._bufferManager.createBuffer(r,n,i)},t.prototype.bindBuffersDirectly=function(){throw"Not implemented on WebGPU"},t.prototype.updateAndBindInstancesBuffer=function(){throw"Not implemented on WebGPU"},t.prototype.unbindInstanceAttributes=function(){},t.prototype.bindBuffers=function(e,t,i,r){this._currentIndexBuffer=t,this._currentOverrideVertexBuffers=null!=r?r:null,this._cacheRenderPipeline.setBuffers(e,t,this._currentOverrideVertexBuffers)},t.prototype._releaseBuffer=function(e){return this._bufferManager.releaseBuffer(e)},t.prototype.createUniformBuffer=function(e,t){var i;return i=e instanceof Array?new Float32Array(e):e,this._bufferManager.createBuffer(i,bf.Uniform|bf.CopyDst,t)},t.prototype.createDynamicUniformBuffer=function(e,t){return this.createUniformBuffer(e,t)},t.prototype.updateUniformBuffer=function(e,t,i,r){void 0===i&&(i=0);var n,o=e;void 0===r?r=(n=t instanceof Float32Array?t:new Float32Array(t)).byteLength:n=t instanceof Float32Array?t:new Float32Array(t),this._bufferManager.setSubData(o,i,n,0,r)},t.prototype.bindUniformBufferBase=function(e,t,i){this._currentDrawContext.setBuffer(i,e)},t.prototype.bindUniformBlock=function(){},t.prototype.createEffect=function(e,t,i,r,n,o,a,s,l,c){var u,h;void 0===c&&(c=pt.GLSL);var d="string"==typeof e?e:e.vertexToken||e.vertexSource||e.vertexElement||e.vertex,p="string"==typeof e?e:e.fragmentToken||e.fragmentSource||e.fragmentElement||e.fragment,f=this._getGlobalDefines(),_=null!==(u=null!=n?n:t.defines)&&void 0!==u?u:"";f&&(_+="\n"+f);var m=d+"+"+p+"@"+_;if(this._compiledEffects[m]){var g=this._compiledEffects[m];return a&&g.isReady()&&a(g),g}var v=new Ei(e,t,i,r,this,n,o,a,s,l,m,null!==(h=t.shaderLanguage)&&void 0!==h?h:c);return this._compiledEffects[m]=v,v},t.prototype._compileRawShaderToSpirV=function(e,t){return this._glslang.compileGLSL(e,t)},t.prototype._compileShaderToSpirV=function(e,t,i,r){return this._compileRawShaderToSpirV(r+(i?i+"\n":"")+e,t)},t.prototype._getWGSLShader=function(e,t,i){return(i=i?"//"+i.split("\n").join("\n//")+"\n":"")+e},t.prototype._createPipelineStageDescriptor=function(e,t,i,r,n){return this._tintWASM&&i===pt.GLSL&&(e=this._tintWASM.convertSpirV2WGSL(e,r),t=this._tintWASM.convertSpirV2WGSL(t,n)),{vertexStage:{module:this._device.createShaderModule({code:e}),entryPoint:"main"},fragmentStage:{module:this._device.createShaderModule({code:t}),entryPoint:"main"}}},t.prototype._compileRawPipelineStageDescriptor=function(e,t,i){var r=e.indexOf(om)>=0,n=t.indexOf(om)>=0,o=i===pt.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,a=i===pt.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(o,a,i,r,n)},t.prototype._compilePipelineStageDescriptor=function(e,t,i,r){this.onBeforeShaderCompilationObservable.notifyObservers(this);var n=e.indexOf(om)>=0,o=t.indexOf(om)>=0,a="#version 450\n",s=r===pt.GLSL?this._compileShaderToSpirV(e,"vertex",i,a):this._getWGSLShader(e,"vertex",i),l=r===pt.GLSL?this._compileShaderToSpirV(t,"fragment",i,a):this._getWGSLShader(t,"fragment",i),c=this._createPipelineStageDescriptor(s,l,r,n,o);return this.onAfterShaderCompilationObservable.notifyObservers(this),c},t.prototype.createRawShaderProgram=function(){throw"Not available on WebGPU"},t.prototype.createShaderProgram=function(){throw"Not available on WebGPU"},t.prototype.inlineShaderCode=function(e){var t=new tf(e);return t.debug=!1,t.processCode(),t.code},t.prototype.createPipelineContext=function(e){return new o_(e,this)},t.prototype.createMaterialContext=function(){return new B_},t.prototype.createDrawContext=function(){return new U_(this._bufferManager)},t.prototype._preparePipelineContext=function(e,t,i,r,n,o,a,s){var l=e,c=l.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(ae.Log(["defines",s]),ae.Log(t),ae.Log(i),ae.Log("***********************************************")),l.sources={fragment:i,vertex:t,rawVertex:n,rawFragment:o},l.stages=r?this._compileRawPipelineStageDescriptor(t,i,c):this._compilePipelineStageDescriptor(t,i,s,c)},t.prototype.getAttributes=function(e,t){for(var i=new Array(t.length),r=e,n=0;n<t.length;n++){var o=t[n],a=r.shaderProcessingContext.availableAttributes[o];void 0!==a&&(i[n]=a)}return i},t.prototype.enableEffect=function(e){if(e){if(fr(e)){if(!e.effect||e.effect===this._currentEffect&&e.materialContext===this._currentMaterialContext&&e.drawContext===this._currentDrawContext&&!this._forceEnableEffect){if(!e.effect&&this.dbgShowEmptyEnableEffectCalls)throw ae.Log(["drawWrapper=",e]),"Invalid call to enableEffect: the effect property is empty!";return}if(this._currentEffect=e.effect,this._currentMaterialContext=e.materialContext,this._currentDrawContext=e.drawContext,this._counters.numEnableDrawWrapper++,!this._currentMaterialContext)throw ae.Log(["drawWrapper=",e]),"Invalid call to enableEffect: the materialContext property is empty!"}else this._currentEffect=e,this._currentMaterialContext=this._defaultMaterialContext,this._currentDrawContext=this._defaultDrawContext,this._counters.numEnableEffects++,this.dbgLogIfNotDrawWrapper&&ae.Warn("enableEffect has been called with an Effect and not a Wrapper! effect.uniqueId=".concat(e.uniqueId,", effect.name=").concat(e.name,", effect.name.vertex=").concat("string"==typeof e.name?"":e.name.vertex,", effect.name.fragment=").concat("string"==typeof e.name?"":e.name.fragment),10);this._stencilStateComposer.stencilMaterial=void 0,this._forceEnableEffect=!1,this._currentEffect.onBind&&this._currentEffect.onBind(this._currentEffect),this._currentEffect._onBindObservable&&this._currentEffect._onBindObservable.notifyObservers(this._currentEffect)}},t.prototype._releaseEffect=function(e){this._compiledEffects[e._key]&&(delete this._compiledEffects[e._key],this._deletePipelineContext(e.getPipelineContext()))},t.prototype.releaseEffects=function(){for(var e in this._compiledEffects){var t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}},t.prototype._deletePipelineContext=function(e){e&&yi(e)},Object.defineProperty(t.prototype,"needPOTTextures",{get:function(){return!1},enumerable:!1,configurable:!0}),t.prototype._createHardwareTexture=function(){return new f_},t.prototype._releaseTexture=function(e){var t=this._internalTexturesCache.indexOf(e);-1!==t&&this._internalTexturesCache.splice(t,1),this._textureHelper.releaseTexture(e)},t.prototype._getRGBABufferInternalSizedFormat=function(){return u.TEXTUREFORMAT_RGBA},t.prototype.updateTextureComparisonFunction=function(e,t){e._comparisonFunction=t},t.prototype._createInternalTexture=function(e,t,i,r){var n,o,a;void 0===i&&(i=!0),void 0===r&&(r=Ti.Unknown);var s={};void 0!==t&&"object"==typeof t?(s.generateMipMaps=t.generateMipMaps,s.type=void 0===t.type?u.TEXTURETYPE_UNSIGNED_INT:t.type,s.samplingMode=void 0===t.samplingMode?u.TEXTURE_TRILINEAR_SAMPLINGMODE:t.samplingMode,s.format=void 0===t.format?u.TEXTUREFORMAT_RGBA:t.format,s.samples=null!==(n=t.samples)&&void 0!==n?n:1,s.creationFlags=null!==(o=t.creationFlags)&&void 0!==o?o:0,s.useSRGBBuffer=null!==(a=t.useSRGBBuffer)&&void 0!==a&&a,s.label=t.label):(s.generateMipMaps=t,s.type=u.TEXTURETYPE_UNSIGNED_INT,s.samplingMode=u.TEXTURE_TRILINEAR_SAMPLINGMODE,s.format=u.TEXTUREFORMAT_RGBA,s.samples=1,s.creationFlags=0,s.useSRGBBuffer=!1),(s.type!==u.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(s.type!==u.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(s.samplingMode=u.TEXTURE_NEAREST_SAMPLINGMODE),s.type!==u.TEXTURETYPE_FLOAT||this._caps.textureFloat||(s.type=u.TEXTURETYPE_UNSIGNED_INT,ae.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));var l=new Pi(this,r),c=e.width||e,h=e.height||e,d=e.depth||0,p=e.layers||0;return l.baseWidth=c,l.baseHeight=h,l.width=c,l.height=h,l.depth=d||p,l.isReady=!0,l.samples=s.samples,l.generateMipMaps=!!s.generateMipMaps,l.samplingMode=s.samplingMode,l.type=s.type,l.format=s.format,l.is2DArray=p>0,l.is3D=d>0,l._cachedWrapU=u.TEXTURE_CLAMP_ADDRESSMODE,l._cachedWrapV=u.TEXTURE_CLAMP_ADDRESSMODE,l._useSRGBBuffer=s.useSRGBBuffer,l.label=s.label,this._internalTexturesCache.push(l),i||this._textureHelper.createGPUTextureForInternalTexture(l,c,h,p||1,s.creationFlags),l},t.prototype.createTexture=function(e,t,i,r,n,o,a,s,l,c,h,d,p,f,_){var m=this;return void 0===n&&(n=u.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null),void 0===l&&(l=null),void 0===c&&(c=null),void 0===h&&(h=null),this._createTextureBase(e,t,i,r,n,o,a,(function(e,t,i,r,n,o,a,s){var l,h=r;if(e.baseWidth=h.width,e.baseHeight=h.height,e.width=h.width,e.height=h.height,e.format=-1!==e.format?e.format:null!=c?c:u.TEXTUREFORMAT_RGBA,e.type=-1!==e.type?e.type:u.TEXTURETYPE_UNSIGNED_BYTE,e._creationFlags=null!=f?f:0,s(e.width,e.height,h,t,e,(function(){})),null===(l=e._hardwareTexture)||void 0===l?void 0:l.underlyingResource)o||a||m._generateMipmaps(e,m._uploadEncoder);else{var d=m._textureHelper.createGPUTextureForInternalTexture(e,h.width,h.height,void 0,f);p_.IsImageBitmap(h)&&(m._textureHelper.updateTexture(h,e,h.width,h.height,e.depth,d.format,0,0,n,!1,0,0),o||a||m._generateMipmaps(e,m._uploadEncoder))}i&&i.removePendingData(e),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}),(function(){return!1}),s,l,c,h,d,p,_)},t.prototype.wrapWebGPUTexture=function(e){var t=new f_(e),i=new Pi(this,Ti.Unknown,!0);return i._hardwareTexture=t,i.isReady=!0,i},t.prototype.wrapWebGLTexture=function(){throw new Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")},t.prototype.generateMipMapsForCubemap=function(e){var t;e.generateMipMaps&&((null===(t=e._hardwareTexture)||void 0===t?void 0:t.underlyingResource)||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e))},t.prototype._getUseSRGBBuffer=function(e,t){return e&&this._caps.supportSRGBBuffers},t.prototype._unpackFlipY=function(e){},t.prototype.updateTextureSamplingMode=function(e,t,i){void 0===i&&(i=!1),i&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e},t.prototype.updateTextureWrappingMode=function(e,t,i,r){void 0===i&&(i=null),void 0===r&&(r=null),null!==t&&(e._cachedWrapU=t),null!==i&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==r&&(e._cachedWrapR=r)},t.prototype.updateTextureDimensions=function(e,t,i,r){if(void 0===r&&(r=1),e._hardwareTexture&&(e.width!==t||e.height!==i||e.depth!==r)){var n=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,r,n)}},t.prototype._setInternalTexture=function(e,t,i){if(i=null!=i?i:e,this._currentEffect){var r=this._currentEffect._pipelineContext.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),r&&r.autoBindSampler){var n=i+n_.AutoSamplerSuffix;this._currentMaterialContext.setSampler(n,t)}}},t.prototype.createPrefilteredCubeTexture=function(e,t,i,r,n,o,a,s,l){return void 0===n&&(n=null),void 0===o&&(o=null),void 0===s&&(s=null),void 0===l&&(l=!0),this.createCubeTexture(e,t,null,!1,(function(e){if(e){var t=e.texture;l?e.info.sphericalPolynomial&&(t._sphericalPolynomial=e.info.sphericalPolynomial):t._sphericalPolynomial=new Sp,t._source=Ti.CubePrefiltered,n&&n(t)}else n&&n(null)}),o,a,s,l,i,r)},t.prototype.setTexture=function(e,t,i,r){this._setTexture(e,i,!1,!1,r,r)},t.prototype.setTextureArray=function(e,t,i,r){for(var n=0;n<i.length;n++)this._setTexture(-1,i[n],!0,!1,r+n.toString(),r)},t.prototype._setTexture=function(e,t,i,r,n,o){if(void 0===i&&(i=!1),void 0===r&&(r=!1),void 0===n&&(n=""),o=null!=o?o:n,this._currentEffect){if(!t)return this._currentMaterialContext.setTexture(n,null),!1;if(t.video)t.update();else if(t.delayLoadState===u.DELAYLOADSTATE_NOTLOADED)return t.delayLoad(),!1;var a=null;if((a=r?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture)&&!a.isMultiview){if(a.isCube&&a._cachedCoordinatesMode!==t.coordinatesMode){a._cachedCoordinatesMode=t.coordinatesMode;var s=t.coordinatesMode!==u.TEXTURE_CUBIC_MODE&&t.coordinatesMode!==u.TEXTURE_SKYBOX_MODE?u.TEXTURE_WRAP_ADDRESSMODE:u.TEXTURE_CLAMP_ADDRESSMODE;t.wrapU=s,t.wrapV=s}a._cachedWrapU=t.wrapU,a._cachedWrapV=t.wrapV,a.is3D&&(a._cachedWrapR=t.wrapR),this._setAnisotropicLevel(0,a,t.anisotropicFilteringLevel)}this._setInternalTexture(n,a,o)}else this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&ae.Log(["frame #"+this._count+" - _setTexture called with a null _currentEffect! texture=",t]));return!0},t.prototype._setAnisotropicLevel=function(e,t,i){t._cachedAnisotropicFilteringLevel!==i&&(t._cachedAnisotropicFilteringLevel=Math.min(i,this._caps.maxAnisotropy))},t.prototype._bindTexture=function(e,t,i){void 0!==e&&this._setInternalTexture(i,t)},t.prototype.generateMipmaps=function(e){this._generateMipmaps(e)},t.prototype._generateMipmaps=function(e,t){t=null!=t?t:this._renderEncoder;var i=e._hardwareTexture;if(i){t===this._renderEncoder&&this._endCurrentRenderPass();var r=e._hardwareTexture.format,n=p_.ComputeNumMipmapLevels(e.width,e.height);this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&ae.Log("frame #"+this._count+" - generate mipmaps - width="+e.width+", height="+e.height+", isCube="+e.isCube+", command encoder="+(t===this._renderEncoder?"render":"copy"))),e.isCube?this._textureHelper.generateCubeMipmaps(i,r,n,t):this._textureHelper.generateMipmaps(i,r,n,0,e.is3D,t)}},t.prototype.updateTextureData=function(e,t,i,r,n,o,a,s,l){var c;void 0===a&&(a=0),void 0===s&&(s=0),void 0===l&&(l=!1);var u=e._hardwareTexture;(null===(c=e._hardwareTexture)||void 0===c?void 0:c.underlyingResource)||(u=this._textureHelper.createGPUTextureForInternalTexture(e));var h=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(h,e,n,o,e.depth,u.format,a,s,e.invertY,!1,i,r),l&&this._generateMipmaps(e)},t.prototype._uploadCompressedDataToTextureDirectly=function(e,t,i,r,n,o,a){var s;void 0===o&&(o=0),void 0===a&&(a=0);var l=e._hardwareTexture;(null===(s=e._hardwareTexture)||void 0===s?void 0:s.underlyingResource)||(e.format=t,l=this._textureHelper.createGPUTextureForInternalTexture(e,i,r));var c=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);this._textureHelper.updateTexture(c,e,i,r,e.depth,l.format,o,a,!1,!1,0,0)},t.prototype._uploadDataToTextureDirectly=function(e,t,i,r,n,o){var a;void 0===i&&(i=0),void 0===r&&(r=0),void 0===o&&(o=!1);var s=Math.round(Math.log(e.width)*Math.LOG2E),l=Math.round(Math.log(e.height)*Math.LOG2E),c=o?e.width:Math.pow(2,Math.max(s-r,0)),u=o?e.height:Math.pow(2,Math.max(l-r,0)),h=e._hardwareTexture;(null===(a=e._hardwareTexture)||void 0===a?void 0:a.underlyingResource)||(h=this._textureHelper.createGPUTextureForInternalTexture(e,c,u));var d=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(d,e,c,u,e.depth,h.format,i,r,e.invertY,!1,0,0)},t.prototype._uploadArrayBufferViewToTexture=function(e,t,i,r){void 0===i&&(i=0),void 0===r&&(r=0),this._uploadDataToTextureDirectly(e,t,i,r)},t.prototype._uploadImageToTexture=function(e,t,i,r){var n;void 0===i&&(i=0),void 0===r&&(r=0);var o=e._hardwareTexture;if((null===(n=e._hardwareTexture)||void 0===n?void 0:n.underlyingResource)||(o=this._textureHelper.createGPUTextureForInternalTexture(e)),t instanceof HTMLImageElement)throw"WebGPU engine: HTMLImageElement not supported in _uploadImageToTexture!";var a=t,s=Math.ceil(e.width/(1<<r)),l=Math.ceil(e.height/(1<<r));this._textureHelper.updateTexture(a,e,s,l,e.depth,o.format,i,r,e.invertY,!1,0,0)},t.prototype.readPixels=function(e,t,i,r,n,o){void 0===n&&(n=!0),void 0===o&&(o=!0);var a=this._getCurrentRenderPassWrapper().colorAttachmentGPUTextures[0];if(!a)return Promise.resolve(new Uint8Array(0));var s=a.underlyingResource,l=a.format;return s?(o&&this.flushFramebuffer(),this._textureHelper.readPixels(s,e,t,i,r,l)):Promise.resolve(new Uint8Array(0))},t.prototype._measureFps=function(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0},Object.defineProperty(t.prototype,"performanceMonitor",{get:function(){return this._performanceMonitor},enumerable:!1,configurable:!0}),t.prototype.beginFrame=function(){this._measureFps(),e.prototype.beginFrame.call(this)},t.prototype.endFrame=function(){if(this._endCurrentRenderPass(),this._snapshotRendering.endFrame(),this._timestampQuery.endFrame(this._renderEncoder),this._timestampIndex=0,this.flushFramebuffer(),this._textureHelper.destroyDeferredTextures(),this._bufferManager.destroyDeferredBuffers(),this._features._collectUbosUpdatedInFrame){if(this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),!this._count||this._count<this.dbgVerboseLogsNumFrames)){var t=[];for(var i in Or._UpdatedUbosInFrame)t.push(i+":"+Or._UpdatedUbosInFrame[i]);ae.Log(["frame #"+this._count+" - updated ubos -",t.join(", ")])}Or._UpdatedUbosInFrame={}}this.countersLastFrame.numEnableEffects=this._counters.numEnableEffects,this.countersLastFrame.numEnableDrawWrapper=this._counters.numEnableDrawWrapper,this.countersLastFrame.numBundleCreationNonCompatMode=this._counters.numBundleCreationNonCompatMode,this.countersLastFrame.numBundleReuseNonCompatMode=this._counters.numBundleReuseNonCompatMode,this._counters.numEnableEffects=0,this._counters.numEnableDrawWrapper=0,this._counters.numBundleCreationNonCompatMode=0,this._counters.numBundleReuseNonCompatMode=0,this._cacheRenderPipeline.endFrame(),this._cacheBindGroups.endFrame(),this._pendingDebugCommands.length=0,this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),this._count<this.dbgVerboseLogsNumFrames&&ae.Log(["%c frame #"+this._count+" - end","background: #ffff00"]),this._count<this.dbgVerboseLogsNumFrames&&(this._count++,this._count!==this.dbgVerboseLogsNumFrames&&ae.Log(["%c frame #"+this._count+" - begin","background: #ffff00"]))),e.prototype.endFrame.call(this)},t.prototype.extractDriverInfo=function(){return""},t.prototype.flushFramebuffer=function(){this._endCurrentRenderPass(),this._commandBuffers[0]=this._uploadEncoder.finish(),this._commandBuffers[1]=this._renderEncoder.finish(),this._device.queue.submit(this._commandBuffers),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._timestampQuery.startFrame(this._uploadEncoder),this._textureHelper.setCommandEncoder(this._uploadEncoder),this._bundleList.reset()},t.prototype._currentFrameBufferIsDefaultFrameBuffer=function(){return this._currentPassIsMainPass()},t.prototype._startRenderTargetRenderPass=function(e,t,i,r,n){var o,a,s,l,c,h,d,p;this._endCurrentRenderPass();var f=e,_=f._depthStencilTexture,m=null==_?void 0:_._hardwareTexture,v=null==m?void 0:m.underlyingResource,y=null==m?void 0:m.getMSAATexture(),b=null==v?void 0:v.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor),T=null==y?void 0:y.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor),E=!!m&&p_.HasStencilAspect(m.format),S=[];this.useReverseDepthBuffer&&this.setDepthFunctionToGreaterOrEqual();var x=am;i&&(x.r=255*i.r,x.g=255*i.g,x.b=255*i.b,x.a=255*i.a);var A=t&&i,C=t&&r,R=t&&n;if(f._attachments&&f.isMulti){this._mrtAttachments&&0!==this._mrtAttachments.length||(this._mrtAttachments=f._defaultAttachments);for(var P=0;P<this._mrtAttachments.length;++P){var I=this._mrtAttachments[P],M=f.textures[P],O=null==M?void 0:M._hardwareTexture,D=null==O?void 0:O.underlyingResource;if(O&&D){var N=O.getMSAATexture(P),F=null!==(a=null===(o=f.layerIndices)||void 0===o?void 0:o[P])&&void 0!==a?a:0,L=null!==(l=null===(s=f.faceIndices)||void 0===s?void 0:s[P])&&void 0!==l?l:0,w=g(g({},this._rttRenderPassWrapper.colorAttachmentViewDescriptor),{dimension:M.is3D?xf.E3d:xf.E2d,format:O.format,baseArrayLayer:M.isCube?6*F+L:M.is3D?0:F}),B=g(g({},this._rttRenderPassWrapper.colorAttachmentViewDescriptor),{dimension:M.is3D?xf.E3d:xf.E2d,format:O.format,baseArrayLayer:0}),U=M.type===u.TEXTURETYPE_UNSIGNED_INTEGER||M.type===u.TEXTURETYPE_UNSIGNED_SHORT,V=D.createView(w),k=null==N?void 0:N.createView(B);S.push({view:k||V,resolveTarget:N?V:void 0,depthSlice:M.is3D?F:void 0,clearValue:0!==I&&A?U?x:i:void 0,loadOp:0!==I&&A?Zf.Clear:Zf.Load,storeOp:Jf.Store})}}this._cacheRenderPipeline.setMRT(f.textures,this._mrtAttachments.length),this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments)}else if(H=f.texture){var G=H._hardwareTexture,z=G.underlyingResource,W=void 0;f.is3D&&(W=this._rttRenderPassWrapper.colorAttachmentViewDescriptor.baseArrayLayer,this._rttRenderPassWrapper.colorAttachmentViewDescriptor.baseArrayLayer=0),N=G.getMSAATexture(),V=z.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor),k=null==N?void 0:N.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor),U=H.type===u.TEXTURETYPE_UNSIGNED_INTEGER||H.type===u.TEXTURETYPE_UNSIGNED_SHORT,S.push({view:k||V,resolveTarget:N?V:void 0,depthSlice:W,clearValue:A?U?x:i:void 0,loadOp:A?Zf.Clear:Zf.Load,storeOp:Jf.Store})}else S.push(null);if(null===(c=this._debugPushGroup)||void 0===c||c.call(this,"render target pass"+(e.label?" ("+e.label+")":""),1),this._rttRenderPassWrapper.renderPassDescriptor={label:(null!==(h=e.label)&&void 0!==h?h:"RTT")+"RenderPass",colorAttachments:S,depthStencilAttachment:_&&v?{view:T||b,depthClearValue:C?this.useReverseDepthBuffer?this._clearReverseDepthValue:this._clearDepthValue:void 0,depthLoadOp:C?Zf.Clear:Zf.Load,depthStoreOp:Jf.Store,stencilClearValue:f._depthStencilTextureWithStencil&&R?this._clearStencilValue:void 0,stencilLoadOp:E?f._depthStencilTextureWithStencil&&R?Zf.Clear:Zf.Load:void 0,stencilStoreOp:E?Jf.Store:void 0}:void 0,occlusionQuerySet:(null===(d=this._occlusionQuery)||void 0===d?void 0:d.hasQueries)?this._occlusionQuery.querySet:void 0},this._timestampQuery.startPass(this._rttRenderPassWrapper.renderPassDescriptor,this._timestampIndex),this._currentRenderPass=this._renderEncoder.beginRenderPass(this._rttRenderPassWrapper.renderPassDescriptor),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),!this._count||this._count<this.dbgVerboseLogsNumFrames)){var H=f.texture;ae.Log(["frame #"+this._count+" - render target begin pass - rtt name="+e.label+", internalTexture.uniqueId="+H.uniqueId+", width="+H.width+", height="+H.height+", setClearStates="+t,"renderPassDescriptor=",this._rttRenderPassWrapper.renderPassDescriptor])}null===(p=this._debugFlushPendingCommands)||void 0===p||p.call(this),this._resetRenderPassStates(),m&&p_.HasStencilAspect(m.format)||(this._stencilStateComposer.enabled=!1)},t.prototype._startMainRenderPass=function(e,t,i,r){var n,o,a;this._endCurrentRenderPass(),this.useReverseDepthBuffer&&this.setDepthFunctionToGreaterOrEqual();var s=e&&t,l=e&&i,c=e&&r;this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].clearValue=s?t:void 0,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].loadOp=s?Zf.Clear:Zf.Load,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthClearValue=l?this.useReverseDepthBuffer?this._clearReverseDepthValue:this._clearDepthValue:void 0,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthLoadOp=l?Zf.Clear:Zf.Load,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilClearValue=c?this._clearStencilValue:void 0,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilLoadOp=this.isStencilEnable?c?Zf.Clear:Zf.Load:void 0,this._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet=(null===(n=this._occlusionQuery)||void 0===n?void 0:n.hasQueries)?this._occlusionQuery.querySet:void 0;var u=this._context.getCurrentTexture();this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].set(u),this._options.antialias?(rm.format=u.format,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].resolveTarget=u.createView(rm)):(nm.format=u.format,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].view=u.createView(nm)),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&ae.Log(["frame #"+this._count+" - main begin pass - texture width="+this._mainTextureExtends.width," height="+this._mainTextureExtends.height+", setClearStates="+e,"renderPassDescriptor=",this._mainRenderPassWrapper.renderPassDescriptor])),null===(o=this._debugPushGroup)||void 0===o||o.call(this,"main pass",0),this._timestampQuery.startPass(this._mainRenderPassWrapper.renderPassDescriptor,this._timestampIndex),this._currentRenderPass=this._renderEncoder.beginRenderPass(this._mainRenderPassWrapper.renderPassDescriptor),this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper),null===(a=this._debugFlushPendingCommands)||void 0===a||a.call(this),this._resetRenderPassStates(),this._isStencilEnable||(this._stencilStateComposer.enabled=!1)},t.prototype._endCurrentRenderPass=function(){var e,t,i;if(!this._currentRenderPass)return 0;var r=this._currentPassIsMainPass()?2:1;return this._snapshotRendering.endRenderPass(this._currentRenderPass)||this.compatibilityMode||(this._bundleList.run(this._currentRenderPass),this._bundleList.reset()),this._currentRenderPass.end(),this._timestampQuery.endPass(this._timestampIndex,this._currentRenderTarget&&this._currentRenderTarget.gpuTimeInFrame?this._currentRenderTarget.gpuTimeInFrame:this.gpuTimeInFrameForMainPass),this._timestampIndex+=2,this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&ae.Log("frame #"+this._count+" - "+(2===r?"main":"render target")+" end pass"+(1===r?" - internalTexture.uniqueId="+(null===(t=null===(e=this._currentRenderTarget)||void 0===e?void 0:e.texture)||void 0===t?void 0:t.uniqueId):""))),null===(i=this._debugPopGroup)||void 0===i||i.call(this,0),this._currentRenderPass=null,r},t.prototype.bindFramebuffer=function(e,t,i,r,n,o,a){var s,l;void 0===t&&(t=0),void 0===o&&(o=0),void 0===a&&(a=0);var c=null===(s=e.texture)||void 0===s?void 0:s._hardwareTexture;this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._endCurrentRenderPass(),this._currentRenderTarget=e;var u=this._currentRenderTarget._depthStencilTexture;this._rttRenderPassWrapper.colorAttachmentGPUTextures[0]=c,this._rttRenderPassWrapper.depthTextureFormat=u?p_.GetWebGPUTextureFormat(-1,u.format):void 0,this._setDepthTextureFormat(this._rttRenderPassWrapper),this._setColorFormat(this._rttRenderPassWrapper),this._rttRenderPassWrapper.colorAttachmentViewDescriptor={format:this._colorFormat,dimension:e.is3D?xf.E3d:xf.E2d,mipLevelCount:1,baseArrayLayer:e.isCube?6*a+t:a,baseMipLevel:o,arrayLayerCount:1,aspect:Af.All},this._rttRenderPassWrapper.depthAttachmentViewDescriptor={format:this._depthTextureFormat,dimension:u&&u.is3D?xf.E3d:xf.E2d,mipLevelCount:1,baseArrayLayer:u?u.isCube?6*a+t:a:0,baseMipLevel:0,arrayLayerCount:1,aspect:Af.All},this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&ae.Log(["frame #"+this._count+" - bindFramebuffer - rtt name="+e.label+", internalTexture.uniqueId="+(null===(l=e.texture)||void 0===l?void 0:l.uniqueId)+", face="+t+", lodLevel="+o+", layer="+a,"colorAttachmentViewDescriptor=",this._rttRenderPassWrapper.colorAttachmentViewDescriptor,"depthAttachmentViewDescriptor=",this._rttRenderPassWrapper.depthAttachmentViewDescriptor])),this._cachedViewport&&!n?this.setViewport(this._cachedViewport,i,r):(i||(i=e.width,o&&(i/=Math.pow(2,o))),r||(r=e.height,o&&(r/=Math.pow(2,o))),this._viewport(0,0,i,r)),this.wipeCaches()},t.prototype.unBindFramebuffer=function(e,t,i){var r,n;void 0===t&&(t=!1);var o=this._currentRenderTarget;this._currentRenderTarget=null,i&&i(),this._currentRenderTarget=o,this._endCurrentRenderPass(),!(null===(r=e.texture)||void 0===r?void 0:r.generateMipMaps)||t||e.isCube||this._generateMipmaps(e.texture),this._currentRenderTarget=null,this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&ae.Log("frame #"+this._count+" - unBindFramebuffer - rtt name="+e.label+", internalTexture.uniqueId=",null===(n=e.texture)||void 0===n?void 0:n.uniqueId)),this._mrtAttachments=[],this._cacheRenderPipeline.setMRT([]),this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments)},t.prototype.restoreDefaultFramebuffer=function(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._currentRenderPass||this._startMainRenderPass(!1),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()},t.prototype._setColorFormat=function(e){var t,i,r=null!==(i=null===(t=e.colorAttachmentGPUTextures[0])||void 0===t?void 0:t.format)&&void 0!==i?i:null;this._cacheRenderPipeline.setColorFormat(r),this._colorFormat!==r&&(this._colorFormat=r)},t.prototype._setDepthTextureFormat=function(e){this._cacheRenderPipeline.setDepthStencilFormat(e.depthTextureFormat),this._depthTextureFormat!==e.depthTextureFormat&&(this._depthTextureFormat=e.depthTextureFormat)},t.prototype.setDitheringState=function(){},t.prototype.setRasterizerState=function(){},t.prototype._executeWhenRenderingStateIsCompiled=function(e,t){t()},t.prototype.bindSamplers=function(){},t.prototype._getUnpackAlignement=function(){return 1},t.prototype._bindTextureDirectly=function(){return!1},t.prototype.setState=function(e,t,i,r,n,o,a){var s,l;void 0===t&&(t=0),void 0===r&&(r=!1),void 0===a&&(a=0),(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);var c=null===(l=null!==(s=this.cullBackFaces)&&void 0!==s?s:n)||void 0===l||l?1:2;(this._depthCullingState.cullFace!==c||i)&&(this._depthCullingState.cullFace=c),this.setZOffset(t),this.setZOffsetUnits(a);var u=r?this._currentRenderTarget?1:2:this._currentRenderTarget?2:1;(this._depthCullingState.frontFace!==u||i)&&(this._depthCullingState.frontFace=u),this._stencilStateComposer.stencilMaterial=o},t.prototype._applyRenderPassChanges=function(e){var t=!!this._stencilStateComposer.enabled&&this._mustUpdateStencilRef(),i=!!this._alphaState.alphaBlend&&this._mustUpdateBlendColor();this._mustUpdateViewport()&&this._applyViewport(e),this._mustUpdateScissor()&&this._applyScissor(e),t&&this._applyStencilRef(e),i&&this._applyBlendColor(e)},t.prototype._draw=function(e,t,i,r,n){var o,a=this._getCurrentRenderPass(),s=this._bundleList;this.applyStates();var l=this._currentEffect._pipelineContext;if(this.bindUniformBufferBase(this._currentRenderTarget?this._ubInvertY:this._ubDontInvertY,0,n_.InternalsUBOName),l.uniformBuffer&&(l.uniformBuffer.update(),this.bindUniformBufferBase(l.uniformBuffer.getBuffer(),0,n_.LeftOvertUBOName)),this._snapshotRendering.play)this._reportDrawCall();else{!this.compatibilityMode&&(this._currentDrawContext.isDirty(this._currentMaterialContext.updateId)||this._currentMaterialContext.isDirty||this._currentMaterialContext.forceBindGroupCreation)&&(this._currentDrawContext.fastBundle=void 0);var c=a;if(!this.compatibilityMode&&this._currentDrawContext.fastBundle||this._snapshotRendering.record){if(this._applyRenderPassChanges(s),!this._snapshotRendering.record)return this._counters.numBundleReuseNonCompatMode++,this._currentDrawContext.indirectDrawBuffer&&this._currentDrawContext.setIndirectData(r,n||1,i),s.addBundle(this._currentDrawContext.fastBundle),void this._reportDrawCall();c=s.getBundleEncoder(this._cacheRenderPipeline.colorFormats,this._depthTextureFormat,this.currentSampleCount),s.numDrawCalls++}var h=0;if(this._currentMaterialContext.hasFloatOrDepthTextures)for(var d=1,p=0;p<l.shaderProcessingContext.textureNames.length;++p){var f=l.shaderProcessingContext.textureNames[p],_=null===(o=this._currentMaterialContext.textures[f])||void 0===o?void 0:o.texture,m=_&&_.format>=u.TEXTUREFORMAT_DEPTH24_STENCIL8&&_.format<=u.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8;((null==_?void 0:_.type)===u.TEXTURETYPE_FLOAT&&!this._caps.textureFloatLinearFiltering||m)&&(h|=d),d<<=1}this._currentMaterialContext.textureState=h;var g=this._cacheRenderPipeline.getRenderPipeline(t,this._currentEffect,this.currentSampleCount,h),v=this._cacheBindGroups.getBindGroups(l,this._currentDrawContext,this._currentMaterialContext);this._snapshotRendering.record||(this._applyRenderPassChanges(this.compatibilityMode?null:s),this.compatibilityMode||(this._counters.numBundleCreationNonCompatMode++,c=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:p_.GetSample(this.currentSampleCount)}))),c.setPipeline(g),this._currentIndexBuffer&&c.setIndexBuffer(this._currentIndexBuffer.underlyingResource,this._currentIndexBuffer.is32Bits?jf.Uint32:jf.Uint16,0);for(var y=this._cacheRenderPipeline.vertexBuffers,b=0;b<y.length;b++){var T=y[b],E=T.effectiveBuffer;E&&c.setVertexBuffer(b,E.underlyingResource,T._validOffsetRange?0:T.byteOffset)}for(p=0;p<v.length;p++)c.setBindGroup(p,v[p]);var S=!this.compatibilityMode&&!this._snapshotRendering.record;S&&this._currentDrawContext.indirectDrawBuffer?(this._currentDrawContext.setIndirectData(r,n||1,i),0===e?c.drawIndexedIndirect(this._currentDrawContext.indirectDrawBuffer,0):c.drawIndirect(this._currentDrawContext.indirectDrawBuffer,0)):0===e?c.drawIndexed(r,n||1,i,0,0):c.draw(r,n||1,i,0),S&&(this._currentDrawContext.fastBundle=c.finish(),s.addBundle(this._currentDrawContext.fastBundle)),this._reportDrawCall()}},t.prototype.drawElementsType=function(e,t,i,r){void 0===r&&(r=1),this._draw(0,e,t,i,r)},t.prototype.drawArraysType=function(e,t,i,r){void 0===r&&(r=1),this._currentIndexBuffer=null,this._draw(1,e,t,i,r)},t.prototype.dispose=function(){var t,i;this._isDisposed=!0,this._timestampQuery.dispose(),null===(t=this._mainTexture)||void 0===t||t.destroy(),null===(i=this._depthTexture)||void 0===i||i.destroy(),this._textureHelper.destroyDeferredTextures(),this._bufferManager.destroyDeferredBuffers(),this._device.destroy(),So(this,this._renderingCanvas),e.prototype.dispose.call(this)},t.prototype.getRenderWidth=function(e){var t,i;return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.width:null!==(i=null===(t=this._renderingCanvas)||void 0===t?void 0:t.width)&&void 0!==i?i:0},t.prototype.getRenderHeight=function(e){var t,i;return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.height:null!==(i=null===(t=this._renderingCanvas)||void 0===t?void 0:t.height)&&void 0!==i?i:0},t.prototype.getError=function(){return 0},t.prototype.createExternalTexture=function(e){return new im(e)},t.prototype.setExternalTexture=function(e,t){t?this._setInternalTexture(e,t):this._currentMaterialContext.setTexture(e,null)},t.prototype.setTextureSampler=function(e,t){var i;null===(i=this._currentMaterialContext)||void 0===i||i.setSampler(e,t)},t.prototype.createStorageBuffer=function(e,t,i){return this._createBuffer(e,t|u.BUFFER_CREATIONFLAG_STORAGE,i)},t.prototype.updateStorageBuffer=function(e,t,i,r){var n,o=e;void 0===i&&(i=0),void 0===r?r=(n=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t).byteLength:n=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,this._bufferManager.setSubData(o,i,n,0,r)},t.prototype.readFromStorageBuffer=function(e,t,i,r,n){var o=this;i=i||e.capacity;var a=this._bufferManager.createRawBuffer(i,bf.MapRead|bf.CopyDst,void 0,"TempReadFromStorageBuffer");return this._renderEncoder.copyBufferToBuffer(e.underlyingResource,null!=t?t:0,a,0,i),new Promise((function(e,t){var s=function(){a.mapAsync(Tf.Read,0,i).then((function(){var t=a.getMappedRange(0,i),n=r;if(void 0===n)(n=new Uint8Array(i)).set(new Uint8Array(t));else{var s=n.constructor;(n=new s(n.buffer)).set(new s(t))}a.unmap(),o._bufferManager.releaseBuffer(a),e(n)}),(function(i){o.isDisposed?e(new Uint8Array):t(i)}))};n?(o.flushFramebuffer(),s()):o.onEndFrameObservable.addOnce((function(){s()}))}))},t.prototype.setStorageBuffer=function(e,t){var i,r;null===(i=this._currentDrawContext)||void 0===i||i.setBuffer(e,null!==(r=null==t?void 0:t.getBuffer())&&void 0!==r?r:null)},t._GLSLslangDefaultOptions={jsPath:"".concat(rr._DefaultCdnUrl,"/glslang/glslang.js"),wasmPath:"".concat(rr._DefaultCdnUrl,"/glslang/glslang.wasm")},t._InstanceId=0,t.UseTWGSL=!0,t}(Mi);sm.prototype.setAlphaMode=function(e,t){if(void 0===t&&(t=!1),this._alphaMode===e&&(e===u.ALPHA_DISABLE&&!this._alphaState.alphaBlend||e!==u.ALPHA_DISABLE&&this._alphaState.alphaBlend)){if(!t){var i=e===u.ALPHA_DISABLE;this.depthCullingState.depthMask!==i&&(this.setDepthWrite(i),this._cacheRenderPipeline.setDepthWriteEnabled(i))}}else{switch(e){case u.ALPHA_DISABLE:this._alphaState.alphaBlend=!1;break;case u.ALPHA_PREMULTIPLIED:this._alphaState.setAlphaBlendFunctionParameters(1,u.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA,1,1),this._alphaState.alphaBlend=!0;break;case u.ALPHA_PREMULTIPLIED_PORTERDUFF:this._alphaState.setAlphaBlendFunctionParameters(1,u.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA,1,u.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case u.ALPHA_COMBINE:this._alphaState.setAlphaBlendFunctionParameters(u.GL_ALPHA_FUNCTION_SRC_ALPHA,u.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA,1,1),this._alphaState.alphaBlend=!0;break;case u.ALPHA_ONEONE:this._alphaState.setAlphaBlendFunctionParameters(1,1,0,1),this._alphaState.alphaBlend=!0;break;case u.ALPHA_ADD:this._alphaState.setAlphaBlendFunctionParameters(u.GL_ALPHA_FUNCTION_SRC_ALPHA,1,0,1),this._alphaState.alphaBlend=!0;break;case u.ALPHA_SUBTRACT:this._alphaState.setAlphaBlendFunctionParameters(0,u.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR,1,1),this._alphaState.alphaBlend=!0;break;case u.ALPHA_MULTIPLY:this._alphaState.setAlphaBlendFunctionParameters(u.GL_ALPHA_FUNCTION_DST_COLOR,0,1,1),this._alphaState.alphaBlend=!0;break;case u.ALPHA_MAXIMIZED:this._alphaState.setAlphaBlendFunctionParameters(u.GL_ALPHA_FUNCTION_SRC_ALPHA,u.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR,1,1),this._alphaState.alphaBlend=!0;break;case u.ALPHA_INTERPOLATE:this._alphaState.setAlphaBlendFunctionParameters(u.GL_ALPHA_FUNCTION_CONSTANT_COLOR,u.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR,u.GL_ALPHA_FUNCTION_CONSTANT_ALPHA,u.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA),this._alphaState.alphaBlend=!0;break;case u.ALPHA_SCREENMODE:this._alphaState.setAlphaBlendFunctionParameters(1,u.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR,1,u.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case u.ALPHA_ONEONE_ONEONE:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,1),this._alphaState.alphaBlend=!0;break;case u.ALPHA_ALPHATOCOLOR:this._alphaState.setAlphaBlendFunctionParameters(u.GL_ALPHA_FUNCTION_DST_ALPHA,1,0,0),this._alphaState.alphaBlend=!0;break;case u.ALPHA_REVERSEONEMINUS:this._alphaState.setAlphaBlendFunctionParameters(u.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR,u.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR,u.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA,u.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case u.ALPHA_SRC_DSTONEMINUSSRCALPHA:this._alphaState.setAlphaBlendFunctionParameters(1,u.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA,1,u.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case u.ALPHA_ONEONE_ONEZERO:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,0),this._alphaState.alphaBlend=!0;break;case u.ALPHA_EXCLUSION:this._alphaState.setAlphaBlendFunctionParameters(u.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR,u.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR,0,1),this._alphaState.alphaBlend=!0;break;case u.ALPHA_LAYER_ACCUMULATE:this._alphaState.setAlphaBlendFunctionParameters(u.GL_ALPHA_FUNCTION_SRC_ALPHA,u.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA,1,u.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0}t||(this.setDepthWrite(e===u.ALPHA_DISABLE),this._cacheRenderPipeline.setDepthWriteEnabled(e===u.ALPHA_DISABLE)),this._alphaMode=e,this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)}},sm.prototype.setAlphaEquation=function(e){Mi.prototype.setAlphaEquation.call(this,e),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)};var lm=function(){function e(t,i){this._device=t,this._cacheSampler=i,this.uniqueId=e._Counter++,this._bindGroupEntries=[],this.clear()}return e.prototype.getBindGroups=function(e,t,i){if(!i)throw new Error("WebGPUComputeContext.getBindGroups: bindingsMapping is required until browsers support reflection for wgsl shaders!");if(0===this._bindGroups.length){var r=this._bindGroupEntries.length>0;for(var n in e){var o=e[n],a=i[n],s=a.group,l=a.binding,c=o.type,u=o.object,h=o.indexInGroupEntries;switch((y=this._bindGroupEntries[s])||(y=this._bindGroupEntries[s]=[]),c){case mh.Sampler:var d=u;void 0!==h&&r?y[h].resource=this._cacheSampler.getSampler(d):(o.indexInGroupEntries=y.length,y.push({binding:l,resource:this._cacheSampler.getSampler(d)}));break;case mh.Texture:case mh.TextureWithoutSampler:var p=(f=u)._texture._hardwareTexture;void 0!==h&&r?(c===mh.Texture&&(y[h++].resource=this._cacheSampler.getSampler(f._texture)),y[h].resource=p.view):(o.indexInGroupEntries=y.length,c===mh.Texture&&y.push({binding:l-1,resource:this._cacheSampler.getSampler(f._texture)}),y.push({binding:l,resource:p.view}));break;case mh.StorageTexture:(p=(f=u)._texture._hardwareTexture).textureAdditionalUsages&Sf.StorageBinding||ae.Error("computeDispatch: The texture (name=".concat(f.name,", uniqueId=").concat(f.uniqueId,") is not a storage texture!"),50),void 0!==h&&r?y[h].resource=p.viewForWriting:(o.indexInGroupEntries=y.length,y.push({binding:l,resource:p.viewForWriting}));break;case mh.ExternalTexture:var f,_=(f=u).underlyingResource;void 0!==h&&r?y[h].resource=this._device.importExternalTexture({source:_}):(o.indexInGroupEntries=y.length,y.push({binding:l,resource:this._device.importExternalTexture({source:_})}));break;case mh.UniformBuffer:case mh.StorageBuffer:case mh.DataBuffer:var m=c===mh.DataBuffer?u:(mh.UniformBuffer,u.getBuffer()),g=m.underlyingResource;void 0!==h&&r?(y[h].resource.buffer=g,y[h].resource.size=m.capacity):(o.indexInGroupEntries=y.length,y.push({binding:l,resource:{buffer:g,offset:0,size:m.capacity}}))}}for(var v=0;v<this._bindGroupEntries.length;++v){var y;(y=this._bindGroupEntries[v])?this._bindGroups[v]=this._device.createBindGroup({layout:t.getBindGroupLayout(v),entries:y}):this._bindGroups[v]=void 0}this._bindGroups.length=this._bindGroupEntries.length}return this._bindGroups},e.prototype.clear=function(){this._bindGroups=[]},e._Counter=0,e}(),cm=function(){function e(e){this._name="unnamed",this.engine=e}return Object.defineProperty(e.prototype,"isAsync",{get:function(){return!1},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isReady",{get:function(){return this.isAsync,!1},enumerable:!1,configurable:!0}),e.prototype._getComputeShaderCode=function(){var e;return null===(e=this.sources)||void 0===e?void 0:e.compute},e.prototype.dispose=function(){},e}(),um={};function hm(e,t,i,r){var n,o=1;r===u.TEXTURETYPE_FLOAT?n=new Float32Array(t*i*4):r===u.TEXTURETYPE_HALF_FLOAT?(n=new Uint16Array(t*i*4),o=15360):n=r===u.TEXTURETYPE_UNSIGNED_INTEGER?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(var a=0;a<t;a++)for(var s=0;s<i;s++){var l=3*(s*t+a),c=4*(s*t+a);n[c+0]=e[l+0],n[c+1]=e[l+1],n[c+2]=e[l+2],n[c+3]=o}return n}sm.prototype.createComputeContext=function(){return new lm(this._device,this._cacheSampler)},sm.prototype.createComputeEffect=function(e,t){var i=("string"==typeof e?e:e.computeToken||e.computeSource||e.computeElement||e.compute)+"@"+t.defines;if(this._compiledComputeEffects[i]){var r=this._compiledComputeEffects[i];return t.onCompiled&&r.isReady()&&t.onCompiled(r),r}var n=new gh(e,t,this,i);return this._compiledComputeEffects[i]=n,n},sm.prototype.createComputePipelineContext=function(){return new cm(this)},sm.prototype.areAllComputeEffectsReady=function(){for(var e in this._compiledComputeEffects)if(!this._compiledComputeEffects[e].isReady())return!1;return!0},sm.prototype.computeDispatch=function(e,t,i,r,n,o,a,s){void 0===n&&(n=1),void 0===o&&(o=1),this._computeDispatch(e,t,i,r,n,o,void 0,void 0,a,s)},sm.prototype.computeDispatchIndirect=function(e,t,i,r,n,o,a){void 0===n&&(n=0),this._computeDispatch(e,t,i,void 0,void 0,void 0,r,n,o,a)},sm.prototype._computeDispatch=function(e,t,i,r,n,o,a,s,l,c){this._endCurrentRenderPass();var u=e._pipelineContext,h=t;u.computePipeline||(u.computePipeline=this._device.createComputePipeline({layout:Uf.Auto,compute:u.stage})),c&&this._timestampQuery.startPass(um,this._timestampIndex);var d=this._renderEncoder.beginComputePass(um);d.setPipeline(u.computePipeline);for(var p=h.getBindGroups(i,u.computePipeline,l),f=0;f<p.length;++f){var _=p[f];_&&d.setBindGroup(f,_)}void 0!==a?d.dispatchWorkgroupsIndirect(a.underlyingResource,s):r+n+o>0&&d.dispatchWorkgroups(r,n,o),d.end(),c&&(this._timestampQuery.endPass(this._timestampIndex,c),this._timestampIndex+=2)},sm.prototype.releaseComputeEffects=function(){for(var e in this._compiledComputeEffects){var t=this._compiledComputeEffects[e].getPipelineContext();this._deleteComputePipelineContext(t)}this._compiledComputeEffects={}},sm.prototype._prepareComputePipelineContext=function(e,t,i,r,n){var o=e;this.dbgShowShaderCode&&(ae.Log(r),ae.Log(t)),o.sources={compute:t,rawCompute:i},o.stage=this._createComputePipelineStageDescriptor(t,r,n)},sm.prototype._releaseComputeEffect=function(e){this._compiledComputeEffects[e._key]&&(delete this._compiledComputeEffects[e._key],this._deleteComputePipelineContext(e.getPipelineContext()))},sm.prototype._rebuildComputeEffects=function(){for(var e in this._compiledComputeEffects){var t=this._compiledComputeEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}},sm.prototype._executeWhenComputeStateIsCompiled=function(e,t){e.stage.module.getCompilationInfo().then((function(e){for(var i={numErrors:0,messages:[]},r=0,n=e.messages;r<n.length;r++){var o=n[r];"error"===o.type&&i.numErrors++,i.messages.push({type:o.type,text:o.message,line:o.lineNum,column:o.linePos,length:o.length,offset:o.offset})}t(i)}))},sm.prototype._deleteComputePipelineContext=function(e){e&&e.dispose()},sm.prototype._createComputePipelineStageDescriptor=function(e,t,i){return t=t?"//"+t.split("\n").join("\n//")+"\n":"",{module:this._device.createShaderModule({code:t+e}),entryPoint:i}},sm.prototype._createDepthStencilCubeTexture=function(e,t){var i=new Pi(this,t.generateStencil?Ti.DepthStencil:Ti.Depth);i.isCube=!0,i.label=t.label;var r=g({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?u.TEXTUREFORMAT_DEPTH24_STENCIL8:u.TEXTUREFORMAT_DEPTH32_FLOAT},t);i.format=r.depthTextureFormat,this._setupDepthStencilTexture(i,e,r.generateStencil,r.bilinearFiltering,r.comparisonFunction,r.samples),this._textureHelper.createGPUTextureForInternalTexture(i);var n=i._hardwareTexture;return i.type=p_.GetTextureTypeFromFormat(n.format),this._internalTexturesCache.push(i),i},sm.prototype.createCubeTexture=function(e,t,i,r,n,o,a,s,l,c,u,h,d){var p=this;return void 0===n&&(n=null),void 0===o&&(o=null),void 0===s&&(s=null),void 0===l&&(l=!1),void 0===c&&(c=0),void 0===u&&(u=0),void 0===h&&(h=null),void 0===d&&(d=!1),this.createCubeTextureBase(e,t,i,!!r,n,o,a,s,l,c,u,h,null,(function(e,t){var i=t,o=i[0].width,s=o;p._setCubeMapTextureParams(e,!r),e.format=null!=a?a:-1;var l=p._textureHelper.createGPUTextureForInternalTexture(e,o,s);p._textureHelper.updateCubeTextures(i,l.underlyingResource,o,s,l.format,!1,!1,0,0),r||p._generateMipmaps(e,p._uploadEncoder),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),n&&n()}),!!d)},sm.prototype._setCubeMapTextureParams=function(e,t,i){e.samplingMode=t?u.TEXTURE_TRILINEAR_SAMPLINGMODE:u.TEXTURE_BILINEAR_SAMPLINGMODE,e._cachedWrapU=u.TEXTURE_CLAMP_ADDRESSMODE,e._cachedWrapV=u.TEXTURE_CLAMP_ADDRESSMODE,i&&(e._maxLodLevel=i)},sm.prototype._debugPushGroup=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?this._renderEncoder.pushDebugGroup(e):this._currentRenderPass?this._currentRenderPass.pushDebugGroup(e):this._pendingDebugCommands.push(["push",e]))},sm.prototype._debugPopGroup=function(e){this._options.enableGPUDebugMarkers&&(0===e||1===e?this._renderEncoder.popDebugGroup():this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null]))},sm.prototype._debugInsertMarker=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?this._renderEncoder.insertDebugMarker(e):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(e):this._pendingDebugCommands.push(["insert",e]))},sm.prototype._debugFlushPendingCommands=function(){for(var e=0;e<this._pendingDebugCommands.length;++e){var t=this._pendingDebugCommands[e],i=t[0],r=t[1];switch(i){case"push":this._debugPushGroup(r);break;case"pop":this._debugPopGroup();break;case"insert":this._debugInsertMarker(r)}}this._pendingDebugCommands.length=0},sm.prototype.createDynamicTexture=function(e,t,i,r){var n=new Pi(this,Ti.Dynamic);return n.baseWidth=e,n.baseHeight=t,i&&(e=this.needPOTTextures?ir(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?ir(t,this._caps.maxTextureSize):t),n.width=e,n.height=t,n.isReady=!1,n.generateMipMaps=i,n.samplingMode=r,this.updateTextureSamplingMode(r,n),this._internalTexturesCache.push(n),e&&t&&this._textureHelper.createGPUTextureForInternalTexture(n,e,t),n},sm.prototype.updateDynamicTexture=function(e,t,i,r,n,o,a){var s;if(void 0===r&&(r=!1),e){var l=t.width,c=t.height,u=e._hardwareTexture;(null===(s=e._hardwareTexture)||void 0===s?void 0:s.underlyingResource)||(u=this._textureHelper.createGPUTextureForInternalTexture(e,l,c)),this._textureHelper.updateTexture(t,e,l,c,e.depth,u.format,0,0,i,r,0,0,a),e.generateMipMaps&&this._generateMipmaps(e),e._dynamicTextureSource=t,e._premulAlpha=r,e.invertY=i||!1,e.isReady=!0}},sm.prototype.unBindMultiColorAttachmentFramebuffer=function(e,t,i){void 0===t&&(t=!1),i&&i();var r=e._attachments.length;this._endCurrentRenderPass();for(var n=0;n<r;n++){var o=e.textures[n];!o.generateMipMaps||t||o.isCube||o.is3D||this._generateMipmaps(o)}this._currentRenderTarget=null,this._mrtAttachments=[],this._cacheRenderPipeline.setMRT([]),this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments)},sm.prototype.createMultipleRenderTarget=function(e,t,i){var r,n,o,a,s=!1,l=!0,c=!1,h=!1,d=u.TEXTUREFORMAT_DEPTH16,p=1,f=u.TEXTURETYPE_UNSIGNED_INT,_=u.TEXTURE_TRILINEAR_SAMPLINGMODE,m=u.TEXTUREFORMAT_RGBA,g=u.TEXTURE_2D,v=[],y=[],b=[],T=[],E=[],S=[],x=[],A=[],C=[],R=this._createHardwareRenderTargetWrapper(!0,!1,e);void 0!==t&&(s=void 0!==t.generateMipMaps&&t.generateMipMaps,l=void 0===t.generateDepthBuffer||t.generateDepthBuffer,c=void 0!==t.generateStencilBuffer&&t.generateStencilBuffer,h=void 0!==t.generateDepthTexture&&t.generateDepthTexture,p=t.textureCount||1,d=null!==(r=t.depthTextureFormat)&&void 0!==r?r:u.TEXTUREFORMAT_DEPTH16,t.types&&(v=t.types),t.samplingModes&&(y=t.samplingModes),t.useSRGBBuffers&&(b=t.useSRGBBuffers),t.formats&&(T=t.formats),t.targetTypes&&(E=t.targetTypes),t.faceIndex&&(S=t.faceIndex),t.layerIndex&&(x=t.layerIndex),t.layerCounts&&(A=t.layerCounts),C=null!==(n=t.labels)&&void 0!==n?n:C),R.label=null!==(o=null==t?void 0:t.label)&&void 0!==o?o:"MultiRenderTargetWrapper";var P=e.width||e,I=e.height||e,M=null;(l||c||h)&&(h||(d=l&&c?u.TEXTUREFORMAT_DEPTH24_STENCIL8:l?u.TEXTUREFORMAT_DEPTH32_FLOAT:u.TEXTUREFORMAT_STENCIL8),M=R.createDepthStencilTexture(0,!1,c,1,d,"MultipleRenderTargetDepthStencil"));var O=[],D=[],N=[];R._generateDepthBuffer=l,R._generateStencilBuffer=c,R._attachments=D,R._defaultAttachments=N;for(var F=0;F<p;F++){var L=y[F]||_,w=v[F]||f,B=T[F]||m,U=!!b[F]&&this._caps.supportSRGBBuffers,V=E[F]||g,k=null!==(a=A[F])&&void 0!==a?a:1;if((w!==u.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(w!==u.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(L=u.TEXTURE_NEAREST_SAMPLINGMODE),w!==u.TEXTURETYPE_FLOAT||this._caps.textureFloat||(w=u.TEXTURETYPE_UNSIGNED_INT,ae.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),D.push(F+1),N.push(i?F+1:0===F?1:0),-1!==V){var G=new Pi(this,Ti.MultiRenderTarget);switch(O[F]=G,V){case u.TEXTURE_CUBE_MAP:G.isCube=!0;break;case u.TEXTURE_3D:G.is3D=!0,G.baseDepth=G.depth=k;break;case u.TEXTURE_2D_ARRAY:G.is2DArray=!0,G.baseDepth=G.depth=k}G.baseWidth=P,G.baseHeight=I,G.width=P,G.height=I,G.isReady=!0,G.samples=1,G.generateMipMaps=s,G.samplingMode=L,G.type=w,G._cachedWrapU=u.TEXTURE_CLAMP_ADDRESSMODE,G._cachedWrapV=u.TEXTURE_CLAMP_ADDRESSMODE,G._useSRGBBuffer=U,G.format=B,G.label=C[F],this._internalTexturesCache.push(G),this._textureHelper.createGPUTextureForInternalTexture(G)}}return M&&(M.incrementReferences(),O[p]=M,this._internalTexturesCache.push(M)),R.setTextures(O),R.setLayerAndFaceIndices(x,S),R},sm.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t){if(!e||!e.textures||e.textures[0].samples===t)return t;var i=e.textures.length;if(0===i)return 1;t=Math.min(t,this.getCaps().maxMSAASamples);for(var r=0;r<i;++r){var n=(a=e.textures[r])._hardwareTexture;null==n||n.releaseMSAATexture()}var o=e._depthStencilTexture===e.textures[i-1];for(r=0;r<i;++r){var a=e.textures[r];this._textureHelper.createMSAATexture(a,t,!1,r===i-1&&o?0:r),a.samples=t}return e._depthStencilTexture&&!o&&(this._textureHelper.createMSAATexture(e._depthStencilTexture,t),e._depthStencilTexture.samples=t),t},sm.prototype.bindAttachments=function(e){0!==e.length&&this._currentRenderTarget&&(this._mrtAttachments=e,this._currentRenderPass&&this._cacheRenderPipeline.setMRTAttachments(e))},sm.prototype.buildTextureLayout=function(e){for(var t=[],i=0;i<e.length;i++)e[i]?t.push(i+1):t.push(0);return t},sm.prototype.restoreSingleAttachment=function(){},sm.prototype.restoreSingleAttachmentForRenderTarget=function(){},sm.prototype.getGPUFrameTimeCounter=function(){return this._timestampQuery.gpuFrameTimeCounter},sm.prototype.captureGPUFrameTime=function(e){this._timestampQuery.enable=e&&!!this._caps.timerQuery},sm.prototype.createQuery=function(){return this._occlusionQuery.createQuery()},sm.prototype.deleteQuery=function(e){return this._occlusionQuery.deleteQuery(e),this},sm.prototype.isQueryResultAvailable=function(e){return this._occlusionQuery.isQueryResultAvailable(e)},sm.prototype.getQueryResult=function(e){return this._occlusionQuery.getQueryResult(e)},sm.prototype.beginOcclusionQuery=function(e,t){var i;return this.compatibilityMode?!!this._occlusionQuery.canBeginQuery(t)&&(null===(i=this._currentRenderPass)||void 0===i||i.beginOcclusionQuery(t),!0):(this._bundleList.addItem(new j_(t)),!0)},sm.prototype.endOcclusionQuery=function(){var e;return this.compatibilityMode?null===(e=this._currentRenderPass)||void 0===e||e.endOcclusionQuery():this._bundleList.addItem(new Y_),this},sm.prototype.createRawTexture=function(e,t,i,r,n,o,a,s,l,c,h){void 0===s&&(s=null),void 0===l&&(l=u.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=0),void 0===h&&(h=!1);var d=new Pi(this,Ti.Raw);return d.baseWidth=t,d.baseHeight=i,d.width=t,d.height=i,d.format=r,d.generateMipMaps=n,d.samplingMode=a,d.invertY=o,d._compression=s,d.type=l,d._creationFlags=c,d._useSRGBBuffer=h,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,void 0,c),this.updateRawTexture(d,e,r,o,s,l,h),this._internalTexturesCache.push(d),d},sm.prototype.updateRawTexture=function(e,t,i,r,n,o,a){if(void 0===n&&(n=null),void 0===o&&(o=u.TEXTURETYPE_UNSIGNED_INT),void 0===a&&(a=!1),e){if(this._doNotHandleContextLost||(e._bufferView=t,e.invertY=r,e._compression=n,e._useSRGBBuffer=a),t){var s=e._hardwareTexture;i===u.TEXTUREFORMAT_RGB&&(t=hm(t,e.width,e.height,o));var l=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(l,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0}},sm.prototype.createRawCubeTexture=function(e,t,i,r,n,o,a,s){void 0===s&&(s=null);var l=new Pi(this,Ti.CubeRaw);return r!==u.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering?r!==u.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering?r!==u.TEXTURETYPE_FLOAT||this._caps.textureFloatRender?r!==u.TEXTURETYPE_HALF_FLOAT||this._caps.colorBufferFloat||(n=!1,ae.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(n=!1,ae.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(n=!1,a=u.TEXTURE_NEAREST_SAMPLINGMODE,ae.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(n=!1,a=u.TEXTURE_NEAREST_SAMPLINGMODE,ae.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")),l.isCube=!0,l._originalFormat=i,l.format=i===u.TEXTUREFORMAT_RGB?u.TEXTUREFORMAT_RGBA:i,l.type=r,l.generateMipMaps=n,l.width=t,l.height=t,l.samplingMode=a,this._doNotHandleContextLost||(l._bufferViewArray=e),l.invertY=o,l._compression=s,l._cachedWrapU=u.TEXTURE_CLAMP_ADDRESSMODE,l._cachedWrapV=u.TEXTURE_CLAMP_ADDRESSMODE,this._textureHelper.createGPUTextureForInternalTexture(l),i===u.TEXTUREFORMAT_RGB&&(l._hardwareTexture._originalFormatIsRGB=!0),e&&this.updateRawCubeTexture(l,e,i,r,o,s),l.isReady=!0,l},sm.prototype.updateRawCubeTexture=function(e,t,i,r,n,o){void 0===o&&(o=null),e._bufferViewArray=t,e.invertY=n,e._compression=o;for(var a=e._hardwareTexture,s=a._originalFormatIsRGB,l=[0,2,4,1,3,5],c=[],u=0;u<t.length;++u){var h=t[l[u]];s&&(h=hm(h,e.width,e.height,r)),c.push(new Uint8Array(h.buffer,h.byteOffset,h.byteLength))}this._textureHelper.updateCubeTextures(c,a.underlyingResource,e.width,e.height,a.format,n,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0},sm.prototype.createRawCubeTextureFromUrl=function(e,t,i,r,n,o,a,s,l,c,h,d){var p=this;void 0===l&&(l=null),void 0===c&&(c=null),void 0===h&&(h=u.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===d&&(d=!1);var f=this.createRawCubeTexture(null,i,r,n,!o,d,h,null);return null==t||t.addPendingData(f),f.url=e,this._internalTexturesCache.push(f),this._loadFile(e,(function(e){!function(e){var i=f.width,o=a(e);if(o){if(s)for(var c=r===u.TEXTUREFORMAT_RGB,h=s(o),_=f._hardwareTexture,m=[0,1,2,3,4,5],g=0;g<h.length;g++){for(var v=i>>g,y=[],b=0;b<6;b++){var T=h[g][m[b]];c&&(T=hm(T,v,v,n)),y.push(new Uint8Array(T.buffer,T.byteOffset,T.byteLength))}p._textureHelper.updateCubeTextures(y,_.underlyingResource,v,v,_.format,d,!1,0,0)}else p.updateRawCubeTexture(f,o,r,n,d);f.isReady=!0,null==t||t.removePendingData(f),l&&l()}}(e)}),void 0,null==t?void 0:t.offlineProvider,!0,(function(e,i){null==t||t.removePendingData(f),c&&e&&c(e.status+" "+e.statusText,i)})),f},sm.prototype.createRawTexture3D=function(e,t,i,r,n,o,a,s,l,c,h){void 0===l&&(l=null),void 0===c&&(c=u.TEXTURETYPE_UNSIGNED_INT),void 0===h&&(h=0);var d=Ti.Raw3D,p=new Pi(this,d);return p.baseWidth=t,p.baseHeight=i,p.baseDepth=r,p.width=t,p.height=i,p.depth=r,p.format=n,p.type=c,p.generateMipMaps=o,p.samplingMode=s,p.is3D=!0,p._creationFlags=h,this._doNotHandleContextLost||(p._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(p,t,i,void 0,h),this.updateRawTexture3D(p,e,n,a,l,c),this._internalTexturesCache.push(p),p},sm.prototype.updateRawTexture3D=function(e,t,i,r,n,o){if(void 0===n&&(n=null),void 0===o&&(o=u.TEXTURETYPE_UNSIGNED_INT),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=r,e._compression=n),t){var a=e._hardwareTexture;i===u.TEXTUREFORMAT_RGB&&(t=hm(t,e.width,e.height,o));var s=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(s,e,e.width,e.height,e.depth,a.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},sm.prototype.createRawTexture2DArray=function(e,t,i,r,n,o,a,s,l,c,h){void 0===l&&(l=null),void 0===c&&(c=u.TEXTURETYPE_UNSIGNED_INT),void 0===h&&(h=0);var d=Ti.Raw2DArray,p=new Pi(this,d);return p.baseWidth=t,p.baseHeight=i,p.baseDepth=r,p.width=t,p.height=i,p.depth=r,p.format=n,p.type=c,p.generateMipMaps=o,p.samplingMode=s,p.is2DArray=!0,p._creationFlags=h,this._doNotHandleContextLost||(p._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(p,t,i,r,h),this.updateRawTexture2DArray(p,e,n,a,l,c),this._internalTexturesCache.push(p),p},sm.prototype.updateRawTexture2DArray=function(e,t,i,r,n,o){if(void 0===n&&(n=null),void 0===o&&(o=u.TEXTURETYPE_UNSIGNED_INT),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=r,e._compression=n),t){var a=e._hardwareTexture;i===u.TEXTUREFORMAT_RGB&&(t=hm(t,e.width,e.height,o));var s=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(s,e,e.width,e.height,e.depth,a.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},sm.prototype._readTexturePixels=function(e,t,i,r,n,o,a,s,l,c){void 0===r&&(r=-1),void 0===n&&(n=0),void 0===o&&(o=null),void 0===a&&(a=!0),void 0===s&&(s=!1),void 0===l&&(l=0),void 0===c&&(c=0);var u=e._hardwareTexture;return a&&this.flushFramebuffer(),this._textureHelper.readPixels(u.underlyingResource,l,c,t,i,u.format,r,n,o,s)},sm.prototype._readTexturePixelsSync=function(){throw"_readTexturePixelsSync is unsupported in WebGPU!"};var dm=function(e){function t(t,i,r,n,o){var a=e.call(this,t,i,r,n,o)||this;return n.enableGPUTimingMeasurements&&(a.gpuTimeInFrame=new vh),a}return m(t,e),t}(cl);sm.prototype._createHardwareRenderTargetWrapper=function(e,t,i){var r=new dm(e,t,i,this);return this._renderTargetWrapperCache.push(r),r},sm.prototype.createRenderTargetTexture=function(e,t){var i,r,n,o=this._createHardwareRenderTargetWrapper(!1,!1,e),a={};void 0!==t&&"object"==typeof t?(a.generateMipMaps=t.generateMipMaps,a.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,a.generateStencilBuffer=a.generateDepthBuffer&&t.generateStencilBuffer,a.samplingMode=void 0===t.samplingMode?u.TEXTURE_TRILINEAR_SAMPLINGMODE:t.samplingMode,a.creationFlags=null!==(i=t.creationFlags)&&void 0!==i?i:0,a.noColorAttachment=!!t.noColorAttachment,a.samples=t.samples,a.label=t.label):(a.generateMipMaps=t,a.generateDepthBuffer=!0,a.generateStencilBuffer=!1,a.samplingMode=u.TEXTURE_TRILINEAR_SAMPLINGMODE,a.creationFlags=0,a.noColorAttachment=!1);var s=a.noColorAttachment?null:this._createInternalTexture(e,t,!0,Ti.RenderTarget);return o.label=null!==(r=a.label)&&void 0!==r?r:"RenderTargetWrapper",o._samples=null!==(n=a.samples)&&void 0!==n?n:1,o._generateDepthBuffer=a.generateDepthBuffer,o._generateStencilBuffer=!!a.generateStencilBuffer,o.setTextures(s),(o._generateDepthBuffer||o._generateStencilBuffer)&&o.createDepthStencilTexture(0,!1,o._generateStencilBuffer,o.samples,a.generateStencilBuffer?u.TEXTUREFORMAT_DEPTH24_STENCIL8:u.TEXTUREFORMAT_DEPTH32_FLOAT,a.label?a.label+"-DepthStencil":void 0),s&&(void 0!==t&&"object"==typeof t&&t.createMipMaps&&!a.generateMipMaps&&(s.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(s,void 0,void 0,void 0,a.creationFlags),void 0!==t&&"object"==typeof t&&t.createMipMaps&&!a.generateMipMaps&&(s.generateMipMaps=!1)),o},sm.prototype._createDepthStencilTexture=function(e,t){var i=new Pi(this,t.generateStencil?Ti.DepthStencil:Ti.Depth);i.label=t.label;var r=g({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?u.TEXTUREFORMAT_DEPTH24_STENCIL8:u.TEXTUREFORMAT_DEPTH32_FLOAT},t);i.format=r.depthTextureFormat,this._setupDepthStencilTexture(i,e,r.generateStencil,r.bilinearFiltering,r.comparisonFunction,r.samples),this._textureHelper.createGPUTextureForInternalTexture(i);var n=i._hardwareTexture;return i.type=p_.GetTextureTypeFromFormat(n.format),this._internalTexturesCache.push(i),i},sm.prototype._setupDepthStencilTexture=function(e,t,i,r,n,o){void 0===o&&(o=1);var a=t.width||t,s=t.height||t,l=t.layers||0,c=t.depth||0;e.baseWidth=a,e.baseHeight=s,e.width=a,e.height=s,e.is2DArray=l>0,e.is3D=c>0,e.depth=l||c,e.isReady=!0,e.samples=o,e.generateMipMaps=!1,e.samplingMode=r?u.TEXTURE_BILINEAR_SAMPLINGMODE:u.TEXTURE_NEAREST_SAMPLINGMODE,e.type=u.TEXTURETYPE_FLOAT,e._comparisonFunction=n,e._cachedWrapU=u.TEXTURE_CLAMP_ADDRESSMODE,e._cachedWrapV=u.TEXTURE_CLAMP_ADDRESSMODE},sm.prototype.updateRenderTargetTextureSampleCount=function(e,t){return e&&e.texture&&e.samples!==t?(t=Math.min(t,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(e.texture,t),e._depthStencilTexture&&(this._textureHelper.createMSAATexture(e._depthStencilTexture,t),e._depthStencilTexture.samples=t),e._samples=t,e.texture.samples=t,t):t},sm.prototype.createRenderTargetCubeTexture=function(e,t){var i,r=this._createHardwareRenderTargetWrapper(!1,!0,e),n=g({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:u.TEXTURETYPE_UNSIGNED_INT,samplingMode:u.TEXTURE_TRILINEAR_SAMPLINGMODE,format:u.TEXTUREFORMAT_RGBA,samples:1},t);n.generateStencilBuffer=n.generateDepthBuffer&&n.generateStencilBuffer,r.label=null!==(i=n.label)&&void 0!==i?i:"RenderTargetWrapper",r._generateDepthBuffer=n.generateDepthBuffer,r._generateStencilBuffer=n.generateStencilBuffer;var o=new Pi(this,Ti.RenderTarget);return o.width=e,o.height=e,o.depth=0,o.isReady=!0,o.isCube=!0,o.samples=n.samples,o.generateMipMaps=n.generateMipMaps,o.samplingMode=n.samplingMode,o.type=n.type,o.format=n.format,this._internalTexturesCache.push(o),r.setTextures(o),(r._generateDepthBuffer||r._generateStencilBuffer)&&r.createDepthStencilTexture(0,void 0===n.samplingMode||n.samplingMode===u.TEXTURE_BILINEAR_SAMPLINGMODE||n.samplingMode===u.TEXTURE_LINEAR_LINEAR||n.samplingMode===u.TEXTURE_TRILINEAR_SAMPLINGMODE||n.samplingMode===u.TEXTURE_LINEAR_LINEAR_MIPLINEAR||n.samplingMode===u.TEXTURE_NEAREST_LINEAR_MIPNEAREST||n.samplingMode===u.TEXTURE_NEAREST_LINEAR_MIPLINEAR||n.samplingMode===u.TEXTURE_NEAREST_LINEAR||n.samplingMode===u.TEXTURE_LINEAR_LINEAR_MIPNEAREST,r._generateStencilBuffer,r.samples),t&&t.createMipMaps&&!n.generateMipMaps&&(o.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(o),t&&t.createMipMaps&&!n.generateMipMaps&&(o.generateMipMaps=!1),r},sm.prototype.updateVideoTexture=function(e,t,i){var r,n=this;if(e&&!e._isDisabled){void 0===this._videoTextureSupported&&(this._videoTextureSupported=!0);var o=e._hardwareTexture;(null===(r=e._hardwareTexture)||void 0===r?void 0:r.underlyingResource)||(o=this._textureHelper.createGPUTextureForInternalTexture(e)),function(e){return!(!e||void 0===e.underlyingResource)}(t)?(this._textureHelper.copyVideoToTexture(t,e,o.format,!i),e.generateMipMaps&&this._generateMipmaps(e),e.isReady=!0):t&&this.createImageBitmap(t).then((function(t){n._textureHelper.updateTexture(t,e,e.width,e.height,e.depth,o.format,0,0,!i,!1,0,0),e.generateMipMaps&&n._generateMipmaps(e),e.isReady=!0})).catch((function(){e.isReady=!0}))}};var pm=function(){function e(){}return e.CreateAsync=function(e,t){return y(this,void 0,void 0,(function(){return b(this,(function(i){switch(i.label){case 0:return[4,sm.IsSupportedAsync];case 1:return i.sent()?[2,sm.CreateAsync(e,t)]:Do.IsSupported?[2,new Do(e,void 0,t)]:[2,new cp(t)]}}))}))},e}(),fm=function(){function e(){}return e.COPY=1,e.CUT=2,e.PASTE=3,e}(),_m=function(){function e(e,t){this.type=e,this.event=t}return e.GetTypeFromCharacter=function(e){switch(e){case 67:return fm.COPY;case 86:return fm.PASTE;case 88:return fm.CUT;default:return-1}},e}(),mm=function(e){function t(i,r,n,o,a,s,l){var c;void 0===r&&(r=Z.Gray()),void 0===n&&(n=Ih.DefaultUtilityLayer),void 0===o&&(o=null),void 0===a&&(a=1),void 0===s&&(s=Z.Yellow()),void 0===l&&(l=Z.Gray());var u,h,d,p,_,m,g,v=this;(v=e.call(this,n)||this)._pointerObserver=null,v.snapDistance=0,v.onSnapObservable=new f,v.uniformScaling=!1,v.sensitivity=1,v.dragScale=1,v.incrementalSnap=!1,v._isEnabled=!0,v._parent=null,v._dragging=!1,v._tmpVector=new V(0,0,0),v._incrementalStartupValue=V.Zero(),v._parent=o,v._coloredMaterial=new Uu("",n.utilityLayerScene),v._coloredMaterial.diffuseColor=r,v._coloredMaterial.specularColor=r.subtract(new Z(.1,.1,.1)),v._hoverMaterial=new Uu("",n.utilityLayerScene),v._hoverMaterial.diffuseColor=s,v._disableMaterial=new Uu("",n.utilityLayerScene),v._disableMaterial.diffuseColor=l,v._disableMaterial.alpha=.4,v._gizmoMesh=new Fa("axis",n.utilityLayerScene);var y=(c=v._createGizmoMesh(v._gizmoMesh,a)).arrowMesh,b=c.arrowTail,T=v._createGizmoMesh(v._gizmoMesh,a+4,!0);v._gizmoMesh.lookAt(v._rootMesh.position.add(i)),v._rootMesh.addChild(v._gizmoMesh,Oh.PreserveScaling),v._gizmoMesh.scaling.scaleInPlace(1/3);var E=y.position.clone(),S=b.position.clone(),x=b.scaling.clone(),A=function(e){var t=e*(3/v._rootMesh.scaling.length())*6;y.position.z+=t/3.5,b.scaling.y+=t,v.dragScale=b.scaling.y,b.position.z=y.position.z/2},C=function(){y.position.set(E.x,E.y,E.z),b.position.set(S.x,S.y,S.z),b.scaling.set(x.x,x.y,x.z),v.dragScale=b.scaling.y,v._dragging=!1};v.dragBehavior=new gs({dragAxis:i}),v.dragBehavior.moveAttached=!1,v.dragBehavior.updateDragPlane=!1,v._rootMesh.addBehavior(v.dragBehavior);var R=0,P=0,I={snapDistance:0};v.dragBehavior.onDragObservable.add((function(e){if(v.attachedNode){var r=v.sensitivity*e.dragDistance*(3*v.scaleRatio/v._rootMesh.scaling.length()),n=v._tmpVector,o=!1,a=0;if(v.uniformScaling?n.setAll(.57735):n.copyFrom(i),0==v.snapDistance)n.scaleToRef(r,n);else{R+=r,P+=r;var s=v.incrementalSnap?P:R;Math.abs(s)>v.snapDistance?(a=Math.floor(Math.abs(s)/v.snapDistance),s<0&&(a*=-1),R%=v.snapDistance,n.scaleToRef(v.snapDistance*a,n),o=!0):n.scaleInPlace(0)}n.addInPlaceFromFloats(1,1,1),n.x=Math.abs(n.x)<t.MinimumAbsoluteScale?t.MinimumAbsoluteScale*(n.x<0?-1:1):n.x,n.y=Math.abs(n.y)<t.MinimumAbsoluteScale?t.MinimumAbsoluteScale*(n.y<0?-1:1):n.y,n.z=Math.abs(n.z)<t.MinimumAbsoluteScale?t.MinimumAbsoluteScale*(n.z<0?-1:1):n.z;var l=v.attachedNode._isMesh?v.attachedNode:void 0;Math.abs(v.snapDistance)>0&&v.incrementalSnap?(v.attachedNode.getWorldMatrix().decompose(void 0,H.Quaternion[0],H.Vector3[2],Oh.PreserveScaling?l:void 0),n.addInPlace(v._incrementalStartupValue),n.addInPlaceFromFloats(-1,-1,-1),n.x=Math.abs(n.x)*(v._incrementalStartupValue.x>0?1:-1),n.y=Math.abs(n.y)*(v._incrementalStartupValue.y>0?1:-1),n.z=Math.abs(n.z)*(v._incrementalStartupValue.z>0?1:-1),z.ComposeToRef(n,H.Quaternion[0],H.Vector3[2],H.Matrix[1])):(z.ScalingToRef(n.x,n.y,n.z,H.Matrix[2]),H.Matrix[2].multiplyToRef(v.attachedNode.getWorldMatrix(),H.Matrix[1])),H.Matrix[1].decompose(H.Vector3[1],void 0,void 0,Oh.PreserveScaling?l:void 0);var c=1e5;Math.abs(H.Vector3[1].x)<c&&Math.abs(H.Vector3[1].y)<c&&Math.abs(H.Vector3[1].z)<c&&v.attachedNode.getWorldMatrix().copyFrom(H.Matrix[1]),o&&(I.snapDistance=v.snapDistance*a,v.onSnapObservable.notifyObservers(I)),v._matrixChanged()}})),v.dragBehavior.onDragStartObservable.add((function(){var e;v._dragging=!0;var t=v.attachedNode._isMesh?v.attachedNode:void 0;null===(e=v.attachedNode)||void 0===e||e.getWorldMatrix().decompose(v._incrementalStartupValue,void 0,void 0,Oh.PreserveScaling?t:void 0),R=0,P=0})),v.dragBehavior.onDragObservable.add((function(e){return A(e.dragDistance)})),v.dragBehavior.onDragEndObservable.add(C),null===(d=null===(h=null===(u=null==o?void 0:o.uniformScaleGizmo)||void 0===u?void 0:u.dragBehavior)||void 0===h?void 0:h.onDragObservable)||void 0===d||d.add((function(e){return A(e.delta.y)})),null===(m=null===(_=null===(p=null==o?void 0:o.uniformScaleGizmo)||void 0===p?void 0:p.dragBehavior)||void 0===_?void 0:_.onDragEndObservable)||void 0===m||m.add(C);var M={gizmoMeshes:[y,b],colliderMeshes:[T.arrowMesh,T.arrowTail],material:v._coloredMaterial,hoverMaterial:v._hoverMaterial,disableMaterial:v._disableMaterial,active:!1,dragBehavior:v.dragBehavior};null===(g=v._parent)||void 0===g||g.addToAxisCache(v._gizmoMesh,M),v._pointerObserver=n.utilityLayerScene.onPointerObservable.add((function(e){var t,i,r,n;if(!v._customMeshSet){var o=null===(t=v._parent)||void 0===t?void 0:t.getAxisCache(v._gizmoMesh);if(v._isHovered=!(!o||-1==o.colliderMeshes.indexOf(null===(i=null==e?void 0:e.pickInfo)||void 0===i?void 0:i.pickedMesh)),o=null===(r=v._parent)||void 0===r?void 0:r.getAxisCache(v._rootMesh),v._isHovered||(v._isHovered=!(!o||-1==o.colliderMeshes.indexOf(null===(n=null==e?void 0:e.pickInfo)||void 0===n?void 0:n.pickedMesh))),!v._parent){var a=v.dragBehavior.enabled?v._isHovered||v._dragging?v._hoverMaterial:v._coloredMaterial:v._disableMaterial;v._setGizmoMeshMaterial(M.gizmoMeshes,a)}}})),v.dragBehavior.onEnabledObservable.add((function(e){v._setGizmoMeshMaterial(M.gizmoMeshes,e?v._coloredMaterial:v._disableMaterial)}));var O=n._getSharedGizmoLight();return O.includedOnlyMeshes=O.includedOnlyMeshes.concat(v._rootMesh.getChildMeshes()),v}return m(t,e),Object.defineProperty(t.prototype,"coloredMaterial",{get:function(){return this._coloredMaterial},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hoverMaterial",{get:function(){return this._hoverMaterial},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"disableMaterial",{get:function(){return this._disableMaterial},enumerable:!1,configurable:!0}),t.prototype._createGizmoMesh=function(e,t,i){void 0===i&&(i=!1);var r=Uh("yPosMesh",{size:.4*(1+(t-1)/4)},this.gizmoLayer.utilityLayerScene),n=xh("cylinder",{diameterTop:.005*t,height:.275,diameterBottom:.005*t,tessellation:96},this.gizmoLayer.utilityLayerScene);return r.scaling.scaleInPlace(.1),r.material=this._coloredMaterial,r.rotation.x=Math.PI/2,r.position.z+=.3,n.material=this._coloredMaterial,n.position.z+=.1375,n.rotation.x=Math.PI/2,i&&(r.visibility=0,n.visibility=0),e.addChild(r),e.addChild(n),{arrowMesh:r,arrowTail:n}},t.prototype._attachedNodeChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)},enumerable:!1,configurable:!0}),t.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((function(e){e&&e.dispose()})),e.prototype.dispose.call(this)},t.prototype.setCustomMesh=function(t,i){var r=this;void 0===i&&(i=!1),e.prototype.setCustomMesh.call(this,t),i&&(this._rootMesh.getChildMeshes().forEach((function(e){e.material=r._coloredMaterial,e.color&&(e.color=r._coloredMaterial.diffuseColor)})),this._customMeshSet=!1)},t.MinimumAbsoluteScale=A,t}(Oh),gm=function(e){function t(t,i){void 0===t&&(t=Z.Gray()),void 0===i&&(i=Ih.DefaultKeepDepthUtilityLayer);var r=e.call(this,i)||this;r._boundingDimensions=new V(1,1,1),r._renderObserver=null,r._pointerObserver=null,r._scaleDragSpeed=.2,r._rotateSpheresDragBehaviors=[],r._scaleBoxesDragBehaviors=[],r._dragging=!1,r._tmpQuaternion=new G,r._tmpVector=new V(0,0,0),r._tmpRotationMatrix=new z,r._incrementalStartupValue=V.Zero(),r._incrementalAnchorStartupValue=V.Zero(),r.ignoreChildren=!1,r.includeChildPredicate=null,r.rotationSphereSize=.1,r.scaleBoxSize=.1,r.fixedDragMeshScreenSize=!1,r.fixedDragMeshBoundsSize=!1,r.fixedDragMeshScreenSizeDistanceFactor=10,r.scalingSnapDistance=0,r.rotationSnapDistance=0,r.onDragStartObservable=new f,r.onScaleBoxDragObservable=new f,r.onScaleBoxDragEndObservable=new f,r.onRotationSphereDragObservable=new f,r.onRotationSphereDragEndObservable=new f,r.scalePivot=null,r._axisFactor=new V(1,1,1),r.incrementalSnap=!1,r._existingMeshScale=new V,r._dragMesh=null,r._pointerDragBehavior=new gs,r.updateScale=!1,r._anchorMesh=new Uo("anchor",i.utilityLayerScene),r._coloredMaterial=new Uu("",i.utilityLayerScene),r._coloredMaterial.disableLighting=!0,r._hoverColoredMaterial=new Uu("",i.utilityLayerScene),r._hoverColoredMaterial.disableLighting=!0,r._lineBoundingBox=new Uo("",i.utilityLayerScene),r._lineBoundingBox.rotationQuaternion=new G;var n=[];n.push(fd("lines",{points:[new V(0,0,0),new V(r._boundingDimensions.x,0,0)]},i.utilityLayerScene)),n.push(fd("lines",{points:[new V(0,0,0),new V(0,r._boundingDimensions.y,0)]},i.utilityLayerScene)),n.push(fd("lines",{points:[new V(0,0,0),new V(0,0,r._boundingDimensions.z)]},i.utilityLayerScene)),n.push(fd("lines",{points:[new V(r._boundingDimensions.x,0,0),new V(r._boundingDimensions.x,r._boundingDimensions.y,0)]},i.utilityLayerScene)),n.push(fd("lines",{points:[new V(r._boundingDimensions.x,0,0),new V(r._boundingDimensions.x,0,r._boundingDimensions.z)]},i.utilityLayerScene)),n.push(fd("lines",{points:[new V(0,r._boundingDimensions.y,0),new V(r._boundingDimensions.x,r._boundingDimensions.y,0)]},i.utilityLayerScene)),n.push(fd("lines",{points:[new V(0,r._boundingDimensions.y,0),new V(0,r._boundingDimensions.y,r._boundingDimensions.z)]},i.utilityLayerScene)),n.push(fd("lines",{points:[new V(0,0,r._boundingDimensions.z),new V(r._boundingDimensions.x,0,r._boundingDimensions.z)]},i.utilityLayerScene)),n.push(fd("lines",{points:[new V(0,0,r._boundingDimensions.z),new V(0,r._boundingDimensions.y,r._boundingDimensions.z)]},i.utilityLayerScene)),n.push(fd("lines",{points:[new V(r._boundingDimensions.x,r._boundingDimensions.y,r._boundingDimensions.z),new V(0,r._boundingDimensions.y,r._boundingDimensions.z)]},i.utilityLayerScene)),n.push(fd("lines",{points:[new V(r._boundingDimensions.x,r._boundingDimensions.y,r._boundingDimensions.z),new V(r._boundingDimensions.x,0,r._boundingDimensions.z)]},i.utilityLayerScene)),n.push(fd("lines",{points:[new V(r._boundingDimensions.x,r._boundingDimensions.y,r._boundingDimensions.z),new V(r._boundingDimensions.x,r._boundingDimensions.y,0)]},i.utilityLayerScene)),n.forEach((function(e){e.color=t,e.position.addInPlace(new V(-r._boundingDimensions.x/2,-r._boundingDimensions.y/2,-r._boundingDimensions.z/2)),e.isPickable=!1,r._lineBoundingBox.addChild(e)})),r._rootMesh.addChild(r._lineBoundingBox),r.setColor(t),r._rotateSpheresParent=new Uo("",i.utilityLayerScene),r._rotateSpheresParent.rotationQuaternion=new G;for(var o=function(e){var t=Gh("",{diameter:1},i.utilityLayerScene);t.rotationQuaternion=new G,t.material=a._coloredMaterial,t.isNearGrabbable=!0;var n=new gs({});n.moveAttached=!1,n.updateDragPlane=!1,t.addBehavior(n);var o=new V(1,0,0),s=0,l=0;n.onDragStartObservable.add((function(){o.copyFrom(t.forward),s=0,l=0})),n.onDragObservable.add((function(t){if(r.onRotationSphereDragObservable.notifyObservers({}),r.attachedMesh){var i=r.attachedMesh.parent;if(i&&i.scaling&&i.scaling.isNonUniformWithinEpsilon(.001))return void ae.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");ds._RemoveAndStorePivotPoint(r.attachedMesh);var n=o,a=t.dragPlaneNormal.scale(V.Dot(t.dragPlaneNormal,n)),c=n.subtract(a).normalizeToNew(),u=V.Dot(c,t.delta)<0?Math.abs(t.delta.length()):-Math.abs(t.delta.length());if(u=u/r._boundingDimensions.length()*r._anchorMesh.scaling.length(),r.attachedMesh.rotationQuaternion||(r.attachedMesh.rotationQuaternion=G.RotationYawPitchRoll(r.attachedMesh.rotation.y,r.attachedMesh.rotation.x,r.attachedMesh.rotation.z)),r._anchorMesh.rotationQuaternion||(r._anchorMesh.rotationQuaternion=G.RotationYawPitchRoll(r._anchorMesh.rotation.y,r._anchorMesh.rotation.x,r._anchorMesh.rotation.z)),s+=u,Math.abs(s)<=2*Math.PI){if(r.rotationSnapDistance>0){var h=Math.floor(Math.abs(s)/r.rotationSnapDistance)*(s<0?-1:1),d=r.rotationSnapDistance*h;u=d-l,l=d}e>=8?G.RotationYawPitchRollToRef(0,0,u,r._tmpQuaternion):e>=4?G.RotationYawPitchRollToRef(u,0,0,r._tmpQuaternion):G.RotationYawPitchRollToRef(0,u,0,r._tmpQuaternion),r.attachedMesh.isUsingPivotMatrix()&&r._anchorMesh.position.copyFrom(r.attachedMesh.position),r._anchorMesh.addChild(r.attachedMesh),r._anchorMesh.getScene().useRightHandedSystem&&r._tmpQuaternion.conjugateInPlace(),r._tmpQuaternion.normalize(),r._anchorMesh.rotationQuaternion.multiplyToRef(r._tmpQuaternion,r._anchorMesh.rotationQuaternion),r._anchorMesh.rotationQuaternion.normalize(),r._anchorMesh.removeChild(r.attachedMesh),r.attachedMesh.setParent(i)}r.updateBoundingBox(),ds._RestorePivotPoint(r.attachedMesh)}r._updateDummy()})),n.onDragStartObservable.add((function(){r.onDragStartObservable.notifyObservers({}),r._dragging=!0,r._selectNode(t)})),n.onDragEndObservable.add((function(e){r.onRotationSphereDragEndObservable.notifyObservers({}),r._dragging=!1,r._selectNode(null),r._updateDummy(),r._unhoverMeshOnTouchUp(e.pointerInfo,t)})),a._rotateSpheresDragBehaviors.push(n),a._rotateSpheresParent.addChild(t)},a=this,s=0;s<12;s++)o(s);for(r._rootMesh.addChild(r._rotateSpheresParent),r._scaleBoxesParent=new Uo("",i.utilityLayerScene),r._scaleBoxesParent.rotationQuaternion=new G,s=0;s<3;s++)for(var l=0;l<3;l++)for(var c=function(e){var t=(1===s?1:0)+(1===l?1:0)+(1===e?1:0);if(1===t||3===t)return"continue";var n=Uh("",{size:1},i.utilityLayerScene);n.material=u._coloredMaterial,n._internalMetadata=2===t,n.isNearGrabbable=!0;var o=new V(s-1,l-1,e-1).normalize(),a=new gs({dragAxis:o});a.updateDragPlane=!1,a.moveAttached=!1;var c=0,h=0;n.addBehavior(a),a.onDragObservable.add((function(e){if(r.onScaleBoxDragObservable.notifyObservers({}),r.attachedMesh){var i=r.attachedMesh.parent;if(i&&i.scaling&&i.scaling.isNonUniformWithinEpsilon(.001))return void ae.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");ds._RemoveAndStorePivotPoint(r.attachedMesh);var a=e.dragDistance/r._boundingDimensions.length()*r._anchorMesh.scaling.length();if(c+=a,r.scalingSnapDistance>0){var s=Math.floor(Math.abs(c)/r.scalingSnapDistance)*(c<0?-1:1),l=r.scalingSnapDistance*s;a=l-h,h=l}var u=new V(a,a,a),d=new V(h,h,h);2===t&&(u.x*=Math.abs(o.x),u.y*=Math.abs(o.y),u.z*=Math.abs(o.z)),u.scaleInPlace(r._scaleDragSpeed),u.multiplyInPlace(r._axisFactor),d.scaleInPlace(r._scaleDragSpeed),d.multiplyInPlace(r._axisFactor),d.addInPlace(r._incrementalStartupValue),r.updateBoundingBox(),r.scalePivot?(r.attachedMesh.getWorldMatrix().getRotationMatrixToRef(r._tmpRotationMatrix),r._boundingDimensions.scaleToRef(.5,r._tmpVector),V.TransformCoordinatesToRef(r._tmpVector,r._tmpRotationMatrix,r._tmpVector),r._anchorMesh.position.subtractInPlace(r._tmpVector),r._boundingDimensions.multiplyToRef(r.scalePivot,r._tmpVector),V.TransformCoordinatesToRef(r._tmpVector,r._tmpRotationMatrix,r._tmpVector),r._anchorMesh.position.addInPlace(r._tmpVector)):(n.absolutePosition.subtractToRef(r._anchorMesh.position,r._tmpVector),r._anchorMesh.position.subtractInPlace(r._tmpVector),r.attachedMesh.isUsingPivotMatrix()&&r._anchorMesh.position.subtractInPlace(r.attachedMesh.getPivotPoint())),r._anchorMesh.addChild(r.attachedMesh),r.incrementalSnap?(d.x/=Math.abs(r._incrementalStartupValue.x)<A?1:r._incrementalStartupValue.x,d.y/=Math.abs(r._incrementalStartupValue.y)<A?1:r._incrementalStartupValue.y,d.z/=Math.abs(r._incrementalStartupValue.z)<A?1:r._incrementalStartupValue.z,d.x=Math.max(r._incrementalAnchorStartupValue.x*d.x,r.scalingSnapDistance),d.y=Math.max(r._incrementalAnchorStartupValue.y*d.y,r.scalingSnapDistance),d.z=Math.max(r._incrementalAnchorStartupValue.z*d.z,r.scalingSnapDistance),r._anchorMesh.scaling.x+=(d.x-r._anchorMesh.scaling.x)*Math.abs(o.x),r._anchorMesh.scaling.y+=(d.y-r._anchorMesh.scaling.y)*Math.abs(o.y),r._anchorMesh.scaling.z+=(d.z-r._anchorMesh.scaling.z)*Math.abs(o.z)):(r._anchorMesh.scaling.addInPlace(u),(r._anchorMesh.scaling.x<0||r._anchorMesh.scaling.y<0||r._anchorMesh.scaling.z<0)&&r._anchorMesh.scaling.subtractInPlace(u)),r._anchorMesh.removeChild(r.attachedMesh),r.attachedMesh.setParent(i),ds._RestorePivotPoint(r.attachedMesh)}r._updateDummy()})),a.onDragStartObservable.add((function(){r.onDragStartObservable.notifyObservers({}),r._dragging=!0,r._selectNode(n),c=0,h=0,r._incrementalStartupValue.copyFrom(r.attachedMesh.scaling),r._incrementalAnchorStartupValue.copyFrom(r._anchorMesh.scaling)})),a.onDragEndObservable.add((function(e){r.onScaleBoxDragEndObservable.notifyObservers({}),r._dragging=!1,r._selectNode(null),r._updateDummy(),r._unhoverMeshOnTouchUp(e.pointerInfo,n)})),u._scaleBoxesParent.addChild(n),u._scaleBoxesDragBehaviors.push(a)},u=this,h=0;h<3;h++)c(h);r._rootMesh.addChild(r._scaleBoxesParent);var d=[];return r._pointerObserver=i.utilityLayerScene.onPointerObservable.add((function(e){d[e.event.pointerId]?e.pickInfo&&e.pickInfo.pickedMesh!=d[e.event.pointerId]&&(d[e.event.pointerId].material=r._coloredMaterial,delete d[e.event.pointerId],r._isHovered=!1):r._rotateSpheresParent.getChildMeshes().concat(r._scaleBoxesParent.getChildMeshes()).forEach((function(t){e.pickInfo&&e.pickInfo.pickedMesh==t&&(d[e.event.pointerId]=t,t.material=r._hoverColoredMaterial,r._isHovered=!0)}))})),r._renderObserver=r.gizmoLayer.originalScene.onBeforeRenderObservable.add((function(){r.attachedMesh&&!r._existingMeshScale.equals(r.attachedMesh.scaling)?r.updateBoundingBox():(r.fixedDragMeshScreenSize||r.fixedDragMeshBoundsSize)&&(r._updateRotationSpheres(),r._updateScaleBoxes()),r._dragMesh&&r.attachedMesh&&r._pointerDragBehavior.dragging&&(r._lineBoundingBox.position.rotateByQuaternionToRef(r._rootMesh.rotationQuaternion,r._tmpVector),r.attachedMesh.setAbsolutePosition(r._dragMesh.position.add(r._tmpVector.scale(-1))))})),r.updateBoundingBox(),r}return m(t,e),Object.defineProperty(t.prototype,"axisFactor",{get:function(){return this._axisFactor},set:function(e){this._axisFactor=e;for(var t=this._scaleBoxesParent.getChildMeshes(),i=0,r=0;r<3;r++)for(var n=0;n<3;n++)for(var o=0;o<3;o++){var a=(1===r?1:0)+(1===n?1:0)+(1===o?1:0);if(1!==a&&3!==a){if(t[i]){var s=new V(r-1,n-1,o-1);s.multiplyInPlace(this._axisFactor),t[i].setEnabled(s.lengthSquared()>A)}i++}}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scaleDragSpeed",{get:function(){return this._scaleDragSpeed},set:function(e){this._scaleDragSpeed=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"coloredMaterial",{get:function(){return this._coloredMaterial},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hoverMaterial",{get:function(){return this._hoverColoredMaterial},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"pointerDragBehavior",{get:function(){return this._pointerDragBehavior},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isDragging",{get:function(){return this._dragging||this._pointerDragBehavior.dragging},enumerable:!1,configurable:!0}),t.prototype.setColor=function(e){this._coloredMaterial.emissiveColor=e,this._hoverColoredMaterial.emissiveColor=e.clone().add(new Z(.3,.3,.3)),this._lineBoundingBox.getChildren().forEach((function(t){t.color&&(t.color=e)}))},t.prototype._attachedNodeChanged=function(e){var t=this;if(e){this._anchorMesh.scaling.setAll(1),ds._RemoveAndStorePivotPoint(e);var i=e.parent;this._anchorMesh.addChild(e),this._anchorMesh.removeChild(e),e.setParent(i),ds._RestorePivotPoint(e),this.updateBoundingBox(),e.getChildMeshes(!1).forEach((function(e){e.markAsDirty("scaling")})),this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce((function(){t._updateDummy()}))}},t.prototype._selectNode=function(e){this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach((function(t){t.isVisible=!e||t==e}))},t.prototype._unhoverMeshOnTouchUp=function(e,t){(null==e?void 0:e.event)instanceof PointerEvent&&"touch"===(null==e?void 0:e.event.pointerType)&&(t.material=this._coloredMaterial)},t.prototype.getScaleBoxes=function(){return this._scaleBoxesParent.getChildMeshes()},t.prototype.updateBoundingBox=function(){if(this.attachedMesh){ds._RemoveAndStorePivotPoint(this.attachedMesh);var e=this.attachedMesh.parent;this.attachedMesh.setParent(null),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=G.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=G.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);var t=this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren,this.includeChildPredicate);t.max.subtractToRef(t.min,this._boundingDimensions),this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions),this._lineBoundingBox.position.set((t.max.x+t.min.x)/2,(t.max.y+t.min.y)/2,(t.max.z+t.min.z)/2),this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position),this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position),this._lineBoundingBox.computeWorldMatrix(),this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),this.attachedMesh.setParent(e)}this._updateRotationSpheres(),this._updateScaleBoxes(),this.attachedMesh&&(this._existingMeshScale.copyFrom(this.attachedMesh.scaling),ds._RestorePivotPoint(this.attachedMesh))},t.prototype._updateRotationSpheres=function(){for(var e=this._rotateSpheresParent.getChildMeshes(),t=0;t<3;t++)for(var i=0;i<2;i++)for(var r=0;r<2;r++){var n=4*t+2*i+r;if(0==t&&(e[n].position.set(this._boundingDimensions.x/2,this._boundingDimensions.y*i,this._boundingDimensions.z*r),e[n].position.addInPlace(new V(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[n].lookAt(V.Cross(e[n].position.normalizeToNew(),V.Right()).normalizeToNew().add(e[n].position))),1==t&&(e[n].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y/2,this._boundingDimensions.z*r),e[n].position.addInPlace(new V(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[n].lookAt(V.Cross(e[n].position.normalizeToNew(),V.Up()).normalizeToNew().add(e[n].position))),2==t&&(e[n].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y*r,this._boundingDimensions.z/2),e[n].position.addInPlace(new V(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[n].lookAt(V.Cross(e[n].position.normalizeToNew(),V.Forward()).normalizeToNew().add(e[n].position))),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[n].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);var o=this.rotationSphereSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[n].scaling.set(o,o,o)}else this.fixedDragMeshBoundsSize?e[n].scaling.set(this.rotationSphereSize*this._boundingDimensions.x,this.rotationSphereSize*this._boundingDimensions.y,this.rotationSphereSize*this._boundingDimensions.z):e[n].scaling.set(this.rotationSphereSize,this.rotationSphereSize,this.rotationSphereSize)}},t.prototype._updateScaleBoxes=function(){for(var e=this._scaleBoxesParent.getChildMeshes(),t=0,i=0;i<3;i++)for(var r=0;r<3;r++)for(var n=0;n<3;n++){var o=(1===i?1:0)+(1===r?1:0)+(1===n?1:0);if(1!==o&&3!==o){if(e[t])if(e[t].position.set(this._boundingDimensions.x*(i/2),this._boundingDimensions.y*(r/2),this._boundingDimensions.z*(n/2)),e[t].position.addInPlace(new V(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[t].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.globalPosition,this._tmpVector);var a=this.scaleBoxSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[t].scaling.set(a,a,a)}else this.fixedDragMeshBoundsSize?e[t].scaling.set(this.scaleBoxSize*this._boundingDimensions.x,this.scaleBoxSize*this._boundingDimensions.y,this.scaleBoxSize*this._boundingDimensions.z):e[t].scaling.set(this.scaleBoxSize,this.scaleBoxSize,this.scaleBoxSize);t++}}},t.prototype.setEnabledRotationAxis=function(e){this._rotateSpheresParent.getChildMeshes().forEach((function(t,i){i<4?t.setEnabled(-1!=e.indexOf("x")):i<8?t.setEnabled(-1!=e.indexOf("y")):t.setEnabled(-1!=e.indexOf("z"))}))},t.prototype.setEnabledScaling=function(e,t){void 0===t&&(t=!1),this._scaleBoxesParent.getChildMeshes().forEach((function(i){var r=e;t&&!0===i._internalMetadata&&(r=!1),i.setEnabled(r)}))},t.prototype._updateDummy=function(){this._dragMesh&&(this._dragMesh.position.copyFrom(this._lineBoundingBox.getAbsolutePosition()),this._dragMesh.scaling.copyFrom(this._lineBoundingBox.scaling),this._dragMesh.rotationQuaternion.copyFrom(this._rootMesh.rotationQuaternion))},t.prototype.enableDragBehavior=function(){this._dragMesh=Uh("dummy",{size:1},this.gizmoLayer.utilityLayerScene),this._dragMesh.visibility=0,this._dragMesh.rotationQuaternion=new G,this._pointerDragBehavior.useObjectOrientationForDragging=!1,this._dragMesh.addBehavior(this._pointerDragBehavior)},t.prototype.releaseDrag=function(){this._scaleBoxesDragBehaviors.forEach((function(e){e.releaseDrag()})),this._rotateSpheresDragBehaviors.forEach((function(e){e.releaseDrag()})),this._pointerDragBehavior.releaseDrag()},t.prototype.dispose=function(){this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver),this._lineBoundingBox.dispose(),this._rotateSpheresParent.dispose(),this._scaleBoxesParent.dispose(),this._dragMesh&&this._dragMesh.dispose(),this._scaleBoxesDragBehaviors.length=0,this._rotateSpheresDragBehaviors.length=0,e.prototype.dispose.call(this)},t.MakeNotPickableAndWrapInBoundingBox=function(e){var t=function(e){e.isPickable=!1,e.getChildMeshes().forEach((function(e){t(e)}))};t(e),e.rotationQuaternion||(e.rotationQuaternion=G.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z));var i=e.position.clone(),r=e.rotationQuaternion.clone();e.rotationQuaternion.set(0,0,0,1),e.position.set(0,0,0);var n=Uh("box",{size:1},e.getScene()),o=e.getHierarchyBoundingVectors();return o.max.subtractToRef(o.min,n.scaling),0===n.scaling.y&&(n.scaling.y=A),0===n.scaling.x&&(n.scaling.x=A),0===n.scaling.z&&(n.scaling.z=A),n.position.set((o.max.x+o.min.x)/2,(o.max.y+o.min.y)/2,(o.max.z+o.min.z)/2),e.addChild(n),e.rotationQuaternion.copyFrom(r),e.position.copyFrom(i),e.removeChild(n),n.addChild(e),n.visibility=0,n},t.prototype.setCustomMesh=function(){ae.Error("Custom meshes are not supported on this gizmo")},t}(Oh),vm=function(e){function t(i,r,n,o,a,s,l,c,u){var h;void 0===r&&(r=Z.Gray()),void 0===n&&(n=Ih.DefaultUtilityLayer),void 0===o&&(o=32),void 0===a&&(a=null),void 0===s&&(s=!1),void 0===l&&(l=1),void 0===c&&(c=Z.Yellow()),void 0===u&&(u=Z.Gray());var d,p=this;(p=e.call(this,n)||this)._pointerObserver=null,p.snapDistance=0,p.onSnapObservable=new f,p.angle=0,p.sensitivity=1,p._isEnabled=!0,p._parent=null,p._dragging=!1,p._angles=new V,p._parent=a,p._coloredMaterial=new Uu("",n.utilityLayerScene),p._coloredMaterial.diffuseColor=r,p._coloredMaterial.specularColor=r.subtract(new Z(.1,.1,.1)),p._hoverMaterial=new Uu("",n.utilityLayerScene),p._hoverMaterial.diffuseColor=c,p._hoverMaterial.specularColor=c,p._disableMaterial=new Uu("",n.utilityLayerScene),p._disableMaterial.diffuseColor=u,p._disableMaterial.alpha=.4,p._gizmoMesh=new Fa("",n.utilityLayerScene);var _=(h=p._createGizmoMesh(p._gizmoMesh,l,o)).rotationMesh,m=h.collider;p._rotationDisplayPlane=fs("rotationDisplay",{size:.6,updatable:!1},p.gizmoLayer.utilityLayerScene),p._rotationDisplayPlane.rotation.z=.5*Math.PI,p._rotationDisplayPlane.parent=p._gizmoMesh,p._rotationDisplayPlane.setEnabled(!1),Ei.ShadersStore.rotationGizmoVertexShader=t._RotationGizmoVertexShader,Ei.ShadersStore.rotationGizmoFragmentShader=t._RotationGizmoFragmentShader,p._rotationShaderMaterial=new ld("shader",p.gizmoLayer.utilityLayerScene,{vertex:"rotationGizmo",fragment:"rotationGizmo"},{attributes:["position","uv"],uniforms:["worldViewProjection","angles","rotationColor"]}),p._rotationShaderMaterial.backFaceCulling=!1,p.rotationColor=c,p._rotationDisplayPlane.material=p._rotationShaderMaterial,p._rotationDisplayPlane.visibility=.999,p._gizmoMesh.lookAt(p._rootMesh.position.add(i)),p._rootMesh.addChild(p._gizmoMesh,Oh.PreserveScaling),p._gizmoMesh.scaling.scaleInPlace(1/3),p.dragBehavior=new gs({dragPlaneNormal:i}),p.dragBehavior.moveAttached=!1,p.dragBehavior.maxDragAngle=t.MaxDragAngle,p.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,p._rootMesh.addBehavior(p.dragBehavior);var g=new V,v=new z,y=new V,b=new V;p.dragBehavior.onDragStartObservable.add((function(e){p.attachedNode&&(g.copyFrom(e.dragPlanePoint),p._rotationDisplayPlane.setEnabled(!0),p._rotationDisplayPlane.getWorldMatrix().invertToRef(v),V.TransformCoordinatesToRef(e.dragPlanePoint,v,g),p._angles.x=Math.atan2(g.y,g.x)+Math.PI,p._angles.y=0,p._angles.z=p.updateGizmoRotationToMatchAttachedMesh?1:0,p._dragging=!0,g.copyFrom(e.dragPlanePoint),p._rotationShaderMaterial.setVector3("angles",p._angles),p.angle=0)})),p.dragBehavior.onDragEndObservable.add((function(){p._dragging=!1,p._rotationDisplayPlane.setEnabled(!1)}));var T={snapDistance:0},E=0,S=new z,x=new G;p.dragBehavior.onDragObservable.add((function(e){if(p.attachedNode){var t=new V(1,1,1),r=new G(0,0,0,1),o=new V(0,0,0);if(p.attachedNode.getWorldMatrix().decompose(t,r,o),!(Math.abs(Math.abs(t.x)-Math.abs(t.y))<=A&&Math.abs(Math.abs(t.x)-Math.abs(t.z))<=A)&&p.updateGizmoRotationToMatchAttachedMesh)return void ae.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");r.normalize();var a=p.updateGizmoPositionToMatchAttachedMesh?o:p._rootMesh.absolutePosition,s=e.dragPlanePoint.subtract(a).normalize(),l=g.subtract(a).normalize(),c=V.Cross(s,l),u=V.Dot(s,l),h=Math.atan2(c.length(),u)*p.sensitivity;y.copyFrom(i),b.copyFrom(i),p.updateGizmoRotationToMatchAttachedMesh&&(r.toRotationMatrix(v),b=V.TransformCoordinates(y,v));var d=!1;if(n.utilityLayerScene.activeCamera){var f=n.utilityLayerScene.activeCamera.position.subtract(a).normalize();V.Dot(f,b)>0&&(y.scaleInPlace(-1),b.scaleInPlace(-1),d=!0)}V.Dot(b,c)>0&&(h=-h),H.Vector3[0].set(h,0,0),p.dragBehavior.validateDrag(H.Vector3[0])||(h=0);var _=!1;if(0!=p.snapDistance)if(E+=h,Math.abs(E)>p.snapDistance){var m=Math.floor(Math.abs(E)/p.snapDistance);E<0&&(m*=-1),E%=p.snapDistance,h=p.snapDistance*m,_=!0}else h=0;var C=Math.sin(h/2);if(x.set(y.x*C,y.y*C,y.z*C,Math.cos(h/2)),S.determinant()>0){var R=new V;x.toEulerAnglesToRef(R),G.RotationYawPitchRollToRef(R.y,-R.x,-R.z,x)}if(p.updateGizmoRotationToMatchAttachedMesh)r.multiplyToRef(x,r),r.normalize(),z.ComposeToRef(t,r,o,p.attachedNode.getWorldMatrix());else{x.toRotationMatrix(H.Matrix[0]);var P=p.attachedNode.getWorldMatrix().getTranslation();p.attachedNode.getWorldMatrix().multiplyToRef(H.Matrix[0],p.attachedNode.getWorldMatrix()),p.attachedNode.getWorldMatrix().setTranslation(P)}g.copyFrom(e.dragPlanePoint),_&&(T.snapDistance=h,p.onSnapObservable.notifyObservers(T)),p._angles.y+=h,p.angle+=d?-h:h,p._rotationShaderMaterial.setVector3("angles",p._angles),p._matrixChanged()}}));var C=n._getSharedGizmoLight();C.includedOnlyMeshes=C.includedOnlyMeshes.concat(p._rootMesh.getChildMeshes(!1));var R={colliderMeshes:[m],gizmoMeshes:[_],material:p._coloredMaterial,hoverMaterial:p._hoverMaterial,disableMaterial:p._disableMaterial,active:!1,dragBehavior:p.dragBehavior};return null===(d=p._parent)||void 0===d||d.addToAxisCache(p._gizmoMesh,R),p._pointerObserver=n.utilityLayerScene.onPointerObservable.add((function(e){var i;if(!p._customMeshSet&&(p.dragBehavior.maxDragAngle=t.MaxDragAngle,p._isHovered=!(-1==R.colliderMeshes.indexOf(null===(i=null==e?void 0:e.pickInfo)||void 0===i?void 0:i.pickedMesh)),!p._parent)){var r=R.dragBehavior.enabled?p._isHovered||p._dragging?p._hoverMaterial:p._coloredMaterial:p._disableMaterial;p._setGizmoMeshMaterial(R.gizmoMeshes,r)}})),p.dragBehavior.onEnabledObservable.add((function(e){p._setGizmoMeshMaterial(R.gizmoMeshes,e?p._coloredMaterial:p._disableMaterial)})),p}return m(t,e),Object.defineProperty(t.prototype,"coloredMaterial",{get:function(){return this._coloredMaterial},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hoverMaterial",{get:function(){return this._hoverMaterial},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rotationColor",{set:function(e){this._rotationShaderMaterial.setColor3("rotationColor",e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"disableMaterial",{get:function(){return this._disableMaterial},enumerable:!1,configurable:!0}),t.prototype._createGizmoMesh=function(e,t,i){var r=sh("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);r.visibility=0;var n=sh("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return n.material=this._coloredMaterial,n.rotation.x=Math.PI/2,r.rotation.x=Math.PI/2,e.addChild(n,Oh.PreserveScaling),e.addChild(r,Oh.PreserveScaling),{rotationMesh:n,collider:r}},t.prototype._attachedNodeChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null},enumerable:!1,configurable:!0}),t.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((function(e){e&&e.dispose()})),e.prototype.dispose.call(this)},t.MaxDragAngle=9*Math.PI/20,t._RotationGizmoVertexShader="\n precision highp float;\n attribute vec3 position;\n attribute vec2 uv;\n uniform mat4 worldViewProjection;\n varying vec3 vPosition;\n varying vec2 vUV;\n\n void main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n vUV = uv;\n }",t._RotationGizmoFragmentShader="\n precision highp float;\n varying vec2 vUV;\n varying vec3 vPosition;\n uniform vec3 angles;\n uniform vec3 rotationColor;\n\n #define twopi 6.283185307\n\n void main(void) {\n vec2 uv = vUV - vec2(0.5);\n float angle = atan(uv.y, uv.x) + 3.141592;\n float delta = gl_FrontFacing ? angles.y : -angles.y;\n float begin = angles.x - delta * angles.z;\n float start = (begin < (begin + delta)) ? begin : (begin + delta);\n float end = (begin > (begin + delta)) ? begin : (begin + delta);\n float len = sqrt(dot(uv,uv));\n float opacity = 1. - step(0.5, len);\n\n float base = abs(floor(start / twopi)) * twopi;\n start += base;\n end += base;\n\n float intensity = 0.;\n for (int i = 0; i < 5; i++)\n {\n intensity += max(step(start, angle) - step(end, angle), 0.);\n angle += twopi;\n }\n gl_FragColor = vec4(rotationColor, min(intensity * 0.25, 0.8)) * opacity;\n }\n ",t}(Oh),ym=function(e){function t(t,i,r,n,o,a){void 0===t&&(t=Ih.DefaultUtilityLayer),void 0===i&&(i=32),void 0===r&&(r=!1),void 0===n&&(n=1);var s=e.call(this,t)||this;s.onDragStartObservable=new f,s.onDragObservable=new f,s.onDragEndObservable=new f,s._observables=[],s._sensitivity=1,s._gizmoAxisCache=new Map;var l=a&&a.xOptions&&a.xOptions.color?a.xOptions.color:Z.Red().scale(.5),c=a&&a.yOptions&&a.yOptions.color?a.yOptions.color:Z.Green().scale(.5),u=a&&a.zOptions&&a.zOptions.color?a.zOptions.color:Z.Blue().scale(.5);return s.xGizmo=new vm(new V(1,0,0),l,t,i,s,r,n),s.yGizmo=new vm(new V(0,1,0),c,t,i,s,r,n),s.zGizmo=new vm(new V(0,0,1),u,t,i,s,r,n),s.additionalTransformNode=null==a?void 0:a.additionalTransformNode,[s.xGizmo,s.yGizmo,s.zGizmo].forEach((function(e){a&&null!=a.updateScale&&(e.updateScale=a.updateScale),e.dragBehavior.onDragStartObservable.add((function(){s.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragObservable.add((function(){s.onDragObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((function(){s.onDragEndObservable.notifyObservers({})}))})),s.attachedMesh=null,s.attachedNode=null,o?o.addToAxisCache(s._gizmoAxisCache):Oh.GizmoAxisPointerObserver(t,s._gizmoAxisCache),s}return m(t,e),Object.defineProperty(t.prototype,"attachedMesh",{get:function(){return this._meshAttached},set:function(e){this._meshAttached=e,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach((function(t){t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"attachedNode",{get:function(){return this._nodeAttached},set:function(e){this._meshAttached=null,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach((function(t){t.isEnabled?t.attachedNode=e:t.attachedNode=null}))},enumerable:!1,configurable:!0}),t.prototype._checkBillboardTransform=function(){this._nodeAttached&&this._nodeAttached.billboardMode&&ae.Log("Rotation Gizmo will not work with transforms in billboard mode.")},Object.defineProperty(t.prototype,"sensitivity",{get:function(){return this._sensitivity},set:function(e){this._sensitivity=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((function(t){t&&(t.sensitivity=e)}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isHovered",{get:function(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isDragging",{get:function(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"additionalTransformNode",{get:function(){return this._additionalTransformNode},set:function(e){[this.xGizmo,this.yGizmo,this.zGizmo].forEach((function(t){t.additionalTransformNode=e}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh},set:function(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"updateGizmoPositionToMatchAttachedMesh",{get:function(){return this.xGizmo.updateGizmoPositionToMatchAttachedMesh},set:function(e){this.xGizmo&&(this.xGizmo.updateGizmoPositionToMatchAttachedMesh=e,this.yGizmo.updateGizmoPositionToMatchAttachedMesh=e,this.zGizmo.updateGizmoPositionToMatchAttachedMesh=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"anchorPoint",{get:function(){return this._anchorPoint},set:function(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((function(t){t.anchorPoint=e}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"coordinatesMode",{set:function(e){[this.xGizmo,this.yGizmo,this.zGizmo].forEach((function(t){t.coordinatesMode=e}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"updateScale",{get:function(){return this.xGizmo.updateScale},set:function(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"snapDistance",{get:function(){return this.xGizmo.snapDistance},set:function(e){this.xGizmo&&(this.xGizmo.snapDistance=e,this.yGizmo.snapDistance=e,this.zGizmo.snapDistance=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scaleRatio",{get:function(){return this.xGizmo.scaleRatio},set:function(e){this.xGizmo&&(this.xGizmo.scaleRatio=e,this.yGizmo.scaleRatio=e,this.zGizmo.scaleRatio=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"customRotationQuaternion",{get:function(){return this._customRotationQuaternion},set:function(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((function(t){t&&(t.customRotationQuaternion=e)}))},enumerable:!1,configurable:!0}),t.prototype.addToAxisCache=function(e,t){this._gizmoAxisCache.set(e,t)},t.prototype.releaseDrag=function(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag()},t.prototype.dispose=function(){var e=this;this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose(),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear(),this._observables.forEach((function(t){e.gizmoLayer.utilityLayerScene.onPointerObservable.remove(t)}))},t.prototype.setCustomMesh=function(){ae.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)")},t}(Oh),bm=function(e){function t(i,r,n,o,a,s){void 0===r&&(r=Z.Gray()),void 0===n&&(n=Ih.DefaultUtilityLayer),void 0===o&&(o=null),void 0===a&&(a=Z.Yellow()),void 0===s&&(s=Z.Gray());var l,c=this;(c=e.call(this,n)||this)._pointerObserver=null,c.snapDistance=0,c.onSnapObservable=new f,c._isEnabled=!1,c._parent=null,c._dragging=!1,c._parent=o,c._coloredMaterial=new Uu("",n.utilityLayerScene),c._coloredMaterial.diffuseColor=r,c._coloredMaterial.specularColor=r.subtract(new Z(.1,.1,.1)),c._hoverMaterial=new Uu("",n.utilityLayerScene),c._hoverMaterial.diffuseColor=a,c._disableMaterial=new Uu("",n.utilityLayerScene),c._disableMaterial.diffuseColor=s,c._disableMaterial.alpha=.4,c._gizmoMesh=t._CreatePlane(n.utilityLayerScene,c._coloredMaterial),c._gizmoMesh.lookAt(c._rootMesh.position.add(i)),c._gizmoMesh.scaling.scaleInPlace(1/3),c._gizmoMesh.parent=c._rootMesh;var u=0,h=new V,d={snapDistance:0};c.dragBehavior=new gs({dragPlaneNormal:i}),c.dragBehavior.moveAttached=!1,c._rootMesh.addBehavior(c.dragBehavior),c.dragBehavior.onDragObservable.add((function(e){if(c.attachedNode){if(0==c.snapDistance)c.attachedNode.getWorldMatrix().getTranslationToRef(H.Vector3[0]),H.Vector3[0].addToRef(e.delta,H.Vector3[0]),c.dragBehavior.validateDrag(H.Vector3[0])&&c.attachedNode.getWorldMatrix().addTranslationFromFloats(e.delta.x,e.delta.y,e.delta.z);else if(u+=e.dragDistance,Math.abs(u)>c.snapDistance){var t=Math.floor(Math.abs(u)/c.snapDistance);u%=c.snapDistance,e.delta.normalizeToRef(h),h.scaleInPlace(c.snapDistance*t),c.attachedNode.getWorldMatrix().getTranslationToRef(H.Vector3[0]),H.Vector3[0].addToRef(h,H.Vector3[0]),c.dragBehavior.validateDrag(H.Vector3[0])&&(c.attachedNode.getWorldMatrix().addTranslationFromFloats(h.x,h.y,h.z),d.snapDistance=c.snapDistance*t,c.onSnapObservable.notifyObservers(d))}c._matrixChanged()}})),c.dragBehavior.onDragStartObservable.add((function(){c._dragging=!0})),c.dragBehavior.onDragEndObservable.add((function(){c._dragging=!1}));var p=n._getSharedGizmoLight();p.includedOnlyMeshes=p.includedOnlyMeshes.concat(c._rootMesh.getChildMeshes(!1));var _={gizmoMeshes:c._gizmoMesh.getChildMeshes(),colliderMeshes:c._gizmoMesh.getChildMeshes(),material:c._coloredMaterial,hoverMaterial:c._hoverMaterial,disableMaterial:c._disableMaterial,active:!1,dragBehavior:c.dragBehavior};return null===(l=c._parent)||void 0===l||l.addToAxisCache(c._gizmoMesh,_),c._pointerObserver=n.utilityLayerScene.onPointerObservable.add((function(e){var t;if(!c._customMeshSet&&(c._isHovered=!(-1==_.colliderMeshes.indexOf(null===(t=null==e?void 0:e.pickInfo)||void 0===t?void 0:t.pickedMesh)),!c._parent)){var i=_.dragBehavior.enabled?c._isHovered||c._dragging?c._hoverMaterial:c._coloredMaterial:c._disableMaterial;c._setGizmoMeshMaterial(_.gizmoMeshes,i)}})),c.dragBehavior.onEnabledObservable.add((function(e){c._setGizmoMeshMaterial(_.gizmoMeshes,e?c._coloredMaterial:c._disableMaterial)})),c}return m(t,e),Object.defineProperty(t.prototype,"coloredMaterial",{get:function(){return this._coloredMaterial},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hoverMaterial",{get:function(){return this._hoverMaterial},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"disableMaterial",{get:function(){return this._disableMaterial},enumerable:!1,configurable:!0}),t._CreatePlane=function(e,t){var i=new Fo("plane",e),r=fs("dragPlane",{width:.1375,height:.1375,sideOrientation:2},e);return r.material=t,r.parent=i,i},t.prototype._attachedNodeChanged=function(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)},Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e,e?this._parent&&(this.attachedNode=this._parent.attachedNode):this.attachedNode=null},enumerable:!1,configurable:!0}),t.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),e.prototype.dispose.call(this),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((function(e){e&&e.dispose()}))},t}(Oh),Tm=function(e){function t(t,i,r,n){void 0===t&&(t=Ih.DefaultUtilityLayer),void 0===i&&(i=1);var o=e.call(this,t)||this;return o._meshAttached=null,o._nodeAttached=null,o._observables=[],o._gizmoAxisCache=new Map,o.onDragStartObservable=new f,o.onDragObservable=new f,o.onDragEndObservable=new f,o._planarGizmoEnabled=!1,o.xGizmo=new Dh(new V(1,0,0),Z.Red().scale(.5),t,o,i),o.yGizmo=new Dh(new V(0,1,0),Z.Green().scale(.5),t,o,i),o.zGizmo=new Dh(new V(0,0,1),Z.Blue().scale(.5),t,o,i),o.xPlaneGizmo=new bm(new V(1,0,0),Z.Red().scale(.5),o.gizmoLayer,o),o.yPlaneGizmo=new bm(new V(0,1,0),Z.Green().scale(.5),o.gizmoLayer,o),o.zPlaneGizmo=new bm(new V(0,0,1),Z.Blue().scale(.5),o.gizmoLayer,o),o.additionalTransformNode=null==n?void 0:n.additionalTransformNode,[o.xGizmo,o.yGizmo,o.zGizmo,o.xPlaneGizmo,o.yPlaneGizmo,o.zPlaneGizmo].forEach((function(e){e.dragBehavior.onDragStartObservable.add((function(){o.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragObservable.add((function(){o.onDragObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((function(){o.onDragEndObservable.notifyObservers({})}))})),o.attachedMesh=null,r?r.addToAxisCache(o._gizmoAxisCache):Oh.GizmoAxisPointerObserver(t,o._gizmoAxisCache),o}return m(t,e),Object.defineProperty(t.prototype,"attachedMesh",{get:function(){return this._meshAttached},set:function(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((function(t){t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"attachedNode",{get:function(){return this._nodeAttached},set:function(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((function(t){t.isEnabled?t.attachedNode=e:t.attachedNode=null}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isHovered",{get:function(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered||this.xPlaneGizmo.isHovered||this.yPlaneGizmo.isHovered||this.zPlaneGizmo.isHovered},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isDragging",{get:function(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging||this.xPlaneGizmo.dragBehavior.dragging||this.yPlaneGizmo.dragBehavior.dragging||this.zPlaneGizmo.dragBehavior.dragging},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"additionalTransformNode",{get:function(){return this._additionalTransformNode},set:function(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((function(t){t.additionalTransformNode=e}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"planarGizmoEnabled",{get:function(){return this._planarGizmoEnabled},set:function(e){var t=this;this._planarGizmoEnabled=e,[this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((function(i){i&&(i.isEnabled=e,e&&(i.attachedMesh?i.attachedMesh=t.attachedMesh:i.attachedNode=t.attachedNode))}),this)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"customRotationQuaternion",{get:function(){return this._customRotationQuaternion},set:function(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((function(t){t&&(t.customRotationQuaternion=e)}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this._updateGizmoRotationToMatchAttachedMesh},set:function(e){this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((function(t){t&&(t.updateGizmoRotationToMatchAttachedMesh=e)}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"updateGizmoPositionToMatchAttachedMesh",{get:function(){return this._updateGizmoPositionToMatchAttachedMesh},set:function(e){this._updateGizmoPositionToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((function(t){t&&(t.updateGizmoPositionToMatchAttachedMesh=e)}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"anchorPoint",{get:function(){return this._anchorPoint},set:function(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((function(t){t.anchorPoint=e}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"coordinatesMode",{set:function(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((function(t){t.coordinatesMode=e}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"updateScale",{get:function(){return this.xGizmo.updateScale},set:function(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"snapDistance",{get:function(){return this._snapDistance},set:function(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((function(t){t&&(t.snapDistance=e)}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scaleRatio",{get:function(){return this._scaleRatio},set:function(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((function(t){t&&(t.scaleRatio=e)}))},enumerable:!1,configurable:!0}),t.prototype.addToAxisCache=function(e,t){this._gizmoAxisCache.set(e,t)},t.prototype.releaseDrag=function(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag(),this.xPlaneGizmo.dragBehavior.releaseDrag(),this.yPlaneGizmo.dragBehavior.releaseDrag(),this.zPlaneGizmo.dragBehavior.releaseDrag()},t.prototype.dispose=function(){var e=this;[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((function(e){e&&e.dispose()})),this._observables.forEach((function(t){e.gizmoLayer.utilityLayerScene.onPointerObservable.remove(t)})),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear()},t.prototype.setCustomMesh=function(){ae.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo,gizmo.xPlaneGizmo, gizmo.yPlaneGizmo, gizmo.zPlaneGizmo)")},t}(Oh),Em=function(e){function t(t,i,r,n){void 0===t&&(t=Ih.DefaultUtilityLayer),void 0===i&&(i=1);var o=e.call(this,t)||this;return o._meshAttached=null,o._nodeAttached=null,o._incrementalSnap=!1,o._sensitivity=1,o._observables=[],o._gizmoAxisCache=new Map,o.onDragStartObservable=new f,o.onDragObservable=new f,o.onDragEndObservable=new f,o.uniformScaleGizmo=o._createUniformScaleMesh(),o.xGizmo=new mm(new V(1,0,0),Z.Red().scale(.5),t,o,i),o.yGizmo=new mm(new V(0,1,0),Z.Green().scale(.5),t,o,i),o.zGizmo=new mm(new V(0,0,1),Z.Blue().scale(.5),t,o,i),o.additionalTransformNode=null==n?void 0:n.additionalTransformNode,[o.xGizmo,o.yGizmo,o.zGizmo,o.uniformScaleGizmo].forEach((function(e){e.dragBehavior.onDragStartObservable.add((function(){o.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragObservable.add((function(){o.onDragObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((function(){o.onDragEndObservable.notifyObservers({})}))})),o.attachedMesh=null,o.attachedNode=null,r?r.addToAxisCache(o._gizmoAxisCache):Oh.GizmoAxisPointerObserver(t,o._gizmoAxisCache),o}return m(t,e),Object.defineProperty(t.prototype,"coloredMaterial",{get:function(){return this._coloredMaterial},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hoverMaterial",{get:function(){return this._hoverMaterial},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"disableMaterial",{get:function(){return this._disableMaterial},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"attachedMesh",{get:function(){return this._meshAttached},set:function(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((function(t){t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"attachedNode",{get:function(){return this._nodeAttached},set:function(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((function(t){t.isEnabled?t.attachedNode=e:t.attachedNode=null}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"updateScale",{get:function(){return this.xGizmo.updateScale},set:function(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isHovered",{get:function(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered||this.uniformScaleGizmo.isHovered},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isDragging",{get:function(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging||this.uniformScaleGizmo.dragBehavior.dragging},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"additionalTransformNode",{get:function(){return this._additionalTransformNode},set:function(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((function(t){t.additionalTransformNode=e}))},enumerable:!1,configurable:!0}),t.prototype._createUniformScaleMesh=function(){this._coloredMaterial=new Uu("",this.gizmoLayer.utilityLayerScene),this._coloredMaterial.diffuseColor=Z.Gray(),this._hoverMaterial=new Uu("",this.gizmoLayer.utilityLayerScene),this._hoverMaterial.diffuseColor=Z.Yellow(),this._disableMaterial=new Uu("",this.gizmoLayer.utilityLayerScene),this._disableMaterial.diffuseColor=Z.Gray(),this._disableMaterial.alpha=.4;var e=new mm(new V(0,1,0),Z.Gray().scale(.5),this.gizmoLayer,this);e.updateGizmoRotationToMatchAttachedMesh=!1,e.uniformScaling=!0,this._uniformScalingMesh=Fd("uniform",{type:1},e.gizmoLayer.utilityLayerScene),this._uniformScalingMesh.scaling.scaleInPlace(.01),this._uniformScalingMesh.visibility=0,this._octahedron=Fd("",{type:1},e.gizmoLayer.utilityLayerScene),this._octahedron.scaling.scaleInPlace(.007),this._uniformScalingMesh.addChild(this._octahedron),e.setCustomMesh(this._uniformScalingMesh,!0);var t=this.gizmoLayer._getSharedGizmoLight();t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._octahedron);var i={gizmoMeshes:[this._octahedron,this._uniformScalingMesh],colliderMeshes:[this._octahedron,this._uniformScalingMesh],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:e.dragBehavior};return this.addToAxisCache(e._rootMesh,i),e},Object.defineProperty(t.prototype,"updateGizmoRotationToMatchAttachedMesh",{get:function(){return this._updateGizmoRotationToMatchAttachedMesh},set:function(e){e?(this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((function(t){t&&(t.updateGizmoRotationToMatchAttachedMesh=e)}))):ae.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.")},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"anchorPoint",{get:function(){return this._anchorPoint},set:function(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((function(t){t&&(t.anchorPoint=e)}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"customRotationQuaternion",{get:function(){return this._customRotationQuaternion},set:function(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((function(t){t&&(t.customRotationQuaternion=e)}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"coordinatesMode",{set:function(e){e==Ph.World&&ae.Warn("Setting coordinates Mode to world on scaling gizmo is not supported."),[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((function(e){e.coordinatesMode=Ph.Local}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"snapDistance",{get:function(){return this._snapDistance},set:function(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((function(t){t&&(t.snapDistance=e)}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"incrementalSnap",{get:function(){return this._incrementalSnap},set:function(e){this._incrementalSnap=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((function(t){t&&(t.incrementalSnap=e)}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scaleRatio",{get:function(){return this._scaleRatio},set:function(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((function(t){t&&(t.scaleRatio=e)}))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"sensitivity",{get:function(){return this._sensitivity},set:function(e){this._sensitivity=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((function(t){t&&(t.sensitivity=e)}))},enumerable:!1,configurable:!0}),t.prototype.addToAxisCache=function(e,t){this._gizmoAxisCache.set(e,t)},t.prototype.getAxisCache=function(e){return this._gizmoAxisCache.get(e)},t.prototype.releaseDrag=function(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag(),this.uniformScaleGizmo.dragBehavior.releaseDrag()},t.prototype.dispose=function(){var e=this;[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((function(e){e&&e.dispose()})),this._observables.forEach((function(t){e.gizmoLayer.utilityLayerScene.onPointerObservable.remove(t)})),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear(),[this._uniformScalingMesh,this._octahedron].forEach((function(e){e&&e.dispose()})),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((function(e){e&&e.dispose()}))},t}(Oh),Sm=function(){function e(e,t,i,r){void 0===t&&(t=1),void 0===i&&(i=Ih.DefaultUtilityLayer),void 0===r&&(r=Ih.DefaultKeepDepthUtilityLayer),this._scene=e,this.clearGizmoOnEmptyPointerEvent=!1,this.enableAutoPicking=!0,this.onAttachedToMeshObservable=new f,this.onAttachedToNodeObservable=new f,this._gizmosEnabled={positionGizmo:!1,rotationGizmo:!1,scaleGizmo:!1,boundingBoxGizmo:!1},this._pointerObservers=[],this._attachedMesh=null,this._attachedNode=null,this._boundingBoxColor=Z.FromHexString("#0984e3"),this._thickness=1,this._scaleRatio=1,this._coordinatesMode=Ph.Local,this._gizmoAxisCache=new Map,this.boundingBoxDragBehavior=new bs,this.attachableMeshes=null,this.attachableNodes=null,this.usePointerToAttachGizmos=!0,this._defaultUtilityLayer=i,this._defaultKeepDepthUtilityLayer=r,this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,this._thickness=t,this.gizmos={positionGizmo:null,rotationGizmo:null,scaleGizmo:null,boundingBoxGizmo:null};var n=this._attachToMeshPointerObserver(e),o=Oh.GizmoAxisPointerObserver(this._defaultUtilityLayer,this._gizmoAxisCache);this._pointerObservers=[n,o]}return Object.defineProperty(e.prototype,"keepDepthUtilityLayer",{get:function(){return this._defaultKeepDepthUtilityLayer},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"utilityLayer",{get:function(){return this._defaultUtilityLayer},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isHovered",{get:function(){var e=!1;for(var t in this.gizmos){var i=this.gizmos[t];if(i&&i.isHovered){e=!0;break}}return e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isDragging",{get:function(){var e=!1;return[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo,this.gizmos.boundingBoxGizmo].forEach((function(t){t&&t.isDragging&&(e=!0)})),e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"scaleRatio",{get:function(){return this._scaleRatio},set:function(e){this._scaleRatio=e,[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo].forEach((function(t){t&&(t.scaleRatio=e)}))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"coordinatesMode",{get:function(){return this._coordinatesMode},set:function(e){this._coordinatesMode=e,[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo].forEach((function(t){t&&(t.coordinatesMode=e)}))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"attachedMesh",{get:function(){return this._attachedMesh},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"attachedNode",{get:function(){return this._attachedNode},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"additionalTransformNode",{get:function(){return this._additionalTransformNode},set:function(e){this._additionalTransformNode=e,this._setAdditionalTransformNode()},enumerable:!1,configurable:!0}),e.prototype._attachToMeshPointerObserver=function(e){var t=this;return e.onPointerObservable.add((function(e){if(t.usePointerToAttachGizmos&&e.type==Gr.POINTERDOWN)if(e.pickInfo&&e.pickInfo.pickedMesh){if(t.enableAutoPicking){var i=e.pickInfo.pickedMesh;if(null==t.attachableMeshes)for(;i&&null!=i.parent;)i=i.parent;else{var r=!1;t.attachableMeshes.forEach((function(e){i&&(i==e||i.isDescendantOf(e))&&(i=e,r=!0)})),r||(i=null)}i instanceof Uo?t._attachedMesh!=i&&t.attachToMesh(i):t.clearGizmoOnEmptyPointerEvent&&t.attachToMesh(null)}}else t.clearGizmoOnEmptyPointerEvent&&t.attachToMesh(null)}))},e.prototype.attachToMesh=function(e){for(var t in this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=e,this._attachedNode=null,this.gizmos){var i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedMesh=e)}this.boundingBoxGizmoEnabled&&this._attachedMesh&&this._attachedMesh.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToMeshObservable.notifyObservers(e)},e.prototype.attachToNode=function(e){for(var t in this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=null,this._attachedNode=e,this.gizmos){var i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedNode=e)}this.boundingBoxGizmoEnabled&&this._attachedNode&&this._attachedNode.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToNodeObservable.notifyObservers(e)},Object.defineProperty(e.prototype,"positionGizmoEnabled",{get:function(){return this._gizmosEnabled.positionGizmo},set:function(e){e?(this.gizmos.positionGizmo||(this.gizmos.positionGizmo=new Tm(this._defaultUtilityLayer,this._thickness,this)),this._attachedNode?this.gizmos.positionGizmo.attachedNode=this._attachedNode:this.gizmos.positionGizmo.attachedMesh=this._attachedMesh):this.gizmos.positionGizmo&&(this.gizmos.positionGizmo.attachedNode=null),this._gizmosEnabled.positionGizmo=e,this._setAdditionalTransformNode()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"rotationGizmoEnabled",{get:function(){return this._gizmosEnabled.rotationGizmo},set:function(e){e?(this.gizmos.rotationGizmo||(this.gizmos.rotationGizmo=new ym(this._defaultUtilityLayer,32,!1,this._thickness,this)),this._attachedNode?this.gizmos.rotationGizmo.attachedNode=this._attachedNode:this.gizmos.rotationGizmo.attachedMesh=this._attachedMesh):this.gizmos.rotationGizmo&&(this.gizmos.rotationGizmo.attachedNode=null),this._gizmosEnabled.rotationGizmo=e,this._setAdditionalTransformNode()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"scaleGizmoEnabled",{get:function(){return this._gizmosEnabled.scaleGizmo},set:function(e){e?(this.gizmos.scaleGizmo=this.gizmos.scaleGizmo||new Em(this._defaultUtilityLayer,this._thickness,this),this._attachedNode?this.gizmos.scaleGizmo.attachedNode=this._attachedNode:this.gizmos.scaleGizmo.attachedMesh=this._attachedMesh):this.gizmos.scaleGizmo&&(this.gizmos.scaleGizmo.attachedNode=null),this._gizmosEnabled.scaleGizmo=e,this._setAdditionalTransformNode()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"boundingBoxGizmoEnabled",{get:function(){return this._gizmosEnabled.boundingBoxGizmo},set:function(e){e?(this.gizmos.boundingBoxGizmo=this.gizmos.boundingBoxGizmo||new gm(this._boundingBoxColor,this._defaultKeepDepthUtilityLayer),this._attachedMesh?this.gizmos.boundingBoxGizmo.attachedMesh=this._attachedMesh:this.gizmos.boundingBoxGizmo.attachedNode=this._attachedNode,this._attachedMesh?(this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh.addBehavior(this.boundingBoxDragBehavior)):this._attachedNode&&(this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode.addBehavior(this.boundingBoxDragBehavior))):this.gizmos.boundingBoxGizmo&&(this._attachedMesh?this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior):this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this.gizmos.boundingBoxGizmo.attachedNode=null),this._gizmosEnabled.boundingBoxGizmo=e,this._setAdditionalTransformNode()},enumerable:!1,configurable:!0}),e.prototype._setAdditionalTransformNode=function(){for(var e in this.gizmos){var t=this.gizmos[e];t&&this._gizmosEnabled[e]&&(t.additionalTransformNode=this._additionalTransformNode)}},e.prototype.addToAxisCache=function(e){var t=this;e.size>0&&e.forEach((function(e,i){t._gizmoAxisCache.set(i,e)}))},e.prototype.releaseDrag=function(){[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo,this.gizmos.boundingBoxGizmo].forEach((function(e){null==e||e.releaseDrag()}))},e.prototype.dispose=function(){var e,t,i=this;for(var r in this._pointerObservers.forEach((function(e){i._scene.onPointerObservable.remove(e)})),this.gizmos){var n=this.gizmos[r];n&&n.dispose()}this._defaultKeepDepthUtilityLayer!==Ih._DefaultKeepDepthUtilityLayer&&(null===(e=this._defaultKeepDepthUtilityLayer)||void 0===e||e.dispose()),this._defaultUtilityLayer!==Ih._DefaultUtilityLayer&&(null===(t=this._defaultUtilityLayer)||void 0===t||t.dispose()),this.boundingBoxDragBehavior.detach(),this.onAttachedToMeshObservable.clear()},e}(),xm=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._needProjectionMatrixCompute=!0,t._viewMatrix=z.Identity(),t._projectionMatrix=z.Identity(),t}return m(t,e),t.prototype._setPosition=function(e){this._position=e},Object.defineProperty(t.prototype,"position",{get:function(){return this._position},set:function(e){this._setPosition(e)},enumerable:!1,configurable:!0}),t.prototype._setDirection=function(e){this._direction=e},Object.defineProperty(t.prototype,"direction",{get:function(){return this._direction},set:function(e){this._setDirection(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"shadowMinZ",{get:function(){return this._shadowMinZ},set:function(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"shadowMaxZ",{get:function(){return this._shadowMaxZ},set:function(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()},enumerable:!1,configurable:!0}),t.prototype.computeTransformedInformation=function(){return!(!this.parent||!this.parent.getWorldMatrix||(this.transformedPosition||(this.transformedPosition=V.Zero()),V.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=V.Zero()),V.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),0))},t.prototype.getDepthScale=function(){return 50},t.prototype.getShadowDirection=function(e){return this.transformedDirection?this.transformedDirection:this.direction},t.prototype.getAbsolutePosition=function(){return this.transformedPosition?this.transformedPosition:this.position},t.prototype.setDirectionToTarget=function(e){return this.direction=V.Normalize(e.subtract(this.position)),this.direction},t.prototype.getRotation=function(){this.direction.normalize();var e=V.Cross(this.direction,_n.Y),t=V.Cross(e,this.direction);return V.RotationFromAxis(e,t,this.direction)},t.prototype.needCube=function(){return!1},t.prototype.needProjectionMatrixCompute=function(){return this._needProjectionMatrixCompute},t.prototype.forceProjectionMatrixCompute=function(){this._needProjectionMatrixCompute=!0},t.prototype._initCache=function(){e.prototype._initCache.call(this),this._cache.position=V.Zero()},t.prototype._isSynchronized=function(){return!!this._cache.position.equals(this.position)},t.prototype.computeWorldMatrix=function(e){return!e&&this.isSynchronized()?(this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix):(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=z.Identity()),z.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this.parent&&this.parent.getWorldMatrix&&(this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix)},t.prototype.getDepthMinZ=function(e){return void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ},t.prototype.getDepthMaxZ=function(e){return void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ},t.prototype.setShadowProjectionMatrix=function(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this},t.prototype._syncParentEnabledState=function(){e.prototype._syncParentEnabledState.call(this),this.parent&&this.parent.getWorldMatrix||(this.transformedPosition=null,this.transformedDirection=null)},t.prototype.getViewMatrix=function(e){var t=H.Vector3[0],i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),V.NormalizeToRef(this.getShadowDirection(e),t),1===Math.abs(V.Dot(t,V.Up()))&&(t.z=1e-13);var r=H.Vector3[1];return i.addToRef(t,r),z.LookAtLHToRef(i,r,V.Up(),this._viewMatrix),this._viewMatrix},t.prototype.getProjectionMatrix=function(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,null!=e?e:this._viewMatrix,null!=t?t:[]),this._projectionMatrix},v([Fe()],t.prototype,"position",null),v([Fe()],t.prototype,"direction",null),v([Ie()],t.prototype,"shadowMinZ",null),v([Ie()],t.prototype,"shadowMaxZ",null),t}(wa);qe.AddNodeConstructor("Light_Type_1",(function(e,t){return function(){return new Am(e,V.Zero(),t)}}));var Am=function(e){function t(t,i,r){var n=e.call(this,t,r)||this;return n._shadowFrustumSize=0,n._shadowOrthoScale=.1,n.autoUpdateExtends=!0,n.autoCalcShadowZBounds=!1,n._orthoLeft=Number.MAX_VALUE,n._orthoRight=Number.MIN_VALUE,n._orthoTop=Number.MIN_VALUE,n._orthoBottom=Number.MAX_VALUE,n.position=i.scale(-1),n.direction=i,n}return m(t,e),Object.defineProperty(t.prototype,"shadowFrustumSize",{get:function(){return this._shadowFrustumSize},set:function(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"shadowOrthoScale",{get:function(){return this._shadowOrthoScale},set:function(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"orthoLeft",{get:function(){return this._orthoLeft},set:function(e){this._orthoLeft=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"orthoRight",{get:function(){return this._orthoRight},set:function(e){this._orthoRight=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"orthoTop",{get:function(){return this._orthoTop},set:function(e){this._orthoTop=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"orthoBottom",{get:function(){return this._orthoBottom},set:function(e){this._orthoBottom=e},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"DirectionalLight"},t.prototype.getTypeID=function(){return wa.LIGHTTYPEID_DIRECTIONALLIGHT},t.prototype._setDefaultShadowProjectionMatrix=function(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)},t.prototype._setDefaultFixedFrustumShadowProjectionMatrix=function(e){var t=this.getScene().activeCamera;t&&z.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,void 0!==this.shadowMinZ?this.shadowMinZ:t.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:t.maxZ,e,this.getScene().getEngine().isNDCHalfZRange)},t.prototype._setDefaultAutoExtendShadowProjectionMatrix=function(e,t,i){var r=this.getScene().activeCamera;if(r){if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){var n=V.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;for(var o=Number.MAX_VALUE,a=-Number.MAX_VALUE,s=0;s<i.length;s++){var l=i[s];if(l)for(var c=l.getBoundingInfo().boundingBox,u=0;u<c.vectorsWorld.length;u++)V.TransformCoordinatesToRef(c.vectorsWorld[u],t,n),n.x<this._orthoLeft&&(this._orthoLeft=n.x),n.y<this._orthoBottom&&(this._orthoBottom=n.y),n.x>this._orthoRight&&(this._orthoRight=n.x),n.y>this._orthoTop&&(this._orthoTop=n.y),this.autoCalcShadowZBounds&&(n.z<o&&(o=n.z),n.z>a&&(a=n.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=o,this._shadowMaxZ=a)}var h=this._orthoRight-this._orthoLeft,d=this._orthoTop-this._orthoBottom,p=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,f=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,_=this.getScene().getEngine().useReverseDepthBuffer;z.OrthoOffCenterLHToRef(this._orthoLeft-h*this.shadowOrthoScale,this._orthoRight+h*this.shadowOrthoScale,this._orthoBottom-d*this.shadowOrthoScale,this._orthoTop+d*this.shadowOrthoScale,_?f:p,_?p:f,e,this.getScene().getEngine().isNDCHalfZRange)}},t.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},t.prototype.transferToEffect=function(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)},t.prototype.transferToNodeMaterialEffect=function(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)},t.prototype.getDepthMinZ=function(e){var t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1},t.prototype.getDepthMaxZ=function(e){var t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1},t.prototype.prepareLightSpecificDefines=function(e,t){e["DIRLIGHT"+t]=!0},v([Ie()],t.prototype,"shadowFrustumSize",null),v([Ie()],t.prototype,"shadowOrthoScale",null),v([Ie()],t.prototype,"autoUpdateExtends",void 0),v([Ie()],t.prototype,"autoCalcShadowZBounds",void 0),v([Ie("orthoLeft")],t.prototype,"_orthoLeft",void 0),v([Ie("orthoRight")],t.prototype,"_orthoRight",void 0),v([Ie("orthoTop")],t.prototype,"_orthoTop",void 0),v([Ie("orthoBottom")],t.prototype,"_orthoBottom",void 0),t}(xm);function Cm(e,t,i){void 0===t&&(t={}),t.diameter||(t.diameter=1),t.segments||(t.segments=16);var r=Gh("",{slice:.5,diameter:t.diameter,segments:t.segments},i),n=qh("",{radius:t.diameter/2,tessellation:3*t.segments+(4-t.segments)},i);n.rotation.x=-Math.PI/2,n.parent=r;var o=Fa.MergeMeshes([n,r],!0);return o.name=e,o}a("BABYLON.DirectionalLight",Am);var Rm={CreateHemisphere:Cm};Fa.CreateHemisphere=function(e,t,i,r){return Cm(e,{segments:t,diameter:i},r)},qe.AddNodeConstructor("Light_Type_2",(function(e,t){return function(){return new Pm(e,V.Zero(),V.Zero(),0,0,t)}}));var Pm=function(e){function t(t,i,r,n,o,a){var s=e.call(this,t,a)||this;return s._innerAngle=0,s._projectionTextureMatrix=z.Zero(),s._projectionTextureLightNear=1e-6,s._projectionTextureLightFar=1e3,s._projectionTextureUpDirection=V.Up(),s._projectionTextureViewLightDirty=!0,s._projectionTextureProjectionLightDirty=!0,s._projectionTextureDirty=!0,s._projectionTextureViewTargetVector=V.Zero(),s._projectionTextureViewLightMatrix=z.Zero(),s._projectionTextureProjectionLightMatrix=z.Zero(),s._projectionTextureScalingMatrix=z.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),s.position=i,s.direction=r,s.angle=n,s.exponent=o,s}return m(t,e),Object.defineProperty(t.prototype,"angle",{get:function(){return this._angle},set:function(e){this._angle=e,this._cosHalfAngle=Math.cos(.5*e),this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute(),this._computeAngleValues()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"innerAngle",{get:function(){return this._innerAngle},set:function(e){this._innerAngle=e,this._computeAngleValues()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"shadowAngleScale",{get:function(){return this._shadowAngleScale},set:function(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"projectionTextureMatrix",{get:function(){return this._projectionTextureMatrix},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"projectionTextureLightNear",{get:function(){return this._projectionTextureLightNear},set:function(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"projectionTextureLightFar",{get:function(){return this._projectionTextureLightFar},set:function(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"projectionTextureUpDirection",{get:function(){return this._projectionTextureUpDirection},set:function(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"projectionTexture",{get:function(){return this._projectionTexture},set:function(e){var i=this;this._projectionTexture!==e&&(this._projectionTexture=e,this._projectionTextureDirty=!0,this._projectionTexture&&!this._projectionTexture.isReady()&&(t._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled((function(){i._markMeshesAsLightDirty()})):t._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce((function(){i._markMeshesAsLightDirty()}))))},enumerable:!1,configurable:!0}),t._IsProceduralTexture=function(e){return void 0!==e.onGeneratedObservable},t._IsTexture=function(e){return void 0!==e.onLoadObservable},Object.defineProperty(t.prototype,"projectionTextureProjectionLightMatrix",{get:function(){return this._projectionTextureProjectionLightMatrix},set:function(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"SpotLight"},t.prototype.getTypeID=function(){return wa.LIGHTTYPEID_SPOTLIGHT},t.prototype._setDirection=function(t){e.prototype._setDirection.call(this,t),this._projectionTextureViewLightDirty=!0},t.prototype._setPosition=function(t){e.prototype._setPosition.call(this,t),this._projectionTextureViewLightDirty=!0},t.prototype._setDefaultShadowProjectionMatrix=function(e,t,i){var r=this.getScene().activeCamera;if(r){this._shadowAngleScale=this._shadowAngleScale||1;var n=this._shadowAngleScale*this._angle,o=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,s=this.getScene().getEngine().useReverseDepthBuffer;z.PerspectiveFovLHToRef(n,1,s?a:o,s?o:a,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,s)}},t.prototype._computeProjectionTextureViewLightMatrix=function(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.getShadowDirection(),this._projectionTextureViewTargetVector),z.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)},t.prototype._computeProjectionTextureProjectionLightMatrix=function(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;var e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),r=-i*t,n=1/Math.tan(this._angle/2);z.FromValuesToRef(n/1,0,0,0,0,n,0,0,0,0,i,1,0,0,r,0,this._projectionTextureProjectionLightMatrix)},t.prototype._computeProjectionTextureMatrix=function(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof Ja){var e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;z.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,.5,0,.5,.5,.5,1,this._projectionTextureScalingMatrix)}this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)},t.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightDirection",3),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},t.prototype._computeAngleValues=function(){this._lightAngleScale=1/Math.max(.001,Math.cos(.5*this._innerAngle)-this._cosHalfAngle),this._lightAngleOffset=-this._cosHalfAngle*this._lightAngleScale},t.prototype.transferTexturesToEffect=function(e,t){return this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),e.setMatrix("textureProjectionMatrix"+t,this._projectionTextureMatrix),e.setTexture("projectionLightSampler"+t,this.projectionTexture)),this},t.prototype.transferToEffect=function(e,t){var i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),i=V.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=V.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",i.x,i.y,i.z,this._cosHalfAngle,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,t),this},t.prototype.transferToNodeMaterialEffect=function(e,t){var i;return i=this.computeTransformedInformation()?V.Normalize(this.transformedDirection):V.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-i.x,-i.y,-i.z):e.setFloat3(t,i.x,i.y,i.z),this},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._projectionTexture&&this._projectionTexture.dispose()},t.prototype.getDepthMinZ=function(e){var t=this._scene.getEngine(),i=void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i},t.prototype.getDepthMaxZ=function(e){var t=this._scene.getEngine(),i=void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:i},t.prototype.prepareLightSpecificDefines=function(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!(!this.projectionTexture||!this.projectionTexture.isReady())},v([Ie()],t.prototype,"angle",null),v([Ie()],t.prototype,"innerAngle",null),v([Ie()],t.prototype,"shadowAngleScale",null),v([Ie()],t.prototype,"exponent",void 0),v([Ie()],t.prototype,"projectionTextureLightNear",null),v([Ie()],t.prototype,"projectionTextureLightFar",null),v([Ie()],t.prototype,"projectionTextureUpDirection",null),v([Me("projectedLightTexture")],t.prototype,"_projectionTexture",void 0),t}(xm);a("BABYLON.SpotLight",Pm);var Im=function(e){function t(t){void 0===t&&(t=Ih.DefaultUtilityLayer);var i=e.call(this,t)||this;return i._cachedPosition=new V,i._cachedForward=new V(0,0,1),i._pointerObserver=null,i.onClickedObservable=new f,i._light=null,i.attachedMesh=new Uo("",i.gizmoLayer.utilityLayerScene),i._attachedMeshParent=new Fo("parent",i.gizmoLayer.utilityLayerScene),i.attachedMesh.parent=i._attachedMeshParent,i._material=new Uu("light",i.gizmoLayer.utilityLayerScene),i._material.diffuseColor=new Z(.5,.5,.5),i._material.specularColor=new Z(.1,.1,.1),i._pointerObserver=t.utilityLayerScene.onPointerObservable.add((function(e){i._light&&(i._isHovered=!(!e.pickInfo||-1==i._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),i._isHovered&&0===e.event.button&&i.onClickedObservable.notifyObservers(i._light))}),Gr.POINTERDOWN),i}return m(t,e),Object.defineProperty(t.prototype,"attachedNode",{get:function(){return this.attachedMesh},set:function(e){ae.Warn("Nodes cannot be attached to LightGizmo. Attach to a mesh instead.")},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"light",{get:function(){return this._light},set:function(e){var i=this;if(this._light=e,e){this._lightMesh&&this._lightMesh.dispose(),this._lightMesh=e instanceof Ch?t._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof Am?t._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof Pm?t._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):t._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach((function(e){e.material=i._material})),this._lightMesh.parent=this._rootMesh;var r=this.gizmoLayer._getSharedGizmoLight();if(r.includedOnlyMeshes=r.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new G,this.attachedMesh.reservedDataStore||(this.attachedMesh.reservedDataStore={}),this.attachedMesh.reservedDataStore.lightGizmo=this,e.parent&&this._attachedMeshParent.freezeWorldMatrix(e.parent.getWorldMatrix()),e.position&&(this.attachedMesh.position.copyFrom(e.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)),e.direction){this.attachedMesh.setDirection(e.direction),this.attachedMesh.computeWorldMatrix(!0);var n=this._getMeshForward();this._cachedForward.copyFrom(n)}this._update()}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"material",{get:function(){return this._material},enumerable:!1,configurable:!0}),t.prototype._getMeshForward=function(){var e=this.attachedMesh.forward;return this.attachedMesh.getScene().useRightHandedSystem&&(e.negateToRef(H.Vector3[0]),e=H.Vector3[0]),e},t.prototype._update=function(){if(e.prototype._update.call(this),this._light){if(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position)if(this.attachedMesh.position.equals(this._cachedPosition))this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position);else{var t=this.attachedMesh.position;this._light.position=new V(t.x,t.y,t.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}if(this._light.direction){var i=this._getMeshForward();if(V.DistanceSquared(i,this._cachedForward)>1e-4){var r=i;this._light.direction=new V(r.x,r.y,r.z),this._cachedForward.copyFrom(i)}else V.DistanceSquared(i,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(i))}}},t.prototype.dispose=function(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),e.prototype.dispose.call(this),this._attachedMeshParent.dispose()},t._CreateHemisphericLightMesh=function(e){var i=new Fa("hemisphereLight",e),r=Cm(i.name,{segments:10,diameter:1},e);return r.position.z=-.15,r.rotation.x=Math.PI/2,r.parent=i,this._CreateLightLines(3,e).parent=i,i.scaling.scaleInPlace(t._Scale),i.rotation.x=Math.PI/2,i},t._CreatePointLightMesh=function(e){var i=new Fa("pointLight",e),r=Gh(i.name,{segments:10,diameter:1},e);return r.rotation.x=Math.PI/2,r.parent=i,this._CreateLightLines(5,e).parent=i,i.scaling.scaleInPlace(t._Scale),i.rotation.x=Math.PI/2,i},t._CreateSpotLightMesh=function(e){var i=new Fa("spotLight",e);Gh(i.name,{segments:10,diameter:1},e).parent=i;var r=Cm(i.name,{segments:10,diameter:2},e);return r.parent=i,r.rotation.x=-Math.PI/2,this._CreateLightLines(2,e).parent=i,i.scaling.scaleInPlace(t._Scale),i.rotation.x=Math.PI/2,i},t._CreateDirectionalLightMesh=function(e){var i=new Fa("directionalLight",e),r=new Fa(i.name,e);r.parent=i,Gh(i.name,{diameter:1.2,segments:10},e).parent=r;var n=xh(i.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);n.parent=r;var o=n.clone(i.name);o.scaling.y=.5,o.position.x+=1.25;var a=n.clone(i.name);a.scaling.y=.5,a.position.x+=-1.25;var s=xh(i.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return s.position.y+=3,s.parent=r,(o=s.clone(i.name)).position.y=1.5,o.position.x+=1.25,(a=s.clone(i.name)).position.y=1.5,a.position.x+=-1.25,r.scaling.scaleInPlace(t._Scale),r.rotation.z=Math.PI/2,r.rotation.y=Math.PI/2,i},t._Scale=.007,t._CreateLightLines=function(e,t){var i=new Fa("root",t);i.rotation.x=Math.PI/2;var r=new Fa("linePivot",t);r.parent=i;var n=xh("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},t);if(n.position.y=n.scaling.y/2+1.2,n.parent=r,e<2)return r;for(var o=0;o<4;o++){var a=r.clone("lineParentClone");a.rotation.z=Math.PI/4,a.rotation.y=Math.PI/2+Math.PI/2*o,a.getChildMeshes()[0].scaling.y=.5,a.getChildMeshes()[0].scaling.x=a.getChildMeshes()[0].scaling.z=.8,a.getChildMeshes()[0].position.y=a.getChildMeshes()[0].scaling.y/2+1.2}if(e<3)return i;for(o=0;o<4;o++){var s=r.clone("linePivotClone");s.rotation.z=Math.PI/2,s.rotation.y=Math.PI/2*o}if(e<4)return i;for(o=0;o<4;o++){var l=r.clone("linePivotClone");l.rotation.z=Math.PI+Math.PI/4,l.rotation.y=Math.PI/2+Math.PI/2*o,l.getChildMeshes()[0].scaling.y=.5,l.getChildMeshes()[0].scaling.x=l.getChildMeshes()[0].scaling.z=.8,l.getChildMeshes()[0].position.y=l.getChildMeshes()[0].scaling.y/2+1.2}return e<5||(r.clone("linePivotClone").rotation.z=Math.PI),i},t}(Oh),Mm=function(e){function t(t,i,r){void 0===t&&(t=Ih.DefaultUtilityLayer);var n=e.call(this,t)||this;return n._pointerObserver=null,n.onClickedObservable=new f,n._camera=null,n._invProjection=new z,n._material=new Uu("cameraGizmoMaterial",n.gizmoLayer.utilityLayerScene),n._frustumLinesColor=r,n._material.diffuseColor=null!=i?i:new Z(.5,.5,.5),n._material.specularColor=new Z(.1,.1,.1),n._pointerObserver=t.utilityLayerScene.onPointerObservable.add((function(e){n._camera&&(n._isHovered=!(!e.pickInfo||-1==n._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),n._isHovered&&0===e.event.button&&n.onClickedObservable.notifyObservers(n._camera))}),Gr.POINTERDOWN),n}return m(t,e),Object.defineProperty(t.prototype,"displayFrustum",{get:function(){return this._cameraLinesMesh.isEnabled()},set:function(e){this._cameraLinesMesh.setEnabled(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"camera",{get:function(){return this._camera},set:function(e){var i,r,n=this;if(this._camera=e,this.attachedNode=e,e){this._customMeshSet||(this._cameraMesh&&this._cameraMesh.dispose(),this._cameraMesh=t._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraMesh.getChildMeshes(!1).forEach((function(e){e.material=n._material})),this._cameraMesh.parent=this._rootMesh),this._cameraLinesMesh&&this._cameraLinesMesh.dispose();var o=null!==(r=null===(i=this._frustumLinesColor)||void 0===i?void 0:i.toColor4(1))&&void 0!==r?r:new J(1,1,1,1);this._cameraLinesMesh=t._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene,o),this._cameraLinesMesh.parent=this._rootMesh,this.gizmoLayer.utilityLayerScene.activeCamera&&this.gizmoLayer.utilityLayerScene.activeCamera.maxZ<1.5*e.maxZ&&(this.gizmoLayer.utilityLayerScene.activeCamera.maxZ=1.5*e.maxZ),this.attachedNode.reservedDataStore||(this.attachedNode.reservedDataStore={}),this.attachedNode.reservedDataStore.cameraGizmo=this;var a=this.gizmoLayer._getSharedGizmoLight();a.includedOnlyMeshes=a.includedOnlyMeshes.concat(this._cameraMesh.getChildMeshes(!1)),this._update()}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"material",{get:function(){return this._material},enumerable:!1,configurable:!0}),t.prototype._update=function(){e.prototype._update.call(this),this._camera&&(this._camera.getProjectionMatrix().invertToRef(this._invProjection),this._cameraLinesMesh.setPivotMatrix(this._invProjection,!1),this._cameraLinesMesh.scaling.x=1/this._rootMesh.scaling.x,this._cameraLinesMesh.scaling.y=1/this._rootMesh.scaling.y,this._cameraLinesMesh.scaling.z=1/this._rootMesh.scaling.z,this._cameraMesh.parent=null,this._cameraMesh.rotation.y=.5*Math.PI*(this._camera.getScene().useRightHandedSystem?1:-1),this._cameraMesh.parent=this._rootMesh)},t.prototype.setCustomMesh=function(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._cameraMesh&&this._cameraMesh.dispose(),this._cameraMesh=e,this._cameraMesh.parent=this._rootMesh,this._customMeshSet=!0},t.prototype.dispose=function(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._material.dispose(),e.prototype.dispose.call(this)},t._CreateCameraMesh=function(e){var i=new Fa("rootCameraGizmo",e),r=new Fa(i.name,e);r.parent=i,Uh(i.name,{width:1,height:.8,depth:.5},e).parent=r;var n=xh(i.name,{height:.5,diameterTop:.8,diameterBottom:.8},e);n.parent=r,n.position.y=.3,n.position.x=-.6,n.rotation.x=.5*Math.PI;var o=xh(i.name,{height:.5,diameterTop:.6,diameterBottom:.6},e);o.parent=r,o.position.y=.5,o.position.x=.4,o.rotation.x=.5*Math.PI;var a=xh(i.name,{height:.5,diameterTop:.5,diameterBottom:.5},e);return a.parent=r,a.position.y=0,a.position.x=.6,a.rotation.z=.5*Math.PI,i.scaling.scaleInPlace(t._Scale),r.position.x=-.9,i},t._CreateCameraFrustum=function(e,t){var i=new Fa("rootCameraGizmo",e),r=new Fa(i.name,e);r.parent=i;for(var n=0;n<4;n+=2)for(var o=0;o<4;o+=2){var a=fd("lines",{points:[new V(-1+o,-1+n,-1),new V(-1+o,-1+n,1)],colors:[t,t]},e);a.parent=r,a.alwaysSelectAsActiveMesh=!0,a.isPickable=!1,(a=fd("lines",{points:[new V(-1,-1+o,-1+n),new V(1,-1+o,-1+n)],colors:[t,t]},e)).parent=r,a.alwaysSelectAsActiveMesh=!0,a.isPickable=!1,(a=fd("lines",{points:[new V(-1+o,-1,-1+n),new V(-1+o,1,-1+n)],colors:[t,t]},e)).parent=r,a.alwaysSelectAsActiveMesh=!0,a.isPickable=!1}return i},t._Scale=.05,t}(Oh);li.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";li.IncludesShadersStore.packingFunctions="vec4 pack(float depth)\n{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}\nfloat unpack(vec4 color)\n{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}";li.IncludesShadersStore.kernelBlurFragment="#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif\n";li.IncludesShadersStore.kernelBlurFragment2="#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif\n";li.ShadersStore.kernelBlurPixelShader="uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; }\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\n#include<packingFunctions>\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float computedWeight=0.0;\n#ifdef PACKEDFLOAT\nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}";li.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";li.ShadersStore.kernelBlurVertexShader="attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";var Om=function(e){function t(t,i,r,n,o,a,s,l,c,h,d,p){void 0===a&&(a=Ja.BILINEAR_SAMPLINGMODE),void 0===c&&(c=u.TEXTURETYPE_UNSIGNED_INT),void 0===h&&(h=""),void 0===d&&(d=!1),void 0===p&&(p=u.TEXTUREFORMAT_RGBA);var f=e.call(this,t,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],n,o,a,s,l,null,c,"kernelBlur",{varyingCount:0,depCount:0},!0,p)||this;return f._blockCompilation=d,f._packedFloat=!1,f._staticDefines="",f._staticDefines=h,f.direction=i,f.onApplyObservable.add((function(e){f._outputTexture?e.setFloat2("delta",1/f._outputTexture.width*f.direction.x,1/f._outputTexture.height*f.direction.y):e.setFloat2("delta",1/f.width*f.direction.x,1/f.height*f.direction.y)})),f.kernel=r,f}return m(t,e),Object.defineProperty(t.prototype,"kernel",{get:function(){return this._idealKernel},set:function(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this._blockCompilation||this._updateParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"packedFloat",{get:function(){return this._packedFloat},set:function(e){this._packedFloat!==e&&(this._packedFloat=e,this._blockCompilation||this._updateParameters())},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"BlurPostProcess"},t.prototype.updateEffect=function(e,t,i,r,n,o){void 0===e&&(e=null),void 0===t&&(t=null),void 0===i&&(i=null),this._updateParameters(n,o)},t.prototype._updateParameters=function(t,i){for(var r=this._kernel,n=(r-1)/2,o=[],a=[],s=0,l=0;l<r;l++){var c=l/(r-1),u=this._gaussianWeight(2*c-1);o[l]=l-n,a[l]=u,s+=u}for(l=0;l<a.length;l++)a[l]/=s;var h=[],d=[],p=[];for(l=0;l<=n;l+=2){var f=Math.min(l+1,Math.floor(n));if(l===f)p.push({o:o[l],w:a[l]});else{var _=f===n,m=a[l]+a[f]*(_?.5:1),g=o[l]+1/(1+a[l]/a[f]);0===g?(p.push({o:o[l],w:a[l]}),p.push({o:o[l+1],w:a[l+1]})):(p.push({o:g,w:m}),p.push({o:-g,w:m}))}}for(l=0;l<p.length;l++)d[l]=p[l].o,h[l]=p[l].w;o=d,a=h;var v=this.getEngine().getCaps().maxVaryingVectors,y=Math.max(v,0)-1,b=Math.min(o.length,y),T="";for(T+=this._staticDefines,-1!=this._staticDefines.indexOf("DOF")&&(T+="#define CENTER_WEIGHT ".concat(this._glslFloat(a[b-1]),"\n"),b--),l=0;l<b;l++)T+="#define KERNEL_OFFSET".concat(l," ").concat(this._glslFloat(o[l]),"\n"),T+="#define KERNEL_WEIGHT".concat(l," ").concat(this._glslFloat(a[l]),"\n");var E=0;for(l=y;l<o.length;l++)T+="#define KERNEL_DEP_OFFSET".concat(E," ").concat(this._glslFloat(o[l]),"\n"),T+="#define KERNEL_DEP_WEIGHT".concat(E," ").concat(this._glslFloat(a[l]),"\n"),E++;this.packedFloat&&(T+="#define PACKEDFLOAT 1"),this._blockCompilation=!1,e.prototype.updateEffect.call(this,T,null,null,{varyingCount:b,depCount:E},t,i)},t.prototype._nearestBestKernel=function(e){for(var t=Math.round(e),i=0,r=[t,t-1,t+1,t-2,t+2];i<r.length;i++){var n=r[i];if(n%2!=0&&Math.floor(n/2)%2==0&&n>0)return Math.max(n,3)}return Math.max(t,3)},t.prototype._gaussianWeight=function(e){var t=1/3,i=-e*e/(2*t*t);return 1/(Math.sqrt(2*Math.PI)*t)*Math.exp(i)},t.prototype._glslFloat=function(e,t){return void 0===t&&(t=8),e.toFixed(t).replace(/0+$/,"")},t._Parse=function(e,i,r,n){return Ke.Parse((function(){return new t(e.name,e.direction,e.kernel,e.options,i,e.renderTargetSamplingMode,r.getEngine(),e.reusable,e.textureType,void 0,!1)}),e,r,n)},v([Ie("kernel")],t.prototype,"_kernel",void 0),v([Ie("packedFloat")],t.prototype,"_packedFloat",void 0),v([Ne()],t.prototype,"direction",void 0),t}(hl);a("BABYLON.BlurPostProcess",Om);var Dm=function(e){function t(t,i,r,n,o,a,s){void 0===o&&(o=u.TEXTURETYPE_UNSIGNED_INT),void 0===a&&(a=Ja.BILINEAR_SAMPLINGMODE),void 0===s&&(s=!0);var l=e.call(this,t,i,r,n,!0,o,!1,a,s)||this;if(l.mirrorPlane=new sn(0,1,0,1),l._transformMatrix=z.Zero(),l._mirrorMatrix=z.Zero(),l._adaptiveBlurKernel=0,l._blurKernelX=0,l._blurKernelY=0,l._blurRatio=1,!(r=l.getScene()))return l;l.ignoreCameraViewport=!0,l._updateGammaSpace(),l._imageProcessingConfigChangeObserver=r.imageProcessingConfiguration.onUpdateParameters.add((function(){l._updateGammaSpace()}));var c,h=r.getEngine();return h.supportsUniformBuffers&&(l._sceneUBO=r.createSceneUniformBuffer('Scene for Mirror Texture (name "'.concat(t,'")'))),l.onBeforeBindObservable.add((function(){var e;null===(e=h._debugPushGroup)||void 0===e||e.call(h,"mirror generation for ".concat(t),1)})),l.onAfterUnbindObservable.add((function(){var e;null===(e=h._debugPopGroup)||void 0===e||e.call(h,1)})),l.onBeforeRenderObservable.add((function(){l._sceneUBO&&(l._currentSceneUBO=r.getSceneUniformBuffer(),r.setSceneUniformBuffer(l._sceneUBO),r.getSceneUniformBuffer().unbindEffect()),z.ReflectionToRef(l.mirrorPlane,l._mirrorMatrix),l._mirrorMatrix.multiplyToRef(r.getViewMatrix(),l._transformMatrix),r.setTransformMatrix(l._transformMatrix,r.getProjectionMatrix()),c=r.clipPlane,r.clipPlane=l.mirrorPlane,r._mirroredCameraPosition=V.TransformCoordinates(r.activeCamera.globalPosition,l._mirrorMatrix)})),l.onAfterRenderObservable.add((function(){l._sceneUBO&&r.setSceneUniformBuffer(l._currentSceneUBO),r.updateTransformMatrix(),r._mirroredCameraPosition=null,r.clipPlane=c})),l}return m(t,e),Object.defineProperty(t.prototype,"blurRatio",{get:function(){return this._blurRatio},set:function(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"adaptiveBlurKernel",{set:function(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"blurKernel",{set:function(e){this.blurKernelX=e,this.blurKernelY=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"blurKernelX",{get:function(){return this._blurKernelX},set:function(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"blurKernelY",{get:function(){return this._blurKernelY},set:function(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())},enumerable:!1,configurable:!0}),t.prototype._autoComputeBlurKernel=function(){var e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i},t.prototype._onRatioRescale=function(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()},t.prototype._updateGammaSpace=function(){var e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)},t.prototype._preparePostProcesses=function(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){var e=this.getScene().getEngine(),t=e.getCaps().textureFloatRender&&e.getCaps().textureFloatLinearFiltering?u.TEXTURETYPE_FLOAT:u.TEXTURETYPE_HALF_FLOAT;this._blurX=new Om("horizontal blur",new U(1,0),this._blurKernelX,this._blurRatio,null,Ja.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._renderTarget:this._blurX.alwaysForcePOT=!0,this._blurY=new Om("vertical blur",new U(0,1),this._blurKernelY,this._blurRatio,null,Ja.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)},t.prototype.clone=function(){var e=this.getScene();if(!e)return this;var i=this.getSize(),r=new t(this.name,i.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return r.hasAlpha=this.hasAlpha,r.level=this.level,r.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(r.renderList=this.renderList.slice(0)),r},t.prototype.serialize=function(){if(!this.name)return null;var t=e.prototype.serialize.call(this);return t.mirrorPlane=this.mirrorPlane.asArray(),t},t.prototype.dispose=function(){var t;e.prototype.dispose.call(this);var i=this.getScene();i&&i.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),null===(t=this._sceneUBO)||void 0===t||t.dispose()},t}(Pl);Ja._CreateMirror=function(e,t,i,r){return new Dm(e,t,i,r)};var Nm=function(e){function t(t,i,r,n,o,a,s,l,c,h,d,p,_,m,g){void 0===r&&(r=null),void 0===n&&(n=!1),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null),void 0===l&&(l=u.TEXTUREFORMAT_RGBA),void 0===c&&(c=!1),void 0===h&&(h=null),void 0===d&&(d=!1),void 0===p&&(p=.8),void 0===_&&(_=0);var v,y=this;return(y=e.call(this,i)||this)._lodScale=.8,y._lodOffset=0,y.onLoadObservable=new f,y.boundingBoxPosition=V.Zero(),y._rotationY=0,y._files=null,y._forcedExtension=null,y._extensions=null,y._textureMatrixRefraction=new z,y.name=t,y.url=t,y._noMipmap=n,y.hasAlpha=!1,y._format=l,y.isCube=!0,y._textureMatrix=z.Identity(),y._createPolynomials=d,y.coordinatesMode=Ja.CUBIC_MODE,y._extensions=r,y._files=o,y._forcedExtension=h,y._loaderOptions=m,y._useSRGBBuffer=g,y._lodScale=p,y._lodOffset=_,t||o?(y.updateURL(t,h,a,c,s,r,null===(v=y.getScene())||void 0===v?void 0:v.useDelayedTextureLoading,o),y):y}return m(t,e),Object.defineProperty(t.prototype,"boundingBoxSize",{get:function(){return this._boundingBoxSize},set:function(e){if(!this._boundingBoxSize||!this._boundingBoxSize.equals(e)){this._boundingBoxSize=e;var t=this.getScene();t&&t.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag)}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rotationY",{get:function(){return this._rotationY},set:function(e){this._rotationY=e,this.setReflectionTextureMatrix(z.RotationY(this._rotationY))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"noMipmap",{get:function(){return this._noMipmap},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"forcedExtension",{get:function(){return this._forcedExtension},enumerable:!1,configurable:!0}),t.CreateFromImages=function(e,i,r){var n="";return e.forEach((function(e){return n+=e})),new t(n,i,null,r,e)},t.CreateFromPrefilteredData=function(e,i,r,n){void 0===r&&(r=null),void 0===n&&(n=!0);var o=i.useDelayedTextureLoading;i.useDelayedTextureLoading=!1;var a=new t(e,i,null,!1,null,null,null,void 0,!0,r,n);return i.useDelayedTextureLoading=o,a},t.prototype.getClassName=function(){return"CubeTexture"},t.prototype.updateURL=function(e,t,i,r,n,o,a,s){void 0===i&&(i=null),void 0===r&&(r=!1),void 0===n&&(n=null),void 0===o&&(o=null),void 0===a&&(a=!1),void 0===s&&(s=null),this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,t&&(this._forcedExtension=t);var l=e.lastIndexOf("."),c=t||(l>-1?e.substring(l).toLowerCase():""),h=0===c.indexOf(".dds"),d=0===c.indexOf(".env"),p=0===c.indexOf(".basis");if(d?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=r,r&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),s)this._files=s;else if(p||d||h||o||(o=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,o){for(var f=0;f<o.length;f++)this._files.push(e+o[f]);this._extensions=o}a?(this.delayLoadState=u.DELAYLOADSTATE_NOTLOADED,this._delayedOnLoad=i,this._delayedOnError=n):this._loadTexture(i,n)},t.prototype.delayLoad=function(e){this.delayLoadState===u.DELAYLOADSTATE_NOTLOADED&&(e&&(this._forcedExtension=e),this.delayLoadState=u.DELAYLOADSTATE_LOADED,this._loadTexture(this._delayedOnLoad,this._delayedOnError))},t.prototype.getReflectionTextureMatrix=function(){return this._textureMatrix},t.prototype.setReflectionTextureMatrix=function(e){var t,i,r=this;if(e.updateFlag!==this._textureMatrix.updateFlag&&(e.isIdentity()!==this._textureMatrix.isIdentity()&&(null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(e){return-1!==e.getActiveTextures().indexOf(r)}))),this._textureMatrix=e,null===(i=this.getScene())||void 0===i?void 0:i.useRightHandedSystem)){var n=H.Vector3[0],o=H.Quaternion[0],a=H.Vector3[1];this._textureMatrix.decompose(n,o,a),o.z*=-1,o.w*=-1,z.ComposeToRef(n,o,a,this._textureMatrixRefraction)}},t.prototype.getRefractionTextureMatrix=function(){var e;return(null===(e=this.getScene())||void 0===e?void 0:e.useRightHandedSystem)?this._textureMatrixRefraction:this._textureMatrix},t.prototype._loadTexture=function(e,t){var i,r=this;void 0===e&&(e=null),void 0===t&&(t=null);var n=this.getScene(),o=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);var a=function(){var t;r.onLoadObservable.notifyObservers(r),o&&(o.dispose(),null===(t=r.getScene())||void 0===t||t.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag)),e&&e()},s=function(e,i){r._loadingError=!0,r._errorObject={message:e,exception:i},t&&t(e,i),Ja.OnTextureLoadErrorObservable.notifyObservers(r)};this._texture?this._texture.isReady?rr.SetImmediate((function(){return a()})):this._texture.onLoadedObservable.add((function(){return a()})):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,n,this._lodScale,this._lodOffset,e,s,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,n,this._files,this._noMipmap,e,s,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),null===(i=this._texture)||void 0===i||i.onLoadedObservable.add((function(){return r.onLoadObservable.notifyObservers(r)})))},t.Parse=function(e,i,r){var n=Ke.Parse((function(){var n,o=!1;return e.prefiltered&&(o=e.prefiltered),new t(r+(null!==(n=e.url)&&void 0!==n?n:e.name),i,e.extensions,!1,e.files||null,null,null,void 0,o,e.forcedExtension)}),e,i);if(e.boundingBoxPosition&&(n.boundingBoxPosition=V.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(n.boundingBoxSize=V.FromArray(e.boundingBoxSize)),e.animations)for(var o=0;o<e.animations.length;o++){var a=e.animations[o],l=s("BABYLON.Animation");l&&n.animations.push(l.Parse(a))}return n},t.prototype.clone=function(){var e=this,i=0,r=Ke.Clone((function(){var r=new t(e.url,e.getScene()||e._getEngine(),e._extensions,e._noMipmap,e._files);return i=r.uniqueId,r}),this);return r.uniqueId=i,r},v([Ie()],t.prototype,"url",void 0),v([Fe()],t.prototype,"boundingBoxPosition",void 0),v([Fe()],t.prototype,"boundingBoxSize",null),v([Ie("rotationY")],t.prototype,"rotationY",null),v([Ie("files")],t.prototype,"_files",void 0),v([Ie("forcedExtension")],t.prototype,"_forcedExtension",void 0),v([Ie("extensions")],t.prototype,"_extensions",void 0),v([ke("textureMatrix")],t.prototype,"_textureMatrix",void 0),v([ke("textureMatrixRefraction")],t.prototype,"_textureMatrixRefraction",void 0),t}(Ya);Ja._CubeTextureParser=Nm.Parse,a("BABYLON.CubeTexture",Nm);li.IncludesShadersStore.backgroundFragmentDeclaration="uniform vec4 vEyePosition;uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;uniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef PROJECTED_GROUND\nuniform vec2 projectedGroundInfos;\n#endif\n";li.IncludesShadersStore.backgroundUboDeclaration="layout(std140,column_major) uniform;uniform Material\n{uniform vec4 vPrimaryColor;uniform vec4 vPrimaryColorShadow;uniform vec2 vDiffuseInfos;uniform vec2 vReflectionInfos;uniform mat4 diffuseMatrix;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;uniform float pointSize;uniform float shadowLevel;uniform float alpha;uniform vec3 vBackgroundCenter;uniform vec4 vReflectionControl;uniform vec2 projectedGroundInfos;};\n#include<sceneUboDeclaration>\n";li.ShadersStore.backgroundPixelShader="#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#include<helperFunctions>\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV==1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV==2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include<logDepthDeclaration>\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#ifdef PROJECTED_GROUND\nfloat diskIntersectWithBackFaceCulling(vec3 ro,vec3 rd,vec3 c,float r) {float d=rd.y;if(d>0.0) { return 1e6; }\nvec3 o=ro-c;float t=-o.y/d;vec3 q=o+rd*t;return (dot(q,q)<r*r) ? t : 1e6;}\nfloat sphereIntersect(vec3 ro,vec3 rd,float ra) {float b=dot(ro,rd);float c=dot(ro,ro)-ra*ra;float h=b*b-c;if(h<0.0) { return -1.0; }\nh=sqrt(h);return-b+h;}\nvec3 project(vec3 viewDirectionW,vec3 eyePosition) {float radius=projectedGroundInfos.x;float height=projectedGroundInfos.y;vec3 camDir=-viewDirectionW;float skySphereDistance=sphereIntersect(eyePosition,camDir,radius);vec3 skySpherePositionW=eyePosition+camDir*skySphereDistance;vec3 p=normalize(skySpherePositionW);eyePosition.y-=height;float sIntersection=sphereIntersect(eyePosition,p,radius);vec3 h=vec3(0.0,-height,0.0);float dIntersection=diskIntersectWithBackFaceCulling(eyePosition,p,h,radius);p=(eyePosition+min(sIntersection,dIntersection)*p);return p;}\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\nfloat shadow=1.;float globalShadow=0.;float shadowLightCount=0.;float aggShadow=0.;float numLights=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n#ifndef BACKMAT_SHADOWONLY\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\n#ifdef PROJECTED_GROUND\nvec3 reflectionVector=project(viewDirectionW,vEyePosition.xyz);reflectionVector=vec3(reflectionMatrix*vec4(reflectionVector,1.));\n#else\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);} else {reflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\nvec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;vec3 reflectionReflectance0=vReflectionControl.yyy;vec3 reflectionReflectance90=vReflectionControl.zzz;float VdotN=dot(normalize(vEyePosition.xyz),normalW);vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor;\n#endif\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\nvec4 color=vec4(finalColor,finalAlpha);\n#else\nvec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha);\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n#if !defined(SKIPFINALCOLORCLAMP)\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#endif\n#else\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0);\n#endif\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";li.IncludesShadersStore.backgroundVertexDeclaration="uniform mat4 view;uniform mat4 viewProjection;uniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n";li.ShadersStore.backgroundVertexShader="precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<instancesDeclaration>\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);}\n#else\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#endif\nvec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vDirectionW=normalize(segment);} else {vDirectionW=normalize(vDirectionW+(vDirectionW-segment));}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n";var Fm=function(e){function t(){var t=e.call(this)||this;return t.DIFFUSE=!1,t.DIFFUSEDIRECTUV=0,t.GAMMADIFFUSE=!1,t.DIFFUSEHASALPHA=!1,t.OPACITYFRESNEL=!1,t.REFLECTIONBLUR=!1,t.REFLECTIONFRESNEL=!1,t.REFLECTIONFALLOFF=!1,t.TEXTURELODSUPPORT=!1,t.PREMULTIPLYALPHA=!1,t.USERGBCOLOR=!1,t.USEHIGHLIGHTANDSHADOWCOLORS=!1,t.BACKMAT_SHADOWONLY=!1,t.NOISE=!1,t.REFLECTIONBGR=!1,t.PROJECTED_GROUND=!1,t.IMAGEPROCESSING=!1,t.VIGNETTE=!1,t.VIGNETTEBLENDMODEMULTIPLY=!1,t.VIGNETTEBLENDMODEOPAQUE=!1,t.TONEMAPPING=0,t.CONTRAST=!1,t.COLORCURVES=!1,t.COLORGRADING=!1,t.COLORGRADING3D=!1,t.SAMPLER3DGREENDEPTH=!1,t.SAMPLER3DBGRMAP=!1,t.DITHER=!1,t.IMAGEPROCESSINGPOSTPROCESS=!1,t.SKIPFINALCOLORCLAMP=!1,t.EXPOSURE=!1,t.MULTIVIEW=!1,t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.EQUIRECTANGULAR_RELFECTION_FOV=!1,t.MAINUV1=!1,t.MAINUV2=!1,t.UV1=!1,t.UV2=!1,t.CLIPPLANE=!1,t.CLIPPLANE2=!1,t.CLIPPLANE3=!1,t.CLIPPLANE4=!1,t.CLIPPLANE5=!1,t.CLIPPLANE6=!1,t.POINTSIZE=!1,t.FOG=!1,t.NORMAL=!1,t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,t.INSTANCES=!1,t.SHADOWFLOAT=!1,t.LOGARITHMICDEPTH=!1,t.NONUNIFORMSCALING=!1,t.ALPHATEST=!1,t.rebuild(),t}return m(t,e),t}(Gs),Lm=function(e){function t(t,i){var r=e.call(this,t,i)||this;return r.primaryColor=Z.White(),r._primaryColorShadowLevel=0,r._primaryColorHighlightLevel=0,r.reflectionTexture=null,r.reflectionBlur=0,r.diffuseTexture=null,r._shadowLights=null,r.shadowLights=null,r.shadowLevel=0,r.sceneCenter=V.Zero(),r.opacityFresnel=!0,r.reflectionFresnel=!1,r.reflectionFalloffDistance=0,r.reflectionAmount=1,r.reflectionReflectance0=.05,r.reflectionReflectance90=.5,r.useRGBColor=!0,r.enableNoise=!1,r._fovMultiplier=1,r.useEquirectangularFOV=!1,r._maxSimultaneousLights=4,r.maxSimultaneousLights=4,r._shadowOnly=!1,r.shadowOnly=!1,r._imageProcessingObserver=null,r.switchToBGR=!1,r._enableGroundProjection=!1,r.enableGroundProjection=!1,r.projectedGroundRadius=1e3,r.projectedGroundHeight=10,r._renderTargets=new ar(16),r._reflectionControls=k.Zero(),r._white=Z.White(),r._primaryShadowColor=Z.Black(),r._primaryHighlightColor=Z.Black(),r._attachImageProcessingConfiguration(null),r.getRenderTargetTextures=function(){return r._renderTargets.reset(),r._diffuseTexture&&r._diffuseTexture.isRenderTarget&&r._renderTargets.push(r._diffuseTexture),r._reflectionTexture&&r._reflectionTexture.isRenderTarget&&r._renderTargets.push(r._reflectionTexture),r._renderTargets},r}return m(t,e),Object.defineProperty(t.prototype,"_perceptualColor",{get:function(){return this.__perceptualColor},set:function(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"primaryColorShadowLevel",{get:function(){return this._primaryColorShadowLevel},set:function(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"primaryColorHighlightLevel",{get:function(){return this._primaryColorHighlightLevel},set:function(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"reflectionStandardFresnelWeight",{set:function(e){var i=e;i<.5?(i*=2,this.reflectionReflectance0=t.StandardReflectance0*i,this.reflectionReflectance90=t.StandardReflectance90*i):(i=2*i-1,this.reflectionReflectance0=t.StandardReflectance0+(1-t.StandardReflectance0)*i,this.reflectionReflectance90=t.StandardReflectance90+(1-t.StandardReflectance90)*i)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"fovMultiplier",{get:function(){return this._fovMultiplier},set:function(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))},enumerable:!1,configurable:!0}),t.prototype._attachImageProcessingConfiguration=function(e){var t=this;e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((function(){t._computePrimaryColorFromPerceptualColor(),t._markAllSubMeshesAsImageProcessingDirty()}))))},Object.defineProperty(t.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this.imageProcessingConfiguration.colorGradingTexture=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorCurves",{get:function(){return this.imageProcessingConfiguration.colorCurves},set:function(e){this.imageProcessingConfiguration.colorCurves=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hasRenderTargetTextures",{get:function(){return!(!this._diffuseTexture||!this._diffuseTexture.isRenderTarget)||!(!this._reflectionTexture||!this._reflectionTexture.isRenderTarget)},enumerable:!1,configurable:!0}),t.prototype.needAlphaTesting=function(){return!0},t.prototype.needAlphaBlending=function(){return this.alpha<1||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||this._shadowOnly},t.prototype.isReadyForSubMesh=function(e,t,i){void 0===i&&(i=!1);var r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new Fm);var n=this.getScene(),o=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;var a=n.getEngine();if(pa(n,e,o,!1,this._maxSimultaneousLights),o._needNormals=!0,ba(n,o),o._areTexturesDirty){if(o._needUVs=!1,n.texturesEnabled){if(n.getEngine().getCaps().textureLOD&&(o.TEXTURELODSUPPORT=!0),this._diffuseTexture&&xu.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;ta(this._diffuseTexture,o,"DIFFUSE"),o.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,o.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,o.OPACITYFRESNEL=this._opacityFresnel}else o.DIFFUSE=!1,o.DIFFUSEDIRECTUV=0,o.DIFFUSEHASALPHA=!1,o.GAMMADIFFUSE=!1,o.OPACITYFRESNEL=!1;var s=this._reflectionTexture;if(s&&xu.ReflectionTextureEnabled){if(!s.isReadyOrNotBlocking())return!1;switch(o.REFLECTION=!0,o.GAMMAREFLECTION=s.gammaSpace,o.RGBDREFLECTION=s.isRGBD,o.REFLECTIONBLUR=this._reflectionBlur>0,o.LODINREFLECTIONALPHA=s.lodLevelInAlpha,o.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,o.REFLECTIONBGR=this.switchToBGR,s.coordinatesMode===Ja.INVCUBIC_MODE&&(o.INVERTCUBICMAP=!0),o.REFLECTIONMAP_3D=s.isCube,o.REFLECTIONMAP_OPPOSITEZ=o.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!s.invertZ:s.invertZ,s.coordinatesMode){case Ja.EXPLICIT_MODE:o.REFLECTIONMAP_EXPLICIT=!0;break;case Ja.PLANAR_MODE:o.REFLECTIONMAP_PLANAR=!0;break;case Ja.PROJECTION_MODE:o.REFLECTIONMAP_PROJECTION=!0;break;case Ja.SKYBOX_MODE:o.REFLECTIONMAP_SKYBOX=!0;break;case Ja.SPHERICAL_MODE:o.REFLECTIONMAP_SPHERICAL=!0;break;case Ja.EQUIRECTANGULAR_MODE:o.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Ja.FIXED_EQUIRECTANGULAR_MODE:o.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Ja.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:o.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Ja.CUBIC_MODE:case Ja.INVCUBIC_MODE:default:o.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(o.REFLECTIONFRESNEL=!0,o.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(o.REFLECTIONFRESNEL=!1,o.REFLECTIONFALLOFF=!1)}else o.REFLECTION=!1,o.REFLECTIONFRESNEL=!1,o.REFLECTIONFALLOFF=!1,o.REFLECTIONBLUR=!1,o.REFLECTIONMAP_3D=!1,o.REFLECTIONMAP_SPHERICAL=!1,o.REFLECTIONMAP_PLANAR=!1,o.REFLECTIONMAP_CUBIC=!1,o.REFLECTIONMAP_PROJECTION=!1,o.REFLECTIONMAP_SKYBOX=!1,o.REFLECTIONMAP_EXPLICIT=!1,o.REFLECTIONMAP_EQUIRECTANGULAR=!1,o.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,o.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,o.INVERTCUBICMAP=!1,o.REFLECTIONMAP_OPPOSITEZ=!1,o.LODINREFLECTIONALPHA=!1,o.GAMMAREFLECTION=!1,o.RGBDREFLECTION=!1}o.PREMULTIPLYALPHA=this.alphaMode===u.ALPHA_PREMULTIPLIED||this.alphaMode===u.ALPHA_PREMULTIPLIED_PORTERDUFF,o.USERGBCOLOR=this._useRGBColor,o.NOISE=this._enableNoise}if(o._areLightsDirty&&(o.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel),o.BACKMAT_SHADOWONLY=this._shadowOnly),o._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(o)}if(o._areMiscDirty&&(o.REFLECTIONMAP_3D&&this._enableGroundProjection?(o.PROJECTED_GROUND=!0,o.REFLECTIONMAP_SKYBOX=!0):o.PROJECTED_GROUND=!1),da(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),o),_a(n,a,this,o,i,null,t.getRenderingMesh().hasThinInstances),ya(e,o,!1,!0,!1)&&e&&(n.getEngine().getCaps().standardDerivatives||e.isVerticesDataPresent(Nr.NormalKind)||(e.createNormals(!0),ae.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name))),o.isDirty){o.markAsProcessed(),n.resetCachedMaterial();var l=new ll;o.FOG&&l.addFallback(0,"FOG"),o.POINTSIZE&&l.addFallback(1,"POINTSIZE"),o.MULTIVIEW&&l.addFallback(0,"MULTIVIEW"),ua(o,l,this._maxSimultaneousLights);var c=[Nr.PositionKind];o.NORMAL&&c.push(Nr.NormalKind),o.UV1&&c.push(Nr.UVKind),o.UV2&&c.push(Nr.UV2Kind),la(c,e,o,l),ca(c,o);var h=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos","logarithmicDepthConstant"];Go(h);var d=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],p=["Material","Scene"];pr&&(pr.PrepareUniforms(h,o),pr.PrepareSamplers(d,o)),Aa({uniformsNames:h,uniformBuffersNames:p,samplers:d,defines:o,maxSimultaneousLights:this._maxSimultaneousLights});var f=o.toString(),_=n.getEngine().createEffect("background",{attributes:c,uniformsNames:h,uniformBuffersNames:p,samplers:d,defines:f,fallbacks:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},a);t.setEffect(_,o,this._materialContext),this.buildUniformLayout()}return!(!t.effect||!t.effect.isReady()||(o._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))},t.prototype._computePrimaryColorFromPerceptualColor=function(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor,this.getScene().getEngine().useExactSrgbConversions),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())},t.prototype._computePrimaryColors=function(){0===this._primaryColorShadowLevel&&0===this._primaryColorHighlightLevel||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))},t.prototype.buildUniformLayout=function(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.addUniform("projectedGroundInfos",2),this._uniformBuffer.create()},t.prototype.unbind=function(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),e.prototype.unbind.call(this)},t.prototype.bindOnlyWorldMatrix=function(e){this._activeEffect.setMatrix("world",e)},t.prototype.bindForSubMesh=function(e,t,i){var r=this.getScene(),n=i.materialDefines;if(n){var o=i.effect;if(o){this._activeEffect=o,this.bindOnlyWorldMatrix(e),na(t,this._activeEffect);var a=this._mustRebind(r,o,i,t.visibility);if(a){this._uniformBuffer.bindToEffect(o,"Material"),this.bindViewProjection(o);var s=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync&&!i._drawWrapper._forceRebindOnNextCall||(r.texturesEnabled&&(this._diffuseTexture&&xu.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),ia(this._diffuseTexture,this._uniformBuffer,"diffuse")),s&&xu.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",s.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",s.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",s.getSize().width,s.lodGenerationScale,s.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),n.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),r.texturesEnabled&&(this._diffuseTexture&&xu.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),s&&xu.ReflectionTextureEnabled&&(n.REFLECTIONBLUR&&n.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",s):n.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",s._lodTextureMid||s),this._uniformBuffer.setTexture("reflectionSamplerLow",s._lodTextureLow||s),this._uniformBuffer.setTexture("reflectionSamplerHigh",s._lodTextureHigh||s)):this._uniformBuffer.setTexture("reflectionSampler",s),n.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w))),n.PROJECTED_GROUND&&this._uniformBuffer.updateFloat2("projectedGroundInfos",this.projectedGroundRadius,this.projectedGroundHeight)),Ho(this._activeEffect,this,r),r.bindEyePosition(o)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(o,"Material"),this._needToBindSceneUbo=!0);!a&&this.isFrozen||(r.lightsEnabled&&sa(r,t,this._activeEffect,n,this._maxSimultaneousLights),this.bindView(o),Qo(r,t,this._activeEffect,!0),this._useLogarithmicDepth&&Ko(n,o,r),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),this._uniformBuffer.update()}}},t.prototype.hasTexture=function(t){return!!e.prototype.hasTexture.call(this,t)||this._reflectionTexture===t||this._diffuseTexture===t},t.prototype.dispose=function(t,i){void 0===t&&(t=!1),void 0===i&&(i=!1),i&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e.prototype.dispose.call(this,t)},t.prototype.clone=function(e){var i=this;return Ke.Clone((function(){return new t(e,i.getScene())}),this)},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.customType="BABYLON.BackgroundMaterial",t},t.prototype.getClassName=function(){return"BackgroundMaterial"},t.Parse=function(e,i,r){return Ke.Parse((function(){return new t(e.name,i)}),e,i,r)},t.StandardReflectance0=.05,t.StandardReflectance90=.5,v([Oe()],t.prototype,"_primaryColor",void 0),v([Pe("_markAllSubMeshesAsLightsDirty")],t.prototype,"primaryColor",void 0),v([Oe()],t.prototype,"__perceptualColor",void 0),v([Ie()],t.prototype,"_primaryColorShadowLevel",void 0),v([Ie()],t.prototype,"_primaryColorHighlightLevel",void 0),v([Pe("_markAllSubMeshesAsLightsDirty")],t.prototype,"primaryColorHighlightLevel",null),v([Me()],t.prototype,"_reflectionTexture",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionTexture",void 0),v([Ie()],t.prototype,"_reflectionBlur",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionBlur",void 0),v([Me()],t.prototype,"_diffuseTexture",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTexture",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"shadowLights",void 0),v([Ie()],t.prototype,"_shadowLevel",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"shadowLevel",void 0),v([Fe()],t.prototype,"_sceneCenter",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"sceneCenter",void 0),v([Ie()],t.prototype,"_opacityFresnel",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"opacityFresnel",void 0),v([Ie()],t.prototype,"_reflectionFresnel",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionFresnel",void 0),v([Ie()],t.prototype,"_reflectionFalloffDistance",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionFalloffDistance",void 0),v([Ie()],t.prototype,"_reflectionAmount",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionAmount",void 0),v([Ie()],t.prototype,"_reflectionReflectance0",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionReflectance0",void 0),v([Ie()],t.prototype,"_reflectionReflectance90",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionReflectance90",void 0),v([Ie()],t.prototype,"_useRGBColor",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRGBColor",void 0),v([Ie()],t.prototype,"_enableNoise",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"enableNoise",void 0),v([Ie()],t.prototype,"_maxSimultaneousLights",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"maxSimultaneousLights",void 0),v([Ie()],t.prototype,"_shadowOnly",void 0),v([Pe("_markAllSubMeshesAsLightsDirty")],t.prototype,"shadowOnly",void 0),v([Ue()],t.prototype,"_imageProcessingConfiguration",void 0),v([Ie(),Pe("_markAllSubMeshesAsMiscDirty")],t.prototype,"enableGroundProjection",void 0),v([Ie()],t.prototype,"projectedGroundRadius",void 0),v([Ie()],t.prototype,"projectedGroundHeight",void 0),t}(ws);a("BABYLON.BackgroundMaterial",Lm);var wm=function(){function e(t,i){var r=this;this._errorHandler=function(e,t){r.onErrorObservable.notifyObservers({message:e,exception:t})},this._options=g(g({},e._GetDefaultOptions(i)),t),this._scene=i,this.onErrorObservable=new f,this._setupBackground(),this._setupImageProcessing()}return e._GetDefaultOptions=function(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new Z(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),groundOpacity:.9,enableGroundShadow:!0,groundShadowLevel:.5,enableGroundMirror:!1,groundMirrorSizeRatio:.3,groundMirrorBlurKernel:64,groundMirrorAmount:1,groundMirrorFresnelWeight:1,groundMirrorFallOffDistance:0,groundMirrorTextureType:u.TEXTURETYPE_UNSIGNED_INT,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._SkyboxTextureCDNUrl,skyboxColor:new Z(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:V.Zero(),setupImageProcessing:!0,environmentTexture:this._EnvironmentTextureCDNUrl,cameraExposure:.8,cameraContrast:1.2,toneMappingEnabled:!0}},Object.defineProperty(e.prototype,"rootMesh",{get:function(){return this._rootMesh},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"skybox",{get:function(){return this._skybox},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"skyboxTexture",{get:function(){return this._skyboxTexture},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"skyboxMaterial",{get:function(){return this._skyboxMaterial},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"ground",{get:function(){return this._ground},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"groundTexture",{get:function(){return this._groundTexture},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"groundMirror",{get:function(){return this._groundMirror},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"groundMirrorRenderList",{get:function(){return this._groundMirror?this._groundMirror.renderList:null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"groundMaterial",{get:function(){return this._groundMaterial},enumerable:!1,configurable:!0}),e.prototype.updateOptions=function(e){var t=g(g({},this._options),e);this._ground&&!t.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!t.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=t.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!t.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!t.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=t.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!t.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=t.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=t,this._setupBackground(),this._setupImageProcessing()},e.prototype.setMainColor=function(e){this.groundMaterial&&(this.groundMaterial.primaryColor=e),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=e),this.groundMirror&&(this.groundMirror.clearColor=new J(e.r,e.g,e.b,1))},e.prototype._setupImageProcessing=function(){this._options.setupImageProcessing&&(this._scene.imageProcessingConfiguration.contrast=this._options.cameraContrast,this._scene.imageProcessingConfiguration.exposure=this._options.cameraExposure,this._scene.imageProcessingConfiguration.toneMappingEnabled=this._options.toneMappingEnabled,this._setupEnvironmentTexture())},e.prototype._setupEnvironmentTexture=function(){if(!this._scene.environmentTexture)if(this._options.environmentTexture instanceof Ya)this._scene.environmentTexture=this._options.environmentTexture;else{var e=Nm.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}},e.prototype._setupBackground=function(){this._rootMesh||(this._rootMesh=new Fa("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;var e=this._getSceneSize();this._options.createGround&&(this._setupGround(e),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(e),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(e),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=e.rootPosition.x,this._rootMesh.position.z=e.rootPosition.z,this._rootMesh.position.y=e.rootPosition.y},e.prototype._getSceneSize=function(){var e=this,t=this._options.groundSize,i=this._options.skyboxSize,r=this._options.rootPosition;if(!this._scene.meshes||1===this._scene.meshes.length)return{groundSize:t,skyboxSize:i,rootPosition:r};var n=this._scene.getWorldExtends((function(t){return t!==e._ground&&t!==e._rootMesh&&t!==e._skybox})),o=n.max.subtract(n.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof Nc&&this._scene.activeCamera.upperRadiusLimit&&(i=t=2*this._scene.activeCamera.upperRadiusLimit);var a=o.length();a>t&&(i=t=2*a),t*=1.1,i*=1.5,(r=n.min.add(o.scale(.5))).y=n.min.y-this._options.groundYBias}return{groundSize:t,skyboxSize:i,rootPosition:r}},e.prototype._setupGround=function(e){var t=this;this._ground&&!this._ground.isDisposed()||(this._ground=fs("BackgroundPlane",{size:e.groundSize},this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add((function(){t._ground=null}))),this._ground.receiveShadows=this._options.enableGroundShadow},e.prototype._setupGroundMaterial=function(){this._groundMaterial||(this._groundMaterial=new Lm("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=u.ALPHA_PREMULTIPLIED_PORTERDUFF,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)},e.prototype._setupGroundDiffuseTexture=function(){this._groundMaterial&&(this._groundTexture||(this._options.groundTexture instanceof Ya?this._groundMaterial.diffuseTexture=this._options.groundTexture:(this._groundTexture=new Ja(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._groundTexture.gammaSpace=!1,this._groundTexture.hasAlpha=!0,this._groundMaterial.diffuseTexture=this._groundTexture)))},e.prototype._setupGroundMirrorTexture=function(e){var t=Ja.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new Dm("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,Ja.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new sn(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(var i=0;i<this._scene.meshes.length;i++){var r=this._scene.meshes[i];r!==this._ground&&r!==this._skybox&&r!==this._rootMesh&&this._groundMirror.renderList.push(r)}var n=this._options.groundColor.toGammaSpace(this._scene.getEngine().useExactSrgbConversions);this._groundMirror.clearColor=new J(n.r,n.g,n.b,1),this._groundMirror.adaptiveBlurKernel=this._options.groundMirrorBlurKernel},e.prototype._setupMirrorInGroundMaterial=function(){this._groundMaterial&&(this._groundMaterial.reflectionTexture=this._groundMirror,this._groundMaterial.reflectionFresnel=!0,this._groundMaterial.reflectionAmount=this._options.groundMirrorAmount,this._groundMaterial.reflectionStandardFresnelWeight=this._options.groundMirrorFresnelWeight,this._groundMaterial.reflectionFalloffDistance=this._options.groundMirrorFallOffDistance)},e.prototype._setupSkybox=function(e){var t=this;this._skybox&&!this._skybox.isDisposed()||(this._skybox=Uh("BackgroundSkybox",{size:e.skyboxSize,sideOrientation:Fa.BACKSIDE},this._scene),this._skybox.onDisposeObservable.add((function(){t._skybox=null}))),this._skybox.parent=this._rootMesh},e.prototype._setupSkyboxMaterial=function(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new Lm("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)},e.prototype._setupSkyboxReflectionTexture=function(){this._skyboxMaterial&&(this._skyboxTexture||(this._options.skyboxTexture instanceof Ya?this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture:(this._skyboxTexture=new Nm(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=Ja.SKYBOX_MODE,this._skyboxTexture.gammaSpace=!1,this._skyboxMaterial.reflectionTexture=this._skyboxTexture)))},e.prototype.dispose=function(){this._groundMaterial&&this._groundMaterial.dispose(!0,!0),this._skyboxMaterial&&this._skyboxMaterial.dispose(!0,!0),this._rootMesh.dispose(!1)},e._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",e._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",e._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env",e}(),Bm=function(e){function t(i,r,n,o,a){void 0===a&&(a=null);var s=e.call(this,i,o)||this;s.onError=a,s._halfDome=!1,s._crossEye=!1,s._useDirectMapping=!1,s._textureMode=t.MODE_MONOSCOPIC,s._onBeforeCameraRenderObserver=null,s.onLoadErrorObservable=new f,s.onLoadObservable=new f,o=s.getScene(),i=i||"textureDome",n.resolution=0|Math.abs(n.resolution)||32,n.clickToPlay=Boolean(n.clickToPlay),n.autoPlay=void 0===n.autoPlay||Boolean(n.autoPlay),n.loop=void 0===n.loop||Boolean(n.loop),n.size=Math.abs(n.size)||(o.activeCamera?.48*o.activeCamera.maxZ:1e3),void 0===n.useDirectMapping?s._useDirectMapping=!0:s._useDirectMapping=n.useDirectMapping,void 0===n.faceForward&&(n.faceForward=!0),s._setReady(!1),n.mesh?s._mesh=n.mesh:s._mesh=Gh(i+"_mesh",{segments:n.resolution,diameter:n.size,updatable:!1,sideOrientation:Fa.BACKSIDE},o);var l=s._material=new Lm(i+"_material",o);l.useEquirectangularFOV=!0,l.fovMultiplier=1,l.opacityFresnel=!1;var c=s._initTexture(r,o,n);if(s.texture=c,s._mesh.material=l,s._mesh.parent=s,s._halfDomeMask=Gh("",{slice:.5,diameter:.98*n.size,segments:2*n.resolution,sideOrientation:Fa.BACKSIDE},o),s._halfDomeMask.rotate(_n.X,-Math.PI/2),s._halfDomeMask.parent=s._mesh,s._halfDome=!!n.halfDomeMode,s._halfDomeMask.setEnabled(s._halfDome),s._crossEye=!!n.crossEyeMode,s._texture.anisotropicFilteringLevel=1,s._texture.onLoadObservable.addOnce((function(){s._setReady(!0)})),n.faceForward&&o.activeCamera){var u=o.activeCamera,h=V.Forward(),d=V.TransformNormal(h,u.getViewMatrix());d.normalize(),s.rotation.y=Math.acos(V.Dot(h,d))}return s._changeTextureMode(s._textureMode),s}return m(t,e),Object.defineProperty(t.prototype,"texture",{get:function(){return this._texture},set:function(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=Ja.CLAMP_ADDRESSMODE,this._texture.wrapV=Ja.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=Ja.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=Ja.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"mesh",{get:function(){return this._mesh},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"fovMultiplier",{get:function(){return this._material.fovMultiplier},set:function(e){this._material.fovMultiplier=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"textureMode",{get:function(){return this._textureMode},set:function(e){this._textureMode!==e&&this._changeTextureMode(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"halfDome",{get:function(){return this._halfDome},set:function(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"crossEye",{get:function(){return this._crossEye},set:function(e){this._crossEye=e,this._changeTextureMode(this._textureMode)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"material",{get:function(){return this._material},enumerable:!1,configurable:!0}),t.prototype._changeTextureMode=function(e){var i=this;switch(this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._textureMode=e,this._texture.uScale=1,this._texture.vScale=1,this._texture.uOffset=0,this._texture.vOffset=0,this._texture.vAng=0,e){case t.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case t.MODE_SIDEBYSIDE:this._texture.uScale=this._halfDome?.99999:.5;var r=this._halfDome?0:.5,n=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((function(e){var t=e.isRightCamera;i._crossEye&&(t=!t),i._texture.uOffset=t?r:n}));break;case t.MODE_TOPBOTTOM:this._texture.vScale=this._halfDome?.99999:.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((function(e){var t=e.isRightCamera;i._crossEye&&(t=!t),i._texture.vOffset=t?.5:0}))}},t.prototype.dispose=function(t,i){void 0===i&&(i=!1),this._texture.dispose(),this._mesh.dispose(),this._material.dispose(),this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this.onLoadErrorObservable.clear(),this.onLoadObservable.clear(),e.prototype.dispose.call(this,t,i)},t.MODE_MONOSCOPIC=0,t.MODE_TOPBOTTOM=1,t.MODE_SIDEBYSIDE=2,t}(Fo),Um=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),Object.defineProperty(t.prototype,"photoTexture",{get:function(){return this.texture},set:function(e){this.texture=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"imageMode",{get:function(){return this.textureMode},set:function(e){this.textureMode=e},enumerable:!1,configurable:!0}),t.prototype._initTexture=function(e,t,i){var r=this;return new Ja(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,(function(){r.onLoadObservable.notifyObservers()}),(function(e,t){r.onLoadErrorObservable.notifyObservers(e||"Unknown error occured"),r.onError&&r.onError(e,t)}))},t.MODE_MONOSCOPIC=Bm.MODE_MONOSCOPIC,t.MODE_TOPBOTTOM=Bm.MODE_TOPBOTTOM,t.MODE_SIDEBYSIDE=Bm.MODE_SIDEBYSIDE,t}(Bm),Vm=0,km=function(e){if(!e.environmentBRDFTexture){var t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;var i=e._blockEntityCollection;e._blockEntityCollection=!1;var r=Ja.CreateFromBase64String("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSeEoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==","EnvironmentBRDFTexture"+Vm++,e,!0,!1,Ja.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;var n=e.getEngine().getLoadedTexturesCache(),o=n.indexOf(r.getInternalTexture());-1!==o&&n.splice(o,1),r.isRGBD=!0,r.wrapU=Ja.CLAMP_ADDRESSMODE,r.wrapV=Ja.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=r,e.useDelayedTextureLoading=t,Np.ExpandRGBDTexture(r);var a=e.getEngine().onContextRestoredObservable.add((function(){r.isRGBD=!0;var t=e.onBeforeRenderObservable.add((function(){r.isReady()&&(e.onBeforeRenderObservable.remove(t),Np.ExpandRGBDTexture(r))}))}));e.onDisposeObservable.add((function(){e.getEngine().onContextRestoredObservable.remove(a)}))}return e.environmentBRDFTexture},Gm={GetEnvironmentBRDFTexture:km},zm=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.BRDF_V_HEIGHT_CORRELATED=!1,t.MS_BRDF_ENERGY_CONSERVATION=!1,t.SPHERICAL_HARMONICS=!1,t.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!1,t}return m(t,e),t}(Gs),Wm=function(e){function t(i,r){void 0===r&&(r=!0);var n=e.call(this,i,"PBRBRDF",90,new zm,r)||this;return n._useEnergyConservation=t.DEFAULT_USE_ENERGY_CONSERVATION,n.useEnergyConservation=t.DEFAULT_USE_ENERGY_CONSERVATION,n._useSmithVisibilityHeightCorrelated=t.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,n.useSmithVisibilityHeightCorrelated=t.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,n._useSphericalHarmonics=t.DEFAULT_USE_SPHERICAL_HARMONICS,n.useSphericalHarmonics=t.DEFAULT_USE_SPHERICAL_HARMONICS,n._useSpecularGlossinessInputEnergyConservation=t.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,n.useSpecularGlossinessInputEnergyConservation=t.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,n._internalMarkAllSubMeshesAsMiscDirty=i._dirtyCallbacks[u.MATERIAL_MiscDirtyFlag],n._enable(!0),n}return m(t,e),t.prototype._markAllSubMeshesAsMiscDirty=function(){this._internalMarkAllSubMeshesAsMiscDirty()},t.prototype.prepareDefines=function(e){e.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,e.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,e.SPHERICAL_HARMONICS=this._useSphericalHarmonics,e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=this._useSpecularGlossinessInputEnergyConservation},t.prototype.getClassName=function(){return"PBRBRDFConfiguration"},t.DEFAULT_USE_ENERGY_CONSERVATION=!0,t.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,t.DEFAULT_USE_SPHERICAL_HARMONICS=!0,t.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,v([Ie(),Pe("_markAllSubMeshesAsMiscDirty")],t.prototype,"useEnergyConservation",void 0),v([Ie(),Pe("_markAllSubMeshesAsMiscDirty")],t.prototype,"useSmithVisibilityHeightCorrelated",void 0),v([Ie(),Pe("_markAllSubMeshesAsMiscDirty")],t.prototype,"useSphericalHarmonics",void 0),v([Ie(),Pe("_markAllSubMeshesAsMiscDirty")],t.prototype,"useSpecularGlossinessInputEnergyConservation",void 0),t}(Nu);li.IncludesShadersStore.pbrFragmentDeclaration="uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor;\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REALTIME_FILTERING\nuniform vec2 vReflectionFilteringInfo;\n#endif\nuniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; \n#endif\n#endif\n#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC)\nuniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; \n#endif\n#ifdef CLEARCOAT\nuniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams;\n#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform vec4 vClearCoatInfos;\n#endif\n#ifdef CLEARCOAT_TEXTURE\nuniform mat4 clearCoatMatrix;\n#endif\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS\nuniform mat4 clearCoatRoughnessMatrix;\n#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT\nuniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance;\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix;\n#endif\n#endif\n#endif\n#ifdef IRIDESCENCE\nuniform vec4 vIridescenceParams;\n#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)\nuniform vec4 vIridescenceInfos;\n#endif\n#ifdef IRIDESCENCE_TEXTURE\nuniform mat4 iridescenceMatrix;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nuniform mat4 iridescenceThicknessMatrix;\n#endif\n#endif\n#ifdef ANISOTROPIC\nuniform vec3 vAnisotropy;\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix;\n#endif\n#endif\n#ifdef SHEEN\nuniform vec4 vSheenColor;\n#ifdef SHEEN_ROUGHNESS\nuniform float vSheenRoughness;\n#endif\n#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform vec4 vSheenInfos;\n#endif\n#ifdef SHEEN_TEXTURE\nuniform mat4 sheenMatrix;\n#endif\n#ifdef SHEEN_TEXTURE_ROUGHNESS\nuniform mat4 sheenRoughnessMatrix;\n#endif\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix;\n#ifdef REALTIME_FILTERING\nuniform vec2 vRefractionFilteringInfo;\n#endif\n#ifdef SS_DISPERSION\nuniform float dispersion;\n#endif\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix;\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix;\n#endif\nuniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity;uniform vec4 vTranslucencyColor;\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\nuniform vec2 vTranslucencyColorInfos;uniform mat4 translucencyColorMatrix;\n#endif\n#endif\n#ifdef PREPASS\n#ifdef SS_SCATTERING\nuniform float scatteringDiffusionProfile;\n#endif\n#endif\n#if DEBUGMODE>0\nuniform vec2 vDebugMode;\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include<decalFragmentDeclaration>\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22;\n#else\nuniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX;\n#endif\n#endif\n#define ADDITIONAL_FRAGMENT_DECLARATION\n";li.IncludesShadersStore.pbrUboDeclaration="layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec2 vReflectionInfos;vec2 vReflectionFilteringInfo;vec3 vReflectionPosition;vec3 vReflectionSize;vec3 vBumpInfos;mat4 albedoMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;mat4 reflectionMatrix;vec3 vReflectionColor;vec4 vAlbedoColor;vec4 vLightingIntensity;vec3 vReflectionMicrosurfaceInfos;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include<sceneUboDeclaration>\n#include<meshUboDeclaration>\n";li.IncludesShadersStore.pbrFragmentExtraDeclaration="varying vec3 vPositionW;\n#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\n#endif\n#include<mainUVVaryingDeclaration>[1..7]\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n";li.IncludesShadersStore.samplerFragmentAlternateDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying vec2 v_VARYINGNAME_UV;\n#endif\n#endif\n";li.IncludesShadersStore.pbrFragmentSamplersDeclaration="#include<samplerFragmentDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef CLEARCOAT\n#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)\n#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform sampler2D clearCoatRoughnessSampler;\n#endif\n#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)\n#endif\n#ifdef SHEEN\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)\n#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform sampler2D sheenRoughnessSampler;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#include<samplerFragmentDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform samplerCube irradianceSampler;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform sampler2D irradianceSampler;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#ifdef SS_REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh;\n#endif\n#endif\n#endif\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)\n#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_SAMPLERNAME_,translucencyColor)\n#endif\n";li.IncludesShadersStore.subSurfaceScatteringFunctions="bool testLightingForSSS(float diffusionProfile)\n{return diffusionProfile<1.;}";li.IncludesShadersStore.importanceSampling="vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}\nvec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}\nvec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { \nfloat phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}";li.IncludesShadersStore.pbrHelperFunctions="#define MINIMUMVARIANCE 0.0005\nfloat convertRoughnessToAverageSlope(float roughness)\n{return square(roughness)+MINIMUMVARIANCE;}\nfloat fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;}\nvec2 getAARoughnessFactors(vec3 normalVector) {\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor);\n#else\nreturn vec2(0.);\n#endif\n}\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_LEGACY\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;}\n#else\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;}\n#endif\n#endif\n#if defined(CLEARCOAT) || defined(SS_REFRACTION)\nvec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);}\nvec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));}\nvec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;}\nvec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0),\ncocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),\nclearCoatIntensity);return clearCoatAbsorption;}\n#endif\n#ifdef MICROSURFACEAUTOMATIC\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;}\n#endif\n";li.IncludesShadersStore.harmonicsFunctions="#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nvec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00\n+ vSphericalL1_1*(normal.y)\n+ vSphericalL10*(normal.z)\n+ vSphericalL11*(normal.x)\n+ vSphericalL2_2*(normal.y*normal.x)\n+ vSphericalL2_1*(normal.y*normal.z)\n+ vSphericalL20*((3.0*normal.z*normal.z)-1.0)\n+ vSphericalL21*(normal.z*normal.x)\n+ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));}\n#else\nvec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;}\n#endif\n#endif\n";li.IncludesShadersStore.pbrDirectLightingSetupFunctions="struct preLightingInfo\n{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness;\n#ifdef IRIDESCENCE\nfloat iridescenceIntensity;\n#endif\n};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightOffset=lightData.xyz-vPositionW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\npreLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\npreLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL;\n#ifdef SPECULARTERM\nresult.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));\n#endif\nreturn result;}";li.IncludesShadersStore.pbrDirectLightingFalloffFunctions="float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{return max(0.,1.0-length(lightOffset)/range);}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{return 1.0/maxEps(lightDistanceSquared);}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle)\n{falloff=max(0.,pow(cosAngle,exponent));}\nreturn falloff;}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}";li.IncludesShadersStore.pbrBRDFFunctions="#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);}\n#endif\n#ifdef ENVIRONMENTBRDF\nvec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV);\n#ifdef ENVIRONMENTBRDF_RGBD\nbrdfLookup.rgb=fromRGBD(brdfLookup.rgba);\n#endif\nreturn brdfLookup.rgb;}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y;\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y;\n#endif\nreturn reflectance;}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#endif\nreturn reflectance;}\n#endif\n/* NOT USED\n#if defined(SHEEN) && defined(SHEEN_SOFTER)\nfloat getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness)\n{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));}\n#endif\n*/\n#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)\nvec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF)\n/**\n* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture.\n* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table\n*/\nvec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;}\n#endif\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\nfloat fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90)\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\n#ifdef CLEARCOAT\nvec3 getR0RemappedForClearCoat(vec3 f0) {\n#ifdef CLEARCOAT_DEFAULTIOR\n#ifdef MOBILE\nreturn saturate(f0*(f0*0.526868+0.529324)-0.0482256);\n#else\nreturn saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);\n#endif\n#else\nvec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t);\n#endif\n}\n#endif\n#ifdef IRIDESCENCE\nconst mat3 XYZ_TO_REC709=mat3(\n3.2404542,-0.9692660, 0.0556434,\n-1.5371385, 1.8760108,-0.2040259,\n-0.4985314, 0.0415560, 1.0572252\n);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);}\nvec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));}\nfloat getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));}\nvec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;}\nvec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;}\nfloat cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR<outsideIOR) phi12=PI;float phi21=PI-phi12;vec3 baseIOR=getIORTfromAirToSurfaceR0(clamp(baseF0,0.0,0.9999)); \nvec3 R1=getR0fromIORs(baseIOR,iridescenceIOR);vec3 R23=fresnelSchlickGGX(cosTheta2,R1,vec3(1.));vec3 phi23=vec3(0.0);if (baseIOR[0]<iridescenceIOR) phi23[0]=PI;if (baseIOR[1]<iridescenceIOR) phi23[1]=PI;if (baseIOR[2]<iridescenceIOR) phi23[2]=PI;float opd=2.0*iridescenceIOR*thinFilmThickness*cosTheta2;vec3 phi=vec3(phi21)+phi23;vec3 R123=clamp(R12*R23,1e-5,0.9999);vec3 r123=sqrt(R123);vec3 Rs=square(T121)*R23/(vec3(1.0)-R123);vec3 C0=R12+Rs;I=C0;vec3 Cm=Rs-T121;for (int m=1; m<=2; ++m)\n{Cm*=r123;vec3 Sm=2.0*evalSensitivity(float(m)*opd,float(m)*phi);I+=Cm*Sm;}\nreturn max(I,vec3(0.0));}\n#endif\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{float a2=square(alphaG);float d=NdotH*NdotH*(a2-1.0)+1.0;return a2/(PI*d*d);}\n#ifdef SHEEN\nfloat normalDistributionFunction_CharlieSheen(float NdotH,float alphaG)\n{float invR=1./alphaG;float cos2h=NdotH*NdotH;float sin2h=1.-cos2h;return (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);}\n#endif\n#ifdef ANISOTROPIC\nfloat normalDistributionFunction_BurleyGGX_Anisotropic(float NdotH,float TdotH,float BdotH,const vec2 alphaTB) {float a2=alphaTB.x*alphaTB.y;vec3 v=vec3(alphaTB.y*TdotH,alphaTB.x *BdotH,a2*NdotH);float v2=dot(v,v);float w2=a2/v2;return a2*w2*w2*RECIPROCAL_PI;}\n#endif\n#ifdef BRDF_V_HEIGHT_CORRELATED\nfloat smithVisibility_GGXCorrelated(float NdotL,float NdotV,float alphaG) {\n#ifdef MOBILE\nfloat GGXV=NdotL*(NdotV*(1.0-alphaG)+alphaG);float GGXL=NdotV*(NdotL*(1.0-alphaG)+alphaG);return 0.5/(GGXV+GGXL);\n#else\nfloat a2=alphaG*alphaG;float GGXV=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);float GGXL=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);return 0.5/(GGXV+GGXL);\n#endif\n}\n#else\nfloat smithVisibilityG1_TrowbridgeReitzGGXFast(float dot,float alphaG)\n{\n#ifdef MOBILE\nreturn 1.0/(dot+alphaG+(1.0-alphaG)*dot ));\n#else\nfloat alphaSquared=alphaG*alphaG;return 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot));\n#endif\n}\nfloat smithVisibility_TrowbridgeReitzGGXFast(float NdotL,float NdotV,float alphaG)\n{float visibility=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);return visibility;}\n#endif\n#ifdef ANISOTROPIC\nfloat smithVisibility_GGXCorrelated_Anisotropic(float NdotL,float NdotV,float TdotV,float BdotV,float TdotL,float BdotL,const vec2 alphaTB) {float lambdaV=NdotL*length(vec3(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));float lambdaL=NdotV*length(vec3(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));float v=0.5/(lambdaV+lambdaL);return v;}\n#endif\n#ifdef CLEARCOAT\nfloat visibility_Kelemen(float VdotH) {return 0.25/(VdotH*VdotH); }\n#endif\n#ifdef SHEEN\nfloat visibility_Ashikhmin(float NdotL,float NdotV)\n{return 1./(4.*(NdotL+NdotV-NdotL*NdotV));}\n/* NOT USED\n#ifdef SHEEN_SOFTER\nfloat l(float x,float alphaG)\n{float oneMinusAlphaSq=(1.0-alphaG)*(1.0-alphaG);float a=mix(21.5473,25.3245,oneMinusAlphaSq);float b=mix(3.82987,3.32435,oneMinusAlphaSq);float c=mix(0.19823,0.16801,oneMinusAlphaSq);float d=mix(-1.97760,-1.27393,oneMinusAlphaSq);float e=mix(-4.32054,-4.85967,oneMinusAlphaSq);return a/(1.0+b*pow(x,c))+d*x+e;}\nfloat lambdaSheen(float cosTheta,float alphaG)\n{return abs(cosTheta)<0.5 ? exp(l(cosTheta,alphaG)) : exp(2.0*l(0.5,alphaG)-l(1.0-cosTheta,alphaG));}\nfloat visibility_CharlieSheen(float NdotL,float NdotV,float alphaG)\n{float G=1.0/(1.0+lambdaSheen(NdotV,alphaG)+lambdaSheen(NdotL,alphaG));return G/(4.0*NdotV*NdotL);}\n#endif\n*/\n#endif\nfloat diffuseBRDF_Burley(float NdotL,float NdotV,float VdotH,float roughness) {float diffuseFresnelNV=pow5(saturateEps(1.0-NdotL));float diffuseFresnelNL=pow5(saturateEps(1.0-NdotV));float diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;float fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);return fresnel/PI;}\n#ifdef SS_TRANSLUCENCY\nvec3 transmittanceBRDF_Burley(const vec3 tintColor,const vec3 diffusionDistance,float thickness) {vec3 S=1./maxEps(diffusionDistance);vec3 temp=exp((-0.333333333*thickness)*S);return tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);}\nfloat computeWrappedDiffuseNdotL(float NdotL,float w) {float t=1.0+w;float invt2=1.0/square(t);return saturate((NdotL+w)*invt2);}\n#endif\n";li.IncludesShadersStore.hdrFilteringFunctions="#ifdef NUM_SAMPLES\n#if NUM_SAMPLES>0\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nfloat radicalInverse_VdC(uint bits) \n{bits=(bits<<16u) | (bits>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return float(bits)*2.3283064365386963e-10; }\nvec2 hammersley(uint i,uint N)\n{return vec2(float(i)/float(N),radicalInverse_VdC(i));}\n#else\nfloat vanDerCorpus(int n,int base)\n{float invBase=1.0/float(base);float denom =1.0;float result =0.0;for(int i=0; i<32; ++i)\n{if(n>0)\n{denom =mod(float(n),2.0);result+=denom*invBase;invBase=invBase/2.0;n =int(float(n)/2.0);}}\nreturn result;}\nvec2 hammersley(int i,int N)\n{return vec2(float(i)/float(N),vanDerCorpus(i,2));}\n#endif\nfloat log4(float x) {return log2(x)/2.;}\nconst float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);const float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;const float K=4.;\n#define inline\nvec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)\n{vec3 n=normalize(inputN);vec3 result=vec3(0.0);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0);\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nfor(uint i=0u; i<NUM_SAMPLES; ++i)\n#else\nfor(int i=0; i<NUM_SAMPLES; ++i)\n#endif\n{vec2 Xi=hammersley(i,NUM_SAMPLES);vec3 Ls=hemisphereCosSample(Xi);Ls=normalize(Ls);vec3 Ns=vec3(0.,0.,1.);float NoL=dot(Ns,Ls);if (NoL>0.) {float pdf_inversed=PI/NoL;float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(l,0.0,maxLevel);vec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb;\n#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\n#endif\nresult+=c;}}\nresult=result*NUM_SAMPLES_FLOAT_INVERSED;return result;}\n#define inline\nvec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)\n{vec3 n=normalize(inputN);vec3 c=textureCube(inputTexture,n).rgb; \nif (alphaG==0.) {\n#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\n#endif\nreturn c;} else {vec3 result=vec3(0.);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0);float weight=0.;\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nfor(uint i=0u; i<NUM_SAMPLES; ++i)\n#else\nfor(int i=0; i<NUM_SAMPLES; ++i)\n#endif\n{vec2 Xi=hammersley(i,NUM_SAMPLES);vec3 H=hemisphereImportanceSampleDggx(Xi,alphaG);float NoV=1.;float NoH=H.z;float NoH2=H.z*H.z;float NoL=2.*NoH2-1.;vec3 L=vec3(2.*NoH*H.x,2.*NoH*H.y,NoL);L=normalize(L);if (NoL>0.) {float pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(float(l),0.0,maxLevel);weight+=NoL;vec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb;\n#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\n#endif\nresult+=c*NoL;}}\nresult=result/weight;return result;}}\n#endif\n#endif\n";li.IncludesShadersStore.pbrDirectLightingFunctions="#define CLEARCOATREFLECTANCE90 1.0\nstruct lightingInfo\n{vec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef CLEARCOAT\nvec4 clearCoat;\n#endif\n#ifdef SHEEN\nvec3 sheen;\n#endif\n};float adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) {\n#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\nfloat lightRoughness=lightRadius/lightDistance;float totalRoughness=saturate(lightRoughness+roughness);return totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nvec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {return mix(groundColor,lightColor,info.NdotL);}\nvec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {float diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;}\n#define inline\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return toLinearSpace(textureColor);}\n#ifdef SS_TRANSLUCENCY\nvec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance) {float NdotL=absEps(info.NdotLUnclamped);float wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);float trAdapt=step(0.,info.NdotLUnclamped);vec3 transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);float diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;}\n#endif\n#ifdef SPECULARTERM\nvec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);\n#ifdef IRIDESCENCE\nfresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);\n#endif\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\n#ifdef BRDF_V_HEIGHT_CORRELATED\nfloat smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG);\n#else\nfloat smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG);\n#endif\nvec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;}\n#endif\n#ifdef ANISOTROPIC\nvec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float TdotH=dot(T,info.H);float BdotH=dot(B,info.H);float TdotV=dot(T,V);float BdotV=dot(B,V);float TdotL=dot(T,info.L);float BdotL=dot(B,info.L);float alphaG=convertRoughnessToAverageSlope(info.roughness);vec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,square(geometricRoughnessFactor));vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);\n#ifdef IRIDESCENCE\nfresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);\n#endif\nfloat distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);float smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;}\n#endif\n#ifdef CLEARCOAT\nvec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {float NccdotL=saturateEps(dot(Ncc,info.L));float NccdotH=saturateEps(dot(Ncc,info.H));float clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);float fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);float kelemenVisibility=visibility_Kelemen(info.VdotH);float clearCoatTerm=fresnel*distribution*kelemenVisibility;return vec4(\nclearCoatTerm*info.attenuation*NccdotL*lightColor,\n1.0-fresnel\n);}\nvec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);float NdotLRefract=saturateEps(dot(Ncc,LRefract));vec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;}\n#endif\n#ifdef SHEEN\nvec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);float fresnel=1.;float distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER\nfloat visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG);\n#else */\nfloat visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */\nfloat sheenTerm=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;}\n#endif\n";li.IncludesShadersStore.pbrIBLFunctions="#if defined(REFLECTION) || defined(SS_REFRACTION)\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {float microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;float lod=log2(microsurfaceAverageSlopeTexels);return lod;}\nfloat getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {float lod=log2(cubeMapDimensionPixels)*roughness;return lod;}\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION)\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {float temp=NdotVUnclamped+ambientOcclusion;return saturate(square(temp)-1.0+ambientOcclusion);}\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION)\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {vec3 reflection=reflect(view,normal);float temp=saturate(1.0+1.1*dot(reflection,geometricNormal));return square(temp);}\n#endif\n#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA)\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {float microsurfaceAverageSlope=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);}\n#endif\n";li.IncludesShadersStore.pbrBlockAlbedoOpacity="struct albedoOpacityOutParams\n{vec3 surfaceAlbedo;float alpha;};\n#define pbr_inline\nvoid albedoOpacityBlock(\nin vec4 vAlbedoColor,\n#ifdef ALBEDO\nin vec4 albedoTexture,\nin vec2 albedoInfos,\n#endif\n#ifdef OPACITY\nin vec4 opacityMap,\nin vec2 vOpacityInfos,\n#endif\n#ifdef DETAIL\nin vec4 detailColor,\nin vec4 vDetailInfos,\n#endif\n#ifdef DECAL\nin vec4 decalColor,\nin vec4 vDecalInfos,\n#endif\nout albedoOpacityOutParams outParams\n)\n{vec3 surfaceAlbedo=vAlbedoColor.rgb;float alpha=vAlbedoColor.a;\n#ifdef ALBEDO\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\n#ifdef GAMMAALBEDO\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\n#else\nsurfaceAlbedo*=albedoTexture.rgb;\n#endif\nsurfaceAlbedo*=albedoInfos.y;\n#endif\n#ifndef DECAL_AFTER_DETAIL\n#include<decalFragment>\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nsurfaceAlbedo*=vColor.rgb;\n#endif\n#ifdef DETAIL\nfloat detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; \n#endif\n#ifdef DECAL_AFTER_DETAIL\n#include<decalFragment>\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALBEDO\n#ifdef OPACITY\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST \n#if DEBUGMODE != 88\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#endif\n#ifndef ALPHABLEND\nalpha=1.0;\n#endif\n#endif\n#endif\noutParams.surfaceAlbedo=surfaceAlbedo;outParams.alpha=alpha;}\n";li.IncludesShadersStore.pbrBlockReflectivity="struct reflectivityOutParams\n{float microSurface;float roughness;vec3 surfaceReflectivityColor;\n#ifdef METALLICWORKFLOW\nvec3 surfaceAlbedo;\n#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\nvec3 ambientOcclusionColor;\n#endif\n#if DEBUGMODE>0\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap;\n#endif\n#ifndef FROSTBITE_REFLECTANCE\nvec3 metallicF0;\n#endif\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap;\n#endif\n#endif\n#endif\n};\n#define pbr_inline\nvoid reflectivityBlock(\nin vec4 vReflectivityColor,\n#ifdef METALLICWORKFLOW\nin vec3 surfaceAlbedo,\nin vec4 metallicReflectanceFactors,\n#endif\n#ifdef REFLECTIVITY\nin vec3 reflectivityInfos,\nin vec4 surfaceMetallicOrReflectivityColorMap,\n#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\nin vec3 ambientOcclusionColorIn,\n#endif\n#ifdef MICROSURFACEMAP\nin vec4 microSurfaceTexel,\n#endif\n#ifdef DETAIL\nin vec4 detailColor,\nin vec4 vDetailInfos,\n#endif\nout reflectivityOutParams outParams\n)\n{float microSurface=vReflectivityColor.a;vec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\n#if DEBUGMODE>0\noutParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap;\n#endif\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g;\n#endif\n#endif\n#endif\n#ifdef DETAIL\nfloat detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);float loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);float hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5));\n#endif\n#ifdef MICROSURFACEMAP\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n#if DEBUGMODE>0\noutParams.metallicRoughness=metallicRoughness;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS\nmicroSurface=1.0-metallicRoughness.g;vec3 baseColor=surfaceAlbedo;\n#ifdef FROSTBITE_REFLECTANCE\noutParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r);\n#else\nvec3 metallicF0=metallicReflectanceFactors.rgb;\n#if DEBUGMODE>0\noutParams.metallicF0=metallicF0;\n#endif\noutParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0),vec3(0.,0.,0.),metallicRoughness.r);surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r);\n#endif\n#else\n#ifdef REFLECTIVITY\nsurfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb;\n#if DEBUGMODE>0\noutParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap;\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE\n#endif\n#endif\n#endif\nmicroSurface=saturate(microSurface);float roughness=1.-microSurface;outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.surfaceReflectivityColor=surfaceReflectivityColor;}\n";li.IncludesShadersStore.pbrBlockAmbientOcclusion="struct ambientOcclusionOutParams\n{vec3 ambientOcclusionColor;\n#if DEBUGMODE>0 && defined(AMBIENT)\nvec3 ambientOcclusionColorMap;\n#endif\n};\n#define pbr_inline\nvoid ambientOcclusionBlock(\n#ifdef AMBIENT\nin vec3 ambientOcclusionColorMap_,\nin vec4 vAmbientInfos,\n#endif\nout ambientOcclusionOutParams outParams\n)\n{vec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#if DEBUGMODE>0\noutParams.ambientOcclusionColorMap=ambientOcclusionColorMap;\n#endif\n#endif\noutParams.ambientOcclusionColor=ambientOcclusionColor;}\n";li.IncludesShadersStore.pbrBlockAlphaFresnel="#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\nstruct alphaFresnelOutParams\n{float alpha;};\n#define pbr_inline\nvoid alphaFresnelBlock(\nin vec3 normalW,\nin vec3 viewDirectionW,\nin float alpha,\nin float microSurface,\nout alphaFresnelOutParams outParams\n)\n{float opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);vec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (outParams.alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\noutParams.alpha=1.0;\n#endif\n#endif\n}\n#endif\n#endif\n";li.IncludesShadersStore.pbrBlockAnisotropic="#ifdef ANISOTROPIC\nstruct anisotropicOutParams\n{float anisotropy;vec3 anisotropicTangent;vec3 anisotropicBitangent;vec3 anisotropicNormal;\n#if DEBUGMODE>0 && defined(ANISOTROPIC_TEXTURE)\nvec3 anisotropyMapData;\n#endif\n};\n#define pbr_inline\nvoid anisotropicBlock(\nin vec3 vAnisotropy,\nin float roughness,\n#ifdef ANISOTROPIC_TEXTURE\nin vec3 anisotropyMapData,\n#endif\nin mat3 TBN,\nin vec3 normalW,\nin vec3 viewDirectionW,\nout anisotropicOutParams outParams\n)\n{float anisotropy=vAnisotropy.b;vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.);\n#ifdef ANISOTROPIC_TEXTURE\nanisotropy*=anisotropyMapData.b;\n#if DEBUGMODE>0\noutParams.anisotropyMapData=anisotropyMapData;\n#endif\nanisotropyMapData.rg=anisotropyMapData.rg*2.0-1.0;\n#ifdef ANISOTROPIC_LEGACY\nanisotropyDirection.rg*=anisotropyMapData.rg;\n#else\nanisotropyDirection.xy=mat2(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(anisotropyMapData.rg);\n#endif\n#endif\nmat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));vec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);vec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);}\n#endif\n";li.IncludesShadersStore.pbrBlockReflection="#ifdef REFLECTION\nstruct reflectionOutParams\n{vec4 environmentRadiance;vec3 environmentIrradiance;\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords;\n#else\nvec2 reflectionCoords;\n#endif\n#ifdef SS_TRANSLUCENCY\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nvec3 irradianceVector;\n#endif\n#endif\n#endif\n};\n#define pbr_inline\nvoid createReflectionCoords(\nin vec3 vPositionW,\nin vec3 normalW,\n#ifdef ANISOTROPIC\nin anisotropicOutParams anisotropicOut,\n#endif\n#ifdef REFLECTIONMAP_3D\nout vec3 reflectionCoords\n#else\nout vec2 reflectionCoords\n#endif\n)\n{\n#ifdef ANISOTROPIC\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal);\n#else\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nreflectionCoords=reflectionVector;\n#else\nreflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n}\n#define pbr_inline\n#define inline\nvoid sampleReflectionTexture(\nin float alphaG,\nin vec3 vReflectionMicrosurfaceInfos,\nin vec2 vReflectionInfos,\nin vec3 vReflectionColor,\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nin float NdotVUnclamped,\n#endif\n#ifdef LINEARSPECULARREFLECTION\nin float roughness,\n#endif\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSampler,\nconst vec3 reflectionCoords,\n#else\nin sampler2D reflectionSampler,\nconst vec2 reflectionCoords,\n#endif\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSamplerLow,\nin samplerCube reflectionSamplerHigh,\n#else\nin sampler2D reflectionSamplerLow,\nin sampler2D reflectionSamplerHigh,\n#endif\n#endif\n#ifdef REALTIME_FILTERING\nin vec2 vReflectionFilteringInfo,\n#endif\nout vec4 environmentRadiance\n)\n{\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#elif defined(LINEARSPECULARREFLECTION)\nfloat reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG);\n#endif\n#ifdef LODBASEDMICROSFURACE\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);float requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\n#ifdef REALTIME_FILTERING\nenvironmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0);\n#else\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#endif\n#else\nfloat lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentMid,\nlodReflectionNormalizedDoubled\n);} else {environmentRadiance=mix(\nenvironmentMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\nenvironmentRadiance.rgb*=vReflectionInfos.x;environmentRadiance.rgb*=vReflectionColor.rgb;}\n#define pbr_inline\n#define inline\nvoid reflectionBlock(\nin vec3 vPositionW,\nin vec3 normalW,\nin float alphaG,\nin vec3 vReflectionMicrosurfaceInfos,\nin vec2 vReflectionInfos,\nin vec3 vReflectionColor,\n#ifdef ANISOTROPIC\nin anisotropicOutParams anisotropicOut,\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nin float NdotVUnclamped,\n#endif\n#ifdef LINEARSPECULARREFLECTION\nin float roughness,\n#endif\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSampler,\n#else\nin sampler2D reflectionSampler,\n#endif\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nin vec3 vEnvironmentIrradiance,\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nin mat4 reflectionMatrix,\n#endif\n#endif\n#ifdef USEIRRADIANCEMAP\n#ifdef REFLECTIONMAP_3D\nin samplerCube irradianceSampler,\n#else\nin sampler2D irradianceSampler,\n#endif\n#endif\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSamplerLow,\nin samplerCube reflectionSamplerHigh,\n#else\nin sampler2D reflectionSamplerLow,\nin sampler2D reflectionSamplerHigh,\n#endif\n#endif\n#ifdef REALTIME_FILTERING\nin vec2 vReflectionFilteringInfo,\n#endif\nout reflectionOutParams outParams\n)\n{vec4 environmentRadiance=vec4(0.,0.,0.,0.);\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=vec3(0.);\n#else\nvec2 reflectionCoords=vec2(0.);\n#endif\ncreateReflectionCoords(\nvPositionW,\nnormalW,\n#ifdef ANISOTROPIC\nanisotropicOut,\n#endif\nreflectionCoords\n);sampleReflectionTexture(\nalphaG,\nvReflectionMicrosurfaceInfos,\nvReflectionInfos,\nvReflectionColor,\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nNdotVUnclamped,\n#endif\n#ifdef LINEARSPECULARREFLECTION\nroughness,\n#endif\n#ifdef REFLECTIONMAP_3D\nreflectionSampler,\nreflectionCoords,\n#else\nreflectionSampler,\nreflectionCoords,\n#endif\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\nreflectionSamplerHigh,\n#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\n#endif\nenvironmentRadiance\n);vec3 environmentIrradiance=vec3(0.,0.,0.);\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\n#ifdef ANISOTROPIC\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\n#ifdef INVERTCUBICMAP\nirradianceVector.y*=-1.0;\n#endif\n#if defined(REALTIME_FILTERING)\nenvironmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo);\n#else\nenvironmentIrradiance=computeEnvironmentIrradiance(irradianceVector);\n#endif\n#ifdef SS_TRANSLUCENCY\noutParams.irradianceVector=irradianceVector;\n#endif\n#endif\n#elif defined(USEIRRADIANCEMAP)\nvec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords);environmentIrradiance=environmentIrradiance4.rgb;\n#ifdef RGBDREFLECTION\nenvironmentIrradiance.rgb=fromRGBD(environmentIrradiance4);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\nenvironmentIrradiance*=vReflectionColor.rgb;outParams.environmentRadiance=environmentRadiance;outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;}\n#endif\n";li.IncludesShadersStore.pbrBlockSheen="#ifdef SHEEN\nstruct sheenOutParams\n{float sheenIntensity;vec3 sheenColor;float sheenRoughness;\n#ifdef SHEEN_LINKWITHALBEDO\nvec3 surfaceAlbedo;\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\nfloat sheenAlbedoScaling;\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nvec3 finalSheenRadianceScaled;\n#endif\n#if DEBUGMODE>0\n#ifdef SHEEN_TEXTURE\nvec4 sheenMapData;\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nvec3 sheenEnvironmentReflectance;\n#endif\n#endif\n};\n#define pbr_inline\n#define inline\nvoid sheenBlock(\nin vec4 vSheenColor,\n#ifdef SHEEN_ROUGHNESS\nin float vSheenRoughness,\n#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)\nin vec4 sheenMapRoughnessData,\n#endif\n#endif\nin float roughness,\n#ifdef SHEEN_TEXTURE\nin vec4 sheenMapData,\nin float sheenMapLevel,\n#endif\nin float reflectance,\n#ifdef SHEEN_LINKWITHALBEDO\nin vec3 baseColor,\nin vec3 surfaceAlbedo,\n#endif\n#ifdef ENVIRONMENTBRDF\nin float NdotV,\nin vec3 environmentBrdf,\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nin vec2 AARoughnessFactors,\nin vec3 vReflectionMicrosurfaceInfos,\nin vec2 vReflectionInfos,\nin vec3 vReflectionColor,\nin vec4 vLightingIntensity,\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSampler,\nin vec3 reflectionCoords,\n#else\nin sampler2D reflectionSampler,\nin vec2 reflectionCoords,\n#endif\nin float NdotVUnclamped,\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSamplerLow,\nin samplerCube reflectionSamplerHigh,\n#else\nin sampler2D reflectionSamplerLow,\nin sampler2D reflectionSamplerHigh,\n#endif\n#endif\n#ifdef REALTIME_FILTERING\nin vec2 vReflectionFilteringInfo,\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)\nin float seo,\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\nin float eho,\n#endif\n#endif\nout sheenOutParams outParams\n)\n{float sheenIntensity=vSheenColor.a;\n#ifdef SHEEN_TEXTURE\n#if DEBUGMODE>0\noutParams.sheenMapData=sheenMapData;\n#endif\n#endif\n#ifdef SHEEN_LINKWITHALBEDO\nfloat sheenFactor=pow5(1.0-sheenIntensity);vec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);float sheenRoughness=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor;\n#ifdef SHEEN_TEXTURE\nsheenIntensity*=sheenMapData.a;\n#endif\n#else\nvec3 sheenColor=vSheenColor.rgb;\n#ifdef SHEEN_TEXTURE\n#ifdef SHEEN_GAMMATEXTURE\nsheenColor.rgb*=toLinearSpace(sheenMapData.rgb);\n#else\nsheenColor.rgb*=sheenMapData.rgb;\n#endif\nsheenColor.rgb*=sheenMapLevel;\n#endif\n#ifdef SHEEN_ROUGHNESS\nfloat sheenRoughness=vSheenRoughness;\n#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE\n#if defined(SHEEN_TEXTURE)\nsheenRoughness*=sheenMapData.a;\n#endif\n#elif defined(SHEEN_TEXTURE_ROUGHNESS)\nsheenRoughness*=sheenMapRoughnessData.a;\n#endif\n#else\nfloat sheenRoughness=roughness;\n#ifdef SHEEN_TEXTURE\nsheenIntensity*=sheenMapData.a;\n#endif\n#endif\n#if !defined(SHEEN_ALBEDOSCALING)\nsheenIntensity*=(1.-reflectance);\n#endif\nsheenColor*=sheenIntensity;\n#endif\n#ifdef ENVIRONMENTBRDF\n/*#ifdef SHEEN_SOFTER\nvec3 environmentSheenBrdf=vec3(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness));\n#else*/\n#ifdef SHEEN_ROUGHNESS\nvec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness);\n#else\nvec3 environmentSheenBrdf=environmentBrdf;\n#endif\n/*#endif*/\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nfloat sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness);\n#ifdef SPECULARAA\nsheenAlphaG+=AARoughnessFactors.y;\n#endif\nvec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);sampleReflectionTexture(\nsheenAlphaG,\nvReflectionMicrosurfaceInfos,\nvReflectionInfos,\nvReflectionColor,\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nNdotVUnclamped,\n#endif\n#ifdef LINEARSPECULARREFLECTION\nsheenRoughness,\n#endif\nreflectionSampler,\nreflectionCoords,\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\nreflectionSamplerHigh,\n#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\n#endif\nenvironmentSheenRadiance\n);vec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf);\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)\nsheenEnvironmentReflectance*=seo;\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\nsheenEnvironmentReflectance*=eho;\n#endif\n#if DEBUGMODE>0\noutParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance;\n#endif\noutParams.finalSheenRadianceScaled=\nenvironmentSheenRadiance.rgb *\nsheenEnvironmentReflectance *\nvLightingIntensity.z;\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\noutParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b;\n#endif\noutParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;}\n#endif\n";li.IncludesShadersStore.pbrBlockClearcoat="struct clearcoatOutParams\n{vec3 specularEnvironmentR0;float conservationFactor;vec3 clearCoatNormalW;vec2 clearCoatAARoughnessFactors;float clearCoatIntensity;float clearCoatRoughness;\n#ifdef REFLECTION\nvec3 finalClearCoatRadianceScaled;\n#endif\n#ifdef CLEARCOAT_TINT\nvec3 absorption;float clearCoatNdotVRefract;vec3 clearCoatColor;float clearCoatThickness;\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nvec3 energyConservationFactorClearCoat;\n#endif\n#if DEBUGMODE>0\n#ifdef CLEARCOAT_BUMP\nmat3 TBNClearCoat;\n#endif\n#ifdef CLEARCOAT_TEXTURE\nvec2 clearCoatMapData;\n#endif\n#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)\nvec4 clearCoatTintMapData;\n#endif\n#ifdef REFLECTION\nvec4 environmentClearCoatRadiance;vec3 clearCoatEnvironmentReflectance;\n#endif\nfloat clearCoatNdotV;\n#endif\n};\n#ifdef CLEARCOAT\n#define pbr_inline\n#define inline\nvoid clearcoatBlock(\nin vec3 vPositionW,\nin vec3 geometricNormalW,\nin vec3 viewDirectionW,\nin vec2 vClearCoatParams,\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\nin vec4 clearCoatMapRoughnessData,\n#endif\nin vec3 specularEnvironmentR0,\n#ifdef CLEARCOAT_TEXTURE\nin vec2 clearCoatMapData,\n#endif\n#ifdef CLEARCOAT_TINT\nin vec4 vClearCoatTintParams,\nin float clearCoatColorAtDistance,\nin vec4 vClearCoatRefractionParams,\n#ifdef CLEARCOAT_TINT_TEXTURE\nin vec4 clearCoatTintMapData,\n#endif\n#endif\n#ifdef CLEARCOAT_BUMP\nin vec2 vClearCoatBumpInfos,\nin vec4 clearCoatBumpMapData,\nin vec2 vClearCoatBumpUV,\n#if defined(TANGENT) && defined(NORMAL)\nin mat3 vTBN,\n#else\nin vec2 vClearCoatTangentSpaceParams,\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nin mat4 normalMatrix,\n#endif\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nin vec3 faceNormal,\n#endif\n#ifdef REFLECTION\nin vec3 vReflectionMicrosurfaceInfos,\nin vec2 vReflectionInfos,\nin vec3 vReflectionColor,\nin vec4 vLightingIntensity,\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSampler,\n#else\nin sampler2D reflectionSampler,\n#endif\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSamplerLow,\nin samplerCube reflectionSamplerHigh,\n#else\nin sampler2D reflectionSamplerLow,\nin sampler2D reflectionSamplerHigh,\n#endif\n#endif\n#ifdef REALTIME_FILTERING\nin vec2 vReflectionFilteringInfo,\n#endif\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n#ifdef RADIANCEOCCLUSION\nin float ambientMonochrome,\n#endif\n#endif\n#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)\nin float frontFacingMultiplier,\n#endif\nout clearcoatOutParams outParams\n)\n{float clearCoatIntensity=vClearCoatParams.x;float clearCoatRoughness=vClearCoatParams.y;\n#ifdef CLEARCOAT_TEXTURE\nclearCoatIntensity*=clearCoatMapData.x;\n#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE\nclearCoatRoughness*=clearCoatMapData.y;\n#endif\n#if DEBUGMODE>0\noutParams.clearCoatMapData=clearCoatMapData;\n#endif\n#endif\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\nclearCoatRoughness*=clearCoatMapRoughnessData.y;\n#endif\noutParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness;\n#ifdef CLEARCOAT_TINT\nvec3 clearCoatColor=vClearCoatTintParams.rgb;float clearCoatThickness=vClearCoatTintParams.a;\n#ifdef CLEARCOAT_TINT_TEXTURE\n#ifdef CLEARCOAT_TINT_GAMMATEXTURE\nclearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb);\n#else\nclearCoatColor*=clearCoatTintMapData.rgb;\n#endif\nclearCoatThickness*=clearCoatTintMapData.a;\n#if DEBUGMODE>0\noutParams.clearCoatTintMapData=clearCoatTintMapData;\n#endif\n#endif\noutParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness;\n#endif\n#ifdef CLEARCOAT_REMAP_F0\nvec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0);\n#else\nvec3 specularEnvironmentR0Updated=specularEnvironmentR0;\n#endif\noutParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);vec3 clearCoatNormalW=geometricNormalW;\n#ifdef CLEARCOAT_BUMP\n#ifdef NORMALXYSCALE\nfloat clearCoatNormalScale=1.0;\n#else\nfloat clearCoatNormalScale=vClearCoatBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBNClearCoat=vTBN;\n#else\nvec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;mat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams);\n#endif\n#if DEBUGMODE>0\noutParams.TBNClearCoat=TBNClearCoat;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nclearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW);\n#else\nclearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y);\n#endif\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nclearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nclearCoatNormalW=clearCoatNormalW*frontFacingMultiplier;\n#endif\noutParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);float clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);float clearCoatNdotV=absEps(clearCoatNdotVUnclamped);\n#if DEBUGMODE>0\noutParams.clearCoatNdotV=clearCoatNdotV;\n#endif\n#ifdef CLEARCOAT_TINT\nvec3 clearCoatVRefract=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract));\n#endif\n#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION))\nvec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness);\n#endif\n#if defined(REFLECTION)\nfloat clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness);\n#ifdef SPECULARAA\nclearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y;\n#endif\nvec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);vec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nclearCoatReflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nvec3 clearCoatReflectionCoords=clearCoatReflectionVector;\n#else\nvec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nclearCoatReflectionCoords/=clearCoatReflectionVector.z;\n#endif\nclearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y;\n#endif\nsampleReflectionTexture(\nclearCoatAlphaG,\nvReflectionMicrosurfaceInfos,\nvReflectionInfos,\nvReflectionColor,\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nclearCoatNdotVUnclamped,\n#endif\n#ifdef LINEARSPECULARREFLECTION\nclearCoatRoughness,\n#endif\nreflectionSampler,\nclearCoatReflectionCoords,\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\nreflectionSamplerHigh,\n#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\n#endif\nenvironmentClearCoatRadiance\n);\n#if DEBUGMODE>0\noutParams.environmentClearCoatRadiance=environmentClearCoatRadiance;\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\nvec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf);\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho;\n#endif\n#endif\n#endif\n#else\nvec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness));\n#endif\nclearCoatEnvironmentReflectance*=clearCoatIntensity;\n#if DEBUGMODE>0\noutParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance;\n#endif\noutParams.finalClearCoatRadianceScaled=\nenvironmentClearCoatRadiance.rgb *\nclearCoatEnvironmentReflectance *\nvLightingIntensity.z;\n#endif\n#if defined(CLEARCOAT_TINT)\noutParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity);\n#endif\nfloat fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat);\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\noutParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf);\n#endif\n}\n#endif\n";li.IncludesShadersStore.pbrBlockIridescence="struct iridescenceOutParams\n{float iridescenceIntensity;float iridescenceIOR;float iridescenceThickness;vec3 specularEnvironmentR0;};\n#ifdef IRIDESCENCE\n#define pbr_inline\n#define inline\nvoid iridescenceBlock(\nin vec4 vIridescenceParams,\nin float viewAngle,\nin vec3 specularEnvironmentR0,\n#ifdef IRIDESCENCE_TEXTURE\nin vec2 iridescenceMapData,\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nin vec2 iridescenceThicknessMapData,\n#endif\n#ifdef CLEARCOAT\nin float NdotVUnclamped,\n#ifdef CLEARCOAT_TEXTURE\nin vec2 clearCoatMapData,\n#endif\n#endif\nout iridescenceOutParams outParams\n)\n{float iridescenceIntensity=vIridescenceParams.x;float iridescenceIOR=vIridescenceParams.y;float iridescenceThicknessMin=vIridescenceParams.z;float iridescenceThicknessMax=vIridescenceParams.w;float iridescenceThicknessWeight=1.;\n#ifdef IRIDESCENCE_TEXTURE\niridescenceIntensity*=iridescenceMapData.x;\n#endif\n#if defined(IRIDESCENCE_THICKNESS_TEXTURE)\niridescenceThicknessWeight=iridescenceThicknessMapData.g;\n#endif\nfloat iridescenceThickness=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);float topIor=1.; \n#ifdef CLEARCOAT\nfloat clearCoatIntensity=vClearCoatParams.x;\n#ifdef CLEARCOAT_TEXTURE\nclearCoatIntensity*=clearCoatMapData.x;\n#endif\ntopIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+square(1.0/topIor)*(square(NdotVUnclamped)-1.0));\n#endif\nvec3 iridescenceFresnel=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;}\n#endif\n";li.IncludesShadersStore.pbrBlockSubSurface="struct subSurfaceOutParams\n{vec3 specularEnvironmentReflectance;\n#ifdef SS_REFRACTION\nvec3 finalRefraction;vec3 surfaceAlbedo;\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nfloat alpha;\n#endif\n#ifdef REFLECTION\nfloat refractionFactorForIrradiance;\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nvec3 transmittance;float translucencyIntensity;\n#ifdef REFLECTION\nvec3 refractionIrradiance;\n#endif\n#endif\n#if DEBUGMODE>0\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nvec4 thicknessMap;\n#endif\n#ifdef SS_REFRACTION\nvec4 environmentRefraction;vec3 refractionTransmittance;\n#endif\n#endif\n};\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#define pbr_inline\n#define inline\nvec4 sampleEnvironmentRefraction(\nin float ior\n,in float thickness\n,in float refractionLOD\n,in vec3 normalW\n,in vec3 vPositionW\n,in vec3 viewDirectionW\n,in mat4 view\n,in vec4 vRefractionInfos\n,in mat4 refractionMatrix\n,in vec4 vRefractionMicrosurfaceInfos\n,in float alphaG\n#ifdef SS_REFRACTIONMAP_3D\n,in samplerCube refractionSampler\n#ifndef LODBASEDMICROSFURACE\n,in samplerCube refractionSamplerLow\n,in samplerCube refractionSamplerHigh\n#endif\n#else\n,in sampler2D refractionSampler\n#ifndef LODBASEDMICROSFURACE\n,in sampler2D refractionSamplerLow\n,in sampler2D refractionSamplerHigh\n#endif\n#endif\n#ifdef ANISOTROPIC\n,in anisotropicOutParams anisotropicOut\n#endif\n#ifdef REALTIME_FILTERING\n,in vec2 vRefractionFilteringInfo\n#endif\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n,in vec3 refractionPosition\n,in vec3 refractionSize\n#endif\n) {vec4 environmentRefraction=vec4(0.,0.,0.,0.);\n#ifdef ANISOTROPIC\nvec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,ior);\n#else\nvec3 refractionVector=refract(-viewDirectionW,normalW,ior);\n#endif\n#ifdef SS_REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n#ifdef SS_REFRACTIONMAP_3D\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\nrefractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition);\n#endif\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;vec3 refractionCoords=refractionVector;refractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\n#ifdef SS_USE_THICKNESS_AS_DEPTH\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0)));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\n#endif\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODBASEDMICROSFURACE\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef SS_LODINREFRACTIONALPHA\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);float requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\n#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D)\nenvironmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0);\n#else\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#endif\n#else\nfloat lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));float lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;vec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);} else {environmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);}\n#endif\n#ifdef SS_RGBDREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef SS_GAMMAREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\nreturn environmentRefraction;}\n#endif\n#define pbr_inline\n#define inline\nvoid subSurfaceBlock(\nin vec3 vSubSurfaceIntensity,\nin vec2 vThicknessParam,\nin vec4 vTintColor,\nin vec3 normalW,\nin vec3 specularEnvironmentReflectance,\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nin vec4 thicknessMap,\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nin vec4 refractionIntensityMap,\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nin vec4 translucencyIntensityMap,\n#endif\n#ifdef REFLECTION\n#ifdef SS_TRANSLUCENCY\nin mat4 reflectionMatrix,\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nin vec3 irradianceVector_,\n#endif\n#if defined(REALTIME_FILTERING)\nin samplerCube reflectionSampler,\nin vec2 vReflectionFilteringInfo,\n#endif\n#endif\n#ifdef USEIRRADIANCEMAP\n#ifdef REFLECTIONMAP_3D\nin samplerCube irradianceSampler,\n#else\nin sampler2D irradianceSampler,\n#endif\n#endif\n#endif\n#endif\n#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\nin vec3 surfaceAlbedo,\n#endif\n#ifdef SS_REFRACTION\nin vec3 vPositionW,\nin vec3 viewDirectionW,\nin mat4 view,\nin vec4 vRefractionInfos,\nin mat4 refractionMatrix,\nin vec4 vRefractionMicrosurfaceInfos,\nin vec4 vLightingIntensity,\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nin float alpha,\n#endif\n#ifdef SS_LODINREFRACTIONALPHA\nin float NdotVUnclamped,\n#endif\n#ifdef SS_LINEARSPECULARREFRACTION\nin float roughness,\n#endif\nin float alphaG,\n#ifdef SS_REFRACTIONMAP_3D\nin samplerCube refractionSampler,\n#ifndef LODBASEDMICROSFURACE\nin samplerCube refractionSamplerLow,\nin samplerCube refractionSamplerHigh,\n#endif\n#else\nin sampler2D refractionSampler,\n#ifndef LODBASEDMICROSFURACE\nin sampler2D refractionSamplerLow,\nin sampler2D refractionSamplerHigh,\n#endif\n#endif\n#ifdef ANISOTROPIC\nin anisotropicOutParams anisotropicOut,\n#endif\n#ifdef REALTIME_FILTERING\nin vec2 vRefractionFilteringInfo,\n#endif\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\nin vec3 refractionPosition,\nin vec3 refractionSize,\n#endif\n#ifdef SS_DISPERSION\nin float dispersion,\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nin vec3 vDiffusionDistance,\nin vec4 vTranslucencyColor,\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\nin vec4 translucencyColorMap,\n#endif\n#endif\nout subSurfaceOutParams outParams\n)\n{outParams.specularEnvironmentReflectance=specularEnvironmentReflectance;\n#ifdef SS_REFRACTION\nfloat refractionIntensity=vSubSurfaceIntensity.x;\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nrefractionIntensity*=(1.0-alpha);outParams.alpha=1.0;\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nfloat translucencyIntensity=vSubSurfaceIntensity.y;\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\n#ifdef SS_USE_GLTF_TEXTURES\nfloat thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x;\n#else\nfloat thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x;\n#endif\n#if DEBUGMODE>0\noutParams.thicknessMap=thicknessMap;\n#endif\n#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS)\n#ifdef SS_USE_GLTF_TEXTURES\nrefractionIntensity*=thicknessMap.r;\n#else\nrefractionIntensity*=thicknessMap.g;\n#endif\n#endif\n#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS)\n#ifdef SS_USE_GLTF_TEXTURES\ntranslucencyIntensity*=thicknessMap.a;\n#else\ntranslucencyIntensity*=thicknessMap.b;\n#endif\n#endif\n#else\nfloat thickness=vThicknessParam.y;\n#endif\n#if defined(SS_REFRACTION) && defined(SS_REFRACTIONINTENSITY_TEXTURE)\n#ifdef SS_USE_GLTF_TEXTURES\nrefractionIntensity*=refractionIntensityMap.r;\n#else\nrefractionIntensity*=refractionIntensityMap.g;\n#endif\n#endif\n#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCYINTENSITY_TEXTURE)\n#ifdef SS_USE_GLTF_TEXTURES\ntranslucencyIntensity*=translucencyIntensityMap.a;\n#else\ntranslucencyIntensity*=translucencyIntensityMap.b;\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nthickness=maxEps(thickness);vec4 translucencyColor=vTranslucencyColor;\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\ntranslucencyColor*=translucencyColorMap;\n#endif\nvec3 transmittance=transmittanceBRDF_Burley(translucencyColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity;\n#endif\n#ifdef SS_REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\n#ifdef SS_HAS_THICKNESS\nfloat ior=vRefractionInfos.y;\n#else\nfloat ior=vRefractionMicrosurfaceInfos.w;\n#endif\n#ifdef SS_LODINREFRACTIONALPHA\nfloat refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped);\n#elif defined(SS_LINEARSPECULARREFRACTION)\nfloat refractionRoughness=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness);\n#else\nfloat refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG);\n#endif\nfloat refraction_ior=vRefractionInfos.y;\n#ifdef SS_DISPERSION\nfloat realIOR=1.0/refraction_ior;float iorDispersionSpread=0.04*dispersion*(realIOR-1.0);vec3 iors=vec3(1.0/(realIOR-iorDispersionSpread),refraction_ior,1.0/(realIOR+iorDispersionSpread));for (int i=0; i<3; i++) {refraction_ior=iors[i];\n#endif\nvec4 envSample=sampleEnvironmentRefraction(refraction_ior,thickness,refractionLOD,normalW,vPositionW,viewDirectionW,view,vRefractionInfos,refractionMatrix,vRefractionMicrosurfaceInfos,alphaG\n#ifdef SS_REFRACTIONMAP_3D\n,refractionSampler\n#ifndef LODBASEDMICROSFURACE\n,refractionSamplerLow\n,refractionSamplerHigh\n#endif\n#else\n,refractionSampler\n#ifndef LODBASEDMICROSFURACE\n,refractionSamplerLow\n,refractionSamplerHigh\n#endif\n#endif\n#ifdef ANISOTROPIC\n,anisotropicOut\n#endif\n#ifdef REALTIME_FILTERING\n,vRefractionFilteringInfo\n#endif\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n,refractionPosition\n,refractionSize\n#endif\n);\n#ifdef SS_DISPERSION\nenvironmentRefraction[i]=envSample[i];}\n#else\nenvironmentRefraction=envSample;\n#endif\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n#ifdef SS_REFRACTION\nvec3 refractionTransmittance=vec3(refractionIntensity);\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nvec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,thickness);\n#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY)\nfloat maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);vec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);environmentRefraction.rgb*=volumeAlbedo;\n#else\nvec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y);\n#endif\n#ifdef SS_ALBEDOFORREFRACTIONTINT\nenvironmentRefraction.rgb*=surfaceAlbedo.rgb;\n#endif\noutParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity);\n#ifdef REFLECTION\noutParams.refractionFactorForIrradiance=(1.-refractionIntensity);\n#endif\n#ifdef UNUSED_MULTIPLEBOUNCES\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity);\n#endif\nrefractionTransmittance*=1.0-outParams.specularEnvironmentReflectance;\n#if DEBUGMODE>0\noutParams.refractionTransmittance=refractionTransmittance;\n#endif\noutParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z;\n#if DEBUGMODE>0\noutParams.environmentRefraction=environmentRefraction;\n#endif\n#endif\n#if defined(REFLECTION) && defined(SS_TRANSLUCENCY)\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP)\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\n#ifdef INVERTCUBICMAP\nirradianceVector.y*=-1.0;\n#endif\n#else\nvec3 irradianceVector=irradianceVector_;\n#endif\n#if defined(USESPHERICALFROMREFLECTIONMAP)\n#if defined(REALTIME_FILTERING)\nvec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo);\n#else\nvec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector);\n#endif\n#elif defined(USEIRRADIANCEMAP)\n#ifdef REFLECTIONMAP_3D\nvec3 irradianceCoords=irradianceVector;\n#else\nvec2 irradianceCoords=irradianceVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nirradianceCoords/=irradianceVector.z;\n#endif\nirradianceCoords.y=1.0-irradianceCoords.y;\n#endif\nvec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords);\n#ifdef RGBDREFLECTION\nrefractionIrradiance.rgb=fromRGBD(refractionIrradiance);\n#endif\n#ifdef GAMMAREFLECTION\nrefractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb);\n#endif\n#else\nvec4 refractionIrradiance=vec4(0.);\n#endif\nrefractionIrradiance.rgb*=transmittance;\n#ifdef SS_ALBEDOFORTRANSLUCENCYTINT\nrefractionIrradiance.rgb*=surfaceAlbedo.rgb;\n#endif\noutParams.refractionIrradiance=refractionIrradiance.rgb;\n#endif\n}\n#endif\n";li.IncludesShadersStore.pbrBlockNormalGeometric="vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\nvec3 geometricNormalW=normalW;\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\ngeometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW;\n#endif\n";li.IncludesShadersStore.pbrBlockNormalFinal="#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n";li.IncludesShadersStore.pbrBlockLightmapInit="#ifdef LIGHTMAP\nvec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);\n#ifdef RGBDLIGHTMAP\nlightmapColor.rgb=fromRGBD(lightmapColor);\n#endif\n#ifdef GAMMALIGHTMAP\nlightmapColor.rgb=toLinearSpace(lightmapColor.rgb);\n#endif\nlightmapColor.rgb*=vLightmapInfos.y;\n#endif\n";li.IncludesShadersStore.pbrBlockGeometryInfo="float NdotVUnclamped=dot(normalW,viewDirectionW);float NdotV=absEps(NdotVUnclamped);float alphaG=convertRoughnessToAverageSlope(roughness);vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz);\n#ifdef SPECULARAA\nalphaG+=AARoughnessFactors.y;\n#endif\n#if defined(ENVIRONMENTBRDF)\nvec3 environmentBrdf=getBRDFLookup(NdotV,roughness);\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=aoOut.ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW);\n#endif\n#endif\n#endif\n#endif\n";li.IncludesShadersStore.pbrBlockReflectance0="float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);vec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec3 specularEnvironmentR90=vec3(metallicReflectanceFactors.a);\n#else \nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\n#endif\n#ifdef ALPHAFRESNEL\nfloat reflectance90=fresnelGrazingReflectance(reflectance);specularEnvironmentR90=specularEnvironmentR90*reflectance90;\n#endif\n";li.IncludesShadersStore.pbrBlockReflectance="#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\nvec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf);\n#ifdef RADIANCEOCCLUSION\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\nvec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n#ifdef CLEARCOAT\nspecularEnvironmentReflectance*=clearcoatOut.conservationFactor;\n#if defined(CLEARCOAT_TINT)\nspecularEnvironmentReflectance*=clearcoatOut.absorption;\n#endif\n#endif\n";li.IncludesShadersStore.pbrBlockDirectLighting="vec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef CLEARCOAT\nvec3 clearCoatBase=vec3(0.,0.,0.);\n#endif\n#ifdef SHEEN\nvec3 sheenBase=vec3(0.,0.,0.);\n#endif\npreLightingInfo preInfo;lightingInfo info;float shadow=1.; \nfloat aggShadow=0.;float numLights=0.;\n#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT)\nvec3 absorption=vec3(0.);\n#endif\n";li.IncludesShadersStore.pbrBlockFinalLitComponents="aggShadow=aggShadow/numLights;\n#if defined(ENVIRONMENTBRDF)\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf);\n#endif\n#endif\n#ifndef METALLICWORKFLOW\n#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n#endif\n#endif\n#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF)\nsurfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb;\n#endif\n#ifdef REFLECTION\nvec3 finalIrradiance=reflectionOut.environmentIrradiance;\n#if defined(CLEARCOAT)\nfinalIrradiance*=clearcoatOut.conservationFactor;\n#if defined(CLEARCOAT_TINT)\nfinalIrradiance*=clearcoatOut.absorption;\n#endif\n#endif\n#if defined(SS_REFRACTION)\nfinalIrradiance*=subSurfaceOut.refractionFactorForIrradiance;\n#endif\n#if defined(SS_TRANSLUCENCY)\nfinalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance;\n#endif\nfinalIrradiance*=surfaceAlbedo.rgb;finalIrradiance*=vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;finalSpecular=max(finalSpecular,0.0);vec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalSpecularScaled*=energyConservationFactor;\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\nfinalSpecularScaled*=sheenOut.sheenAlbedoScaling;\n#endif\n#endif\n#ifdef REFLECTION\nvec3 finalRadiance=reflectionOut.environmentRadiance.rgb;finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;vec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalRadianceScaled*=energyConservationFactor;\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\nfinalRadianceScaled*=sheenOut.sheenAlbedoScaling;\n#endif\n#endif\n#ifdef SHEEN\nvec3 finalSheen=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,0.0);vec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w;\n#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nsheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor;\n#if defined(CLEARCOAT_TINT)\nsheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption;\n#endif\n#endif\n#endif\n#ifdef CLEARCOAT\nvec3 finalClearCoat=clearCoatBase;finalClearCoat=max(finalClearCoat,0.0);vec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w;\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat;\n#endif\n#ifdef SS_REFRACTION\nsubSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor;\n#ifdef CLEARCOAT_TINT\nsubSurfaceOut.finalRefraction*=clearcoatOut.absorption;\n#endif\n#endif\n#endif\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#if defined(CLEARCOAT)\nluminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled);\n#endif\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalClearCoatScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA)\nalpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha);\n#endif\n#endif\n";li.IncludesShadersStore.pbrBlockFinalUnlitComponents="vec3 finalDiffuse=diffuseBase;finalDiffuse*=surfaceAlbedo.rgb;finalDiffuse=max(finalDiffuse,0.0);finalDiffuse*=vLightingIntensity.x;vec3 finalAmbient=vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;vec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\n#ifdef GAMMAEMISSIVE\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\n#else\nfinalEmissive*=emissiveColorTex.rgb;\n#endif\nfinalEmissive*= vEmissiveInfos.y;\n#endif\nfinalEmissive*=vLightingIntensity.y;\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor;\n#endif\nfinalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse;\n";li.IncludesShadersStore.pbrBlockFinalColorComposition="vec4 finalColor=vec4(\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance +\n#endif\n#ifdef SPECULARTERM\nfinalSpecularScaled +\n#endif\n#ifdef SHEEN\nfinalSheenScaled +\n#endif\n#ifdef CLEARCOAT\nfinalClearCoatScaled +\n#endif\n#ifdef REFLECTION\nfinalRadianceScaled +\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF)\nsheenOut.finalSheenRadianceScaled +\n#endif\n#ifdef CLEARCOAT\nclearcoatOut.finalClearCoatRadianceScaled +\n#endif\n#endif\n#ifdef SS_REFRACTION\nsubSurfaceOut.finalRefraction +\n#endif\n#endif\nfinalAmbient +\nfinalDiffuse,\nalpha);\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor.rgb;\n#else\nfinalColor.rgb+=lightmapColor.rgb;\n#endif\n#endif\n#endif\nfinalColor.rgb+=finalEmissive;\n#define CUSTOM_FRAGMENT_BEFORE_FOG\nfinalColor=max(finalColor,0.0);\n";li.IncludesShadersStore.pbrBlockImageProcessing="#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING)\n#if !defined(SKIPFINALCOLORCLAMP)\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#endif\n#else\nfinalColor=applyImageProcessing(finalColor);\n#endif\nfinalColor.a*=visibility;\n#ifdef PREMULTIPLYALPHA\nfinalColor.rgb*=finalColor.a;\n#endif\n";li.IncludesShadersStore.pbrDebug="#if DEBUGMODE>0\nif (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) {\n#if DEBUGMODE==1\ngl_FragColor.rgb=vPositionW.rgb;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==2 && defined(NORMAL)\ngl_FragColor.rgb=vNormalW.rgb;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC)\ngl_FragColor.rgb=TBN[0];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC)\ngl_FragColor.rgb=TBN[1];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==5\ngl_FragColor.rgb=normalW;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==6 && defined(MAINUV1)\ngl_FragColor.rgb=vec3(vMainUV1,0.0);\n#elif DEBUGMODE==7 && defined(MAINUV2)\ngl_FragColor.rgb=vec3(vMainUV2,0.0);\n#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)\ngl_FragColor.rgb=clearcoatOut.TBNClearCoat[0];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)\ngl_FragColor.rgb=clearcoatOut.TBNClearCoat[1];\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==10 && defined(CLEARCOAT)\ngl_FragColor.rgb=clearcoatOut.clearCoatNormalW;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==11 && defined(ANISOTROPIC)\ngl_FragColor.rgb=anisotropicOut.anisotropicNormal;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==12 && defined(ANISOTROPIC)\ngl_FragColor.rgb=anisotropicOut.anisotropicTangent;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==13 && defined(ANISOTROPIC)\ngl_FragColor.rgb=anisotropicOut.anisotropicBitangent;\n#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==20 && defined(ALBEDO)\ngl_FragColor.rgb=albedoTexture.rgb;\n#ifndef GAMMAALBEDO\n#define DEBUGMODE_GAMMA\n#endif\n#elif DEBUGMODE==21 && defined(AMBIENT)\ngl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb;\n#elif DEBUGMODE==22 && defined(OPACITY)\ngl_FragColor.rgb=opacityMap.rgb;\n#elif DEBUGMODE==23 && defined(EMISSIVE)\ngl_FragColor.rgb=emissiveColorTex.rgb;\n#ifndef GAMMAEMISSIVE\n#define DEBUGMODE_GAMMA\n#endif\n#elif DEBUGMODE==24 && defined(LIGHTMAP)\ngl_FragColor.rgb=lightmapColor.rgb;\n#ifndef GAMMALIGHTMAP\n#define DEBUGMODE_GAMMA\n#endif\n#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW)\ngl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb;\n#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW)\ngl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE)\ngl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0);\n#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)\ngl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb;\n#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE)\ngl_FragColor.rgb=sheenOut.sheenMapData.rgb;\n#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE)\ngl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb;\n#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE)\ngl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb;\n#elif DEBUGMODE==32 && defined(BUMP)\ngl_FragColor.rgb=texture2D(bumpSampler,vBumpUV).rgb;\n#elif DEBUGMODE==40 && defined(SS_REFRACTION)\ngl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==41 && defined(REFLECTION)\ngl_FragColor.rgb=reflectionOut.environmentRadiance.rgb;\n#ifndef GAMMAREFLECTION\n#define DEBUGMODE_GAMMA\n#endif\n#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION)\ngl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==50\ngl_FragColor.rgb=diffuseBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==51 && defined(SPECULARTERM)\ngl_FragColor.rgb=specularBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==52 && defined(CLEARCOAT)\ngl_FragColor.rgb=clearCoatBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==53 && defined(SHEEN)\ngl_FragColor.rgb=sheenBase.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==54 && defined(REFLECTION)\ngl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb;\n#ifndef GAMMAREFLECTION\n#define DEBUGMODE_GAMMA\n#endif\n#elif DEBUGMODE==60\ngl_FragColor.rgb=surfaceAlbedo.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==61\ngl_FragColor.rgb=clearcoatOut.specularEnvironmentR0;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==62 && defined(METALLICWORKFLOW)\ngl_FragColor.rgb=vec3(reflectivityOut.metallicRoughness.r);\n#elif DEBUGMODE==71 && defined(METALLICWORKFLOW)\ngl_FragColor.rgb=reflectivityOut.metallicF0;\n#elif DEBUGMODE==63\ngl_FragColor.rgb=vec3(roughness);\n#elif DEBUGMODE==64\ngl_FragColor.rgb=vec3(alphaG);\n#elif DEBUGMODE==65\ngl_FragColor.rgb=vec3(NdotV);\n#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT)\ngl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==67 && defined(CLEARCOAT)\ngl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness);\n#elif DEBUGMODE==68 && defined(CLEARCOAT)\ngl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV);\n#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY)\ngl_FragColor.rgb=subSurfaceOut.transmittance;\n#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION)\ngl_FragColor.rgb=subSurfaceOut.refractionTransmittance;\n#elif DEBUGMODE==72\ngl_FragColor.rgb=vec3(microSurface);\n#elif DEBUGMODE==73\ngl_FragColor.rgb=vAlbedoColor.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==74 && !defined(METALLICWORKFLOW)\ngl_FragColor.rgb=vReflectivityColor.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==75\ngl_FragColor.rgb=vEmissiveColor.rgb;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION)\ngl_FragColor.rgb=vec3(seo);\n#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\ngl_FragColor.rgb=vec3(eho);\n#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION)\ngl_FragColor.rgb=vec3(energyConservationFactor);\n#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\ngl_FragColor.rgb=specularEnvironmentReflectance;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\ngl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION)\ngl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance;\n#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==86 && defined(ALPHABLEND)\ngl_FragColor.rgb=vec3(luminanceOverAlpha);\n#elif DEBUGMODE==87\ngl_FragColor.rgb=vec3(alpha);\n#elif DEBUGMODE==88 && defined(ALBEDO)\ngl_FragColor.rgb=vec3(albedoTexture.a);\n#elif DEBUGMODE==89\ngl_FragColor.rgb=aoOut.ambientOcclusionColor.rgb;\n#else\nfloat stripeWidth=30.;float stripePos=floor((gl_FragCoord.x+gl_FragCoord.y)/stripeWidth);float whichColor=mod(stripePos,2.);vec3 color1=vec3(.6,.2,.2);vec3 color2=vec3(.3,.1,.1);gl_FragColor.rgb=mix(color1,color2,whichColor);\n#endif\ngl_FragColor.rgb*=vDebugMode.y;\n#ifdef DEBUGMODE_NORMALIZE\ngl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5;\n#endif\n#ifdef DEBUGMODE_GAMMA\ngl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb);\n#endif\ngl_FragColor.a=1.0;\n#ifdef PREPASS\ngl_FragData[0]=toLinearSpace(gl_FragColor); \ngl_FragData[1]=vec4(0.,0.,0.,0.); \n#endif\n#ifdef DEBUGMODE_FORCERETURN\nreturn;\n#endif\n}\n#endif\n";li.ShadersStore.pbrPixelShader="#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include<prePassDeclaration>[SCENE_MRT_COUNT]\nprecision highp float;\n#include<oitDeclaration>\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE\n#endif\n#include<__decl__pbrFragment>\n#include<pbrFragmentExtraDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<pbrFragmentSamplersDeclaration>\n#include<imageProcessingDeclaration>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#include<helperFunctions>\n#include<subSurfaceScatteringFunctions>\n#include<importanceSampling>\n#include<pbrHelperFunctions>\n#include<imageProcessingFunctions>\n#include<shadowsFragmentFunctions>\n#include<harmonicsFunctions>\n#include<pbrDirectLightingSetupFunctions>\n#include<pbrDirectLightingFalloffFunctions>\n#include<pbrBRDFFunctions>\n#include<hdrFilteringFunctions>\n#include<pbrDirectLightingFunctions>\n#include<pbrIBLFunctions>\n#include<bumpFragmentMainFunctions>\n#include<bumpFragmentFunctions>\n#ifdef REFLECTION\n#include<reflectionFunction>\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#include<pbrBlockAlbedoOpacity>\n#include<pbrBlockReflectivity>\n#include<pbrBlockAmbientOcclusion>\n#include<pbrBlockAlphaFresnel>\n#include<pbrBlockAnisotropic>\n#include<pbrBlockReflection>\n#include<pbrBlockSheen>\n#include<pbrBlockClearcoat>\n#include<pbrBlockIridescence>\n#include<pbrBlockSubSurface>\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\n#include<pbrBlockNormalGeometric>\n#include<bumpFragment>\n#include<pbrBlockNormalFinal>\nalbedoOpacityOutParams albedoOpacityOut;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#endif\n#ifdef DECAL\nvec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset);\n#endif\nalbedoOpacityBlock(\nvAlbedoColor,\n#ifdef ALBEDO\nalbedoTexture,\nvAlbedoInfos,\n#endif\n#ifdef OPACITY\nopacityMap,\nvOpacityInfos,\n#endif\n#ifdef DETAIL\ndetailColor,\nvDetailInfos,\n#endif\n#ifdef DECAL\ndecalColor,\nvDecalInfos,\n#endif\nalbedoOpacityOut\n);vec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;float alpha=albedoOpacityOut.alpha;\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\n#include<depthPrePass>\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\nambientOcclusionOutParams aoOut;\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb;\n#endif\nambientOcclusionBlock(\n#ifdef AMBIENT\nambientOcclusionColorMap,\nvAmbientInfos,\n#endif\naoOut\n);\n#include<pbrBlockLightmapInit>\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\nvec3 baseColor=surfaceAlbedo;reflectivityOutParams reflectivityOut;\n#if defined(REFLECTIVITY)\nvec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);vec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap;\n#ifndef METALLICWORKFLOW\n#ifdef REFLECTIVITY_GAMMA\nsurfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap);\n#endif\nsurfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y;\n#endif\n#endif\n#if defined(MICROSURFACEMAP)\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\n#endif\n#ifdef METALLICWORKFLOW\nvec4 metallicReflectanceFactors=vMetallicReflectanceFactors;\n#ifdef REFLECTANCE\nvec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset);\n#ifdef REFLECTANCE_GAMMA\nreflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap);\n#endif\nmetallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb;\n#endif\n#ifdef METALLIC_REFLECTANCE\nvec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset);\n#ifdef METALLIC_REFLECTANCE_GAMMA\nmetallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap);\n#endif\n#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY\nmetallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb;\n#endif\nmetallicReflectanceFactors*=metallicReflectanceFactorsMap.a;\n#endif\n#endif\nreflectivityBlock(\nvReflectivityColor,\n#ifdef METALLICWORKFLOW\nsurfaceAlbedo,\nmetallicReflectanceFactors,\n#endif\n#ifdef REFLECTIVITY\nvReflectivityInfos,\nsurfaceMetallicOrReflectivityColorMap,\n#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\naoOut.ambientOcclusionColor,\n#endif\n#ifdef MICROSURFACEMAP\nmicroSurfaceTexel,\n#endif\n#ifdef DETAIL\ndetailColor,\nvDetailInfos,\n#endif\nreflectivityOut\n);float microSurface=reflectivityOut.microSurface;float roughness=reflectivityOut.roughness;\n#ifdef METALLICWORKFLOW\nsurfaceAlbedo=reflectivityOut.surfaceAlbedo;\n#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\naoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor;\n#endif\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\nalphaFresnelOutParams alphaFresnelOut;alphaFresnelBlock(\nnormalW,\nviewDirectionW,\nalpha,\nmicroSurface,\nalphaFresnelOut\n);alpha=alphaFresnelOut.alpha;\n#endif\n#endif\n#include<pbrBlockGeometryInfo>\n#ifdef ANISOTROPIC\nanisotropicOutParams anisotropicOut;\n#ifdef ANISOTROPIC_TEXTURE\nvec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y;\n#endif\nanisotropicBlock(\nvAnisotropy,\nroughness,\n#ifdef ANISOTROPIC_TEXTURE\nanisotropyMapData,\n#endif\nTBN,\nnormalW,\nviewDirectionW,\nanisotropicOut\n);\n#endif\n#ifdef REFLECTION\nreflectionOutParams reflectionOut;\n#ifndef USE_CUSTOM_REFLECTION\nreflectionBlock(\nvPositionW,\nnormalW,\nalphaG,\nvReflectionMicrosurfaceInfos,\nvReflectionInfos,\nvReflectionColor,\n#ifdef ANISOTROPIC\nanisotropicOut,\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nNdotVUnclamped,\n#endif\n#ifdef LINEARSPECULARREFLECTION\nroughness,\n#endif\nreflectionSampler,\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nvEnvironmentIrradiance,\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nreflectionMatrix,\n#endif\n#endif\n#ifdef USEIRRADIANCEMAP\nirradianceSampler,\n#endif\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\nreflectionSamplerHigh,\n#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\n#endif\nreflectionOut\n);\n#else\n#define CUSTOM_REFLECTION\n#endif\n#endif\n#include<pbrBlockReflectance0>\n#ifdef SHEEN\nsheenOutParams sheenOut;\n#ifdef SHEEN_TEXTURE\nvec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset);\n#endif\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)\nvec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w;\n#endif\nsheenBlock(\nvSheenColor,\n#ifdef SHEEN_ROUGHNESS\nvSheenRoughness,\n#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)\nsheenMapRoughnessData,\n#endif\n#endif\nroughness,\n#ifdef SHEEN_TEXTURE\nsheenMapData,\nvSheenInfos.y,\n#endif\nreflectance,\n#ifdef SHEEN_LINKWITHALBEDO\nbaseColor,\nsurfaceAlbedo,\n#endif\n#ifdef ENVIRONMENTBRDF\nNdotV,\nenvironmentBrdf,\n#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nAARoughnessFactors,\nvReflectionMicrosurfaceInfos,\nvReflectionInfos,\nvReflectionColor,\nvLightingIntensity,\nreflectionSampler,\nreflectionOut.reflectionCoords,\nNdotVUnclamped,\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\nreflectionSamplerHigh,\n#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)\nseo,\n#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\neho,\n#endif\n#endif\nsheenOut\n);\n#ifdef SHEEN_LINKWITHALBEDO\nsurfaceAlbedo=sheenOut.surfaceAlbedo;\n#endif\n#endif\n#ifdef CLEARCOAT\n#ifdef CLEARCOAT_TEXTURE\nvec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y;\n#endif\n#endif\n#ifdef IRIDESCENCE\niridescenceOutParams iridescenceOut;\n#ifdef IRIDESCENCE_TEXTURE\nvec2 iridescenceMapData=texture2D(iridescenceSampler,vIridescenceUV+uvOffset).rg*vIridescenceInfos.y;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nvec2 iridescenceThicknessMapData=texture2D(iridescenceThicknessSampler,vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w;\n#endif\niridescenceBlock(\nvIridescenceParams,\nNdotV,\nspecularEnvironmentR0,\n#ifdef IRIDESCENCE_TEXTURE\niridescenceMapData,\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\niridescenceThicknessMapData,\n#endif\n#ifdef CLEARCOAT\nNdotVUnclamped,\n#ifdef CLEARCOAT_TEXTURE\nclearCoatMapData,\n#endif\n#endif\niridescenceOut\n);float iridescenceIntensity=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0;\n#endif\nclearcoatOutParams clearcoatOut;\n#ifdef CLEARCOAT\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\nvec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w;\n#endif\n#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)\nvec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset);\n#endif\n#ifdef CLEARCOAT_BUMP\nvec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset);\n#endif\nclearcoatBlock(\nvPositionW,\ngeometricNormalW,\nviewDirectionW,\nvClearCoatParams,\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\nclearCoatMapRoughnessData,\n#endif\nspecularEnvironmentR0,\n#ifdef CLEARCOAT_TEXTURE\nclearCoatMapData,\n#endif\n#ifdef CLEARCOAT_TINT\nvClearCoatTintParams,\nclearCoatColorAtDistance,\nvClearCoatRefractionParams,\n#ifdef CLEARCOAT_TINT_TEXTURE\nclearCoatTintMapData,\n#endif\n#endif\n#ifdef CLEARCOAT_BUMP\nvClearCoatBumpInfos,\nclearCoatBumpMapData,\nvClearCoatBumpUV,\n#if defined(TANGENT) && defined(NORMAL)\nvTBN,\n#else\nvClearCoatTangentSpaceParams,\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nnormalMatrix,\n#endif\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nfaceNormal,\n#endif\n#ifdef REFLECTION\nvReflectionMicrosurfaceInfos,\nvReflectionInfos,\nvReflectionColor,\nvLightingIntensity,\nreflectionSampler,\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\nreflectionSamplerHigh,\n#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\n#endif\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n#ifdef RADIANCEOCCLUSION\nambientMonochrome,\n#endif\n#endif\n#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)\n(gl_FrontFacing ? 1. : -1.),\n#endif\nclearcoatOut\n);\n#else\nclearcoatOut.specularEnvironmentR0=specularEnvironmentR0;\n#endif\n#include<pbrBlockReflectance>\nsubSurfaceOutParams subSurfaceOut;\n#ifdef SUBSURFACE\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nvec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset);\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nvec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset);\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nvec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset);\n#endif\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\nvec4 translucencyColorMap=texture2D(translucencyColorSampler,vTranslucencyColorUV+uvOffset);\n#endif\nsubSurfaceBlock(\nvSubSurfaceIntensity,\nvThicknessParam,\nvTintColor,\nnormalW,\nspecularEnvironmentReflectance,\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nthicknessMap,\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nrefractionIntensityMap,\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\ntranslucencyIntensityMap,\n#endif\n#ifdef REFLECTION\n#ifdef SS_TRANSLUCENCY\nreflectionMatrix,\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nreflectionOut.irradianceVector,\n#endif\n#if defined(REALTIME_FILTERING)\nreflectionSampler,\nvReflectionFilteringInfo,\n#endif\n#endif\n#ifdef USEIRRADIANCEMAP\nirradianceSampler,\n#endif\n#endif\n#endif\n#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\nsurfaceAlbedo,\n#endif\n#ifdef SS_REFRACTION\nvPositionW,\nviewDirectionW,\nview,\nvRefractionInfos,\nrefractionMatrix,\nvRefractionMicrosurfaceInfos,\nvLightingIntensity,\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nalpha,\n#endif\n#ifdef SS_LODINREFRACTIONALPHA\nNdotVUnclamped,\n#endif\n#ifdef SS_LINEARSPECULARREFRACTION\nroughness,\n#endif\nalphaG,\nrefractionSampler,\n#ifndef LODBASEDMICROSFURACE\nrefractionSamplerLow,\nrefractionSamplerHigh,\n#endif\n#ifdef ANISOTROPIC\nanisotropicOut,\n#endif\n#ifdef REALTIME_FILTERING\nvRefractionFilteringInfo,\n#endif\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\nvRefractionPosition,\nvRefractionSize,\n#endif\n#ifdef SS_DISPERSION\ndispersion,\n#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nvDiffusionDistance,\nvTranslucencyColor,\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\ntranslucencyColorMap,\n#endif\n#endif\nsubSurfaceOut\n);\n#ifdef SS_REFRACTION\nsurfaceAlbedo=subSurfaceOut.surfaceAlbedo;\n#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nalpha=subSurfaceOut.alpha;\n#endif\n#endif\n#else\nsubSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance;\n#endif\n#include<pbrBlockDirectLighting>\n#include<lightFragment>[0..maxSimultaneousLights]\n#include<pbrBlockFinalLitComponents>\n#endif \n#include<pbrBlockFinalUnlitComponents>\n#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION\n#include<pbrBlockFinalColorComposition>\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#include<pbrBlockImageProcessing>\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\n#ifdef PREPASS\nfloat writeGeometryInfo=finalColor.a>0.4 ? 1.0 : 0.0;\n#ifdef PREPASS_POSITION\ngl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);\n#endif\n#ifdef PREPASS_VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo);\n#endif\n#ifdef PREPASS_ALBEDO_SQRT\nvec3 sqAlbedo=sqrt(surfaceAlbedo); \n#endif\n#ifdef PREPASS_IRRADIANCE\nvec3 irradiance=finalDiffuse;\n#ifndef UNLIT\n#ifdef REFLECTION\nirradiance+=finalIrradiance;\n#endif\n#endif\n#ifdef SS_SCATTERING\ngl_FragData[0]=vec4(finalColor.rgb-irradiance,finalColor.a); \nirradiance/=sqAlbedo;\n#else\ngl_FragData[0]=finalColor; \nfloat scatteringDiffusionProfile=255.;\n#endif\ngl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); \n#else\ngl_FragData[0]=vec4(finalColor.rgb,finalColor.a);\n#endif\n#ifdef PREPASS_DEPTH\ngl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); \n#endif\n#ifdef PREPASS_NORMAL\n#ifdef PREPASS_NORMAL_WORLDSPACE\ngl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); \n#else\ngl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); \n#endif\n#endif\n#ifdef PREPASS_ALBEDO_SQRT\ngl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo); \n#endif\n#ifdef PREPASS_REFLECTIVITY\n#ifndef UNLIT\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo;\n#else\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo;\n#endif\n#endif\n#endif\n#if !defined(PREPASS) || defined(WEBGL2)\ngl_FragColor=finalColor;\n#endif\n#include<oitFragment>\n#if ORDER_INDEPENDENT_TRANSPARENCY\nif (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);} else {backColor+=finalColor;}\n#endif\n#include<pbrDebug>\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";li.IncludesShadersStore.pbrVertexDeclaration="uniform mat4 view;uniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;uniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;uniform vec4 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;uniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;uniform mat4 reflectivityMatrix;\n#endif\n#ifdef METALLIC_REFLECTANCE\nuniform vec2 vMetallicReflectanceInfos;uniform mat4 metallicReflectanceMatrix;\n#endif\n#ifdef REFLECTANCE\nuniform vec2 vReflectanceInfos;uniform mat4 reflectanceMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;uniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;\n#endif\n#ifdef CLEARCOAT\n#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform vec4 vClearCoatInfos;\n#endif\n#ifdef CLEARCOAT_TEXTURE\nuniform mat4 clearCoatMatrix;\n#endif\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS\nuniform mat4 clearCoatRoughnessMatrix;\n#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;uniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix;\n#endif\n#endif\n#ifdef IRIDESCENCE\n#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)\nuniform vec4 vIridescenceInfos;\n#endif\n#ifdef IRIDESCENCE_TEXTURE\nuniform mat4 iridescenceMatrix;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nuniform mat4 iridescenceThicknessMatrix;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix;\n#endif\n#endif\n#ifdef SHEEN\n#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform vec4 vSheenInfos;\n#endif\n#ifdef SHEEN_TEXTURE\nuniform mat4 sheenMatrix;\n#endif\n#ifdef SHEEN_TEXTURE_ROUGHNESS\nuniform mat4 sheenRoughnessMatrix;\n#endif\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionInfos;uniform mat4 refractionMatrix;\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix;\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\nuniform vec2 vTranslucencyColorInfos;uniform mat4 translucencyColorMatrix;\n#endif\n#endif\n#ifdef NORMAL\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22;\n#else\nuniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX;\n#endif\n#endif\n#endif\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;uniform mat4 detailMatrix;\n#endif\n#include<decalVertexDeclaration>\n#define ADDITIONAL_VERTEX_DECLARATION\n";li.ShadersStore.pbrVertexShader="precision highp float;\n#include<__decl__pbrVertex>\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#include<uvAttributeDeclaration>[2..7]\n#include<mainUVVaryingDeclaration>[1..7]\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<instancesDeclaration>\n#include<prePassVertexDeclaration>\n#include<samplerVertexDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo)\n#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)\n#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)\n#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)\n#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)\n#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)\n#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity)\n#include<samplerVertexDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler)\n#include<samplerVertexDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance)\n#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance)\n#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)\n#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)\n#ifdef CLEARCOAT\n#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat)\n#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump)\n#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence)\n#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness)\n#endif\n#ifdef SHEEN\n#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen)\n#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#endif\n#ifdef ANISOTROPIC\n#include<samplerVertexDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy)\n#endif\n#ifdef SUBSURFACE\n#include<samplerVertexDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness)\n#include<samplerVertexDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity)\n#include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity)\n#include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor)\n#endif\nvarying vec3 vPositionW;\n#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\n#endif\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertexGlobal>\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif\n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vPositionW=vec3(worldPos);\n#include<prePassVertex>\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector);\n#endif\n#endif\n#define CUSTOM_VERTEX_UPDATE_WORLDPOS\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#if DEBUGMODE>0\nvClipSpacePosition=gl_Position;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n#ifndef UV1\nvec2 uvUpdated=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uvUpdated;\n#endif\n#include<uvVariableDeclaration>[2..7]\n#include<samplerVertexImplementation>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)\n#ifdef CLEARCOAT\n#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z)\n#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x)\n#endif\n#ifdef IRIDESCENCE\n#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z)\n#endif\n#ifdef SHEEN\n#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheenRoughness,_INFONAME_,SheenInfos.z)\n#endif\n#ifdef ANISOTROPIC\n#include<samplerVertexImplementation>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x)\n#endif\n#ifdef SUBSURFACE\n#include<samplerVertexImplementation>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x)\n#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_MATRIXNAME_,translucencyColor,_INFONAME_,TranslucencyColorInfos.x)\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#include<vertexColorMixing>\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}";var Hm=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.CLEARCOAT=!1,t.CLEARCOAT_DEFAULTIOR=!1,t.CLEARCOAT_TEXTURE=!1,t.CLEARCOAT_TEXTURE_ROUGHNESS=!1,t.CLEARCOAT_TEXTUREDIRECTUV=0,t.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,t.CLEARCOAT_BUMP=!1,t.CLEARCOAT_BUMPDIRECTUV=0,t.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,t.CLEARCOAT_REMAP_F0=!1,t.CLEARCOAT_TINT=!1,t.CLEARCOAT_TINT_TEXTURE=!1,t.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,t.CLEARCOAT_TINT_GAMMATEXTURE=!1,t}return m(t,e),t}(Gs),Xm=function(e){function t(i,r){void 0===r&&(r=!0);var n=e.call(this,i,"PBRClearCoat",100,new Hm,r)||this;return n._isEnabled=!1,n.isEnabled=!1,n.intensity=1,n.roughness=0,n._indexOfRefraction=t._DefaultIndexOfRefraction,n.indexOfRefraction=t._DefaultIndexOfRefraction,n._texture=null,n.texture=null,n._useRoughnessFromMainTexture=!0,n.useRoughnessFromMainTexture=!0,n._textureRoughness=null,n.textureRoughness=null,n._remapF0OnInterfaceChange=!0,n.remapF0OnInterfaceChange=!0,n._bumpTexture=null,n.bumpTexture=null,n._isTintEnabled=!1,n.isTintEnabled=!1,n.tintColor=Z.White(),n.tintColorAtDistance=1,n.tintThickness=1,n._tintTexture=null,n.tintTexture=null,n._internalMarkAllSubMeshesAsTexturesDirty=i._dirtyCallbacks[u.MATERIAL_TextureDirtyFlag],n}return m(t,e),t.prototype._markAllSubMeshesAsTexturesDirty=function(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()},t.prototype.isReadyForSubMesh=function(e,t,i){if(!this._isEnabled)return!0;var r=this._material._disableBumpMap;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&xu.ClearCoatTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&xu.ClearCoatTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1;if(i.getCaps().standardDerivatives&&this._bumpTexture&&xu.ClearCoatBumpTextureEnabled&&!r&&!this._bumpTexture.isReady())return!1;if(this._isTintEnabled&&this._tintTexture&&xu.ClearCoatTintTextureEnabled&&!this._tintTexture.isReadyOrNotBlocking())return!1}return!0},t.prototype.prepareDefinesBeforeAttributes=function(e,i){this._isEnabled?(e.CLEARCOAT=!0,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e.CLEARCOAT_REMAP_F0=this._remapF0OnInterfaceChange,e._areTexturesDirty&&i.texturesEnabled&&(this._texture&&xu.ClearCoatTextureEnabled?ta(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&xu.ClearCoatTextureEnabled?ta(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&xu.ClearCoatBumpTextureEnabled?ta(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===t._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&xu.ClearCoatTintTextureEnabled?(ta(this._tintTexture,e,"CLEARCOAT_TINT_TEXTURE"),e.CLEARCOAT_TINT_GAMMATEXTURE=this._tintTexture.gammaSpace):e.CLEARCOAT_TINT_TEXTURE=!1):(e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1))):(e.CLEARCOAT=!1,e.CLEARCOAT_TEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.CLEARCOAT_DEFAULTIOR=!1,e.CLEARCOAT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,e.CLEARCOAT_BUMPDIRECTUV=0,e.CLEARCOAT_REMAP_F0=!1,e.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TINT_GAMMATEXTURE=!1)},t.prototype.bindForSubMesh=function(e,t,i,r){var n,o,a,s,l,c,u,h;if(this._isEnabled){var d=r.materialDefines,p=this._material.isFrozen,f=this._material._disableBumpMap,_=this._material._invertNormalMapX,m=this._material._invertNormalMapY;if(!e.useUbo||!p||!e.isSync){(this._texture||this._textureRoughness)&&xu.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",null!==(o=null===(n=this._texture)||void 0===n?void 0:n.coordinatesIndex)&&void 0!==o?o:0,null!==(s=null===(a=this._texture)||void 0===a?void 0:a.level)&&void 0!==s?s:0,null!==(c=null===(l=this._textureRoughness)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==c?c:0,null!==(h=null===(u=this._textureRoughness)||void 0===u?void 0:u.level)&&void 0!==h?h:0),this._texture&&ia(this._texture,e,"clearCoat"),this._textureRoughness&&!d.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&ia(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&xu.ClearCoatTextureEnabled&&!f&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),ia(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",_?1:-1,m?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",_?-1:1,m?-1:1)),this._tintTexture&&xu.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),ia(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);var g=1-this._indexOfRefraction,v=1+this._indexOfRefraction,y=Math.pow(-g/v,2),b=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",y,b,g,v),this._isTintEnabled&&(e.updateFloat4("vClearCoatTintParams",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintThickness)),e.updateFloat("clearCoatColorAtDistance",Math.max(1e-5,this.tintColorAtDistance)))}t.texturesEnabled&&(this._texture&&xu.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!d.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&xu.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&xu.ClearCoatBumpTextureEnabled&&!f&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&xu.ClearCoatTintTextureEnabled&&e.setTexture("clearCoatTintSampler",this._tintTexture))}},t.prototype.hasTexture=function(e){return this._texture===e||this._textureRoughness===e||this._bumpTexture===e||this._tintTexture===e},t.prototype.getActiveTextures=function(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness),this._bumpTexture&&e.push(this._bumpTexture),this._tintTexture&&e.push(this._tintTexture)},t.prototype.getAnimatables=function(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)},t.prototype.dispose=function(e){var t,i,r,n;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._textureRoughness)||void 0===i||i.dispose(),null===(r=this._bumpTexture)||void 0===r||r.dispose(),null===(n=this._tintTexture)||void 0===n||n.dispose())},t.prototype.getClassName=function(){return"PBRClearCoatConfiguration"},t.prototype.addFallbacks=function(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i},t.prototype.getSamplers=function(e){e.push("clearCoatSampler","clearCoatRoughnessSampler","clearCoatBumpSampler","clearCoatTintSampler")},t.prototype.getUniforms=function(){return{ubo:[{name:"vClearCoatParams",size:2,type:"vec2"},{name:"vClearCoatRefractionParams",size:4,type:"vec4"},{name:"vClearCoatInfos",size:4,type:"vec4"},{name:"clearCoatMatrix",size:16,type:"mat4"},{name:"clearCoatRoughnessMatrix",size:16,type:"mat4"},{name:"vClearCoatBumpInfos",size:2,type:"vec2"},{name:"vClearCoatTangentSpaceParams",size:2,type:"vec2"},{name:"clearCoatBumpMatrix",size:16,type:"mat4"},{name:"vClearCoatTintParams",size:4,type:"vec4"},{name:"clearCoatColorAtDistance",size:1,type:"float"},{name:"vClearCoatTintInfos",size:2,type:"vec2"},{name:"clearCoatTintMatrix",size:16,type:"mat4"}]}},t._DefaultIndexOfRefraction=1.5,v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"isEnabled",void 0),v([Ie()],t.prototype,"intensity",void 0),v([Ie()],t.prototype,"roughness",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"indexOfRefraction",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"texture",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRoughnessFromMainTexture",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"textureRoughness",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"remapF0OnInterfaceChange",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"bumpTexture",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"isTintEnabled",void 0),v([Oe()],t.prototype,"tintColor",void 0),v([Ie()],t.prototype,"tintColorAtDistance",void 0),v([Ie()],t.prototype,"tintThickness",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"tintTexture",void 0),t}(Nu),jm=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.IRIDESCENCE=!1,t.IRIDESCENCE_TEXTURE=!1,t.IRIDESCENCE_TEXTUREDIRECTUV=0,t.IRIDESCENCE_THICKNESS_TEXTURE=!1,t.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0,t}return m(t,e),t}(Gs),Ym=function(e){function t(i,r){void 0===r&&(r=!0);var n=e.call(this,i,"PBRIridescence",110,new jm,r)||this;return n._isEnabled=!1,n.isEnabled=!1,n.intensity=1,n.minimumThickness=t._DefaultMinimumThickness,n.maximumThickness=t._DefaultMaximumThickness,n.indexOfRefraction=t._DefaultIndexOfRefraction,n._texture=null,n.texture=null,n._thicknessTexture=null,n.thicknessTexture=null,n._internalMarkAllSubMeshesAsTexturesDirty=i._dirtyCallbacks[u.MATERIAL_TextureDirtyFlag],n}return m(t,e),t.prototype._markAllSubMeshesAsTexturesDirty=function(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()},t.prototype.isReadyForSubMesh=function(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&xu.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._thicknessTexture&&xu.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1}return!0},t.prototype.prepareDefinesBeforeAttributes=function(e,t){this._isEnabled?(e.IRIDESCENCE=!0,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&xu.IridescenceTextureEnabled?ta(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,this._thicknessTexture&&xu.IridescenceTextureEnabled?ta(this._thicknessTexture,e,"IRIDESCENCE_THICKNESS_TEXTURE"):e.IRIDESCENCE_THICKNESS_TEXTURE=!1)):(e.IRIDESCENCE=!1,e.IRIDESCENCE_TEXTURE=!1,e.IRIDESCENCE_THICKNESS_TEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)},t.prototype.bindForSubMesh=function(e,t){var i,r,n,o,a,s,l,c;if(this._isEnabled){var u=this._material.isFrozen;e.useUbo&&u&&e.isSync||((this._texture||this._thicknessTexture)&&xu.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",null!==(r=null===(i=this._texture)||void 0===i?void 0:i.coordinatesIndex)&&void 0!==r?r:0,null!==(o=null===(n=this._texture)||void 0===n?void 0:n.level)&&void 0!==o?o:0,null!==(s=null===(a=this._thicknessTexture)||void 0===a?void 0:a.coordinatesIndex)&&void 0!==s?s:0,null!==(c=null===(l=this._thicknessTexture)||void 0===l?void 0:l.level)&&void 0!==c?c:0),this._texture&&ia(this._texture,e,"iridescence"),this._thicknessTexture&&ia(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&xu.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&xu.IridescenceTextureEnabled&&e.setTexture("iridescenceThicknessSampler",this._thicknessTexture))}},t.prototype.hasTexture=function(e){return this._texture===e||this._thicknessTexture===e},t.prototype.getActiveTextures=function(e){this._texture&&e.push(this._texture),this._thicknessTexture&&e.push(this._thicknessTexture)},t.prototype.getAnimatables=function(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture)},t.prototype.dispose=function(e){var t,i;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._thicknessTexture)||void 0===i||i.dispose())},t.prototype.getClassName=function(){return"PBRIridescenceConfiguration"},t.prototype.addFallbacks=function(e,t,i){return e.IRIDESCENCE&&t.addFallback(i++,"IRIDESCENCE"),i},t.prototype.getSamplers=function(e){e.push("iridescenceSampler","iridescenceThicknessSampler")},t.prototype.getUniforms=function(){return{ubo:[{name:"vIridescenceParams",size:4,type:"vec4"},{name:"vIridescenceInfos",size:4,type:"vec4"},{name:"iridescenceMatrix",size:16,type:"mat4"},{name:"iridescenceThicknessMatrix",size:16,type:"mat4"}]}},t._DefaultMinimumThickness=100,t._DefaultMaximumThickness=400,t._DefaultIndexOfRefraction=1.3,v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"isEnabled",void 0),v([Ie()],t.prototype,"intensity",void 0),v([Ie()],t.prototype,"minimumThickness",void 0),v([Ie()],t.prototype,"maximumThickness",void 0),v([Ie()],t.prototype,"indexOfRefraction",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"texture",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"thicknessTexture",void 0),t}(Nu),Km=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.ANISOTROPIC=!1,t.ANISOTROPIC_TEXTURE=!1,t.ANISOTROPIC_TEXTUREDIRECTUV=0,t.ANISOTROPIC_LEGACY=!1,t.MAINUV1=!1,t}return m(t,e),t}(Gs),Qm=function(e){function t(t,i){void 0===i&&(i=!0);var r=e.call(this,t,"PBRAnisotropic",110,new Km,i)||this;return r._isEnabled=!1,r.isEnabled=!1,r.intensity=1,r.direction=new U(1,0),r._texture=null,r.texture=null,r._legacy=!1,r.legacy=!1,r._internalMarkAllSubMeshesAsTexturesDirty=t._dirtyCallbacks[u.MATERIAL_TextureDirtyFlag],r._internalMarkAllSubMeshesAsMiscDirty=t._dirtyCallbacks[u.MATERIAL_MiscDirtyFlag],r}return m(t,e),Object.defineProperty(t.prototype,"angle",{get:function(){return Math.atan2(this.direction.y,this.direction.x)},set:function(e){this.direction.x=Math.cos(e),this.direction.y=Math.sin(e)},enumerable:!1,configurable:!0}),t.prototype._markAllSubMeshesAsTexturesDirty=function(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()},t.prototype._markAllSubMeshesAsMiscDirty=function(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsMiscDirty()},t.prototype.isReadyForSubMesh=function(e,t){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&xu.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking())},t.prototype.prepareDefinesBeforeAttributes=function(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(Nr.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&xu.AnisotropicTextureEnabled?ta(this._texture,e,"ANISOTROPIC_TEXTURE"):e.ANISOTROPIC_TEXTURE=!1),e._areMiscDirty&&(e.ANISOTROPIC_LEGACY=this._legacy)):(e.ANISOTROPIC=!1,e.ANISOTROPIC_TEXTURE=!1,e.ANISOTROPIC_TEXTUREDIRECTUV=0,e.ANISOTROPIC_LEGACY=!1)},t.prototype.bindForSubMesh=function(e,t){if(this._isEnabled){var i=this._material.isFrozen;e.useUbo&&i&&e.isSync||(this._texture&&xu.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),ia(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&xu.AnisotropicTextureEnabled&&e.setTexture("anisotropySampler",this._texture)}},t.prototype.hasTexture=function(e){return this._texture===e},t.prototype.getActiveTextures=function(e){this._texture&&e.push(this._texture)},t.prototype.getAnimatables=function(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)},t.prototype.dispose=function(e){e&&this._texture&&this._texture.dispose()},t.prototype.getClassName=function(){return"PBRAnisotropicConfiguration"},t.prototype.addFallbacks=function(e,t,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i},t.prototype.getSamplers=function(e){e.push("anisotropySampler")},t.prototype.getUniforms=function(){return{ubo:[{name:"vAnisotropy",size:3,type:"vec3"},{name:"vAnisotropyInfos",size:2,type:"vec2"},{name:"anisotropyMatrix",size:16,type:"mat4"}]}},t.prototype.parse=function(t,i,r){e.prototype.parse.call(this,t,i,r),void 0===t.legacy&&(this.legacy=!0)},v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"isEnabled",void 0),v([Ie()],t.prototype,"intensity",void 0),v([Ne()],t.prototype,"direction",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"texture",void 0),v([Ie(),Pe("_markAllSubMeshesAsMiscDirty")],t.prototype,"legacy",void 0),t}(Nu),qm=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.SHEEN=!1,t.SHEEN_TEXTURE=!1,t.SHEEN_GAMMATEXTURE=!1,t.SHEEN_TEXTURE_ROUGHNESS=!1,t.SHEEN_TEXTUREDIRECTUV=0,t.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0,t.SHEEN_LINKWITHALBEDO=!1,t.SHEEN_ROUGHNESS=!1,t.SHEEN_ALBEDOSCALING=!1,t.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,t}return m(t,e),t}(Gs),Zm=function(e){function t(t,i){void 0===i&&(i=!0);var r=e.call(this,t,"Sheen",120,new qm,i)||this;return r._isEnabled=!1,r.isEnabled=!1,r._linkSheenWithAlbedo=!1,r.linkSheenWithAlbedo=!1,r.intensity=1,r.color=Z.White(),r._texture=null,r.texture=null,r._useRoughnessFromMainTexture=!0,r.useRoughnessFromMainTexture=!0,r._roughness=null,r.roughness=null,r._textureRoughness=null,r.textureRoughness=null,r._albedoScaling=!1,r.albedoScaling=!1,r._internalMarkAllSubMeshesAsTexturesDirty=t._dirtyCallbacks[u.MATERIAL_TextureDirtyFlag],r}return m(t,e),t.prototype._markAllSubMeshesAsTexturesDirty=function(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()},t.prototype.isReadyForSubMesh=function(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&xu.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&xu.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1}return!0},t.prototype.prepareDefinesBeforeAttributes=function(e,t){this._isEnabled?(e.SHEEN=!0,e.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,e.SHEEN_ROUGHNESS=null!==this._roughness,e.SHEEN_ALBEDOSCALING=this._albedoScaling,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&xu.SheenTextureEnabled?(ta(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&xu.SheenTextureEnabled?ta(this._textureRoughness,e,"SHEEN_TEXTURE_ROUGHNESS"):e.SHEEN_TEXTURE_ROUGHNESS=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)},t.prototype.bindForSubMesh=function(e,t,i,r){var n,o,a,s,l,c,u,h;if(this._isEnabled){var d=r.materialDefines,p=this._material.isFrozen;e.useUbo&&p&&e.isSync||((this._texture||this._textureRoughness)&&xu.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",null!==(o=null===(n=this._texture)||void 0===n?void 0:n.coordinatesIndex)&&void 0!==o?o:0,null!==(s=null===(a=this._texture)||void 0===a?void 0:a.level)&&void 0!==s?s:0,null!==(c=null===(l=this._textureRoughness)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==c?c:0,null!==(h=null===(u=this._textureRoughness)||void 0===u?void 0:u.level)&&void 0!==h?h:0),this._texture&&ia(this._texture,e,"sheen"),this._textureRoughness&&!d.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&ia(this._textureRoughness,e,"sheenRoughness")),e.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity),null!==this._roughness&&e.updateFloat("vSheenRoughness",this._roughness)),t.texturesEnabled&&(this._texture&&xu.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!d.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&xu.SheenTextureEnabled&&e.setTexture("sheenRoughnessSampler",this._textureRoughness))}},t.prototype.hasTexture=function(e){return this._texture===e||this._textureRoughness===e},t.prototype.getActiveTextures=function(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness)},t.prototype.getAnimatables=function(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness)},t.prototype.dispose=function(e){var t,i;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._textureRoughness)||void 0===i||i.dispose())},t.prototype.getClassName=function(){return"PBRSheenConfiguration"},t.prototype.addFallbacks=function(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i},t.prototype.getSamplers=function(e){e.push("sheenSampler","sheenRoughnessSampler")},t.prototype.getUniforms=function(){return{ubo:[{name:"vSheenColor",size:4,type:"vec4"},{name:"vSheenRoughness",size:1,type:"float"},{name:"vSheenInfos",size:4,type:"vec4"},{name:"sheenMatrix",size:16,type:"mat4"},{name:"sheenRoughnessMatrix",size:16,type:"mat4"}]}},v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"isEnabled",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"linkSheenWithAlbedo",void 0),v([Ie()],t.prototype,"intensity",void 0),v([Oe()],t.prototype,"color",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"texture",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRoughnessFromMainTexture",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"roughness",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"textureRoughness",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"albedoScaling",void 0),t}(Nu),Jm=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.SUBSURFACE=!1,t.SS_REFRACTION=!1,t.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,t.SS_TRANSLUCENCY=!1,t.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,t.SS_SCATTERING=!1,t.SS_DISPERSION=!1,t.SS_THICKNESSANDMASK_TEXTURE=!1,t.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,t.SS_HAS_THICKNESS=!1,t.SS_REFRACTIONINTENSITY_TEXTURE=!1,t.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,t.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,t.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,t.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,t.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0,t.SS_REFRACTIONMAP_3D=!1,t.SS_REFRACTIONMAP_OPPOSITEZ=!1,t.SS_LODINREFRACTIONALPHA=!1,t.SS_GAMMAREFRACTION=!1,t.SS_RGBDREFRACTION=!1,t.SS_LINEARSPECULARREFRACTION=!1,t.SS_LINKREFRACTIONTOTRANSPARENCY=!1,t.SS_ALBEDOFORREFRACTIONTINT=!1,t.SS_ALBEDOFORTRANSLUCENCYTINT=!1,t.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,t.SS_USE_THICKNESS_AS_DEPTH=!1,t.SS_USE_GLTF_TEXTURES=!1,t}return m(t,e),t}(Gs),$m=function(e){function t(t,i){void 0===i&&(i=!0);var r=e.call(this,t,"PBRSubSurface",130,new Jm,i)||this;return r._isRefractionEnabled=!1,r.isRefractionEnabled=!1,r._isTranslucencyEnabled=!1,r.isTranslucencyEnabled=!1,r._isDispersionEnabled=!1,r.isDispersionEnabled=!1,r._isScatteringEnabled=!1,r.isScatteringEnabled=!1,r._scatteringDiffusionProfileIndex=0,r.refractionIntensity=1,r.translucencyIntensity=1,r.useAlbedoToTintRefraction=!1,r.useAlbedoToTintTranslucency=!1,r._thicknessTexture=null,r.thicknessTexture=null,r._refractionTexture=null,r.refractionTexture=null,r._indexOfRefraction=1.5,r.indexOfRefraction=1.5,r._volumeIndexOfRefraction=-1,r._invertRefractionY=!1,r.invertRefractionY=!1,r._linkRefractionWithTransparency=!1,r.linkRefractionWithTransparency=!1,r.minimumThickness=0,r.maximumThickness=1,r.useThicknessAsDepth=!1,r.tintColor=Z.White(),r.tintColorAtDistance=1,r.dispersion=0,r.diffusionDistance=Z.White(),r._useMaskFromThicknessTexture=!1,r.useMaskFromThicknessTexture=!1,r._refractionIntensityTexture=null,r.refractionIntensityTexture=null,r._translucencyIntensityTexture=null,r.translucencyIntensityTexture=null,r.translucencyColor=null,r._translucencyColorTexture=null,r.translucencyColorTexture=null,r._useGltfStyleTextures=!0,r.useGltfStyleTextures=!0,r._scene=t.getScene(),r.registerForExtraEvents=!0,r._internalMarkAllSubMeshesAsTexturesDirty=t._dirtyCallbacks[u.MATERIAL_TextureDirtyFlag],r._internalMarkScenePrePassDirty=t._dirtyCallbacks[u.MATERIAL_PrePassDirtyFlag],r}return m(t,e),Object.defineProperty(t.prototype,"scatteringDiffusionProfile",{get:function(){return this._scene.subSurfaceConfiguration?this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]:null},set:function(e){this._scene.enableSubSurfaceForPrePass()&&e&&(this._scatteringDiffusionProfileIndex=this._scene.subSurfaceConfiguration.addDiffusionProfile(e))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"volumeIndexOfRefraction",{get:function(){return this._volumeIndexOfRefraction>=1?this._volumeIndexOfRefraction:this._indexOfRefraction},set:function(e){this._volumeIndexOfRefraction=e>=1?e:-1},enumerable:!1,configurable:!0}),t.prototype._markAllSubMeshesAsTexturesDirty=function(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()},t.prototype._markScenePrePassDirty=function(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()},t.prototype.isReadyForSubMesh=function(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&xu.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;if(this._translucencyColorTexture&&xu.TranslucencyColorTextureEnabled&&!this._translucencyColorTexture.isReadyOrNotBlocking())return!1;var i=this._getRefractionTexture(t);if(i&&xu.RefractionTextureEnabled&&!i.isReadyOrNotBlocking())return!1}return!0},t.prototype.prepareDefinesBeforeAttributes=function(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return e.SUBSURFACE=!1,e.SS_DISPERSION=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,e.SS_HAS_THICKNESS=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,e.SS_REFRACTIONMAP_3D=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,void(e.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0);if(e._areTexturesDirty){if(e.SUBSURFACE=!0,e.SS_DISPERSION=this._isDispersionEnabled,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_SCATTERING=this._isScatteringEnabled,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_HAS_THICKNESS=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_REFRACTIONMAP_3D=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&xu.ThicknessTextureEnabled&&ta(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&xu.RefractionIntensityTextureEnabled&&ta(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&xu.TranslucencyIntensityTextureEnabled&&ta(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE"),this._translucencyColorTexture&&xu.TranslucencyColorTextureEnabled&&ta(this._translucencyColorTexture,e,"SS_TRANSLUCENCYCOLOR_TEXTURE")),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!=0,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._refractionIntensityTexture,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._translucencyIntensityTexture,this._isRefractionEnabled&&t.texturesEnabled){var i=this._getRefractionTexture(t);i&&xu.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}},t.prototype.hardBindForSubMesh=function(e,t,i,r){if(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled){r.getRenderingMesh().getWorldMatrix().decompose(H.Vector3[0]);var n=Math.max(Math.abs(H.Vector3[0].x),Math.abs(H.Vector3[0].y),Math.abs(H.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*n,(this.maximumThickness-this.minimumThickness)*n)}},t.prototype.bindForSubMesh=function(e,t,i,r){var n;if(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled){var o=r.materialDefines,a=this._material.isFrozen,s=this._material.realTimeFiltering,l=o.LODBASEDMICROSFURACE,c=this._getRefractionTexture(t);if(!e.useUbo||!a||!e.isSync){if(this._thicknessTexture&&xu.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),ia(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&xu.RefractionIntensityTextureEnabled&&o.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),ia(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyColorTexture&&xu.TranslucencyColorTextureEnabled&&o.SS_TRANSLUCENCYCOLOR_TEXTURE&&(e.updateFloat2("vTranslucencyColorInfos",this._translucencyColorTexture.coordinatesIndex,this._translucencyColorTexture.level),ia(this._translucencyColorTexture,e,"translucencyColor")),c&&xu.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",c.getRefractionTextureMatrix());var u=1;c.isCube||c.depth&&(u=c.depth);var h=c.getSize().width,d=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",c.level,1/d,u,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",h,c.lodGenerationScale,c.lodGenerationOffset,1/this.indexOfRefraction),s&&e.updateFloat2("vRefractionFilteringInfo",h,j.Log2(h)),c.boundingBoxSize){var p=c;e.updateVector3("vRefractionPosition",p.boundingBoxPosition),e.updateVector3("vRefractionSize",p.boundingBoxSize)}}this._isScatteringEnabled&&e.updateFloat("scatteringDiffusionProfile",this._scatteringDiffusionProfileIndex),e.updateColor3("vDiffusionDistance",this.diffusionDistance),e.updateFloat4("vTintColor",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintColorAtDistance)),e.updateColor4("vTranslucencyColor",null!==(n=this.translucencyColor)&&void 0!==n?n:this.tintColor,0),e.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0),e.updateFloat("dispersion",this.dispersion)}t.texturesEnabled&&(this._thicknessTexture&&xu.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&xu.RefractionIntensityTextureEnabled&&o.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&xu.TranslucencyIntensityTextureEnabled&&o.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),this._translucencyColorTexture&&xu.TranslucencyColorTextureEnabled&&o.SS_TRANSLUCENCYCOLOR_TEXTURE&&e.setTexture("translucencyColorSampler",this._translucencyColorTexture),c&&xu.RefractionTextureEnabled&&(l?e.setTexture("refractionSampler",c):(e.setTexture("refractionSampler",c._lodTextureMid||c),e.setTexture("refractionSamplerLow",c._lodTextureLow||c),e.setTexture("refractionSamplerHigh",c._lodTextureHigh||c))))}},t.prototype._getRefractionTexture=function(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null},Object.defineProperty(t.prototype,"disableAlphaBlending",{get:function(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency},enumerable:!1,configurable:!0}),t.prototype.fillRenderTargetTextures=function(e){xu.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)},t.prototype.hasTexture=function(e){return this._thicknessTexture===e||this._refractionTexture===e||this._refractionIntensityTexture===e||this._translucencyIntensityTexture===e||this._translucencyColorTexture===e},t.prototype.hasRenderTargetTextures=function(){return!!(xu.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)},t.prototype.getActiveTextures=function(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture),this._translucencyColorTexture&&e.push(this._translucencyColorTexture)},t.prototype.getAnimatables=function(e){this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),this._translucencyColorTexture&&this._translucencyColorTexture.animations&&this._translucencyColorTexture.animations.length>0&&e.push(this._translucencyColorTexture)},t.prototype.dispose=function(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose(),this._translucencyColorTexture&&this._translucencyColorTexture.dispose())},t.prototype.getClassName=function(){return"PBRSubSurfaceConfiguration"},t.prototype.addFallbacks=function(e,t,i){return e.SS_SCATTERING&&t.addFallback(i++,"SS_SCATTERING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i},t.prototype.getSamplers=function(e){e.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh","translucencyColorSampler")},t.prototype.getUniforms=function(){return{ubo:[{name:"vRefractionMicrosurfaceInfos",size:4,type:"vec4"},{name:"vRefractionFilteringInfo",size:2,type:"vec2"},{name:"vTranslucencyIntensityInfos",size:2,type:"vec2"},{name:"vRefractionInfos",size:4,type:"vec4"},{name:"refractionMatrix",size:16,type:"mat4"},{name:"vThicknessInfos",size:2,type:"vec2"},{name:"vRefractionIntensityInfos",size:2,type:"vec2"},{name:"thicknessMatrix",size:16,type:"mat4"},{name:"refractionIntensityMatrix",size:16,type:"mat4"},{name:"translucencyIntensityMatrix",size:16,type:"mat4"},{name:"vThicknessParam",size:2,type:"vec2"},{name:"vDiffusionDistance",size:3,type:"vec3"},{name:"vTintColor",size:4,type:"vec4"},{name:"vSubSurfaceIntensity",size:3,type:"vec3"},{name:"vRefractionPosition",size:3,type:"vec3"},{name:"vRefractionSize",size:3,type:"vec3"},{name:"scatteringDiffusionProfile",size:1,type:"float"},{name:"dispersion",size:1,type:"float"},{name:"vTranslucencyColor",size:4,type:"vec4"},{name:"vTranslucencyColorInfos",size:2,type:"vec2"},{name:"translucencyColorMatrix",size:16,type:"mat4"}]}},v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"isRefractionEnabled",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"isTranslucencyEnabled",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"isDispersionEnabled",void 0),v([Ie(),Pe("_markScenePrePassDirty")],t.prototype,"isScatteringEnabled",void 0),v([Ie()],t.prototype,"_scatteringDiffusionProfileIndex",void 0),v([Ie()],t.prototype,"refractionIntensity",void 0),v([Ie()],t.prototype,"translucencyIntensity",void 0),v([Ie()],t.prototype,"useAlbedoToTintRefraction",void 0),v([Ie()],t.prototype,"useAlbedoToTintTranslucency",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"thicknessTexture",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"refractionTexture",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"indexOfRefraction",void 0),v([Ie()],t.prototype,"_volumeIndexOfRefraction",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"volumeIndexOfRefraction",null),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"invertRefractionY",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"linkRefractionWithTransparency",void 0),v([Ie()],t.prototype,"minimumThickness",void 0),v([Ie()],t.prototype,"maximumThickness",void 0),v([Ie()],t.prototype,"useThicknessAsDepth",void 0),v([Oe()],t.prototype,"tintColor",void 0),v([Ie()],t.prototype,"tintColorAtDistance",void 0),v([Ie()],t.prototype,"dispersion",void 0),v([Oe()],t.prototype,"diffusionDistance",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useMaskFromThicknessTexture",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"refractionIntensityTexture",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"translucencyIntensityTexture",void 0),v([Oe()],t.prototype,"translucencyColor",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"translucencyColorTexture",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useGltfStyleTextures",void 0),t}(Nu),eg={effect:null,subMesh:null},tg=function(e){function t(t){var i=e.call(this,t)||this;return i.PBR=!0,i.NUM_SAMPLES="0",i.REALTIME_FILTERING=!1,i.MAINUV1=!1,i.MAINUV2=!1,i.MAINUV3=!1,i.MAINUV4=!1,i.MAINUV5=!1,i.MAINUV6=!1,i.UV1=!1,i.UV2=!1,i.UV3=!1,i.UV4=!1,i.UV5=!1,i.UV6=!1,i.ALBEDO=!1,i.GAMMAALBEDO=!1,i.ALBEDODIRECTUV=0,i.VERTEXCOLOR=!1,i.BAKED_VERTEX_ANIMATION_TEXTURE=!1,i.AMBIENT=!1,i.AMBIENTDIRECTUV=0,i.AMBIENTINGRAYSCALE=!1,i.OPACITY=!1,i.VERTEXALPHA=!1,i.OPACITYDIRECTUV=0,i.OPACITYRGB=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.ALPHABLEND=!1,i.ALPHAFROMALBEDO=!1,i.ALPHATESTVALUE="0.5",i.SPECULAROVERALPHA=!1,i.RADIANCEOVERALPHA=!1,i.ALPHAFRESNEL=!1,i.LINEARALPHAFRESNEL=!1,i.PREMULTIPLYALPHA=!1,i.EMISSIVE=!1,i.EMISSIVEDIRECTUV=0,i.GAMMAEMISSIVE=!1,i.REFLECTIVITY=!1,i.REFLECTIVITY_GAMMA=!1,i.REFLECTIVITYDIRECTUV=0,i.SPECULARTERM=!1,i.MICROSURFACEFROMREFLECTIVITYMAP=!1,i.MICROSURFACEAUTOMATIC=!1,i.LODBASEDMICROSFURACE=!1,i.MICROSURFACEMAP=!1,i.MICROSURFACEMAPDIRECTUV=0,i.METALLICWORKFLOW=!1,i.ROUGHNESSSTOREINMETALMAPALPHA=!1,i.ROUGHNESSSTOREINMETALMAPGREEN=!1,i.METALLNESSSTOREINMETALMAPBLUE=!1,i.AOSTOREINMETALMAPRED=!1,i.METALLIC_REFLECTANCE=!1,i.METALLIC_REFLECTANCE_GAMMA=!1,i.METALLIC_REFLECTANCEDIRECTUV=0,i.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=!1,i.REFLECTANCE=!1,i.REFLECTANCE_GAMMA=!1,i.REFLECTANCEDIRECTUV=0,i.ENVIRONMENTBRDF=!1,i.ENVIRONMENTBRDF_RGBD=!1,i.NORMAL=!1,i.TANGENT=!1,i.BUMP=!1,i.BUMPDIRECTUV=0,i.OBJECTSPACE_NORMALMAP=!1,i.PARALLAX=!1,i.PARALLAX_RHS=!1,i.PARALLAXOCCLUSION=!1,i.NORMALXYSCALE=!0,i.LIGHTMAP=!1,i.LIGHTMAPDIRECTUV=0,i.USELIGHTMAPASSHADOWMAP=!1,i.GAMMALIGHTMAP=!1,i.RGBDLIGHTMAP=!1,i.REFLECTION=!1,i.REFLECTIONMAP_3D=!1,i.REFLECTIONMAP_SPHERICAL=!1,i.REFLECTIONMAP_PLANAR=!1,i.REFLECTIONMAP_CUBIC=!1,i.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,i.REFLECTIONMAP_PROJECTION=!1,i.REFLECTIONMAP_SKYBOX=!1,i.REFLECTIONMAP_EXPLICIT=!1,i.REFLECTIONMAP_EQUIRECTANGULAR=!1,i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,i.INVERTCUBICMAP=!1,i.USESPHERICALFROMREFLECTIONMAP=!1,i.USEIRRADIANCEMAP=!1,i.USESPHERICALINVERTEX=!1,i.REFLECTIONMAP_OPPOSITEZ=!1,i.LODINREFLECTIONALPHA=!1,i.GAMMAREFLECTION=!1,i.RGBDREFLECTION=!1,i.LINEARSPECULARREFLECTION=!1,i.RADIANCEOCCLUSION=!1,i.HORIZONOCCLUSION=!1,i.INSTANCES=!1,i.THIN_INSTANCES=!1,i.INSTANCESCOLOR=!1,i.PREPASS=!1,i.PREPASS_IRRADIANCE=!1,i.PREPASS_IRRADIANCE_INDEX=-1,i.PREPASS_ALBEDO_SQRT=!1,i.PREPASS_ALBEDO_SQRT_INDEX=-1,i.PREPASS_DEPTH=!1,i.PREPASS_DEPTH_INDEX=-1,i.PREPASS_NORMAL=!1,i.PREPASS_NORMAL_INDEX=-1,i.PREPASS_NORMAL_WORLDSPACE=!1,i.PREPASS_POSITION=!1,i.PREPASS_POSITION_INDEX=-1,i.PREPASS_VELOCITY=!1,i.PREPASS_VELOCITY_INDEX=-1,i.PREPASS_REFLECTIVITY=!1,i.PREPASS_REFLECTIVITY_INDEX=-1,i.SCENE_MRT_COUNT=0,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.BONETEXTURE=!1,i.BONES_VELOCITY_ENABLED=!1,i.NONUNIFORMSCALING=!1,i.MORPHTARGETS=!1,i.MORPHTARGETS_NORMAL=!1,i.MORPHTARGETS_TANGENT=!1,i.MORPHTARGETS_UV=!1,i.NUM_MORPH_INFLUENCERS=0,i.MORPHTARGETS_TEXTURE=!1,i.IMAGEPROCESSING=!1,i.VIGNETTE=!1,i.VIGNETTEBLENDMODEMULTIPLY=!1,i.VIGNETTEBLENDMODEOPAQUE=!1,i.TONEMAPPING=0,i.CONTRAST=!1,i.COLORCURVES=!1,i.COLORGRADING=!1,i.COLORGRADING3D=!1,i.SAMPLER3DGREENDEPTH=!1,i.SAMPLER3DBGRMAP=!1,i.DITHER=!1,i.IMAGEPROCESSINGPOSTPROCESS=!1,i.SKIPFINALCOLORCLAMP=!1,i.EXPOSURE=!1,i.MULTIVIEW=!1,i.ORDER_INDEPENDENT_TRANSPARENCY=!1,i.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,i.USEPHYSICALLIGHTFALLOFF=!1,i.USEGLTFLIGHTFALLOFF=!1,i.TWOSIDEDLIGHTING=!1,i.SHADOWFLOAT=!1,i.CLIPPLANE=!1,i.CLIPPLANE2=!1,i.CLIPPLANE3=!1,i.CLIPPLANE4=!1,i.CLIPPLANE5=!1,i.CLIPPLANE6=!1,i.POINTSIZE=!1,i.FOG=!1,i.LOGARITHMICDEPTH=!1,i.CAMERA_ORTHOGRAPHIC=!1,i.CAMERA_PERSPECTIVE=!1,i.FORCENORMALFORWARD=!1,i.SPECULARAA=!1,i.UNLIT=!1,i.DECAL_AFTER_DETAIL=!1,i.DEBUGMODE=0,i.rebuild(),i}return m(t,e),t.prototype.reset=function(){e.prototype.reset.call(this),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0},t}(Gs),ig=function(e){function t(i,r){var n=e.call(this,i,r)||this;return n._directIntensity=1,n._emissiveIntensity=1,n._environmentIntensity=1,n._specularIntensity=1,n._lightingInfos=new k(n._directIntensity,n._emissiveIntensity,n._environmentIntensity,n._specularIntensity),n._disableBumpMap=!1,n._albedoTexture=null,n._ambientTexture=null,n._ambientTextureStrength=1,n._ambientTextureImpactOnAnalyticalLights=t.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,n._opacityTexture=null,n._reflectionTexture=null,n._emissiveTexture=null,n._reflectivityTexture=null,n._metallicTexture=null,n._metallic=null,n._roughness=null,n._metallicF0Factor=1,n._metallicReflectanceColor=Z.White(),n._useOnlyMetallicFromMetallicReflectanceTexture=!1,n._metallicReflectanceTexture=null,n._reflectanceTexture=null,n._microSurfaceTexture=null,n._bumpTexture=null,n._lightmapTexture=null,n._ambientColor=new Z(0,0,0),n._albedoColor=new Z(1,1,1),n._reflectivityColor=new Z(1,1,1),n._reflectionColor=new Z(1,1,1),n._emissiveColor=new Z(0,0,0),n._microSurface=.9,n._useLightmapAsShadowmap=!1,n._useHorizonOcclusion=!0,n._useRadianceOcclusion=!0,n._useAlphaFromAlbedoTexture=!1,n._useSpecularOverAlpha=!0,n._useMicroSurfaceFromReflectivityMapAlpha=!1,n._useRoughnessFromMetallicTextureAlpha=!0,n._useRoughnessFromMetallicTextureGreen=!1,n._useMetallnessFromMetallicTextureBlue=!1,n._useAmbientOcclusionFromMetallicTextureRed=!1,n._useAmbientInGrayScale=!1,n._useAutoMicroSurfaceFromReflectivityMap=!1,n._lightFalloff=t.LIGHTFALLOFF_PHYSICAL,n._useRadianceOverAlpha=!0,n._useObjectSpaceNormalMap=!1,n._useParallax=!1,n._useParallaxOcclusion=!1,n._parallaxScaleBias=.05,n._disableLighting=!1,n._maxSimultaneousLights=4,n._invertNormalMapX=!1,n._invertNormalMapY=!1,n._twoSidedLighting=!1,n._alphaCutOff=.4,n._forceAlphaTest=!1,n._useAlphaFresnel=!1,n._useLinearAlphaFresnel=!1,n._environmentBRDFTexture=null,n._forceIrradianceInFragment=!1,n._realTimeFiltering=!1,n._realTimeFilteringQuality=u.TEXTURE_FILTERING_QUALITY_LOW,n._forceNormalForward=!1,n._enableSpecularAntiAliasing=!1,n._imageProcessingObserver=null,n._renderTargets=new ar(16),n._globalAmbientColor=new Z(0,0,0),n._unlit=!1,n._applyDecalMapAfterDetailMap=!1,n._debugMode=0,n.debugMode=0,n.debugLimit=-1,n.debugFactor=1,n._cacheHasRenderTargetTextures=!1,n.brdf=new Wm(n),n.clearCoat=new Xm(n),n.iridescence=new Ym(n),n.anisotropy=new Qm(n),n.sheen=new Zm(n),n.subSurface=new $m(n),n.detailMap=new Lu(n),n._attachImageProcessingConfiguration(null),n.getRenderTargetTextures=function(){return n._renderTargets.reset(),xu.ReflectionTextureEnabled&&n._reflectionTexture&&n._reflectionTexture.isRenderTarget&&n._renderTargets.push(n._reflectionTexture),n._eventInfo.renderTargets=n._renderTargets,n._callbackPluginEventFillRenderTargetTextures(n._eventInfo),n._renderTargets},n._environmentBRDFTexture=km(n.getScene()),n.prePassConfiguration=new Su,n}return m(t,e),Object.defineProperty(t.prototype,"realTimeFiltering",{get:function(){return this._realTimeFiltering},set:function(e){this._realTimeFiltering=e,this.markAsDirty(u.MATERIAL_TextureDirtyFlag)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"realTimeFilteringQuality",{get:function(){return this._realTimeFilteringQuality},set:function(e){this._realTimeFilteringQuality=e,this.markAsDirty(u.MATERIAL_TextureDirtyFlag)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"canRenderToMRT",{get:function(){return!0},enumerable:!1,configurable:!0}),t.prototype._attachImageProcessingConfiguration=function(e){var t=this;e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((function(){t._markAllSubMeshesAsImageProcessingDirty()}))))},Object.defineProperty(t.prototype,"hasRenderTargetTextures",{get:function(){return!!(xu.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isPrePassCapable",{get:function(){return!this.disableDepthWrite},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"PBRBaseMaterial"},Object.defineProperty(t.prototype,"_disableAlphaBlending",{get:function(){var e;return this._transparencyMode===t.PBRMATERIAL_OPAQUE||this._transparencyMode===t.PBRMATERIAL_ALPHATEST||(null===(e=this.subSurface)||void 0===e?void 0:e.disableAlphaBlending)},enumerable:!1,configurable:!0}),t.prototype.needAlphaBlending=function(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromAlbedoTexture())},t.prototype.needAlphaTesting=function(){var e;return!!this._forceAlphaTest||!(null===(e=this.subSurface)||void 0===e?void 0:e.disableAlphaBlending)&&this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===t.PBRMATERIAL_ALPHATEST)},t.prototype._shouldUseAlphaFromAlbedoTexture=function(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==t.PBRMATERIAL_OPAQUE},t.prototype._hasAlphaChannel=function(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture},t.prototype.getAlphaTestTexture=function(){return this._albedoTexture},t.prototype.isReadyForSubMesh=function(e,t,i){var r;this._uniformBufferLayoutBuilt||this.buildUniformLayout();var n=t._drawWrapper;if(n.effect&&this.isFrozen&&n._wasPreviouslyReady&&n._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(Vo.GetDefineNames,this._eventInfo),t.materialDefines=new tg(this._eventInfo.defineNames));var o=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;var a=this.getScene(),s=a.getEngine();if(o._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,a.texturesEnabled)){if(this._albedoTexture&&xu.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking())return!1;if(this._ambientTexture&&xu.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking())return!1;if(this._opacityTexture&&xu.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;var l=this._getReflectionTexture();if(l&&xu.ReflectionTextureEnabled){if(!l.isReadyOrNotBlocking())return!1;if(l.irradianceTexture){if(!l.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!l.sphericalPolynomial&&(null===(r=l.getInternalTexture())||void 0===r?void 0:r._sphericalPolynomialPromise))return!1}if(this._lightmapTexture&&xu.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking())return!1;if(this._emissiveTexture&&xu.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(xu.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking())return!1;if(this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking())return!1;if(this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(s.getCaps().standardDerivatives&&this._bumpTexture&&xu.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady())return!1;if(this._environmentBRDFTexture&&xu.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=o,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(o._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;s.getCaps().standardDerivatives||e.isVerticesDataPresent(Nr.NormalKind)||(e.createNormals(!0),ae.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));var c=t.effect,u=o._areLightsDisposed,h=this._prepareEffect(e,o,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),d=!1;if(h)if(this._onEffectCreatedObservable&&(eg.effect=h,eg.subMesh=t,this._onEffectCreatedObservable.notifyObservers(eg)),this.allowShaderHotSwapping&&c&&!h.isReady()){if(h=c,o.markAsUnprocessed(),d=this.isFrozen,u)return o._areLightsDisposed=!0,!1}else a.resetCachedMaterial(),t.setEffect(h,o,this._materialContext);return!(!t.effect||!t.effect.isReady()||(o._renderId=a.getRenderId(),n._wasPreviouslyReady=!d,n._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),0))},t.prototype.isMetallicWorkflow=function(){return!(null==this._metallic&&null==this._roughness&&!this._metallicTexture)},t.prototype._prepareEffect=function(e,t,i,r,n,o,a){if(void 0===i&&(i=null),void 0===r&&(r=null),void 0===n&&(n=null),void 0===o&&(o=null),this._prepareDefines(e,t,n,o,a),!t.isDirty)return null;t.markAsProcessed();var s=this.getScene().getEngine(),l=new ll,c=0;t.USESPHERICALINVERTEX&&l.addFallback(c++,"USESPHERICALINVERTEX"),t.FOG&&l.addFallback(c,"FOG"),t.SPECULARAA&&l.addFallback(c,"SPECULARAA"),t.POINTSIZE&&l.addFallback(c,"POINTSIZE"),t.LOGARITHMICDEPTH&&l.addFallback(c,"LOGARITHMICDEPTH"),t.PARALLAX&&l.addFallback(c,"PARALLAX"),t.PARALLAX_RHS&&l.addFallback(c,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&l.addFallback(c++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&l.addFallback(c++,"ENVIRONMENTBRDF"),t.TANGENT&&l.addFallback(c++,"TANGENT"),t.BUMP&&l.addFallback(c++,"BUMP"),c=ua(t,l,this._maxSimultaneousLights,c++),t.SPECULARTERM&&l.addFallback(c++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&l.addFallback(c++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&l.addFallback(c++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&l.addFallback(c++,"LIGHTMAP"),t.NORMAL&&l.addFallback(c++,"NORMAL"),t.AMBIENT&&l.addFallback(c++,"AMBIENT"),t.EMISSIVE&&l.addFallback(c++,"EMISSIVE"),t.VERTEXCOLOR&&l.addFallback(c++,"VERTEXCOLOR"),t.MORPHTARGETS&&l.addFallback(c++,"MORPHTARGETS"),t.MULTIVIEW&&l.addFallback(0,"MULTIVIEW");var h=[Nr.PositionKind];t.NORMAL&&h.push(Nr.NormalKind),t.TANGENT&&h.push(Nr.TangentKind);for(var d=1;d<=u.MAX_SUPPORTED_UV_SETS;++d)t["UV"+d]&&h.push("uv".concat(1===d?"":d));t.VERTEXCOLOR&&h.push(Nr.ColorKind),la(h,e,t,l),ca(h,t),Zo(h,e,t),ra(h,0,t);var p="pbr",f=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vMetallicReflectanceFactors","vEmissiveColor","visibility","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vReflectionFilteringInfo","vMetallicReflectanceInfos","vReflectanceInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","mBones","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","metallicReflectanceMatrix","reflectanceMatrix","vLightingIntensity","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX_ZZ","vSphericalYY_ZZ","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vSphericalL00","vSphericalL1_1","vSphericalL10","vSphericalL11","vSphericalL2_2","vSphericalL2_1","vSphericalL20","vSphericalL21","vSphericalL22","vReflectionMicrosurfaceInfos","vTangentSpaceParams","boneTextureWidth","vDebugMode","morphTargetTextureInfo","morphTargetTextureIndices"],_=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],m=["Material","Scene","Mesh"],g={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=l,this._eventInfo.fallbackRank=c,this._eventInfo.defines=t,this._eventInfo.uniforms=f,this._eventInfo.attributes=h,this._eventInfo.samplers=_,this._eventInfo.uniformBuffersNames=m,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=g,this._callbackPluginEventGeneric(Vo.PrepareEffect,this._eventInfo),Su.AddUniforms(f),Su.AddSamplers(_),Go(f),pr&&(pr.PrepareUniforms(f,t),pr.PrepareSamplers(_,t)),Aa({uniformsNames:f,uniformBuffersNames:m,samplers:_,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});var v={};this.customShaderNameResolve&&(p=this.customShaderNameResolve(p,f,m,_,t,h,v));var y=t.toString(),b=s.createEffect(p,{attributes:h,uniformsNames:f,uniformBuffersNames:m,samplers:_,defines:y,fallbacks:l,onCompiled:i,onError:r,indexParameters:g,processFinalCode:v.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},s);return this._eventInfo.customCode=void 0,b},t.prototype._prepareDefines=function(e,i,r,n,o){void 0===r&&(r=null),void 0===n&&(n=null),void 0===o&&(o=!1);var a=this.getScene(),s=a.getEngine();pa(a,e,i,!0,this._maxSimultaneousLights,this._disableLighting),i._needNormals=!0,ba(a,i);var l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Ea(a,i,this.canRenderToMRT&&!l),Ta(a,i,l),i.METALLICWORKFLOW=this.isMetallicWorkflow(),i._areTexturesDirty){i._needUVs=!1;for(var c=1;c<=u.MAX_SUPPORTED_UV_SETS;++c)i["MAINUV"+c]=!1;if(a.texturesEnabled){i.ALBEDODIRECTUV=0,i.AMBIENTDIRECTUV=0,i.OPACITYDIRECTUV=0,i.EMISSIVEDIRECTUV=0,i.REFLECTIVITYDIRECTUV=0,i.MICROSURFACEMAPDIRECTUV=0,i.METALLIC_REFLECTANCEDIRECTUV=0,i.REFLECTANCEDIRECTUV=0,i.BUMPDIRECTUV=0,i.LIGHTMAPDIRECTUV=0,s.getCaps().textureLOD&&(i.LODBASEDMICROSFURACE=!0),this._albedoTexture&&xu.DiffuseTextureEnabled?(ta(this._albedoTexture,i,"ALBEDO"),i.GAMMAALBEDO=this._albedoTexture.gammaSpace):i.ALBEDO=!1,this._ambientTexture&&xu.AmbientTextureEnabled?(ta(this._ambientTexture,i,"AMBIENT"),i.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):i.AMBIENT=!1,this._opacityTexture&&xu.OpacityTextureEnabled?(ta(this._opacityTexture,i,"OPACITY"),i.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):i.OPACITY=!1;var h=this._getReflectionTexture();if(h&&xu.ReflectionTextureEnabled){switch(i.REFLECTION=!0,i.GAMMAREFLECTION=h.gammaSpace,i.RGBDREFLECTION=h.isRGBD,i.LODINREFLECTIONALPHA=h.lodLevelInAlpha,i.LINEARSPECULARREFLECTION=h.linearSpecularLOD,this.realTimeFiltering&&this.realTimeFilteringQuality>0?(i.NUM_SAMPLES=""+this.realTimeFilteringQuality,s._features.needTypeSuffixInShaderConstants&&(i.NUM_SAMPLES=i.NUM_SAMPLES+"u"),i.REALTIME_FILTERING=!0):i.REALTIME_FILTERING=!1,i.INVERTCUBICMAP=h.coordinatesMode===Ja.INVCUBIC_MODE,i.REFLECTIONMAP_3D=h.isCube,i.REFLECTIONMAP_OPPOSITEZ=i.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!h.invertZ:h.invertZ,i.REFLECTIONMAP_CUBIC=!1,i.REFLECTIONMAP_EXPLICIT=!1,i.REFLECTIONMAP_PLANAR=!1,i.REFLECTIONMAP_PROJECTION=!1,i.REFLECTIONMAP_SKYBOX=!1,i.REFLECTIONMAP_SPHERICAL=!1,i.REFLECTIONMAP_EQUIRECTANGULAR=!1,i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,h.coordinatesMode){case Ja.EXPLICIT_MODE:i.REFLECTIONMAP_EXPLICIT=!0;break;case Ja.PLANAR_MODE:i.REFLECTIONMAP_PLANAR=!0;break;case Ja.PROJECTION_MODE:i.REFLECTIONMAP_PROJECTION=!0;break;case Ja.SKYBOX_MODE:i.REFLECTIONMAP_SKYBOX=!0;break;case Ja.SPHERICAL_MODE:i.REFLECTIONMAP_SPHERICAL=!0;break;case Ja.EQUIRECTANGULAR_MODE:i.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Ja.FIXED_EQUIRECTANGULAR_MODE:i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Ja.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Ja.CUBIC_MODE:case Ja.INVCUBIC_MODE:default:i.REFLECTIONMAP_CUBIC=!0,i.USE_LOCAL_REFLECTIONMAP_CUBIC=!!h.boundingBoxSize}h.coordinatesMode!==Ja.SKYBOX_MODE&&(h.irradianceTexture?(i.USEIRRADIANCEMAP=!0,i.USESPHERICALFROMREFLECTIONMAP=!1):h.isCube&&(i.USESPHERICALFROMREFLECTIONMAP=!0,i.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||s.getCaps().maxVaryingVectors<=8?i.USESPHERICALINVERTEX=!1:i.USESPHERICALINVERTEX=!0))}else i.REFLECTION=!1,i.REFLECTIONMAP_3D=!1,i.REFLECTIONMAP_SPHERICAL=!1,i.REFLECTIONMAP_PLANAR=!1,i.REFLECTIONMAP_CUBIC=!1,i.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,i.REFLECTIONMAP_PROJECTION=!1,i.REFLECTIONMAP_SKYBOX=!1,i.REFLECTIONMAP_EXPLICIT=!1,i.REFLECTIONMAP_EQUIRECTANGULAR=!1,i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,i.INVERTCUBICMAP=!1,i.USESPHERICALFROMREFLECTIONMAP=!1,i.USEIRRADIANCEMAP=!1,i.USESPHERICALINVERTEX=!1,i.REFLECTIONMAP_OPPOSITEZ=!1,i.LODINREFLECTIONALPHA=!1,i.GAMMAREFLECTION=!1,i.RGBDREFLECTION=!1,i.LINEARSPECULARREFLECTION=!1;this._lightmapTexture&&xu.LightmapTextureEnabled?(ta(this._lightmapTexture,i,"LIGHTMAP"),i.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,i.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,i.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):i.LIGHTMAP=!1,this._emissiveTexture&&xu.EmissiveTextureEnabled?(ta(this._emissiveTexture,i,"EMISSIVE"),i.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):i.EMISSIVE=!1,xu.SpecularTextureEnabled?(this._metallicTexture?(ta(this._metallicTexture,i,"REFLECTIVITY"),i.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,i.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,i.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,i.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed,i.REFLECTIVITY_GAMMA=!1):this._reflectivityTexture?(ta(this._reflectivityTexture,i,"REFLECTIVITY"),i.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,i.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap,i.REFLECTIVITY_GAMMA=this._reflectivityTexture.gammaSpace):i.REFLECTIVITY=!1,this._metallicReflectanceTexture||this._reflectanceTexture?(i.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture,this._metallicReflectanceTexture?(ta(this._metallicReflectanceTexture,i,"METALLIC_REFLECTANCE"),i.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):i.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(ta(this._reflectanceTexture,i,"REFLECTANCE"),i.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):i.REFLECTANCE=!1):(i.METALLIC_REFLECTANCE=!1,i.REFLECTANCE=!1),this._microSurfaceTexture?ta(this._microSurfaceTexture,i,"MICROSURFACEMAP"):i.MICROSURFACEMAP=!1):(i.REFLECTIVITY=!1,i.MICROSURFACEMAP=!1),s.getCaps().standardDerivatives&&this._bumpTexture&&xu.BumpTextureEnabled&&!this._disableBumpMap?(ta(this._bumpTexture,i,"BUMP"),this._useParallax&&this._albedoTexture&&xu.DiffuseTextureEnabled?(i.PARALLAX=!0,i.PARALLAX_RHS=a.useRightHandedSystem,i.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):i.PARALLAX=!1,i.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(i.BUMP=!1,i.PARALLAX=!1,i.PARALLAX_RHS=!1,i.PARALLAXOCCLUSION=!1,i.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&xu.ReflectionTextureEnabled?(i.ENVIRONMENTBRDF=!0,i.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(i.ENVIRONMENTBRDF=!1,i.ENVIRONMENTBRDF_RGBD=!1),this._shouldUseAlphaFromAlbedoTexture()?i.ALPHAFROMALBEDO=!0:i.ALPHAFROMALBEDO=!1}i.SPECULAROVERALPHA=this._useSpecularOverAlpha,this._lightFalloff===t.LIGHTFALLOFF_STANDARD?(i.USEPHYSICALLIGHTFALLOFF=!1,i.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===t.LIGHTFALLOFF_GLTF?(i.USEPHYSICALLIGHTFALLOFF=!1,i.USEGLTFLIGHTFALLOFF=!0):(i.USEPHYSICALLIGHTFALLOFF=!0,i.USEGLTFLIGHTFALLOFF=!1),i.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?i.TWOSIDEDLIGHTING=!0:i.TWOSIDEDLIGHTING=!1,i.SPECULARAA=s.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(i._areTexturesDirty||i._areMiscDirty)&&(i.ALPHATESTVALUE="".concat(this._alphaCutOff).concat(this._alphaCutOff%1==0?".":""),i.PREMULTIPLYALPHA=this.alphaMode===u.ALPHA_PREMULTIPLIED||this.alphaMode===u.ALPHA_PREMULTIPLIED_PORTERDUFF,i.ALPHABLEND=this.needAlphaBlendingForMesh(e),i.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,i.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),i._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(i),i.FORCENORMALFORWARD=this._forceNormalForward,i.RADIANCEOCCLUSION=this._useRadianceOcclusion,i.HORIZONOCCLUSION=this._useHorizonOcclusion,i._areMiscDirty&&(da(e,a,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,i,this._applyDecalMapAfterDetailMap),i.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(Nr.NormalKind),i.DEBUGMODE=this._debugMode),_a(a,s,this,i,!!r,n,o),this._eventInfo.defines=i,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),ya(e,i,!0,!0,!0,this._transparencyMode!==t.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)},t.prototype.forceCompilation=function(e,t,i){var r=this,n=g({clipPlane:!1,useInstances:!1},i);this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(Vo.GetDefineNames,this._eventInfo);var o=new tg(this._eventInfo.defineNames),a=this._prepareEffect(e,o,void 0,void 0,n.useInstances,n.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(eg.effect=a,eg.subMesh=null,this._onEffectCreatedObservable.notifyObservers(eg)),a.isReady()?t&&t(this):a.onCompileObservable.add((function(){t&&t(r)}))},t.prototype.buildUniformLayout=function(){var t=this._uniformBuffer;t.addUniform("vAlbedoInfos",2),t.addUniform("vAmbientInfos",4),t.addUniform("vOpacityInfos",2),t.addUniform("vEmissiveInfos",2),t.addUniform("vLightmapInfos",2),t.addUniform("vReflectivityInfos",3),t.addUniform("vMicroSurfaceSamplerInfos",2),t.addUniform("vReflectionInfos",2),t.addUniform("vReflectionFilteringInfo",2),t.addUniform("vReflectionPosition",3),t.addUniform("vReflectionSize",3),t.addUniform("vBumpInfos",3),t.addUniform("albedoMatrix",16),t.addUniform("ambientMatrix",16),t.addUniform("opacityMatrix",16),t.addUniform("emissiveMatrix",16),t.addUniform("lightmapMatrix",16),t.addUniform("reflectivityMatrix",16),t.addUniform("microSurfaceSamplerMatrix",16),t.addUniform("bumpMatrix",16),t.addUniform("vTangentSpaceParams",2),t.addUniform("reflectionMatrix",16),t.addUniform("vReflectionColor",3),t.addUniform("vAlbedoColor",4),t.addUniform("vLightingIntensity",4),t.addUniform("vReflectionMicrosurfaceInfos",3),t.addUniform("pointSize",1),t.addUniform("vReflectivityColor",4),t.addUniform("vEmissiveColor",3),t.addUniform("vAmbientColor",3),t.addUniform("vDebugMode",2),t.addUniform("vMetallicReflectanceFactors",4),t.addUniform("vMetallicReflectanceInfos",2),t.addUniform("metallicReflectanceMatrix",16),t.addUniform("vReflectanceInfos",2),t.addUniform("reflectanceMatrix",16),t.addUniform("vSphericalL00",3),t.addUniform("vSphericalL1_1",3),t.addUniform("vSphericalL10",3),t.addUniform("vSphericalL11",3),t.addUniform("vSphericalL2_2",3),t.addUniform("vSphericalL2_1",3),t.addUniform("vSphericalL20",3),t.addUniform("vSphericalL21",3),t.addUniform("vSphericalL22",3),t.addUniform("vSphericalX",3),t.addUniform("vSphericalY",3),t.addUniform("vSphericalZ",3),t.addUniform("vSphericalXX_ZZ",3),t.addUniform("vSphericalYY_ZZ",3),t.addUniform("vSphericalZZ",3),t.addUniform("vSphericalXY",3),t.addUniform("vSphericalYZ",3),t.addUniform("vSphericalZX",3),e.prototype.buildUniformLayout.call(this)},t.prototype.bindForSubMesh=function(e,t,i){var r,n,o,a,s=this.getScene(),l=i.materialDefines;if(l){var c=i.effect;if(c){this._activeEffect=c,t.getMeshUniformBuffer().bindToEffect(c,"Mesh"),t.transferToEffect(e);var u=s.getEngine();this._uniformBuffer.bindToEffect(c,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),l.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));var h=this._mustRebind(s,c,i,t.visibility);na(t,this._activeEffect,this.prePassConfiguration);var d=null,p=this._uniformBuffer;if(h){if(this.bindViewProjection(c),d=this._getReflectionTexture(),!p.useUbo||!this.isFrozen||!p.isSync||i._drawWrapper._forceRebindOnNextCall){if(s.texturesEnabled){if(this._albedoTexture&&xu.DiffuseTextureEnabled&&(p.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),ia(this._albedoTexture,p,"albedo")),this._ambientTexture&&xu.AmbientTextureEnabled&&(p.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),ia(this._ambientTexture,p,"ambient")),this._opacityTexture&&xu.OpacityTextureEnabled&&(p.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),ia(this._opacityTexture,p,"opacity")),d&&xu.ReflectionTextureEnabled){if(p.updateMatrix("reflectionMatrix",d.getReflectionTextureMatrix()),p.updateFloat2("vReflectionInfos",d.level,0),d.boundingBoxSize){var f=d;p.updateVector3("vReflectionPosition",f.boundingBoxPosition),p.updateVector3("vReflectionSize",f.boundingBoxSize)}if(this.realTimeFiltering){var _=d.getSize().width;p.updateFloat2("vReflectionFilteringInfo",_,j.Log2(_))}if(!l.USEIRRADIANCEMAP){var m=d.sphericalPolynomial;if(l.USESPHERICALFROMREFLECTIONMAP&&m)if(l.SPHERICAL_HARMONICS){var g=m.preScaledHarmonics;p.updateVector3("vSphericalL00",g.l00),p.updateVector3("vSphericalL1_1",g.l1_1),p.updateVector3("vSphericalL10",g.l10),p.updateVector3("vSphericalL11",g.l11),p.updateVector3("vSphericalL2_2",g.l2_2),p.updateVector3("vSphericalL2_1",g.l2_1),p.updateVector3("vSphericalL20",g.l20),p.updateVector3("vSphericalL21",g.l21),p.updateVector3("vSphericalL22",g.l22)}else p.updateFloat3("vSphericalX",m.x.x,m.x.y,m.x.z),p.updateFloat3("vSphericalY",m.y.x,m.y.y,m.y.z),p.updateFloat3("vSphericalZ",m.z.x,m.z.y,m.z.z),p.updateFloat3("vSphericalXX_ZZ",m.xx.x-m.zz.x,m.xx.y-m.zz.y,m.xx.z-m.zz.z),p.updateFloat3("vSphericalYY_ZZ",m.yy.x-m.zz.x,m.yy.y-m.zz.y,m.yy.z-m.zz.z),p.updateFloat3("vSphericalZZ",m.zz.x,m.zz.y,m.zz.z),p.updateFloat3("vSphericalXY",m.xy.x,m.xy.y,m.xy.z),p.updateFloat3("vSphericalYZ",m.yz.x,m.yz.y,m.yz.z),p.updateFloat3("vSphericalZX",m.zx.x,m.zx.y,m.zx.z)}p.updateFloat3("vReflectionMicrosurfaceInfos",d.getSize().width,d.lodGenerationScale,d.lodGenerationOffset)}this._emissiveTexture&&xu.EmissiveTextureEnabled&&(p.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),ia(this._emissiveTexture,p,"emissive")),this._lightmapTexture&&xu.LightmapTextureEnabled&&(p.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),ia(this._lightmapTexture,p,"lightmap")),xu.SpecularTextureEnabled&&(this._metallicTexture?(p.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),ia(this._metallicTexture,p,"reflectivity")):this._reflectivityTexture&&(p.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),ia(this._reflectivityTexture,p,"reflectivity")),this._metallicReflectanceTexture&&(p.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),ia(this._metallicReflectanceTexture,p,"metallicReflectance")),this._reflectanceTexture&&l.REFLECTANCE&&(p.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),ia(this._reflectanceTexture,p,"reflectance")),this._microSurfaceTexture&&(p.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),ia(this._microSurfaceTexture,p,"microSurfaceSampler"))),this._bumpTexture&&u.getCaps().standardDerivatives&&xu.BumpTextureEnabled&&!this._disableBumpMap&&(p.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),ia(this._bumpTexture,p,"bump"),s._mirroredCameraPosition?p.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):p.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&p.updateFloat("pointSize",this.pointSize),l.METALLICWORKFLOW){$.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,$.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,p.updateColor4("vReflectivityColor",$.Color3[0],1);var v=null!==(n=null===(r=this.subSurface)||void 0===r?void 0:r._indexOfRefraction)&&void 0!==n?n:1.5,y=Math.pow((v-1)/(v+1),2);this._metallicReflectanceColor.scaleToRef(y*this._metallicF0Factor,$.Color3[0]);var b=this._metallicF0Factor;p.updateColor4("vMetallicReflectanceFactors",$.Color3[0],b)}else p.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);p.updateColor3("vEmissiveColor",xu.EmissiveTextureEnabled?this._emissiveColor:Z.BlackReadOnly),p.updateColor3("vReflectionColor",this._reflectionColor),!l.SS_REFRACTION&&(null===(o=this.subSurface)||void 0===o?void 0:o._linkRefractionWithTransparency)?p.updateColor4("vAlbedoColor",this._albedoColor,1):p.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*s.environmentIntensity,this._lightingInfos.w=this._specularIntensity,p.updateVector4("vLightingIntensity",this._lightingInfos),s.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),p.updateColor3("vAmbientColor",this._globalAmbientColor),p.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}s.texturesEnabled&&(this._albedoTexture&&xu.DiffuseTextureEnabled&&p.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&xu.AmbientTextureEnabled&&p.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&xu.OpacityTextureEnabled&&p.setTexture("opacitySampler",this._opacityTexture),d&&xu.ReflectionTextureEnabled&&(l.LODBASEDMICROSFURACE?p.setTexture("reflectionSampler",d):(p.setTexture("reflectionSampler",d._lodTextureMid||d),p.setTexture("reflectionSamplerLow",d._lodTextureLow||d),p.setTexture("reflectionSamplerHigh",d._lodTextureHigh||d)),l.USEIRRADIANCEMAP&&p.setTexture("irradianceSampler",d.irradianceTexture)),l.ENVIRONMENTBRDF&&p.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&xu.EmissiveTextureEnabled&&p.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&xu.LightmapTextureEnabled&&p.setTexture("lightmapSampler",this._lightmapTexture),xu.SpecularTextureEnabled&&(this._metallicTexture?p.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&p.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&p.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&l.REFLECTANCE&&p.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&p.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&u.getCaps().standardDerivatives&&xu.BumpTextureEnabled&&!this._disableBumpMap&&p.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(c),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),Ho(this._activeEffect,this,s),this.bindEyePosition(c)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!h&&this.isFrozen||(s.lightsEnabled&&!this._disableLighting&&sa(s,t,this._activeEffect,l,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==pn.FOGMODE_NONE||d||this.subSurface.refractionTexture||t.receiveShadows||l.PREPASS)&&this.bindView(c),Qo(s,t,this._activeEffect,!0),l.NUM_MORPH_INFLUENCERS&&$o(t,this._activeEffect),l.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(a=t.bakedVertexAnimationManager)||void 0===a||a.bind(c,l.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),Ko(l,this._activeEffect,s)),this._afterBind(t,this._activeEffect,i),p.update()}}},t.prototype.getAnimatables=function(){var t=e.prototype.getAnimatables.call(this);return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&t.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&t.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&t.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&t.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&t.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?t.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&t.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&t.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&t.push(this._lightmapTexture),this._metallicReflectanceTexture&&this._metallicReflectanceTexture.animations&&this._metallicReflectanceTexture.animations.length>0&&t.push(this._metallicReflectanceTexture),this._reflectanceTexture&&this._reflectanceTexture.animations&&this._reflectanceTexture.animations.length>0&&t.push(this._reflectanceTexture),this._microSurfaceTexture&&this._microSurfaceTexture.animations&&this._microSurfaceTexture.animations.length>0&&t.push(this._microSurfaceTexture),t},t.prototype._getReflectionTexture=function(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);return this._albedoTexture&&t.push(this._albedoTexture),this._ambientTexture&&t.push(this._ambientTexture),this._opacityTexture&&t.push(this._opacityTexture),this._reflectionTexture&&t.push(this._reflectionTexture),this._emissiveTexture&&t.push(this._emissiveTexture),this._reflectivityTexture&&t.push(this._reflectivityTexture),this._metallicTexture&&t.push(this._metallicTexture),this._metallicReflectanceTexture&&t.push(this._metallicReflectanceTexture),this._reflectanceTexture&&t.push(this._reflectanceTexture),this._microSurfaceTexture&&t.push(this._microSurfaceTexture),this._bumpTexture&&t.push(this._bumpTexture),this._lightmapTexture&&t.push(this._lightmapTexture),t},t.prototype.hasTexture=function(t){return!!e.prototype.hasTexture.call(this,t)||this._albedoTexture===t||this._ambientTexture===t||this._opacityTexture===t||this._reflectionTexture===t||this._emissiveTexture===t||this._reflectivityTexture===t||this._metallicTexture===t||this._metallicReflectanceTexture===t||this._reflectanceTexture===t||this._microSurfaceTexture===t||this._bumpTexture===t||this._lightmapTexture===t},t.prototype.setPrePassRenderer=function(){var e;if(!(null===(e=this.subSurface)||void 0===e?void 0:e.isScatteringEnabled))return!1;var t=this.getScene().enableSubSurfaceForPrePass();return t&&(t.enabled=!0),!0},t.prototype.dispose=function(t,i){var r,n,o,a,s,l,c,u,h,d,p,f;i&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),null===(r=this._albedoTexture)||void 0===r||r.dispose(),null===(n=this._ambientTexture)||void 0===n||n.dispose(),null===(o=this._opacityTexture)||void 0===o||o.dispose(),null===(a=this._reflectionTexture)||void 0===a||a.dispose(),null===(s=this._emissiveTexture)||void 0===s||s.dispose(),null===(l=this._metallicTexture)||void 0===l||l.dispose(),null===(c=this._reflectivityTexture)||void 0===c||c.dispose(),null===(u=this._bumpTexture)||void 0===u||u.dispose(),null===(h=this._lightmapTexture)||void 0===h||h.dispose(),null===(d=this._metallicReflectanceTexture)||void 0===d||d.dispose(),null===(p=this._reflectanceTexture)||void 0===p||p.dispose(),null===(f=this._microSurfaceTexture)||void 0===f||f.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e.prototype.dispose.call(this,t,i)},t.PBRMATERIAL_OPAQUE=Ca.MATERIAL_OPAQUE,t.PBRMATERIAL_ALPHATEST=Ca.MATERIAL_ALPHATEST,t.PBRMATERIAL_ALPHABLEND=Ca.MATERIAL_ALPHABLEND,t.PBRMATERIAL_ALPHATESTANDBLEND=Ca.MATERIAL_ALPHATESTANDBLEND,t.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,t.LIGHTFALLOFF_PHYSICAL=0,t.LIGHTFALLOFF_GLTF=1,t.LIGHTFALLOFF_STANDARD=2,v([Ue()],t.prototype,"_imageProcessingConfiguration",void 0),v([Pe("_markAllSubMeshesAsMiscDirty")],t.prototype,"debugMode",void 0),t}(ws),rg=function(e){function t(i,r){var n=e.call(this,i,r)||this;return n.directIntensity=1,n.emissiveIntensity=1,n.environmentIntensity=1,n.specularIntensity=1,n.disableBumpMap=!1,n.ambientTextureStrength=1,n.ambientTextureImpactOnAnalyticalLights=t.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,n.metallicF0Factor=1,n.metallicReflectanceColor=Z.White(),n.useOnlyMetallicFromMetallicReflectanceTexture=!1,n.ambientColor=new Z(0,0,0),n.albedoColor=new Z(1,1,1),n.reflectivityColor=new Z(1,1,1),n.reflectionColor=new Z(1,1,1),n.emissiveColor=new Z(0,0,0),n.microSurface=1,n.useLightmapAsShadowmap=!1,n.useAlphaFromAlbedoTexture=!1,n.forceAlphaTest=!1,n.alphaCutOff=.4,n.useSpecularOverAlpha=!0,n.useMicroSurfaceFromReflectivityMapAlpha=!1,n.useRoughnessFromMetallicTextureAlpha=!0,n.useRoughnessFromMetallicTextureGreen=!1,n.useMetallnessFromMetallicTextureBlue=!1,n.useAmbientOcclusionFromMetallicTextureRed=!1,n.useAmbientInGrayScale=!1,n.useAutoMicroSurfaceFromReflectivityMap=!1,n.useRadianceOverAlpha=!0,n.useObjectSpaceNormalMap=!1,n.useParallax=!1,n.useParallaxOcclusion=!1,n.parallaxScaleBias=.05,n.disableLighting=!1,n.forceIrradianceInFragment=!1,n.maxSimultaneousLights=4,n.invertNormalMapX=!1,n.invertNormalMapY=!1,n.twoSidedLighting=!1,n.useAlphaFresnel=!1,n.useLinearAlphaFresnel=!1,n.environmentBRDFTexture=null,n.forceNormalForward=!1,n.enableSpecularAntiAliasing=!1,n.useHorizonOcclusion=!0,n.useRadianceOcclusion=!0,n.unlit=!1,n.applyDecalMapAfterDetailMap=!1,n._environmentBRDFTexture=km(n.getScene()),n}return m(t,e),Object.defineProperty(t.prototype,"refractionTexture",{get:function(){return this.subSurface.refractionTexture},set:function(e){this.subSurface.refractionTexture=e,e?this.subSurface.isRefractionEnabled=!0:this.subSurface.linkRefractionWithTransparency||(this.subSurface.isRefractionEnabled=!1)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"indexOfRefraction",{get:function(){return this.subSurface.indexOfRefraction},set:function(e){this.subSurface.indexOfRefraction=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"invertRefractionY",{get:function(){return this.subSurface.invertRefractionY},set:function(e){this.subSurface.invertRefractionY=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"linkRefractionWithTransparency",{get:function(){return this.subSurface.linkRefractionWithTransparency},set:function(e){this.subSurface.linkRefractionWithTransparency=e,e&&(this.subSurface.isRefractionEnabled=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"usePhysicalLightFalloff",{get:function(){return this._lightFalloff===ig.LIGHTFALLOFF_PHYSICAL},set:function(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?ig.LIGHTFALLOFF_PHYSICAL:ig.LIGHTFALLOFF_STANDARD)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"useGLTFLightFalloff",{get:function(){return this._lightFalloff===ig.LIGHTFALLOFF_GLTF},set:function(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?ig.LIGHTFALLOFF_GLTF:ig.LIGHTFALLOFF_STANDARD)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this._imageProcessingConfiguration.colorGradingTexture=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorCurves",{get:function(){return this._imageProcessingConfiguration.colorCurves},set:function(e){this._imageProcessingConfiguration.colorCurves=e},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"PBRMaterial"},t.prototype.clone=function(e,i,r){var n=this;void 0===i&&(i=!0),void 0===r&&(r="");var o=Ke.Clone((function(){return new t(e,n.getScene())}),this,{cloneTexturesOnlyOnce:i});return o.id=e,o.name=e,this.stencil.copyTo(o.stencil),this._clonePlugins(o,r),o},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.customType="BABYLON.PBRMaterial",t},t.Parse=function(e,i,r){var n=Ke.Parse((function(){return new t(e.name,i)}),e,i,r);return e.stencil&&n.stencil.parse(e.stencil,i,r),Ca._ParsePlugins(e,n,i,r),e.clearCoat&&n.clearCoat.parse(e.clearCoat,i,r),e.anisotropy&&n.anisotropy.parse(e.anisotropy,i,r),e.brdf&&n.brdf.parse(e.brdf,i,r),e.sheen&&n.sheen.parse(e.sheen,i,r),e.subSurface&&n.subSurface.parse(e.subSurface,i,r),e.iridescence&&n.iridescence.parse(e.iridescence,i,r),n},t.PBRMATERIAL_OPAQUE=ig.PBRMATERIAL_OPAQUE,t.PBRMATERIAL_ALPHATEST=ig.PBRMATERIAL_ALPHATEST,t.PBRMATERIAL_ALPHABLEND=ig.PBRMATERIAL_ALPHABLEND,t.PBRMATERIAL_ALPHATESTANDBLEND=ig.PBRMATERIAL_ALPHATESTANDBLEND,t.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=ig.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"directIntensity",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"emissiveIntensity",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"environmentIntensity",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"specularIntensity",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"disableBumpMap",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"albedoTexture",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"ambientTexture",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"ambientTextureStrength",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"opacityTexture",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionTexture",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"emissiveTexture",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectivityTexture",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"metallicTexture",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"metallic",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"roughness",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"metallicF0Factor",void 0),v([Oe(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"metallicReflectanceColor",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"metallicReflectanceTexture",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectanceTexture",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"microSurfaceTexture",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"bumpTexture",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty",null)],t.prototype,"lightmapTexture",void 0),v([Oe("ambient"),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"ambientColor",void 0),v([Oe("albedo"),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"albedoColor",void 0),v([Oe("reflectivity"),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectivityColor",void 0),v([Oe("reflection"),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionColor",void 0),v([Oe("emissive"),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"emissiveColor",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"microSurface",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useLightmapAsShadowmap",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"useAlphaFromAlbedoTexture",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"forceAlphaTest",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"alphaCutOff",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useSpecularOverAlpha",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRoughnessFromMetallicTextureGreen",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useMetallnessFromMetallicTextureBlue",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useAmbientInGrayScale",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),v([Ie()],t.prototype,"usePhysicalLightFalloff",null),v([Ie()],t.prototype,"useGLTFLightFalloff",null),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRadianceOverAlpha",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useObjectSpaceNormalMap",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useParallax",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useParallaxOcclusion",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"parallaxScaleBias",void 0),v([Ie(),Pe("_markAllSubMeshesAsLightsDirty")],t.prototype,"disableLighting",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"forceIrradianceInFragment",void 0),v([Ie(),Pe("_markAllSubMeshesAsLightsDirty")],t.prototype,"maxSimultaneousLights",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"invertNormalMapX",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"invertNormalMapY",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"twoSidedLighting",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useAlphaFresnel",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useLinearAlphaFresnel",void 0),v([Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"environmentBRDFTexture",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"forceNormalForward",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"enableSpecularAntiAliasing",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useHorizonOcclusion",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRadianceOcclusion",void 0),v([Ie(),Pe("_markAllSubMeshesAsMiscDirty")],t.prototype,"unlit",void 0),v([Ie(),Pe("_markAllSubMeshesAsMiscDirty")],t.prototype,"applyDecalMapAfterDetailMap",void 0),t}(ig);a("BABYLON.PBRMaterial",rg);var ng=131072,og=131072;function ag(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}var sg=ag("DXT1"),lg=ag("DXT3"),cg=ag("DXT5"),ug=ag("DX10"),hg=function(){function e(){}return e.GetDDSInfo=function(e){var t=new Int32Array(e.buffer,e.byteOffset,31),i=new Int32Array(e.buffer,e.byteOffset,35),r=1;t[2]&ng&&(r=Math.max(1,t[7]));var n=t[21],o=n===ug?i[32]:0,a=u.TEXTURETYPE_UNSIGNED_INT;switch(n){case 113:a=u.TEXTURETYPE_HALF_FLOAT;break;case 116:a=u.TEXTURETYPE_FLOAT;break;case ug:if(10===o){a=u.TEXTURETYPE_HALF_FLOAT;break}if(2===o){a=u.TEXTURETYPE_FLOAT;break}}return{width:t[4],height:t[3],mipmapCount:r,isFourCC:!(4&~t[20]),isRGB:!(64&~t[20]),isLuminance:(t[20]&og)===og,isCube:!(512&~t[28]),isCompressed:n===sg||n===lg||n===cg,dxgiFormat:o,textureType:a}},e._GetHalfFloatAsFloatRGBAArrayBuffer=function(t,i,r,n,o,a){for(var s=new Float32Array(n),l=new Uint16Array(o,r),c=0,u=0;u<i;u++)for(var h=0;h<t;h++){var d=4*(h+u*t);s[c]=Ip(l[d]),s[c+1]=Ip(l[d+1]),s[c+2]=Ip(l[d+2]),e.StoreLODInAlphaChannel?s[c+3]=a:s[c+3]=Ip(l[d+3]),c+=4}return s},e._GetHalfFloatRGBAArrayBuffer=function(t,i,r,n,o,a){if(e.StoreLODInAlphaChannel){for(var s=new Uint16Array(n),l=new Uint16Array(o,r),c=0,u=0;u<i;u++)for(var h=0;h<t;h++){var d=4*(h+u*t);s[c]=l[d],s[c+1]=l[d+1],s[c+2]=l[d+2],s[c+3]=Pp(a),c+=4}return s}return new Uint16Array(o,r,n)},e._GetFloatRGBAArrayBuffer=function(t,i,r,n,o,a){if(e.StoreLODInAlphaChannel){for(var s=new Float32Array(n),l=new Float32Array(o,r),c=0,u=0;u<i;u++)for(var h=0;h<t;h++){var d=4*(h+u*t);s[c]=l[d],s[c+1]=l[d+1],s[c+2]=l[d+2],s[c+3]=a,c+=4}return s}return new Float32Array(o,r,n)},e._GetFloatAsHalfFloatRGBAArrayBuffer=function(t,i,r,n,o,a){for(var s=new Uint16Array(n),l=new Float32Array(o,r),c=0,u=0;u<i;u++)for(var h=0;h<t;h++)s[c]=Pp(l[c]),s[c+1]=Pp(l[c+1]),s[c+2]=Pp(l[c+2]),e.StoreLODInAlphaChannel?s[c+3]=Pp(a):s[c+3]=Pp(l[c+3]),c+=4;return s},e._GetFloatAsUIntRGBAArrayBuffer=function(t,i,r,n,o,a){for(var s=new Uint8Array(n),l=new Float32Array(o,r),c=0,u=0;u<i;u++)for(var h=0;h<t;h++){var d=4*(h+u*t);s[c]=255*j.Clamp(l[d]),s[c+1]=255*j.Clamp(l[d+1]),s[c+2]=255*j.Clamp(l[d+2]),e.StoreLODInAlphaChannel?s[c+3]=a:s[c+3]=255*j.Clamp(l[d+3]),c+=4}return s},e._GetHalfFloatAsUIntRGBAArrayBuffer=function(t,i,r,n,o,a){for(var s=new Uint8Array(n),l=new Uint16Array(o,r),c=0,u=0;u<i;u++)for(var h=0;h<t;h++){var d=4*(h+u*t);s[c]=255*j.Clamp(Ip(l[d])),s[c+1]=255*j.Clamp(Ip(l[d+1])),s[c+2]=255*j.Clamp(Ip(l[d+2])),e.StoreLODInAlphaChannel?s[c+3]=a:s[c+3]=255*j.Clamp(Ip(l[d+3])),c+=4}return s},e._GetRGBAArrayBuffer=function(e,t,i,r,n,o,a,s,l){for(var c=new Uint8Array(r),u=new Uint8Array(n,i),h=0,d=0;d<t;d++)for(var p=0;p<e;p++){var f=4*(p+d*e);c[h]=u[f+o],c[h+1]=u[f+a],c[h+2]=u[f+s],c[h+3]=u[f+l],h+=4}return c},e._ExtractLongWordOrder=function(t){return 0===t||255===t||-16777216===t?0:1+e._ExtractLongWordOrder(t>>8)},e._GetRGBArrayBuffer=function(e,t,i,r,n,o,a,s){for(var l=new Uint8Array(r),c=new Uint8Array(n,i),u=0,h=0;h<t;h++)for(var d=0;d<e;d++){var p=3*(d+h*e);l[u]=c[p+o],l[u+1]=c[p+a],l[u+2]=c[p+s],u+=3}return l},e._GetLuminanceArrayBuffer=function(e,t,i,r,n){for(var o=new Uint8Array(r),a=new Uint8Array(n,i),s=0,l=0;l<t;l++)for(var c=0;c<e;c++){var u=c+l*e;o[s]=a[u],s++}return o},e.UploadDDSLevels=function(t,i,r,n,o,a,s,l,c){void 0===s&&(s=-1),void 0===c&&(c=!0);var h=null;n.sphericalPolynomial&&(h=[]);var d=!!t.getCaps().s3tc;i.generateMipMaps=o;var p,f,_,m,g,v,y,b=new Int32Array(r.buffer,r.byteOffset,31),T=0,E=0,S=1;if(542327876===b[0])if(n.isFourCC||n.isRGB||n.isLuminance)if(!n.isCompressed||d){var x=b[22];m=b[1]+4;var A,C=!1;if(n.isFourCC)switch(p=b[21]){case sg:S=8,E=u.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1;break;case lg:S=16,E=u.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3;break;case cg:S=16,E=u.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5;break;case 113:C=!0,x=64;break;case 116:C=!0,x=128;break;case ug:m+=20;var R=!1;switch(n.dxgiFormat){case 10:C=!0,x=64,R=!0;break;case 2:C=!0,x=128,R=!0;break;case 88:n.isRGB=!0,n.isFourCC=!1,x=32,R=!0}if(R)break;default:return void ae.Error(["Unsupported FourCC code:",(A=p,String.fromCharCode(255&A,A>>8&255,A>>16&255,A>>24&255))])}var P=e._ExtractLongWordOrder(b[23]),I=e._ExtractLongWordOrder(b[24]),M=e._ExtractLongWordOrder(b[25]),O=e._ExtractLongWordOrder(b[26]);C&&(E=t._getRGBABufferInternalSizedFormat(n.textureType)),v=1,b[2]&ng&&!1!==o&&(v=Math.max(1,b[7]));for(var D=l||0,N=t.getCaps(),F=D;F<a;F++){for(f=b[4],_=b[3],y=0;y<v;++y){if(-1===s||s===y){var L=-1===s?y:0;if(!n.isCompressed&&n.isFourCC){i.format=u.TEXTUREFORMAT_RGBA,T=f*_*4;var w=null;if(t._badOS||t._badDesktopOS||!N.textureHalfFloat&&!N.textureFloat)128===x?(w=e._GetFloatAsUIntRGBAArrayBuffer(f,_,r.byteOffset+m,T,r.buffer,L),h&&0==L&&h.push(e._GetFloatRGBAArrayBuffer(f,_,r.byteOffset+m,T,r.buffer,L))):64===x&&(w=e._GetHalfFloatAsUIntRGBAArrayBuffer(f,_,r.byteOffset+m,T,r.buffer,L),h&&0==L&&h.push(e._GetHalfFloatAsFloatRGBAArrayBuffer(f,_,r.byteOffset+m,T,r.buffer,L))),i.type=u.TEXTURETYPE_UNSIGNED_INT;else{var B=N.textureFloat&&(c&&N.textureFloatLinearFiltering||!c),U=N.textureHalfFloat&&(c&&N.textureHalfFloatLinearFiltering||!c),V=(128===x||64===x&&!U)&&B?u.TEXTURETYPE_FLOAT:(64===x||128===x&&!B)&&U?u.TEXTURETYPE_HALF_FLOAT:u.TEXTURETYPE_UNSIGNED_BYTE,k=void 0,G=null;if(128===x)switch(V){case u.TEXTURETYPE_FLOAT:k=e._GetFloatRGBAArrayBuffer,G=null;break;case u.TEXTURETYPE_HALF_FLOAT:k=e._GetFloatAsHalfFloatRGBAArrayBuffer,G=e._GetFloatRGBAArrayBuffer;break;case u.TEXTURETYPE_UNSIGNED_BYTE:k=e._GetFloatAsUIntRGBAArrayBuffer,G=e._GetFloatRGBAArrayBuffer}else switch(V){case u.TEXTURETYPE_FLOAT:k=e._GetHalfFloatAsFloatRGBAArrayBuffer,G=null;break;case u.TEXTURETYPE_HALF_FLOAT:k=e._GetHalfFloatRGBAArrayBuffer,G=e._GetHalfFloatAsFloatRGBAArrayBuffer;break;case u.TEXTURETYPE_UNSIGNED_BYTE:k=e._GetHalfFloatAsUIntRGBAArrayBuffer,G=e._GetHalfFloatAsFloatRGBAArrayBuffer}i.type=V,w=k(f,_,r.byteOffset+m,T,r.buffer,L),h&&0==L&&h.push(G?G(f,_,r.byteOffset+m,T,r.buffer,L):w)}w&&t._uploadDataToTextureDirectly(i,w,F,L)}else if(n.isRGB)i.type=u.TEXTURETYPE_UNSIGNED_INT,24===x?(i.format=u.TEXTUREFORMAT_RGB,T=f*_*3,g=e._GetRGBArrayBuffer(f,_,r.byteOffset+m,T,r.buffer,P,I,M),t._uploadDataToTextureDirectly(i,g,F,L)):(i.format=u.TEXTUREFORMAT_RGBA,T=f*_*4,g=e._GetRGBAArrayBuffer(f,_,r.byteOffset+m,T,r.buffer,P,I,M,O),t._uploadDataToTextureDirectly(i,g,F,L));else if(n.isLuminance){var z=t._getUnpackAlignement(),W=f;T=Math.floor((f+z-1)/z)*z*(_-1)+W,g=e._GetLuminanceArrayBuffer(f,_,r.byteOffset+m,T,r.buffer),i.format=u.TEXTUREFORMAT_LUMINANCE,i.type=u.TEXTURETYPE_UNSIGNED_INT,t._uploadDataToTextureDirectly(i,g,F,L)}else T=Math.max(4,f)/4*Math.max(4,_)/4*S,g=new Uint8Array(r.buffer,r.byteOffset+m,T),i.type=u.TEXTURETYPE_UNSIGNED_INT,t._uploadCompressedDataToTextureDirectly(i,E,f,_,g,F,L)}m+=x?f*_*(x/8):T,f*=.5,_*=.5,f=Math.max(1,f),_=Math.max(1,_)}if(void 0!==l)break}h&&h.length>0?n.sphericalPolynomial=Lp.ConvertCubeMapToSphericalPolynomial({size:b[4],right:h[0],left:h[1],up:h[2],down:h[3],front:h[4],back:h[5],format:u.TEXTUREFORMAT_RGBA,type:u.TEXTURETYPE_FLOAT,gammaSpace:!1}):n.sphericalPolynomial=void 0}else ae.Error("Compressed textures are not supported on this platform.");else ae.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");else ae.Error("Invalid magic number in DDS header")},e.StoreLODInAlphaChannel=!1,e}();Er.prototype.createPrefilteredCubeTexture=function(e,t,i,r,n,o,a,s,l){var c=this;return void 0===n&&(n=null),void 0===o&&(o=null),void 0===s&&(s=null),void 0===l&&(l=!0),this.createCubeTexture(e,t,null,!1,(function(e){if(e){var o=e.texture;if(l?e.info.sphericalPolynomial&&(o._sphericalPolynomial=e.info.sphericalPolynomial):o._sphericalPolynomial=new Sp,o._source=Ti.CubePrefiltered,c.getCaps().textureLOD)n&&n(o);else{var a=c._gl,s=e.width;if(s){for(var h=[],d=0;d<3;d++){var p=1-d/2,f=r,_=j.Log2(s)*i+r,m=f+(_-f)*p,g=Math.round(Math.min(Math.max(m,0),_)),v=new Pi(c,Ti.Temp);if(v.type=o.type,v.format=o.format,v.width=Math.pow(2,Math.max(j.Log2(s)-g,0)),v.height=v.width,v.isCube=!0,v._cachedWrapU=u.TEXTURE_CLAMP_ADDRESSMODE,v._cachedWrapV=u.TEXTURE_CLAMP_ADDRESSMODE,c._bindTextureDirectly(a.TEXTURE_CUBE_MAP,v,!0),v.samplingMode=u.TEXTURE_LINEAR_LINEAR,a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),e.isDDS){var y=e.info,b=e.data;c._unpackFlipY(y.isCompressed),hg.UploadDDSLevels(c,v,b,y,!0,6,g)}else ae.Warn("DDS is the only prefiltered cube map supported so far.");c._bindTextureDirectly(a.TEXTURE_CUBE_MAP,null);var T=new Ya(t);T._isCube=!0,T._texture=v,v.isReady=!0,h.push(T)}o._lodTextureHigh=h[2],o._lodTextureMid=h[1],o._lodTextureLow=h[0],n&&n(o)}}}else n&&n(null)}),o,a,s,l,i,r)};var dg=function(){function e(){this.supportCascades=!0}return e.prototype.canLoad=function(e){return e.endsWith(".dds")},e.prototype.loadCubeData=function(e,t,i,r){var n,o=t.getEngine(),a=!1,s=1e3;if(Array.isArray(e))for(var l=0;l<e.length;l++){var c=e[l];n=hg.GetDDSInfo(c),t.width=n.width,t.height=n.height,a=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps,o._unpackFlipY(n.isCompressed),hg.UploadDDSLevels(o,t,c,n,a,6,-1,l),n.isFourCC||1!==n.mipmapCount?s=n.mipmapCount-1:o.generateMipMapsForCubemap(t)}else c=e,n=hg.GetDDSInfo(c),t.width=n.width,t.height=n.height,i&&(n.sphericalPolynomial=new Sp),a=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps,o._unpackFlipY(n.isCompressed),hg.UploadDDSLevels(o,t,c,n,a,6),n.isFourCC||1!==n.mipmapCount?s=n.mipmapCount-1:o.generateMipMapsForCubemap(t,!1);o._setCubeMapTextureParams(t,a,s),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r({isDDS:!0,width:t.width,info:n,data:e,texture:t})},e.prototype.loadData=function(e,t,i){var r=hg.GetDDSInfo(e),n=(r.isRGB||r.isLuminance||r.mipmapCount>1)&&t.generateMipMaps&&r.width>>r.mipmapCount-1==1;i(r.width,r.height,n,r.isFourCC,(function(){hg.UploadDDSLevels(t.getEngine(),t,e,r,n,1)}))},e}();Do._TextureLoaders.push(new dg);var pg=function(){function e(){this.supportCascades=!1}return e.prototype.canLoad=function(e){return e.endsWith(".env")},e.prototype.loadCubeData=function(e,t,i,r,n){if(!Array.isArray(e)){var o=Vp(e);if(o){t.width=o.width,t.height=o.width;try{Yp(t,o),Hp(t,e,o).then((function(){t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}),(function(e){null==n||n("Can not upload environment levels",e)}))}catch(e){null==n||n("Can not upload environment file",e)}}else n&&n("Can not parse the environment file",null)}},e.prototype.loadData=function(){throw".env not supported in 2d."},e}();Do._TextureLoaders.push(new pg);var fg,_g,mg,gg=function(){function e(t,i){if(this.data=t,this.isInvalid=!1,!e.IsValid(t))return this.isInvalid=!0,void ae.Error("texture missing KTX identifier");var r=Uint32Array.BYTES_PER_ELEMENT,n=new DataView(this.data.buffer,this.data.byteOffset+12,13*r),o=67305985===n.getUint32(0,!0);return this.glType=n.getUint32(1*r,o),this.glTypeSize=n.getUint32(2*r,o),this.glFormat=n.getUint32(3*r,o),this.glInternalFormat=n.getUint32(4*r,o),this.glBaseInternalFormat=n.getUint32(5*r,o),this.pixelWidth=n.getUint32(6*r,o),this.pixelHeight=n.getUint32(7*r,o),this.pixelDepth=n.getUint32(8*r,o),this.numberOfArrayElements=n.getUint32(9*r,o),this.numberOfFaces=n.getUint32(10*r,o),this.numberOfMipmapLevels=n.getUint32(11*r,o),this.bytesOfKeyValueData=n.getUint32(12*r,o),0!==this.glType?(ae.Error("only compressed formats currently supported"),void(this.isInvalid=!0)):(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth?(ae.Error("only 2D textures currently supported"),void(this.isInvalid=!0)):0!==this.numberOfArrayElements?(ae.Error("texture arrays not currently supported"),void(this.isInvalid=!0)):this.numberOfFaces!==i?(ae.Error("number of faces expected"+i+", but found "+this.numberOfFaces),void(this.isInvalid=!0)):void(this.loadType=e.COMPRESSED_2D))}return e.prototype.uploadLevels=function(t,i){switch(this.loadType){case e.COMPRESSED_2D:this._upload2DCompressedLevels(t,i);case e.TEX_2D:case e.COMPRESSED_3D:case e.TEX_3D:}},e.prototype._upload2DCompressedLevels=function(t,i){for(var r=e.HEADER_LEN+this.bytesOfKeyValueData,n=this.pixelWidth,o=this.pixelHeight,a=i?this.numberOfMipmapLevels:1,s=0;s<a;s++){var l=new Int32Array(this.data.buffer,this.data.byteOffset+r,1)[0];r+=4;for(var c=0;c<this.numberOfFaces;c++){var u=new Uint8Array(this.data.buffer,this.data.byteOffset+r,l);t.getEngine()._uploadCompressedDataToTextureDirectly(t,t.format,n,o,u,c,s),r+=l,r+=3-(l+3)%4}n=Math.max(1,.5*n),o=Math.max(1,.5*o)}},e.IsValid=function(e){if(e.byteLength>=12){var t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&49===t[5]&&49===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1},e.HEADER_LEN=64,e.COMPRESSED_2D=0,e.COMPRESSED_3D=1,e.TEX_2D=2,e.TEX_3D=3,e}(),vg=function(){function e(e){this._pendingActions=new Array,this._workerInfos=e.map((function(e){return{workerPromise:Promise.resolve(e),idle:!0}}))}return e.prototype.dispose=function(){for(var e=0,t=this._workerInfos;e<t.length;e++)t[e].workerPromise.then((function(e){e.terminate()}));this._workerInfos.length=0,this._pendingActions.length=0},e.prototype.push=function(e){this._executeOnIdleWorker(e)||this._pendingActions.push(e)},e.prototype._executeOnIdleWorker=function(e){for(var t=0,i=this._workerInfos;t<i.length;t++){var r=i[t];if(r.idle)return this._execute(r,e),!0}return!1},e.prototype._execute=function(e,t){var i=this;e.idle=!1,e.workerPromise.then((function(r){t(r,(function(){var t=i._pendingActions.shift();t?i._execute(e,t):e.idle=!0}))}))},e}(),yg=function(e){function t(i,r,n){void 0===n&&(n=t.DefaultOptions);var o=e.call(this,[])||this;return o._maxWorkers=i,o._createWorkerAsync=r,o._options=n,o}return m(t,e),t.prototype.push=function(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length<this._maxWorkers){var t={workerPromise:this._createWorkerAsync(),idle:!1};this._workerInfos.push(t),this._execute(t,e)}else this._pendingActions.push(e)},t.prototype._execute=function(t,i){var r=this;t.timeoutId&&(clearTimeout(t.timeoutId),delete t.timeoutId),e.prototype._execute.call(this,t,(function(e,n){i(e,(function(){n(),t.idle&&(t.timeoutId=setTimeout((function(){t.workerPromise.then((function(e){e.terminate()}));var e=r._workerInfos.indexOf(t);-1!==e&&r._workerInfos.splice(e,1)}),r._options.idleTimeElapsedBeforeRelease))}))}))},t.DefaultOptions={idleTimeElapsedBeforeRelease:1e3},t}(vg);function bg(e,t){var i=(null==t?void 0:t.jsDecoderModule)||KTX2DECODER;e&&(e.wasmUASTCToASTC&&(i.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),e.wasmUASTCToBC7&&(i.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM&&(i.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB&&(i.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),e.wasmUASTCToR8_UNORM&&(i.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=e.wasmUASTCToR8_UNORM),e.wasmUASTCToRG8_UNORM&&(i.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=e.wasmUASTCToRG8_UNORM),e.jsMSCTranscoder&&(i.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),e.wasmMSCTranscoder&&(i.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),e.wasmZSTDDecoder&&(i.ZSTDDecoder.WasmModuleURL=e.wasmZSTDDecoder)),t&&(t.wasmUASTCToASTC&&(i.LiteTranscoder_UASTC_ASTC.WasmBinary=t.wasmUASTCToASTC),t.wasmUASTCToBC7&&(i.LiteTranscoder_UASTC_BC7.WasmBinary=t.wasmUASTCToBC7),t.wasmUASTCToRGBA_UNORM&&(i.LiteTranscoder_UASTC_RGBA_UNORM.WasmBinary=t.wasmUASTCToRGBA_UNORM),t.wasmUASTCToRGBA_SRGB&&(i.LiteTranscoder_UASTC_RGBA_SRGB.WasmBinary=t.wasmUASTCToRGBA_SRGB),t.wasmUASTCToR8_UNORM&&(i.LiteTranscoder_UASTC_R8_UNORM.WasmBinary=t.wasmUASTCToR8_UNORM),t.wasmUASTCToRG8_UNORM&&(i.LiteTranscoder_UASTC_RG8_UNORM.WasmBinary=t.wasmUASTCToRG8_UNORM),t.jsMSCTranscoder&&(i.MSCTranscoder.JSModule=t.jsMSCTranscoder),t.wasmMSCTranscoder&&(i.MSCTranscoder.WasmBinary=t.wasmMSCTranscoder),t.wasmZSTDDecoder&&(i.ZSTDDecoder.WasmBinary=t.wasmZSTDDecoder))}function Tg(e){var t;void 0===e&&"undefined"!=typeof KTX2DECODER&&(e=KTX2DECODER),onmessage=function(i){if(i.data)switch(i.data.action){case"init":var r=i.data.urls;r&&(r.jsDecoderModule&&void 0===e&&(importScripts(r.jsDecoderModule),e=KTX2DECODER),bg(r)),i.data.wasmBinaries&&bg(void 0,g(g({},i.data.wasmBinaries),{jsDecoderModule:e})),t=new e.KTX2Decoder,postMessage({action:"init"});break;case"setDefaultDecoderOptions":e.KTX2Decoder.DefaultDecoderOptions=i.data.options;break;case"decode":t.decode(i.data.data,i.data.caps,i.data.options).then((function(e){for(var t=[],i=0;i<e.mipmaps.length;++i){var r=e.mipmaps[i];r&&r.data&&t.push(r.data.buffer)}postMessage({action:"decoded",success:!0,decodedData:e},t)})).catch((function(e){postMessage({action:"decoded",success:!1,msg:e})}))}}}!function(e){e[e.ETC1S=0]="ETC1S",e[e.UASTC4x4=1]="UASTC4x4"}(fg||(fg={})),function(e){e[e.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",e[e.BC7_RGBA=1]="BC7_RGBA",e[e.BC3_RGBA=2]="BC3_RGBA",e[e.BC1_RGB=3]="BC1_RGB",e[e.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",e[e.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",e[e.ETC2_RGBA=6]="ETC2_RGBA",e[e.ETC1_RGB=7]="ETC1_RGB",e[e.RGBA32=8]="RGBA32",e[e.R8=9]="R8",e[e.RG8=10]="RG8"}(_g||(_g={})),function(e){e[e.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",e[e.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",e[e.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",e[e.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",e[e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",e[e.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",e[e.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",e[e.RGBA8Format=32856]="RGBA8Format",e[e.R8Format=33321]="R8Format",e[e.RG8Format=33323]="RG8Format"}(mg||(mg={}));var Eg=function(){function e(){this._isDirty=!0,this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=!0,this._ktx2DecoderOptions={}}return Object.defineProperty(e.prototype,"isDirty",{get:function(){return this._isDirty},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useRGBAIfASTCBC7NotAvailableWhenUASTC",{get:function(){return this._useRGBAIfASTCBC7NotAvailableWhenUASTC},set:function(e){this._useRGBAIfASTCBC7NotAvailableWhenUASTC!==e&&(this._useRGBAIfASTCBC7NotAvailableWhenUASTC=e,this._isDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useRGBAIfOnlyBC1BC3AvailableWhenUASTC",{get:function(){return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC},set:function(e){this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC!==e&&(this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=e,this._isDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"forceRGBA",{get:function(){return this._forceRGBA},set:function(e){this._forceRGBA!==e&&(this._forceRGBA=e,this._isDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"forceR8",{get:function(){return this._forceR8},set:function(e){this._forceR8!==e&&(this._forceR8=e,this._isDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"forceRG8",{get:function(){return this._forceRG8},set:function(e){this._forceRG8!==e&&(this._forceRG8=e,this._isDirty=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"bypassTranscoders",{get:function(){return this._bypassTranscoders},set:function(e){this._bypassTranscoders!==e&&(this._bypassTranscoders=e,this._isDirty=!0)},enumerable:!1,configurable:!0}),e.prototype._getKTX2DecoderOptions=function(){if(!this._isDirty)return this._ktx2DecoderOptions;this._isDirty=!1;var e={useRGBAIfASTCBC7NotAvailableWhenUASTC:this._useRGBAIfASTCBC7NotAvailableWhenUASTC,forceRGBA:this._forceRGBA,forceR8:this._forceR8,forceRG8:this._forceRG8,bypassTranscoders:this._bypassTranscoders};return this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC&&(e.transcodeFormatDecisionTree={UASTC:{transcodeFormat:[_g.BC1_RGB,_g.BC3_RGBA],yes:{transcodeFormat:_g.RGBA32,engineFormat:mg.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e},e}(),Sg=function(){function e(t,i){var r,n;void 0===i&&(i=e.DefaultNumWorkers),this._engine=t;var o="object"==typeof i&&i.workerPool||e.WorkerPool;if(o)e._WorkerPoolPromise=Promise.resolve(o);else{"object"==typeof i?e._KTX2DecoderModule=null===(r=null==i?void 0:i.binariesAndModulesContainer)||void 0===r?void 0:r.jsDecoderModule:"undefined"!=typeof KTX2DECODER&&(e._KTX2DecoderModule=KTX2DECODER);var a="number"==typeof i?i:null!==(n=i.numWorkers)&&void 0!==n?n:e.DefaultNumWorkers;e._Initialize(a)}}return e.GetDefaultNumWorkers=function(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1},e._Initialize=function(t){if(!e._WorkerPoolPromise&&!e._DecoderModulePromise){var i={jsDecoderModule:rr.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:rr.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:rr.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:rr.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:rr.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:rr.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:rr.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:rr.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:rr.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:rr.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};t&&"function"==typeof Worker&&"undefined"!=typeof URL?e._WorkerPoolPromise=new Promise((function(e){var r="".concat(bg,"(").concat(Tg,")()"),n=URL.createObjectURL(new Blob([r],{type:"application/javascript"}));e(new yg(t,(function(){return function(e,t,i){return new Promise((function(t,r){var n=function(t){e.removeEventListener("error",n),e.removeEventListener("message",o),r(t)},o=function(i){"init"===i.data.action&&(e.removeEventListener("error",n),e.removeEventListener("message",o),t(e))};e.addEventListener("error",n),e.addEventListener("message",o),e.postMessage({action:"init",urls:i,wasmBinaries:undefined})}))}(new Worker(n),0,i)})))})):void 0===e._KTX2DecoderModule?e._DecoderModulePromise=rr.LoadBabylonScriptAsync(i.jsDecoderModule).then((function(){return e._KTX2DecoderModule=KTX2DECODER,e._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,e._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,bg(i,e._KTX2DecoderModule),new e._KTX2DecoderModule.KTX2Decoder})):(e._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,e._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,e._DecoderModulePromise=Promise.resolve(new e._KTX2DecoderModule.KTX2Decoder))}},e.prototype._uploadAsync=function(t,i,r){var n=this,o=this._engine.getCaps(),a={astc:!!o.astc,bptc:!!o.bptc,s3tc:!!o.s3tc,pvrtc:!!o.pvrtc,etc2:!!o.etc2,etc1:!!o.etc1};if(e._WorkerPoolPromise)return e._WorkerPoolPromise.then((function(o){return new Promise((function(s,l){o.push((function(o,c){var u=function(e){o.removeEventListener("error",u),o.removeEventListener("message",h),l(e),c()},h=function(e){if("decoded"===e.data.action){if(o.removeEventListener("error",u),o.removeEventListener("message",h),e.data.success)try{n._createTexture(e.data.decodedData,i,r),s()}catch(e){l({message:e})}else l({message:e.data.msg});c()}};o.addEventListener("error",u),o.addEventListener("message",h),o.postMessage({action:"setDefaultDecoderOptions",options:e.DefaultDecoderOptions._getKTX2DecoderOptions()});var d=new Uint8Array(t.byteLength);d.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),o.postMessage({action:"decode",data:d,caps:a,options:r},[d.buffer])}))}))}));if(e._DecoderModulePromise)return e._DecoderModulePromise.then((function(r){return e.DefaultDecoderOptions.isDirty&&(e._KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions=e.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise((function(e,a){r.decode(t,o).then((function(t){n._createTexture(t,i),e()})).catch((function(e){a({message:e})}))}))}));throw new Error("KTX2 decoder module is not available")},e.prototype._createTexture=function(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);var r=!0;switch(e.transcodedFormat){case 32856:t.type=u.TEXTURETYPE_UNSIGNED_BYTE,t.format=u.TEXTUREFORMAT_RGBA;break;case 33321:t.type=u.TEXTURETYPE_UNSIGNED_BYTE,t.format=u.TEXTUREFORMAT_R;break;case 33323:t.type=u.TEXTURETYPE_UNSIGNED_BYTE,t.format=u.TEXTUREFORMAT_RG;break;default:t.format=e.transcodedFormat,r=!1}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,e.errors)throw new Error("KTX2 container - could not transcode the data. "+e.errors);for(var n=0;n<e.mipmaps.length;++n){var o=e.mipmaps[n];if(!o||!o.data)throw new Error("KTX2 container - could not transcode one of the image");r?(t.width=o.width,t.height=o.height,this._engine._uploadDataToTextureDirectly(t,o.data,0,n,void 0,!0)):this._engine._uploadCompressedDataToTextureDirectly(t,e.transcodedFormat,o.width,o.height,o.data,0,n)}t._extension=".ktx2",t.width=e.mipmaps[0].width,t.height=e.mipmaps[0].height,t.isReady=!0,this._engine._bindTextureDirectly(3553,null)},e.IsValid=function(e){if(e.byteLength>=12){var t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&50===t[5]&&48===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1},e.URLConfig={jsDecoderModule:"https://cdn.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,wasmUASTCToR8_UNORM:null,wasmUASTCToRG8_UNORM:null,jsMSCTranscoder:null,wasmMSCTranscoder:null,wasmZSTDDecoder:null},e.DefaultNumWorkers=e.GetDefaultNumWorkers(),e.DefaultDecoderOptions=new Eg,e}(),xg=function(){function e(){this.supportCascades=!1}return e.prototype.canLoad=function(e,t){return e.endsWith(".ktx")||e.endsWith(".ktx2")||"image/ktx"===t||"image/ktx2"===t},e.prototype.loadCubeData=function(e,t,i,r){if(!Array.isArray(e)){t._invertVScale=!t.invertY;var n=t.getEngine(),o=new gg(e,6),a=o.numberOfMipmapLevels>1&&t.generateMipMaps;n._unpackFlipY(!0),o.uploadLevels(t,t.generateMipMaps),t.width=o.pixelWidth,t.height=o.pixelHeight,n._setCubeMapTextureParams(t,a,o.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}},e.prototype.loadData=function(e,t,i,r){if(gg.IsValid(e)){t._invertVScale=!t.invertY;var n=new gg(e,1),o=function(e){switch(e){case u.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT:return u.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1;case u.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT:return u.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3;case u.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:return u.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5;case u.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2:return u.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2;case u.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:return u.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC;case u.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:return u.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;case u.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:return u.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4;case u.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM:return u.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM}return null}(n.glInternalFormat);o?(t.format=o,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=n.glInternalFormat,i(n.pixelWidth,n.pixelHeight,t.generateMipMaps,!0,(function(){n.uploadLevels(t,t.generateMipMaps)}),n.isInvalid)}else Sg.IsValid(e)?new Sg(t.getEngine())._uploadAsync(e,t,r).then((function(){i(t.width,t.height,t.generateMipMaps,!0,(function(){}),!1)}),(function(e){ae.Warn("Failed to load KTX2 texture data: ".concat(e.message)),i(0,0,!1,!1,(function(){}),!0)})):(ae.Error("texture missing KTX identifier"),i(0,0,!1,!1,(function(){}),!0))},e}();Do._TextureLoaders.push(new xg);var Ag=function(e){function t(t,i,r){var n=e.call(this,t,V.Zero(),i)||this;return n._xrSessionManager=r,n._firstFrame=!1,n._referenceQuaternion=G.Identity(),n._referencedPosition=new V,n._trackingState=ku.NOT_TRACKING,n.onXRCameraInitializedObservable=new f,n.onBeforeCameraTeleport=new f,n.onAfterCameraTeleport=new f,n.onTrackingStateChanged=new f,n.compensateOnFirstFrame=!0,n._rotate180=new G(0,1,0,0),n.minZ=.1,n.rotationQuaternion=new G,n.cameraRigMode=$n.RIG_MODE_CUSTOM,n.updateUpVectorFromRotation=!0,n._updateNumberOfRigCameras(1),n.freezeProjectionMatrix(),n._deferOnly=!0,n._xrSessionManager.onXRSessionInit.add((function(){n._referencedPosition.copyFromFloats(0,0,0),n._referenceQuaternion.copyFromFloats(0,0,0,1),n._firstFrame=n.compensateOnFirstFrame,n._xrSessionManager.onWorldScaleFactorChangedObservable.add((function(){n._xrSessionManager.currentFrame&&n._updateDepthNearFar()}))})),n._xrSessionManager.onXRFrameObservable.add((function(){n._firstFrame&&n._updateFromXRSession(),n.onXRCameraInitializedObservable.hasObservers()&&(n.onXRCameraInitializedObservable.notifyObservers(n),n.onXRCameraInitializedObservable.clear()),n._deferredUpdated&&(n.position.copyFrom(n._deferredPositionUpdate),n.rotationQuaternion.copyFrom(n._deferredRotationQuaternionUpdate)),n._updateReferenceSpace(),n._updateFromXRSession()}),void 0,!0),n}return m(t,e),Object.defineProperty(t.prototype,"trackingState",{get:function(){return this._trackingState},enumerable:!1,configurable:!0}),t.prototype._setTrackingState=function(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))},Object.defineProperty(t.prototype,"realWorldHeight",{get:function(){var e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);return e&&e.transform?e.transform.position.y*this._xrSessionManager.worldScalingFactor:0},enumerable:!1,configurable:!0}),t.prototype._updateForDualEyeDebugging=function(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new Jn(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new Jn(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null},t.prototype.setTransformationFromNonVRCamera=function(e,t){void 0===e&&(e=this.getScene().activeCamera),void 0===t&&(t=!0),e&&e!==this&&(e.computeWorldMatrix().decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,G.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace())},t.prototype.getClassName=function(){return"WebXRCamera"},t.prototype.setTarget=function(e){var t=H.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();var i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),G.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._lastXRViewerPose=void 0},t.prototype._updateDepthNearFar=function(){var e=(this.maxZ||1e4)*this._xrSessionManager.worldScalingFactor,t={depthFar:e,depthNear:this.minZ};this._xrSessionManager.updateRenderState(t),this._cache.minZ=this.minZ,this._cache.maxZ=e},t.prototype._updateFromXRSession=function(){var e=this,t=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=t||void 0,t){var i=t.emulatedPosition?ku.TRACKING_LOST:ku.TRACKING;if(this._setTrackingState(i),this.minZ===this._cache.minZ&&this.maxZ===this._cache.maxZ||this._updateDepthNearFar(),t.transform){var r=t.transform.orientation;if(void 0===t.transform.orientation.x)return;var n=t.transform.position;this._referencedPosition.set(n.x,n.y,n.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._referenceQuaternion.set(r.x,r.y,r.z,r.w),this._scene.useRightHandedSystem||(this._referencedPosition.z*=-1,this._referenceQuaternion.z*=-1,this._referenceQuaternion.w*=-1),this._firstFrame?(this._firstFrame=!1,this.position.y+=this._referencedPosition.y,this._referenceQuaternion.copyFromFloats(0,0,0,1)):(this.rotationQuaternion.copyFrom(this._referenceQuaternion),this.position.copyFrom(this._referencedPosition))}this.rigCameras.length!==t.views.length&&this._updateNumberOfRigCameras(t.views.length),t.views.forEach((function(t,i){var r,n=e.rigCameras[i];n.isLeftCamera||n.isRightCamera||("right"===t.eye?n._isRightCamera=!0:"left"===t.eye&&(n._isLeftCamera=!0));for(var o=e.getScene().customRenderTargets,a=0;a<o.length;a++){var s=o[a];-1===n.customRenderTargets.indexOf(s)&&n.customRenderTargets.push(s)}var l=t.transform.position,c=t.transform.orientation;n.parent=e.parent,n.position.set(l.x,l.y,l.z).scaleInPlace(e._xrSessionManager.worldScalingFactor),n.rotationQuaternion.set(c.x,c.y,c.z,c.w),e._scene.useRightHandedSystem?n.rotationQuaternion.multiplyInPlace(e._rotate180):(n.position.z*=-1,n.rotationQuaternion.z*=-1,n.rotationQuaternion.w*=-1),z.FromFloat32ArrayToRefScaled(t.projectionMatrix,0,1,n._projectionMatrix),e._scene.useRightHandedSystem||n._projectionMatrix.toggleProjectionMatrixHandInPlace();var u=2*Math.atan2(1,t.projectionMatrix[5]);n.fov=u,0===i&&(e.fov=u,e._projectionMatrix.copyFrom(n._projectionMatrix));var h=e._xrSessionManager.getRenderTargetTextureForView(t);e._renderingMultiview=(null===(r=null==h?void 0:h._texture)||void 0===r?void 0:r.isMultiview)||!1,e._renderingMultiview?0==i&&(e._xrSessionManager.trySetViewportForView(e.viewport,t),e.outputRenderTarget=h):(e._xrSessionManager.trySetViewportForView(n.viewport,t),n.outputRenderTarget=h||e._xrSessionManager.getRenderTargetTextureForView(t)),n.layerMask=e.layerMask}))}else this._setTrackingState(ku.NOT_TRACKING)},t.prototype._updateNumberOfRigCameras=function(e){for(void 0===e&&(e=1);this.rigCameras.length<e;){var t=new Mc("XR-RigCamera: "+this.rigCameras.length,V.Zero(),this.getScene());t.minZ=.1,t.rotationQuaternion=new G,t.updateUpVectorFromRotation=!0,t.isRigCamera=!0,t.rigParent=this,t.freezeProjectionMatrix(),this.rigCameras.push(t)}for(;this.rigCameras.length>e;){var i=this.rigCameras.pop();i&&i.dispose()}},t.prototype._updateReferenceSpace=function(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){var e=H.Matrix[0],i=H.Matrix[1],r=H.Matrix[2];z.ComposeToRef(t._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),z.ComposeToRef(t._ScaleReadOnly,this.rotationQuaternion,this.position,i),e.invert().multiplyToRef(i,r),r.invert(),this._scene.useRightHandedSystem||r.toggleModelMatrixHandInPlace(),r.decompose(void 0,this._referenceQuaternion,this._referencedPosition);var n=new XRRigidTransform({x:this._referencedPosition.x/this._xrSessionManager.worldScalingFactor,y:this._referencedPosition.y/this._xrSessionManager.worldScalingFactor,z:this._referencedPosition.z/this._xrSessionManager.worldScalingFactor},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(n)}},t._ScaleReadOnly=V.One(),t}(Oc),Cg=function(){function e(e){var t=this;this._scene=e,this._nonVRCamera=null,this._attachedToElement=!1,this._spectatorCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this._spectatorMode=!1,this._lastTimestamp=0,this.onInitialXRPoseSetObservable=new f,this.onStateChangedObservable=new f,this.state=Vu.NOT_IN_XR,this.sessionManager=new Zu(e),this.camera=new Ag("webxr",e,this.sessionManager),this.featuresManager=new xs(this.sessionManager),e.onDisposeObservable.addOnce((function(){t.dispose()}))}return e.CreateAsync=function(t){var i=new e(t);return i.sessionManager.initializeAsync().then((function(){return i._supported=!0,i})).catch((function(e){throw i._setState(Vu.NOT_IN_XR),i.dispose(),e}))},e.prototype.dispose=function(){var e;this.exitXRAsync(),this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),null===(e=this._spectatorCamera)||void 0===e||e.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)},e.prototype.enterXRAsync=function(e,t,i,r){var n,o,a;return void 0===i&&(i=this.sessionManager.getWebXRRenderTarget()),void 0===r&&(r={}),y(this,void 0,void 0,(function(){var s,l,c,u=this;return b(this,(function(h){switch(h.label){case 0:if(!this._supported)throw"WebXR not supported in this browser or environment";return this._setState(Vu.ENTERING_XR),"viewer"!==t&&"local"!==t&&(r.optionalFeatures=r.optionalFeatures||[],r.optionalFeatures.push(t)),[4,this.featuresManager._extendXRSessionInitObject(r)];case 1:r=h.sent(),"immersive-ar"===e&&"unbounded"!==t&&ae.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode"),h.label=2;case 2:return h.trys.push([2,7,,8]),[4,this.sessionManager.initializeSessionAsync(e,r)];case 3:return h.sent(),[4,this.sessionManager.setReferenceSpaceTypeAsync(t)];case 4:return h.sent(),s={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ},this.featuresManager.getEnabledFeature(Ss.LAYERS)?[3,6]:[4,i.initializeXRLayerAsync(this.sessionManager.session)];case 5:l=h.sent(),s.baseLayer=l,h.label=6;case 6:return this.sessionManager.updateRenderState(s),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!(null===(o=null===(n=this._nonVRCamera)||void 0===n?void 0:n.inputs)||void 0===o?void 0:o.attachedToElement),null===(a=this._nonVRCamera)||void 0===a||a.detachControl(),this._scene.activeCamera=this.camera,"immersive-ar"!==e?this._nonXRToXRCamera():(this._scene.autoClear=!1,this.camera.compensateOnFirstFrame=!1,this.camera.position.set(0,0,0),this.camera.rotationQuaternion.set(0,0,0,1),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)),this.sessionManager.onXRSessionEnded.addOnce((function(){u.state!==Vu.EXITING_XR&&u._setState(Vu.EXITING_XR),u.camera.rigCameras.forEach((function(e){e.outputRenderTarget=null})),u._scene.autoClear=u._originalSceneAutoClear,u._scene.activeCamera=u._nonVRCamera,u._attachedToElement&&u._nonVRCamera&&u._nonVRCamera.attachControl(!!u._nonVRCamera.inputs.noPreventDefault),"immersive-ar"!==e&&u.camera.compensateOnFirstFrame&&(u._nonVRCamera.setPosition?u._nonVRCamera.setPosition(u.camera.position):u._nonVRCamera.position.copyFrom(u.camera.position)),u._setState(Vu.NOT_IN_XR)})),this.sessionManager.onXRFrameObservable.addOnce((function(){u._setState(Vu.IN_XR)})),[2,this.sessionManager];case 7:throw c=h.sent(),ae.Log(c),ae.Log(c.message),this._setState(Vu.NOT_IN_XR),c;case 8:return[2]}}))}))},e.prototype.exitXRAsync=function(){return this.state!==Vu.IN_XR?Promise.resolve():(this._setState(Vu.EXITING_XR),this.sessionManager.exitXRAsync())},e.prototype.enableSpectatorMode=function(e){this._spectatorMode||(this._spectatorMode=!0,this._switchSpectatorMode(e))},e.prototype.disableSpecatatorMode=function(){this._spectatorMode&&(this._spectatorMode=!1,this._switchSpectatorMode())},e.prototype._switchSpectatorMode=function(e){var t=this,i=1/((null==e?void 0:e.fps)?e.fps:1e3)*1e3,r=(null==e?void 0:e.preferredCameraIndex)?null==e?void 0:e.preferredCameraIndex:0,n=function(){t._spectatorCamera&&t.sessionManager.currentTimestamp-t._lastTimestamp>=i&&(t._lastTimestamp=t.sessionManager.currentTimestamp,t._spectatorCamera.position.copyFrom(t.camera.rigCameras[r].globalPosition),t._spectatorCamera.rotationQuaternion.copyFrom(t.camera.rigCameras[r].absoluteRotation))};if(this._spectatorMode){if(r>=this.camera.rigCameras.length)throw new Error("the preferred camera index is beyond the length of rig camera array.");var o=function(){t.state===Vu.IN_XR?(t._spectatorCamera=new Kc("webxr-spectator",V.Zero(),t._scene),t._spectatorCamera.rotationQuaternion=new G,t._scene.activeCameras=[t.camera,t._spectatorCamera],t.sessionManager.onXRFrameObservable.add(n),t._scene.onAfterRenderCameraObservable.add((function(e){e===t.camera&&(t._scene.getEngine().framebufferDimensionsObject=null)}))):t.state===Vu.EXITING_XR&&(t.sessionManager.onXRFrameObservable.removeCallback(n),t._scene.activeCameras=null)};this.onStateChangedObservable.add(o),o()}else this.sessionManager.onXRFrameObservable.removeCallback(n),this._scene.activeCameras=[this.camera]},e.prototype._nonXRToXRCamera=function(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)},e.prototype._setState=function(e){this.state!==e&&(this.state=e,this.onStateChangedObservable.notifyObservers(this.state))},e}(),Rg=function(){function e(e,t,i,r){void 0===i&&(i=-1),void 0===r&&(r=[]),this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=r,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new f,this.onButtonStateChangedObservable=new f}return Object.defineProperty(e.prototype,"axes",{get:function(){return this._axes},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"changes",{get:function(){return this._changes},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hasChanges",{get:function(){return this._hasChanges},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"pressed",{get:function(){return this._pressed},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"touched",{get:function(){return this._touched},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this._currentValue},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){this.onAxisValueChangedObservable.clear(),this.onButtonStateChangedObservable.clear()},e.prototype.isAxes=function(){return 0!==this._axesIndices.length},e.prototype.isButton=function(){return-1!==this._buttonIndex},e.prototype.update=function(e){var t=!1,i=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){var r=e.buttons[this._buttonIndex];if(!r)return;this._currentValue!==r.value&&(this.changes.value={current:r.value,previous:this._currentValue},t=!0,this._currentValue=r.value),this._touched!==r.touched&&(this.changes.touched={current:r.touched,previous:this._touched},t=!0,this._touched=r.touched),this._pressed!==r.pressed&&(this.changes.pressed={current:r.pressed,previous:this._pressed},t=!0,this._pressed=r.pressed)}this.isAxes()&&(this._axes.x!==e.axes[this._axesIndices[0]]&&(this.changes.axes={current:{x:e.axes[this._axesIndices[0]],y:this._axes.y},previous:{x:this._axes.x,y:this._axes.y}},this._axes.x=e.axes[this._axesIndices[0]],i=!0),this._axes.y!==e.axes[this._axesIndices[1]]&&(this.changes.axes?this.changes.axes.current.y=e.axes[this._axesIndices[1]]:this.changes.axes={current:{x:this._axes.x,y:e.axes[this._axesIndices[1]]},previous:{x:this._axes.x,y:this._axes.y}},this._axes.y=e.axes[this._axesIndices[1]],i=!0)),t&&(this._hasChanges=!0,this.onButtonStateChangedObservable.notifyObservers(this)),i&&(this._hasChanges=!0,this.onAxisValueChangedObservable.notifyObservers(this._axes))},e.BUTTON_TYPE="button",e.SQUEEZE_TYPE="squeeze",e.THUMBSTICK_TYPE="thumbstick",e.TOUCHPAD_TYPE="touchpad",e.TRIGGER_TYPE="trigger",e}(),Pg=function(){function e(e,t,i,r,n,o){void 0===n&&(n=!1);var a=this;this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=r,this._doNotLoadControllerMesh=n,this._controllerCache=o,this._initComponent=function(e){if(e){var t=a.layout.components[e],i=t.type,r=t.gamepadIndices.button,n=[];void 0!==t.gamepadIndices.xAxis&&void 0!==t.gamepadIndices.yAxis&&n.push(t.gamepadIndices.xAxis,t.gamepadIndices.yAxis),a.components[e]=new Rg(e,i,r,n)}},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new f,t.components&&Object.keys(t.components).forEach(this._initComponent)}return e.prototype.dispose=function(){var e=this;this.getComponentIds().forEach((function(t){return e.getComponent(t).dispose()})),this.rootMesh&&(this.rootMesh.getChildren(void 0,!0).forEach((function(e){e.setEnabled(!1)})),this.rootMesh.dispose(!!this._controllerCache,!this._controllerCache))},e.prototype.getAllComponentsOfType=function(e){var t=this;return this.getComponentIds().map((function(e){return t.components[e]})).filter((function(t){return t.type===e}))},e.prototype.getComponent=function(e){return this.components[e]},e.prototype.getComponentIds=function(){return Object.keys(this.components)},e.prototype.getComponentOfType=function(e){return this.getAllComponentsOfType(e)[0]||null},e.prototype.getMainComponent=function(){return this.getComponent(this.layout.selectComponentId)},e.prototype.loadModel=function(){return y(this,void 0,void 0,(function(){var e,t,i=this;return b(this,(function(r){return e=!this._getModelLoadingConstraints(),t=this._getGenericFilenameAndPath(),e?ae.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),[2,new Promise((function(r,n){var o=function(t){e?i._getGenericParentMesh(t):i._setRootMesh(t),i._processLoadedModel(t),i._modelReady=!0,i.onModelLoadedObservable.notifyObservers(i),r(!0)};if(i._controllerCache){var a=i._controllerCache.filter((function(e){return e.filename===t.filename&&e.path===t.path}));if(a[0])return a[0].meshes.forEach((function(e){return e.setEnabled(!0)})),void o(a[0].meshes)}Ls.ImportMesh("",t.path,t.filename,i.scene,(function(e){i._controllerCache&&i._controllerCache.push(g(g({},t),{meshes:e})),o(e)}),null,(function(e,r){ae.Log(r),ae.Warn("Failed to retrieve controller model of type ".concat(i.profileId," from the remote server: ").concat(t.path).concat(t.filename)),n(r)}))}))]}))}))},e.prototype.updateFromXRFrame=function(e){var t=this;this.getComponentIds().forEach((function(e){return t.getComponent(e).update(t.gamepadObject)})),this.updateModel(e)},Object.defineProperty(e.prototype,"handness",{get:function(){return this.handedness},enumerable:!1,configurable:!0}),e.prototype.pulse=function(e,t,i){return void 0===i&&(i=0),this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[i]?this.gamepadObject.hapticActuators[i].pulse(e,t):Promise.resolve(!1)},e.prototype._getChildByName=function(e,t){return e.getChildren((function(e){return e.name===t}),!1)[0]},e.prototype._getImmediateChildByName=function(e,t){return e.getChildren((function(e){return e.name==t}),!0)[0]},e.prototype._lerpTransform=function(e,t,i){if(e.minMesh&&e.maxMesh&&e.valueMesh&&e.minMesh.rotationQuaternion&&e.maxMesh.rotationQuaternion&&e.valueMesh.rotationQuaternion){var r=i?.5*t+.5:t;G.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,r,e.valueMesh.rotationQuaternion),V.LerpToRef(e.minMesh.position,e.maxMesh.position,r,e.valueMesh.position)}},e.prototype.updateModel=function(e){this._modelReady&&this._updateModel(e)},e.prototype._getGenericFilenameAndPath=function(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}},e.prototype._getGenericParentMesh=function(e){var t=this;this.rootMesh=new Fa(this.profileId+" "+this.handedness,this.scene),e.forEach((function(e){e.parent||(e.isPickable=!1,e.setParent(t.rootMesh))})),this.rootMesh.rotationQuaternion=G.FromEulerAngles(0,Math.PI,0)},e}(),Ig=function(e){function t(i,r,n){var o=e.call(this,i,Mg[n],r,n)||this;return o.profileId=t.ProfileId,o}return m(t,e),t.prototype._getFilenameAndPath=function(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}},t.prototype._getModelLoadingConstraints=function(){return!0},t.prototype._processLoadedModel=function(e){},t.prototype._setRootMesh=function(e){var t=this;this.rootMesh=new Fa(this.profileId+" "+this.handedness,this.scene),e.forEach((function(e){e.isPickable=!1,e.parent||e.setParent(t.rootMesh)})),this.rootMesh.rotationQuaternion=G.FromEulerAngles(0,Math.PI,0)},t.prototype._updateModel=function(){},t.ProfileId="generic-trigger",t}(Pg),Mg={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-none",assetPath:"none.glb"}},Og=function(e){function t(t,i,r,n,o){var a=e.call(this,t,r.layouts[i.handedness||"none"],i.gamepad,i.handedness,void 0,o)||this;return a._repositoryUrl=n,a.controllerCache=o,a._buttonMeshMapping={},a._touchDots={},a.profileId=r.profileId,a}return m(t,e),t.prototype.dispose=function(){var t=this;e.prototype.dispose.call(this),this.controllerCache||Object.keys(this._touchDots).forEach((function(e){t._touchDots[e].dispose()}))},t.prototype._getFilenameAndPath=function(){return{filename:this.layout.assetPath,path:"".concat(this._repositoryUrl,"/profiles/").concat(this.profileId,"/")}},t.prototype._getModelLoadingConstraints=function(){var e=Ls.IsPluginForExtensionAvailable(".glb");return e||ae.Warn("glTF / glb loader was not registered, using generic controller instead"),e},t.prototype._processLoadedModel=function(e){var t=this;this.getComponentIds().forEach((function(e){var i=t.layout.components[e];t._buttonMeshMapping[e]={mainMesh:t._getChildByName(t.rootMesh,i.rootNodeName),states:{}},Object.keys(i.visualResponses).forEach((function(r){var n=i.visualResponses[r];if("transform"===n.valueNodeProperty)t._buttonMeshMapping[e].states[r]={valueMesh:t._getChildByName(t.rootMesh,n.valueNodeName),minMesh:t._getChildByName(t.rootMesh,n.minNodeName),maxMesh:t._getChildByName(t.rootMesh,n.maxNodeName)};else{var o=i.type===Rg.TOUCHPAD_TYPE&&i.touchPointNodeName?i.touchPointNodeName:n.valueNodeName;if(t._buttonMeshMapping[e].states[r]={valueMesh:t._getChildByName(t.rootMesh,o)},i.type===Rg.TOUCHPAD_TYPE&&!t._touchDots[r]){var a=Gh(r+"dot",{diameter:.0015,segments:8},t.scene);a.material=new Uu(r+"mat",t.scene),a.material.diffuseColor=Z.Red(),a.parent=t._buttonMeshMapping[e].states[r].valueMesh||null,a.isVisible=!1,t._touchDots[r]=a}}}))}))},t.prototype._setRootMesh=function(e){var t;this.rootMesh=new Fa(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(var i=0;i<e.length;i++){var r=e[i];r.isPickable=!1,r.parent||(t=r)}t&&t.setParent(this.rootMesh),this.scene.useRightHandedSystem||this.rootMesh.rotate(_n.Y,Math.PI,dn.WORLD)},t.prototype._updateModel=function(e){var t=this;this.disableAnimation||this.getComponentIds().forEach((function(e){var i=t.getComponent(e);if(i.hasChanges){var r=t._buttonMeshMapping[e],n=t.layout.components[e];Object.keys(n.visualResponses).forEach((function(e){var o=n.visualResponses[e],a=i.value;if("xAxis"===o.componentProperty?a=i.axes.x:"yAxis"===o.componentProperty&&(a=i.axes.y),"transform"===o.valueNodeProperty)t._lerpTransform(r.states[e],a,"button"!==o.componentProperty);else{var s=r.states[e].valueMesh;s&&(s.isVisible=i.touched||i.pressed),t._touchDots[e]&&(t._touchDots[e].isVisible=i.touched||i.pressed)}}))}}))},t}(Pg),Dg=[],Ng=function(){function e(){}return e.ClearProfilesCache=function(){this._ProfilesList=null,this._ProfileLoadingPromises={}},e.DefaultFallbacks=function(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("generic-hand-select",["generic-trigger"])},e.FindFallbackWithProfileId=function(e){var t=this._Fallbacks[e]||[];return t.unshift(e),t},e.GetMotionControllerWithXRInput=function(e,t,i){var r=this,n=[];i&&n.push(i),n.push.apply(n,e.profiles||[]),n.length&&!n[0]&&n.pop(),e.gamepad&&e.gamepad.id&&e.gamepad.id===(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0)&&n.push("oculus-touch-v2");var o=n.indexOf("windows-mixed-reality");if(-1!==o&&n.splice(o,0,"microsoft-mixed-reality"),n.length||n.push("generic-trigger"),this.UseOnlineRepository){var a=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,s=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return a.call(this,n,e,t).catch((function(){return s.call(r,n,e,t)}))}return this._LoadProfilesFromAvailableControllers(n,e,t)},e.RegisterController=function(e,t){this._AvailableControllers[e]=t},e.RegisterFallbacksForProfileId=function(e,t){var i;this._Fallbacks[e]?(i=this._Fallbacks[e]).push.apply(i,t):this._Fallbacks[e]=t},e.UpdateProfilesList=function(){return this._ProfilesList=rr.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then((function(e){return JSON.parse(e)})),this._ProfilesList},e.ClearControllerCache=function(){Dg.forEach((function(e){e.meshes.forEach((function(e){e.dispose(!1,!0)}))})),Dg.length=0},e._LoadProfileFromRepository=function(e,t,i){var r=this;return Promise.resolve().then((function(){return r._ProfilesList?r._ProfilesList:r.UpdateProfilesList()})).then((function(t){for(var i=0;i<e.length;++i)if(e[i]&&t[e[i]])return e[i];throw new Error("neither controller ".concat(e[0]," nor all fallbacks were found in the repository,"))})).then((function(e){return r._ProfileLoadingPromises[e]||(r._ProfileLoadingPromises[e]=rr.LoadFileAsync("".concat(r.BaseRepositoryUrl,"/profiles/").concat(e,"/profile.json"),!1).then((function(e){return JSON.parse(e)}))),r._ProfileLoadingPromises[e]})).then((function(e){return new Og(i,t,e,r.BaseRepositoryUrl,r.DisableControllerCache?void 0:Dg)}))},e._LoadProfilesFromAvailableControllers=function(e,t,i){for(var r=0;r<e.length;++r)if(e[r])for(var n=this.FindFallbackWithProfileId(e[r]),o=0;o<n.length;++o){var a=this._AvailableControllers[n[o]];if(a)return Promise.resolve(a(t,i))}throw new Error("no controller requested was found in the available controllers list")},e._AvailableControllers={},e._Fallbacks={},e._ProfileLoadingPromises={},e.BaseRepositoryUrl="https://immersive-web.github.io/webxr-input-profiles/packages/viewer/dist",e.PrioritizeOnlineRepository=!0,e.UseOnlineRepository=!0,e.DisableControllerCache=!0,e}();Ng.RegisterController(Ig.ProfileId,(function(e,t){return new Ig(t,e.gamepad,e.handedness)})),Ng.DefaultFallbacks();var Fg,Lg,wg=0,Bg=function(){function e(e,t,i){void 0===i&&(i={});var r=this;this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new V,this._disposed=!1,this.onDisposeObservable=new f,this.onMeshLoadedObservable=new f,this.onMotionControllerInitObservable=new f,this._uniqueId="controller-".concat(wg++,"-").concat(t.targetRayMode,"-").concat(t.handedness),this.pointer=new Uo("".concat(this._uniqueId,"-pointer"),e),this.pointer.rotationQuaternion=new G,this.inputSource.gripSpace&&(this.grip=new Uo("".concat(this._uniqueId,"-grip"),this._scene),this.grip.rotationQuaternion=new G),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&"tracked-pointer"===this.inputSource.targetRayMode&&Ng.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then((function(e){r.motionController=e,r.onMotionControllerInitObservable.notifyObservers(e),r._options.doNotLoadControllerMesh||r.motionController._doNotLoadControllerMesh||r.motionController.loadModel().then((function(e){var t;e&&r.motionController&&r.motionController.rootMesh&&(r._options.renderingGroupId&&(r.motionController.rootMesh.renderingGroupId=r._options.renderingGroupId,r.motionController.rootMesh.getChildMeshes(!1).forEach((function(e){return e.renderingGroupId=r._options.renderingGroupId}))),r.onMeshLoadedObservable.notifyObservers(r.motionController.rootMesh),r.motionController.rootMesh.parent=r.grip||r.pointer,r.motionController.disableAnimation=!!r._options.disableMotionControllerAnimation),r._disposed&&(null===(t=r.motionController)||void 0===t||t.dispose())}))}),(function(){rr.Warn("Could not find a matching motion controller for the registered input source")}))}return Object.defineProperty(e.prototype,"uniqueId",{get:function(){return this._uniqueId},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){this.grip&&this.grip.dispose(!0),this.motionController&&this.motionController.dispose(),this.pointer.dispose(!0),this.onMotionControllerInitObservable.clear(),this.onMeshLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._disposed=!0},e.prototype.getWorldPointerRayToRef=function(e,t){void 0===t&&(t=!1);var i=t&&this.grip?this.grip:this.pointer;V.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3},e.prototype.updateFromXRFrame=function(e,t,i,r){var n=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=n,n){var o=n.transform.position;this.pointer.position.set(o.x,o.y,o.z).scaleInPlace(r.worldScalingFactor);var a=n.transform.orientation;this.pointer.rotationQuaternion.set(a.x,a.y,a.z,a.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent,this.pointer.scaling.setAll(r.worldScalingFactor)}if(this.inputSource.gripSpace&&this.grip){var s=e.getPose(this.inputSource.gripSpace,t);if(s){o=s.transform.position;var l=s.transform.orientation;this.grip.position.set(o.x,o.y,o.z).scaleInPlace(r.worldScalingFactor),this.grip.rotationQuaternion.set(l.x,l.y,l.z,l.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent,this.grip.scaling.setAll(r.worldScalingFactor)}this.motionController&&this.motionController.updateFromXRFrame(e)},e}(),Ug=function(){function e(e,t,i){void 0===i&&(i={});var r=this;if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new f,this.onControllerRemovedObservable=new f,this._onInputSourcesChange=function(e){r._addAndRemoveControllers(e.added,e.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add((function(){r._addAndRemoveControllers([],r.controllers.map((function(e){return e.inputSource})))})),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add((function(e){e.addEventListener("inputsourceschange",r._onInputSourcesChange)})),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add((function(e){r.controllers.forEach((function(t){t.updateFromXRFrame(e,r.xrSessionManager.referenceSpace,r.xrCamera,r.xrSessionManager)}))})),this._options.customControllersRepositoryURL&&(Ng.BaseRepositoryUrl=this._options.customControllersRepositoryURL),Ng.UseOnlineRepository=!this._options.disableOnlineControllerRepository,Ng.UseOnlineRepository)try{Ng.UpdateProfilesList().catch((function(){Ng.UseOnlineRepository=!1}))}catch(e){Ng.UseOnlineRepository=!1}}return e.prototype._addAndRemoveControllers=function(e,t){for(var i=this,r=this.controllers.map((function(e){return e.inputSource})),n=0,o=e;n<o.length;n++){var a=o[n];if(-1===r.indexOf(a)){var s=new Bg(this.xrSessionManager.scene,a,g(g({},this._options.controllerOptions||{}),{forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation}));this.controllers.push(s),this.onControllerAddedObservable.notifyObservers(s)}}var l=[],c=[];this.controllers.forEach((function(e){-1===t.indexOf(e.inputSource)?l.push(e):c.push(e)})),this.controllers=l,c.forEach((function(e){i.onControllerRemovedObservable.notifyObservers(e),e.dispose()}))},e.prototype.dispose=function(){this.controllers.forEach((function(e){e.dispose()})),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),Ng.ClearControllerCache()},e}(),Vg=function(e){function t(i,r){var n=e.call(this,i)||this;return n._options=r,n._attachController=function(e){var i;if(!n._controllers[e.uniqueId]){var r=(i=n._generateNewMeshPair(n._options.forceGripIfAvailable&&e.grip?e.grip:e.pointer)).laserPointer,o=i.selectionMesh;switch(n._controllers[e.uniqueId]={xrController:e,laserPointer:r,selectionMesh:o,meshUnderPointer:null,pick:null,tmpRay:new hs(new V,new V),disabledByNearInteraction:!1,id:t._IdCounter++},n._attachedController?!n._options.enablePointerSelectionOnAllControllers&&n._options.preferredHandedness&&e.inputSource.handedness===n._options.preferredHandedness&&(n._attachedController=e.uniqueId):n._options.enablePointerSelectionOnAllControllers||(n._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return n._attachTrackedPointerRayMode(e);case"gaze":return n._attachGazeMode(e);case"screen":case"transient-pointer":return n._attachScreenRayMode(e)}}},n._controllers={},n._tmpVectorForPickCompare=new V,n.disablePointerLighting=!0,n.disableSelectionMeshLighting=!0,n.displayLaserPointer=!0,n.displaySelectionMesh=!0,n.laserPointerPickedColor=new Z(.9,.9,.9),n.laserPointerDefaultColor=new Z(.7,.7,.7),n.selectionMeshDefaultColor=new Z(.8,.8,.8),n.selectionMeshPickedColor=new Z(.3,.3,1),n._identityMatrix=z.Identity(),n._screenCoordinatesRef=V.Zero(),n._viewportRef=new Jn(0,0,0,0),n._scene=n._xrSessionManager.scene,void 0===n._options.lookAndPickMode&&(n._scene.getEngine()._badDesktopOS||n._scene.getEngine()._badOS)&&(n._options.lookAndPickMode=!0),n._options.lookAndPickMode&&(n._options.enablePointerSelectionOnAllControllers=!0,n.displayLaserPointer=!1),n}return m(t,e),t.prototype.attach=function(){var i,r=this;if(!e.prototype.attach.call(this))return!1;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController,!0),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(function(e){r._detachController(e.uniqueId)}),!0),this._scene.constantlyUpdateMeshUnderPointer=!0,this._options.gazeCamera){var n=this._options.gazeCamera,o=(i=this._generateNewMeshPair(n)).laserPointer,a=i.selectionMesh;this._controllers.camera={webXRCamera:n,laserPointer:o,selectionMesh:a,meshUnderPointer:null,pick:null,tmpRay:new hs(new V,new V),disabledByNearInteraction:!1,id:t._IdCounter++},this._attachGazeMode()}return!0},t.prototype.detach=function(){var t=this;return!!e.prototype.detach.call(this)&&(Object.keys(this._controllers).forEach((function(e){t._detachController(e)})),!0)},t.prototype.getMeshUnderPointer=function(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null},t.prototype.getXRControllerByPointerId=function(e){for(var t=Object.keys(this._controllers),i=0;i<t.length;++i)if(this._controllers[t[i]].id===e)return this._controllers[t[i]].xrController||null;return null},t.prototype._getPointerSelectionDisabledByPointerId=function(e){for(var t=Object.keys(this._controllers),i=0;i<t.length;++i)if(this._controllers[t[i]].id===e)return this._controllers[t[i]].disabledByNearInteraction;return!0},t.prototype._setPointerSelectionDisabledByPointerId=function(e,t){for(var i=Object.keys(this._controllers),r=0;r<i.length;++r)if(this._controllers[i[r]].id===e)return void(this._controllers[i[r]].disabledByNearInteraction=t)},t.prototype._onXRFrame=function(e){var t=this;Object.keys(this._controllers).forEach((function(e){var i,r=t._controllers[e];if(!t._options.lookAndPickMode||"transient-pointer"===(null===(i=r.xrController)||void 0===i?void 0:i.inputSource.targetRayMode)){if(!t._options.enablePointerSelectionOnAllControllers&&e!==t._attachedController||r.disabledByNearInteraction)return r.selectionMesh.isVisible=!1,r.laserPointer.isVisible=!1,void(r.pick=null);var n;if(r.laserPointer.isVisible=t.displayLaserPointer,r.xrController)n=t._options.forceGripIfAvailable&&r.xrController.grip?r.xrController.grip.position:r.xrController.pointer.position,r.xrController.getWorldPointerRayToRef(r.tmpRay,t._options.forceGripIfAvailable);else{if(!r.webXRCamera)return;n=r.webXRCamera.position,r.webXRCamera.getForwardRayToRef(r.tmpRay)}if(t._options.maxPointerDistance&&(r.tmpRay.length=t._options.maxPointerDistance),!t._options.disableScenePointerVectorUpdate&&n){var o=t._xrSessionManager.scene,a=t._options.xrInput.xrCamera;a&&(a.viewport.toGlobalToRef(o.getEngine().getRenderWidth()/a.rigCameras.length,o.getEngine().getRenderHeight(),t._viewportRef),V.ProjectToRef(n,t._identityMatrix,a.getTransformationMatrix(),t._viewportRef,t._screenCoordinatesRef),"number"!=typeof t._screenCoordinatesRef.x||"number"!=typeof t._screenCoordinatesRef.y||isNaN(t._screenCoordinatesRef.x)||isNaN(t._screenCoordinatesRef.y)||t._screenCoordinatesRef.x===1/0||t._screenCoordinatesRef.y===1/0||(o.pointerX=t._screenCoordinatesRef.x,o.pointerY=t._screenCoordinatesRef.y,r.screenCoordinates={x:t._screenCoordinatesRef.x,y:t._screenCoordinatesRef.y}))}var s=null;t._utilityLayerScene&&(s=t._utilityLayerScene.pickWithRay(r.tmpRay,t._utilityLayerScene.pointerMovePredicate||t.raySelectionPredicate));var l=t._scene.pickWithRay(r.tmpRay,t._scene.pointerMovePredicate||t.raySelectionPredicate);s&&s.hit?l&&l.hit?s.distance<l.distance?r.pick=s:r.pick=l:r.pick=s:r.pick=l,r.pick&&r.xrController&&(r.pick.aimTransform=r.xrController.pointer,r.pick.gripTransform=r.xrController.grip||null,r.pick.originMesh=r.xrController.pointer);var c=r.pick;if(c&&c.pickedPoint&&c.hit){t._updatePointerDistance(r.laserPointer,c.distance),r.selectionMesh.position.copyFrom(c.pickedPoint),r.selectionMesh.scaling.x=Math.sqrt(c.distance),r.selectionMesh.scaling.y=Math.sqrt(c.distance),r.selectionMesh.scaling.z=Math.sqrt(c.distance);var u=t._convertNormalToDirectionOfRay(c.getNormal(!0),r.tmpRay);if(r.selectionMesh.position.copyFrom(c.pickedPoint),u){var h=V.Cross(_n.Y,u),d=V.Cross(u,h);V.RotationFromAxisToRef(d,u,h,r.selectionMesh.rotation),r.selectionMesh.position.addInPlace(u.scale(.001))}r.selectionMesh.isVisible=t.displaySelectionMesh,r.meshUnderPointer=c.pickedMesh}else r.selectionMesh.isVisible=!1,t._updatePointerDistance(r.laserPointer,1),r.meshUnderPointer=null}}))},Object.defineProperty(t.prototype,"_utilityLayerScene",{get:function(){return this._options.customUtilityLayerScene||Ih.DefaultUtilityLayer.utilityLayerScene},enumerable:!1,configurable:!0}),t.prototype._attachGazeMode=function(e){var t=this,i=this._controllers[e&&e.uniqueId||"camera"],r=this._options.timeToSelect||3e3,n=this._options.useUtilityLayer?this._utilityLayerScene:this._scene,o=new Fr,a=sh("selection",{diameter:.0525,thickness:.015,tessellation:20},n);a.isVisible=!1,a.isPickable=!1,a.parent=i.selectionMesh;var s=0,l=!1,c={pointerId:i.id,pointerType:"xr"};i.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((function(){if(i.pick){if(t._augmentPointerInit(c,i.id,i.screenCoordinates),i.laserPointer.material.alpha=0,a.isVisible=!1,i.pick.hit)if(t._pickingMoved(o,i.pick))l&&(t._options.disablePointerUpOnTouchOut||t._scene.simulatePointerUp(i.pick,c)),l=!1,s=0;else if(s>r/10&&(a.isVisible=!0),(s+=t._scene.getEngine().getDeltaTime())>=r)t._scene.simulatePointerDown(i.pick,c),l=!0,t._options.disablePointerUpOnTouchOut&&t._scene.simulatePointerUp(i.pick,c),a.isVisible=!1;else{var e=1-s/r;a.scaling.set(e,e,e)}else l=!1,s=0;t._scene.simulatePointerMove(i.pick,c),o=i.pick}})),void 0!==this._options.renderingGroupId&&(a.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce((function(){i.pick&&!t._options.disablePointerUpOnTouchOut&&l&&(t._scene.simulatePointerUp(i.pick,c),i.finalPointerUpTriggered=!0),a.dispose()}))},t.prototype._attachScreenRayMode=function(e){var t=this,i=this._controllers[e.uniqueId],r=!1,n={pointerId:i.id,pointerType:"xr"};i.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((function(){t._augmentPointerInit(n,i.id,i.screenCoordinates),!i.pick||t._options.disablePointerUpOnTouchOut&&r||(r?t._scene.simulatePointerMove(i.pick,n):(t._scene.simulatePointerDown(i.pick,n),i.pointerDownTriggered=!0,r=!0,t._options.disablePointerUpOnTouchOut&&t._scene.simulatePointerUp(i.pick,n)))})),e.onDisposeObservable.addOnce((function(){t._augmentPointerInit(n,i.id,i.screenCoordinates),t._xrSessionManager.runInXRFrame((function(){i.pick&&!i.finalPointerUpTriggered&&r&&!t._options.disablePointerUpOnTouchOut&&(t._scene.simulatePointerUp(i.pick,n),i.finalPointerUpTriggered=!0)}))}))},t.prototype._attachTrackedPointerRayMode=function(e){var t=this,i=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);var r={pointerId:i.id,pointerType:"xr"};if(i.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((function(){i.laserPointer.material.disableLighting=t.disablePointerLighting,i.selectionMesh.material.disableLighting=t.disableSelectionMeshLighting,i.pick&&(t._augmentPointerInit(r,i.id,i.screenCoordinates),t._scene.simulatePointerMove(i.pick,r))})),e.inputSource.gamepad){var n=function(n){t._options.overrideButtonId&&(i.selectionComponent=n.getComponent(t._options.overrideButtonId)),i.selectionComponent||(i.selectionComponent=n.getMainComponent()),i.onButtonChangedObserver=i.selectionComponent.onButtonStateChangedObservable.add((function(n){if(n.changes.pressed){var o=n.changes.pressed.current;if(i.pick)(t._options.enablePointerSelectionOnAllControllers||e.uniqueId===t._attachedController)&&(t._augmentPointerInit(r,i.id,i.screenCoordinates),o?(t._scene.simulatePointerDown(i.pick,r),i.pointerDownTriggered=!0,i.selectionMesh.material.emissiveColor=t.selectionMeshPickedColor,i.laserPointer.material.emissiveColor=t.laserPointerPickedColor):(t._scene.simulatePointerUp(i.pick,r),i.selectionMesh.material.emissiveColor=t.selectionMeshDefaultColor,i.laserPointer.material.emissiveColor=t.laserPointerDefaultColor));else if(o&&!t._options.enablePointerSelectionOnAllControllers&&!t._options.disableSwitchOnClick){var a=t._controllers[t._attachedController];a&&a.pointerDownTriggered&&!a.finalPointerUpTriggered&&(t._augmentPointerInit(r,a.id,a.screenCoordinates),t._scene.simulatePointerUp(new Fr,{pointerId:a.id,pointerType:"xr"}),a.finalPointerUpTriggered=!0),t._attachedController=e.uniqueId}}}))};e.motionController?n(e.motionController):e.onMotionControllerInitObservable.add(n)}else{var o=function(e){t._xrSessionManager.onXRFrameObservable.addOnce((function(){t._augmentPointerInit(r,i.id,i.screenCoordinates),i.xrController&&e.inputSource===i.xrController.inputSource&&i.pick&&(t._scene.simulatePointerDown(i.pick,r),i.pointerDownTriggered=!0,i.selectionMesh.material.emissiveColor=t.selectionMeshPickedColor,i.laserPointer.material.emissiveColor=t.laserPointerPickedColor)}))},a=function(e){t._xrSessionManager.onXRFrameObservable.addOnce((function(){t._augmentPointerInit(r,i.id,i.screenCoordinates),i.xrController&&e.inputSource===i.xrController.inputSource&&i.pick&&(t._scene.simulatePointerUp(i.pick,r),i.selectionMesh.material.emissiveColor=t.selectionMeshDefaultColor,i.laserPointer.material.emissiveColor=t.laserPointerDefaultColor)}))};i.eventListeners={selectend:a,selectstart:o},this._xrSessionManager.session.addEventListener("selectstart",o),this._xrSessionManager.session.addEventListener("selectend",a)}},t.prototype._convertNormalToDirectionOfRay=function(e,t){return e&&Math.acos(V.Dot(e,t.direction))<Math.PI/2&&e.scaleInPlace(-1),e},t.prototype._detachController=function(e){var t=this,i=this._controllers[e];if(i){if(i.selectionComponent&&i.onButtonChangedObserver&&i.selectionComponent.onButtonStateChangedObservable.remove(i.onButtonChangedObserver),i.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(i.onFrameObserver),i.eventListeners&&Object.keys(i.eventListeners).forEach((function(e){var r=i.eventListeners&&i.eventListeners[e];r&&t._xrSessionManager.session.removeEventListener(e,r)})),!i.finalPointerUpTriggered&&i.pointerDownTriggered){var r={pointerId:i.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame((function(){t._augmentPointerInit(r,i.id,i.screenCoordinates),t._scene.simulatePointerUp(i.pick||new Fr,r),i.finalPointerUpTriggered=!0}))}this._xrSessionManager.scene.onBeforeRenderObservable.addOnce((function(){try{if(i.selectionMesh.dispose(),i.laserPointer.dispose(),delete t._controllers[e],t._attachedController===e){var r=Object.keys(t._controllers);r.length?t._attachedController=r[0]:t._attachedController=""}}catch(e){rr.Warn("controller already detached.")}}))}},t.prototype._generateNewMeshPair=function(e){var t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Ih.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():xh("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;var r=new Uu("laserPointerMat",t);r.emissiveColor=this.laserPointerDefaultColor,r.alpha=.7,i.material=r,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;var n=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():sh("gazeTracker",{diameter:.0105,thickness:.0075,tessellation:20},t);n.bakeCurrentTransformIntoVertices(),n.isPickable=!1,n.isVisible=!1;var o=new Uu("targetMat",t);return o.specularColor=Z.Black(),o.emissiveColor=this.selectionMeshDefaultColor,o.backFaceCulling=!1,n.material=o,void 0!==this._options.renderingGroupId&&(i.renderingGroupId=this._options.renderingGroupId,n.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:n}},t.prototype._pickingMoved=function(e,t){var i;if(!e.hit||!t.hit)return!0;if(!(e.pickedMesh&&e.pickedPoint&&t.pickedMesh&&t.pickedPoint))return!0;if(e.pickedMesh!==t.pickedMesh)return!0;null===(i=e.pickedPoint)||void 0===i||i.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));var r=.01*(this._options.gazeModePointerMovedFactor||1)*t.distance;return this._tmpVectorForPickCompare.length()>r},t.prototype._updatePointerDistance=function(e,t){void 0===t&&(t=100),e.scaling.y=t,this._scene.useRightHandedSystem&&(t*=-1),e.position.z=t/2+.05},t.prototype._augmentPointerInit=function(e,t,i){e.pointerId=t,e.pointerType="xr",i&&(e.screenX=i.x,e.screenY=i.y)},Object.defineProperty(t.prototype,"lasterPointerDefaultColor",{get:function(){return this.laserPointerDefaultColor},enumerable:!1,configurable:!0}),t._IdCounter=200,t.Name=Ss.POINTER_SELECTION,t.Version=1,t}(As);xs.AddWebXRFeature(Vg.Name,(function(e,t){return function(){return new Vg(e,t)}}),Vg.Version,!0),po.prototype._projectOnTrianglesToRef=function(e,t,i,r,n,o){for(var a=H.Vector3[0],s=H.Vector3[1],l=1/0,c=this.indexStart;c<this.indexStart+this.indexCount-(3-r);c+=r){var u=i[c],h=i[c+1],d=i[c+2];if(n&&4294967295===d)c+=2;else{var p=t[u],f=t[h],_=t[d];if(p&&f&&_){var m=V.ProjectOnTriangleToRef(e,p,f,_,s);m<l&&(a.copyFrom(s),l=m)}}}return o.copyFrom(a),l},po.prototype._projectOnUnIndexedTrianglesToRef=function(e,t,i,r){for(var n=H.Vector3[0],o=H.Vector3[1],a=1/0,s=this.verticesStart;s<this.verticesStart+this.verticesCount;s+=3){var l=t[s],c=t[s+1],u=t[s+2],h=V.ProjectOnTriangleToRef(e,l,c,u,o);h<a&&(n.copyFrom(o),a=h)}return r.copyFrom(n),a},po.prototype.projectToRef=function(e,t,i,r){var n=this.getMaterial();if(!n)return-1;var o=3,a=!1;switch(n.fillMode){case u.MATERIAL_PointListDrawMode:case u.MATERIAL_LineLoopDrawMode:case u.MATERIAL_LineStripDrawMode:case u.MATERIAL_TriangleFanDrawMode:return-1;case u.MATERIAL_TriangleStripDrawMode:o=1,a=!0}return n.fillMode===u.MATERIAL_LineListDrawMode?-1:!i.length&&this._mesh._unIndexed?this._projectOnUnIndexedTrianglesToRef(e,t,i,r):this._projectOnTrianglesToRef(e,t,i,o,a,r)},function(e){e[e.DEHYDRATED=0]="DEHYDRATED",e[e.HOVER=1]="HOVER",e[e.TOUCH=2]="TOUCH"}(Fg||(Fg={})),function(e){e[e.DISABLED=0]="DISABLED",e[e.CENTERED_ON_CONTROLLER=1]="CENTERED_ON_CONTROLLER",e[e.CENTERED_IN_FRONT=2]="CENTERED_IN_FRONT"}(Lg||(Lg={}));var kg=function(e){function t(i,r){var n=e.call(this,i)||this;return n._options=r,n._tmpRay=new hs(new V,new V),n._attachController=function(e){var i;if(!n._controllers[e.uniqueId]){var r=(i=n._generateNewTouchPointMesh()).touchCollisionMesh,o=i.touchCollisionMeshFunction,a=i.hydrateCollisionMeshFunction,s=n._generateVisualCue();switch(n._controllers[e.uniqueId]={xrController:e,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:r,touchCollisionMeshFunction:o,hydrateCollisionMeshFunction:a,currentAnimationState:Fg.DEHYDRATED,grabRay:new hs(new V,new V),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,downTriggered:!1,id:t._IdCounter++,pickedPointVisualCue:s},n._controllers[e.uniqueId]._worldScaleObserver=n._controllers[e.uniqueId]._worldScaleObserver||n._xrSessionManager.onWorldScaleFactorChangedObservable.add((function(t){var i;if(t.newScaleFactor!==t.previousScaleFactor){n._controllers[e.uniqueId].touchCollisionMesh.dispose(),n._controllers[e.uniqueId].pickedPointVisualCue.dispose();var r=(i=n._generateNewTouchPointMesh()).touchCollisionMesh,o=i.touchCollisionMeshFunction,a=i.hydrateCollisionMeshFunction;n._controllers[e.uniqueId].touchCollisionMesh=r,n._controllers[e.uniqueId].touchCollisionMeshFunction=o,n._controllers[e.uniqueId].hydrateCollisionMeshFunction=a,n._controllers[e.uniqueId].pickedPointVisualCue=n._generateVisualCue()}})),n._attachedController?!n._options.enableNearInteractionOnAllControllers&&n._options.preferredHandedness&&e.inputSource.handedness===n._options.preferredHandedness&&(n._attachedController=e.uniqueId):n._options.enableNearInteractionOnAllControllers||(n._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return n._attachNearInteractionMode(e);case"gaze":case"screen":return null}}},n._controllers={},n._farInteractionFeature=null,n.selectionMeshDefaultColor=new Z(.8,.8,.8),n.selectionMeshPickedColor=new Z(.3,.3,1),n._hoverRadius=.1,n._pickRadius=.02,n._controllerPickRadius=.03,n._nearGrabLengthScale=5,n._scene=n._xrSessionManager.scene,void 0===n._options.nearInteractionControllerMode&&(n._options.nearInteractionControllerMode=Lg.CENTERED_IN_FRONT),n._options.farInteractionFeature&&(n._farInteractionFeature=n._options.farInteractionFeature),n}return m(t,e),t.prototype.attach=function(){var t=this;return!!e.prototype.attach.call(this)&&(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(function(e){t._detachController(e.uniqueId)})),this._scene.constantlyUpdateMeshUnderPointer=!0,!0)},t.prototype.detach=function(){var t=this;return!!e.prototype.detach.call(this)&&(Object.keys(this._controllers).forEach((function(e){t._detachController(e)})),!0)},t.prototype.getMeshUnderPointer=function(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null},t.prototype.getXRControllerByPointerId=function(e){for(var t=Object.keys(this._controllers),i=0;i<t.length;++i)if(this._controllers[t[i]].id===e)return this._controllers[t[i]].xrController||null;return null},t.prototype.setFarInteractionFeature=function(e){this._farInteractionFeature=e},t.prototype._nearPickPredicate=function(e){return e.isEnabled()&&e.isVisible&&e.isPickable&&e.isNearPickable},t.prototype._nearGrabPredicate=function(e){return e.isEnabled()&&e.isVisible&&e.isPickable&&e.isNearGrabbable},t.prototype._nearInteractionPredicate=function(e){return e.isEnabled()&&e.isVisible&&e.isPickable&&(e.isNearPickable||e.isNearGrabbable)},t.prototype._controllerAvailablePredicate=function(e,t){for(var i=e;i;){if(i.reservedDataStore&&i.reservedDataStore.nearInteraction&&i.reservedDataStore.nearInteraction.excludedControllerId===t)return!1;i=i.parent}return!0},t.prototype._handleTransitionAnimation=function(e,t){var i;if(e.currentAnimationState!==t&&this._options.nearInteractionControllerMode===Lg.CENTERED_IN_FRONT&&!(null===(i=e.xrController)||void 0===i?void 0:i.inputSource.hand)){if(t>e.currentAnimationState)switch(e.currentAnimationState){case Fg.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===Fg.HOVER)break;case Fg.HOVER:if(e.touchCollisionMeshFunction(!0),t===Fg.TOUCH)break}else switch(e.currentAnimationState){case Fg.TOUCH:if(e.touchCollisionMeshFunction(!1),t===Fg.HOVER)break;case Fg.HOVER:if(e.hydrateCollisionMeshFunction(!1),t===Fg.DEHYDRATED)break}e.currentAnimationState=t}},t.prototype._processTouchPoint=function(e,t,i){var r,n=this._controllers[e];n.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(H.Vector3[0]),n.grabRay.direction.copyFrom(H.Vector3[0]),this._options.nearInteractionControllerMode!==Lg.CENTERED_IN_FRONT||(null===(r=n.xrController)||void 0===r?void 0:r.inputSource.hand)||(n.xrController.getWorldPointerRayToRef(this._tmpRay),n.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),n.grabRay.length=this._nearGrabLengthScale*this._hoverRadius*this._xrSessionManager.worldScalingFactor,n.touchCollisionMesh.position.copyFrom(n.grabRay.origin).scaleInPlace(this._xrSessionManager.worldScalingFactor)},t.prototype._onXRFrame=function(e){var t=this;Object.keys(this._controllers).forEach((function(i){var r,n=t._controllers[i],o=null===(r=n.xrController)||void 0===r?void 0:r.inputSource.hand;if((t._options.enableNearInteractionOnAllControllers||i===t._attachedController)&&n.xrController&&(o||t._options.nearInteractionControllerMode&&n.xrController.inputSource.gamepad)){if(n.hoverInteraction=!1,n.nearInteraction=!1,n.xrController){if(o){var a=o.get("index-finger-tip");if(a){var s=e.getJointPose(a,t._xrSessionManager.referenceSpace);if(s&&s.transform){var l=t._scene.useRightHandedSystem?1:-1;H.Vector3[0].set(s.transform.position.x,s.transform.position.y,s.transform.position.z*l),H.Quaternion[0].set(s.transform.orientation.x,s.transform.orientation.y,s.transform.orientation.z*l,s.transform.orientation.w*l),t._processTouchPoint(i,H.Vector3[0],H.Quaternion[0])}}}else if(n.xrController.inputSource.gamepad&&t._options.nearInteractionControllerMode!==Lg.DISABLED){var c=n.xrController.pointer;n.xrController.grip&&t._options.nearInteractionControllerMode===Lg.CENTERED_ON_CONTROLLER&&(c=n.xrController.grip),t._processTouchPoint(i,c.position,c.rotationQuaternion)}var u=function(e,t){return t&&t.hit?e&&e.hit?t.distance<e.distance?t:e:t:e},h=function(e){var t=new Fr,i=!1,r=e&&e.pickedPoint&&e.hit;return(null==e?void 0:e.pickedPoint)&&(i=0===e.pickedPoint.x&&0===e.pickedPoint.y&&0===e.pickedPoint.z),r&&!i&&(t=e),t};if(!n.grabInteraction){var d=null,p=null;t._options.useUtilityLayer&&t._utilityLayerScene&&(p=t._pickWithSphere(n,t._hoverRadius*t._xrSessionManager.worldScalingFactor,t._utilityLayerScene,(function(e){return t._nearInteractionPredicate(e)})));var f=u(t._pickWithSphere(n,t._hoverRadius*t._xrSessionManager.worldScalingFactor,t._scene,(function(e){return t._nearInteractionPredicate(e)})),p);if(f&&f.hit&&(d=h(f)).hit&&(n.hoverInteraction=!0),n.hoverInteraction){var _=null,m=(o?t._pickRadius:t._controllerPickRadius)*t._xrSessionManager.worldScalingFactor;t._options.useUtilityLayer&&t._utilityLayerScene&&(_=t._pickWithSphere(n,m,t._utilityLayerScene,(function(e){return t._nearPickPredicate(e)})));var g=h(u(t._pickWithSphere(n,m,t._scene,(function(e){return t._nearPickPredicate(e)})),_));g.hit&&(d=g,n.nearInteraction=!0)}n.stalePick=n.pick,n.pick=d,n.pick&&n.pick.pickedPoint&&n.pick.hit?(n.meshUnderPointer=n.pick.pickedMesh,n.pickedPointVisualCue.position.copyFrom(n.pick.pickedPoint),n.pickedPointVisualCue.isVisible=!0,t._farInteractionFeature&&t._farInteractionFeature.attached&&t._farInteractionFeature._setPointerSelectionDisabledByPointerId(n.id,!0)):(n.meshUnderPointer=null,n.pickedPointVisualCue.isVisible=!1,t._farInteractionFeature&&t._farInteractionFeature.attached&&t._farInteractionFeature._setPointerSelectionDisabledByPointerId(n.id,!1))}var v=Fg.DEHYDRATED;n.grabInteraction||n.nearInteraction?v=Fg.TOUCH:n.hoverInteraction&&(v=Fg.HOVER),t._handleTransitionAnimation(n,v)}}else n.pick=null}))},Object.defineProperty(t.prototype,"_utilityLayerScene",{get:function(){return this._options.customUtilityLayerScene||Ih.DefaultUtilityLayer.utilityLayerScene},enumerable:!1,configurable:!0}),t.prototype._generateVisualCue=function(){var e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Ih.DefaultUtilityLayer.utilityLayerScene:this._scene,t=Gh("nearInteraction",{diameter:.0105*this._xrSessionManager.worldScalingFactor},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=G.Identity();var i=new Uu("targetMat",e);return i.specularColor=Z.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t},t.prototype._isControllerReadyForNearInteraction=function(e){return!this._farInteractionFeature||this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e)},t.prototype._attachNearInteractionMode=function(e){var t=this,i=this._controllers[e.uniqueId],r={pointerId:i.id,pointerType:"xr-near"};i.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((function(){(t._options.enableNearInteractionOnAllControllers||e.uniqueId===t._attachedController)&&i.xrController&&(i.xrController.inputSource.hand||t._options.nearInteractionControllerMode&&i.xrController.inputSource.gamepad)&&(i.pick&&(i.pick.ray=i.grabRay),i.pick&&t._isControllerReadyForNearInteraction(i.id)&&t._scene.simulatePointerMove(i.pick,r),i.nearInteraction&&i.pick&&i.pick.hit?i.nearInteractionTargetMesh||(t._scene.simulatePointerDown(i.pick,r),i.nearInteractionTargetMesh=i.meshUnderPointer,i.downTriggered=!0):i.nearInteractionTargetMesh&&i.stalePick&&(t._scene.simulatePointerUp(i.stalePick,r),i.downTriggered=!1,i.nearInteractionTargetMesh=null))}));var n=function(n){t._options.enableNearInteractionOnAllControllers||e.uniqueId===t._attachedController&&t._isControllerReadyForNearInteraction(i.id)?(i.pick&&(i.pick.ray=i.grabRay),n&&i.pick&&i.meshUnderPointer&&t._nearGrabPredicate(i.meshUnderPointer)?(i.grabInteraction=!0,i.pickedPointVisualCue.isVisible=!1,t._scene.simulatePointerDown(i.pick,r),i.downTriggered=!0):!n&&i.pick&&i.grabInteraction&&(t._scene.simulatePointerUp(i.pick,r),i.downTriggered=!1,i.grabInteraction=!1,i.pickedPointVisualCue.isVisible=!0)):!n||t._options.enableNearInteractionOnAllControllers||t._options.disableSwitchOnClick||(t._attachedController=e.uniqueId)};if(e.inputSource.gamepad){var o=function(e){i.squeezeComponent=e.getComponent("grasp"),i.squeezeComponent?i.onSqueezeButtonChangedObserver=i.squeezeComponent.onButtonStateChangedObservable.add((function(e){if(e.changes.pressed){var t=e.changes.pressed.current;n(t)}})):(i.selectionComponent=e.getMainComponent(),i.onButtonChangedObserver=i.selectionComponent.onButtonStateChangedObservable.add((function(e){if(e.changes.pressed){var t=e.changes.pressed.current;n(t)}})))};e.motionController?o(e.motionController):e.onMotionControllerInitObservable.add(o)}else{var a=function(e){i.xrController&&e.inputSource===i.xrController.inputSource&&i.pick&&t._isControllerReadyForNearInteraction(i.id)&&i.meshUnderPointer&&t._nearGrabPredicate(i.meshUnderPointer)&&(i.grabInteraction=!0,i.pickedPointVisualCue.isVisible=!1,t._scene.simulatePointerDown(i.pick,r),i.downTriggered=!0)},s=function(e){i.xrController&&e.inputSource===i.xrController.inputSource&&i.pick&&t._isControllerReadyForNearInteraction(i.id)&&(t._scene.simulatePointerUp(i.pick,r),i.grabInteraction=!1,i.pickedPointVisualCue.isVisible=!0,i.downTriggered=!1)};i.eventListeners={selectend:s,selectstart:a},this._xrSessionManager.session.addEventListener("selectstart",a),this._xrSessionManager.session.addEventListener("selectend",s)}},t.prototype._detachController=function(e){var t=this,i=this._controllers[e];if(i&&(i.squeezeComponent&&i.onSqueezeButtonChangedObserver&&i.squeezeComponent.onButtonStateChangedObservable.remove(i.onSqueezeButtonChangedObserver),i.selectionComponent&&i.onButtonChangedObserver&&i.selectionComponent.onButtonStateChangedObservable.remove(i.onButtonChangedObserver),i.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(i.onFrameObserver),i.eventListeners&&Object.keys(i.eventListeners).forEach((function(e){var r=i.eventListeners&&i.eventListeners[e];r&&t._xrSessionManager.session.removeEventListener(e,r)})),i.touchCollisionMesh.dispose(),i.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame((function(){if(i.downTriggered){var e={pointerId:i.id,pointerType:"xr-near"};t._scene.simulatePointerUp(new Fr,e)}})),i._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(i._worldScaleObserver),delete this._controllers[e],this._attachedController===e)){var r=Object.keys(this._controllers);r.length?this._attachedController=r[0]:this._attachedController=""}},t.prototype._generateNewTouchPointMesh=function(){var e=this._xrSessionManager.worldScalingFactor,t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Ih.DefaultUtilityLayer.utilityLayerScene:this._scene,i=Gh("PickSphere",{diameter:1*e},t);i.isVisible=!1,this._options.motionControllerOrbMaterial?i.material=this._options.motionControllerOrbMaterial:(this._options.motionControllerTouchMaterialSnippetUrl?Ll.ParseFromFileAsync("motionControllerTouchMaterial",this._options.motionControllerTouchMaterialSnippetUrl,t):Ll.ParseFromSnippetAsync("8RUNKL#3",t)).then((function(e){i.material=e})).catch((function(e){ae.Warn("Error creating touch material in WebXRNearInteraction: ".concat(e))}));var r=new Ln;r.setEasingMode(Rn.EASINGMODE_EASEINOUT);var n=new V(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius).scaleInPlace(e),o=this._controllerPickRadius*(4/3),a=new V(o,o,o).scaleInPlace(e),s=this._controllerPickRadius*(7/6),l=new V(s,s,s).scaleInPlace(e),c=.8*this._controllerPickRadius,u=new V(c,c,c).scaleInPlace(e),h=1.5*this._controllerPickRadius,d=[{frame:0,value:n},{frame:10,value:new V(h,h,h).scaleInPlace(e)},{frame:18,value:a}],p=[{frame:0,value:a},{frame:10,value:u},{frame:18,value:n}],f=[{frame:0,value:V.ZeroReadOnly},{frame:12,value:l},{frame:15,value:n}],_=[{frame:0,value:n},{frame:10,value:V.ZeroReadOnly},{frame:15,value:V.ZeroReadOnly}],m=new at("touch","scaling",60,at.ANIMATIONTYPE_VECTOR3,at.ANIMATIONLOOPMODE_CONSTANT),g=new at("release","scaling",60,at.ANIMATIONTYPE_VECTOR3,at.ANIMATIONLOOPMODE_CONSTANT),v=new at("hydrate","scaling",60,at.ANIMATIONTYPE_VECTOR3,at.ANIMATIONLOOPMODE_CONSTANT),y=new at("dehydrate","scaling",60,at.ANIMATIONTYPE_VECTOR3,at.ANIMATIONLOOPMODE_CONSTANT);return m.setEasingFunction(r),g.setEasingFunction(r),v.setEasingFunction(r),y.setEasingFunction(r),m.setKeys(d),g.setKeys(p),v.setKeys(f),y.setKeys(_),{touchCollisionMesh:i,touchCollisionMeshFunction:function(e){var r=e?m:g;t.beginDirectAnimation(i,[r],0,18,!1,1)},hydrateCollisionMeshFunction:function(e){var r=e?v:y;e&&(i.isVisible=!0),t.beginDirectAnimation(i,[r],0,15,!1,1,(function(){e||(i.isVisible=!1)}))}}},t.prototype._pickWithSphere=function(e,i,r,n){var o=new Fr;if(o.distance=1/0,e.touchCollisionMesh&&e.xrController)for(var a=e.touchCollisionMesh.position,s=io.CreateFromCenterAndRadius(a,i),l=0;l<r.meshes.length;l++){var c=r.meshes[l];if(n(c)&&this._controllerAvailablePredicate(c,e.xrController.uniqueId)){var u=t.PickMeshWithSphere(c,s);u&&u.hit&&u.distance<o.distance&&(o.hit=u.hit,o.pickedMesh=c,o.pickedPoint=u.pickedPoint,o.aimTransform=e.xrController.pointer,o.gripTransform=e.xrController.grip||null,o.originMesh=e.touchCollisionMesh,o.distance=u.distance,o.bu=u.bu,o.bv=u.bv,o.faceId=u.faceId,o.subMeshId=u.subMeshId)}}return o},t.PickMeshWithSphere=function(e,t,i){void 0===i&&(i=!1);var r=e.subMeshes,n=new Fr,o=e.getBoundingInfo();if(!e._generatePointsArray())return n;if(!e.subMeshes||!o)return n;if(!i&&!io.Intersects(o.boundingSphere,t))return n;var a,s,l,c,u=H.Vector3[0],h=H.Vector3[1],d=new hs(V.Zero(),V.Zero(),1),p=1/0,f=H.Vector3[2],_=H.Matrix[0];_.copyFrom(e.getWorldMatrix()),_.invert(),V.TransformCoordinatesToRef(t.center,_,f);for(var m=0;m<r.length;m++)r[m].projectToRef(f,e._positions,e.getIndices(),h),V.TransformCoordinatesToRef(h,e.getWorldMatrix(),h),a=V.Distance(h,t.center),l=V.Distance(h,e.getAbsolutePosition()),-1!==(s=V.Distance(t.center,e.getAbsolutePosition()))&&-1!==l&&l>s&&(a=0,h.copyFrom(t.center)),-1!==a&&a<p&&(p=a,hs.CreateFromToToRef(t.center,h,d),d.length=2*p,c=d.intersectsMesh(e),u.copyFrom(h));return p<t.radius&&(n.hit=!0,n.distance=p,n.pickedMesh=e,n.pickedPoint=u.clone(),c&&null!==c.bu&&null!==c.bv&&(n.faceId=c.faceId,n.subMeshId=c.subMeshId,n.bu=c.bu,n.bv=c.bv)),n},t._IdCounter=200,t.Name=Ss.NEAR_INTERACTION,t.Version=1,t}(As);xs.AddWebXRFeature(kg.Name,(function(e,t){return function(){return new kg(e,t)}}),kg.Version,!0);var Gg,zg=function(){function e(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}return e.prototype.update=function(e){},e}(),Wg=function(){},Hg=function(){function e(e,t){var i=this;if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new f,this._onSessionGranted=function(e){i._helper&&i._enterXRWithButtonIndex(0)},this.overlay=document.createElement("div"),this.overlay.classList.add("xr-button-overlay"),!t.ignoreSessionGrantedEvent&&navigator.xr&&navigator.xr.addEventListener("sessiongranted",this._onSessionGranted),"undefined"!=typeof window&&window.location&&"http:"===window.location.protocol&&"localhost"!==window.location.hostname)throw rr.Warn("WebXR can only be served over HTTPS"),new Error("WebXR can only be served over HTTPS");if(t.customButtons)this._buttons=t.customButtons;else{this.overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;";var r=t.sessionMode||"immersive-vr",n=t.referenceSpaceType||"local-floor",o=".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+("undefined"==typeof SVGSVGElement?"https://cdn.babylonjs.com/Assets/vrButton.png":"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";o+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';var a=document.createElement("style");a.appendChild(document.createTextNode(o)),document.getElementsByTagName("head")[0].appendChild(a);var s=document.createElement("button");s.className="babylonVRicon",s.title="".concat(r," - ").concat(n),this._buttons.push(new zg(s,r,n)),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",s.className="babylonVRicon"+(e===this?" vrdisplaypresenting":"")},this._updateButtons(null)}var l=e.getEngine().getInputElement();l&&l.parentNode&&(l.parentNode.appendChild(this.overlay),e.onDisposeObservable.addOnce((function(){i.dispose()})))}return e.prototype.setHelperAsync=function(e,t){return y(this,void 0,void 0,(function(){var i,r=this;return b(this,(function(n){switch(n.label){case 0:return this._helper=e,this._renderTarget=t,i=this._buttons.map((function(t){return e.sessionManager.isSessionSupportedAsync(t.sessionMode)})),e.onStateChangedObservable.add((function(e){e==Vu.NOT_IN_XR&&r._updateButtons(null)})),[4,Promise.all(i)];case 1:return n.sent().forEach((function(e,t){e?(r.overlay.appendChild(r._buttons[t].element),r._buttons[t].element.onclick=r._enterXRWithButtonIndex.bind(r,t)):rr.Warn('Session mode "'.concat(r._buttons[t].sessionMode,'" not supported in browser'))})),[2]}}))}))},e.CreateAsync=function(t,i,r){return y(this,void 0,void 0,(function(){var n;return b(this,(function(o){switch(o.label){case 0:return[4,(n=new e(t,r)).setHelperAsync(i,r.renderTarget||void 0)];case 1:return o.sent(),[2,n]}}))}))},e.prototype._enterXRWithButtonIndex=function(e){return void 0===e&&(e=0),y(this,void 0,void 0,(function(){var t,i,r;return b(this,(function(n){switch(n.label){case 0:return this._helper.state!=Vu.IN_XR?[3,2]:[4,this._helper.exitXRAsync()];case 1:return n.sent(),this._updateButtons(null),[3,6];case 2:if(this._helper.state!=Vu.NOT_IN_XR)return[3,6];n.label=3;case 3:return n.trys.push([3,5,,6]),[4,this._helper.enterXRAsync(this._buttons[e].sessionMode,this._buttons[e].referenceSpaceType,this._renderTarget,{optionalFeatures:this.options.optionalFeatures,requiredFeatures:this.options.requiredFeatures})];case 4:return n.sent(),this._updateButtons(this._buttons[e]),[3,6];case 5:return t=n.sent(),this._updateButtons(null),i=this._buttons[e].element,r=i.title,i.title="Error entering XR session : "+r,i.classList.add("xr-error"),this.options.onError&&this.options.onError(t),[3,6];case 6:return[2]}}))}))},e.prototype.dispose=function(){var e=this._scene.getEngine().getInputElement();e&&e.parentNode&&e.parentNode.contains(this.overlay)&&e.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear(),navigator.xr.removeEventListener("sessiongranted",this._onSessionGranted)},e.prototype._updateButtons=function(e){var t=this;this._activeButton=e,this._buttons.forEach((function(e){e.update(t._activeButton)})),this.activeButtonChangedObservable.notifyObservers(this._activeButton)},e}();function Xg(e){var t,i=0,r=Date.now();e.observableParameters=null!==(t=e.observableParameters)&&void 0!==t?t:{};var n=e.contextObservable.add((function(t){var o=Date.now(),a={startTime:r,currentTime:o,deltaTime:i=o-r,completeRate:i/e.timeout,payload:t};e.onTick&&e.onTick(a),e.breakCondition&&e.breakCondition()&&(e.contextObservable.remove(n),e.onAborted&&e.onAborted(a)),i>=e.timeout&&(e.contextObservable.remove(n),e.onEnded&&e.onEnded(a))}),e.observableParameters.mask,e.observableParameters.insertFirst,e.observableParameters.scope);return n}!function(e){e[e.INIT=0]="INIT",e[e.STARTED=1]="STARTED",e[e.ENDED=2]="ENDED"}(Gg||(Gg={}));var jg=function(){function e(e){var t,i,r=this;this.onEachCountObservable=new f,this.onTimerAbortedObservable=new f,this.onTimerEndedObservable=new f,this.onStateChangedObservable=new f,this._observer=null,this._breakOnNextTick=!1,this._tick=function(e){var t=Date.now();r._timer=t-r._startTime;var i={startTime:r._startTime,currentTime:t,deltaTime:r._timer,completeRate:r._timer/r._timeToEnd,payload:e},n=r._breakOnNextTick||r._breakCondition(i);n||r._timer>=r._timeToEnd?r._stop(i,n):r.onEachCountObservable.notifyObservers(i)},this._setState(Gg.INIT),this._contextObservable=e.contextObservable,this._observableParameters=null!==(t=e.observableParameters)&&void 0!==t?t:{},this._breakCondition=null!==(i=e.breakCondition)&&void 0!==i?i:function(){return!1},this._timeToEnd=e.timeout,e.onEnded&&this.onTimerEndedObservable.add(e.onEnded),e.onTick&&this.onEachCountObservable.add(e.onTick),e.onAborted&&this.onTimerAbortedObservable.add(e.onAborted)}return Object.defineProperty(e.prototype,"breakCondition",{set:function(e){this._breakCondition=e},enumerable:!1,configurable:!0}),e.prototype.clearObservables=function(){this.onEachCountObservable.clear(),this.onTimerAbortedObservable.clear(),this.onTimerEndedObservable.clear(),this.onStateChangedObservable.clear()},e.prototype.start=function(e){if(void 0===e&&(e=this._timeToEnd),this._state===Gg.STARTED)throw new Error("Timer already started. Please stop it before starting again");this._timeToEnd=e,this._startTime=Date.now(),this._timer=0,this._observer=this._contextObservable.add(this._tick,this._observableParameters.mask,this._observableParameters.insertFirst,this._observableParameters.scope),this._setState(Gg.STARTED)},e.prototype.stop=function(){this._state===Gg.STARTED&&(this._breakOnNextTick=!0)},e.prototype.dispose=function(){this._observer&&this._contextObservable.remove(this._observer),this.clearObservables()},e.prototype._setState=function(e){this._state=e,this.onStateChangedObservable.notifyObservers(this._state)},e.prototype._stop=function(e,t){void 0===t&&(t=!1),this._contextObservable.remove(this._observer),this._setState(Gg.ENDED),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)},e}(),Yg=function(e){function t(t,i){var r=e.call(this,t)||this;return r._options=i,r._controllers={},r._snappedToPoint=!1,r._cachedColor4White=new J(1,1,1,1),r._tmpRay=new hs(new V,new V),r._tmpVector=new V,r._tmpQuaternion=new G,r._worldScaleObserver=null,r.skipNextTeleportation=!1,r.backwardsMovementEnabled=!0,r.backwardsTeleportationDistance=.7,r.parabolicCheckRadius=5,r.parabolicRayEnabled=!0,r.straightRayEnabled=!0,r.rotationAngle=Math.PI/8,r.onTargetMeshPositionUpdatedObservable=new f,r.teleportationEnabled=!0,r._rotationEnabled=!0,r.onBeforeCameraTeleportRotation=new f,r.onAfterCameraTeleportRotation=new f,r._attachController=function(e){if(!(r._controllers[e.uniqueId]||r._options.forceHandedness&&e.inputSource.handedness!==r._options.forceHandedness)){r._controllers[e.uniqueId]={xrController:e,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0,blocked:!1,initialHit:!1,mainComponentUsed:!1}};var t=r._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){var i=function(){if(e.motionController){var i=e.motionController.getComponentOfType(Rg.THUMBSTICK_TYPE)||e.motionController.getComponentOfType(Rg.TOUCHPAD_TYPE);if(!i||r._options.useMainComponentOnly){var n=e.motionController.getMainComponent();if(!n)return;t.teleportationState.mainComponentUsed=!0,t.teleportationComponent=n,t.onButtonChangedObserver=n.onButtonStateChangedObservable.add((function(){if(r.teleportationEnabled){var i=function(){t.teleportationState.forward=!0,t.teleportationState.initialHit=!1,r._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=r._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,Xg({timeout:r._options.timeToTeleport||3e3,contextObservable:r._xrSessionManager.onXRFrameObservable,breakCondition:function(){return!n.pressed},onEnded:function(){r._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&r._teleportForward(e.uniqueId)}})};n.changes.pressed&&(n.changes.pressed.current?r._options.timeToTeleportStart?Xg({timeout:r._options.timeToTeleportStart,contextObservable:r._xrSessionManager.onXRFrameObservable,onEnded:function(){n.pressed&&i()}}):i():(t.teleportationState.forward=!1,r._currentTeleportationControllerId=""))}}))}else t.teleportationComponent=i,t.onAxisChangedObserver=i.onAxisValueChangedObservable.add((function(i){if(i.y<=.7&&t.teleportationState.backwards&&(t.teleportationState.backwards=!1),i.y>.7&&!t.teleportationState.forward&&r.backwardsMovementEnabled&&!r.snapPointsOnly&&!t.teleportationState.backwards){t.teleportationState.backwards=!0,r._tmpQuaternion.copyFrom(r._options.xrInput.xrCamera.rotationQuaternion),r._tmpQuaternion.toEulerAnglesToRef(r._tmpVector),r._tmpVector.x=0,r._tmpVector.z=0,G.FromEulerVectorToRef(r._tmpVector,r._tmpQuaternion),r._tmpVector.set(0,0,r.backwardsTeleportationDistance*(r._xrSessionManager.scene.useRightHandedSystem?1:-1)),r._tmpVector.rotateByQuaternionToRef(r._tmpQuaternion,r._tmpVector),r._tmpVector.addInPlace(r._options.xrInput.xrCamera.position),r._tmpRay.origin.copyFrom(r._tmpVector),r._tmpRay.length=r._options.xrInput.xrCamera.realWorldHeight+.1,r._tmpRay.direction.set(0,-1,0);var n=r._xrSessionManager.scene.pickWithRay(r._tmpRay,(function(e){return-1!==r._floorMeshes.indexOf(e)}));n&&n.pickedPoint&&(r._options.xrInput.xrCamera.position.x=n.pickedPoint.x,r._options.xrInput.xrCamera.position.z=n.pickedPoint.z)}if(i.y<-.7&&!r._currentTeleportationControllerId&&!t.teleportationState.rotating&&r.teleportationEnabled&&(t.teleportationState.forward=!0,r._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=r._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),i.x){if(t.teleportationState.forward)r._currentTeleportationControllerId===t.xrController.uniqueId&&(r.rotationEnabled?setTimeout((function(){t.teleportationState.currentRotation=Math.atan2(i.x,i.y*(r._xrSessionManager.scene.useRightHandedSystem?1:-1))})):t.teleportationState.currentRotation=0);else if(!t.teleportationState.rotating&&Math.abs(i.x)>.7){t.teleportationState.rotating=!0;var o=r.rotationAngle*(i.x>0?1:-1)*(r._xrSessionManager.scene.useRightHandedSystem?-1:1);r.onBeforeCameraTeleportRotation.notifyObservers(o),G.FromEulerAngles(0,o,0).multiplyToRef(r._options.xrInput.xrCamera.rotationQuaternion,r._options.xrInput.xrCamera.rotationQuaternion),r.onAfterCameraTeleportRotation.notifyObservers(r._options.xrInput.xrCamera.rotationQuaternion)}}else t.teleportationState.rotating=!1;0===i.x&&0===i.y&&(t.teleportationState.blocked&&(t.teleportationState.blocked=!1,r._setTargetMeshVisibility(!1)),t.teleportationState.forward&&r._teleportForward(e.uniqueId))}))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((function(){i()}))}else{t.teleportationState.mainComponentUsed=!0;var n=!1,o=function(){r._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.forward=!0,t.teleportationState.initialHit=!1,t.teleportationState.baseRotation=r._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,Xg({timeout:r._options.timeToTeleport||3e3,contextObservable:r._xrSessionManager.onXRFrameObservable,onEnded:function(){r._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&r._teleportForward(e.uniqueId)}})};r._xrSessionManager.scene.onPointerObservable.add((function(e){e.type===Gr.POINTERDOWN?(n=!1,r._options.timeToTeleportStart?Xg({timeout:r._options.timeToTeleportStart,contextObservable:r._xrSessionManager.onXRFrameObservable,onEnded:function(){r._currentTeleportationControllerId===t.xrController.uniqueId&&o()},breakCondition:function(){return!!n&&(n=!1,!0)}}):o()):e.type===Gr.POINTERUP&&(n=!0,t.teleportationState.forward=!1,r._currentTeleportationControllerId="")}))}}},r._colorArray=Array(24).fill(r._cachedColor4White),r._options.teleportationTargetMesh||r._createDefaultTargetMesh(),r._floorMeshes=r._options.floorMeshes||[],r._snapToPositions=r._options.snapPositions||[],r._blockedRayColor=r._options.blockedRayColor||new J(1,0,0,.75),r._setTargetMeshVisibility(!1),r.onBeforeCameraTeleport=i.xrInput.xrCamera.onBeforeCameraTeleport,r.onAfterCameraTeleport=i.xrInput.xrCamera.onAfterCameraTeleport,r.parabolicCheckRadius*=r._xrSessionManager.worldScalingFactor,r._worldScaleObserver=t.onWorldScaleFactorChangedObservable.add((function(e){var t;r.parabolicCheckRadius=r.parabolicCheckRadius/e.previousScaleFactor*e.newScaleFactor,null===(t=r._options.teleportationTargetMesh)||void 0===t||t.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor)})),r}return m(t,e),Object.defineProperty(t.prototype,"rotationEnabled",{get:function(){return this._rotationEnabled},set:function(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){var t=this._options.teleportationTargetMesh.getChildMeshes(!1,(function(e){return"rotationCone"===e.name}));t[0]&&t[0].setEnabled(e)}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"teleportationTargetMesh",{get:function(){return this._options.teleportationTargetMesh||null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"snapPointsOnly",{get:function(){return!!this._options.snapPointsOnly},set:function(e){this._options.snapPointsOnly=e},enumerable:!1,configurable:!0}),t.prototype.addFloorMesh=function(e){this._floorMeshes.push(e)},t.prototype.addBlockerMesh=function(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[],this._options.pickBlockerMeshes.push(e)},t.prototype.addSnapPoint=function(e){this._snapToPositions.push(e)},t.prototype.attach=function(){var t=this;return!!e.prototype.attach.call(this)&&(this._currentTeleportationControllerId="",this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(function(e){t._detachController(e.uniqueId)})),!0)},t.prototype.detach=function(){var t=this;return!!e.prototype.detach.call(this)&&(Object.keys(this._controllers).forEach((function(e){t._detachController(e)})),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0)},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver)},t.prototype.removeFloorMesh=function(e){var t=this._floorMeshes.indexOf(e);-1!==t&&this._floorMeshes.splice(t,1)},t.prototype.removeBlockerMesh=function(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];var t=this._options.pickBlockerMeshes.indexOf(e);-1!==t&&this._options.pickBlockerMeshes.splice(t,1)},t.prototype.removeFloorMeshByName=function(e){var t=this._xrSessionManager.scene.getMeshByName(e);t&&this.removeFloorMesh(t)},t.prototype.removeSnapPoint=function(e){var t=this._snapToPositions.indexOf(e);if(-1===t)for(var i=0;i<this._snapToPositions.length;++i)if(this._snapToPositions[i].equals(e)){t=i;break}return-1!==t&&(this._snapToPositions.splice(t,1),!0)},t.prototype.setSelectionFeature=function(e){this._selectionFeature=e},t.prototype._onXRFrame=function(e){var t=this,i=this._xrSessionManager.currentFrame,r=this._xrSessionManager.scene;if(this.attach&&i){var n=this._options.teleportationTargetMesh;if(this._currentTeleportationControllerId){if(!n)return;n.rotationQuaternion=n.rotationQuaternion||new G;var o=this._controllers[this._currentTeleportationControllerId];if(o&&o.teleportationState.forward){G.RotationYawPitchRollToRef(o.teleportationState.currentRotation+o.teleportationState.baseRotation,0,0,n.rotationQuaternion);var a=!1,s="transient-pointer"!==o.xrController.inputSource.targetRayMode;if(o.xrController.getWorldPointerRayToRef(this._tmpRay),this.straightRayEnabled){var l=(c=r.pickWithRay(this._tmpRay,(function(e){if(t._options.blockerMeshesPredicate&&t._options.blockerMeshesPredicate(e))return!0;if(t._options.blockAllPickableMeshes&&e.isPickable)return!0;if(t._options.pickBlockerMeshes&&-1!==t._options.pickBlockerMeshes.indexOf(e))return!0;var i=t._floorMeshes.indexOf(e);return-1!==i&&t._floorMeshes[i].absolutePosition.y<t._options.xrInput.xrCamera.globalPosition.y})))&&c.pickedMesh&&-1!==this._floorMeshes.indexOf(c.pickedMesh);if(c&&c.pickedMesh&&!l)return o.teleportationState.mainComponentUsed&&!o.teleportationState.initialHit?void(o.teleportationState.forward=!1):(o.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1,!1,s),void this._showParabolicPath(c));c&&c.pickedPoint&&(o.teleportationState.initialHit=!0,o.teleportationState.blocked=!1,a=!0,this._setTargetMeshPosition(c),this._setTargetMeshVisibility(!0,!1,s),this._showParabolicPath(c))}if(this.parabolicRayEnabled&&!a){var c,u=o.xrController.pointer.rotationQuaternion.toEulerAngles().x,h=Math.PI/2-Math.abs(u)+1,d=this.parabolicCheckRadius*h;if(this._tmpRay.origin.addToRef(this._tmpRay.direction.scale(2*d),this._tmpVector),this._tmpVector.y=this._tmpRay.origin.y,this._tmpRay.origin.addInPlace(this._tmpRay.direction.scale(d)),this._tmpVector.subtractToRef(this._tmpRay.origin,this._tmpRay.direction),this._tmpRay.direction.normalize(),l=(c=r.pickWithRay(this._tmpRay,(function(e){return!(!t._options.blockerMeshesPredicate||!t._options.blockerMeshesPredicate(e))||!(!t._options.blockAllPickableMeshes||!e.isPickable)||!(!t._options.pickBlockerMeshes||-1===t._options.pickBlockerMeshes.indexOf(e))||-1!==t._floorMeshes.indexOf(e)})))&&c.pickedMesh&&-1!==this._floorMeshes.indexOf(c.pickedMesh),c&&c.pickedMesh&&!l)return o.teleportationState.mainComponentUsed&&!o.teleportationState.initialHit?void(o.teleportationState.forward=!1):(o.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1,!1,s),void this._showParabolicPath(c));c&&c.pickedPoint&&(o.teleportationState.initialHit=!0,o.teleportationState.blocked=!1,a=!0,this._setTargetMeshPosition(c),this._setTargetMeshVisibility(!0,!1,s),this._showParabolicPath(c))}this._setTargetMeshVisibility(a,!1,s)}else this._setTargetMeshVisibility(!1,!1,!0)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1,!1,!0)}},t.prototype._createDefaultTargetMesh=function(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};var e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Ih.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=ih("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{var i=new Gu("teleportationPlaneDynamicTexture",512,e,!0);i.hasAlpha=!0;var r=i.getContext();r.beginPath(),r.arc(256,256,200,0,2*Math.PI,!1),r.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",r.fill(),r.lineWidth=10,r.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",r.stroke(),r.closePath(),i.update();var n=new Uu("teleportationPlaneMaterial",e);n.diffuseTexture=i,t.material=n}var o=sh("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(o.isPickable=!1,o.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){var a=new at("animationInnerCircle","position.y",30,at.ANIMATIONTYPE_FLOAT,at.ANIMATIONLOOPMODE_CYCLE),s=[];s.push({frame:0,value:0}),s.push({frame:30,value:.4}),s.push({frame:60,value:0}),a.setKeys(s);var l=new Un;l.setEasingMode(Rn.EASINGMODE_EASEINOUT),a.setEasingFunction(l),o.animations=[],o.animations.push(a),e.beginAnimation(o,0,60,!0)}var c=xh("rotationCone",{diameterTop:0,tessellation:4},e);if(c.isPickable=!1,c.scaling.set(.5,.12,.2),c.rotate(_n.X,Math.PI/2),c.position.z=.6,c.parent=o,this._options.defaultTargetMeshOptions.torusArrowMaterial)o.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,c.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{var u=new Uu("torusConsMat",e);u.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,u.disableLighting?u.emissiveColor=new Z(.3,.3,1):u.diffuseColor=new Z(.3,.3,1),u.alpha=.9,o.material=u,c.material=u,this._teleportationRingMaterial=u}void 0!==this._options.renderingGroupId&&(t.renderingGroupId=this._options.renderingGroupId,o.renderingGroupId=this._options.renderingGroupId,c.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._options.teleportationTargetMesh.scaling.setAll(this._xrSessionManager.worldScalingFactor),this._setTargetMeshVisibility(!1)},t.prototype._detachController=function(e){var t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])},t.prototype._findClosestSnapPointWithRadius=function(e,t){void 0===t&&(t=this._options.snapToPositionRadius||.8);var i=null,r=Number.MAX_VALUE;if(this._snapToPositions.length){var n=t*t;this._snapToPositions.forEach((function(t){var o=V.DistanceSquared(t,e);o<=n&&o<r&&(r=o,i=t)}))}return i},t.prototype._setTargetMeshPosition=function(e){var t=e.pickedPoint;if(this._options.teleportationTargetMesh&&t){var i=this._findClosestSnapPointWithRadius(t);this._snappedToPoint=!!i,this.snapPointsOnly&&!this._snappedToPoint&&this._teleportationRingMaterial?this._teleportationRingMaterial.diffuseColor.set(1,.3,.3):this.snapPointsOnly&&this._snappedToPoint&&this._teleportationRingMaterial&&this._teleportationRingMaterial.diffuseColor.set(.3,.3,1),this._options.teleportationTargetMesh.position.copyFrom(i||t),this._options.teleportationTargetMesh.position.y+=.01,this.onTargetMeshPositionUpdatedObservable.notifyObservers(e)}},t.prototype._setTargetMeshVisibility=function(e,t,i){this._options.teleportationTargetMesh&&(this._options.teleportationTargetMesh.isVisible!==e||t)&&(this._options.teleportationTargetMesh.isVisible=e,this._options.teleportationTargetMesh.getChildren(void 0,!1).forEach((function(t){t.isVisible=e})),e?this._selectionFeature&&i&&this._selectionFeature.detach():(this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null),this._selectionFeature&&i&&this._selectionFeature.attach()))},t.prototype._disposeBezierCurve=function(){this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null)},t.prototype._showParabolicPath=function(e){if(e.pickedPoint&&this._currentTeleportationControllerId){var t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Ih.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],r=Cn.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),n=i.teleportationState.blocked?this._blockedRayColor:void 0,o=this._colorArray.fill(n||this._cachedColor4White),a=r.getPoints();a.shift(),a.shift(),this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(r.getPoints(),e):this._quadraticBezierCurve=fd("teleportation path line",{points:a,instance:this._quadraticBezierCurve,updatable:!0,colors:o},t),this._quadraticBezierCurve.isPickable=!1,void 0!==this._options.renderingGroupId&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}},t.prototype._teleportForward=function(e){var t=this._controllers[e];if(t&&t.teleportationState.forward&&this.teleportationEnabled&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",!this.snapPointsOnly||this._snappedToPoint))if(this.skipNextTeleportation)this.skipNextTeleportation=!1;else if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){var i=this._options.xrInput.xrCamera.realWorldHeight;this.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=i,G.FromEulerAngles(0,t.teleportationState.currentRotation-(this._xrSessionManager.scene.useRightHandedSystem?Math.PI:0),0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)}},t.Name=Ss.TELEPORTATION,t.Version=1,t}(As);xs.AddWebXRFeature(Yg.Name,(function(e,t){return function(){return new Yg(e,t)}}),Yg.Version,!0);var Kg=function(){},Qg=function(){function e(){}return e.CreateAsync=function(t,i){void 0===i&&(i={});var r=new e;if(t.onDisposeObservable.addOnce((function(){r.dispose()})),!i.disableDefaultUI){var n=g({renderTarget:r.renderTarget},i.uiOptions||{});i.optionalFeatures&&("boolean"==typeof i.optionalFeatures?n.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:n.optionalFeatures=i.optionalFeatures),r.enterExitUI=new Hg(t,n)}return Cg.CreateAsync(t).then((function(e){if(r.baseExperience=e,i.ignoreNativeCameraTransformation&&(r.baseExperience.camera.compensateOnFirstFrame=!1),r.input=new Ug(e.sessionManager,e.camera,g({controllerOptions:{renderingGroupId:i.renderingGroupId}},i.inputOptions||{})),!i.disablePointerSelection){var t=g(g({},i.pointerSelectionOptions),{xrInput:r.input,renderingGroupId:i.renderingGroupId});r.pointerSelection=r.baseExperience.featuresManager.enableFeature(Vg.Name,i.useStablePlugins?"stable":"latest",t),i.disableTeleportation||(r.teleportation=r.baseExperience.featuresManager.enableFeature(Yg.Name,i.useStablePlugins?"stable":"latest",g({floorMeshes:i.floorMeshes,xrInput:r.input,renderingGroupId:i.renderingGroupId},i.teleportationOptions)),r.teleportation.setSelectionFeature(r.pointerSelection))}return i.disableNearInteraction||(r.nearInteraction=r.baseExperience.featuresManager.enableFeature(kg.Name,i.useStablePlugins?"stable":"latest",g({xrInput:r.input,farInteractionFeature:r.pointerSelection,renderingGroupId:i.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0},i.nearInteractionOptions))),i.disableHandTracking||r.baseExperience.featuresManager.enableFeature(Kl.Name,i.useStablePlugins?"stable":"latest",g({xrInput:r.input},i.handSupportOptions),void 0,!1),r.renderTarget=r.baseExperience.sessionManager.getWebXRRenderTarget(i.outputCanvasOptions),i.disableDefaultUI?void 0:r.enterExitUI.setHelperAsync(r.baseExperience,r.renderTarget)})).then((function(){return r})).catch((function(e){return ae.Error("Error initializing XR"),ae.Error(e),r}))},e.prototype.dispose=function(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()},e}(),qg=!0;function Zg(e){for(;e.firstChild;)e.removeChild(e.firstChild);e.srcObject=null,e.src="",e.removeAttribute("src")}pn.prototype.createDefaultLight=function(e){if(void 0===e&&(e=!1),e&&this.lights)for(var t=0;t<this.lights.length;t++)this.lights[t].dispose();0===this.lights.length&&new Ch("default light",V.Up(),this)},pn.prototype.createDefaultCamera=function(e,t,i){if(void 0===e&&(e=!1),void 0===t&&(t=!1),void 0===i&&(i=!1),t&&this.activeCamera&&(this.activeCamera.dispose(),this.activeCamera=null),!this.activeCamera){var r=this.getWorldExtends((function(e){return e.isVisible&&e.isEnabled()})),n=r.max.subtract(r.min),o=r.min.add(n.scale(.5)),a=void 0,s=1.5*n.length();if(isFinite(s)||(s=1,o.copyFromFloats(0,0,0)),e){var l=new Nc("default camera",-Math.PI/2,Math.PI/2,s,o,this);l.lowerRadiusLimit=.01*s,l.wheelPrecision=100/s,a=l}else{var c=new Oc("default camera",new V(o.x,o.y,-s),this);c.setTarget(o),a=c}a.minZ=.01*s,a.maxZ=1e3*s,a.speed=.2*s,this.activeCamera=a,i&&a.attachControl()}},pn.prototype.createDefaultCameraOrLight=function(e,t,i){void 0===e&&(e=!1),void 0===t&&(t=!1),void 0===i&&(i=!1),this.createDefaultLight(t),this.createDefaultCamera(e,t,i)},pn.prototype.createDefaultSkybox=function(e,t,i,r,n){if(void 0===t&&(t=!1),void 0===i&&(i=1e3),void 0===r&&(r=0),void 0===n&&(n=!0),!e)return ae.Warn("Can not create default skybox without environment texture."),null;n&&e&&(this.environmentTexture=e);var o=Uh("hdrSkyBox",{size:i},this);if(t){var a=new rg("skyBox",this);a.backFaceCulling=!1,a.reflectionTexture=e.clone(),a.reflectionTexture&&(a.reflectionTexture.coordinatesMode=Ja.SKYBOX_MODE),a.microSurface=1-r,a.disableLighting=!0,a.twoSidedLighting=!0,o.material=a}else{var s=new Uu("skyBox",this);s.backFaceCulling=!1,s.reflectionTexture=e.clone(),s.reflectionTexture&&(s.reflectionTexture.coordinatesMode=Ja.SKYBOX_MODE),s.disableLighting=!0,o.material=s}return o.isPickable=!1,o.infiniteDistance=!0,o.ignoreCameraMaxZ=!0,o},pn.prototype.createDefaultEnvironment=function(e){return wm?new wm(e,this):null},pn.prototype.createDefaultVRExperience=function(e){return void 0===e&&(e={}),new dh(this,e)},pn.prototype.createDefaultXRExperienceAsync=function(e){return void 0===e&&(e={}),Qg.CreateAsync(this,e).then((function(e){return e}))};var Jg=function(e){function t(t,i,r,n,o,a,s,l,c){void 0===n&&(n=!1),void 0===o&&(o=!1),void 0===a&&(a=Ja.TRILINEAR_SAMPLINGMODE),void 0===s&&(s={}),void 0===c&&(c=u.TEXTUREFORMAT_RGBA);var h=e.call(this,null,r,!n,o)||this;h._externalTexture=null,h._onUserActionRequestedObservable=null,h._stillImageCaptured=!1,h._displayingPosterTexture=!1,h._frameId=-1,h._currentSrc=null,h._errorFound=!1,h.isVideo=!0,h._resizeInternalTexture=function(){var e;null!=h._texture&&h._texture.dispose(),!h._getEngine().needPOTTextures||rr.IsExponentOfTwo(h.video.videoWidth)&&rr.IsExponentOfTwo(h.video.videoHeight)?(h.wrapU=Ja.WRAP_ADDRESSMODE,h.wrapV=Ja.WRAP_ADDRESSMODE):(h.wrapU=Ja.CLAMP_ADDRESSMODE,h.wrapV=Ja.CLAMP_ADDRESSMODE,h._generateMipMaps=!1),h._texture=h._getEngine().createDynamicTexture(h.video.videoWidth,h.video.videoHeight,h._generateMipMaps,h.samplingMode),h._texture.format=null!==(e=h._format)&&void 0!==e?e:u.TEXTUREFORMAT_RGBA,h._frameId=-1,h._updateInternalTexture()},h._createInternalTexture=function(){if(null!=h._texture){if(!h._displayingPosterTexture)return;h._displayingPosterTexture=!1}if(h.video.addEventListener("resize",h._resizeInternalTexture),h._resizeInternalTexture(),h.video.autoplay||h._settings.poster||h._settings.independentVideoSource)h._updateInternalTexture(),h.onLoadObservable.hasObservers()&&h.onLoadObservable.notifyObservers(h);else{var e=h.video.onplaying,t=h.video.muted;h.video.muted=!0,h.video.onplaying=function(){h.video.muted=t,h.video.onplaying=e,h._updateInternalTexture(),h._errorFound||h.video.pause(),h.onLoadObservable.hasObservers()&&h.onLoadObservable.notifyObservers(h)},h._handlePlay()}},h._reset=function(){null!=h._texture&&(h._displayingPosterTexture||(h._texture.dispose(),h._texture=null))},h._updateInternalTexture=function(){if(null!=h._texture&&!(h.video.readyState<h.video.HAVE_CURRENT_DATA||h._displayingPosterTexture)){var e=h.getScene().getFrameId();h._frameId!==e&&(h._frameId=e,h._getEngine().updateVideoTexture(h._texture,h._externalTexture?h._externalTexture:h.video,h._invertY))}},h._settings=g({autoPlay:!0,loop:!0,autoUpdateTexture:!0},s),h._onError=l,h._generateMipMaps=n,h._initialSamplingMode=a,h.autoUpdateTexture=h._settings.autoUpdateTexture,h._currentSrc=i,h.name=t||h._getName(i),h.video=h._getVideo(i);var d=h._engine,p=null==d?void 0:d.createExternalTexture;p&&(h._externalTexture=p.call(d,h.video)),h._settings.independentVideoSource||(h._settings.poster&&(h.video.poster=h._settings.poster),void 0!==h._settings.autoPlay&&(h.video.autoplay=h._settings.autoPlay),void 0!==h._settings.loop&&(h.video.loop=h._settings.loop),void 0!==h._settings.muted&&(h.video.muted=h._settings.muted),h.video.setAttribute("playsinline",""),h.video.addEventListener("paused",h._updateInternalTexture),h.video.addEventListener("seeked",h._updateInternalTexture),h.video.addEventListener("loadeddata",h._updateInternalTexture),h.video.addEventListener("emptied",h._reset),h._settings.autoPlay&&h._handlePlay()),h._createInternalTextureOnEvent=h._settings.poster&&!h._settings.autoPlay?"play":"canplay",h.video.addEventListener(h._createInternalTextureOnEvent,h._createInternalTexture),h._format=c;var f=h.video.readyState>=h.video.HAVE_CURRENT_DATA;return!h._settings.poster||h._settings.autoPlay&&f?f&&h._createInternalTexture():(h._texture=h._getEngine().createTexture(h._settings.poster,!1,!h.invertY,r),h._displayingPosterTexture=!0),h}return m(t,e),Object.defineProperty(t.prototype,"onUserActionRequestedObservable",{get:function(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new f),this._onUserActionRequestedObservable},enumerable:!1,configurable:!0}),t.prototype._processError=function(e){this._errorFound=!0,this._onError?this._onError(null==e?void 0:e.message):ae.Error(null==e?void 0:e.message)},t.prototype._handlePlay=function(){var e=this;this._errorFound=!1,this.video.play().catch((function(t){if("NotAllowedError"===(null==t?void 0:t.name)){if(e._onUserActionRequestedObservable&&e._onUserActionRequestedObservable.hasObservers())return void e._onUserActionRequestedObservable.notifyObservers(e);if(!e.video.muted)return ae.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),e.video.muted=!0,e._errorFound=!1,void e.video.play().catch((function(t){e._processError(t)}))}e._processError(t)}))},t.prototype.getClassName=function(){return"VideoTexture"},t.prototype._getName=function(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e},t.prototype._getVideo=function(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return rr.SetCorsBehavior(e.currentSrc,e),e;var t=document.createElement("video");return"string"==typeof e?(rr.SetCorsBehavior(e,t),t.src=e):(rr.SetCorsBehavior(e[0],t),e.forEach((function(e){var i=document.createElement("source");i.src=e,t.appendChild(i)}))),this.onDisposeObservable.addOnce((function(){Zg(t)})),t},t.prototype._rebuild=function(){this.update()},t.prototype.update=function(){this.autoUpdateTexture&&this.updateTexture(!0)},t.prototype.updateTexture=function(e){e&&(this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture()))},Object.defineProperty(t.prototype,"externalTexture",{get:function(){return this._externalTexture},enumerable:!1,configurable:!0}),t.prototype.updateURL=function(e){this.video.src=e,this._currentSrc=e},t.prototype.clone=function(){return new t(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)},t.prototype.dispose=function(){var t;e.prototype.dispose.call(this),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._settings.independentVideoSource||(this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("loadeddata",this._updateInternalTexture),this.video.removeEventListener("emptied",this._reset),this.video.removeEventListener("resize",this._resizeInternalTexture),this.video.pause()),null===(t=this._externalTexture)||void 0===t||t.dispose()},t.CreateFromStreamAsync=function(e,i,r,n){void 0===n&&(n=!0);var o=e.getEngine().createVideoElement(r);return e.getEngine()._badOS&&(document.body.appendChild(o),o.style.transform="scale(0.0001, 0.0001)",o.style.opacity="0",o.style.position="fixed",o.style.bottom="0px",o.style.right="0px"),o.setAttribute("autoplay",""),o.setAttribute("muted","true"),o.setAttribute("playsinline",""),o.muted=!0,o.isNative||(void 0!==o.mozSrcObject?o.mozSrcObject=i:"object"==typeof o.srcObject?o.srcObject=i:o.src=window.URL&&window.URL.createObjectURL(i)),new Promise((function(i){var r=function(){var a=new t("video",o,e,!0,n,void 0,void 0,void 0,u.TEXTUREFORMAT_RGB);e.getEngine()._badOS&&a.onDisposeObservable.addOnce((function(){o.remove()})),a.onDisposeObservable.addOnce((function(){Zg(o)})),i(a),o.removeEventListener("playing",r)};o.addEventListener("playing",r),o.play()}))},t.CreateFromWebCamAsync=function(e,t,i,r){return void 0===i&&(i=!1),void 0===r&&(r=!0),y(this,void 0,void 0,(function(){var n,o;return b(this,(function(a){switch(a.label){case 0:return navigator.mediaDevices?[4,navigator.mediaDevices.getUserMedia({video:t,audio:i})]:[3,3];case 1:return n=a.sent(),[4,this.CreateFromStreamAsync(e,n,t,r)];case 2:return(o=a.sent()).onDisposeObservable.addOnce((function(){n.getTracks().forEach((function(e){e.stop()}))})),[2,o];case 3:return[2,Promise.reject("No support for userMedia on this device")]}}))}))},t.CreateFromWebCam=function(e,t,i,r,n){void 0===r&&(r=!1),void 0===n&&(n=!0),this.CreateFromWebCamAsync(e,i,r,n).then((function(e){t&&t(e)})).catch((function(e){ae.Error(e.name)}))},v([Ie("settings")],t.prototype,"_settings",void 0),v([Ie("src")],t.prototype,"_currentSrc",void 0),v([Ie()],t.prototype,"isVideo",void 0),t}(Ja);Ja._CreateVideoTexture=function(e,t,i,r,n,o,a,s,l){return void 0===r&&(r=!1),void 0===n&&(n=!1),void 0===o&&(o=Ja.TRILINEAR_SAMPLINGMODE),void 0===a&&(a={}),void 0===l&&(l=u.TEXTUREFORMAT_RGBA),new Jg(e,t,i,r,n,o,a,s,l)},a("BABYLON.VideoTexture",Jg);var $g=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),Object.defineProperty(t.prototype,"videoTexture",{get:function(){return this._texture},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"videoMode",{get:function(){return this.textureMode},set:function(e){this.textureMode=e},enumerable:!1,configurable:!0}),t.prototype._initTexture=function(e,t,i){var r=this,n={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},o=new Jg((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,Ja.TRILINEAR_SAMPLINGMODE,n);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add((function(e){var t;(null===(t=e.pickInfo)||void 0===t?void 0:t.pickedMesh)===r.mesh&&r._texture.video.play()}),Gr.POINTERDOWN)),this._textureObserver=o.onLoadObservable.add((function(){r.onLoadObservable.notifyObservers()})),o},t.prototype.dispose=function(t,i){void 0===i&&(i=!1),this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),e.prototype.dispose.call(this,t,i)},t.MODE_MONOSCOPIC=Bm.MODE_MONOSCOPIC,t.MODE_TOPBOTTOM=Bm.MODE_TOPBOTTOM,t.MODE_SIDEBYSIDE=Bm.MODE_SIDEBYSIDE,t}(Bm),ev=function(){function e(e){this.engine=e,this._captureGPUFrameTime=!1,this._captureShaderCompilationTime=!1,this._shaderCompilationTime=new an,this._onBeginFrameObserver=null,this._onEndFrameObserver=null,this._onBeforeShaderCompilationObserver=null,this._onAfterShaderCompilationObserver=null}return Object.defineProperty(e.prototype,"gpuFrameTimeCounter",{get:function(){return this.engine.getGPUFrameTimeCounter()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"captureGPUFrameTime",{get:function(){return this._captureGPUFrameTime},set:function(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,this.engine.captureGPUFrameTime(e))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"shaderCompilationTimeCounter",{get:function(){return this._shaderCompilationTime},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"captureShaderCompilationTime",{get:function(){return this._captureShaderCompilationTime},set:function(e){var t=this;e!==this._captureShaderCompilationTime&&(this._captureShaderCompilationTime=e,e?(this._onBeforeShaderCompilationObserver=this.engine.onBeforeShaderCompilationObservable.add((function(){t._shaderCompilationTime.fetchNewFrame(),t._shaderCompilationTime.beginMonitoring()})),this._onAfterShaderCompilationObserver=this.engine.onAfterShaderCompilationObservable.add((function(){t._shaderCompilationTime.endMonitoring()}))):(this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null))},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null,this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null,this.engine=null},e}(),tv=function(){function e(e){var t=this;this.scene=e,this._captureActiveMeshesEvaluationTime=!1,this._activeMeshesEvaluationTime=new an,this._captureRenderTargetsRenderTime=!1,this._renderTargetsRenderTime=new an,this._captureFrameTime=!1,this._frameTime=new an,this._captureRenderTime=!1,this._renderTime=new an,this._captureInterFrameTime=!1,this._interFrameTime=new an,this._captureParticlesRenderTime=!1,this._particlesRenderTime=new an,this._captureSpritesRenderTime=!1,this._spritesRenderTime=new an,this._capturePhysicsTime=!1,this._physicsTime=new an,this._captureAnimationsTime=!1,this._animationsTime=new an,this._captureCameraRenderTime=!1,this._cameraRenderTime=new an,this._onBeforeActiveMeshesEvaluationObserver=null,this._onAfterActiveMeshesEvaluationObserver=null,this._onBeforeRenderTargetsRenderObserver=null,this._onAfterRenderTargetsRenderObserver=null,this._onAfterRenderObserver=null,this._onBeforeDrawPhaseObserver=null,this._onAfterDrawPhaseObserver=null,this._onBeforeAnimationsObserver=null,this._onBeforeParticlesRenderingObserver=null,this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver=null,this._onAfterSpritesRenderingObserver=null,this._onBeforePhysicsObserver=null,this._onAfterPhysicsObserver=null,this._onAfterAnimationsObserver=null,this._onBeforeCameraRenderObserver=null,this._onAfterCameraRenderObserver=null,this._onBeforeAnimationsObserver=e.onBeforeAnimationsObservable.add((function(){t._captureActiveMeshesEvaluationTime&&t._activeMeshesEvaluationTime.fetchNewFrame(),t._captureRenderTargetsRenderTime&&t._renderTargetsRenderTime.fetchNewFrame(),t._captureFrameTime&&(rr.StartPerformanceCounter("Scene rendering"),t._frameTime.beginMonitoring()),t._captureInterFrameTime&&t._interFrameTime.endMonitoring(),t._captureParticlesRenderTime&&t._particlesRenderTime.fetchNewFrame(),t._captureSpritesRenderTime&&t._spritesRenderTime.fetchNewFrame(),t._captureAnimationsTime&&t._animationsTime.beginMonitoring(),t._captureRenderTime&&t._renderTime.fetchNewFrame(),t._captureCameraRenderTime&&t._cameraRenderTime.fetchNewFrame(),t.scene.getEngine()._drawCalls.fetchNewFrame()})),this._onAfterRenderObserver=e.onAfterRenderObservable.add((function(){t._captureFrameTime&&(rr.EndPerformanceCounter("Scene rendering"),t._frameTime.endMonitoring()),t._captureRenderTime&&t._renderTime.endMonitoring(!1),t._captureInterFrameTime&&t._interFrameTime.beginMonitoring(),t._captureActiveMeshesEvaluationTime&&t._activeMeshesEvaluationTime.endFrame(),t._captureRenderTargetsRenderTime&&t._renderTargetsRenderTime.endFrame(),t._captureParticlesRenderTime&&t._particlesRenderTime.endFrame(),t._captureSpritesRenderTime&&t._spritesRenderTime.endFrame(),t._captureRenderTime&&t._renderTime.endFrame(),t._captureCameraRenderTime&&t._cameraRenderTime.endFrame()}))}return Object.defineProperty(e.prototype,"activeMeshesEvaluationTimeCounter",{get:function(){return this._activeMeshesEvaluationTime},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"captureActiveMeshesEvaluationTime",{get:function(){return this._captureActiveMeshesEvaluationTime},set:function(e){var t=this;e!==this._captureActiveMeshesEvaluationTime&&(this._captureActiveMeshesEvaluationTime=e,e?(this._onBeforeActiveMeshesEvaluationObserver=this.scene.onBeforeActiveMeshesEvaluationObservable.add((function(){rr.StartPerformanceCounter("Active meshes evaluation"),t._activeMeshesEvaluationTime.beginMonitoring()})),this._onAfterActiveMeshesEvaluationObserver=this.scene.onAfterActiveMeshesEvaluationObservable.add((function(){rr.EndPerformanceCounter("Active meshes evaluation"),t._activeMeshesEvaluationTime.endMonitoring(!1)}))):(this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"renderTargetsRenderTimeCounter",{get:function(){return this._renderTargetsRenderTime},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"captureRenderTargetsRenderTime",{get:function(){return this._captureRenderTargetsRenderTime},set:function(e){var t=this;e!==this._captureRenderTargetsRenderTime&&(this._captureRenderTargetsRenderTime=e,e?(this._onBeforeRenderTargetsRenderObserver=this.scene.onBeforeRenderTargetsRenderObservable.add((function(){rr.StartPerformanceCounter("Render targets rendering"),t._renderTargetsRenderTime.beginMonitoring()})),this._onAfterRenderTargetsRenderObserver=this.scene.onAfterRenderTargetsRenderObservable.add((function(){rr.EndPerformanceCounter("Render targets rendering"),t._renderTargetsRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"particlesRenderTimeCounter",{get:function(){return this._particlesRenderTime},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"captureParticlesRenderTime",{get:function(){return this._captureParticlesRenderTime},set:function(e){var t=this;e!==this._captureParticlesRenderTime&&(this._captureParticlesRenderTime=e,e?(this._onBeforeParticlesRenderingObserver=this.scene.onBeforeParticlesRenderingObservable.add((function(){rr.StartPerformanceCounter("Particles"),t._particlesRenderTime.beginMonitoring()})),this._onAfterParticlesRenderingObserver=this.scene.onAfterParticlesRenderingObservable.add((function(){rr.EndPerformanceCounter("Particles"),t._particlesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"spritesRenderTimeCounter",{get:function(){return this._spritesRenderTime},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"captureSpritesRenderTime",{get:function(){return this._captureSpritesRenderTime},set:function(e){var t=this;e!==this._captureSpritesRenderTime&&(this._captureSpritesRenderTime=e,this.scene.spriteManagers&&(e?(this._onBeforeSpritesRenderingObserver=this.scene.onBeforeSpritesRenderingObservable.add((function(){rr.StartPerformanceCounter("Sprites"),t._spritesRenderTime.beginMonitoring()})),this._onAfterSpritesRenderingObserver=this.scene.onAfterSpritesRenderingObservable.add((function(){rr.EndPerformanceCounter("Sprites"),t._spritesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null)))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"physicsTimeCounter",{get:function(){return this._physicsTime},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"capturePhysicsTime",{get:function(){return this._capturePhysicsTime},set:function(e){var t=this;e!==this._capturePhysicsTime&&this.scene.onBeforePhysicsObservable&&(this._capturePhysicsTime=e,e?(this._onBeforePhysicsObserver=this.scene.onBeforePhysicsObservable.add((function(){rr.StartPerformanceCounter("Physics"),t._physicsTime.beginMonitoring()})),this._onAfterPhysicsObserver=this.scene.onAfterPhysicsObservable.add((function(){rr.EndPerformanceCounter("Physics"),t._physicsTime.endMonitoring()}))):(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"animationsTimeCounter",{get:function(){return this._animationsTime},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"captureAnimationsTime",{get:function(){return this._captureAnimationsTime},set:function(e){var t=this;e!==this._captureAnimationsTime&&(this._captureAnimationsTime=e,e?this._onAfterAnimationsObserver=this.scene.onAfterAnimationsObservable.add((function(){t._animationsTime.endMonitoring()})):(this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"frameTimeCounter",{get:function(){return this._frameTime},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"captureFrameTime",{get:function(){return this._captureFrameTime},set:function(e){this._captureFrameTime=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"interFrameTimeCounter",{get:function(){return this._interFrameTime},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"captureInterFrameTime",{get:function(){return this._captureInterFrameTime},set:function(e){this._captureInterFrameTime=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"renderTimeCounter",{get:function(){return this._renderTime},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"captureRenderTime",{get:function(){return this._captureRenderTime},set:function(e){var t=this;e!==this._captureRenderTime&&(this._captureRenderTime=e,e?(this._onBeforeDrawPhaseObserver=this.scene.onBeforeDrawPhaseObservable.add((function(){t._renderTime.beginMonitoring(),rr.StartPerformanceCounter("Main render")})),this._onAfterDrawPhaseObserver=this.scene.onAfterDrawPhaseObservable.add((function(){t._renderTime.endMonitoring(!1),rr.EndPerformanceCounter("Main render")}))):(this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"cameraRenderTimeCounter",{get:function(){return this._cameraRenderTime},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"captureCameraRenderTime",{get:function(){return this._captureCameraRenderTime},set:function(e){var t=this;e!==this._captureCameraRenderTime&&(this._captureCameraRenderTime=e,e?(this._onBeforeCameraRenderObserver=this.scene.onBeforeCameraRenderObservable.add((function(e){t._cameraRenderTime.beginMonitoring(),rr.StartPerformanceCounter("Rendering camera ".concat(e.name))})),this._onAfterCameraRenderObserver=this.scene.onAfterCameraRenderObservable.add((function(e){t._cameraRenderTime.endMonitoring(!1),rr.EndPerformanceCounter("Rendering camera ".concat(e.name))}))):(this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"drawCallsCounter",{get:function(){return this.scene.getEngine()._drawCalls},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=null,this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null,this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null,this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver),this._onBeforeAnimationsObserver=null,this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver&&(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null),this._onAfterSpritesRenderingObserver&&(this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null),this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null,this._onBeforePhysicsObserver&&(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null),this._onAfterPhysicsObserver&&(this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null),this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null,this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null,this.scene=null},e}();li.ShadersStore.glowMapGenerationPixelShader="#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)\n#include<helperFunctions>\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform sampler2D diffuseSampler;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform sampler2D emissiveSampler;\n#endif\n#ifdef VERTEXALPHA\nvarying vec4 vColor;\n#endif\nuniform vec4 glowColor;uniform float glowIntensity;\n#include<clipPlaneFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include<clipPlaneFragment>\nvec4 finalColor=glowColor;\n#ifdef DIFFUSE\nvec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);\n#ifdef DIFFUSE_ISLINEAR\nalbedoTexture=toGammaSpace(albedoTexture);\n#endif\n#ifdef GLOW\nfinalColor.a*=albedoTexture.a;\n#endif\n#ifdef HIGHLIGHT\nfinalColor.a=albedoTexture.a;\n#endif\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vUVOpacity);\n#ifdef OPACITYRGB\nfinalColor.a*=getLuminance(opacityMap.rgb);\n#else\nfinalColor.a*=opacityMap.a;\n#endif\nfinalColor.a*=opacityIntensity;\n#endif\n#ifdef VERTEXALPHA\nfinalColor.a*=vColor.a;\n#endif\n#ifdef ALPHATEST\nif (finalColor.a<ALPHATESTVALUE)\ndiscard;\n#endif\n#ifdef EMISSIVE\nvec4 emissive=texture2D(emissiveSampler,vUVEmissive);\n#ifdef EMISSIVE_ISLINEAR\nemissive=toGammaSpace(emissive);\n#endif\ngl_FragColor=emissive*finalColor*glowIntensity;\n#else\ngl_FragColor=finalColor*glowIntensity;\n#endif\n#ifdef HIGHLIGHT\ngl_FragColor.a=glowColor.a;\n#endif\n}";li.ShadersStore.glowMapGenerationVertexShader="attribute vec3 position;\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#include<clipPlaneVertexDeclaration>\n#include<instancesDeclaration>\nuniform mat4 viewProjection;varying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform mat4 diffuseMatrix;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform mat4 opacityMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform mat4 emissiveMatrix;\n#endif\n#ifdef VERTEXALPHA\nattribute vec4 color;varying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertexGlobal>\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef CUBEMAP\nvPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*worldPos;gl_Position=vPosition;\n#endif\n#ifdef DIFFUSE\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef OPACITY\n#ifdef OPACITYUV1\nvUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef OPACITYUV2\nvUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef VERTEXALPHA\nvColor=color;\n#endif\n#include<clipPlaneVertex>\n}";var iv=function(){function e(t,i){this._vertexBuffers={},this._maxSize=0,this._mainTextureDesiredSize={width:0,height:0},this._shouldRender=!0,this._postProcesses=[],this._textures=[],this._emissiveTextureAndColor={texture:null,color:new J},this._effectIntensity={},this.neutralColor=new J,this.isEnabled=!0,this.disableBoundingBoxesFromEffectLayer=!1,this.onDisposeObservable=new f,this.onBeforeRenderMainTextureObservable=new f,this.onBeforeComposeObservable=new f,this.onBeforeRenderMeshToEffect=new f,this.onAfterRenderMeshToEffect=new f,this.onAfterComposeObservable=new f,this.onSizeChangedObservable=new f,this._materialForRendering={},this.name=t,this._scene=i||M.LastCreatedScene,e._SceneComponentInitialization(this._scene),this._engine=this._scene.getEngine(),this._maxSize=this._engine.getCaps().maxTextureSize,this._scene.effectLayers.push(this),this._mergeDrawWrapper=[],this._generateIndexBuffer(),this._generateVertexBuffer()}return Object.defineProperty(e.prototype,"camera",{get:function(){return this._effectLayerOptions.camera},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"renderingGroupId",{get:function(){return this._effectLayerOptions.renderingGroupId},set:function(e){this._effectLayerOptions.renderingGroupId=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"mainTexture",{get:function(){return this._mainTexture},enumerable:!1,configurable:!0}),e.prototype.setMaterialForRendering=function(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(var i=0;i<e.length;++i){var r=e[i];t?this._materialForRendering[r.uniqueId]=[r,t]:delete this._materialForRendering[r.uniqueId]}else t?this._materialForRendering[e.uniqueId]=[e,t]:delete this._materialForRendering[e.uniqueId]},e.prototype.getEffectIntensity=function(e){var t;return null!==(t=this._effectIntensity[e.uniqueId])&&void 0!==t?t:1},e.prototype.setEffectIntensity=function(e,t){this._effectIntensity[e.uniqueId]=t},e.prototype._numInternalDraws=function(){return 1},e.prototype._init=function(e){this._effectLayerOptions=g({mainTextureRatio:.5,alphaBlendingMode:u.ALPHA_COMBINE,camera:null,renderingGroupId:-1,mainTextureType:u.TEXTURETYPE_UNSIGNED_INT,generateStencilBuffer:!1},e),this._setMainTextureSize(),this._createMainTexture(),this._createTextureAndPostProcesses()},e.prototype._generateIndexBuffer=function(){var e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._engine.createIndexBuffer(e)},e.prototype._generateVertexBuffer=function(){var e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1);var t=new Nr(this._engine,e,Nr.PositionKind,!1,!1,2);this._vertexBuffers[Nr.PositionKind]=t},e.prototype._setMainTextureSize=function(){this._effectLayerOptions.mainTextureFixedSize?(this._mainTextureDesiredSize.width=this._effectLayerOptions.mainTextureFixedSize,this._mainTextureDesiredSize.height=this._effectLayerOptions.mainTextureFixedSize):(this._mainTextureDesiredSize.width=this._engine.getRenderWidth()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.height=this._engine.getRenderHeight()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.width=this._engine.needPOTTextures?ir(this._mainTextureDesiredSize.width,this._maxSize):this._mainTextureDesiredSize.width,this._mainTextureDesiredSize.height=this._engine.needPOTTextures?ir(this._mainTextureDesiredSize.height,this._maxSize):this._mainTextureDesiredSize.height),this._mainTextureDesiredSize.width=Math.floor(this._mainTextureDesiredSize.width),this._mainTextureDesiredSize.height=Math.floor(this._mainTextureDesiredSize.height)},e.prototype._createMainTexture=function(){var e,t=this;for(var i in this._mainTexture=new Pl("EffectLayerMainRTT",{width:this._mainTextureDesiredSize.width,height:this._mainTextureDesiredSize.height},this._scene,!1,!0,this._effectLayerOptions.mainTextureType,!1,Ja.TRILINEAR_SAMPLINGMODE,!0,this._effectLayerOptions.generateStencilBuffer),this._mainTexture.activeCamera=this._effectLayerOptions.camera,this._mainTexture.wrapU=Ja.CLAMP_ADDRESSMODE,this._mainTexture.wrapV=Ja.CLAMP_ADDRESSMODE,this._mainTexture.anisotropicFilteringLevel=1,this._mainTexture.updateSamplingMode(Ja.BILINEAR_SAMPLINGMODE),this._mainTexture.renderParticles=!1,this._mainTexture.renderList=null,this._mainTexture.ignoreCameraViewport=!0,this._materialForRendering){var r=(e=this._materialForRendering[i])[0],n=e[1];this._mainTexture.setMaterialForRendering(r,n)}if(this._mainTexture.customIsReadyFunction=function(e,i,r){if((r||0===i)&&e.subMeshes)for(var n=0;n<e.subMeshes.length;++n){var o=e.subMeshes[n],a=o.getMaterial(),s=o.getRenderingMesh();if(a){var l=s._getInstancesRenderList(o._id,!!o.getReplacementMesh()).hardwareInstancedRendering[o._id]||s.hasThinInstances;if(t._setEmissiveTextureAndColor(s,o,a),!t._isReady(o,l,t._emissiveTextureAndColor.texture))return!1}}return!0},this._mainTexture.customRenderFunction=function(e,i,r,n){var o;t.onBeforeRenderMainTextureObservable.notifyObservers(t);var a=t._scene.getEngine();if(n.length){for(a.setColorWrite(!1),o=0;o<n.length;o++)t._renderSubMesh(n.data[o]);a.setColorWrite(!0)}for(o=0;o<e.length;o++)t._renderSubMesh(e.data[o]);for(o=0;o<i.length;o++)t._renderSubMesh(i.data[o]);var s=a.getAlphaMode();for(o=0;o<r.length;o++)t._renderSubMesh(r.data[o],!0);a.setAlphaMode(s)},this._mainTexture.onClearObservable.add((function(e){e.clear(t.neutralColor,!0,!0,!0)})),this._scene.getBoundingBoxRenderer){var o=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add((function(){t._scene.getBoundingBoxRenderer().enabled=!t.disableBoundingBoxesFromEffectLayer&&o})),this._mainTexture.onAfterUnbindObservable.add((function(){t._scene.getBoundingBoxRenderer().enabled=o}))}},e.prototype._addCustomEffectDefines=function(e){},e.prototype._isReady=function(e,t,i){var r,n=this._scene.getEngine(),o=e.getMesh(),a=null===(r=o._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===r?void 0:r[n.currentRenderPassId];if(a)return a.isReadyForSubMesh(o,e,t);var s=e.getMaterial();if(!s)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return s.isReadyForSubMesh(e.getMesh(),e,t);var l=[],c=[Nr.PositionKind],u=!1,h=!1;if(s){var d=s.needAlphaTesting(),p=s.getAlphaTestTexture(),f=p&&p.hasAlpha&&(s.useAlphaFromDiffuseTexture||s._useAlphaFromAlbedoTexture);p&&(d||f)&&(l.push("#define DIFFUSE"),o.isVerticesDataPresent(Nr.UV2Kind)&&1===p.coordinatesIndex?(l.push("#define DIFFUSEUV2"),h=!0):o.isVerticesDataPresent(Nr.UVKind)&&(l.push("#define DIFFUSEUV1"),u=!0),d&&(l.push("#define ALPHATEST"),l.push("#define ALPHATESTVALUE 0.4")),p.gammaSpace||l.push("#define DIFFUSE_ISLINEAR"));var _=s.opacityTexture;_&&(l.push("#define OPACITY"),o.isVerticesDataPresent(Nr.UV2Kind)&&1===_.coordinatesIndex?(l.push("#define OPACITYUV2"),h=!0):o.isVerticesDataPresent(Nr.UVKind)&&(l.push("#define OPACITYUV1"),u=!0))}i&&(l.push("#define EMISSIVE"),o.isVerticesDataPresent(Nr.UV2Kind)&&1===i.coordinatesIndex?(l.push("#define EMISSIVEUV2"),h=!0):o.isVerticesDataPresent(Nr.UVKind)&&(l.push("#define EMISSIVEUV1"),u=!0),i.gammaSpace||l.push("#define EMISSIVE_ISLINEAR")),o.useVertexColors&&o.isVerticesDataPresent(Nr.ColorKind)&&o.hasVertexAlpha&&s.transparencyMode!==Ca.MATERIAL_OPAQUE&&(c.push(Nr.ColorKind),l.push("#define VERTEXALPHA")),u&&(c.push(Nr.UVKind),l.push("#define UV1")),h&&(c.push(Nr.UV2Kind),l.push("#define UV2"));var m=new ll;if(o.useBones&&o.computeBonesUsingShaders){c.push(Nr.MatricesIndicesKind),c.push(Nr.MatricesWeightsKind),o.numBoneInfluencers>4&&(c.push(Nr.MatricesIndicesExtraKind),c.push(Nr.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+o.numBoneInfluencers);var g=o.skeleton;g&&g.isUsingTextureForMatrices?l.push("#define BONETEXTURE"):l.push("#define BonesPerMesh "+(g?g.bones.length+1:0)),o.numBoneInfluencers>0&&m.addCPUSkinningFallback(0,o)}else l.push("#define NUM_BONE_INFLUENCERS 0");var v=o.morphTargetManager,y=0;v&&(y=v.numMaxInfluencers||v.numInfluencers)>0&&(l.push("#define MORPHTARGETS"),l.push("#define NUM_MORPH_INFLUENCERS "+y),v.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),qo(c,o,y)),t&&(l.push("#define INSTANCES"),Jo(c),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),zo(s,this._scene,l),this._addCustomEffectDefines(l);var b=e._getDrawWrapper(void 0,!0),T=b.defines,E=l.join("\n");if(T!==E){var S=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];Go(S),b.setEffect(this._engine.createEffect("glowMapGeneration",c,S,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],E,m,void 0,void 0,{maxSimultaneousMorphTargets:y}),E)}return b.effect.isReady()},e.prototype.render=function(){for(var e=0;e<this._postProcesses.length;e++)if(!this._postProcesses[e].isReady())return;var t=this._scene.getEngine(),i=this._numInternalDraws(),r=!0;for(e=0;e<i;++e)(o=this._mergeDrawWrapper[e])||(o=this._mergeDrawWrapper[e]=new ho(this._engine)).setEffect(this._createMergeEffect()),r=r&&o.effect.isReady();if(r){this.onBeforeComposeObservable.notifyObservers(this);var n=t.getAlphaMode();for(e=0;e<i;++e){var o=this._mergeDrawWrapper[e];t.enableEffect(o),t.setState(!1),t.bindBuffers(this._vertexBuffers,this._indexBuffer,o.effect),t.setAlphaMode(this._effectLayerOptions.alphaBlendingMode),this._internalRender(o.effect,e)}t.setAlphaMode(n),this.onAfterComposeObservable.notifyObservers(this);var a=this._mainTexture.getSize();this._setMainTextureSize(),a.width===this._mainTextureDesiredSize.width&&a.height===this._mainTextureDesiredSize.height||0===this._mainTextureDesiredSize.width||0===this._mainTextureDesiredSize.height||(this.onSizeChangedObservable.notifyObservers(this),this._disposeTextureAndPostProcesses(),this._createMainTexture(),this._createTextureAndPostProcesses())}},e.prototype.hasMesh=function(e){return-1===this.renderingGroupId||e.renderingGroupId===this.renderingGroupId},e.prototype.shouldRender=function(){return this.isEnabled&&this._shouldRender},e.prototype._shouldRenderMesh=function(e){return!0},e.prototype._canRenderMesh=function(e,t){return!t.needAlphaBlendingForMesh(e)},e.prototype._shouldRenderEmissiveTextureForMesh=function(){return!0},e.prototype._renderSubMesh=function(e,t){var i,r;if(void 0===t&&(t=!1),this.shouldRender()){var n=e.getMaterial(),o=e.getMesh(),a=e.getReplacementMesh(),s=e.getRenderingMesh(),l=e.getEffectiveMesh(),c=this._scene,u=c.getEngine();if(l._internalAbstractMeshDataInfo._isActiveIntermediate=!1,n&&this._canRenderMesh(s,n)){var h=null!==(i=s.overrideMaterialSideOrientation)&&void 0!==i?i:n.sideOrientation;l._getWorldMatrixDeterminant()<0&&(h=h===Ca.ClockWiseSideOrientation?Ca.CounterClockWiseSideOrientation:Ca.ClockWiseSideOrientation);var d=h===Ca.ClockWiseSideOrientation;u.setState(n.backFaceCulling,n.zOffset,void 0,d,n.cullBackFaces,void 0,n.zOffsetUnits);var p=s._getInstancesRenderList(e._id,!!a);if(!p.mustReturn&&this._shouldRenderMesh(s)){var f=p.hardwareInstancedRendering[e._id]||s.hasThinInstances;if(this._setEmissiveTextureAndColor(s,e,n),this.onBeforeRenderMeshToEffect.notifyObservers(o),this._useMeshMaterial(s))s.render(e,t,a||void 0);else if(this._isReady(e,f,this._emissiveTextureAndColor.texture)){var _=null===(r=l._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===r?void 0:r[u.currentRenderPassId],m=e._getDrawWrapper();if(!m&&_&&(m=_._getDrawWrapper()),!m)return;var g=m.effect;if(u.enableEffect(m),f||s._bind(e,g,n.fillMode),_?_.bindForSubMesh(l.getWorldMatrix(),l,e):(g.setMatrix("viewProjection",c.getTransformMatrix()),g.setMatrix("world",l.getWorldMatrix()),g.setFloat4("glowColor",this._emissiveTextureAndColor.color.r,this._emissiveTextureAndColor.color.g,this._emissiveTextureAndColor.color.b,this._emissiveTextureAndColor.color.a)),!_){var v=n.needAlphaTesting(),y=n.getAlphaTestTexture(),b=y&&y.hasAlpha&&(n.useAlphaFromDiffuseTexture||n._useAlphaFromAlbedoTexture);y&&(v||b)&&(g.setTexture("diffuseSampler",y),(T=y.getTextureMatrix())&&g.setMatrix("diffuseMatrix",T));var T,E=n.opacityTexture;if(E&&(g.setTexture("opacitySampler",E),g.setFloat("opacityIntensity",E.level),(T=E.getTextureMatrix())&&g.setMatrix("opacityMatrix",T)),this._emissiveTextureAndColor.texture&&(g.setTexture("emissiveSampler",this._emissiveTextureAndColor.texture),g.setMatrix("emissiveMatrix",this._emissiveTextureAndColor.texture.getTextureMatrix())),s.useBones&&s.computeBonesUsingShaders&&s.skeleton){var S=s.skeleton;if(S.isUsingTextureForMatrices){var x=S.getTransformMatrixTexture(s);if(!x)return;g.setTexture("boneSampler",x),g.setFloat("boneTextureWidth",4*(S.bones.length+1))}else g.setMatrices("mBones",S.getTransformMatrices(s))}$o(s,g),s.morphTargetManager&&s.morphTargetManager.isUsingTextureForTargets&&s.morphTargetManager._bind(g),t&&u.setAlphaMode(n.alphaMode),g.setFloat("glowIntensity",this.getEffectIntensity(s)),Ho(g,n,c)}s._processRendering(l,e,g,n.fillMode,p,f,(function(e,t){return g.setMatrix("world",t)}))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(o)}}}},e.prototype._useMeshMaterial=function(e){return!1},e.prototype._rebuild=function(){var e=this._vertexBuffers[Nr.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()},e.prototype._disposeTextureAndPostProcesses=function(){this._mainTexture.dispose();for(var e=0;e<this._postProcesses.length;e++)this._postProcesses[e]&&this._postProcesses[e].dispose();for(this._postProcesses=[],e=0;e<this._textures.length;e++)this._textures[e]&&this._textures[e].dispose();this._textures=[]},e.prototype.dispose=function(){var e=this._vertexBuffers[Nr.PositionKind];e&&(e.dispose(),this._vertexBuffers[Nr.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null);for(var t=0,i=this._mergeDrawWrapper;t<i.length;t++)i[t].dispose();this._mergeDrawWrapper=[],this._disposeTextureAndPostProcesses();var r=this._scene.effectLayers.indexOf(this,0);r>-1&&this._scene.effectLayers.splice(r,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()},e.prototype.getClassName=function(){return"EffectLayer"},e.Parse=function(e,t,i){return rr.Instantiate(e.customType).Parse(e,t,i)},e._SceneComponentInitialization=function(e){throw He("EffectLayerSceneComponent")},v([Ie()],e.prototype,"name",void 0),v([Be()],e.prototype,"neutralColor",void 0),v([Ie()],e.prototype,"isEnabled",void 0),v([Ge()],e.prototype,"camera",null),v([Ie()],e.prototype,"renderingGroupId",null),v([Ie()],e.prototype,"disableBoundingBoxesFromEffectLayer",void 0),e}();c.AddParser(Vr.NAME_EFFECTLAYER,(function(e,t,i,r){if(e.effectLayers){i.effectLayers||(i.effectLayers=[]);for(var n=0;n<e.effectLayers.length;n++){var o=iv.Parse(e.effectLayers[n],t,r);i.effectLayers.push(o)}}})),c.prototype.removeEffectLayer=function(e){var t=this.effectLayers.indexOf(e);return-1!==t&&this.effectLayers.splice(t,1),t},c.prototype.addEffectLayer=function(e){this.effectLayers.push(e)};var rv=function(){function e(e){this.name=Vr.NAME_EFFECTLAYER,this._renderEffects=!1,this._needStencil=!1,this._previousStencilState=!1,this.scene=e||M.LastCreatedScene,this.scene&&(this._engine=this.scene.getEngine(),this.scene.effectLayers=[])}return e.prototype.register=function(){this.scene._isReadyForMeshStage.registerStep(Vr.STEP_ISREADYFORMESH_EFFECTLAYER,this,this._isReadyForMesh),this.scene._cameraDrawRenderTargetStage.registerStep(Vr.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER,this,this._renderMainTexture),this.scene._beforeCameraDrawStage.registerStep(Vr.STEP_BEFORECAMERADRAW_EFFECTLAYER,this,this._setStencil),this.scene._afterRenderingGroupDrawStage.registerStep(Vr.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW,this,this._drawRenderingGroup),this.scene._afterCameraDrawStage.registerStep(Vr.STEP_AFTERCAMERADRAW_EFFECTLAYER,this,this._setStencilBack),this.scene._afterCameraDrawStage.registerStep(Vr.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW,this,this._drawCamera)},e.prototype.rebuild=function(){for(var e=0,t=this.scene.effectLayers;e<t.length;e++)t[e]._rebuild()},e.prototype.serialize=function(e){e.effectLayers=[];for(var t=0,i=this.scene.effectLayers;t<i.length;t++){var r=i[t];r.serialize&&e.effectLayers.push(r.serialize())}},e.prototype.addFromContainer=function(e){var t=this;e.effectLayers&&e.effectLayers.forEach((function(e){t.scene.addEffectLayer(e)}))},e.prototype.removeFromContainer=function(e,t){var i=this;e.effectLayers&&e.effectLayers.forEach((function(e){i.scene.removeEffectLayer(e),t&&e.dispose()}))},e.prototype.dispose=function(){for(var e=this.scene.effectLayers;e.length;)e[0].dispose()},e.prototype._isReadyForMesh=function(e,t){for(var i=this._engine.currentRenderPassId,r=0,n=this.scene.effectLayers;r<n.length;r++){var o=n[r];if(o.hasMesh(e)){var a=o._mainTexture;this._engine.currentRenderPassId=a.renderPassId;for(var s=0,l=e.subMeshes;s<l.length;s++){var c=l[s];if(!o.isReady(c,t))return this._engine.currentRenderPassId=i,!1}}}return this._engine.currentRenderPassId=i,!0},e.prototype._renderMainTexture=function(e){this._renderEffects=!1,this._needStencil=!1;var t=!1,i=this.scene.effectLayers;if(i&&i.length>0){this._previousStencilState=this._engine.getStencilBuffer();for(var r=0,n=i;r<n.length;r++){var o=n[r];if(o.shouldRender()&&(!o.camera||o.camera.cameraRigMode===$n.RIG_MODE_NONE&&e===o.camera||o.camera.cameraRigMode!==$n.RIG_MODE_NONE&&o.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||o.needStencil();var a=o._mainTexture;a._shouldRender()&&(this.scene.incrementRenderId(),a.render(!1,!1),t=!0)}}this.scene.incrementRenderId()}return t},e.prototype._setStencil=function(){this._needStencil&&this._engine.setStencilBuffer(!0)},e.prototype._setStencilBack=function(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)},e.prototype._draw=function(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);for(var t=this.scene.effectLayers,i=0;i<t.length;i++){var r=t[i];r.renderingGroupId===e&&r.shouldRender()&&r.render()}this._engine.setDepthBuffer(!0)}},e.prototype._drawCamera=function(){this._renderEffects&&this._draw(-1)},e.prototype._drawRenderingGroup=function(e){!this.scene._isInIntermediateRendering()&&this._renderEffects&&this._draw(e)},e}();iv._SceneComponentInitialization=function(e){var t=e._getComponent(Vr.NAME_EFFECTLAYER);t||(t=new rv(e),e._addComponent(t))};li.ShadersStore.glowMapMergePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\nuniform float offset;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);baseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\n#if LDR\nbaseColor=clamp(baseColor,0.,1.0);\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";li.ShadersStore.glowMapMergeVertexShader="attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}",c.prototype.getGlowLayerByName=function(e){for(var t,i=0;i<(null===(t=this.effectLayers)||void 0===t?void 0:t.length);i++)if(this.effectLayers[i].name===e&&this.effectLayers[i].getEffectName()===nv.EffectName)return this.effectLayers[i];return null};var nv=function(e){function t(i,r,n){var o=e.call(this,i,r)||this;return o._intensity=1,o._includedOnlyMeshes=[],o._excludedMeshes=[],o._meshesUsingTheirOwnMaterials=[],o.neutralColor=new J(0,0,0,1),o._options=g({mainTextureRatio:t.DefaultTextureRatio,blurKernelSize:32,mainTextureFixedSize:void 0,camera:null,mainTextureSamples:1,renderingGroupId:-1,ldrMerge:!1,alphaBlendingMode:u.ALPHA_ADD,mainTextureType:u.TEXTURETYPE_UNSIGNED_INT,generateStencilBuffer:!1},n),o._init({alphaBlendingMode:o._options.alphaBlendingMode,camera:o._options.camera,mainTextureFixedSize:o._options.mainTextureFixedSize,mainTextureRatio:o._options.mainTextureRatio,renderingGroupId:o._options.renderingGroupId,mainTextureType:o._options.mainTextureType,generateStencilBuffer:o._options.generateStencilBuffer}),o}return m(t,e),Object.defineProperty(t.prototype,"blurKernelSize",{get:function(){return this._options.blurKernelSize},set:function(e){if(e!==this._options.blurKernelSize){this._options.blurKernelSize=e;var t=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1.kernel=t,this._verticalBlurPostprocess1.kernel=t,this._horizontalBlurPostprocess2.kernel=t,this._verticalBlurPostprocess2.kernel=t}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"intensity",{get:function(){return this._intensity},set:function(e){this._intensity=e},enumerable:!1,configurable:!0}),t.prototype.getEffectName=function(){return t.EffectName},t.prototype._createMergeEffect=function(){var e="#define EMISSIVE \n";return this._options.ldrMerge&&(e+="#define LDR \n"),this._engine.createEffect("glowMapMerge",[Nr.PositionKind],["offset"],["textureSampler","textureSampler2"],e)},t.prototype._createTextureAndPostProcesses=function(){var e=this,t=this._mainTextureDesiredSize.width,i=this._mainTextureDesiredSize.height;t=this._engine.needPOTTextures?ir(t,this._maxSize):t,i=this._engine.needPOTTextures?ir(i,this._maxSize):i;var r;r=this._engine.getCaps().textureHalfFloatRender?u.TEXTURETYPE_HALF_FLOAT:u.TEXTURETYPE_UNSIGNED_INT,this._blurTexture1=new Pl("GlowLayerBlurRTT",{width:t,height:i},this._scene,!1,!0,r),this._blurTexture1.wrapU=Ja.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=Ja.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(Ja.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;var n=Math.floor(t/2),o=Math.floor(i/2);this._blurTexture2=new Pl("GlowLayerBlurRTT2",{width:n,height:o},this._scene,!1,!0,r),this._blurTexture2.wrapU=Ja.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=Ja.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(Ja.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2];var a=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1=new Om("GlowLayerHBP1",new U(1,0),a,{width:t,height:i},null,Ja.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,r),this._horizontalBlurPostprocess1.width=t,this._horizontalBlurPostprocess1.height=i,this._horizontalBlurPostprocess1.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess1.onApplyObservable.add((function(t){t.setTexture("textureSampler",e._mainTexture)})),this._verticalBlurPostprocess1=new Om("GlowLayerVBP1",new U(0,1),a,{width:t,height:i},null,Ja.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,r),this._horizontalBlurPostprocess2=new Om("GlowLayerHBP2",new U(1,0),a,{width:n,height:o},null,Ja.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,r),this._horizontalBlurPostprocess2.width=n,this._horizontalBlurPostprocess2.height=o,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add((function(t){t.setTexture("textureSampler",e._blurTexture1)})),this._verticalBlurPostprocess2=new Om("GlowLayerVBP2",new U(0,1),a,{width:n,height:o},null,Ja.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,r),this._postProcesses=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1,this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._postProcesses1=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1],this._postProcesses2=[this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._mainTexture.samples=this._options.mainTextureSamples,this._mainTexture.onAfterUnbindObservable.add((function(){var t=e._blurTexture1.renderTarget;if(t){e._scene.postProcessManager.directRender(e._postProcesses1,t,!0);var i=e._blurTexture2.renderTarget;i&&e._scene.postProcessManager.directRender(e._postProcesses2,i,!0),e._engine.unBindFramebuffer(null!=i?i:t,!0)}})),this._postProcesses.map((function(e){e.autoClear=!1}))},t.prototype._getEffectiveBlurKernelSize=function(){return this._options.blurKernelSize/2},t.prototype.isReady=function(t,i){var r=t.getMaterial(),n=t.getRenderingMesh();if(!r||!n)return!1;var o=r.emissiveTexture;return e.prototype._isReady.call(this,t,i,o)},t.prototype.needStencil=function(){return!1},t.prototype._canRenderMesh=function(e,t){return!0},t.prototype._internalRender=function(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);var t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(Ca.TriangleFillMode,0,6),t.setStencilBuffer(i)},t.prototype._setEmissiveTextureAndColor=function(e,t,i){var r,n=1;this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(n=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector?this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color):i.emissiveColor?(n*=null!==(r=i.emissiveIntensity)&&void 0!==r?r:1,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*n,i.emissiveColor.g*n,i.emissiveColor.b*n,i.alpha)):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a)},t.prototype._shouldRenderMesh=function(e){return this.hasMesh(e)},t.prototype._addCustomEffectDefines=function(e){e.push("#define GLOW")},t.prototype.addExcludedMesh=function(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)},t.prototype.removeExcludedMesh=function(e){var t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)},t.prototype.addIncludedOnlyMesh=function(e){-1===this._includedOnlyMeshes.indexOf(e.uniqueId)&&this._includedOnlyMeshes.push(e.uniqueId)},t.prototype.removeIncludedOnlyMesh=function(e){var t=this._includedOnlyMeshes.indexOf(e.uniqueId);-1!==t&&this._includedOnlyMeshes.splice(t,1)},t.prototype.hasMesh=function(t){return!!e.prototype.hasMesh.call(this,t)&&(this._includedOnlyMeshes.length?-1!==this._includedOnlyMeshes.indexOf(t.uniqueId):!this._excludedMeshes.length||-1===this._excludedMeshes.indexOf(t.uniqueId))},t.prototype._useMeshMaterial=function(e){return 0!=this._meshesUsingTheirOwnMaterials.length&&this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)>-1},t.prototype.referenceMeshToUseItsOwnMaterial=function(e){var t=this;e.resetDrawCache(this._mainTexture.renderPassId),this._meshesUsingTheirOwnMaterials.push(e.uniqueId),e.onDisposeObservable.add((function(){t._disposeMesh(e)}))},t.prototype.unReferenceMeshFromUsingItsOwnMaterial=function(e){for(var t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);t>=0;)this._meshesUsingTheirOwnMaterials.splice(t,1),t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);e.resetDrawCache(this._mainTexture.renderPassId)},t.prototype._disposeMesh=function(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)},t.prototype.getClassName=function(){return"GlowLayer"},t.prototype.serialize=function(){var e,t=Ke.Serialize(this);if(t.customType="BABYLON.GlowLayer",t.includedMeshes=[],this._includedOnlyMeshes.length)for(e=0;e<this._includedOnlyMeshes.length;e++)(i=this._scene.getMeshByUniqueId(this._includedOnlyMeshes[e]))&&t.includedMeshes.push(i.id);if(t.excludedMeshes=[],this._excludedMeshes.length)for(e=0;e<this._excludedMeshes.length;e++){var i;(i=this._scene.getMeshByUniqueId(this._excludedMeshes[e]))&&t.excludedMeshes.push(i.id)}return t},t.Parse=function(e,i,r){var n,o=Ke.Parse((function(){return new t(e.name,i,e.options)}),e,i,r);for(n=0;n<e.excludedMeshes.length;n++)(a=i.getMeshById(e.excludedMeshes[n]))&&o.addExcludedMesh(a);for(n=0;n<e.includedMeshes.length;n++){var a;(a=i.getMeshById(e.includedMeshes[n]))&&o.addIncludedOnlyMesh(a)}return o},t.EffectName="GlowLayer",t.DefaultBlurKernelSize=32,t.DefaultTextureRatio=.5,v([Ie()],t.prototype,"blurKernelSize",null),v([Ie()],t.prototype,"intensity",null),v([Ie("options")],t.prototype,"_options",void 0),t}(iv);a("BABYLON.GlowLayer",nv);li.ShadersStore.glowBlurPostProcessPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 direction;uniform float blurWidth;float getLuminance(vec3 color)\n{return dot(color,vec3(0.2126,0.7152,0.0722));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float weights[7];weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;vec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);vec2 texelStep=texelSize*direction*blurWidth;vec2 start=vUV-3.0*texelStep;vec4 baseColor=vec4(0.,0.,0.,0.);vec2 texelOffset=vec2(0.,0.);for (int i=0; i<7; i++)\n{vec4 texel=texture2D(textureSampler,start+texelOffset);baseColor.a+=texel.a*weights[i];float luminance=getLuminance(baseColor.rgb);float luminanceTexel=getLuminance(texel.rgb);float choice=step(luminanceTexel,luminance);baseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;texelOffset+=texelStep;}\ngl_FragColor=baseColor;}",c.prototype.getHighlightLayerByName=function(e){for(var t,i=0;i<(null===(t=this.effectLayers)||void 0===t?void 0:t.length);i++)if(this.effectLayers[i].name===e&&this.effectLayers[i].getEffectName()===av.EffectName)return this.effectLayers[i];return null};var ov=function(e){function t(t,i,r,n,o,a,s,l){void 0===a&&(a=Ja.BILINEAR_SAMPLINGMODE);var c=e.call(this,t,"glowBlurPostProcess",["screenSize","direction","blurWidth"],null,n,o,a,s,l)||this;return c.direction=i,c.kernel=r,c.onApplyObservable.add((function(e){e.setFloat2("screenSize",c.width,c.height),e.setVector2("direction",c.direction),e.setFloat("blurWidth",c.kernel)})),c}return m(t,e),t}(hl),av=function(e){function t(i,r,n){var o=e.call(this,i,r)||this;return o.name=i,o.innerGlow=!0,o.outerGlow=!0,o.onBeforeBlurObservable=new f,o.onAfterBlurObservable=new f,o._instanceGlowingMeshStencilReference=t.GlowingMeshStencilReference++,o._meshes={},o._excludedMeshes={},o.neutralColor=t.NeutralColor,o._engine.isStencilEnable||ae.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),o._options=g({mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:u.ALPHA_COMBINE,camera:null,renderingGroupId:-1,mainTextureType:u.TEXTURETYPE_UNSIGNED_INT},n),o._init({alphaBlendingMode:o._options.alphaBlendingMode,camera:o._options.camera,mainTextureFixedSize:o._options.mainTextureFixedSize,mainTextureRatio:o._options.mainTextureRatio,renderingGroupId:o._options.renderingGroupId,mainTextureType:o._options.mainTextureType}),o._shouldRender=!1,o}return m(t,e),Object.defineProperty(t.prototype,"blurHorizontalSize",{get:function(){return this._horizontalBlurPostprocess.kernel},set:function(e){this._horizontalBlurPostprocess.kernel=e,this._options.blurHorizontalSize=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"blurVerticalSize",{get:function(){return this._verticalBlurPostprocess.kernel},set:function(e){this._verticalBlurPostprocess.kernel=e,this._options.blurVerticalSize=e},enumerable:!1,configurable:!0}),t.prototype.getEffectName=function(){return t.EffectName},t.prototype._numInternalDraws=function(){return 2},t.prototype._createMergeEffect=function(){return this._engine.createEffect("glowMapMerge",[Nr.PositionKind],["offset"],["textureSampler"],this._options.isStroke?"#define STROKE \n":void 0)},t.prototype._createTextureAndPostProcesses=function(){var e=this,t=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,i=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;t=this._engine.needPOTTextures?ir(t,this._maxSize):t,i=this._engine.needPOTTextures?ir(i,this._maxSize):i;var r;r=this._engine.getCaps().textureHalfFloatRender?u.TEXTURETYPE_HALF_FLOAT:u.TEXTURETYPE_UNSIGNED_INT,this._blurTexture=new Pl("HighlightLayerBlurRTT",{width:t,height:i},this._scene,!1,!0,r),this._blurTexture.wrapU=Ja.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=Ja.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(Ja.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],this._options.alphaBlendingMode===u.ALPHA_COMBINE?(this._downSamplePostprocess=new qc("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,Ja.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add((function(t){t.setTexture("textureSampler",e._mainTexture)})),this._horizontalBlurPostprocess=new ov("HighlightLayerHBP",new U(1,0),this._options.blurHorizontalSize,1,null,Ja.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add((function(e){e.setFloat2("screenSize",t,i)})),this._verticalBlurPostprocess=new ov("HighlightLayerVBP",new U(0,1),this._options.blurVerticalSize,1,null,Ja.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add((function(e){e.setFloat2("screenSize",t,i)})),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new Om("HighlightLayerHBP",new U(1,0),this._options.blurHorizontalSize/2,{width:t,height:i},null,Ja.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,r),this._horizontalBlurPostprocess.width=t,this._horizontalBlurPostprocess.height=i,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add((function(t){t.setTexture("textureSampler",e._mainTexture)})),this._verticalBlurPostprocess=new Om("HighlightLayerVBP",new U(0,1),this._options.blurVerticalSize/2,{width:t,height:i},null,Ja.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,r),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add((function(){e.onBeforeBlurObservable.notifyObservers(e);var t=e._blurTexture.renderTarget;t&&(e._scene.postProcessManager.directRender(e._postProcesses,t,!0),e._engine.unBindFramebuffer(t,!0)),e.onAfterBlurObservable.notifyObservers(e)})),this._postProcesses.map((function(e){e.autoClear=!1}))},t.prototype.needStencil=function(){return!0},t.prototype.isReady=function(t,i){var r=t.getMaterial(),n=t.getRenderingMesh();if(!r||!n||!this._meshes)return!1;var o=null,a=this._meshes[n.uniqueId];return a&&a.glowEmissiveOnly&&r&&(o=r.emissiveTexture),e.prototype._isReady.call(this,t,i,o)},t.prototype._internalRender=function(e,t){e.setTexture("textureSampler",this._blurTexture);var i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(u.REPLACE),i.setStencilOperationFail(u.KEEP),i.setStencilOperationDepthFail(u.KEEP),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&0===t&&(e.setFloat("offset",0),i.setStencilFunction(u.NOTEQUAL),i.drawElementsType(Ca.TriangleFillMode,0,6)),this.innerGlow&&1===t&&(e.setFloat("offset",1),i.setStencilFunction(u.EQUAL),i.drawElementsType(Ca.TriangleFillMode,0,6)),i.restoreStencilState()},t.prototype.shouldRender=function(){return!!e.prototype.shouldRender.call(this)&&!!this._meshes},t.prototype._shouldRenderMesh=function(t){return!(this._excludedMeshes&&this._excludedMeshes[t.uniqueId]||!e.prototype.hasMesh.call(this,t))},t.prototype._canRenderMesh=function(e,t){return!0},t.prototype._addCustomEffectDefines=function(e){e.push("#define HIGHLIGHT")},t.prototype._setEmissiveTextureAndColor=function(e,t,i){var r=this._meshes[e.uniqueId];r?this._emissiveTextureAndColor.color.set(r.color.r,r.color.g,r.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),r&&r.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null},t.prototype.addExcludedMesh=function(e){if(this._excludedMeshes&&!this._excludedMeshes[e.uniqueId]){var t={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};t.beforeBind=e.onBeforeBindObservable.add((function(e){t.stencilState=e.getEngine().getStencilBuffer(),e.getEngine().setStencilBuffer(!1)})),t.afterRender=e.onAfterRenderObservable.add((function(e){e.getEngine().setStencilBuffer(t.stencilState)})),this._excludedMeshes[e.uniqueId]=t}},t.prototype.removeExcludedMesh=function(e){if(this._excludedMeshes){var t=this._excludedMeshes[e.uniqueId];t&&(t.beforeBind&&e.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.uniqueId]=null}},t.prototype.hasMesh=function(t){return!!this._meshes&&!!e.prototype.hasMesh.call(this,t)&&void 0!==this._meshes[t.uniqueId]&&null!==this._meshes[t.uniqueId]},t.prototype.addMesh=function(e,t,i){var r=this;if(void 0===i&&(i=!1),this._meshes){var n=this._meshes[e.uniqueId];n?n.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add((function(e){r.isEnabled&&(r._excludedMeshes&&r._excludedMeshes[e.uniqueId]?r._defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(r._instanceGlowingMeshStencilReference))})),observerDefault:e.onAfterRenderObservable.add((function(e){r.isEnabled&&r._defaultStencilReference(e)})),glowEmissiveOnly:i},e.onDisposeObservable.add((function(){r._disposeMesh(e)}))),this._shouldRender=!0}},t.prototype.removeMesh=function(e){if(this._meshes){var t=this._meshes[e.uniqueId];for(var i in t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1,this._meshes)if(this._meshes[i]){this._shouldRender=!0;break}}},t.prototype.removeAllMeshes=function(){if(this._meshes)for(var e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){var t=this._meshes[e];t&&this.removeMesh(t.mesh)}},t.prototype._defaultStencilReference=function(e){e.getScene().getEngine().setStencilFunctionReference(t.NormalMeshStencilReference)},t.prototype._disposeMesh=function(e){this.removeMesh(e),this.removeExcludedMesh(e)},t.prototype.dispose=function(){if(this._meshes){for(var t in this._meshes)(i=this._meshes[t])&&i.mesh&&(i.observerHighlight&&i.mesh.onBeforeBindObservable.remove(i.observerHighlight),i.observerDefault&&i.mesh.onAfterRenderObservable.remove(i.observerDefault));this._meshes=null}if(this._excludedMeshes){for(var t in this._excludedMeshes){var i;(i=this._excludedMeshes[t])&&(i.beforeBind&&i.mesh.onBeforeBindObservable.remove(i.beforeBind),i.afterRender&&i.mesh.onAfterRenderObservable.remove(i.afterRender))}this._excludedMeshes=null}e.prototype.dispose.call(this)},t.prototype.getClassName=function(){return"HighlightLayer"},t.prototype.serialize=function(){var e=Ke.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(var t in this._meshes){var i=this._meshes[t];i&&e.meshes.push({glowEmissiveOnly:i.glowEmissiveOnly,color:i.color.asArray(),meshId:i.mesh.id})}if(e.excludedMeshes=[],this._excludedMeshes)for(var r in this._excludedMeshes){var n=this._excludedMeshes[r];n&&e.excludedMeshes.push(n.mesh.id)}return e},t.Parse=function(e,i,r){var n,o=Ke.Parse((function(){return new t(e.name,i,e.options)}),e,i,r);for(n=0;n<e.excludedMeshes.length;n++)(a=i.getMeshById(e.excludedMeshes[n]))&&o.addExcludedMesh(a);for(n=0;n<e.meshes.length;n++){var a,s=e.meshes[n];(a=i.getMeshById(s.meshId))&&o.addMesh(a,Z.FromArray(s.color),s.glowEmissiveOnly)}return o},t.EffectName="HighlightLayer",t.NeutralColor=new J(0,0,0,0),t.GlowingMeshStencilReference=2,t.NormalMeshStencilReference=1,v([Ie()],t.prototype,"innerGlow",void 0),v([Ie()],t.prototype,"outerGlow",void 0),v([Ie()],t.prototype,"blurHorizontalSize",null),v([Ie()],t.prototype,"blurVerticalSize",null),v([Ie("options")],t.prototype,"_options",void 0),t}(iv);a("BABYLON.HighlightLayer",av);var sv=function(){function e(e){this.name=Vr.NAME_LAYER,this.scene=e||M.LastCreatedScene,this.scene&&(this._engine=this.scene.getEngine(),this.scene.layers=[])}return e.prototype.register=function(){this.scene._beforeCameraDrawStage.registerStep(Vr.STEP_BEFORECAMERADRAW_LAYER,this,this._drawCameraBackground),this.scene._afterCameraDrawStage.registerStep(Vr.STEP_AFTERCAMERADRAW_LAYER,this,this._drawCameraForegroundWithPostProcessing),this.scene._afterCameraPostProcessStage.registerStep(Vr.STEP_AFTERCAMERAPOSTPROCESS_LAYER,this,this._drawCameraForegroundWithoutPostProcessing),this.scene._beforeRenderTargetDrawStage.registerStep(Vr.STEP_BEFORERENDERTARGETDRAW_LAYER,this,this._drawRenderTargetBackground),this.scene._afterRenderTargetDrawStage.registerStep(Vr.STEP_AFTERRENDERTARGETDRAW_LAYER,this,this._drawRenderTargetForegroundWithPostProcessing),this.scene._afterRenderTargetPostProcessStage.registerStep(Vr.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER,this,this._drawRenderTargetForegroundWithoutPostProcessing)},e.prototype.rebuild=function(){for(var e=0,t=this.scene.layers;e<t.length;e++)t[e]._rebuild()},e.prototype.dispose=function(){for(var e=this.scene.layers;e.length;)e[0].dispose()},e.prototype._draw=function(e){var t=this.scene.layers;if(t.length){this._engine.setDepthBuffer(!1);for(var i=0,r=t;i<r.length;i++){var n=r[i];e(n)&&n.render()}this._engine.setDepthBuffer(!0)}},e.prototype._drawCameraPredicate=function(e,t,i,r){return!e.renderOnlyInRenderTargetTextures&&e.isBackground===t&&e.applyPostProcess===i&&!!(e.layerMask&r)},e.prototype._drawCameraBackground=function(e){var t=this;this._draw((function(i){return t._drawCameraPredicate(i,!0,!0,e.layerMask)}))},e.prototype._drawCameraForegroundWithPostProcessing=function(e){var t=this;this._draw((function(i){return t._drawCameraPredicate(i,!1,!0,e.layerMask)}))},e.prototype._drawCameraForegroundWithoutPostProcessing=function(e){var t=this;this._draw((function(i){return t._drawCameraPredicate(i,!1,!1,e.layerMask)}))},e.prototype._drawRenderTargetPredicate=function(e,t,i,r,n){return e.renderTargetTextures.length>0&&e.isBackground===t&&e.applyPostProcess===i&&e.renderTargetTextures.indexOf(n)>-1&&!!(e.layerMask&r)},e.prototype._drawRenderTargetBackground=function(e){var t=this;this._draw((function(i){return t._drawRenderTargetPredicate(i,!0,!0,t.scene.activeCamera.layerMask,e)}))},e.prototype._drawRenderTargetForegroundWithPostProcessing=function(e){var t=this;this._draw((function(i){return t._drawRenderTargetPredicate(i,!1,!0,t.scene.activeCamera.layerMask,e)}))},e.prototype._drawRenderTargetForegroundWithoutPostProcessing=function(e){var t=this;this._draw((function(i){return t._drawRenderTargetPredicate(i,!1,!1,t.scene.activeCamera.layerMask,e)}))},e.prototype.addFromContainer=function(e){var t=this;e.layers&&e.layers.forEach((function(e){t.scene.layers.push(e)}))},e.prototype.removeFromContainer=function(e,t){var i=this;void 0===t&&(t=!1),e.layers&&e.layers.forEach((function(e){var r=i.scene.layers.indexOf(e);-1!==r&&i.scene.layers.splice(r,1),t&&e.dispose()}))},e}();li.ShadersStore.layerPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;\n#include<helperFunctions>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef LINEAR\nbaseColor.rgb=toGammaSpace(baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";li.ShadersStore.layerVertexShader="attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";var lv=function(){function e(e,t,i,r,n){this.name=e,this._applyPostProcess=!0,this.scale=new U(1,1),this.offset=new U(0,0),this.alphaBlendingMode=u.ALPHA_COMBINE,this.layerMask=268435455,this.renderTargetTextures=[],this.renderOnlyInRenderTargetTextures=!1,this.isEnabled=!0,this._vertexBuffers={},this.onDisposeObservable=new f,this.onBeforeRenderObservable=new f,this.onAfterRenderObservable=new f,this.texture=t?new Ja(t,i,!0):null,this.isBackground=void 0===r||r,this.color=void 0===n?new J(1,1,1,1):n,this._scene=i||M.LastCreatedScene;var o=this._scene._getComponent(Vr.NAME_LAYER);o||(o=new sv(this._scene),this._scene._addComponent(o)),this._scene.layers.push(this);var a=this._scene.getEngine();this._drawWrapper=new ho(a);var s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1);var l=new Nr(a,s,Nr.PositionKind,!1,!1,2);this._vertexBuffers[Nr.PositionKind]=l,this._createIndexBuffer()}return Object.defineProperty(e.prototype,"applyPostProcess",{get:function(){return this.isBackground||this._applyPostProcess},set:function(e){this._applyPostProcess=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onBeforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onAfterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)},enumerable:!1,configurable:!0}),e.prototype._createIndexBuffer=function(){var e=this._scene.getEngine(),t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)},e.prototype._rebuild=function(){var e=this._vertexBuffers[Nr.PositionKind];e&&e._rebuild(),this._createIndexBuffer()},e.prototype.isReady=function(){var e,t=this._scene.getEngine(),i="";this.alphaTest&&(i="#define ALPHATEST"),this.texture&&!this.texture.gammaSpace&&(i+="\n#define LINEAR"),this._previousDefines!==i&&(this._previousDefines=i,this._drawWrapper.effect=t.createEffect("layer",[Nr.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],i));var r=this._drawWrapper.effect;return(null==r?void 0:r.isReady())&&(null===(e=this.texture)||void 0===e?void 0:e.isReady())},e.prototype.render=function(){if(this.isEnabled){var e=this._scene.getEngine();if(this.isReady()){var t=this._drawWrapper.effect;this.onBeforeRenderObservable.notifyObservers(this),e.enableEffect(this._drawWrapper),e.setState(!1),t.setTexture("textureSampler",this.texture),t.setMatrix("textureMatrix",this.texture.getTextureMatrix()),t.setFloat4("color",this.color.r,this.color.g,this.color.b,this.color.a),t.setVector2("offset",this.offset),t.setVector2("scale",this.scale),e.bindBuffers(this._vertexBuffers,this._indexBuffer,t),this.alphaTest?e.drawElementsType(Ca.TriangleFillMode,0,6):(e.setAlphaMode(this.alphaBlendingMode),e.drawElementsType(Ca.TriangleFillMode,0,6),e.setAlphaMode(u.ALPHA_DISABLE)),this.onAfterRenderObservable.notifyObservers(this)}}},e.prototype.dispose=function(){var e=this._vertexBuffers[Nr.PositionKind];e&&(e.dispose(),this._vertexBuffers[Nr.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.texture&&(this.texture.dispose(),this.texture=null),this.renderTargetTextures=[];var t=this._scene.layers.indexOf(this);this._scene.layers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderObservable.clear()},e}(),cv=function(){function e(e,t,i,r,n){this.size=e,this.position=t,this.alphaMode=u.ALPHA_ONEONE,this.color=i||new Z(1,1,1),this.texture=r?new Ja(r,n.getScene(),!0):null,this._system=n;var o=n.scene.getEngine();this._drawWrapper=new ho(o),this._drawWrapper.effect=o.createEffect("lensFlare",[Nr.PositionKind],["color","viewportMatrix"],["textureSampler"],""),n.lensFlares.push(this)}return e.AddFlare=function(t,i,r,n,o){return new e(t,i,r,n,o)},e.prototype.dispose=function(){this.texture&&this.texture.dispose();var e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)},e}();li.ShadersStore.lensFlarePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";li.ShadersStore.lensFlareVertexShader="attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";var uv=function(){function e(t,i,r){this.name=t,this.lensFlares=[],this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=r||M.LastCreatedScene,e._SceneComponentInitialization(this._scene),this._emitter=i,this.id=t,r.lensFlareSystems.push(this),this.meshesSelectionPredicate=function(e){return r.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&!!(e.layerMask&r.activeCamera.layerMask)};var n=r.getEngine(),o=[];o.push(1,1),o.push(-1,1),o.push(-1,-1),o.push(1,-1),this._vertexBuffers[Nr.PositionKind]=new Nr(n,o,Nr.PositionKind,!1,!1,2),this._createIndexBuffer()}return Object.defineProperty(e.prototype,"scene",{get:function(){return this._scene},enumerable:!1,configurable:!0}),e.prototype._createIndexBuffer=function(){var e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)},Object.defineProperty(e.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e},enumerable:!1,configurable:!0}),e.prototype.getScene=function(){return this._scene},e.prototype.getEmitter=function(){return this._emitter},e.prototype.setEmitter=function(e){this._emitter=e},e.prototype.getEmitterPosition=function(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position},e.prototype.computeEffectivePosition=function(e){var t=this.getEmitterPosition();t=V.Project(t,z.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=V.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(e.x-=this.viewportBorder,e.y-=this.viewportBorder,e.width+=2*this.viewportBorder,e.height+=2*this.viewportBorder,t.x+=this.viewportBorder,t.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder);var i=this._scene.useRightHandedSystem;return!!(t.z>0&&!i||t.z<0&&i)&&(this._positionX>e.x&&this._positionX<e.x+e.width&&this._positionY>e.y&&(this._positionY,e.y,e.height),!0)},e.prototype._isVisible=function(){if(!this._isEnabled||!this._scene.activeCamera)return!1;var e=this.getEmitterPosition().subtract(this._scene.activeCamera.globalPosition),t=e.length();e.normalize();var i=new hs(this._scene.activeCamera.globalPosition,e),r=this._scene.pickWithRay(i,this.meshesSelectionPredicate,!0);return!r||!r.hit||r.distance>t},e.prototype.render=function(){if(!this._scene.activeCamera)return!1;var e,t,i=this._scene.getEngine(),r=this._scene.activeCamera.viewport.toGlobal(i.getRenderWidth(!0),i.getRenderHeight(!0));if(!this.computeEffectivePosition(r))return!1;if(!this._isVisible())return!1;var n=(e=this._positionX<this.borderLimit+r.x?this.borderLimit+r.x-this._positionX:this._positionX>r.x+r.width-this.borderLimit?this._positionX-r.x-r.width+this.borderLimit:0)>(t=this._positionY<this.borderLimit+r.y?this.borderLimit+r.y-this._positionY:this._positionY>r.y+r.height-this.borderLimit?this._positionY-r.y-r.height+this.borderLimit:0)?e:t;(n-=this.viewportBorder)>this.borderLimit&&(n=this.borderLimit);var o=1-j.Clamp(n/this.borderLimit,0,1);if(o<0)return!1;o>1&&(o=1),this.viewportBorder>0&&(r.x+=this.viewportBorder,r.y+=this.viewportBorder,r.width-=2*this.viewportBorder,r.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);var a=r.x+r.width/2,s=r.y+r.height/2,l=a-this._positionX,c=s-this._positionY;i.setState(!1),i.setDepthBuffer(!1);for(var h=0;h<this.lensFlares.length;h++){var d=this.lensFlares[h];if(d._drawWrapper.effect.isReady()&&(!d.texture||d.texture.isReady())){i.enableEffect(d._drawWrapper),i.bindBuffers(this._vertexBuffers,this._indexBuffer,d._drawWrapper.effect),i.setAlphaMode(d.alphaMode);var p=a-l*d.position,f=s-c*d.position,_=d.size,m=d.size*i.getAspectRatio(this._scene.activeCamera,!0),g=p/(r.width+2*r.x)*2-1,v=1-f/(r.height+2*r.y)*2,y=z.FromValues(_/2,0,0,0,0,m/2,0,0,0,0,1,0,g,v,0,1);d._drawWrapper.effect.setMatrix("viewportMatrix",y),d._drawWrapper.effect.setTexture("textureSampler",d.texture),d._drawWrapper.effect.setFloat4("color",d.color.r*o,d.color.g*o,d.color.b*o,1),i.drawElementsType(Ca.TriangleFillMode,0,6)}}return i.setDepthBuffer(!0),i.setAlphaMode(u.ALPHA_DISABLE),!0},e.prototype.rebuild=function(){var e;for(var t in this._createIndexBuffer(),this._vertexBuffers)null===(e=this._vertexBuffers[t])||void 0===e||e._rebuild()},e.prototype.dispose=function(){var e=this._vertexBuffers[Nr.PositionKind];for(e&&(e.dispose(),this._vertexBuffers[Nr.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null);this.lensFlares.length;)this.lensFlares[0].dispose();var t=this._scene.lensFlareSystems.indexOf(this);this._scene.lensFlareSystems.splice(t,1)},e.Parse=function(t,i,r){var n=i.getLastEntryById(t.emitterId),o=t.name||"lensFlareSystem#"+t.emitterId,a=new e(o,n,i);a.id=t.id||o,a.borderLimit=t.borderLimit;for(var s=0;s<t.flares.length;s++){var l=t.flares[s];cv.AddFlare(l.size,l.position,Z.FromArray(l.color),l.textureName?r+l.textureName:"",a)}return a},e.prototype.serialize=function(){var e={};e.id=this.id,e.name=this.name,e.emitterId=this.getEmitter().id,e.borderLimit=this.borderLimit,e.flares=[];for(var t=0;t<this.lensFlares.length;t++){var i=this.lensFlares[t];e.flares.push({size:i.size,position:i.position,color:i.color.asArray(),textureName:rr.GetFilename(i.texture?i.texture.name:"")})}return e},e._SceneComponentInitialization=function(e){throw He("LensFlareSystemSceneComponent")},e}();c.AddParser(Vr.NAME_LENSFLARESYSTEM,(function(e,t,i,r){if(void 0!==e.lensFlareSystems&&null!==e.lensFlareSystems){i.lensFlareSystems||(i.lensFlareSystems=[]);for(var n=0,o=e.lensFlareSystems.length;n<o;n++){var a=e.lensFlareSystems[n],s=uv.Parse(a,t,r);i.lensFlareSystems.push(s)}}})),c.prototype.getLensFlareSystemByName=function(e){for(var t=0;t<this.lensFlareSystems.length;t++)if(this.lensFlareSystems[t].name===e)return this.lensFlareSystems[t];return null},c.prototype.getLensFlareSystemById=function(e){for(var t=0;t<this.lensFlareSystems.length;t++)if(this.lensFlareSystems[t].id===e)return this.lensFlareSystems[t];return null},c.prototype.getLensFlareSystemByID=function(e){return this.getLensFlareSystemById(e)},c.prototype.removeLensFlareSystem=function(e){var t=this.lensFlareSystems.indexOf(e);return-1!==t&&this.lensFlareSystems.splice(t,1),t},c.prototype.addLensFlareSystem=function(e){this.lensFlareSystems.push(e)};var hv=function(){function e(e){this.name=Vr.NAME_LENSFLARESYSTEM,this.scene=e,e.lensFlareSystems=[]}return e.prototype.register=function(){this.scene._afterCameraDrawStage.registerStep(Vr.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM,this,this._draw)},e.prototype.rebuild=function(){for(var e=0;e<this.scene.lensFlareSystems.length;e++)this.scene.lensFlareSystems[e].rebuild()},e.prototype.addFromContainer=function(e){var t=this;e.lensFlareSystems&&e.lensFlareSystems.forEach((function(e){t.scene.addLensFlareSystem(e)}))},e.prototype.removeFromContainer=function(e,t){var i=this;e.lensFlareSystems&&e.lensFlareSystems.forEach((function(e){i.scene.removeLensFlareSystem(e),t&&e.dispose()}))},e.prototype.serialize=function(e){e.lensFlareSystems=[];for(var t=0,i=this.scene.lensFlareSystems;t<i.length;t++){var r=i[t];e.lensFlareSystems.push(r.serialize())}},e.prototype.dispose=function(){for(var e=this.scene.lensFlareSystems;e.length;)e[0].dispose()},e.prototype._draw=function(e){if(this.scene.lensFlaresEnabled){var t=this.scene.lensFlareSystems;rr.StartPerformanceCounter("Lens flares",t.length>0);for(var i=0,r=t;i<r.length;i++){var n=r[i];e.layerMask&n.layerMask&&n.render()}rr.EndPerformanceCounter("Lens flares",t.length>0)}},e}();uv._SceneComponentInitialization=function(e){var t=e._getComponent(Vr.NAME_LENSFLARESYSTEM);t||(t=new hv(e),e._addComponent(t))};li.IncludesShadersStore.bayerDitherFunctions="float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);}\nfloat bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5*mod(_P,4.0)); \nreturn 4.0*bayerDither2(P1)+bayerDither2(P2);}\nfloat bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5 *mod(_P,4.0)); \nvec2 P4=floor(0.25*mod(_P,8.0)); \nreturn 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);}\n";li.IncludesShadersStore.shadowMapFragmentExtraDeclaration="#if SM_FLOAT==0\n#include<packingFunctions>\n#endif\n#if SM_SOFTTRANSPARENTSHADOW==1\n#include<bayerDitherFunctions>\nuniform float softTransparentShadowSM;\n#endif\nvarying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nuniform vec3 lightDataSM;varying vec3 vPositionWSM;\n#endif\nuniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";li.IncludesShadersStore.shadowMapFragment="float depthSM=vDepthMetricSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\n#if SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\ndepthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\ndepthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_FragDepth=clamp(1.0-depthSM,0.0,1.0);\n#else\ngl_FragDepth=clamp(depthSM,0.0,1.0); \n#endif\n#elif SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#if SM_ESM==1\ndepthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.);\n#endif\n#if SM_FLOAT==1\ngl_FragColor=vec4(depthSM,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depthSM);\n#endif\nreturn;";li.ShadersStore.shadowMapPixelShader="#include<shadowMapFragmentExtraDeclaration>\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include<clipPlaneFragment>\n#ifdef ALPHATEXTURE\nfloat alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a;\n#ifdef ALPHATESTVALUE\nif (alphaFromAlphaTexture<ALPHATESTVALUE)\ndiscard;\n#endif\n#endif\n#if SM_SOFTTRANSPARENTSHADOW==1\n#ifdef ALPHATEXTURE\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alphaFromAlphaTexture) discard;\n#else\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard;\n#endif\n#endif\n#include<shadowMapFragment>\n}";li.IncludesShadersStore.sceneVertexDeclaration="uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\nuniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition;\n";li.IncludesShadersStore.meshVertexDeclaration="uniform mat4 world;uniform float visibility;\n";li.IncludesShadersStore.shadowMapVertexDeclaration="#include<sceneVertexDeclaration>\n#include<meshVertexDeclaration>\n";li.IncludesShadersStore.shadowMapUboDeclaration="layout(std140,column_major) uniform;\n#include<sceneUboDeclaration>\n#include<meshUboDeclaration>\n";li.IncludesShadersStore.shadowMapVertexExtraDeclaration="#if SM_NORMALBIAS==1\nuniform vec3 lightDataSM;\n#endif\nuniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nvarying vec3 vPositionWSM;\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";li.IncludesShadersStore.shadowMapVertexNormalBias="#if SM_NORMALBIAS==1\n#if SM_DIRECTIONINLIGHTDATA==1\nvec3 worldLightDirSM=normalize(-lightDataSM.xyz);\n#else\nvec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM);\n#endif\nfloat ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM;\n#endif\n";li.IncludesShadersStore.shadowMapVertexMetric="#if SM_USEDISTANCE==1\nvPositionWSM=worldPos.xyz;\n#endif\n#if SM_DEPTHTEXTURE==1\n#ifdef IS_NDC_HALF_ZRANGE\n#define BIASFACTOR 0.5\n#else\n#define BIASFACTOR 1.0\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#else\ngl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#endif\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nzSM=gl_Position.z;gl_Position.z=0.0;\n#elif SM_USEDISTANCE==0\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\nvDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n";li.ShadersStore.shadowMapVertexShader="attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef INSTANCES\nattribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;\n#endif\n#include<helperFunctions>\n#include<__decl__shadowMapVertex>\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<shadowMapVertexExtraDeclaration>\n#include<clipPlaneVertexDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#include<morphTargetsVertexGlobal>\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef NORMAL\nmat3 normWorldSM=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvec3 vNormalW=normalize(normWorldSM*normalUpdated);\n#endif\n#endif\n#include<shadowMapVertexNormalBias>\ngl_Position=viewProjection*worldPos;\n#include<shadowMapVertexMetric>\n#ifdef ALPHATEXTURE\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<clipPlaneVertex>\n}";li.ShadersStore.depthBoxBlurPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}";li.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow="#if SM_SOFTTRANSPARENTSHADOW==1\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard;\n#endif\n";var dv=function(){function e(t,i,r,n,o){this.onBeforeShadowMapRenderObservable=new f,this.onAfterShadowMapRenderObservable=new f,this.onBeforeShadowMapRenderMeshObservable=new f,this.onAfterShadowMapRenderMeshObservable=new f,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=e.FILTER_NONE,this._filteringQuality=e.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=V.Zero(),this._viewMatrix=z.Zero(),this._projectionMatrix=z.Zero(),this._transformMatrix=z.Zero(),this._cachedPosition=new V(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new V(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=z.Identity(),this._mapSize=t,this._light=i,this._scene=i.getScene(),this._camera=null!=n?n:null,this._useRedTextureType=!!o;var a=i._shadowGenerators;a||(a=i._shadowGenerators=new Map),a.set(this._camera,this),this.id=i.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer('Scene for Shadow Generator (light "'.concat(this._light.name,'")')))),e._SceneComponentInitialization(this._scene);var s=this._scene.getEngine().getCaps();r?s.textureFloatRender&&s.textureFloatLinearFiltering?this._textureType=u.TEXTURETYPE_FLOAT:s.textureHalfFloatRender&&s.textureHalfFloatLinearFiltering?this._textureType=u.TEXTURETYPE_HALF_FLOAT:this._textureType=u.TEXTURETYPE_UNSIGNED_INT:s.textureHalfFloatRender&&s.textureHalfFloatLinearFiltering?this._textureType=u.TEXTURETYPE_HALF_FLOAT:s.textureFloatRender&&s.textureFloatLinearFiltering?this._textureType=u.TEXTURETYPE_FLOAT:this._textureType=u.TEXTURETYPE_UNSIGNED_INT,this._initializeGenerator(),this._applyFilterValues()}return Object.defineProperty(e.prototype,"bias",{get:function(){return this._bias},set:function(e){this._bias=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"normalBias",{get:function(){return this._normalBias},set:function(e){this._normalBias=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"blurBoxOffset",{get:function(){return this._blurBoxOffset},set:function(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"blurScale",{get:function(){return this._blurScale},set:function(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"blurKernel",{get:function(){return this._blurKernel},set:function(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useKernelBlur",{get:function(){return this._useKernelBlur},set:function(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"depthScale",{get:function(){return void 0!==this._depthScale?this._depthScale:this._light.getDepthScale()},set:function(e){this._depthScale=e},enumerable:!1,configurable:!0}),e.prototype._validateFilter=function(e){return e},Object.defineProperty(e.prototype,"filter",{get:function(){return this._filter},set:function(t){if(t=this._validateFilter(t),this._light.needCube()){if(t===e.FILTER_BLUREXPONENTIALSHADOWMAP)return void(this.useExponentialShadowMap=!0);if(t===e.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)return void(this.useCloseExponentialShadowMap=!0);if(t===e.FILTER_PCF||t===e.FILTER_PCSS)return void(this.usePoissonSampling=!0)}t!==e.FILTER_PCF&&t!==e.FILTER_PCSS||this._scene.getEngine()._features.supportShadowSamplers?this._filter!==t&&(this._filter=t,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty()):this.usePoissonSampling=!0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"usePoissonSampling",{get:function(){return this.filter===e.FILTER_POISSONSAMPLING},set:function(t){var i=this._validateFilter(e.FILTER_POISSONSAMPLING);(t||this.filter===e.FILTER_POISSONSAMPLING)&&(this.filter=t?i:e.FILTER_NONE)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useExponentialShadowMap",{get:function(){return this.filter===e.FILTER_EXPONENTIALSHADOWMAP},set:function(t){var i=this._validateFilter(e.FILTER_EXPONENTIALSHADOWMAP);(t||this.filter===e.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=t?i:e.FILTER_NONE)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useBlurExponentialShadowMap",{get:function(){return this.filter===e.FILTER_BLUREXPONENTIALSHADOWMAP},set:function(t){var i=this._validateFilter(e.FILTER_BLUREXPONENTIALSHADOWMAP);(t||this.filter===e.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=t?i:e.FILTER_NONE)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useCloseExponentialShadowMap",{get:function(){return this.filter===e.FILTER_CLOSEEXPONENTIALSHADOWMAP},set:function(t){var i=this._validateFilter(e.FILTER_CLOSEEXPONENTIALSHADOWMAP);(t||this.filter===e.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=t?i:e.FILTER_NONE)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useBlurCloseExponentialShadowMap",{get:function(){return this.filter===e.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP},set:function(t){var i=this._validateFilter(e.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(t||this.filter===e.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=t?i:e.FILTER_NONE)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"usePercentageCloserFiltering",{get:function(){return this.filter===e.FILTER_PCF},set:function(t){var i=this._validateFilter(e.FILTER_PCF);(t||this.filter===e.FILTER_PCF)&&(this.filter=t?i:e.FILTER_NONE)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"filteringQuality",{get:function(){return this._filteringQuality},set:function(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useContactHardeningShadow",{get:function(){return this.filter===e.FILTER_PCSS},set:function(t){var i=this._validateFilter(e.FILTER_PCSS);(t||this.filter===e.FILTER_PCSS)&&(this.filter=t?i:e.FILTER_NONE)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"contactHardeningLightSizeUVRatio",{get:function(){return this._contactHardeningLightSizeUVRatio},set:function(e){this._contactHardeningLightSizeUVRatio=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"darkness",{get:function(){return this._darkness},set:function(e){this.setDarkness(e)},enumerable:!1,configurable:!0}),e.prototype.getDarkness=function(){return this._darkness},e.prototype.setDarkness=function(e){return this._darkness=e>=1?1:e<=0?0:e,this},Object.defineProperty(e.prototype,"transparencyShadow",{get:function(){return this._transparencyShadow},set:function(e){this.setTransparencyShadow(e)},enumerable:!1,configurable:!0}),e.prototype.setTransparencyShadow=function(e){return this._transparencyShadow=e,this},e.prototype.getShadowMap=function(){return this._shadowMap},e.prototype.getShadowMapForRendering=function(){return this._shadowMap2?this._shadowMap2:this._shadowMap},e.prototype.getClassName=function(){return e.CLASSNAME},e.prototype.addShadowCaster=function(e,t){if(void 0===t&&(t=!0),!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),-1===this._shadowMap.renderList.indexOf(e)&&this._shadowMap.renderList.push(e),t)for(var i=0,r=e.getChildMeshes();i<r.length;i++){var n=r[i];-1===this._shadowMap.renderList.indexOf(n)&&this._shadowMap.renderList.push(n)}return this},e.prototype.removeShadowCaster=function(e,t){if(void 0===t&&(t=!0),!this._shadowMap||!this._shadowMap.renderList)return this;var i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(var r=0,n=e.getChildren();r<n.length;r++){var o=n[r];this.removeShadowCaster(o)}return this},e.prototype.getLight=function(){return this._light},e.prototype._getCamera=function(){var e;return null!==(e=this._camera)&&void 0!==e?e:this._scene.activeCamera},Object.defineProperty(e.prototype,"mapSize",{get:function(){return this._mapSize},set:function(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()},enumerable:!1,configurable:!0}),e.prototype._initializeGenerator=function(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()},e.prototype._createTargetRenderTexture=function(){var e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new Pl(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?u.TEXTUREFORMAT_RED:u.TEXTUREFORMAT_RGBA),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?u.GREATER:u.LESS,!0,void 0,void 0,void 0,"DepthStencilForShadowGenerator-".concat(this._light.name))):this._shadowMap=new Pl(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0},e.prototype._initializeShadowMap=function(){var t=this;if(this._createTargetRenderTexture(),null!==this._shadowMap){this._shadowMap.wrapU=Ja.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=Ja.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(Ja.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=function(e,i,r,n){return t._renderForShadowMap(e,i,r,n)},this._shadowMap.customIsReadyFunction=function(){return!0};var i=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add((function(){var e;t._currentSceneUBO=t._scene.getSceneUniformBuffer(),null===(e=i._debugPushGroup)||void 0===e||e.call(i,"shadow map generation for pass id ".concat(i.currentRenderPassId),1)})),this._shadowMap.onBeforeRenderObservable.add((function(r){t._sceneUBOs&&t._scene.setSceneUniformBuffer(t._sceneUBOs[0]),t._currentFaceIndex=r,t._filter===e.FILTER_PCF&&i.setColorWrite(!1),t.getTransformMatrix(),t._scene.setTransformMatrix(t._viewMatrix,t._projectionMatrix),t._useUBO&&(t._scene.getSceneUniformBuffer().unbindEffect(),t._scene.finalizeSceneUbo())})),this._shadowMap.onAfterUnbindObservable.add((function(){var r,n;if(t._sceneUBOs&&t._scene.setSceneUniformBuffer(t._currentSceneUBO),t._scene.updateTransformMatrix(),t._filter===e.FILTER_PCF&&i.setColorWrite(!0),t.useBlurExponentialShadowMap||t.useBlurCloseExponentialShadowMap){var o=t.getShadowMapForRendering();o&&(t._scene.postProcessManager.directRender(t._blurPostProcesses,o.renderTarget,!0),i.unBindFramebuffer(o.renderTarget,!0),null===(n=i._debugPopGroup)||void 0===n||n.call(i,1))}else null===(r=i._debugPopGroup)||void 0===r||r.call(i,1)}));var r=new J(0,0,0,0),n=new J(1,1,1,1);this._shadowMap.onClearObservable.add((function(i){t._filter===e.FILTER_PCF?i.clear(n,!1,!0,!1):t.useExponentialShadowMap||t.useBlurExponentialShadowMap?i.clear(r,!0,!0,!1):i.clear(n,!0,!0,!1)})),this._shadowMap.onResizeObservable.add((function(e){t._storedUniqueId=t._shadowMap.uniqueId,t._mapSize=e.getRenderSize(),t._light._markMeshesAsLightDirty(),t.recreateShadowMap()}));for(var o=Ur.MIN_RENDERINGGROUPS;o<Ur.MAX_RENDERINGGROUPS;o++)this._shadowMap.setRenderingAutoClearDepthStencil(o,!1)}},e.prototype._initializeBlurRTTAndPostProcesses=function(){var e=this,t=this._scene.getEngine(),i=this._mapSize/this.blurScale;this.useKernelBlur&&1===this.blurScale||(this._shadowMap2=new Pl(this._light.name+"_shadowMap2",i,this._scene,!1,!0,this._textureType,void 0,void 0,!1),this._shadowMap2.wrapU=Ja.CLAMP_ADDRESSMODE,this._shadowMap2.wrapV=Ja.CLAMP_ADDRESSMODE,this._shadowMap2.updateSamplingMode(Ja.BILINEAR_SAMPLINGMODE)),this.useKernelBlur?(this._kernelBlurXPostprocess=new Om(this._light.name+"KernelBlurX",new U(1,0),this.blurKernel,1,null,Ja.BILINEAR_SAMPLINGMODE,t,!1,this._textureType),this._kernelBlurXPostprocess.width=i,this._kernelBlurXPostprocess.height=i,this._kernelBlurXPostprocess.externalTextureSamplerBinding=!0,this._kernelBlurXPostprocess.onApplyObservable.add((function(t){t.setTexture("textureSampler",e._shadowMap)})),this._kernelBlurYPostprocess=new Om(this._light.name+"KernelBlurY",new U(0,1),this.blurKernel,1,null,Ja.BILINEAR_SAMPLINGMODE,t,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,this._textureType===u.TEXTURETYPE_UNSIGNED_INT&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new hl(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,Ja.BILINEAR_SAMPLINGMODE,t,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add((function(t){t.setFloat2("screenSize",i,i),t.setTexture("textureSampler",e._shadowMap)})),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])},e.prototype._renderForShadowMap=function(e,t,i,r){var n;if(r.length)for(n=0;n<r.length;n++)this._renderSubMeshForShadowMap(r.data[n]);for(n=0;n<e.length;n++)this._renderSubMeshForShadowMap(e.data[n]);for(n=0;n<t.length;n++)this._renderSubMeshForShadowMap(t.data[n]);if(this._transparencyShadow)for(n=0;n<i.length;n++)this._renderSubMeshForShadowMap(i.data[n],!0);else for(n=0;n<i.length;n++)i.data[n].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate=!1},e.prototype._bindCustomEffectForRenderSubMeshForShadowMap=function(e,t,i){t.setMatrix("viewProjection",this.getTransformMatrix())},e.prototype._renderSubMeshForShadowMap=function(e,t){var i,r;void 0===t&&(t=!1);var n=e.getRenderingMesh(),o=e.getEffectiveMesh(),a=this._scene,s=a.getEngine(),l=e.getMaterial();if(o._internalAbstractMeshDataInfo._isActiveIntermediate=!1,l&&0!==e.verticesCount&&e._renderId!==a.getRenderId()){var c=o._getWorldMatrixDeterminant()<0,h=null!==(i=n.overrideMaterialSideOrientation)&&void 0!==i?i:l.sideOrientation;c&&(h=h===u.MATERIAL_ClockWiseSideOrientation?u.MATERIAL_CounterClockWiseSideOrientation:u.MATERIAL_ClockWiseSideOrientation);var d=h===u.MATERIAL_ClockWiseSideOrientation;s.setState(l.backFaceCulling,void 0,void 0,d,l.cullBackFaces);var p=n._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(!p.mustReturn){var f=s.getCaps().instancedArrays&&(null!==p.visibleInstances[e._id]&&void 0!==p.visibleInstances[e._id]||n.hasThinInstances);if(!this.customAllowRendering||this.customAllowRendering(e))if(this.isReady(e,f,t)){e._renderId=a.getRenderId();var _=l.shadowDepthWrapper,m=null!==(r=null==_?void 0:_.getEffect(e,this,s.currentRenderPassId))&&void 0!==r?r:e._getDrawWrapper(),g=ho.GetEffect(m);s.enableEffect(m),f||n._bind(e,g,l.fillMode),this.getTransformMatrix(),g.setFloat3("biasAndScaleSM",this.bias,this.normalBias,this.depthScale),this.getLight().getTypeID()===wa.LIGHTTYPEID_DIRECTIONALLIGHT?g.setVector3("lightDataSM",this._cachedDirection):g.setVector3("lightDataSM",this._cachedPosition);var v=this._getCamera();if(v&&g.setFloat2("depthValuesSM",this.getLight().getDepthMinZ(v),this.getLight().getDepthMinZ(v)+this.getLight().getDepthMaxZ(v)),t&&this.enableSoftTransparentShadow&&g.setFloat("softTransparentShadowSM",o.visibility*l.alpha),_)e._setMainDrawWrapperOverride(m),_.standalone?_.baseMaterial.bindForSubMesh(o.getWorldMatrix(),n,e):l.bindForSubMesh(o.getWorldMatrix(),n,e),e._setMainDrawWrapperOverride(null);else{if(this._opacityTexture&&(g.setTexture("diffuseSampler",this._opacityTexture),g.setMatrix("diffuseMatrix",this._opacityTexture.getTextureMatrix()||this._defaultTextureMatrix)),n.useBones&&n.computeBonesUsingShaders&&n.skeleton){var y=n.skeleton;if(y.isUsingTextureForMatrices){var b=y.getTransformMatrixTexture(n);if(!b)return;g.setTexture("boneSampler",b),g.setFloat("boneTextureWidth",4*(y.bones.length+1))}else g.setMatrices("mBones",y.getTransformMatrices(n))}$o(n,g),n.morphTargetManager&&n.morphTargetManager.isUsingTextureForTargets&&n.morphTargetManager._bind(g);var T=e.getMesh().bakedVertexAnimationManager;f&&T&&T.isEnabled&&T.bind(g,!0),Ho(g,l,a)}this._useUBO||_||this._bindCustomEffectForRenderSubMeshForShadowMap(e,g,o),ea(g,this._scene.getSceneUniformBuffer()),this._scene.getSceneUniformBuffer().bindUniformBuffer();var E=o.getWorldMatrix();f&&(o.getMeshUniformBuffer().bindToEffect(g,"Mesh"),o.transferToEffect(E)),this.forceBackFacesOnly&&s.setState(!0,0,!1,!0,l.cullBackFaces),this.onBeforeShadowMapRenderMeshObservable.notifyObservers(n),this.onBeforeShadowMapRenderObservable.notifyObservers(g),n._processRendering(o,e,g,l.fillMode,p,f,(function(e,t){o===n||e?(o.getMeshUniformBuffer().bindToEffect(g,"Mesh"),o.transferToEffect(e?t:E)):(n.getMeshUniformBuffer().bindToEffect(g,"Mesh"),n.transferToEffect(t))})),this.forceBackFacesOnly&&s.setState(!0,0,!1,!1,l.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(g),this.onAfterShadowMapRenderMeshObservable.notifyObservers(n)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}}},e.prototype._applyFilterValues=function(){this._shadowMap&&(this.filter===e.FILTER_NONE||this.filter===e.FILTER_PCSS?this._shadowMap.updateSamplingMode(Ja.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(Ja.BILINEAR_SAMPLINGMODE))},e.prototype.forceCompilation=function(e,t){var i=this,r=g({useInstances:!1},t),n=this.getShadowMap();if(n){var o=n.renderList;if(o){for(var a=[],s=0,l=o;s<l.length;s++){var c=l[s];a.push.apply(a,c.subMeshes)}if(0!==a.length){var u=0,h=function(){var t,n;if(i._scene&&i._scene.getEngine()){for(;i.isReady(a[u],r.useInstances,null!==(n=null===(t=a[u].getMaterial())||void 0===t?void 0:t.needAlphaBlendingForMesh(a[u].getMesh()))&&void 0!==n&&n);)if(++u>=a.length)return void(e&&e(i));setTimeout(h,16)}};h()}else e&&e(this)}else e&&e(this)}else e&&e(this)},e.prototype.forceCompilationAsync=function(e){var t=this;return new Promise((function(i){t.forceCompilation((function(){i()}),e)}))},e.prototype._isReadyCustomDefines=function(e,t,i){},e.prototype._prepareShadowDefines=function(e,t,i,r){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(this._textureType!==u.TEXTURETYPE_UNSIGNED_INT?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));var n=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&n.isVerticesDataPresent(Nr.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===wa.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&r?"1":"0")),this._isReadyCustomDefines(i,e,t),i},e.prototype.isReady=function(t,i,r){var n,o=t.getMaterial(),a=null==o?void 0:o.shadowDepthWrapper;if(this._opacityTexture=null,!o)return!1;var s=[];if(this._prepareShadowDefines(t,i,s,r),a){if(!a.isReadyForSubMesh(t,s,this,i,this._scene.getEngine().currentRenderPassId))return!1}else{var l=t._getDrawWrapper(void 0,!0),c=l.effect,u=l.defines,h=[Nr.PositionKind],d=t.getMesh();this.normalBias&&d.isVerticesDataPresent(Nr.NormalKind)&&(h.push(Nr.NormalKind),s.push("#define NORMAL"),d.nonUniformScaling&&s.push("#define NONUNIFORMSCALING"));var p=o.needAlphaTesting();if((p||o.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=o.opacityTexture:this._opacityTexture=o.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;var f=null!==(n=o.alphaCutOff)&&void 0!==n?n:e.DEFAULT_ALPHA_CUTOFF;s.push("#define ALPHATEXTURE"),p&&s.push("#define ALPHATESTVALUE ".concat(f).concat(f%1==0?".":"")),d.isVerticesDataPresent(Nr.UVKind)&&(h.push(Nr.UVKind),s.push("#define UV1")),d.isVerticesDataPresent(Nr.UV2Kind)&&1===this._opacityTexture.coordinatesIndex&&(h.push(Nr.UV2Kind),s.push("#define UV2"))}var _=new ll;if(d.useBones&&d.computeBonesUsingShaders&&d.skeleton){h.push(Nr.MatricesIndicesKind),h.push(Nr.MatricesWeightsKind),d.numBoneInfluencers>4&&(h.push(Nr.MatricesIndicesExtraKind),h.push(Nr.MatricesWeightsExtraKind));var m=d.skeleton;s.push("#define NUM_BONE_INFLUENCERS "+d.numBoneInfluencers),d.numBoneInfluencers>0&&_.addCPUSkinningFallback(0,d),m.isUsingTextureForMatrices?s.push("#define BONETEXTURE"):s.push("#define BonesPerMesh "+(m.bones.length+1))}else s.push("#define NUM_BONE_INFLUENCERS 0");var g=d.morphTargetManager,v=0;if(g&&(v=g.numMaxInfluencers||g.numInfluencers)>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+v),g.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),qo(h,d,v)),zo(o,this._scene,s),i&&(s.push("#define INSTANCES"),Jo(h),t.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(var y=0,b=this.customShaderOptions.defines;y<b.length;y++){var T=b[y];-1===s.indexOf(T)&&s.push(T)}var E=d.bakedVertexAnimationManager;i&&E&&E.isEnabled&&(s.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),h.push("bakedVertexAnimationSettingsInstanced"));var S=s.join("\n");if(u!==S){u=S;var x="shadowMap",A=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","morphTargetCount","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],C=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"];if(Go(A),this.customShaderOptions){if(x=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(var R=0,P=this.customShaderOptions.attributes;R<P.length;R++){var I=P[R];-1===h.indexOf(I)&&h.push(I)}if(this.customShaderOptions.uniforms)for(var M=0,O=this.customShaderOptions.uniforms;M<O.length;M++){var D=O[M];-1===A.indexOf(D)&&A.push(D)}if(this.customShaderOptions.samplers)for(var N=0,F=this.customShaderOptions.samplers;N<F.length;N++){var L=F[N];-1===C.indexOf(L)&&C.push(L)}}var w=this._scene.getEngine();c=w.createEffect(x,{attributes:h,uniformsNames:A,uniformBuffersNames:["Scene","Mesh"],samplers:C,defines:S,fallbacks:_,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:v}},w),l.setEffect(c,u)}if(!c.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(this._blurPostProcesses&&this._blurPostProcesses.length||this._initializeBlurRTTAndPostProcesses()),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady()||this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady()||this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())},e.prototype.prepareDefines=function(t,i){var r=this._scene,n=this._light;r.shadowsEnabled&&n.shadowEnabled&&(t["SHADOW"+i]=!0,this.useContactHardeningShadow?(t["SHADOWPCSS"+i]=!0,this._filteringQuality===e.QUALITY_LOW?t["SHADOWLOWQUALITY"+i]=!0:this._filteringQuality===e.QUALITY_MEDIUM&&(t["SHADOWMEDIUMQUALITY"+i]=!0)):this.usePercentageCloserFiltering?(t["SHADOWPCF"+i]=!0,this._filteringQuality===e.QUALITY_LOW?t["SHADOWLOWQUALITY"+i]=!0:this._filteringQuality===e.QUALITY_MEDIUM&&(t["SHADOWMEDIUMQUALITY"+i]=!0)):this.usePoissonSampling?t["SHADOWPOISSON"+i]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?t["SHADOWESM"+i]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(t["SHADOWCLOSEESM"+i]=!0),n.needCube()&&(t["SHADOWCUBE"+i]=!0))},e.prototype.bindShadowLight=function(t,i){var r=this._light;if(this._scene.shadowsEnabled&&r.shadowEnabled){var n=this._getCamera();if(n){var o=this.getShadowMap();o&&(r.needCube()||i.setMatrix("lightMatrix"+t,this.getTransformMatrix()),this._filter===e.FILTER_PCF?(i.setDepthStencilTexture("shadowSampler"+t,this.getShadowMapForRendering()),r._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),o.getSize().width,1/o.getSize().width,this.frustumEdgeFalloff,t)):this._filter===e.FILTER_PCSS?(i.setDepthStencilTexture("shadowSampler"+t,this.getShadowMapForRendering()),i.setTexture("depthSampler"+t,this.getShadowMapForRendering()),r._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/o.getSize().width,this._contactHardeningLightSizeUVRatio*o.getSize().width,this.frustumEdgeFalloff,t)):(i.setTexture("shadowSampler"+t,this.getShadowMapForRendering()),r._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/o.getSize().width,this.depthScale,this.frustumEdgeFalloff,t)),r._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(n),this.getLight().getDepthMinZ(n)+this.getLight().getDepthMaxZ(n),t))}}},Object.defineProperty(e.prototype,"viewMatrix",{get:function(){return this._viewMatrix},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"projectionMatrix",{get:function(){return this._projectionMatrix},enumerable:!1,configurable:!0}),e.prototype.getTransformMatrix=function(){var e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;var t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),V.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(V.Dot(this._lightDirection,V.Up()))&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),z.LookAtLHToRef(t,t.add(this._lightDirection),V.Up(),this._viewMatrix);var i=this.getShadowMap();if(i){var r=i.renderList;r&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,r)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix},e.prototype.recreateShadowMap=function(){var e=this._shadowMap;if(e){var t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t){this._shadowMap.renderList||(this._shadowMap.renderList=[]);for(var i=0,r=t;i<r.length;i++){var n=r[i];this._shadowMap.renderList.push(n)}}else this._shadowMap.renderList=null}},e.prototype._disposeBlurPostProcesses=function(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]},e.prototype._disposeRTTandPostProcesses=function(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()},e.prototype._disposeSceneUBOs=function(){if(this._sceneUBOs){for(var e=0,t=this._sceneUBOs;e<t.length;e++)t[e].dispose();this._sceneUBOs=[]}},e.prototype.dispose=function(){var e;if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){for(var t=this._light._shadowGenerators.entries(),i=t.next();!0!==i.done;i=t.next()){var r=(e=i.value)[0];e[1]===this&&this._light._shadowGenerators.delete(r)}0===this._light._shadowGenerators.size&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()},e.prototype.serialize=function(){var e,t={},i=this.getShadowMap();if(!i)return t;if(t.className=this.getClassName(),t.lightId=this._light.id,t.cameraId=null===(e=this._camera)||void 0===e?void 0:e.id,t.id=this.id,t.mapSize=i.getRenderSize(),t.forceBackFacesOnly=this.forceBackFacesOnly,t.darkness=this.getDarkness(),t.transparencyShadow=this._transparencyShadow,t.frustumEdgeFalloff=this.frustumEdgeFalloff,t.bias=this.bias,t.normalBias=this.normalBias,t.usePercentageCloserFiltering=this.usePercentageCloserFiltering,t.useContactHardeningShadow=this.useContactHardeningShadow,t.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,t.filteringQuality=this.filteringQuality,t.useExponentialShadowMap=this.useExponentialShadowMap,t.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,t.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.usePoissonSampling=this.usePoissonSampling,t.depthScale=this.depthScale,t.blurBoxOffset=this.blurBoxOffset,t.blurKernel=this.blurKernel,t.blurScale=this.blurScale,t.useKernelBlur=this.useKernelBlur,t.renderList=[],i.renderList)for(var r=0;r<i.renderList.length;r++){var n=i.renderList[r];t.renderList.push(n.id)}return t},e.Parse=function(t,i,r){for(var n=i.getLightById(t.lightId),o=void 0!==t.cameraId?i.getCameraById(t.cameraId):null,a=r?r(t.mapSize,n,o):new e(t.mapSize,n,void 0,o),s=a.getShadowMap(),l=0;l<t.renderList.length;l++)i.getMeshesById(t.renderList[l]).forEach((function(e){s&&(s.renderList||(s.renderList=[]),s.renderList.push(e))}));return void 0!==t.id&&(a.id=t.id),a.forceBackFacesOnly=!!t.forceBackFacesOnly,void 0!==t.darkness&&a.setDarkness(t.darkness),t.transparencyShadow&&a.setTransparencyShadow(!0),void 0!==t.frustumEdgeFalloff&&(a.frustumEdgeFalloff=t.frustumEdgeFalloff),void 0!==t.bias&&(a.bias=t.bias),void 0!==t.normalBias&&(a.normalBias=t.normalBias),t.usePercentageCloserFiltering?a.usePercentageCloserFiltering=!0:t.useContactHardeningShadow?a.useContactHardeningShadow=!0:t.usePoissonSampling?a.usePoissonSampling=!0:t.useExponentialShadowMap?a.useExponentialShadowMap=!0:t.useBlurExponentialShadowMap?a.useBlurExponentialShadowMap=!0:t.useCloseExponentialShadowMap?a.useCloseExponentialShadowMap=!0:t.useBlurCloseExponentialShadowMap?a.useBlurCloseExponentialShadowMap=!0:t.useVarianceShadowMap?a.useExponentialShadowMap=!0:t.useBlurVarianceShadowMap&&(a.useBlurExponentialShadowMap=!0),void 0!==t.contactHardeningLightSizeUVRatio&&(a.contactHardeningLightSizeUVRatio=t.contactHardeningLightSizeUVRatio),void 0!==t.filteringQuality&&(a.filteringQuality=t.filteringQuality),t.depthScale&&(a.depthScale=t.depthScale),t.blurScale&&(a.blurScale=t.blurScale),t.blurBoxOffset&&(a.blurBoxOffset=t.blurBoxOffset),t.useKernelBlur&&(a.useKernelBlur=t.useKernelBlur),t.blurKernel&&(a.blurKernel=t.blurKernel),a},e.CLASSNAME="ShadowGenerator",e.FILTER_NONE=0,e.FILTER_EXPONENTIALSHADOWMAP=1,e.FILTER_POISSONSAMPLING=2,e.FILTER_BLUREXPONENTIALSHADOWMAP=3,e.FILTER_CLOSEEXPONENTIALSHADOWMAP=4,e.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP=5,e.FILTER_PCF=6,e.FILTER_PCSS=7,e.QUALITY_HIGH=0,e.QUALITY_MEDIUM=1,e.QUALITY_LOW=2,e.DEFAULT_ALPHA_CUTOFF=.5,e._SceneComponentInitialization=function(e){throw He("ShadowGeneratorSceneComponent")},e}();li.ShadersStore.depthPixelShader="#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\nvarying float vDepthMetric;\n#ifdef PACKED\n#include<packingFunctions>\n#endif\n#ifdef STORE_CAMERASPACE_Z\nvarying vec4 vViewPos;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include<clipPlaneFragment>\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef STORE_CAMERASPACE_Z\n#ifdef PACKED\ngl_FragColor=pack(vViewPos.z);\n#else\ngl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);\n#endif\n#else\n#ifdef NONLINEARDEPTH\n#ifdef PACKED\ngl_FragColor=pack(gl_FragCoord.z);\n#else\ngl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);\n#endif\n#else\n#ifdef PACKED\ngl_FragColor=pack(vDepthMetric);\n#else\ngl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);\n#endif\n#endif\n#endif\n}";li.IncludesShadersStore.pointCloudVertexDeclaration="#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n";li.ShadersStore.depthVertexShader="attribute vec3 position;\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#include<clipPlaneVertexDeclaration>\n#include<instancesDeclaration>\nuniform mat4 viewProjection;uniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef STORE_CAMERASPACE_Z\nuniform mat4 view;varying vec4 vViewPos;\n#endif\n#include<pointCloudVertexDeclaration>\nvarying float vDepthMetric;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertexGlobal>\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#include<clipPlaneVertex>\ngl_Position=viewProjection*worldPos;\n#ifdef STORE_CAMERASPACE_Z\nvViewPos=view*worldPos;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));\n#else\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#endif\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<pointCloudVertex>\n}\n";var pv=function(){function e(t,i,r,n,o,a,s){void 0===i&&(i=u.TEXTURETYPE_FLOAT),void 0===r&&(r=null),void 0===n&&(n=!1),void 0===o&&(o=Ja.TRILINEAR_SAMPLINGMODE),void 0===a&&(a=!1);var l=this;this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=t,this._storeNonLinearDepth=n,this._storeCameraSpaceZ=a,this.isPacked=i===u.TEXTURETYPE_UNSIGNED_BYTE,this.isPacked?this.clearColor=new J(1,1,1,1):this.clearColor=new J(a?1e8:1,0,0,1),e._SceneComponentInitialization(this._scene);var c=t.getEngine();this._camera=r,o!==Ja.NEAREST_SAMPLINGMODE&&(i!==u.TEXTURETYPE_FLOAT||c._caps.textureFloatLinearFiltering||(o=Ja.NEAREST_SAMPLINGMODE),i!==u.TEXTURETYPE_HALF_FLOAT||c._caps.textureHalfFloatLinearFiltering||(o=Ja.NEAREST_SAMPLINGMODE));var h=this.isPacked||!c._features.supportExtendedTextureFormats?u.TEXTUREFORMAT_RGBA:u.TEXTUREFORMAT_R;this._depthMap=new Pl(null!=s?s:"DepthRenderer",{width:c.getRenderWidth(),height:c.getRenderHeight()},this._scene,!1,!0,i,!1,o,void 0,void 0,void 0,h),this._depthMap.wrapU=Ja.CLAMP_ADDRESSMODE,this._depthMap.wrapV=Ja.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add((function(e){e.clear(l.clearColor,!0,!0,!0)})),this._depthMap.onBeforeBindObservable.add((function(){var e;null===(e=c._debugPushGroup)||void 0===e||e.call(c,"depth renderer",1)})),this._depthMap.onAfterUnbindObservable.add((function(){var e;null===(e=c._debugPopGroup)||void 0===e||e.call(c,1)})),this._depthMap.customIsReadyFunction=function(e,t,i){if((i||0===t)&&e.subMeshes)for(var r=0;r<e.subMeshes.length;++r){var n=e.subMeshes[r],o=n.getRenderingMesh(),a=o._getInstancesRenderList(n._id,!!n.getReplacementMesh()),s=c.getCaps().instancedArrays&&(null!==a.visibleInstances[n._id]&&void 0!==a.visibleInstances[n._id]||o.hasThinInstances);if(!l.isReady(n,s))return!1}return!0};var d=function(e){var t,i,r=e.getRenderingMesh(),n=e.getEffectiveMesh(),o=l._scene,a=o.getEngine(),s=e.getMaterial();if(n._internalAbstractMeshDataInfo._isActiveIntermediate=!1,s&&!n.infiniteDistance&&!s.disableDepthWrite&&0!==e.verticesCount&&e._renderId!==o.getRenderId()){var c=n._getWorldMatrixDeterminant()<0,h=null!==(t=r.overrideMaterialSideOrientation)&&void 0!==t?t:s.sideOrientation;c&&(h=h===u.MATERIAL_ClockWiseSideOrientation?u.MATERIAL_CounterClockWiseSideOrientation:u.MATERIAL_ClockWiseSideOrientation);var d=h===u.MATERIAL_ClockWiseSideOrientation;a.setState(s.backFaceCulling,0,!1,d,l.reverseCulling?!s.cullBackFaces:s.cullBackFaces);var p=r._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(!p.mustReturn){var f=a.getCaps().instancedArrays&&(null!==p.visibleInstances[e._id]&&void 0!==p.visibleInstances[e._id]||r.hasThinInstances),_=l._camera||o.activeCamera;if(l.isReady(e,f)&&_){e._renderId=o.getRenderId();var m=null===(i=n._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[a.currentRenderPassId],g=e._getDrawWrapper();!g&&m&&(g=m._getDrawWrapper());var v=_.mode===$n.ORTHOGRAPHIC_CAMERA;if(!g)return;var y=g.effect;a.enableEffect(g),f||r._bind(e,y,s.fillMode),m?m.bindForSubMesh(n.getWorldMatrix(),n,e):(y.setMatrix("viewProjection",o.getTransformMatrix()),y.setMatrix("world",n.getWorldMatrix()),l._storeCameraSpaceZ&&y.setMatrix("view",o.getViewMatrix()));var b=void 0,T=void 0;if(v?(b=!a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:1,T=a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:1):(b=a.useReverseDepthBuffer&&a.isNDCHalfZRange?_.minZ:a.isNDCHalfZRange?0:_.minZ,T=a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:_.maxZ),y.setFloat2("depthValues",b,b+T),!m){if(s.needAlphaTesting()){var E=s.getAlphaTestTexture();E&&(y.setTexture("diffuseSampler",E),y.setMatrix("diffuseMatrix",E.getTextureMatrix()))}if(r.useBones&&r.computeBonesUsingShaders&&r.skeleton){var S=r.skeleton;if(S.isUsingTextureForMatrices){var x=S.getTransformMatrixTexture(r);if(!x)return;y.setTexture("boneSampler",x),y.setFloat("boneTextureWidth",4*(S.bones.length+1))}else y.setMatrices("mBones",S.getTransformMatrices(r))}Ho(y,s,o),$o(r,y),r.morphTargetManager&&r.morphTargetManager.isUsingTextureForTargets&&r.morphTargetManager._bind(y),s.pointsCloud&&y.setFloat("pointSize",s.pointSize)}r._processRendering(n,e,y,s.fillMode,p,f,(function(e,t){return y.setMatrix("world",t)}))}}}};this._depthMap.customRenderFunction=function(e,t,i,r){var n;if(r.length)for(n=0;n<r.length;n++)d(r.data[n]);for(n=0;n<e.length;n++)d(e.data[n]);for(n=0;n<t.length;n++)d(t.data[n]);if(l.forceDepthWriteTransparentMeshes)for(n=0;n<i.length;n++)d(i.data[n]);else for(n=0;n<i.length;n++)i.data[n].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate=!1}}return e.prototype.setMaterialForRendering=function(e,t){this._depthMap.setMaterialForRendering(e,t)},e.prototype.isReady=function(e,t){var i,r=this._scene.getEngine(),n=e.getMesh(),o=n.getScene(),a=null===(i=n._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[r.currentRenderPassId];if(a)return a.isReadyForSubMesh(n,e,t);var s=e.getMaterial();if(!s||s.disableDepthWrite)return!1;var l=[],c=[Nr.PositionKind];if(s&&s.needAlphaTesting()&&s.getAlphaTestTexture()&&(l.push("#define ALPHATEST"),n.isVerticesDataPresent(Nr.UVKind)&&(c.push(Nr.UVKind),l.push("#define UV1")),n.isVerticesDataPresent(Nr.UV2Kind)&&(c.push(Nr.UV2Kind),l.push("#define UV2"))),n.useBones&&n.computeBonesUsingShaders){c.push(Nr.MatricesIndicesKind),c.push(Nr.MatricesWeightsKind),n.numBoneInfluencers>4&&(c.push(Nr.MatricesIndicesExtraKind),c.push(Nr.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),l.push("#define BonesPerMesh "+(n.skeleton?n.skeleton.bones.length+1:0));var u=e.getRenderingMesh().skeleton;(null==u?void 0:u.isUsingTextureForMatrices)&&l.push("#define BONETEXTURE")}else l.push("#define NUM_BONE_INFLUENCERS 0");var h=n.morphTargetManager,d=0;h&&(d=h.numMaxInfluencers||h.numInfluencers)>0&&(l.push("#define MORPHTARGETS"),l.push("#define NUM_MORPH_INFLUENCERS "+d),h.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),qo(c,n,d)),s.pointsCloud&&l.push("#define POINTSIZE"),t&&(l.push("#define INSTANCES"),Jo(c),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&l.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&l.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&l.push("#define PACKED"),zo(s,o,l);var p=e._getDrawWrapper(void 0,!0),f=p.defines,_=l.join("\n");if(f!==_){var m=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];Go(m),p.setEffect(r.createEffect("depth",c,m,["diffuseSampler","morphTargets","boneSampler"],_,void 0,void 0,void 0,{maxSimultaneousMorphTargets:d}),_)}return p.effect.isReady()},e.prototype.getDepthMap=function(){return this._depthMap},e.prototype.dispose=function(){var e=[];for(var t in this._scene._depthRenderer)this._scene._depthRenderer[t]===this&&e.push(t);if(e.length>0){this._depthMap.dispose();for(var i=0,r=e;i<r.length;i++)t=r[i],delete this._scene._depthRenderer[t]}},e._SceneComponentInitialization=function(e){throw He("DepthRendererSceneComponent")},e}();li.ShadersStore.minmaxReduxPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#if defined(INITIAL)\nuniform sampler2D sourceTexture;uniform vec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4);\n#ifdef DEPTH_REDUX\nfloat maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);\n#else\nfloat maxz=max(max(max(f1,f2),f3),f4);\n#endif\nglFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(MAIN)\nuniform vec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(ONEBEFORELAST)\nuniform ivec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(LAST)\nvoid main(void)\n{glFragColor=vec4(0.);if (true) { \ndiscard;}}\n#endif\n";var fv=function(){function e(e){var t=this;this.onAfterReductionPerformed=new f,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new Lr(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((function(){t._postProcessManager._rebuild()}))}return Object.defineProperty(e.prototype,"sourceTexture",{get:function(){return this._sourceTexture},enumerable:!1,configurable:!0}),e.prototype.setSourceTexture=function(e,t,i,r){var n=this;if(void 0===i&&(i=u.TEXTURETYPE_HALF_FLOAT),void 0===r&&(r=!0),e!==this._sourceTexture){this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=r;var o=this._camera.getScene(),a=new hl("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,u.TEXTURE_NEAREST_NEAREST,o.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,u.TEXTUREFORMAT_RG);a.autoClear=!1,a.forceFullscreenViewport=r;var s=this._sourceTexture.getRenderWidth(),l=this._sourceTexture.getRenderHeight();a.onApply=function(e,t){return function(i){i.setTexture("sourceTexture",n._sourceTexture),i.setFloat2("texSize",e,t)}}(s,l),this._reductionSteps.push(a);for(var c=1;s>1||l>1;){s=Math.max(Math.round(s/2),1),l=Math.max(Math.round(l/2),1);var h=new hl("Reduction phase "+c,"minmaxRedux",["texSize"],null,{width:s,height:l},null,u.TEXTURE_NEAREST_NEAREST,o.getEngine(),!1,"#define "+(1==s&&1==l?"LAST":1==s||1==l?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,u.TEXTUREFORMAT_RG);h.autoClear=!1,h.forceFullscreenViewport=r,h.onApply=function(e,t){return function(i){1==e||1==t?i.setInt2("texSize",e,t):i.setFloat2("texSize",e,t)}}(s,l),this._reductionSteps.push(h),c++,1==s&&1==l&&h.onAfterRenderObservable.add(function(e,t,i){var r=new Float32Array(4*e*t),a={min:0,max:0};return function(){o.getEngine()._readTexturePixels(i.inputTexture.texture,e,t,-1,0,r,!1),a.min=r[0],a.max=r[1],n.onAfterReductionPerformed.notifyObservers(a)}}(s,l,h))}}},Object.defineProperty(e.prototype,"refreshRate",{get:function(){return this._sourceTexture?this._sourceTexture.refreshRate:-1},set:function(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"activated",{get:function(){return this._activated},enumerable:!1,configurable:!0}),e.prototype.activate=function(){var e=this;!this._onAfterUnbindObserver&&this._sourceTexture&&(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add((function(){var t,i,r=e._camera.getScene().getEngine();null===(t=r._debugPushGroup)||void 0===t||t.call(r,"min max reduction",1),e._reductionSteps[0].activate(e._camera),e._postProcessManager.directRender(e._reductionSteps,e._reductionSteps[0].inputTexture,e._forceFullscreenViewport),r.unBindFramebuffer(e._reductionSteps[0].inputTexture,!1),null===(i=r._debugPopGroup)||void 0===i||i.call(r,1)})),this._activated=!0)},e.prototype.deactivate=function(){this._onAfterUnbindObserver&&this._sourceTexture&&(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)},e.prototype.dispose=function(e){if(void 0===e&&(e=!0),e&&(this.onAfterReductionPerformed.clear(),this._onContextRestoredObserver&&(this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)),this.deactivate(),this._reductionSteps){for(var t=0;t<this._reductionSteps.length;++t)this._reductionSteps[t].dispose();this._reductionSteps=null}this._postProcessManager&&e&&this._postProcessManager.dispose(),this._sourceTexture=null},e}(),_v=function(e){function t(t){return e.call(this,t)||this}return m(t,e),Object.defineProperty(t.prototype,"depthRenderer",{get:function(){return this._depthRenderer},enumerable:!1,configurable:!0}),t.prototype.setDepthRenderer=function(t,i,r){void 0===t&&(t=null),void 0===i&&(i=u.TEXTURETYPE_HALF_FLOAT),void 0===r&&(r=!0);var n=this._camera.getScene();this._depthRenderer&&(delete n._depthRenderer[this._depthRendererId],this._depthRenderer.dispose(),this._depthRenderer=null),null===t&&(n._depthRenderer||(n._depthRenderer={}),(t=this._depthRenderer=new pv(n,i,this._camera,!1,u.TEXTURE_NEAREST_SAMPLINGMODE)).enabled=!1,this._depthRendererId="minmax"+this._camera.id,n._depthRenderer[this._depthRendererId]=t),e.prototype.setSourceTexture.call(this,t.getDepthMap(),!0,i,r)},t.prototype.setSourceTexture=function(t,i,r,n){void 0===r&&(r=u.TEXTURETYPE_HALF_FLOAT),void 0===n&&(n=!0),e.prototype.setSourceTexture.call(this,t,i,r,n)},t.prototype.activate=function(){this._depthRenderer&&(this._depthRenderer.enabled=!0),e.prototype.activate.call(this)},t.prototype.deactivate=function(){e.prototype.deactivate.call(this),this._depthRenderer&&(this._depthRenderer.enabled=!1)},t.prototype.dispose=function(t){if(void 0===t&&(t=!0),e.prototype.dispose.call(this,t),this._depthRenderer&&t){var i=this._depthRenderer.getDepthMap().getScene();i&&delete i._depthRenderer[this._depthRendererId],this._depthRenderer.dispose(),this._depthRenderer=null}},t}(fv),mv=V.Up(),gv=V.Zero(),vv=new V,yv=new V,bv=new z,Tv=function(e){function t(i,r,n,o,a){void 0===a&&(a=!0);var s=this;return t.IsSupported?((s=e.call(this,i,r,n,o,a)||this).usePercentageCloserFiltering=!0,s):(ae.Error("CascadedShadowMap is not supported by the current engine."),s)}return m(t,e),t.prototype._validateFilter=function(e){return e===dv.FILTER_NONE||e===dv.FILTER_PCF||e===dv.FILTER_PCSS?e:(ae.Error('Unsupported filter "'+e+'"!'),dv.FILTER_NONE)},Object.defineProperty(t.prototype,"numCascades",{get:function(){return this._numCascades},set:function(e){(e=Math.min(Math.max(e,t.MIN_CASCADES_COUNT),t.MAX_CASCADES_COUNT))!==this._numCascades&&(this._numCascades=e,this.recreateShadowMap(),this._recreateSceneUBOs())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"freezeShadowCastersBoundingInfo",{get:function(){return this._freezeShadowCastersBoundingInfo},set:function(e){var t=this;this._freezeShadowCastersBoundingInfoObservable&&e&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),this._freezeShadowCastersBoundingInfoObservable||e||(this._freezeShadowCastersBoundingInfoObservable=this._scene.onBeforeRenderObservable.add((function(){return t._computeShadowCastersBoundingInfo()}))),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()},enumerable:!1,configurable:!0}),t.prototype._computeShadowCastersBoundingInfo=function(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){for(var e=this._shadowMap.renderList,t=0;t<e.length;t++)if(n=e[t]){var i=n.getBoundingInfo().boundingBox;this._scbiMin.minimizeInPlace(i.minimumWorld),this._scbiMax.maximizeInPlace(i.maximumWorld)}var r=this._scene.meshes;for(t=0;t<r.length;t++){var n;(n=r[t])&&n.isVisible&&n.isEnabled&&n.receiveShadows&&(i=n.getBoundingInfo().boundingBox,this._scbiMin.minimizeInPlace(i.minimumWorld),this._scbiMax.maximizeInPlace(i.maximumWorld))}}this._shadowCastersBoundingInfo.reConstruct(this._scbiMin,this._scbiMax)},Object.defineProperty(t.prototype,"shadowCastersBoundingInfo",{get:function(){return this._shadowCastersBoundingInfo},set:function(e){this._shadowCastersBoundingInfo=e},enumerable:!1,configurable:!0}),t.prototype.setMinMaxDistance=function(e,t){this._minDistance===e&&this._maxDistance===t||(e>t&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)},Object.defineProperty(t.prototype,"minDistance",{get:function(){return this._minDistance},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"maxDistance",{get:function(){return this._maxDistance},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return t.CLASSNAME},t.prototype.getCascadeMinExtents=function(e){return e>=0&&e<this._numCascades?this._cascadeMinExtents[e]:null},t.prototype.getCascadeMaxExtents=function(e){return e>=0&&e<this._numCascades?this._cascadeMaxExtents[e]:null},Object.defineProperty(t.prototype,"shadowMaxZ",{get:function(){return this._getCamera()?this._shadowMaxZ:0},set:function(e){var t=this._getCamera();t?this._shadowMaxZ===e||e<t.minZ||e>t.maxZ&&0!==t.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0):this._shadowMaxZ=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"debug",{get:function(){return this._debug},set:function(e){this._debug=e,this._light._markMeshesAsLightDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"depthClamp",{get:function(){return this._depthClamp},set:function(e){this._depthClamp=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cascadeBlendPercentage",{get:function(){return this._cascadeBlendPercentage},set:function(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"lambda",{get:function(){return this._lambda},set:function(e){var t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)},enumerable:!1,configurable:!0}),t.prototype.getCascadeViewMatrix=function(e){return e>=0&&e<this._numCascades?this._viewMatrices[e]:null},t.prototype.getCascadeProjectionMatrix=function(e){return e>=0&&e<this._numCascades?this._projectionMatrices[e]:null},t.prototype.getCascadeTransformMatrix=function(e){return e>=0&&e<this._numCascades?this._transformMatrices[e]:null},t.prototype.setDepthRenderer=function(e){this._depthRenderer=e,this._depthReducer&&this._depthReducer.setDepthRenderer(this._depthRenderer)},Object.defineProperty(t.prototype,"autoCalcDepthBounds",{get:function(){return this._autoCalcDepthBounds},set:function(e){var t=this,i=this._getCamera();if(i){if(this._autoCalcDepthBounds=e,!e)return this._depthReducer&&this._depthReducer.deactivate(),void this.setMinMaxDistance(0,1);this._depthReducer||(this._depthReducer=new _v(i),this._depthReducer.onAfterReductionPerformed.add((function(e){var i=e.min,r=e.max;i>=r&&(i=0,r=1),i==t._minDistance&&r==t._maxDistance||t.setMinMaxDistance(i,r)})),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"autoCalcDepthBoundsRefreshRate",{get:function(){var e,t,i;return null!==(i=null===(t=null===(e=this._depthReducer)||void 0===e?void 0:e.depthRenderer)||void 0===t?void 0:t.getDepthMap().refreshRate)&&void 0!==i?i:-1},set:function(e){var t;(null===(t=this._depthReducer)||void 0===t?void 0:t.depthRenderer)&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)},enumerable:!1,configurable:!0}),t.prototype.splitFrustum=function(){this._breaksAreDirty=!0},t.prototype._splitFrustum=function(){var e=this._getCamera();if(e){for(var t=e.minZ,i=e.maxZ||this._shadowMaxZ,r=i-t,n=this._minDistance,o=t+n*r,a=t+(this._shadowMaxZ<i&&this._shadowMaxZ>=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance)*r,s=a-o,l=a/o,c=0;c<this._cascades.length;++c){var u=(c+1)/this._numCascades,h=o*Math.pow(l,u),d=o+s*u,p=this._lambda*(h-d)+d;this._cascades[c].prevBreakDistance=0===c?n:this._cascades[c-1].breakDistance,this._cascades[c].breakDistance=(p-t)/r,this._viewSpaceFrustumsZ[c]=p,this._frustumLengths[c]=(this._cascades[c].breakDistance-this._cascades[c].prevBreakDistance)*r}this._breaksAreDirty=!1}},t.prototype._computeMatrices=function(){var e=this._scene;if(this._getCamera()){V.NormalizeToRef(this._light.getShadowDirection(0),this._lightDirection),1===Math.abs(V.Dot(this._lightDirection,V.Up()))&&(this._lightDirection.z=1e-13),this._cachedDirection.copyFrom(this._lightDirection);for(var t=e.getEngine().useReverseDepthBuffer,i=0;i<this._numCascades;++i){this._computeFrustumInWorldSpace(i),this._computeCascadeFrustum(i),this._cascadeMaxExtents[i].subtractToRef(this._cascadeMinExtents[i],vv),this._frustumCenter[i].addToRef(this._lightDirection.scale(this._cascadeMinExtents[i].z),this._shadowCameraPos[i]),z.LookAtLHToRef(this._shadowCameraPos[i],this._frustumCenter[i],mv,this._viewMatrices[i]);var r=0,n=vv.z,o=this._shadowCastersBoundingInfo;o.update(this._viewMatrices[i]),n=Math.min(n,o.boundingBox.maximumWorld.z),r=this._depthClamp&&this.filter!==dv.FILTER_PCSS?Math.max(r,o.boundingBox.minimumWorld.z):Math.min(r,o.boundingBox.minimumWorld.z),z.OrthoOffCenterLHToRef(this._cascadeMinExtents[i].x,this._cascadeMaxExtents[i].x,this._cascadeMinExtents[i].y,this._cascadeMaxExtents[i].y,t?n:r,t?r:n,this._projectionMatrices[i],e.getEngine().isNDCHalfZRange),this._cascadeMinExtents[i].z=r,this._cascadeMaxExtents[i].z=n,this._viewMatrices[i].multiplyToRef(this._projectionMatrices[i],this._transformMatrices[i]),V.TransformCoordinatesToRef(gv,this._transformMatrices[i],vv),vv.scaleInPlace(this._mapSize/2),yv.copyFromFloats(Math.round(vv.x),Math.round(vv.y),Math.round(vv.z)),yv.subtractInPlace(vv).scaleInPlace(2/this._mapSize),z.TranslationToRef(yv.x,yv.y,0,bv),this._projectionMatrices[i].multiplyToRef(bv,this._projectionMatrices[i]),this._viewMatrices[i].multiplyToRef(this._projectionMatrices[i],this._transformMatrices[i]),this._transformMatrices[i].copyToArray(this._transformMatricesAsArray,16*i)}}},t.prototype._computeFrustumInWorldSpace=function(e){var i=this._getCamera();if(i){var r=this._cascades[e].prevBreakDistance,n=this._cascades[e].breakDistance,o=this._scene.getEngine().isNDCHalfZRange;i.getViewMatrix();var a=0===i.maxZ,s=i.maxZ;a&&(i.maxZ=this._shadowMaxZ,i.getProjectionMatrix(!0));var l=z.Invert(i.getTransformationMatrix());a&&(i.maxZ=s,i.getProjectionMatrix(!0));for(var c=this._scene.getEngine().useReverseDepthBuffer?4:0,u=0;u<t._FrustumCornersNDCSpace.length;++u)vv.copyFrom(t._FrustumCornersNDCSpace[(u+c)%t._FrustumCornersNDCSpace.length]),o&&-1===vv.z&&(vv.z=0),V.TransformCoordinatesToRef(vv,l,this._frustumCornersWorldSpace[e][u]);for(u=0;u<t._FrustumCornersNDCSpace.length/2;++u)vv.copyFrom(this._frustumCornersWorldSpace[e][u+4]).subtractInPlace(this._frustumCornersWorldSpace[e][u]),yv.copyFrom(vv).scaleInPlace(r),vv.scaleInPlace(n),vv.addInPlace(this._frustumCornersWorldSpace[e][u]),this._frustumCornersWorldSpace[e][u+4].copyFrom(vv),this._frustumCornersWorldSpace[e][u].addInPlace(yv)}},t.prototype._computeCascadeFrustum=function(e){if(this._cascadeMinExtents[e].copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cascadeMaxExtents[e].copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._frustumCenter[e].copyFromFloats(0,0,0),this._getCamera()){for(var t=0;t<this._frustumCornersWorldSpace[e].length;++t)this._frustumCenter[e].addInPlace(this._frustumCornersWorldSpace[e][t]);if(this._frustumCenter[e].scaleInPlace(1/this._frustumCornersWorldSpace[e].length),this.stabilizeCascades){var i=0;for(t=0;t<this._frustumCornersWorldSpace[e].length;++t){var r=this._frustumCornersWorldSpace[e][t].subtractToRef(this._frustumCenter[e],vv).length();i=Math.max(i,r)}i=Math.ceil(16*i)/16,this._cascadeMaxExtents[e].copyFromFloats(i,i,i),this._cascadeMinExtents[e].copyFromFloats(-i,-i,-i)}else{var n=this._frustumCenter[e];for(this._frustumCenter[e].addToRef(this._lightDirection,vv),z.LookAtLHToRef(n,vv,mv,bv),t=0;t<this._frustumCornersWorldSpace[e].length;++t)V.TransformCoordinatesToRef(this._frustumCornersWorldSpace[e][t],bv,vv),this._cascadeMinExtents[e].minimizeInPlace(vv),this._cascadeMaxExtents[e].maximizeInPlace(vv)}}},t.prototype._recreateSceneUBOs=function(){if(this._disposeSceneUBOs(),this._sceneUBOs)for(var e=0;e<this._numCascades;++e)this._sceneUBOs.push(this._scene.createSceneUniformBuffer('Scene for CSM Shadow Generator (light "'.concat(this._light.name,'" cascade #').concat(e,")")))},Object.defineProperty(t,"IsSupported",{get:function(){var e=M.LastCreatedEngine;return!!e&&e._features.supportCSM},enumerable:!1,configurable:!0}),t.prototype._initializeGenerator=function(){var i,r,n,o,a,s,l,c,u,h,d,p,f,_,m,g,v,y,b,T;this.penumbraDarkness=null!==(i=this.penumbraDarkness)&&void 0!==i?i:1,this._numCascades=null!==(r=this._numCascades)&&void 0!==r?r:t.DEFAULT_CASCADES_COUNT,this.stabilizeCascades=null!==(n=this.stabilizeCascades)&&void 0!==n&&n,this._freezeShadowCastersBoundingInfoObservable=null!==(o=this._freezeShadowCastersBoundingInfoObservable)&&void 0!==o?o:null,this.freezeShadowCastersBoundingInfo=null!==(a=this.freezeShadowCastersBoundingInfo)&&void 0!==a&&a,this._scbiMin=null!==(s=this._scbiMin)&&void 0!==s?s:new V(0,0,0),this._scbiMax=null!==(l=this._scbiMax)&&void 0!==l?l:new V(0,0,0),this._shadowCastersBoundingInfo=null!==(c=this._shadowCastersBoundingInfo)&&void 0!==c?c:new so(new V(0,0,0),new V(0,0,0)),this._breaksAreDirty=null===(u=this._breaksAreDirty)||void 0===u||u,this._minDistance=null!==(h=this._minDistance)&&void 0!==h?h:0,this._maxDistance=null!==(d=this._maxDistance)&&void 0!==d?d:1,this._currentLayer=null!==(p=this._currentLayer)&&void 0!==p?p:0,this._shadowMaxZ=null!==(m=null!==(f=this._shadowMaxZ)&&void 0!==f?f:null===(_=this._getCamera())||void 0===_?void 0:_.maxZ)&&void 0!==m?m:1e4,this._debug=null!==(g=this._debug)&&void 0!==g&&g,this._depthClamp=null===(v=this._depthClamp)||void 0===v||v,this._cascadeBlendPercentage=null!==(y=this._cascadeBlendPercentage)&&void 0!==y?y:.1,this._lambda=null!==(b=this._lambda)&&void 0!==b?b:.5,this._autoCalcDepthBounds=null!==(T=this._autoCalcDepthBounds)&&void 0!==T&&T,this._recreateSceneUBOs(),e.prototype._initializeGenerator.call(this)},t.prototype._createTargetRenderTexture=function(){var e=this._scene.getEngine(),t={width:this._mapSize,height:this._mapSize,layers:this.numCascades};this._shadowMap=new Pl(this._light.name+"_CSMShadowMap",t,this._scene,!1,!0,this._textureType,!1,void 0,!1,!1,void 0,this._useRedTextureType?u.TEXTUREFORMAT_RED:u.TEXTUREFORMAT_RGBA),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?u.GREATER:u.LESS,!0,void 0,void 0,void 0,"DepthStencilForCSMShadowGenerator-".concat(this._light.name)),this._shadowMap.noPrePassRenderer=!0},t.prototype._initializeShadowMap=function(){var i=this;if(e.prototype._initializeShadowMap.call(this),null!==this._shadowMap){this._transformMatricesAsArray=new Float32Array(16*this._numCascades),this._viewSpaceFrustumsZ=new Array(this._numCascades),this._frustumLengths=new Array(this._numCascades),this._lightSizeUVCorrection=new Array(2*this._numCascades),this._depthCorrection=new Array(this._numCascades),this._cascades=[],this._viewMatrices=[],this._projectionMatrices=[],this._transformMatrices=[],this._cascadeMinExtents=[],this._cascadeMaxExtents=[],this._frustumCenter=[],this._shadowCameraPos=[],this._frustumCornersWorldSpace=[];for(var r=0;r<this._numCascades;++r){this._cascades[r]={prevBreakDistance:0,breakDistance:0},this._viewMatrices[r]=z.Zero(),this._projectionMatrices[r]=z.Zero(),this._transformMatrices[r]=z.Zero(),this._cascadeMinExtents[r]=new V,this._cascadeMaxExtents[r]=new V,this._frustumCenter[r]=new V,this._shadowCameraPos[r]=new V,this._frustumCornersWorldSpace[r]=new Array(t._FrustumCornersNDCSpace.length);for(var n=0;n<t._FrustumCornersNDCSpace.length;++n)this._frustumCornersWorldSpace[r][n]=new V}var o=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.clear(),this._shadowMap.onBeforeRenderObservable.clear(),this._shadowMap.onBeforeRenderObservable.add((function(e){i._sceneUBOs&&i._scene.setSceneUniformBuffer(i._sceneUBOs[e]),i._currentLayer=e,i._filter===dv.FILTER_PCF&&o.setColorWrite(!1),i._scene.setTransformMatrix(i.getCascadeViewMatrix(e),i.getCascadeProjectionMatrix(e)),i._useUBO&&(i._scene.getSceneUniformBuffer().unbindEffect(),i._scene.finalizeSceneUbo())})),this._shadowMap.onBeforeBindObservable.add((function(){var e;i._currentSceneUBO=i._scene.getSceneUniformBuffer(),null===(e=o._debugPushGroup)||void 0===e||e.call(o,"cascaded shadow map generation for pass id ".concat(o.currentRenderPassId),1),i._breaksAreDirty&&i._splitFrustum(),i._computeMatrices()})),this._splitFrustum()}},t.prototype._bindCustomEffectForRenderSubMeshForShadowMap=function(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))},t.prototype._isReadyCustomDefines=function(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==dv.FILTER_PCSS?"1":"0"))},t.prototype.prepareDefines=function(t,i){e.prototype.prepareDefines.call(this,t,i);var r=this._scene,n=this._light;if(r.shadowsEnabled&&n.shadowEnabled){t["SHADOWCSM"+i]=!0,t["SHADOWCSMDEBUG"+i]=this.debug,t["SHADOWCSMNUM_CASCADES"+i]=this.numCascades,t["SHADOWCSM_RIGHTHANDED"+i]=r.useRightHandedSystem;var o=this._getCamera();o&&this._shadowMaxZ<=(o.maxZ||this._shadowMaxZ)&&(t["SHADOWCSMUSESHADOWMAXZ"+i]=!0),0===this.cascadeBlendPercentage&&(t["SHADOWCSMNOBLEND"+i]=!0)}},t.prototype.bindShadowLight=function(e,t){var i=this._light;if(this._scene.shadowsEnabled&&i.shadowEnabled){var r=this._getCamera();if(r){var n=this.getShadowMap();if(n){var o=n.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,0===this.cascadeBlendPercentage?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===dv.FILTER_PCF)t.setDepthStencilTexture("shadowSampler"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),o,1/o,this.frustumEdgeFalloff,e);else if(this._filter===dv.FILTER_PCSS){for(var a=0;a<this._numCascades;++a)this._lightSizeUVCorrection[2*a+0]=0===a?1:(this._cascadeMaxExtents[0].x-this._cascadeMinExtents[0].x)/(this._cascadeMaxExtents[a].x-this._cascadeMinExtents[a].x),this._lightSizeUVCorrection[2*a+1]=0===a?1:(this._cascadeMaxExtents[0].y-this._cascadeMinExtents[0].y)/(this._cascadeMaxExtents[a].y-this._cascadeMinExtents[a].y),this._depthCorrection[a]=0===a?1:(this._cascadeMaxExtents[a].z-this._cascadeMinExtents[a].z)/(this._cascadeMaxExtents[0].z-this._cascadeMinExtents[0].z);t.setDepthStencilTexture("shadowSampler"+e,n),t.setTexture("depthSampler"+e,n),t.setArray2("lightSizeUVCorrection"+e,this._lightSizeUVCorrection),t.setArray("depthCorrection"+e,this._depthCorrection),t.setFloat("penumbraDarkness"+e,this.penumbraDarkness),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/o,this._contactHardeningLightSizeUVRatio*o,this.frustumEdgeFalloff,e)}else t.setTexture("shadowSampler"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),o,1/o,this.frustumEdgeFalloff,e);i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(r),this.getLight().getDepthMinZ(r)+this.getLight().getDepthMaxZ(r),e)}}}},t.prototype.getTransformMatrix=function(){return this.getCascadeTransformMatrix(0)},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._freezeShadowCastersBoundingInfoObservable&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),this._depthReducer&&(this._depthReducer.dispose(),this._depthReducer=null)},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this),i=this.getShadowMap();if(!i)return t;if(t.numCascades=this._numCascades,t.debug=this._debug,t.stabilizeCascades=this.stabilizeCascades,t.lambda=this._lambda,t.cascadeBlendPercentage=this.cascadeBlendPercentage,t.depthClamp=this._depthClamp,t.autoCalcDepthBounds=this.autoCalcDepthBounds,t.shadowMaxZ=this._shadowMaxZ,t.penumbraDarkness=this.penumbraDarkness,t.freezeShadowCastersBoundingInfo=this._freezeShadowCastersBoundingInfo,t.minDistance=this.minDistance,t.maxDistance=this.maxDistance,t.renderList=[],i.renderList)for(var r=0;r<i.renderList.length;r++){var n=i.renderList[r];t.renderList.push(n.id)}return t},t.Parse=function(e,i){var r=dv.Parse(e,i,(function(e,i,r){return new t(e,i,void 0,r)}));return void 0!==e.numCascades&&(r.numCascades=e.numCascades),void 0!==e.debug&&(r.debug=e.debug),void 0!==e.stabilizeCascades&&(r.stabilizeCascades=e.stabilizeCascades),void 0!==e.lambda&&(r.lambda=e.lambda),void 0!==e.cascadeBlendPercentage&&(r.cascadeBlendPercentage=e.cascadeBlendPercentage),void 0!==e.depthClamp&&(r.depthClamp=e.depthClamp),void 0!==e.autoCalcDepthBounds&&(r.autoCalcDepthBounds=e.autoCalcDepthBounds),void 0!==e.shadowMaxZ&&(r.shadowMaxZ=e.shadowMaxZ),void 0!==e.penumbraDarkness&&(r.penumbraDarkness=e.penumbraDarkness),void 0!==e.freezeShadowCastersBoundingInfo&&(r.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),void 0!==e.minDistance&&void 0!==e.maxDistance&&r.setMinMaxDistance(e.minDistance,e.maxDistance),r},t._FrustumCornersNDCSpace=[new V(-1,1,-1),new V(1,1,-1),new V(1,-1,-1),new V(-1,-1,-1),new V(-1,1,1),new V(1,1,1),new V(1,-1,1),new V(-1,-1,1)],t.CLASSNAME="CascadedShadowGenerator",t.DEFAULT_CASCADES_COUNT=4,t.MIN_CASCADES_COUNT=2,t.MAX_CASCADES_COUNT=4,t._SceneComponentInitialization=function(e){throw He("ShadowGeneratorSceneComponent")},t}(dv);c.AddParser(Vr.NAME_SHADOWGENERATOR,(function(e,t){if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(var i=0,r=e.shadowGenerators.length;i<r;i++){var n=e.shadowGenerators[i];n.className===Tv.CLASSNAME?Tv.Parse(n,t):dv.Parse(n,t)}}));var Ev=function(){function e(e){this.name=Vr.NAME_SHADOWGENERATOR,this.scene=e}return e.prototype.register=function(){this.scene._gatherRenderTargetsStage.registerStep(Vr.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR,this,this._gatherRenderTargets)},e.prototype.rebuild=function(){},e.prototype.serialize=function(e){e.shadowGenerators=[];for(var t=0,i=this.scene.lights;t<i.length;t++){var r=i[t].getShadowGenerators();if(r)for(var n=r.values(),o=n.next();!0!==o.done;o=n.next()){var a=o.value;e.shadowGenerators.push(a.serialize())}}},e.prototype.addFromContainer=function(e){},e.prototype.removeFromContainer=function(e,t){},e.prototype.dispose=function(){},e.prototype._gatherRenderTargets=function(e){var t=this.scene;if(this.scene.shadowsEnabled)for(var i=0;i<t.lights.length;i++){var r=t.lights[i],n=r.getShadowGenerators();if(r.isEnabled()&&r.shadowEnabled&&n)for(var o=n.values(),a=o.next();!0!==a.done;a=o.next()){var s=a.value.getShadowMap();-1!==t.textures.indexOf(s)&&e.push(s)}}},e}();dv._SceneComponentInitialization=function(e){var t=e._getComponent(Vr.NAME_SHADOWGENERATOR);t||(t=new Ev(e),e._addComponent(t))},qe.AddNodeConstructor("Light_Type_0",(function(e,t){return function(){return new Sv(e,V.Zero(),t)}}));var Sv=function(e){function t(t,i,r){var n=e.call(this,t,r)||this;return n._shadowAngle=Math.PI/2,n.position=i,n}return m(t,e),Object.defineProperty(t.prototype,"shadowAngle",{get:function(){return this._shadowAngle},set:function(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"direction",{get:function(){return this._direction},set:function(e){var t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators)for(var i=this._shadowGenerators.values(),r=i.next();!0!==r.done;r=i.next())r.value.recreateShadowMap()},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"PointLight"},t.prototype.getTypeID=function(){return wa.LIGHTTYPEID_POINTLIGHT},t.prototype.needCube=function(){return!this.direction},t.prototype.getShadowDirection=function(t){if(this.direction)return e.prototype.getShadowDirection.call(this,t);switch(t){case 0:return new V(1,0,0);case 1:return new V(-1,0,0);case 2:return new V(0,-1,0);case 3:return new V(0,1,0);case 4:return new V(0,0,1);case 5:return new V(0,0,-1)}return V.Zero()},t.prototype._setDefaultShadowProjectionMatrix=function(e,t,i){var r=this.getScene().activeCamera;if(r){var n=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;z.PerspectiveFovLHToRef(this.shadowAngle,1,a?o:n,a?n:o,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,a)}},t.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},t.prototype.transferToEffect=function(e,t){return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,t):this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,0,0,t),this},t.prototype.transferToNodeMaterialEffect=function(e,t){return this.computeTransformedInformation()?e.setFloat3(t,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z):e.setFloat3(t,this.position.x,this.position.y,this.position.z),this},t.prototype.prepareLightSpecificDefines=function(e,t){e["POINTLIGHT"+t]=!0},v([Ie()],t.prototype,"shadowAngle",null),t}(xm);a("BABYLON.PointLight",Sv);var xv=function(){function e(e,t,i){void 0===t&&(t=""),void 0===i&&(i="black");var r=this;this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=function(){var e=r._renderingCanvas.getBoundingClientRect(),t=window.getComputedStyle(r._renderingCanvas).position;r._loadingDiv&&(r._loadingDiv.style.position="fixed"===t?"fixed":"absolute",r._loadingDiv.style.left=e.left+"px",r._loadingDiv.style.top=e.top+"px",r._loadingDiv.style.width=e.width+"px",r._loadingDiv.style.height=e.height+"px")}}return e.prototype.displayLoadingUI=function(){if(!this._loadingDiv){this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingDiv.style.pointerEvents="none",this._loadingDiv.style.display="grid",this._loadingDiv.style.gridTemplateRows="100%",this._loadingDiv.style.gridTemplateColumns="100%",this._loadingDiv.style.justifyItems="center",this._loadingDiv.style.alignItems="center",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.style.zIndex="1",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText,this._style=document.createElement("style"),this._style.type="text/css",this._style.innerHTML="@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }",document.getElementsByTagName("head")[0].appendChild(this._style);var t=!!window.SVGSVGElement,i=new Image;e.DefaultLogoUrl?i.src=e.DefaultLogoUrl:i.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",i.style.width="150px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";var r=document.createElement("div");r.style.width="300px",r.style.gridColumn="1",r.style.gridRow="1",r.style.top="50%",r.style.left="50%",r.style.transform="translate(-50%, -50%)",r.style.position="absolute";var n=new Image;if(e.DefaultSpinnerUrl?n.src=e.DefaultSpinnerUrl:n.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",n.style.animation="spin1 0.75s infinite linear",n.style.webkitAnimation="spin1 0.75s infinite linear",n.style.transformOrigin="50% 50%",n.style.webkitTransformOrigin="50% 50%",!t){var o={w:16,h:18.5},a={w:30,h:30};i.style.width="".concat(o.w,"vh"),i.style.height="".concat(o.h,"vh"),i.style.left="calc(50% - ".concat(o.w/2,"vh)"),i.style.top="calc(50% - ".concat(o.h/2,"vh)"),n.style.width="".concat(a.w,"vh"),n.style.height="".concat(a.h,"vh"),n.style.left="calc(50% - ".concat(a.w/2,"vh)"),n.style.top="calc(50% - ".concat(a.h/2,"vh)")}r.appendChild(n),this._loadingDiv.appendChild(i),this._loadingDiv.appendChild(r),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}},e.prototype.hideLoadingUI=function(){var e=this;this._loadingDiv&&(this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",(function(){e._loadingTextDiv&&(e._loadingTextDiv.remove(),e._loadingTextDiv=null),e._loadingDiv&&(e._loadingDiv.remove(),e._loadingDiv=null),e._style&&(e._style.remove(),e._style=null),window.removeEventListener("resize",e._resizeLoadingUI)})))},Object.defineProperty(e.prototype,"loadingUIText",{get:function(){return this._loadingText},set:function(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"loadingUIBackgroundColor",{get:function(){return this._loadingDivBackgroundColor},set:function(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)},enumerable:!1,configurable:!0}),e.DefaultLogoUrl="",e.DefaultSpinnerUrl="",e}();Mi.DefaultLoadingScreenFactory=function(e){return new xv(e)};var Av=function(){function e(){}return e.ConvertPanoramaToCubemap=function(e,t,i,r,n){if(void 0===n&&(n=!1),!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";return{front:this.CreateCubemapTexture(r,this.FACE_FRONT,e,t,i,n),back:this.CreateCubemapTexture(r,this.FACE_BACK,e,t,i,n),left:this.CreateCubemapTexture(r,this.FACE_LEFT,e,t,i,n),right:this.CreateCubemapTexture(r,this.FACE_RIGHT,e,t,i,n),up:this.CreateCubemapTexture(r,this.FACE_UP,e,t,i,n),down:this.CreateCubemapTexture(r,this.FACE_DOWN,e,t,i,n),size:r,type:u.TEXTURETYPE_FLOAT,format:u.TEXTUREFORMAT_RGB,gammaSpace:!1}},e.CreateCubemapTexture=function(e,t,i,r,n,o){void 0===o&&(o=!1);for(var a=new ArrayBuffer(e*e*4*3),s=new Float32Array(a),l=o?Math.max(1,Math.round(r/4/e)):1,c=1/l,u=c*c,h=t[1].subtract(t[0]).scale(c/e),d=t[3].subtract(t[2]).scale(c/e),p=1/e,f=0,_=0;_<e;_++)for(var m=0;m<l;m++){for(var g=t[0],v=t[2],y=0;y<e;y++)for(var b=0;b<l;b++){var T=v.subtract(g).scale(f).add(g);T.normalize();var E=this.CalcProjectionSpherical(T,i,r,n);s[_*e*3+3*y+0]+=E.r*u,s[_*e*3+3*y+1]+=E.g*u,s[_*e*3+3*y+2]+=E.b*u,g=g.add(h),v=v.add(d)}f+=p*c}return s},e.CalcProjectionSpherical=function(e,t,i,r){for(var n=Math.atan2(e.z,e.x),o=Math.acos(e.y);n<-Math.PI;)n+=2*Math.PI;for(;n>Math.PI;)n-=2*Math.PI;var a=n/Math.PI,s=o/Math.PI;a=.5*a+.5;var l=Math.round(a*i);l<0?l=0:l>=i&&(l=i-1);var c=Math.round(s*r);c<0?c=0:c>=r&&(c=r-1);var u=r-c-1;return{r:t[u*i*3+3*l+0],g:t[u*i*3+3*l+1],b:t[u*i*3+3*l+2]}},e.FACE_LEFT=[new V(-1,-1,-1),new V(1,-1,-1),new V(-1,1,-1),new V(1,1,-1)],e.FACE_RIGHT=[new V(1,-1,1),new V(-1,-1,1),new V(1,1,1),new V(-1,1,1)],e.FACE_FRONT=[new V(1,-1,-1),new V(1,-1,1),new V(1,1,-1),new V(1,1,1)],e.FACE_BACK=[new V(-1,-1,1),new V(-1,-1,-1),new V(-1,1,1),new V(-1,1,-1)],e.FACE_DOWN=[new V(1,1,-1),new V(1,1,1),new V(-1,1,-1),new V(-1,1,1)],e.FACE_UP=[new V(-1,-1,-1),new V(-1,-1,1),new V(1,-1,-1),new V(1,-1,1)],e}(),Cv=function(){function e(){}return e._Ldexp=function(e,t){return t>1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)},e._Rgbe2float=function(e,t,i,r,n,o){n>0?(n=this._Ldexp(1,n-136),e[o+0]=t*n,e[o+1]=i*n,e[o+2]=r*n):(e[o+0]=0,e[o+1]=0,e[o+2]=0)},e._ReadStringLine=function(e,t){for(var i="",r="",n=t;n<e.length-t&&"\n"!=(r=String.fromCharCode(e[n]));n++)i+=r;return i},e.RGBE_ReadHeader=function(e){var t,i,r=this._ReadStringLine(e,0);if("#"!=r[0]||"?"!=r[1])throw"Bad HDR Format.";var n=!1,o=!1,a=0;do{a+=r.length+1,"FORMAT=32-bit_rle_rgbe"==(r=this._ReadStringLine(e,a))?o=!0:0==r.length&&(n=!0)}while(!n);if(!o)throw"HDR Bad header format, unsupported FORMAT";a+=r.length+1,r=this._ReadStringLine(e,a);var s=/^-Y (.*) \+X (.*)$/g.exec(r);if(!s||s.length<3)throw"HDR Bad header format, no size";if(i=parseInt(s[2]),t=parseInt(s[1]),i<8||i>32767)throw"HDR Bad header format, unsupported size";return{height:t,width:i,dataPosition:a+=r.length+1}},e.GetCubeMapTextureData=function(e,t,i){void 0===i&&(i=!1);var r=new Uint8Array(e),n=this.RGBE_ReadHeader(r),o=this.RGBE_ReadPixels(r,n);return Av.ConvertPanoramaToCubemap(o,n.width,n.height,t,i)},e.RGBE_ReadPixels=function(e,t){return this._RGBEReadPixelsRLE(e,t)},e._RGBEReadPixelsRLE=function(e,t){for(var i,r,n,o,a,s=t.height,l=t.width,c=t.dataPosition,u=0,h=0,d=0,p=new ArrayBuffer(4*l),f=new Uint8Array(p),_=new ArrayBuffer(t.width*t.height*4*3),m=new Float32Array(_);s>0;){if(i=e[c++],r=e[c++],n=e[c++],o=e[c++],2!=i||2!=r||128&n||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((n<<8|o)!=l)throw"HDR Bad header format, wrong scan line width";for(u=0,d=0;d<4;d++)for(h=(d+1)*l;u<h;)if(i=e[c++],r=e[c++],i>128){if(0==(a=i-128)||a>h-u)throw"HDR Bad Format, bad scanline data (run)";for(;a-- >0;)f[u++]=r}else{if(0==(a=i)||a>h-u)throw"HDR Bad Format, bad scanline data (non-run)";if(f[u++]=r,--a>0)for(var g=0;g<a;g++)f[u++]=e[c++]}for(d=0;d<l;d++)i=f[d],r=f[d+l],n=f[d+2*l],o=f[d+3*l],this._Rgbe2float(m,i,r,n,o,(t.height-s)*l*3+3*d);s--}return m},e._RGBEReadPixelsNOTRLE=function(e,t){for(var i,r,n,o,a,s=t.height,l=t.width,c=t.dataPosition,u=new ArrayBuffer(t.width*t.height*4*3),h=new Float32Array(u);s>0;){for(a=0;a<t.width;a++)i=e[c++],r=e[c++],n=e[c++],o=e[c++],this._Rgbe2float(h,i,r,n,o,(t.height-s)*l*3+3*a);s--}return h},e}();li.ShadersStore.hdrFilteringVertexShader="attribute vec2 position;varying vec3 direction;uniform vec3 up;uniform vec3 right;uniform vec3 front;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nmat3 view=mat3(up,right,front);direction=view*vec3(position,1.0);gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";li.ShadersStore.hdrFilteringPixelShader="#include<helperFunctions>\n#include<importanceSampling>\n#include<pbrBRDFFunctions>\n#include<hdrFilteringFunctions>\nuniform float alphaG;uniform samplerCube inputTexture;uniform vec2 vFilteringInfo;uniform float hdrScale;varying vec3 direction;void main() {vec3 color=radiance(alphaG,inputTexture,direction,vFilteringInfo);gl_FragColor=vec4(color*hdrScale,1.0);}";var Rv=function(){function e(e,t){void 0===t&&(t={}),this._lodGenerationOffset=0,this._lodGenerationScale=.8,this.quality=u.TEXTURE_FILTERING_QUALITY_OFFLINE,this.hdrScale=1,this._engine=e,this.hdrScale=t.hdrScale||this.hdrScale,this.quality=t.quality||this.quality}return e.prototype._createRenderTarget=function(e){var t=u.TEXTURETYPE_UNSIGNED_BYTE;this._engine.getCaps().textureHalfFloatRender?t=u.TEXTURETYPE_HALF_FLOAT:this._engine.getCaps().textureFloatRender&&(t=u.TEXTURETYPE_FLOAT);var i=this._engine.createRenderTargetCubeTexture(e,{format:u.TEXTUREFORMAT_RGBA,type:t,createMipMaps:!0,generateMipMaps:!1,generateDepthBuffer:!1,generateStencilBuffer:!1,samplingMode:u.TEXTURE_NEAREST_SAMPLINGMODE});return this._engine.updateTextureWrappingMode(i.texture,u.TEXTURE_CLAMP_ADDRESSMODE,u.TEXTURE_CLAMP_ADDRESSMODE,u.TEXTURE_CLAMP_ADDRESSMODE),this._engine.updateTextureSamplingMode(u.TEXTURE_TRILINEAR_SAMPLINGMODE,i.texture,!0),i},e.prototype._prefilterInternal=function(e){var t=e.getSize().width,i=j.ILog2(t)+1,r=this._effectWrapper.effect,n=this._createRenderTarget(t);this._effectRenderer.saveStates(),this._effectRenderer.setViewport();var o=e.getInternalTexture();o&&this._engine.updateTextureSamplingMode(u.TEXTURE_TRILINEAR_SAMPLINGMODE,o,!0),this._effectRenderer.applyEffectWrapper(this._effectWrapper);var a=[[new V(0,0,-1),new V(0,-1,0),new V(1,0,0)],[new V(0,0,1),new V(0,-1,0),new V(-1,0,0)],[new V(1,0,0),new V(0,0,1),new V(0,1,0)],[new V(1,0,0),new V(0,0,-1),new V(0,-1,0)],[new V(1,0,0),new V(0,-1,0),new V(0,0,1)],[new V(-1,0,0),new V(0,-1,0),new V(0,0,-1)]];r.setFloat("hdrScale",this.hdrScale),r.setFloat2("vFilteringInfo",e.getSize().width,i),r.setTexture("inputTexture",e);for(var s=0;s<6;s++){r.setVector3("up",a[s][0]),r.setVector3("right",a[s][1]),r.setVector3("front",a[s][2]);for(var l=0;l<i;l++){this._engine.bindFramebuffer(n,s,void 0,void 0,!0,l),this._effectRenderer.applyEffectWrapper(this._effectWrapper);var c=Math.pow(2,(l-this._lodGenerationOffset)/this._lodGenerationScale)/t;0===l&&(c=0),r.setFloat("alphaG",c),this._effectRenderer.draw()}}this._effectRenderer.restoreStates(),this._engine.restoreDefaultFramebuffer(),this._engine._releaseTexture(e._texture);var h=n.texture.type,d=n.texture.format;return n._swapAndDie(e._texture),e._texture.type=h,e._texture.format=d,e.gammaSpace=!1,e.lodGenerationOffset=this._lodGenerationOffset,e.lodGenerationScale=this._lodGenerationScale,e._prefiltered=!0,e},e.prototype._createEffect=function(e,t){var i=[];return e.gammaSpace&&i.push("#define GAMMA_INPUT"),i.push("#define NUM_SAMPLES "+this.quality+"u"),new El({engine:this._engine,name:"hdrFiltering",vertexShader:"hdrFiltering",fragmentShader:"hdrFiltering",samplerNames:["inputTexture"],uniformNames:["vSampleDirections","vWeights","up","right","front","vFilteringInfo","hdrScale","alphaG"],useShaderStore:!0,defines:i,onCompiled:t})},e.prototype.isReady=function(e){return e.isReady()&&this._effectWrapper.effect.isReady()},e.prototype.prefilter=function(e,t){var i=this;return void 0===t&&(t=null),this._engine._features.allowTexturePrefiltering?new Promise((function(r){i._effectRenderer=new Tl(i._engine),i._effectWrapper=i._createEffect(e),i._effectWrapper.effect.executeWhenCompiled((function(){i._prefilterInternal(e),i._effectRenderer.dispose(),i._effectWrapper.dispose(),r(),t&&t()}))})):(ae.Warn("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."),Promise.reject("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."))},e}(),Pv=function(e){function t(t,i,r,n,o,a,s,l,c,h){void 0===n&&(n=!1),void 0===o&&(o=!0),void 0===a&&(a=!1),void 0===s&&(s=!1),void 0===l&&(l=null),void 0===c&&(c=null),void 0===h&&(h=!1);var d,p=this;return(p=e.call(this,i)||this)._generateHarmonics=!0,p._onError=null,p._isBlocking=!0,p._rotationY=0,p.boundingBoxPosition=V.Zero(),p.onLoadObservable=new f,t?(p._coordinatesMode=Ja.CUBIC_MODE,p.name=t,p.url=t,p.hasAlpha=!1,p.isCube=!0,p._textureMatrix=z.Identity(),p._prefilterOnLoad=s,p._onLoad=function(){p.onLoadObservable.notifyObservers(p),l&&l()},p._onError=c,p.gammaSpace=a,p._noMipmap=n,p._size=r,p._supersample=h,p._generateHarmonics=o,p._texture=p._getFromCache(t,p._noMipmap,void 0,void 0,void 0,p.isCube),p._texture?p._texture.isReady?rr.SetImmediate((function(){return p._onLoad()})):p._texture.onLoadedObservable.add(p._onLoad):(null===(d=p.getScene())||void 0===d?void 0:d.useDelayedTextureLoading)?p.delayLoadState=u.DELAYLOADSTATE_NOTLOADED:p._loadTexture(),p):p}return m(t,e),Object.defineProperty(t.prototype,"isBlocking",{get:function(){return this._isBlocking},set:function(e){this._isBlocking=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rotationY",{get:function(){return this._rotationY},set:function(e){this._rotationY=e,this.setReflectionTextureMatrix(z.RotationY(this._rotationY))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"boundingBoxSize",{get:function(){return this._boundingBoxSize},set:function(e){if(!this._boundingBoxSize||!this._boundingBoxSize.equals(e)){this._boundingBoxSize=e;var t=this.getScene();t&&t.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag)}},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"HDRCubeTexture"},t.prototype._loadTexture=function(){var e=this,i=this._getEngine(),r=i.getCaps(),n=u.TEXTURETYPE_UNSIGNED_BYTE;if(r.textureFloat&&r.textureFloatLinearFiltering?n=u.TEXTURETYPE_FLOAT:r.textureHalfFloat&&r.textureHalfFloatLinearFiltering&&(n=u.TEXTURETYPE_HALF_FLOAT),i._features.allowTexturePrefiltering&&this._prefilterOnLoad){var o=this._onLoad,a=new Rv(i);this._onLoad=function(){a.prefilter(e,o)}}this._texture=i.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,u.TEXTUREFORMAT_RGB,n,this._noMipmap,(function(i){e.lodGenerationOffset=0,e.lodGenerationScale=.8;var r=Cv.GetCubeMapTextureData(i,e._size,e._supersample);if(e._generateHarmonics){var o=Lp.ConvertCubeMapToSphericalPolynomial(r);e.sphericalPolynomial=o}for(var a=[],s=null,l=null,c=0;c<6;c++){n===u.TEXTURETYPE_HALF_FLOAT?l=new Uint16Array(e._size*e._size*3):n===u.TEXTURETYPE_UNSIGNED_BYTE&&(s=new Uint8Array(e._size*e._size*3));var h=r[t._FacesMapping[c]];if(e.gammaSpace||l||s)for(var d=0;d<e._size*e._size;d++)if(e.gammaSpace&&(h[3*d+0]=Math.pow(h[3*d+0],E),h[3*d+1]=Math.pow(h[3*d+1],E),h[3*d+2]=Math.pow(h[3*d+2],E)),l&&(l[3*d+0]=Pp(h[3*d+0]),l[3*d+1]=Pp(h[3*d+1]),l[3*d+2]=Pp(h[3*d+2])),s){var p=Math.max(255*h[3*d+0],0),f=Math.max(255*h[3*d+1],0),_=Math.max(255*h[3*d+2],0),m=Math.max(Math.max(p,f),_);if(m>255){var g=255/m;p*=g,f*=g,_*=g}s[3*d+0]=p,s[3*d+1]=f,s[3*d+2]=_}l?a.push(l):s?a.push(s):a.push(h)}return a}),null,this._onLoad,this._onError)},t.prototype.clone=function(){var e=new t(this.url,this.getScene()||this._getEngine(),this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return e.level=this.level,e.wrapU=this.wrapU,e.wrapV=this.wrapV,e.coordinatesIndex=this.coordinatesIndex,e.coordinatesMode=this.coordinatesMode,e},t.prototype.delayLoad=function(){this.delayLoadState===u.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=u.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this._loadTexture())},t.prototype.getReflectionTextureMatrix=function(){return this._textureMatrix},t.prototype.setReflectionTextureMatrix=function(e){var t,i=this;this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&(null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(e){return-1!==e.getActiveTextures().indexOf(i)})))},t.prototype.dispose=function(){this.onLoadObservable.clear(),e.prototype.dispose.call(this)},t.Parse=function(e,i,r){var n=null;return e.name&&!e.isRenderTarget&&((n=new t(r+e.name,i,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace)).name=e.name,n.hasAlpha=e.hasAlpha,n.level=e.level,n.coordinatesMode=e.coordinatesMode,n.isBlocking=e.isBlocking),n&&(e.boundingBoxPosition&&(n.boundingBoxPosition=V.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(n.boundingBoxSize=V.FromArray(e.boundingBoxSize)),e.rotationY&&(n.rotationY=e.rotationY)),n},t.prototype.serialize=function(){if(!this.name)return null;var e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e},t._FacesMapping=["right","left","up","down","front","back"],t}(Ya);a("BABYLON.HDRCubeTexture",Pv);var Iv=function(){function e(e,t,i){void 0===t&&(t=0),void 0===i&&(i=null),this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new f,this._onDataLayoutChanged=new f,this._animationPropertiesOverride=null,this._scene=i||M.LastCreatedScene,this.influence=t,this._scene&&(this._uniqueId=this._scene.getUniqueId())}return Object.defineProperty(e.prototype,"influence",{get:function(){return this._influence},set:function(e){if(this._influence!==e){var t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(0===t||0===e)}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"animationPropertiesOverride",{get:function(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride},set:function(e){this._animationPropertiesOverride=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"uniqueId",{get:function(){return this._uniqueId},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hasPositions",{get:function(){return!!this._positions},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hasNormals",{get:function(){return!!this._normals},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hasTangents",{get:function(){return!!this._tangents},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hasUVs",{get:function(){return!!this._uvs},enumerable:!1,configurable:!0}),e.prototype.setPositions=function(e){var t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)},e.prototype.getPositions=function(){return this._positions},e.prototype.setNormals=function(e){var t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)},e.prototype.getNormals=function(){return this._normals},e.prototype.setTangents=function(e){var t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)},e.prototype.getTangents=function(){return this._tangents},e.prototype.setUVs=function(e){var t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)},e.prototype.getUVs=function(){return this._uvs},e.prototype.clone=function(){var t=this,i=Ke.Clone((function(){return new e(t.name,t.influence,t._scene)}),this);return i._positions=this._positions,i._normals=this._normals,i._tangents=this._tangents,i._uvs=this._uvs,i},e.prototype.serialize=function(){var e={};return e.name=this.name,e.influence=this.influence,e.positions=Array.prototype.slice.call(this.getPositions()),null!=this.id&&(e.id=this.id),this.hasNormals&&(e.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(e.tangents=Array.prototype.slice.call(this.getTangents())),this.hasUVs&&(e.uvs=Array.prototype.slice.call(this.getUVs())),Ke.AppendSerializedAnimations(this,e),e},e.prototype.getClassName=function(){return"MorphTarget"},e.Parse=function(t,i){var r=new e(t.name,t.influence);if(r.setPositions(t.positions),null!=t.id&&(r.id=t.id),t.normals&&r.setNormals(t.normals),t.tangents&&r.setTangents(t.tangents),t.uvs&&r.setUVs(t.uvs),t.animations){for(var n=0;n<t.animations.length;n++){var o=t.animations[n],a=s("BABYLON.Animation");a&&r.animations.push(a.Parse(o))}t.autoAnimate&&i&&i.beginAnimation(r,t.autoAnimateFrom,t.autoAnimateTo,t.autoAnimateLoop,t.autoAnimateSpeed||1)}return r},e.FromMesh=function(t,i,r){i||(i=t.name);var n=new e(i,r,t.getScene());return n.setPositions(t.getVerticesData(Nr.PositionKind)),t.isVerticesDataPresent(Nr.NormalKind)&&n.setNormals(t.getVerticesData(Nr.NormalKind)),t.isVerticesDataPresent(Nr.TangentKind)&&n.setTangents(t.getVerticesData(Nr.TangentKind)),t.isVerticesDataPresent(Nr.UVKind)&&n.setUVs(t.getVerticesData(Nr.UVKind)),n},v([Ie()],e.prototype,"id",void 0),e}(),Mv=function(e){function t(t,i,r,n,o,a,s,l,c,h,d){void 0===s&&(s=!0),void 0===l&&(l=!1),void 0===c&&(c=Ja.TRILINEAR_SAMPLINGMODE),void 0===h&&(h=u.TEXTURETYPE_UNSIGNED_INT);var p=e.call(this,null,a,!s,l)||this;return p.format=o,p._texture=a.getEngine().createRawTexture2DArray(t,i,r,n,o,s,l,c,null,h,d),p._depth=n,p.is2DArray=!0,p}return m(t,e),Object.defineProperty(t.prototype,"depth",{get:function(){return this._depth},enumerable:!1,configurable:!0}),t.prototype.update=function(e){this._texture&&this._getEngine().updateRawTexture2DArray(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)},t.CreateRGBATexture=function(e,i,r,n,o,a,s,l,c){return void 0===a&&(a=!0),void 0===s&&(s=!1),void 0===l&&(l=u.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===c&&(c=u.TEXTURETYPE_UNSIGNED_INT),new t(e,i,r,n,u.TEXTUREFORMAT_RGBA,o,a,s,l,c)},t}(Ja),Ov=function(){function e(e){if(void 0===e&&(e=null),this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new ar(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._numMaxInfluencers=0,this._useTextureToStoreTargets=!0,e||(e=M.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();var t=this._scene.getEngine().getCaps();this._canUseTextureForTargets=t.canUseGLVertexID&&t.textureFloat&&t.maxVertexTextureImageUnits>0&&t.texture2DArrayMaxLayerCount>1}}return Object.defineProperty(e.prototype,"areUpdatesFrozen",{get:function(){return this._blockCounter>0},set:function(e){e?this._blockCounter++:(this._blockCounter--,this._blockCounter<=0&&(this._blockCounter=0,this._syncActiveTargets(!0)))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"numMaxInfluencers",{get:function(){return this._numMaxInfluencers},set:function(e){this._numMaxInfluencers!==e&&(this._numMaxInfluencers=e,this._syncActiveTargets(!0))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"uniqueId",{get:function(){return this._uniqueId},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"vertexCount",{get:function(){return this._vertexCount},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"supportsNormals",{get:function(){return this._supportsNormals&&this.enableNormalMorphing},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"supportsTangents",{get:function(){return this._supportsTangents&&this.enableTangentMorphing},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"supportsUVs",{get:function(){return this._supportsUVs&&this.enableUVMorphing},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"numTargets",{get:function(){return this._targets.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"numInfluencers",{get:function(){return this._activeTargets.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"influences",{get:function(){return this._influences},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useTextureToStoreTargets",{get:function(){return this._useTextureToStoreTargets},set:function(e){this._useTextureToStoreTargets=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isUsingTextureForTargets",{get:function(){var t;return e.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!(null===(t=this._scene)||void 0===t?void 0:t.getEngine().getCaps().disableMorphTargetTexture)},enumerable:!1,configurable:!0}),e.prototype.getActiveTarget=function(e){return this._activeTargets.data[e]},e.prototype.getTarget=function(e){return this._targets[e]},e.prototype.addTarget=function(e){var t=this;this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add((function(e){t._syncActiveTargets(e)}))),this._targetDataLayoutChangedObservers.push(e._onDataLayoutChanged.add((function(){t._syncActiveTargets(!0)}))),this._syncActiveTargets(!0)},e.prototype.removeTarget=function(e){var t=this._targets.indexOf(e);t>=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(t,1)[0]),e._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(t,1)[0]),this._syncActiveTargets(!0)),this._scene&&this._scene.stopAnimation(e)},e.prototype._bind=function(e){e.setFloat3("morphTargetTextureInfo",this._textureVertexStride,this._textureWidth,this._textureHeight),e.setFloatArray("morphTargetTextureIndices",this._morphTargetTextureIndices),e.setTexture("morphTargets",this._targetStoreTexture),e.setInt("morphTargetCount",this.numInfluencers)},e.prototype.clone=function(){for(var t=new e(this._scene),i=0,r=this._targets;i<r.length;i++){var n=r[i];t.addTarget(n.clone())}return t.enableNormalMorphing=this.enableNormalMorphing,t.enableTangentMorphing=this.enableTangentMorphing,t.enableUVMorphing=this.enableUVMorphing,t},e.prototype.serialize=function(){var e={};e.id=this.uniqueId,e.targets=[];for(var t=0,i=this._targets;t<i.length;t++){var r=i[t];e.targets.push(r.serialize())}return e},e.prototype._syncActiveTargets=function(t){if(!this.areUpdatesFrozen){var i=0;this._activeTargets.reset(),this._supportsNormals=!0,this._supportsTangents=!0,this._supportsUVs=!0,this._vertexCount=0,this._scene&&this._targets.length>this._scene.getEngine().getCaps().texture2DArrayMaxLayerCount&&(this.useTextureToStoreTargets=!1),this._morphTargetTextureIndices&&this._morphTargetTextureIndices.length===this._targets.length||(this._morphTargetTextureIndices=new Float32Array(this._targets.length));for(var r=-1,n=0,o=this._targets;n<o.length;n++){var a=o[n];if(r++,0!==a.influence||!this.optimizeInfluencers){if(this._activeTargets.length>=e.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(a),this._morphTargetTextureIndices[i]=r,this._tempInfluences[i++]=a.influence,this._supportsNormals=this._supportsNormals&&a.hasNormals,this._supportsTangents=this._supportsTangents&&a.hasTangents,this._supportsUVs=this._supportsUVs&&a.hasUVs;var s=a.getPositions();if(s){var l=s.length/3;if(0===this._vertexCount)this._vertexCount=l;else if(this._vertexCount!==l)return void ae.Error("Incompatible target. Targets must all have the same vertices count.")}}}this._morphTargetTextureIndices.length!==i&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,i)),this._influences&&this._influences.length===i||(this._influences=new Float32Array(i));for(var c=0;c<i;c++)this._influences[c]=this._tempInfluences[c];t&&this.synchronize()}},e.prototype.synchronize=function(){if(this._scene&&!this.areUpdatesFrozen){if(this.isUsingTextureForTargets&&(this._vertexCount||this.numMaxInfluencers>0)){this._textureVertexStride=1,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride||1,this._textureHeight=1;var e=this._scene.getEngine().getCaps().maxTextureSize;this._textureWidth>e&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);var t=!0;if(this._targetStoreTexture){var i=this._targetStoreTexture.getSize();i.width===this._textureWidth&&i.height===this._textureHeight&&this._targetStoreTexture.depth===this._targets.length&&(t=!1)}if(t){this._targetStoreTexture&&this._targetStoreTexture.dispose();for(var r=this._targets.length,n=new Float32Array(r*this._textureWidth*this._textureHeight*4),o=0,a=0;a<r;a++){var s=this._targets[a],l=s.getPositions(),c=s.getNormals(),h=s.getUVs(),d=s.getTangents();if(!l)return void(0===a&&ae.Error("Invalid morph target. Target must have positions."));o=a*this._textureWidth*this._textureHeight*4;for(var p=0;p<this._vertexCount;p++)n[o]=l[3*p],n[o+1]=l[3*p+1],n[o+2]=l[3*p+2],o+=4,this._supportsNormals&&c&&(n[o]=c[3*p],n[o+1]=c[3*p+1],n[o+2]=c[3*p+2],o+=4),this._supportsUVs&&h&&(n[o]=h[2*p],n[o+1]=h[2*p+1],o+=4),this._supportsTangents&&d&&(n[o]=d[3*p],n[o+1]=d[3*p+1],n[o+2]=d[3*p+2],o+=4)}this._targetStoreTexture=Mv.CreateRGBATexture(n,this._textureWidth,this._textureHeight,r,this._scene,!1,!1,u.TEXTURE_NEAREST_SAMPLINGMODE,u.TEXTURETYPE_FLOAT)}}for(var f=0,_=this._scene.meshes;f<_.length;f++){var m=_[f];m.morphTargetManager===this&&m._syncGeometryWithMorphTargetManager()}}},e.prototype.dispose=function(){if(this._targetStoreTexture&&this._targetStoreTexture.dispose(),this._targetStoreTexture=null,this._scene){if(this._scene.removeMorphTargetManager(this),this._parentContainer){var e=this._parentContainer.morphTargetManagers.indexOf(this);e>-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(var t=0,i=this._targets;t<i.length;t++){var r=i[t];this._scene.stopAnimation(r)}}},e.Parse=function(t,i){var r=new e(i);r._uniqueId=t.id;for(var n=0,o=t.targets;n<o.length;n++){var a=o[n];r.addTarget(Iv.Parse(a,i))}return r},e.EnableTextureStorage=!0,e.MaxActiveMorphTargetsInVertexAttributeMode=8,e}(),Dv=function(){function e(){this._hasHit=!1,this._hitNormal=V.Zero(),this._hitPoint=V.Zero(),this._triangleIndex=-1}return Object.defineProperty(e.prototype,"hitPoint",{get:function(){return this._hitPoint},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hitNormal",{get:function(){return this._hitNormal},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hasHit",{get:function(){return this._hasHit},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"triangleIndex",{get:function(){return this._triangleIndex},enumerable:!1,configurable:!0}),e.prototype.setHitData=function(e,t,i){this._hasHit=!0,this._hitNormal.set(e.x,e.y,e.z),this._hitPoint.set(t.x,t.y,t.z),this._triangleIndex=null!=i?i:-1},e.prototype.reset=function(){this._hasHit=!1,this._hitNormal.setAll(0),this._hitPoint.setAll(0),this._triangleIndex=-1,this.body=void 0,this.bodyIndex=void 0,this.shape=void 0},e}(),Nv=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._hitDistance=0,t._rayFromWorld=V.Zero(),t._rayToWorld=V.Zero(),t}return m(t,e),Object.defineProperty(t.prototype,"hitDistance",{get:function(){return this._hitDistance},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hitNormalWorld",{get:function(){return this._hitNormal},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hitPointWorld",{get:function(){return this._hitPoint},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rayFromWorld",{get:function(){return this._rayFromWorld},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rayToWorld",{get:function(){return this._rayToWorld},enumerable:!1,configurable:!0}),t.prototype.setHitDistance=function(e){this._hitDistance=e},t.prototype.calculateHitDistance=function(){this._hitDistance=V.Distance(this._rayFromWorld,this._hitPoint)},t.prototype.reset=function(t,i){void 0===t&&(t=V.Zero()),void 0===i&&(i=V.Zero()),e.prototype.reset.call(this),this._rayFromWorld.copyFrom(t),this._rayToWorld.copyFrom(i),this._hitDistance=0},t}(Dv),Fv=function(){function e(t,i){if(void 0===i&&(i=e.DefaultPluginFactory()),this._physicsPlugin=i,this._impostors=[],this._joints=[],this._subTimeStep=0,this._uniqueIdCounter=0,!this._physicsPlugin.isSupported())throw new Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");t=t||new V(0,-9.807,0),this.setGravity(t),this.setTimeStep()}return e.prototype.getPluginVersion=function(){return this._physicsPlugin.getPluginVersion()},e.DefaultPluginFactory=function(){throw He("CannonJSPlugin")},e.prototype.setGravity=function(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)},e.prototype.setTimeStep=function(e){void 0===e&&(e=1/60),this._physicsPlugin.setTimeStep(e)},e.prototype.getTimeStep=function(){return this._physicsPlugin.getTimeStep()},e.prototype.setSubTimeStep=function(e){void 0===e&&(e=0),this._subTimeStep=e},e.prototype.getSubTimeStep=function(){return this._subTimeStep},e.prototype.dispose=function(){this._impostors.forEach((function(e){e.dispose()})),this._physicsPlugin.dispose()},e.prototype.getPhysicsPluginName=function(){return this._physicsPlugin.name},e.prototype.addImpostor=function(e){this._impostors.push(e),e.uniqueId=this._uniqueIdCounter++,e.parent||this._physicsPlugin.generatePhysicsBody(e)},e.prototype.removeImpostor=function(e){var t=this._impostors.indexOf(e);t>-1&&this._impostors.splice(t,1).length&&this.getPhysicsPlugin().removePhysicsBody(e)},e.prototype.addJoint=function(e,t,i){var r={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(r),this._physicsPlugin.generateJoint(r)},e.prototype.removeJoint=function(e,t,i){var r=this._joints.filter((function(r){return r.connectedImpostor===t&&r.joint===i&&r.mainImpostor===e}));r.length&&this._physicsPlugin.removeJoint(r[0])},e.prototype._step=function(e){var t=this;this._impostors.forEach((function(e){e.isBodyInitRequired()&&t._physicsPlugin.generatePhysicsBody(e)})),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)},e.prototype.getPhysicsPlugin=function(){return this._physicsPlugin},e.prototype.getImpostors=function(){return this._impostors},e.prototype.getImpostorForPhysicsObject=function(e){for(var t=0;t<this._impostors.length;++t)if(this._impostors[t].object===e)return this._impostors[t];return null},e.prototype.getImpostorWithPhysicsBody=function(e){for(var t=0;t<this._impostors.length;++t)if(this._impostors[t].physicsBody===e)return this._impostors[t];return null},e.prototype.raycast=function(e,t){return this._physicsPlugin.raycast(e,t)},e.prototype.raycastToRef=function(e,t,i){return this._physicsPlugin.raycastToRef(e,t,i)},e}(),Lv=function(){function e(e,t,i){void 0===e&&(e=!0),void 0===t&&(t=10),void 0===i&&(i=CANNON),this._useDeltaForWorldStep=e,this.name="CannonJSPlugin",this._physicsMaterials=new Array,this._fixedTimeStep=1/60,this._physicsBodiesToRemoveAfterStep=new Array,this._firstFrame=!0,this._tmpQuaternion=new G,this._minus90X=new G(-.7071067811865475,0,0,.7071067811865475),this._plus90X=new G(.7071067811865475,0,0,.7071067811865475),this._tmpPosition=V.Zero(),this._tmpDeltaPosition=V.Zero(),this._tmpUnityRotation=new G,this.BJSCANNON=i,this.isSupported()?(this._extendNamespace(),this.world=new this.BJSCANNON.World,this.world.broadphase=new this.BJSCANNON.NaiveBroadphase,this.world.solver.iterations=t,this._cannonRaycastResult=new this.BJSCANNON.RaycastResult,this._raycastResult=new Nv):ae.Error("CannonJS is not available. Please make sure you included the js file.")}return e.prototype.getPluginVersion=function(){return 1},e.prototype.setGravity=function(e){var t=e;this.world.gravity.set(t.x,t.y,t.z)},e.prototype.setTimeStep=function(e){this._fixedTimeStep=e},e.prototype.getTimeStep=function(){return this._fixedTimeStep},e.prototype.executeStep=function(e,t){if(this._firstFrame){this._firstFrame=!1;for(var i=0,r=t;i<r.length;i++){var n=r[i];n.type!=Ds.HeightmapImpostor&&n.type!==Ds.PlaneImpostor&&n.beforeStep()}}this.world.step(this._useDeltaForWorldStep?e:this._fixedTimeStep),this._removeMarkedPhysicsBodiesFromWorld()},e.prototype._removeMarkedPhysicsBodiesFromWorld=function(){var e=this;this._physicsBodiesToRemoveAfterStep.length>0&&(this._physicsBodiesToRemoveAfterStep.forEach((function(t){"function"==typeof e.world.removeBody?e.world.removeBody(t):e.world.remove(t)})),this._physicsBodiesToRemoveAfterStep.length=0)},e.prototype.applyImpulse=function(e,t,i){var r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),n=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(n,r)},e.prototype.applyForce=function(e,t,i){var r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),n=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(n,r)},e.prototype.generatePhysicsBody=function(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){var t=this._createShape(e);if(!t)return void ae.Warn("It was not possible to create a physics body for this object.");var i=e.physicsBody;i&&this.removePhysicsBody(e);var r=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),n={mass:e.getParam("mass"),material:r},o=e.getParam("nativeOptions");for(var a in o)Object.prototype.hasOwnProperty.call(o,a)&&(n[a]=o[a]);e.physicsBody=new this.BJSCANNON.Body(n),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),"function"==typeof this.world.addBody?this.world.addBody(e.physicsBody):this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach((function(t){var r=i[t];e.physicsBody[t].set(r.x,r.y,r.z)})),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}},e.prototype._processChildMeshes=function(e){var t=this,i=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],r=e.object.rotationQuaternion;if(r?r.conjugateToRef(this._tmpQuaternion):this._tmpQuaternion.set(0,0,0,1),i.length){var n=function(i){if(i.rotationQuaternion){var r=i.getPhysicsImpostor();if(r&&r.parent!==e&&i.parent){var o=i.getAbsolutePosition().subtract(i.parent.getAbsolutePosition()),a=i.rotationQuaternion.multiply(t._tmpQuaternion);r.physicsBody&&(t.removePhysicsBody(r),r.physicsBody=null),r.parent=e,r.resetUpdateFlags(),e.physicsBody.addShape(t._createShape(r),new t.BJSCANNON.Vec3(o.x,o.y,o.z),new t.BJSCANNON.Quaternion(a.x,a.y,a.z,a.w)),e.physicsBody.mass+=r.getParam("mass")}i.getChildMeshes(!0).filter((function(e){return!!e.physicsImpostor})).forEach(n)}};i.filter((function(e){return!!e.physicsImpostor})).forEach(n)}},e.prototype.removePhysicsBody=function(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),-1===this._physicsBodiesToRemoveAfterStep.indexOf(e.physicsBody)&&this._physicsBodiesToRemoveAfterStep.push(e.physicsBody)},e.prototype.generateJoint=function(e){var t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(t&&i){var r,n=e.joint.jointData,o={pivotA:n.mainPivot?(new this.BJSCANNON.Vec3).set(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z):null,pivotB:n.connectedPivot?(new this.BJSCANNON.Vec3).set(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z):null,axisA:n.mainAxis?(new this.BJSCANNON.Vec3).set(n.mainAxis.x,n.mainAxis.y,n.mainAxis.z):null,axisB:n.connectedAxis?(new this.BJSCANNON.Vec3).set(n.connectedAxis.x,n.connectedAxis.y,n.connectedAxis.z):null,maxForce:n.nativeParams.maxForce,collideConnected:!!n.collision};switch(e.joint.type){case Cs.HingeJoint:case Cs.Hinge2Joint:r=new this.BJSCANNON.HingeConstraint(t,i,o);break;case Cs.DistanceJoint:r=new this.BJSCANNON.DistanceConstraint(t,i,n.maxDistance||2);break;case Cs.SpringJoint:var a=n;r=new this.BJSCANNON.Spring(t,i,{restLength:a.length,stiffness:a.stiffness,damping:a.damping,localAnchorA:o.pivotA,localAnchorB:o.pivotB});break;case Cs.LockJoint:r=new this.BJSCANNON.LockConstraint(t,i,o);break;case Cs.PointToPointJoint:case Cs.BallAndSocketJoint:default:r=new this.BJSCANNON.PointToPointConstraint(t,o.pivotA,i,o.pivotB,o.maxForce)}r.collideConnected=!!n.collision,e.joint.physicsJoint=r,e.joint.type!==Cs.SpringJoint?this.world.addConstraint(r):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){r.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}},e.prototype.removeJoint=function(e){e.joint.type!==Cs.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)},e.prototype._addMaterial=function(e,t,i){var r,n;for(r=0;r<this._physicsMaterials.length;r++)if((n=this._physicsMaterials[r]).friction===t&&n.restitution===i)return n;var o=new this.BJSCANNON.Material(e);return o.friction=t,o.restitution=i,this._physicsMaterials.push(o),o},e.prototype._checkWithEpsilon=function(e){return e<A?A:e},e.prototype._createShape=function(e){var t,i=e.object,r=e.getObjectExtents();switch(e.type){case Ds.SphereImpostor:var n=r.x,o=r.y,a=r.z;t=new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(n),this._checkWithEpsilon(o),this._checkWithEpsilon(a))/2);break;case Ds.CylinderImpostor:var s=e.getParam("nativeOptions");s||(s={});var l=void 0!==s.radiusTop?s.radiusTop:this._checkWithEpsilon(r.x)/2,c=void 0!==s.radiusBottom?s.radiusBottom:this._checkWithEpsilon(r.x)/2,u=void 0!==s.height?s.height:this._checkWithEpsilon(r.y),h=void 0!==s.numSegments?s.numSegments:16;t=new this.BJSCANNON.Cylinder(l,c,u,h);var d=new this.BJSCANNON.Quaternion;d.setFromAxisAngle(new this.BJSCANNON.Vec3(1,0,0),-Math.PI/2);var p=new this.BJSCANNON.Vec3(0,0,0);t.transformAllPoints(p,d);break;case Ds.BoxImpostor:var f=r.scale(.5);t=new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(f.x),this._checkWithEpsilon(f.y),this._checkWithEpsilon(f.z)));break;case Ds.PlaneImpostor:ae.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead"),t=new this.BJSCANNON.Plane;break;case Ds.MeshImpostor:var _=i.getVerticesData?i.getVerticesData(Nr.PositionKind):[],m=i.getIndices?i.getIndices():[];if(!_)return void ae.Warn("Tried to create a MeshImpostor for an object without vertices. This will fail.");var g=i.position.clone(),v=i.rotation&&i.rotation.clone(),y=i.rotationQuaternion&&i.rotationQuaternion.clone();i.position.copyFromFloats(0,0,0),i.rotation&&i.rotation.copyFromFloats(0,0,0),i.rotationQuaternion&&i.rotationQuaternion.copyFrom(e.getParentsRotation()),i.rotationQuaternion&&i.parent&&i.rotationQuaternion.conjugateInPlace();var b=i.computeWorldMatrix(!0),T=[],E=void 0;for(E=0;E<_.length;E+=3)V.TransformCoordinates(V.FromArray(_,E),b).toArray(T,E);ae.Warn("MeshImpostor only collides against spheres."),t=new this.BJSCANNON.Trimesh(T,m),i.position.copyFrom(g),v&&i.rotation&&i.rotation.copyFrom(v),y&&i.rotationQuaternion&&i.rotationQuaternion.copyFrom(y);break;case Ds.HeightmapImpostor:var S=i.position.clone(),x=i.rotation&&i.rotation.clone(),A=i.rotationQuaternion&&i.rotationQuaternion.clone();i.position.copyFromFloats(0,0,0),i.rotation&&i.rotation.copyFromFloats(0,0,0),i.rotationQuaternion&&i.rotationQuaternion.copyFrom(e.getParentsRotation()),i.rotationQuaternion&&i.parent&&i.rotationQuaternion.conjugateInPlace(),i.rotationQuaternion&&i.rotationQuaternion.multiplyInPlace(this._minus90X),t=this._createHeightmap(i),i.position.copyFrom(S),x&&i.rotation&&i.rotation.copyFrom(x),A&&i.rotationQuaternion&&i.rotationQuaternion.copyFrom(A),i.computeWorldMatrix(!0);break;case Ds.ParticleImpostor:t=new this.BJSCANNON.Particle;break;case Ds.NoImpostor:t=new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(0,0,0))}return t},e.prototype._createHeightmap=function(e,t){var i,r=e.getVerticesData(Nr.PositionKind),n=e.computeWorldMatrix(!0),o=[];for(i=0;i<r.length;i+=3)V.TransformCoordinates(V.FromArray(r,i),n).toArray(o,i);r=o;for(var a=new Array,s=t||~~(Math.sqrt(r.length/3)-1),l=e.getBoundingInfo(),c=Math.min(l.boundingBox.extendSizeWorld.x,l.boundingBox.extendSizeWorld.y),u=l.boundingBox.extendSizeWorld.z,h=2*c/s,d=0;d<r.length;d+=3){var p=Math.round(r[d+0]/h+s/2),f=Math.round(-1*(r[d+1]/h-s/2)),_=-r[d+2]+u;a[p]||(a[p]=[]),a[p][f]||(a[p][f]=_),a[p][f]=Math.max(_,a[p][f])}for(p=0;p<=s;++p){if(!a[p]){for(var m=1;!a[(p+m)%s];)m++;a[p]=a[(p+m)%s].slice()}for(f=0;f<=s;++f)if(!a[p][f]){m=1;for(var g=void 0;void 0===g;)g=a[p][(f+m++)%s];a[p][f]=g}}var v=new this.BJSCANNON.Heightfield(a,{elementSize:h});return v.minY=u,v},e.prototype._updatePhysicsBodyTransformation=function(e){var t=e.object;if(t.computeWorldMatrix&&t.computeWorldMatrix(!0),t.getBoundingInfo()){var i=e.getObjectCenter();this._tmpDeltaPosition.copyFrom(t.getAbsolutePivotPoint().subtract(i)),this._tmpDeltaPosition.divideInPlace(e.object.scaling),this._tmpPosition.copyFrom(i);var r=t.rotationQuaternion;if(r){if(e.type!==Ds.PlaneImpostor&&e.type!==Ds.HeightmapImpostor||(r=r.multiply(this._minus90X),e.setDeltaRotation(this._plus90X)),e.type===Ds.HeightmapImpostor){var n=t,o=n.getBoundingInfo(),a=n.rotationQuaternion;n.rotationQuaternion=this._tmpUnityRotation,n.computeWorldMatrix(!0);var s=i.clone(),l=n.getPivotMatrix();l=l?l.clone():z.Identity();var c=z.Translation(o.boundingBox.extendSizeWorld.x,0,-o.boundingBox.extendSizeWorld.z);n.setPreTransformMatrix(c),n.computeWorldMatrix(!0);var u=(o=n.getBoundingInfo()).boundingBox.centerWorld.subtract(i).subtract(n.position).negate();this._tmpPosition.copyFromFloats(u.x,u.y-o.boundingBox.extendSizeWorld.y,u.z),this._tmpDeltaPosition.copyFrom(o.boundingBox.centerWorld.subtract(s)),this._tmpDeltaPosition.y+=o.boundingBox.extendSizeWorld.y,n.rotationQuaternion=a,n.setPreTransformMatrix(l),n.computeWorldMatrix(!0)}else e.type===Ds.MeshImpostor&&this._tmpDeltaPosition.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpDeltaPosition),e.physicsBody.position.set(this._tmpPosition.x,this._tmpPosition.y,this._tmpPosition.z),e.physicsBody.quaternion.set(r.x,r.y,r.z,r.w)}}},e.prototype.setTransformationFromPhysicsBody=function(e){if(e.object.position.set(e.physicsBody.position.x,e.physicsBody.position.y,e.physicsBody.position.z),e.object.rotationQuaternion){var t=e.physicsBody.quaternion;e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}},e.prototype.setPhysicsBodyTransformation=function(e,t,i){e.physicsBody.position.set(t.x,t.y,t.z),e.physicsBody.quaternion.set(i.x,i.y,i.z,i.w)},e.prototype.isSupported=function(){return void 0!==this.BJSCANNON},e.prototype.setLinearVelocity=function(e,t){e.physicsBody.velocity.set(t.x,t.y,t.z)},e.prototype.setAngularVelocity=function(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)},e.prototype.getLinearVelocity=function(e){var t=e.physicsBody.velocity;return t?new V(t.x,t.y,t.z):null},e.prototype.getAngularVelocity=function(e){var t=e.physicsBody.angularVelocity;return t?new V(t.x,t.y,t.z):null},e.prototype.setBodyMass=function(e,t){e.physicsBody.mass=t,e.physicsBody.updateMassProperties()},e.prototype.getBodyMass=function(e){return e.physicsBody.mass},e.prototype.getBodyFriction=function(e){return e.physicsBody.material.friction},e.prototype.setBodyFriction=function(e,t){e.physicsBody.material.friction=t},e.prototype.getBodyRestitution=function(e){return e.physicsBody.material.restitution},e.prototype.setBodyRestitution=function(e,t){e.physicsBody.material.restitution=t},e.prototype.sleepBody=function(e){e.physicsBody.sleep()},e.prototype.wakeUpBody=function(e){e.physicsBody.wakeUp()},e.prototype.updateDistanceJoint=function(e,t){e.physicsJoint.distance=t},e.prototype.setMotor=function(e,t,i,r){r||(e.physicsJoint.enableMotor(),e.physicsJoint.setMotorSpeed(t),i&&this.setLimit(e,i))},e.prototype.setLimit=function(e,t,i){e.physicsJoint.motorEquation.maxForce=i,e.physicsJoint.motorEquation.minForce=void 0===t?-t:t},e.prototype.syncMeshWithImpostor=function(e,t){var i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.quaternion.x,e.rotationQuaternion.y=i.quaternion.y,e.rotationQuaternion.z=i.quaternion.z,e.rotationQuaternion.w=i.quaternion.w)},e.prototype.getRadius=function(e){return e.physicsBody.shapes[0].boundingSphereRadius},e.prototype.getBoxSizeToRef=function(e,t){var i=e.physicsBody.shapes[0];t.x=2*i.halfExtents.x,t.y=2*i.halfExtents.y,t.z=2*i.halfExtents.z},e.prototype.dispose=function(){},e.prototype._extendNamespace=function(){var e=new this.BJSCANNON.Vec3,t=this.BJSCANNON;this.BJSCANNON.World.prototype.step=function(i,r,n){if(n=n||10,0===(r=r||0))this.internalStep(i),this.time+=i;else{var o=Math.floor((this.time+r)/i)-Math.floor(this.time/i);o=Math.min(o,n)||1;for(var a=performance.now(),s=0;s!==o&&(this.internalStep(i),!(performance.now()-a>1e3*i));s++);this.time+=r;for(var l=this.time%i/i,c=e,u=this.bodies,h=0;h!==u.length;h++){var d=u[h];d.type!==t.Body.STATIC&&d.sleepState!==t.Body.SLEEPING?(d.position.vsub(d.previousPosition,c),c.scale(l,c),d.position.vadd(c,d.interpolatedPosition)):(d.interpolatedPosition.set(d.position.x,d.position.y,d.position.z),d.interpolatedQuaternion.set(d.quaternion.x,d.quaternion.y,d.quaternion.z,d.quaternion.w))}}}},e.prototype.raycast=function(e,t){return this._raycastResult.reset(e,t),this.raycastToRef(e,t,this._raycastResult),this._raycastResult},e.prototype.raycastToRef=function(e,t,i){this._cannonRaycastResult.reset(),this.world.raycastClosest(e,t,{},this._cannonRaycastResult),i.reset(e,t),this._cannonRaycastResult.hasHit&&(i.setHitData({x:this._cannonRaycastResult.hitNormalWorld.x,y:this._cannonRaycastResult.hitNormalWorld.y,z:this._cannonRaycastResult.hitNormalWorld.z},{x:this._cannonRaycastResult.hitPointWorld.x,y:this._cannonRaycastResult.hitPointWorld.y,z:this._cannonRaycastResult.hitPointWorld.z}),i.setHitDistance(this._cannonRaycastResult.distance))},e}();Fv.DefaultPluginFactory=function(){return new Lv};var wv=function(){function e(e,t,i){void 0===e&&(e=!0),void 0===i&&(i=OIMO),this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=V.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new Nv}return e.prototype.getPluginVersion=function(){return 1},e.prototype.setGravity=function(e){this.world.gravity.set(e.x,e.y,e.z)},e.prototype.setTimeStep=function(e){this.world.timeStep=e},e.prototype.getTimeStep=function(){return this.world.timeStep},e.prototype.executeStep=function(e,t){var i=this;t.forEach((function(e){e.beforeStep()})),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach((function(e){e.afterStep(),i._tmpImpostorsArray[e.uniqueId]=e}));for(var r=this.world.contacts;null!==r;)if(!r.touching||r.body1.sleeping||r.body2.sleeping){var n=this._tmpImpostorsArray[+r.body1.name],o=this._tmpImpostorsArray[+r.body2.name];n&&o?(n.onCollide({body:o.physicsBody,point:null,distance:0,impulse:0,normal:null}),o.onCollide({body:n.physicsBody,point:null,distance:0,impulse:0,normal:null}),r=r.next):r=r.next}else r=r.next},e.prototype.applyImpulse=function(e,t,i){var r=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*r))},e.prototype.applyForce=function(e,t,i){ae.Warn("Oimo doesn't support applying force. Using impulse instead."),this.applyImpulse(e,t,i)},e.prototype.generatePhysicsBody=function(e){var t=this;if(e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){var i={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==e.getParam("mass"),density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},r=[e];(a=e.object).getChildMeshes&&a.getChildMeshes().forEach((function(e){e.physicsImpostor&&r.push(e.physicsImpostor)}));var n=function(e){return Math.max(e,A)},o=new G;r.forEach((function(r){if(r.object.rotationQuaternion){var a=r.object.rotationQuaternion;o.copyFrom(a),r.object.rotationQuaternion.set(0,0,0,1),r.object.computeWorldMatrix(!0);var s=o.toEulerAngles(),l=r.getObjectExtents(),c=57.29577951308232;if(r===e){var u=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(u,t._tmpPositionVector),t._tmpPositionVector.divideInPlace(e.object.scaling),i.pos.push(u.x),i.pos.push(u.y),i.pos.push(u.z),i.posShape.push(0,0,0),i.rotShape.push(0,0,0)}else{var h=r.object.position.clone();i.posShape.push(h.x),i.posShape.push(h.y),i.posShape.push(h.z),i.rotShape.push(s.x*c,s.y*c,s.z*c)}switch(r.object.rotationQuaternion.copyFrom(o),r.type){case Ds.ParticleImpostor:ae.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case Ds.SphereImpostor:var d=l.x,p=l.y,f=l.z,_=Math.max(n(d),n(p),n(f))/2;i.type.push("sphere"),i.size.push(_),i.size.push(_),i.size.push(_);break;case Ds.CylinderImpostor:var m=n(l.x)/2,g=n(l.y);i.type.push("cylinder"),i.size.push(m),i.size.push(g),i.size.push(g);break;case Ds.PlaneImpostor:case Ds.BoxImpostor:default:m=n(l.x),g=n(l.y);var v=n(l.z);i.type.push("box"),i.size.push(m),i.size.push(g),i.size.push(v)}r.object.rotationQuaternion=a}})),e.physicsBody=this.world.add(i),e.physicsBody.resetQuaternion(o),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);var a;e.setDeltaPosition(this._tmpPositionVector)}},e.prototype.removePhysicsBody=function(e){this.world.removeRigidBody(e.physicsBody)},e.prototype.generateJoint=function(e){var t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(t&&i){var r,n=e.joint.jointData,o=n.nativeParams||{},a={body1:t,body2:i,axe1:o.axe1||(n.mainAxis?n.mainAxis.asArray():null),axe2:o.axe2||(n.connectedAxis?n.connectedAxis.asArray():null),pos1:o.pos1||(n.mainPivot?n.mainPivot.asArray():null),pos2:o.pos2||(n.connectedPivot?n.connectedPivot.asArray():null),min:o.min,max:o.max,collision:o.collision||n.collision,spring:o.spring,world:this.world};switch(e.joint.type){case Cs.BallAndSocketJoint:r="jointBall";break;case Cs.SpringJoint:ae.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");var s=n;a.min=s.length||a.min,a.max=Math.max(a.min,a.max);case Cs.DistanceJoint:r="jointDistance",a.max=n.maxDistance;break;case Cs.PrismaticJoint:r="jointPrisme";break;case Cs.SliderJoint:r="jointSlide";break;case Cs.WheelJoint:r="jointWheel";break;case Cs.HingeJoint:default:r="jointHinge"}a.type=r,e.joint.physicsJoint=this.world.add(a)}},e.prototype.removeJoint=function(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(e){ae.Warn(e)}},e.prototype.isSupported=function(){return void 0!==this.BJSOIMO},e.prototype.setTransformationFromPhysicsBody=function(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){for(var t=e.physicsBody.shapes;t.next;)t=t.next;e.object.position.set(t.position.x,t.position.y,t.position.z)}else{var i=e.physicsBody.getPosition();e.object.position.set(i.x,i.y,i.z)}if(e.object.rotationQuaternion){var r=e.physicsBody.getQuaternion();e.object.rotationQuaternion.set(r.x,r.y,r.z,r.w)}}},e.prototype.setPhysicsBodyTransformation=function(e,t,i){var r=e.physicsBody;e.physicsBody.shapes.next||(r.position.set(t.x,t.y,t.z),r.orientation.set(i.x,i.y,i.z,i.w),r.syncShapes(),r.awake())},e.prototype.setLinearVelocity=function(e,t){e.physicsBody.linearVelocity.set(t.x,t.y,t.z)},e.prototype.setAngularVelocity=function(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)},e.prototype.getLinearVelocity=function(e){var t=e.physicsBody.linearVelocity;return t?new V(t.x,t.y,t.z):null},e.prototype.getAngularVelocity=function(e){var t=e.physicsBody.angularVelocity;return t?new V(t.x,t.y,t.z):null},e.prototype.setBodyMass=function(e,t){var i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)},e.prototype.getBodyMass=function(e){return e.physicsBody.shapes.density},e.prototype.getBodyFriction=function(e){return e.physicsBody.shapes.friction},e.prototype.setBodyFriction=function(e,t){e.physicsBody.shapes.friction=t},e.prototype.getBodyRestitution=function(e){return e.physicsBody.shapes.restitution},e.prototype.setBodyRestitution=function(e,t){e.physicsBody.shapes.restitution=t},e.prototype.sleepBody=function(e){e.physicsBody.sleep()},e.prototype.wakeUpBody=function(e){e.physicsBody.awake()},e.prototype.updateDistanceJoint=function(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)},e.prototype.setMotor=function(e,t,i,r){void 0!==i?ae.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;var n=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;n&&n.setMotor(t,i)},e.prototype.setLimit=function(e,t,i,r){var n=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;n&&n.setLimit(t,void 0===i?-t:i)},e.prototype.syncMeshWithImpostor=function(e,t){var i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.w)},e.prototype.getRadius=function(e){return e.physicsBody.shapes.radius},e.prototype.getBoxSizeToRef=function(e,t){var i=e.physicsBody.shapes;t.x=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth},e.prototype.dispose=function(){this.world.clear()},e.prototype.raycast=function(e,t){return ae.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult},e.prototype.raycastToRef=function(e,t,i){ae.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)},e}(),Bv=function(){function e(e,t,i){void 0===e&&(e=!0),void 0===t&&(t=Ammo),void 0===i&&(i=null);var r=this;this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new G,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new V,this._tmpContactNormal=new V,this._tmpVec3=new V,this._tmpMatrix=new z,"function"!=typeof t?(this.bjsAMMO=t,this.isSupported()?(this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=i||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=function(e){var t=(e=r.bjsAMMO.wrapPointer(e,r.bjsAMMO.btManifoldPoint)).getPositionWorldOnA(),i=e.m_normalWorldOnB;r._tmpContactPoint.x=t.x(),r._tmpContactPoint.y=t.y(),r._tmpContactPoint.z=t.z(),r._tmpContactNormal.x=i.x(),r._tmpContactNormal.y=i.y(),r._tmpContactNormal.z=i.z(),r._tmpContactImpulse=e.getAppliedImpulse(),r._tmpContactDistance=e.getDistance(),r._tmpContactCallbackResult=!0},this._raycastResult=new Nv,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)):ae.Error("AmmoJS is not available. Please make sure you included the js file.")):ae.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.")}return e.prototype.getPluginVersion=function(){return 1},e.prototype.setGravity=function(e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)},e.prototype.setTimeStep=function(e){this._timeStep=e},e.prototype.setFixedTimeStep=function(e){this._fixedTimeStep=e},e.prototype.setMaxSteps=function(e){this._maxSteps=e},e.prototype.getTimeStep=function(){return this._timeStep},e.prototype._isImpostorInContact=function(e){return this._tmpContactCallbackResult=!1,this.world.contactTest(e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult},e.prototype._isImpostorPairInContact=function(e,t){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(e.physicsBody,t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult},e.prototype._stepSimulation=function(e,t,i){if(void 0===e&&(e=1/60),void 0===t&&(t=10),void 0===i&&(i=1/60),0==t)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i<i?(this.world.stepSimulation(e,0),e=0):(e-=i,this.world.stepSimulation(i,0)),t--},e.prototype.executeStep=function(e,t){for(var i=0,r=t;i<r.length;i++){var n=r[i];n.soft||n.beforeStep()}this._stepSimulation(this._useDeltaForWorldStep?e:this._timeStep,this._maxSteps,this._fixedTimeStep);for(var o=0,a=t;o<a.length;o++){var s=a[o];if(s.soft?this._afterSoftStep(s):s.afterStep(),s._onPhysicsCollideCallbacks.length>0&&this._isImpostorInContact(s))for(var l=0,c=s._onPhysicsCollideCallbacks;l<c.length;l++)for(var u=0,h=c[l].otherImpostors;u<h.length;u++){var d=h[u];(s.physicsBody.isActive()||d.physicsBody.isActive())&&this._isImpostorPairInContact(s,d)&&(s.onCollide({body:d.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),d.onCollide({body:s.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}}},e.prototype._afterSoftStep=function(e){e.type===Ds.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)},e.prototype._ropeStep=function(e){for(var t,i,r,n,o=e.physicsBody.get_m_nodes(),a=o.size(),s=new Array,l=0;l<a;l++)i=(t=o.at(l).get_m_x()).x(),r=t.y(),n=t.z(),s.push(new V(i,r,n));var c=e.object,u=e.getParam("shape");e._isFromLine?e.object=fd("lines",{points:s,instance:c}):e.object=Ad("ext",{shape:u,path:s,instance:c})},e.prototype._softbodyOrClothStep=function(e){var t=e.type===Ds.ClothImpostor?1:-1,i=e.object,r=i.getVerticesData(Nr.PositionKind);r||(r=[]);var n=i.getVerticesData(Nr.NormalKind);n||(n=[]);for(var o,a,s,l,c,u,h,d,p=r.length/3,f=e.physicsBody.get_m_nodes(),_=0;_<p;_++){s=(a=(o=f.at(_)).get_m_x()).x(),l=a.y(),c=a.z()*t;var m=o.get_m_n();u=m.x(),h=m.y(),d=m.z()*t,r[3*_]=s,r[3*_+1]=l,r[3*_+2]=c,n[3*_]=u,n[3*_+1]=h,n[3*_+2]=d}var g=new _o;g.positions=r,g.normals=n,g.uvs=i.getVerticesData(Nr.UVKind),g.colors=i.getVerticesData(Nr.ColorKind),i&&i.getIndices&&(g.indices=i.getIndices()),g.applyToMesh(i)},e.prototype.applyImpulse=function(e,t,i){if(e.soft)ae.Warn("Cannot be applied to a soft body");else{e.physicsBody.activate();var r=this._tmpAmmoVectorA,n=this._tmpAmmoVectorB;e.object&&e.object.getWorldMatrix&&i.subtractInPlace(e.object.getWorldMatrix().getTranslation()),r.setValue(i.x,i.y,i.z),n.setValue(t.x,t.y,t.z),e.physicsBody.applyImpulse(n,r)}},e.prototype.applyForce=function(e,t,i){if(e.soft)ae.Warn("Cannot be applied to a soft body");else{e.physicsBody.activate();var r=this._tmpAmmoVectorA,n=this._tmpAmmoVectorB;if(e.object&&e.object.getWorldMatrix){var o=e.object.getWorldMatrix().getTranslation();r.setValue(i.x-o.x,i.y-o.y,i.z-o.z)}else r.setValue(i.x,i.y,i.z);n.setValue(t.x,t.y,t.z),e.physicsBody.applyForce(n,r)}},e.prototype.generatePhysicsBody=function(t){if(t._pluginData.toDispose=[],t.parent)t.physicsBody&&(this.removePhysicsBody(t),t.forceUpdate());else if(t.isBodyInitRequired()){var i=this._createShape(t),r=t.getParam("mass");if(t._pluginData.mass=r,t.soft)i.get_m_cfg().set_collisions(17),i.get_m_cfg().set_kDP(t.getParam("damping")),this.bjsAMMO.castObject(i,this.bjsAMMO.btCollisionObject).getCollisionShape().setMargin(t.getParam("margin")),i.setActivationState(e._DISABLE_DEACTIVATION_FLAG),this.world.addSoftBody(i,1,-1),t.physicsBody=i,t._pluginData.toDispose.push(i),this.setBodyPressure(t,0),t.type===Ds.SoftbodyImpostor&&this.setBodyPressure(t,t.getParam("pressure")),this.setBodyStiffness(t,t.getParam("stiffness")),this.setBodyVelocityIterations(t,t.getParam("velocityIterations")),this.setBodyPositionIterations(t,t.getParam("positionIterations"));else{var n=new this.bjsAMMO.btVector3(0,0,0),o=new this.bjsAMMO.btTransform;t.object.computeWorldMatrix(!0),o.setIdentity(),0!==r&&i.calculateLocalInertia(r,n),this._tmpAmmoVectorA.setValue(t.object.position.x,t.object.position.y,t.object.position.z),this._tmpAmmoQuaternion.setValue(t.object.rotationQuaternion.x,t.object.rotationQuaternion.y,t.object.rotationQuaternion.z,t.object.rotationQuaternion.w),o.setOrigin(this._tmpAmmoVectorA),o.setRotation(this._tmpAmmoQuaternion);var a=new this.bjsAMMO.btDefaultMotionState(o),s=new this.bjsAMMO.btRigidBodyConstructionInfo(r,a,i,n),l=new this.bjsAMMO.btRigidBody(s);if(0===r&&(l.setCollisionFlags(l.getCollisionFlags()|e._KINEMATIC_FLAG),l.setActivationState(e._DISABLE_DEACTIVATION_FLAG)),t.type!=Ds.NoImpostor||i.getChildShape||l.setCollisionFlags(l.getCollisionFlags()|e._DISABLE_COLLISION_FLAG),t.type!==Ds.MeshImpostor&&t.type!==Ds.NoImpostor){var c=t.object.getBoundingInfo();this._tmpVec3.copyFrom(t.object.getAbsolutePosition()),this._tmpVec3.subtractInPlace(c.boundingBox.centerWorld),this._tmpVec3.x/=t.object.scaling.x,this._tmpVec3.y/=t.object.scaling.y,this._tmpVec3.z/=t.object.scaling.z,t.setDeltaPosition(this._tmpVec3)}var u=t.getParam("group"),h=t.getParam("mask");u&&h?this.world.addRigidBody(l,u,h):this.world.addRigidBody(l),t.physicsBody=l,t._pluginData.toDispose=t._pluginData.toDispose.concat([l,s,a,o,n,i])}this.setBodyRestitution(t,t.getParam("restitution")),this.setBodyFriction(t,t.getParam("friction"))}},e.prototype.removePhysicsBody=function(e){var t=this;this.world&&(e.soft?this.world.removeSoftBody(e.physicsBody):this.world.removeRigidBody(e.physicsBody),e._pluginData&&(e._pluginData.toDispose.forEach((function(e){t.bjsAMMO.destroy(e)})),e._pluginData.toDispose=[]))},e.prototype.generateJoint=function(e){var t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(t&&i&&!e.joint.physicsJoint){var r,n=e.joint.jointData;switch(n.mainPivot||(n.mainPivot=new V(0,0,0)),n.connectedPivot||(n.connectedPivot=new V(0,0,0)),e.joint.type){case Cs.DistanceJoint:var o=n.maxDistance;o&&(n.mainPivot=new V(0,-o/2,0),n.connectedPivot=new V(0,o/2,0)),(l=this._tmpAmmoVectorA).setValue(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z),(c=this._tmpAmmoVectorB).setValue(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,l,c);break;case Cs.HingeJoint:n.mainAxis||(n.mainAxis=new V(0,0,0)),n.connectedAxis||(n.connectedAxis=new V(0,0,0)),(l=this._tmpAmmoVectorA).setValue(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z),(c=this._tmpAmmoVectorB).setValue(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z);var a=this._tmpAmmoVectorC;a.setValue(n.mainAxis.x,n.mainAxis.y,n.mainAxis.z);var s=this._tmpAmmoVectorD;s.setValue(n.connectedAxis.x,n.connectedAxis.y,n.connectedAxis.z),r=new this.bjsAMMO.btHingeConstraint(t,i,l,c,a,s);break;case Cs.BallAndSocketJoint:(l=this._tmpAmmoVectorA).setValue(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z),(c=this._tmpAmmoVectorB).setValue(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,l,c);break;default:var l,c;ae.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"),(l=this._tmpAmmoVectorA).setValue(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z),(c=this._tmpAmmoVectorB).setValue(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,l,c)}this.world.addConstraint(r,!e.joint.jointData.collision),e.joint.physicsJoint=r}},e.prototype.removeJoint=function(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint),this.bjsAMMO.destroy(e.joint.physicsJoint)},e.prototype._addMeshVerts=function(e,t,i){var r=this,n=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){var o=i.getIndices();o||(o=[]);var a=i.getVerticesData(Nr.PositionKind);a||(a=[]);var s=void 0;if(t&&t!==i){var l;l=t.rotationQuaternion?t.rotationQuaternion:t.rotation?G.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):G.Identity(),z.Compose(V.One(),l,t.position).invertToRef(this._tmpMatrix),s=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else z.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),s=this._tmpMatrix;for(var c=o.length/3,u=0;u<c;u++){for(var h=[],d=0;d<3;d++){var p=new V(a[3*o[3*u+d]+0],a[3*o[3*u+d]+1],a[3*o[3*u+d]+2]);p=V.TransformCoordinates(p,s);var f=void 0;(f=0==d?this._tmpAmmoVectorA:1==d?this._tmpAmmoVectorB:this._tmpAmmoVectorC).setValue(p.x,p.y,p.z),h.push(f)}e.addTriangle(h[0],h[1],h[2]),n++}i.getChildMeshes().forEach((function(i){n+=r._addMeshVerts(e,t,i)}))}return n},e.prototype._softVertexData=function(e){var t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){var i=t.getIndices();i||(i=[]);var r=t.getVerticesData(Nr.PositionKind);r||(r=[]);var n=t.getVerticesData(Nr.NormalKind);n||(n=[]),t.computeWorldMatrix(!1);for(var o=[],a=[],s=0;s<r.length;s+=3){var l=new V(r[s],r[s+1],r[s+2]),c=new V(n[s],n[s+1],n[s+2]);l=V.TransformCoordinates(l,t.getWorldMatrix()),c=V.TransformNormal(c,t.getWorldMatrix()),o.push(l.x,l.y,l.z),a.push(c.x,c.y,c.z)}var u=new _o;return u.positions=o,u.normals=a,u.uvs=t.getVerticesData(Nr.UVKind),u.colors=t.getVerticesData(Nr.ColorKind),t&&t.getIndices&&(u.indices=t.getIndices()),u.applyToMesh(t),t.position=V.Zero(),t.rotationQuaternion=null,t.rotation=V.Zero(),t.computeWorldMatrix(!0),u}return _o.ExtractFromMesh(t)},e.prototype._createSoftbody=function(e){var t=e.object;if(t&&t.getIndices){var i=t.getIndices();i||(i=[]);var r=this._softVertexData(e),n=r.positions,o=r.normals;if(null===n||null===o)return new this.bjsAMMO.btCompoundShape;for(var a=[],s=[],l=0;l<n.length;l+=3){var c=new V(n[l],n[l+1],n[l+2]),u=new V(o[l],o[l+1],o[l+2]);a.push(c.x,c.y,-c.z),s.push(u.x,u.y,-u.z)}var h=(new this.bjsAMMO.btSoftBodyHelpers).CreateFromTriMesh(this.world.getWorldInfo(),a,t.getIndices(),i.length/3,!0),d=n.length/3,p=h.get_m_nodes(),f=void 0;for(l=0;l<d;l++)(f=p.at(l).get_m_n()).setX(s[3*l]),f.setY(s[3*l+1]),f.setZ(s[3*l+2]);return h}},e.prototype._createCloth=function(e){var t=e.object;if(t&&t.getIndices){var i=t.getIndices();i||(i=[]);var r=this._softVertexData(e),n=r.positions,o=r.normals;if(null===n||null===o)return new this.bjsAMMO.btCompoundShape;var a=n.length,s=Math.sqrt(a/3);e.segments=s;var l=s-1;return this._tmpAmmoVectorA.setValue(n[0],n[1],n[2]),this._tmpAmmoVectorB.setValue(n[3*l],n[3*l+1],n[3*l+2]),this._tmpAmmoVectorD.setValue(n[a-3],n[a-2],n[a-1]),this._tmpAmmoVectorC.setValue(n[a-3-3*l],n[a-2-3*l],n[a-1-3*l]),(new this.bjsAMMO.btSoftBodyHelpers).CreatePatch(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,this._tmpAmmoVectorC,this._tmpAmmoVectorD,s,s,e.getParam("fixedPoints"),!0)}},e.prototype._createRope=function(e){var t,i,r=this._softVertexData(e),n=r.positions,o=r.normals;if(null===n||null===o)return new this.bjsAMMO.btCompoundShape;if(r.applyToMesh(e.object,!0),e._isFromLine=!0,0===o.map((function(e){return e*e})).reduce((function(e,t){return e+t})))i=(t=n.length)/3-1,this._tmpAmmoVectorA.setValue(n[0],n[1],n[2]),this._tmpAmmoVectorB.setValue(n[t-3],n[t-2],n[t-1]);else{e._isFromLine=!1;var a=e.getParam("path");if(null===e.getParam("shape"))return ae.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;i=(t=a.length)-1,this._tmpAmmoVectorA.setValue(a[0].x,a[0].y,a[0].z),this._tmpAmmoVectorB.setValue(a[t-1].x,a[t-1].y,a[t-1].z)}e.segments=i;var s=e.getParam("fixedPoints");s=s>3?3:s;var l=(new this.bjsAMMO.btSoftBodyHelpers).CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,s);return l.get_m_cfg().set_collisions(17),l},e.prototype._createCustom=function(e){var t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),null==t&&(t=new this.bjsAMMO.btCompoundShape),t},e.prototype._addHullVerts=function(e,t,i){var r=this,n=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){var o=i.getIndices();o||(o=[]);var a=i.getVerticesData(Nr.PositionKind);a||(a=[]),i.computeWorldMatrix(!1);for(var s=o.length/3,l=0;l<s;l++){for(var c=[],u=0;u<3;u++){var h=new V(a[3*o[3*l+u]+0],a[3*o[3*l+u]+1],a[3*o[3*l+u]+2]);z.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),h=V.TransformCoordinates(h,this._tmpMatrix);var d=void 0;(d=0==u?this._tmpAmmoVectorA:1==u?this._tmpAmmoVectorB:this._tmpAmmoVectorC).setValue(h.x,h.y,h.z),c.push(d)}e.addPoint(c[0],!0),e.addPoint(c[1],!0),e.addPoint(c[2],!0),n++}i.getChildMeshes().forEach((function(i){n+=r._addHullVerts(e,t,i)}))}return n},e.prototype._createShape=function(e,t){var i=this;void 0===t&&(t=!1);var r,n=e.object,o=e.getObjectExtents();if(!t){var a=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];r=new this.bjsAMMO.btCompoundShape;var s=0;if(a.forEach((function(e){var t=e.getPhysicsImpostor();if(t){if(t.type==Ds.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";var n=i._createShape(t),o=e.parent.getWorldMatrix().clone(),a=new V;o.decompose(a),i._tmpAmmoTransform.getOrigin().setValue(e.position.x*a.x,e.position.y*a.y,e.position.z*a.z),i._tmpAmmoQuaternion.setValue(e.rotationQuaternion.x,e.rotationQuaternion.y,e.rotationQuaternion.z,e.rotationQuaternion.w),i._tmpAmmoTransform.setRotation(i._tmpAmmoQuaternion),r.addChildShape(i._tmpAmmoTransform,n),t.dispose(),s++}})),s>0){if(e.type!=Ds.NoImpostor){var l=this._createShape(e,!0);l&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),r.addChildShape(this._tmpAmmoTransform,l))}return r}this.bjsAMMO.destroy(r),r=null}switch(e.type){case Ds.SphereImpostor:if(j.WithinEpsilon(o.x,o.y,1e-4)&&j.WithinEpsilon(o.x,o.z,1e-4))r=new this.bjsAMMO.btSphereShape(o.x/2);else{this._tmpAmmoVectorA.setValue(0,0,0);var c=[this._tmpAmmoVectorA];r=new this.bjsAMMO.btMultiSphereShape(c,[1],1),this._tmpAmmoVectorA.setValue(o.x/2,o.y/2,o.z/2),r.setLocalScaling(this._tmpAmmoVectorA)}break;case Ds.CapsuleImpostor:var u=o.x/2;r=new this.bjsAMMO.btCapsuleShape(u,o.y-2*u);break;case Ds.CylinderImpostor:this._tmpAmmoVectorA.setValue(o.x/2,o.y/2,o.z/2),r=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case Ds.PlaneImpostor:case Ds.BoxImpostor:this._tmpAmmoVectorA.setValue(o.x/2,o.y/2,o.z/2),r=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case Ds.MeshImpostor:if(0==e.getParam("mass")){if(this.onCreateCustomMeshImpostor)r=this.onCreateCustomMeshImpostor(e);else{var h=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(h);var d=this._addMeshVerts(h,n,n);r=0==d?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(h)}break}case Ds.ConvexHullImpostor:if(this.onCreateCustomConvexHullImpostor)r=this.onCreateCustomConvexHullImpostor(e);else{var p=new this.bjsAMMO.btConvexHullShape;0==(d=this._addHullVerts(p,n,n))?(e._pluginData.toDispose.push(p),r=new this.bjsAMMO.btCompoundShape):r=p}break;case Ds.NoImpostor:r=new this.bjsAMMO.btSphereShape(o.x/2);break;case Ds.CustomImpostor:r=this._createCustom(e);break;case Ds.SoftbodyImpostor:r=this._createSoftbody(e);break;case Ds.ClothImpostor:r=this._createCloth(e);break;case Ds.RopeImpostor:r=this._createRope(e);break;default:ae.Warn("The impostor type is not currently supported by the ammo plugin.")}return r},e.prototype.setTransformationFromPhysicsBody=function(e){e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),e.object.rotationQuaternion?e.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):e.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(e.object.rotation))},e.prototype.setPhysicsBodyTransformation=function(e,t,i){var r=e.physicsBody.getWorldTransform();if(Math.abs(r.getOrigin().x()-t.x)>A||Math.abs(r.getOrigin().y()-t.y)>A||Math.abs(r.getOrigin().z()-t.z)>A||Math.abs(r.getRotation().x()-i.x)>A||Math.abs(r.getRotation().y()-i.y)>A||Math.abs(r.getRotation().z()-i.z)>A||Math.abs(r.getRotation().w()-i.w)>A)if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),r.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),r.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(r),0==e.mass){var n=e.physicsBody.getMotionState();n&&n.setWorldTransform(r)}else e.physicsBody.activate()},e.prototype.isSupported=function(){return void 0!==this.bjsAMMO},e.prototype.setLinearVelocity=function(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.linearVelocity(this._tmpAmmoVectorA):e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)},e.prototype.setAngularVelocity=function(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.angularVelocity(this._tmpAmmoVectorA):e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)},e.prototype.getLinearVelocity=function(e){var t;if(!(t=e.soft?e.physicsBody.linearVelocity():e.physicsBody.getLinearVelocity()))return null;var i=new V(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i},e.prototype.getAngularVelocity=function(e){var t;if(!(t=e.soft?e.physicsBody.angularVelocity():e.physicsBody.getAngularVelocity()))return null;var i=new V(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i},e.prototype.setBodyMass=function(e,t){e.soft?e.physicsBody.setTotalMass(t,!1):e.physicsBody.setMassProps(t),e._pluginData.mass=t},e.prototype.getBodyMass=function(e){return e._pluginData.mass||0},e.prototype.getBodyFriction=function(e){return e._pluginData.friction||0},e.prototype.setBodyFriction=function(e,t){e.soft?e.physicsBody.get_m_cfg().set_kDF(t):e.physicsBody.setFriction(t),e._pluginData.friction=t},e.prototype.getBodyRestitution=function(e){return e._pluginData.restitution||0},e.prototype.setBodyRestitution=function(e,t){e.physicsBody.setRestitution(t),e._pluginData.restitution=t},e.prototype.getBodyPressure=function(e){return e.soft?e._pluginData.pressure||0:(ae.Warn("Pressure is not a property of a rigid body"),0)},e.prototype.setBodyPressure=function(e,t){e.soft?e.type===Ds.SoftbodyImpostor?(e.physicsBody.get_m_cfg().set_kPR(t),e._pluginData.pressure=t):(e.physicsBody.get_m_cfg().set_kPR(0),e._pluginData.pressure=0):ae.Warn("Pressure can only be applied to a softbody")},e.prototype.getBodyStiffness=function(e){return e.soft?e._pluginData.stiffness||0:(ae.Warn("Stiffness is not a property of a rigid body"),0)},e.prototype.setBodyStiffness=function(e,t){e.soft?(t=(t=t<0?0:t)>1?1:t,e.physicsBody.get_m_materials().at(0).set_m_kLST(t),e._pluginData.stiffness=t):ae.Warn("Stiffness cannot be applied to a rigid body")},e.prototype.getBodyVelocityIterations=function(e){return e.soft?e._pluginData.velocityIterations||0:(ae.Warn("Velocity iterations is not a property of a rigid body"),0)},e.prototype.setBodyVelocityIterations=function(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_viterations(t),e._pluginData.velocityIterations=t):ae.Warn("Velocity iterations cannot be applied to a rigid body")},e.prototype.getBodyPositionIterations=function(e){return e.soft?e._pluginData.positionIterations||0:(ae.Warn("Position iterations is not a property of a rigid body"),0)},e.prototype.setBodyPositionIterations=function(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_piterations(t),e._pluginData.positionIterations=t):ae.Warn("Position iterations cannot be applied to a rigid body")},e.prototype.appendAnchor=function(e,t,i,r,n,o){void 0===n&&(n=1),void 0===o&&(o=!1);var a=e.segments,s=Math.round((a-1)*i)+a*(a-1-Math.round((a-1)*r));e.physicsBody.appendAnchor(s,t.physicsBody,o,n)},e.prototype.appendHook=function(e,t,i,r,n){void 0===r&&(r=1),void 0===n&&(n=!1);var o=Math.round(e.segments*i);e.physicsBody.appendAnchor(o,t.physicsBody,n,r)},e.prototype.sleepBody=function(e){e.physicsBody.forceActivationState(0)},e.prototype.wakeUpBody=function(e){e.physicsBody.activate()},e.prototype.updateDistanceJoint=function(){ae.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")},e.prototype.setMotor=function(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)},e.prototype.setLimit=function(){ae.Warn("setLimit is not currently supported by the Ammo physics plugin")},e.prototype.syncMeshWithImpostor=function(e,t){t.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.position.x=this._tmpAmmoTransform.getOrigin().x(),e.position.y=this._tmpAmmoTransform.getOrigin().y(),e.position.z=this._tmpAmmoTransform.getOrigin().z(),e.rotationQuaternion&&(e.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),e.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),e.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),e.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())},e.prototype.getRadius=function(e){return e.getObjectExtents().x/2},e.prototype.getBoxSizeToRef=function(e,t){var i=e.getObjectExtents();t.x=i.x,t.y=i.y,t.z=i.z},e.prototype.dispose=function(){this.bjsAMMO.destroy(this.world),this.bjsAMMO.destroy(this._softBodySolver),this.bjsAMMO.destroy(this._solver),this.bjsAMMO.destroy(this._overlappingPairCache),this.bjsAMMO.destroy(this._dispatcher),this.bjsAMMO.destroy(this._collisionConfiguration),this.bjsAMMO.destroy(this._tmpAmmoVectorA),this.bjsAMMO.destroy(this._tmpAmmoVectorB),this.bjsAMMO.destroy(this._tmpAmmoVectorC),this.bjsAMMO.destroy(this._tmpAmmoVectorD),this.bjsAMMO.destroy(this._tmpAmmoTransform),this.bjsAMMO.destroy(this._tmpAmmoQuaternion),this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback),this.world=null},e.prototype.raycast=function(e,t){return this.raycastToRef(e,t,this._raycastResult),this._raycastResult},e.prototype.raycastToRef=function(e,t,i){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(e.x,e.y,e.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(t.x,t.y,t.z);var r=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,r),i.reset(e,t),r.hasHit()&&(i.setHitData({x:r.get_m_hitNormalWorld().x(),y:r.get_m_hitNormalWorld().y(),z:r.get_m_hitNormalWorld().z()},{x:r.get_m_hitPointWorld().x(),y:r.get_m_hitPointWorld().y(),z:r.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(r),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)},e._DISABLE_COLLISION_FLAG=4,e._KINEMATIC_FLAG=2,e._DISABLE_DEACTIVATION_FLAG=4,e}();c.prototype.removeReflectionProbe=function(e){if(!this.reflectionProbes)return-1;var t=this.reflectionProbes.indexOf(e);return-1!==t&&this.reflectionProbes.splice(t,1),t},c.prototype.addReflectionProbe=function(e){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(e)};var Uv=function(){function e(e,t,i,r,n,o){void 0===r&&(r=!0),void 0===n&&(n=!1),void 0===o&&(o=!1);var a=this;if(this.name=e,this._viewMatrix=z.Identity(),this._target=V.Zero(),this._add=V.Zero(),this._invertYAxis=!1,this.position=V.Zero(),this.metadata=null,this._parentContainer=null,this._scene=i,i.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(var s=0;s<6;++s)this._sceneUBOs.push(i.createSceneUniformBuffer('Scene for Reflection Probe (name "'.concat(e,'") face #').concat(s)))}this._scene.reflectionProbes||(this._scene.reflectionProbes=[]),this._scene.reflectionProbes.push(this);var l=u.TEXTURETYPE_UNSIGNED_BYTE;if(n){var c=this._scene.getEngine().getCaps();c.textureHalfFloatRender?l=u.TEXTURETYPE_HALF_FLOAT:c.textureFloatRender&&(l=u.TEXTURETYPE_FLOAT)}this._renderTargetTexture=new Pl(e,t,i,r,!0,l,!0),this._renderTargetTexture.gammaSpace=!o,this._renderTargetTexture.invertZ=i.useRightHandedSystem;var h,d=i.getEngine().useReverseDepthBuffer;this._renderTargetTexture.onBeforeRenderObservable.add((function(e){switch(a._sceneUBOs&&(i.setSceneUniformBuffer(a._sceneUBOs[e]),i.getSceneUniformBuffer().unbindEffect()),e){case 0:a._add.copyFromFloats(1,0,0);break;case 1:a._add.copyFromFloats(-1,0,0);break;case 2:a._add.copyFromFloats(0,a._invertYAxis?1:-1,0);break;case 3:a._add.copyFromFloats(0,a._invertYAxis?-1:1,0);break;case 4:a._add.copyFromFloats(0,0,i.useRightHandedSystem?-1:1);break;case 5:a._add.copyFromFloats(0,0,i.useRightHandedSystem?1:-1)}a._attachedMesh&&a.position.copyFrom(a._attachedMesh.getAbsolutePosition()),a.position.addToRef(a._add,a._target);var t=i.useRightHandedSystem?z.LookAtRHToRef:z.LookAtLHToRef,r=i.useRightHandedSystem?z.PerspectiveFovRH:z.PerspectiveFovLH;t(a.position,a._target,V.Up(),a._viewMatrix),i.activeCamera&&(a._projectionMatrix=r(Math.PI/2,1,d?i.activeCamera.maxZ:i.activeCamera.minZ,d?i.activeCamera.minZ:i.activeCamera.maxZ,a._scene.getEngine().isNDCHalfZRange),i.setTransformMatrix(a._viewMatrix,a._projectionMatrix),i.activeCamera.isRigCamera&&!a._renderTargetTexture.activeCamera&&(a._renderTargetTexture.activeCamera=i.activeCamera.rigParent||null)),i._forcedViewPosition=a.position})),this._renderTargetTexture.onBeforeBindObservable.add((function(){var t,r;a._currentSceneUBO=i.getSceneUniformBuffer(),null===(r=(t=i.getEngine())._debugPushGroup)||void 0===r||r.call(t,"reflection probe generation for ".concat(e),1),h=a._scene.imageProcessingConfiguration.applyByPostProcess,o&&(i.imageProcessingConfiguration.applyByPostProcess=!0)})),this._renderTargetTexture.onAfterUnbindObservable.add((function(){var e,t;i.imageProcessingConfiguration.applyByPostProcess=h,i._forcedViewPosition=null,a._sceneUBOs&&i.setSceneUniformBuffer(a._currentSceneUBO),i.updateTransformMatrix(!0),null===(t=(e=i.getEngine())._debugPopGroup)||void 0===t||t.call(e,1)}))}return Object.defineProperty(e.prototype,"samples",{get:function(){return this._renderTargetTexture.samples},set:function(e){this._renderTargetTexture.samples=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"refreshRate",{get:function(){return this._renderTargetTexture.refreshRate},set:function(e){this._renderTargetTexture.refreshRate=e},enumerable:!1,configurable:!0}),e.prototype.getScene=function(){return this._scene},Object.defineProperty(e.prototype,"cubeTexture",{get:function(){return this._renderTargetTexture},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"renderList",{get:function(){return this._renderTargetTexture.renderList},set:function(e){this._renderTargetTexture.renderList=e},enumerable:!1,configurable:!0}),e.prototype.attachToMesh=function(e){this._attachedMesh=e},e.prototype.setRenderingAutoClearDepthStencil=function(e,t){this._renderTargetTexture.setRenderingAutoClearDepthStencil(e,t)},e.prototype.dispose=function(){var e=this._scene.reflectionProbes.indexOf(this);if(-1!==e&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){var t=this._parentContainer.reflectionProbes.indexOf(this);t>-1&&this._parentContainer.reflectionProbes.splice(t,1),this._parentContainer=null}if(this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null),this._sceneUBOs){for(var i=0,r=this._sceneUBOs;i<r.length;i++)r[i].dispose();this._sceneUBOs=[]}},e.prototype.toString=function(e){var t="Name: "+this.name;return e&&(t+=", position: "+this.position.toString(),this._attachedMesh&&(t+=", attached mesh: "+this._attachedMesh.name)),t},e.prototype.getClassName=function(){return"ReflectionProbe"},e.prototype.serialize=function(){var e=Ke.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e},e.Parse=function(t,i,r){var n=null;if(i.reflectionProbes)for(var o=0;o<i.reflectionProbes.length;o++){var a=i.reflectionProbes[o];if(a.name===t.name){n=a;break}}return(n=Ke.Parse((function(){return n||new e(t.name,t.renderTargetSize,i,t._generateMipMaps)}),t,i,r)).cubeTexture._waitingRenderList=t.renderList,t._attachedMesh&&n.attachToMesh(i.getMeshById(t._attachedMesh)),t.metadata&&(n.metadata=t.metadata),n},v([Le()],e.prototype,"_attachedMesh",void 0),v([Fe()],e.prototype,"position",void 0),e}(),Vv=function(e){function t(t,i){var r=e.call(this)||this;return r.name=t,r.animations=new Array,r.isPickable=!1,r.useAlphaForPicking=!1,r.onDisposeObservable=new f,r._onAnimationEnd=null,r._endAnimation=function(){r._onAnimationEnd&&r._onAnimationEnd(),r.disposeWhenFinishedAnimating&&r.dispose()},r.color=new J(1,1,1,1),r.position=V.Zero(),r._manager=i,r._manager.sprites.push(r),r.uniqueId=r._manager.scene.getUniqueId(),r}return m(t,e),Object.defineProperty(t.prototype,"size",{get:function(){return this.width},set:function(e){this.width=e,this.height=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"manager",{get:function(){return this._manager},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"Sprite"},Object.defineProperty(t.prototype,"fromIndex",{get:function(){return this._fromIndex},set:function(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"toIndex",{get:function(){return this._toIndex},set:function(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"loopAnimation",{get:function(){return this._loopAnimation},set:function(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"delay",{get:function(){return Math.max(this._delay,1)},set:function(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)},enumerable:!1,configurable:!0}),t.prototype.playAnimation=function(t,i,r,n,o){void 0===o&&(o=null),this._onAnimationEnd=o,e.prototype.playAnimation.call(this,t,i,r,n,this._endAnimation)},t.prototype.dispose=function(){for(var e=0;e<this._manager.sprites.length;e++)this._manager.sprites[e]==this&&this._manager.sprites.splice(e,1);this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},t.prototype.serialize=function(){var e={};return e.name=this.name,e.position=this.position.asArray(),e.color=this.color.asArray(),e.width=this.width,e.height=this.height,e.angle=this.angle,e.cellIndex=this.cellIndex,e.cellRef=this.cellRef,e.invertU=this.invertU,e.invertV=this.invertV,e.disposeWhenFinishedAnimating=this.disposeWhenFinishedAnimating,e.isPickable=this.isPickable,e.isVisible=this.isVisible,e.useAlphaForPicking=this.useAlphaForPicking,e.animationStarted=this.animationStarted,e.fromIndex=this.fromIndex,e.toIndex=this.toIndex,e.loopAnimation=this.loopAnimation,e.delay=this.delay,e},t.Parse=function(e,i){var r=new t(e.name,i);return r.position=V.FromArray(e.position),r.color=J.FromArray(e.color),r.width=e.width,r.height=e.height,r.angle=e.angle,r.cellIndex=e.cellIndex,r.cellRef=e.cellRef,r.invertU=e.invertU,r.invertV=e.invertV,r.disposeWhenFinishedAnimating=e.disposeWhenFinishedAnimating,r.isPickable=e.isPickable,r.isVisible=e.isVisible,r.useAlphaForPicking=e.useAlphaForPicking,r._fromIndex=e.fromIndex,r._toIndex=e.toIndex,r._loopAnimation=e.loopAnimation,r._delay=e.delay,e.animationStarted&&r.playAnimation(r.fromIndex,r.toIndex,r.loopAnimation,r.delay),r},t}(function(){function e(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}return Object.defineProperty(e.prototype,"animationStarted",{get:function(){return this._animationStarted},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"fromIndex",{get:function(){return this._fromIndex},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"toIndex",{get:function(){return this._toIndex},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"loopAnimation",{get:function(){return this._loopAnimation},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"delay",{get:function(){return Math.max(this._delay,1)},enumerable:!1,configurable:!0}),e.prototype.playAnimation=function(e,t,i,r,n){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=r||1,this._animationStarted=!0,this._onBaseAnimationEnd=n,e<t?this._direction=1:(this._direction=-1,this._toIndex=e,this._fromIndex=t),this.cellIndex=e,this._time=0},e.prototype.stopAnimation=function(){this._animationStarted=!1},e.prototype._animate=function(e){this._animationStarted&&(this._time+=e,this._time>this._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex<this._fromIndex)&&(this._loopAnimation?this.cellIndex=this._direction>0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))},e}());pn.prototype._internalPickSprites=function(e,t,i,r){if(!Fr)return null;var n=null;if(!r){if(!this.activeCamera)return null;r=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(var o=0;o<this.spriteManagers.length;o++){var a=this.spriteManagers[o];if(a.isPickable){var s=a.intersects(e,r,t,i);if(s&&s.hit&&(i||null==n||!(s.distance>=n.distance))&&(n=s,i))break}}return n||new Fr},pn.prototype._internalMultiPickSprites=function(e,t,i){if(!Fr)return null;var r=[];if(!i){if(!this.activeCamera)return null;i=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(var n=0;n<this.spriteManagers.length;n++){var o=this.spriteManagers[n];if(o.isPickable){var a=o.multiIntersects(e,i,t);null!==a&&(r=r.concat(a))}}return r},pn.prototype.pickSprite=function(e,t,i,r,n){if(!this._tempSpritePickingRay)return null;this.createPickingRayInCameraSpaceToRef(e,t,this._tempSpritePickingRay,n);var o=this._internalPickSprites(this._tempSpritePickingRay,i,r,n);return o&&(o.ray=this.createPickingRayInCameraSpace(e,t,n)),o},pn.prototype.pickSpriteWithRay=function(e,t,i,r){if(!this._tempSpritePickingRay)return null;if(!r){if(!this.activeCamera)return null;r=this.activeCamera}hs.TransformToRef(e,r.getViewMatrix(),this._tempSpritePickingRay);var n=this._internalPickSprites(this._tempSpritePickingRay,t,i,r);return n&&(n.ray=e),n},pn.prototype.multiPickSprite=function(e,t,i,r){return this.createPickingRayInCameraSpaceToRef(e,t,this._tempSpritePickingRay,r),this._internalMultiPickSprites(this._tempSpritePickingRay,i,r)},pn.prototype.multiPickSpriteWithRay=function(e,t,i){if(!this._tempSpritePickingRay)return null;if(!i){if(!this.activeCamera)return null;i=this.activeCamera}return hs.TransformToRef(e,i.getViewMatrix(),this._tempSpritePickingRay),this._internalMultiPickSprites(this._tempSpritePickingRay,t,i)},pn.prototype.setPointerOverSprite=function(e){this._pointerOverSprite!==e&&(this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(u.ACTION_OnPointerOutTrigger,te.CreateNewFromSprite(this._pointerOverSprite,this)),this._pointerOverSprite=e,this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(u.ACTION_OnPointerOverTrigger,te.CreateNewFromSprite(this._pointerOverSprite,this)))},pn.prototype.getPointerOverSprite=function(){return this._pointerOverSprite};var kv=function(){function e(e){this.name=Vr.NAME_SPRITE,this.scene=e,this.scene.spriteManagers=[],this.scene._tempSpritePickingRay=hs?hs.Zero():null,this.scene.onBeforeSpritesRenderingObservable=new f,this.scene.onAfterSpritesRenderingObservable=new f,this._spritePredicate=function(e){return!!e.actionManager&&e.isPickable&&e.actionManager.hasPointerTriggers}}return e.prototype.register=function(){this.scene._pointerMoveStage.registerStep(Vr.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(Vr.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(Vr.STEP_POINTERUP_SPRITE,this,this._pointerUp)},e.prototype.rebuild=function(){},e.prototype.dispose=function(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();var e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()},e.prototype._pickSpriteButKeepRay=function(e,t,i,r,n){var o=this.scene.pickSprite(t,i,this._spritePredicate,r,n);return o&&(o.ray=e?e.ray:null),o},e.prototype._pointerMove=function(e,t,i,r,n){var o=this.scene;return r?o.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,o.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite?(o.setPointerOverSprite(i.pickedSprite),!o.doNotHandleCursors&&n&&(o._pointerOverSprite&&o._pointerOverSprite.actionManager&&o._pointerOverSprite.actionManager.hoverCursor?n.style.cursor=o._pointerOverSprite.actionManager.hoverCursor:n.style.cursor=o.hoverCursor)):o.setPointerOverSprite(null),i},e.prototype._pointerDown=function(e,t,i,r){var n=this.scene;if(n._pickedDownSprite=null,n.spriteManagers&&n.spriteManagers.length>0&&(i=n.pickSprite(e,t,this._spritePredicate,!1,n.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(n._pickedDownSprite=i.pickedSprite,r.button){case 0:i.pickedSprite.actionManager.processTrigger(u.ACTION_OnLeftPickTrigger,te.CreateNewFromSprite(i.pickedSprite,n,r));break;case 1:i.pickedSprite.actionManager.processTrigger(u.ACTION_OnCenterPickTrigger,te.CreateNewFromSprite(i.pickedSprite,n,r));break;case 2:i.pickedSprite.actionManager.processTrigger(u.ACTION_OnRightPickTrigger,te.CreateNewFromSprite(i.pickedSprite,n,r))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(u.ACTION_OnPickDownTrigger,te.CreateNewFromSprite(i.pickedSprite,n,r))}return i},e.prototype._pointerUp=function(e,t,i,r,n){var o=this.scene;if(o.spriteManagers&&o.spriteManagers.length>0){var a=o.pickSprite(e,t,this._spritePredicate,!1,o.cameraToUseForPointers||void 0);a&&(a.hit&&a.pickedSprite&&a.pickedSprite.actionManager&&(a.pickedSprite.actionManager.processTrigger(u.ACTION_OnPickUpTrigger,te.CreateNewFromSprite(a.pickedSprite,o,r)),a.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||a.pickedSprite.actionManager.processTrigger(u.ACTION_OnPickTrigger,te.CreateNewFromSprite(a.pickedSprite,o,r)),n&&a.pickedSprite.actionManager.processTrigger(u.ACTION_OnDoublePickTrigger,te.CreateNewFromSprite(a.pickedSprite,o,r)))),o._pickedDownSprite&&o._pickedDownSprite.actionManager&&o._pickedDownSprite!==a.pickedSprite&&o._pickedDownSprite.actionManager.processTrigger(u.ACTION_OnPickOutTrigger,te.CreateNewFromSprite(o._pickedDownSprite,o,r)))}return i},e}();li.IncludesShadersStore.imageProcessingCompatibility="#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2));\n#endif\n";li.ShadersStore.spritesPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler;\n#include<fogFragmentDeclaration>\n#include<logDepthDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#ifdef PIXEL_PERFECT\nvec2 uvPixelPerfect(vec2 uv) {vec2 res=vec2(textureSize(diffuseSampler,0));uv=uv*res;vec2 seam=floor(uv+0.5);uv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);return uv/res;}\n#endif\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#ifdef PIXEL_PERFECT\nvec2 uv=uvPixelPerfect(vUV);\n#else\nvec2 uv=vUV;\n#endif\nvec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.)\n{if (color.a<0.95)\ndiscard;}\ncolor*=vColor;\n#include<logDepthFragment>\n#include<fogFragment>\ngl_FragColor=color;\n#include<imageProcessingCompatibility>\n#define CUSTOM_FRAGMENT_MAIN_END\n}";li.ShadersStore.spritesVertexShader="attribute vec4 position;attribute vec2 options;attribute vec2 offsets;attribute vec2 inverts;attribute vec4 cellInfo;attribute vec4 color;uniform mat4 view;uniform mat4 projection;varying vec2 vUV;varying vec4 vColor;\n#include<fogVertexDeclaration>\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=offsets.xy;cornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); \nvColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));vec2 uvPlace=cellInfo.xy;vec2 uvSize=cellInfo.zw;vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vUV.y=uvPlace.y+uvSize.y*uvOffset.y;\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}";var Gv=function(){function e(e,t,i,r){void 0===i&&(i=.01),void 0===r&&(r=null),this.blendMode=u.ALPHA_COMBINE,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this._fogEnabled=!0,this._pixelPerfect=!1,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},this._capacity=t,this._epsilon=i,this._engine=e,this._useInstancing=e.getCaps().instancedArrays&&e._features.supportSpriteInstancing,this._useVAO=e.getCaps().vertexArrayObject&&!e.disableVertexArrayObjects,this._scene=r,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new Dr(e,this._vertexData,!0,this._vertexBufferSize);var n,o=this._buffer.createVertexBuffer(Nr.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),a=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing),s=6;if(this._useInstancing){var l=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Dr(e,l,!1,2),n=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else n=this._buffer.createVertexBuffer("offsets",s,2,this._vertexBufferSize,this._useInstancing),s+=2;var c=this._buffer.createVertexBuffer("inverts",s,2,this._vertexBufferSize,this._useInstancing),h=this._buffer.createVertexBuffer("cellInfo",s+2,4,this._vertexBufferSize,this._useInstancing),d=this._buffer.createVertexBuffer(Nr.ColorKind,s+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[Nr.PositionKind]=o,this._vertexBuffers.options=a,this._vertexBuffers.offsets=n,this._vertexBuffers.inverts=c,this._vertexBuffers.cellInfo=h,this._vertexBuffers[Nr.ColorKind]=d,this._createEffects()}return Object.defineProperty(e.prototype,"fogEnabled",{get:function(){return this._fogEnabled},set:function(e){this._fogEnabled!==e&&(this._fogEnabled=e,this._createEffects())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useLogarithmicDepth",{get:function(){return this._useLogarithmicDepth},set:function(e){var t,i=!!(null===(t=this._scene)||void 0===t?void 0:t.getEngine().getCaps().fragmentDepthSupported);e&&!i&&ae.Warn("Logarithmic depth has been requested for a sprite renderer on a device that doesn't support it."),this._useLogarithmicDepth=e&&i,this._createEffects()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"capacity",{get:function(){return this._capacity},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"pixelPerfect",{get:function(){return this._pixelPerfect},set:function(e){this._pixelPerfect!==e&&(this._pixelPerfect=e,this._createEffects())},enumerable:!1,configurable:!0}),e.prototype._createEffects=function(){var e,t;null===(e=this._drawWrapperBase)||void 0===e||e.dispose(),null===(t=this._drawWrapperDepth)||void 0===t||t.dispose(),this._drawWrapperBase=new ho(this._engine),this._drawWrapperDepth=new ho(this._engine,!1),this._drawWrapperBase.drawContext&&(this._drawWrapperBase.drawContext.useInstancing=this._useInstancing),this._drawWrapperDepth.drawContext&&(this._drawWrapperDepth.drawContext.useInstancing=this._useInstancing);var i="";this._pixelPerfect&&(i+="#define PIXEL_PERFECT\n"),this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode&&this._fogEnabled&&(i+="#define FOG\n"),this._useLogarithmicDepth&&(i+="#define LOGARITHMICDEPTH\n"),this._drawWrapperBase.effect=this._engine.createEffect("sprites",[Nr.PositionKind,"options","offsets","inverts","cellInfo",Nr.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor","logarithmicDepthConstant"],["diffuseSampler"],i),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext},e.prototype.render=function(e,t,i,r,n){if(void 0===n&&(n=null),this.texture&&this.texture.isReady()&&e.length){var o=this._drawWrapperBase,a=this._drawWrapperDepth,s=this.fogEnabled&&this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode,l=o.effect;if(l.isReady()){for(var c=this._engine,h=!(!this._scene||!this._scene.useRightHandedSystem),d=this.texture.getBaseSize(),p=Math.min(this._capacity,e.length),f=0,_=!0,m=0;m<p;m++){var g=e[m];g&&g.isVisible&&(_=!1,g._animate(t),this._appendSpriteVertex(f++,g,0,0,d,h,n),this._useInstancing||(this._appendSpriteVertex(f++,g,1,0,d,h,n),this._appendSpriteVertex(f++,g,1,1,d,h,n),this._appendSpriteVertex(f++,g,0,1,d,h,n)))}if(!_){this._buffer.update(this._vertexData);var v=!!c.depthCullingState.cull,y=c.depthCullingState.zOffset,b=c.depthCullingState.zOffsetUnits;if(c.setState(v,y,!1,!1,void 0,void 0,b),c.enableEffect(o),l.setTexture("diffuseSampler",this.texture),l.setMatrix("view",i),l.setMatrix("projection",r),s){var T=this._scene;l.setFloat4("vFogInfos",T.fogMode,T.fogStart,T.fogEnd,T.fogDensity),l.setColor3("vFogColor",T.fogColor)}this.useLogarithmicDepth&&this._scene&&Ko(o.defines,l,this._scene),this._useVAO?(this._vertexArrayObject||(this._vertexArrayObject=c.recordVertexArrayObject(this._vertexBuffers,this._indexBuffer,l)),c.bindVertexArrayObject(this._vertexArrayObject,this._indexBuffer)):c.bindBuffers(this._vertexBuffers,this._indexBuffer,l),c.depthCullingState.depthFunc=c.useReverseDepthBuffer?u.GEQUAL:u.LEQUAL,this.disableDepthWrite||(l.setBool("alphaTest",!0),c.setColorWrite(!1),c.enableEffect(a),this._useInstancing?c.drawArraysType(u.MATERIAL_TriangleStripDrawMode,0,4,f):c.drawElementsType(u.MATERIAL_TriangleFillMode,0,f/4*6),c.enableEffect(o),c.setColorWrite(!0),l.setBool("alphaTest",!1)),c.setAlphaMode(this.blendMode),this._useInstancing?c.drawArraysType(u.MATERIAL_TriangleStripDrawMode,0,4,f):c.drawElementsType(u.MATERIAL_TriangleFillMode,0,f/4*6),this.autoResetAlpha&&c.setAlphaMode(u.ALPHA_DISABLE),h&&this._scene.getEngine().setState(v,y,!1,!0,void 0,void 0,b),c.unbindInstanceAttributes()}}}},e.prototype._appendSpriteVertex=function(e,t,i,r,n,o,a){var s=e*this._vertexBufferSize;if(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===r?r=this._epsilon:1===r&&(r=1-this._epsilon),a)a(t,n);else{t.cellIndex||(t.cellIndex=0);var l=n.width/this.cellWidth,c=t.cellIndex/l|0;t._xOffset=(t.cellIndex-c*l)*this.cellWidth/n.width,t._yOffset=c*this.cellHeight/n.height,t._xSize=this.cellWidth,t._ySize=this.cellHeight}this._vertexData[s]=t.position.x,this._vertexData[s+1]=t.position.y,this._vertexData[s+2]=t.position.z,this._vertexData[s+3]=t.angle,this._vertexData[s+4]=t.width,this._vertexData[s+5]=t.height,this._useInstancing?s-=2:(this._vertexData[s+6]=i,this._vertexData[s+7]=r),this._vertexData[s+8]=o?t.invertU?0:1:t.invertU?1:0,this._vertexData[s+9]=t.invertV?1:0,this._vertexData[s+10]=t._xOffset,this._vertexData[s+11]=t._yOffset,this._vertexData[s+12]=t._xSize/n.width,this._vertexData[s+13]=t._ySize/n.height,this._vertexData[s+14]=t.color.r,this._vertexData[s+15]=t.color.g,this._vertexData[s+16]=t.color.b,this._vertexData[s+17]=t.color.a},e.prototype._buildIndexBuffer=function(){for(var e=[],t=0,i=0;i<this._capacity;i++)e.push(t),e.push(t+1),e.push(t+2),e.push(t),e.push(t+2),e.push(t+3),t+=4;this._indexBuffer=this._engine.createIndexBuffer(e)},e.prototype.rebuild=function(){var e;for(var t in this._indexBuffer&&this._buildIndexBuffer(),this._useVAO&&(this._vertexArrayObject=void 0),this._buffer._rebuild(),this._vertexBuffers)this._vertexBuffers[t]._rebuild();null===(e=this._spriteBuffer)||void 0===e||e._rebuild()},e.prototype.dispose=function(){this._buffer&&(this._buffer.dispose(),this._buffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this.texture&&(this.texture.dispose(),this.texture=null),this._drawWrapperBase.dispose(),this._drawWrapperDepth.dispose()},e}(),zv=function(){function e(e,t,i,r,n,o,a,s,l){void 0===o&&(o=.01),void 0===a&&(a=Ja.TRILINEAR_SAMPLINGMODE),void 0===s&&(s=!1),void 0===l&&(l=null);var c=this;this.name=e,this.sprites=[],this.renderingGroupId=0,this.layerMask=268435455,this.isPickable=!1,this.metadata=null,this._wasDispatched=!1,this.onDisposeObservable=new f,this._disableDepthWrite=!1,this._packedAndReady=!1,this._customUpdate=function(e,t){e.cellRef||(e.cellIndex=0);var i=e.cellIndex;"number"==typeof i&&isFinite(i)&&Math.floor(i)===i&&(e.cellRef=c._spriteMap[e.cellIndex]),e._xOffset=c._cellData[e.cellRef].frame.x/t.width,e._yOffset=c._cellData[e.cellRef].frame.y/t.height,e._xSize=c._cellData[e.cellRef].frame.w,e._ySize=c._cellData[e.cellRef].frame.h},n||(n=M.LastCreatedScene),n._getComponent(Vr.NAME_SPRITE)||n._addComponent(new kv(n)),this._fromPacked=s,this._scene=n;var u=this._scene.getEngine();if(this._spriteRenderer=new Gv(u,i,o,n),r.width&&r.height)this.cellWidth=r.width,this.cellHeight=r.height;else{if(void 0===r)return void(this._spriteRenderer=null);this.cellWidth=r,this.cellHeight=r}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new Ja(t,n,!0,!1,a)),this._fromPacked&&this._makePacked(t,l)}return Object.defineProperty(e.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"children",{get:function(){return this.sprites},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"scene",{get:function(){return this._scene},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"capacity",{get:function(){return this._spriteRenderer.capacity},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"texture",{get:function(){return this._spriteRenderer.texture},set:function(e){e.wrapU=Ja.CLAMP_ADDRESSMODE,e.wrapV=Ja.CLAMP_ADDRESSMODE,this._spriteRenderer.texture=e,this._textureContent=null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"cellWidth",{get:function(){return this._spriteRenderer.cellWidth},set:function(e){this._spriteRenderer.cellWidth=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"cellHeight",{get:function(){return this._spriteRenderer.cellHeight},set:function(e){this._spriteRenderer.cellHeight=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"fogEnabled",{get:function(){return this._spriteRenderer.fogEnabled},set:function(e){this._spriteRenderer.fogEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useLogarithmicDepth",{get:function(){return this._spriteRenderer.useLogarithmicDepth},set:function(e){this._spriteRenderer.useLogarithmicDepth=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"blendMode",{get:function(){return this._spriteRenderer.blendMode},set:function(e){this._spriteRenderer.blendMode=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"disableDepthWrite",{get:function(){return this._disableDepthWrite},set:function(e){this._disableDepthWrite=e,this._spriteRenderer.disableDepthWrite=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"pixelPerfect",{get:function(){return this._spriteRenderer.pixelPerfect},set:function(e){this._spriteRenderer.pixelPerfect=e,e&&this.texture.samplingMode!==u.TEXTURE_TRILINEAR_SAMPLINGMODE&&this.texture.updateSamplingMode(u.TEXTURE_TRILINEAR_SAMPLINGMODE)},enumerable:!1,configurable:!0}),e.prototype.getClassName=function(){return"SpriteManager"},e.prototype._makePacked=function(e,t){var i=this;if(null!==t)try{var r=void 0;if((r="string"==typeof t?JSON.parse(t):t).frames.length){for(var n={},o=0;o<r.frames.length;o++){var a=r.frames[o];if("string"!=typeof Object.keys(a)[0])throw new Error("Invalid JSON Format. Check the frame values and make sure the name is the first parameter.");n[a[Object.keys(a)[0]]]=a}r.frames=n}var s=Reflect.ownKeys(r.frames);this._spriteMap=s,this._packedAndReady=!0,this._cellData=r.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,new Error("Invalid JSON from string. Spritesheet managed with constant cell size.")}else{var l=/\./g,c=void 0;do{c=l.lastIndex,l.test(e)}while(l.lastIndex>0);var u=e.substring(0,c-1)+".json";rr.LoadFile(u,(function(e){try{var t=JSON.parse(e),r=Reflect.ownKeys(t.frames);i._spriteMap=r,i._packedAndReady=!0,i._cellData=t.frames}catch(e){throw i._fromPacked=!1,i._packedAndReady=!1,new Error("Invalid JSON format. Please check documentation for format specifications.")}}),void 0,void 0,!1,(function(){ae.Error("JSON ERROR: Unable to load JSON file."),i._fromPacked=!1,i._packedAndReady=!1}))}},e.prototype._checkTextureAlpha=function(e,t,i,r,n){if(!e.useAlphaForPicking||!this.texture)return!0;var o=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(o.width*o.height*4),this.texture.readPixels(0,0,this._textureContent));var a=H.Vector3[0];a.copyFrom(t.direction),a.normalize(),a.scaleInPlace(i),a.addInPlace(t.origin);var s=(a.x-r.x)/(n.x-r.x),l=1-(a.y-r.y)/(n.y-r.y),c=e._xOffset*o.width+s*e._xSize|0,u=e._yOffset*o.height+l*e._ySize|0;return this._textureContent[4*(c+u*o.width)+3]>.5},e.prototype.intersects=function(e,t,i,r){for(var n=Math.min(this.capacity,this.sprites.length),o=V.Zero(),a=V.Zero(),s=Number.MAX_VALUE,l=null,c=H.Vector3[0],u=H.Vector3[1],h=t.getViewMatrix(),d=e,p=e,f=0;f<n;f++){var _=this.sprites[f];if(_){if(i){if(!i(_))continue}else if(!_.isPickable)continue;if(V.TransformCoordinatesToRef(_.position,h,u),_.angle?(z.TranslationToRef(-u.x,-u.y,0,H.Matrix[1]),z.TranslationToRef(u.x,u.y,0,H.Matrix[2]),z.RotationZToRef(-_.angle,H.Matrix[3]),H.Matrix[1].multiplyToRef(H.Matrix[3],H.Matrix[4]),H.Matrix[4].multiplyToRef(H.Matrix[2],H.Matrix[0]),d=e.clone(),V.TransformCoordinatesToRef(e.origin,H.Matrix[0],d.origin),V.TransformNormalToRef(e.direction,H.Matrix[0],d.direction)):d=e,o.copyFromFloats(u.x-_.width/2,u.y-_.height/2,u.z),a.copyFromFloats(u.x+_.width/2,u.y+_.height/2,u.z),d.intersectsBoxMinMax(o,a)){var m=V.Distance(u,d.origin);if(s>m){if(!this._checkTextureAlpha(_,d,m,o,a))continue;if(p=d,s=m,l=_,r)break}}}}if(l){var g=new Fr;h.invertToRef(H.Matrix[0]),g.hit=!0,g.pickedSprite=l,g.distance=s;var v=H.Vector3[2];return v.copyFrom(p.direction),v.normalize(),v.scaleInPlace(s),p.origin.addToRef(v,c),g.pickedPoint=V.TransformCoordinates(c,H.Matrix[0]),g}return null},e.prototype.multiIntersects=function(e,t,i){for(var r,n=Math.min(this.capacity,this.sprites.length),o=V.Zero(),a=V.Zero(),s=[],l=H.Vector3[0].copyFromFloats(0,0,0),c=H.Vector3[1].copyFromFloats(0,0,0),u=t.getViewMatrix(),h=0;h<n;h++){var d=this.sprites[h];if(d){if(i){if(!i(d))continue}else if(!d.isPickable)continue;if(V.TransformCoordinatesToRef(d.position,u,c),o.copyFromFloats(c.x-d.width/2,c.y-d.height/2,c.z),a.copyFromFloats(c.x+d.width/2,c.y+d.height/2,c.z),e.intersectsBoxMinMax(o,a)){if(r=V.Distance(c,e.origin),!this._checkTextureAlpha(d,e,r,o,a))continue;var p=new Fr;s.push(p),u.invertToRef(H.Matrix[0]),p.hit=!0,p.pickedSprite=d,p.distance=r;var f=H.Vector3[2];f.copyFrom(e.direction),f.normalize(),f.scaleInPlace(r),e.origin.addToRef(f,l),p.pickedPoint=V.TransformCoordinates(l,H.Matrix[0])}}}return s},e.prototype.render=function(){if(!this._fromPacked||this._packedAndReady&&this._spriteMap&&this._cellData){var e=this._scene.getEngine().getDeltaTime();this._packedAndReady?this._spriteRenderer.render(this.sprites,e,this._scene.getViewMatrix(),this._scene.getProjectionMatrix(),this._customUpdate):this._spriteRenderer.render(this.sprites,e,this._scene.getViewMatrix(),this._scene.getProjectionMatrix())}},e.prototype.rebuild=function(){var e;null===(e=this._spriteRenderer)||void 0===e||e.rebuild()},e.prototype.dispose=function(){if(this._spriteRenderer&&(this._spriteRenderer.dispose(),this._spriteRenderer=null),this._textureContent=null,this._scene.spriteManagers){var e=this._scene.spriteManagers.indexOf(this);this._scene.spriteManagers.splice(e,1)}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null},e.prototype.serialize=function(e){void 0===e&&(e=!1);var t={};t.name=this.name,t.capacity=this.capacity,t.cellWidth=this.cellWidth,t.cellHeight=this.cellHeight,t.fogEnabled=this.fogEnabled,t.blendMode=this.blendMode,t.disableDepthWrite=this.disableDepthWrite,t.pixelPerfect=this.pixelPerfect,t.useLogarithmicDepth=this.useLogarithmicDepth,this.texture&&(e?t.texture=this.texture.serialize():(t.textureUrl=this.texture.name,t.invertY=this.texture._invertY)),t.sprites=[];for(var i=0,r=this.sprites;i<r.length;i++){var n=r[i];t.sprites.push(n.serialize())}return t.metadata=this.metadata,t},e.Parse=function(t,i,r){var n=new e(t.name,"",t.capacity,{width:t.cellWidth,height:t.cellHeight},i);void 0!==t.fogEnabled&&(n.fogEnabled=t.fogEnabled),void 0!==t.blendMode&&(n.blendMode=t.blendMode),void 0!==t.disableDepthWrite&&(n.disableDepthWrite=t.disableDepthWrite),void 0!==t.pixelPerfect&&(n.pixelPerfect=t.pixelPerfect),void 0!==t.useLogarithmicDepth&&(n.useLogarithmicDepth=t.useLogarithmicDepth),void 0!==t.metadata&&(n.metadata=t.metadata),t.texture?n.texture=Ja.Parse(t.texture,i,r):t.textureName&&(n.texture=new Ja(r+t.textureUrl,i,!1,void 0===t.invertY||t.invertY));for(var o=0,a=t.sprites;o<a.length;o++){var s=a[o];Vv.Parse(s,n)}return n},e.ParseFromFileAsync=function(t,i,r,n){return void 0===n&&(n=""),new Promise((function(o,a){var s=new Je;s.addEventListener("readystatechange",(function(){if(4==s.readyState)if(200==s.status){var i=JSON.parse(s.responseText),l=e.Parse(i,r||M.LastCreatedScene,n);t&&(l.name=t),o(l)}else a("Unable to load the sprite manager")})),s.open("GET",i),s.send()}))},e.ParseFromSnippetAsync=function(t,i,r){var n=this;return void 0===r&&(r=""),"_BLANK"===t?Promise.resolve(new e("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,i)):new Promise((function(o,a){var s=new Je;s.addEventListener("readystatechange",(function(){if(4==s.readyState)if(200==s.status){var n=JSON.parse(JSON.parse(s.responseText).jsonPayload),l=JSON.parse(n.spriteManager),c=e.Parse(l,i||M.LastCreatedScene,r);c.snippetId=t,o(c)}else a("Unable to load the snippet "+t)})),s.open("GET",n.SnippetUrl+"/"+t.replace(/#/g,"/")),s.send()}))},e.SnippetUrl=u.SnippetUrl,e.CreateFromSnippetAsync=e.ParseFromSnippetAsync,e}(),Wv=!0,Hv=function(){function e(){}return e.LoaderInjectedPhysicsEngine=void 0,e}(),Xv={},jv={},Yv=function(e,t,i,r){if(!t.materials)return null;for(var n=0,o=t.materials.length;n<o;n++){var a=t.materials[n];if(e(a))return{parsedMaterial:a,material:Ca.Parse(a,i,r)}}return null},Kv=function(e,t){return e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown")},Qv=function(e,t){var i=t;if(t._waitingData.lods){if(t._waitingData.lods.ids&&t._waitingData.lods.ids.length>0){var r=t._waitingData.lods.ids,n=i.isEnabled(!1);if(t._waitingData.lods.distances){var o=t._waitingData.lods.distances;if(o.length>=r.length){var a=o.length>r.length?o[o.length-1]:0;i.setEnabled(!1);for(var s=0;s<r.length;s++){var l=r[s],c=e.getMeshById(l);null!=c&&i.addLODLevel(o[s],c)}a>0&&i.addLODLevel(a,null),!0===n&&i.setEnabled(!0)}else rr.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},qv=function(e,t,i){if("number"!=typeof e){var r=i.getLastEntryById(e);return r&&null!=t?r.instances[parseInt(t)]:r}var n=Xv[e];return n&&null!=t?n.instances[parseInt(t)]:n},Zv=function(e,t){return"number"!=typeof e?t.getLastMaterialById(e,!0):jv[e]},Jv=function(e,t,i,r,n){void 0===n&&(n=!1);var o=new Va(e),a="importScene has failed JSON parse";try{var l=JSON.parse(t);a="";var u=Ls.loggingLevel===Ls.DETAILED_LOGGING,h=void 0,d=void 0;if(void 0!==l.environmentTexture&&null!==l.environmentTexture){var p=void 0===l.isPBR||l.isPBR;if(l.environmentTextureType&&"BABYLON.HDRCubeTexture"===l.environmentTextureType){var f=l.environmentTextureSize?l.environmentTextureSize:128,_=new Pv((l.environmentTexture.match(/https?:\/\//g)?"":i)+l.environmentTexture,e,f,!0,!p,void 0,l.environmentTexturePrefilterOnLoad);l.environmentTextureRotationY&&(_.rotationY=l.environmentTextureRotationY),e.environmentTexture=_}else if("object"==typeof l.environmentTexture){var m=Nm.Parse(l.environmentTexture,e,i);e.environmentTexture=m}else if(l.environmentTexture.endsWith(".env")){var g=new Nm((l.environmentTexture.match(/https?:\/\//g)?"":i)+l.environmentTexture,e,l.environmentTextureForcedExtension);l.environmentTextureRotationY&&(g.rotationY=l.environmentTextureRotationY),e.environmentTexture=g}else{var v=Nm.CreateFromPrefilteredData((l.environmentTexture.match(/https?:\/\//g)?"":i)+l.environmentTexture,e,l.environmentTextureForcedExtension);l.environmentTextureRotationY&&(v.rotationY=l.environmentTextureRotationY),e.environmentTexture=v}if(!0===l.createDefaultSkybox){var y=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,b=l.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,p,y,b)}o.environmentTexture=e.environmentTexture}if(void 0!==l.environmentIntensity&&null!==l.environmentIntensity&&(e.environmentIntensity=l.environmentIntensity),void 0!==l.lights&&null!==l.lights)for(h=0,d=l.lights.length;h<d;h++){var T=l.lights[h];(oe=wa.Parse(T,e))&&(Xv[T.uniqueId]=oe,o.lights.push(oe),oe._parentContainer=o,a+=0===h?"\n\tLights:":"",a+="\n\t\t"+oe.toString(u))}if(void 0!==l.reflectionProbes&&null!==l.reflectionProbes)for(h=0,d=l.reflectionProbes.length;h<d;h++){var E=l.reflectionProbes[h],S=Uv.Parse(E,e,i);S&&(o.reflectionProbes.push(S),S._parentContainer=o,a+=0===h?"\n\tReflection Probes:":"",a+="\n\t\t"+S.toString(u))}if(void 0!==l.animations&&null!==l.animations)for(h=0,d=l.animations.length;h<d;h++){var x=l.animations[h],A=s("BABYLON.Animation");if(A){var C=A.Parse(x);e.animations.push(C),o.animations.push(C),a+=0===h?"\n\tAnimations:":"",a+="\n\t\t"+C.toString(u)}}if(void 0!==l.materials&&null!==l.materials)for(h=0,d=l.materials.length;h<d;h++){var R=l.materials[h],P=Ca.Parse(R,e,i);P&&(jv[R.uniqueId||R.id]=P,o.materials.push(P),P._parentContainer=o,a+=0===h?"\n\tMaterials:":"",a+="\n\t\t"+P.toString(u),P.getActiveTextures().forEach((function(e){-1==o.textures.indexOf(e)&&(o.textures.push(e),e._parentContainer=o)})))}if(void 0!==l.multiMaterials&&null!==l.multiMaterials)for(h=0,d=l.multiMaterials.length;h<d;h++){var I=l.multiMaterials[h],M=Ra.ParseMultiMaterial(I,e);jv[I.uniqueId||I.id]=M,o.multiMaterials.push(M),M._parentContainer=o,a+=0===h?"\n\tMultiMaterials:":"",a+="\n\t\t"+M.toString(u),M.getActiveTextures().forEach((function(e){-1==o.textures.indexOf(e)&&(o.textures.push(e),e._parentContainer=o)}))}if(void 0!==l.morphTargetManagers&&null!==l.morphTargetManagers)for(var O=0,D=l.morphTargetManagers;O<D.length;O++){var N=D[O],F=Ov.Parse(N,e);o.morphTargetManagers.push(F),F._parentContainer=o}if(void 0!==l.skeletons&&null!==l.skeletons)for(h=0,d=l.skeletons.length;h<d;h++){var L=l.skeletons[h],w=rs.Parse(L,e);o.skeletons.push(w),w._parentContainer=o,a+=0===h?"\n\tSkeletons:":"",a+="\n\t\t"+w.toString(u)}var B=l.geometries;if(null!=B){var U=new Array,V=B.vertexData;if(null!=V)for(h=0,d=V.length;h<d;h++){var k=V[h];U.push(vo.Parse(k,e,i))}U.forEach((function(e){e&&(o.geometries.push(e),e._parentContainer=o)}))}if(void 0!==l.transformNodes&&null!==l.transformNodes)for(h=0,d=l.transformNodes.length;h<d;h++){var G=l.transformNodes[h],z=Fo.Parse(G,e,i);Xv[G.uniqueId]=z,o.transformNodes.push(z),z._parentContainer=o}if(void 0!==l.meshes&&null!==l.meshes)for(h=0,d=l.meshes.length;h<d;h++){var W=l.meshes[h],H=Fa.Parse(W,e,i);if(Xv[W.uniqueId]=H,o.meshes.push(H),H._parentContainer=o,H.hasInstances)for(var X=0,j=H.instances;X<j.length;X++){var Y=j[X];o.meshes.push(Y),Y._parentContainer=o}a+=0===h?"\n\tMeshes:":"",a+="\n\t\t"+H.toString(u)}if(void 0!==l.cameras&&null!==l.cameras)for(h=0,d=l.cameras.length;h<d;h++){var K=l.cameras[h],Q=$n.Parse(K,e);Xv[K.uniqueId]=Q,o.cameras.push(Q),Q._parentContainer=o,a+=0===h?"\n\tCameras:":"",a+="\n\t\t"+Q.toString(u)}if(void 0!==l.postProcesses&&null!==l.postProcesses)for(h=0,d=l.postProcesses.length;h<d;h++){var q=l.postProcesses[h],Z=hl.Parse(q,e,i);Z&&(o.postProcesses.push(Z),Z._parentContainer=o,a+=0===h?"\nPostprocesses:":"",a+="\n\t\t"+Z.toString())}if(void 0!==l.animationGroups&&null!==l.animationGroups)for(h=0,d=l.animationGroups.length;h<d;h++){var J=l.animationGroups[h],$=zn.Parse(J,e);o.animationGroups.push($),$._parentContainer=o,a+=0===h?"\n\tAnimationGroups:":"",a+="\n\t\t"+$.toString(u)}if(l.spriteManagers)for(var ee=0,te=l.spriteManagers.length;ee<te;ee++){var ie=l.spriteManagers[ee];a+="\n\t\tSpriteManager "+zv.Parse(ie,e,i).name}for(h=0,d=e.cameras.length;h<d;h++)null!==(Q=e.cameras[h])._waitingParentId&&(Q.parent=qv(Q._waitingParentId,Q._waitingParentInstanceIndex,e),Q._waitingParentId=null,Q._waitingParentInstanceIndex=null);for(h=0,d=e.lights.length;h<d;h++)(oe=e.lights[h])&&null!==oe._waitingParentId&&(oe.parent=qv(oe._waitingParentId,oe._waitingParentInstanceIndex,e),oe._waitingParentId=null,oe._waitingParentInstanceIndex=null);for(h=0,d=e.transformNodes.length;h<d;h++){var re=e.transformNodes[h];null!==re._waitingParentId&&(re.parent=qv(re._waitingParentId,re._waitingParentInstanceIndex,e),re._waitingParentId=null,re._waitingParentInstanceIndex=null)}for(h=0,d=e.meshes.length;h<d;h++)null!==(H=e.meshes[h])._waitingParentId&&(H.parent=qv(H._waitingParentId,H._waitingParentInstanceIndex,e),H._waitingParentId=null,H._waitingParentInstanceIndex=null),H._waitingData.lods&&Qv(e,H);for(e.multiMaterials.forEach((function(t){t._waitingSubMaterialsUniqueIds.forEach((function(i){t.subMaterials.push(Zv(i,e))})),t._waitingSubMaterialsUniqueIds=[]})),e.meshes.forEach((function(t){null!==t._waitingMaterialId&&(t.material=Zv(t._waitingMaterialId,e),t._waitingMaterialId=null)})),h=0,d=e.skeletons.length;h<d;h++)(w=e.skeletons[h])._hasWaitingData&&(null!=w.bones&&w.bones.forEach((function(t){if(t._waitingTransformNodeId){var i=e.getLastEntryById(t._waitingTransformNodeId);i&&t.linkTransformNode(i),t._waitingTransformNodeId=null}})),w._hasWaitingData=null);for(h=0,d=e.meshes.length;h<d;h++){var ne=e.meshes[h];ne._waitingData.freezeWorldMatrix?(ne.freezeWorldMatrix(),ne._waitingData.freezeWorldMatrix=null):ne.computeWorldMatrix(!0)}for(h=0,d=e.lights.length;h<d;h++){var oe;if((oe=e.lights[h])._excludedMeshesIds.length>0){for(var se=0;se<oe._excludedMeshesIds.length;se++){var le=e.getMeshById(oe._excludedMeshesIds[se]);le&&oe.excludedMeshes.push(le)}oe._excludedMeshesIds=[]}if(oe._includedOnlyMeshesIds.length>0){for(var ce=0;ce<oe._includedOnlyMeshesIds.length;ce++){var ue=e.getMeshById(oe._includedOnlyMeshesIds[ce]);ue&&oe.includedOnlyMeshes.push(ue)}oe._includedOnlyMeshesIds=[]}}for(e.geometries.forEach((function(e){e._loadedUniqueId=""})),c.Parse(l,e,o,i),h=0,d=e.meshes.length;h<d;h++)(H=e.meshes[h])._waitingData.actions&&(be.Parse(H._waitingData.actions,H,e),H._waitingData.actions=null);void 0!==l.actions&&null!==l.actions&&be.Parse(l.actions,null,e)}catch(e){var he=Kv("loadAssets",l?l.producer:"Unknown")+a;if(!r)throw ae.Log(he),e;r(he,e)}finally{Xv={},jv={},n||o.removeAllFromScene(),null!==a&&Ls.loggingLevel!==Ls.NO_LOGGING&&ae.Log(Kv("loadAssets",l?l.producer:"Unknown")+(Ls.loggingLevel!==Ls.MINIMAL_LOGGING?a:""))}return o};Ls.RegisterPlugin({name:"babylon.js",extensions:".babylon",canDirectLoad:function(e){return-1!==e.indexOf("babylon")},importMesh:function(e,t,i,r,n,o,a,s){var l,u="importMesh has failed JSON parse";try{var h=JSON.parse(i);u="";var d=Ls.loggingLevel===Ls.DETAILED_LOGGING;e?Array.isArray(e)||(e=[e]):e=null;var p=[],f=new Map,_=[];if(void 0!==h.transformNodes&&null!==h.transformNodes)for(var m=0,g=h.transformNodes.length;m<g;m++){var v=h.transformNodes[m],y=Fo.Parse(v,t,r);_.push(y),f.set(y._waitingParsedUniqueId,y),y._waitingParsedUniqueId=null}if(void 0!==h.meshes&&null!==h.meshes){var b=[],T=[],E=[],S=[],x=function(i,o){var s=h.meshes[i];if(null===e||function(e,t,i){for(var r in t)if(e.name===t[r])return i.push(e.id),!0;return void 0!==e.parentId&&-1!==i.indexOf(e.parentId)&&(i.push(e.id),!0)}(s,e,p)){if(null!==e&&delete e[e.indexOf(s.name)],void 0!==s.geometryId&&null!==s.geometryId&&void 0!==h.geometries&&null!==h.geometries){var l=!1;["boxes","spheres","cylinders","toruses","grounds","planes","torusKnots","vertexData"].forEach((function(e){!0!==l&&h.geometries[e]&&Array.isArray(h.geometries[e])&&h.geometries[e].forEach((function(i){i.id===s.geometryId&&("vertexData"===e&&vo.Parse(i,t,r),l=!0)}))})),!1===l&&ae.Warn("Geometry not found for mesh "+s.id)}if(s.materialUniqueId||s.materialId){var c=s.materialUniqueId?E:T,_=-1!==c.indexOf(s.materialUniqueId||s.materialId);if(!1===_&&void 0!==h.multiMaterials&&null!==h.multiMaterials)for(var m=function(e,i){c.push(e);var n=Yv(i,h,t,r);n&&n.material&&(jv[n.parsedMaterial.uniqueId||n.parsedMaterial.id]=n.material,u+="\n\tMaterial "+n.material.toString(d))},g=0,v=h.multiMaterials.length;g<v;g++){var y=h.multiMaterials[g];if(s.materialUniqueId&&y.uniqueId===s.materialUniqueId||y.id===s.materialId){y.materialsUniqueIds?y.materialsUniqueIds.forEach((function(e){return m(e,(function(t){return t.uniqueId===e}))})):y.materials.forEach((function(e){return m(e,(function(t){return t.id===e}))})),c.push(y.uniqueId||y.id);var x=Ra.ParseMultiMaterial(y,t);jv[y.uniqueId||y.id]=x,x&&(_=!0,u+="\n\tMulti-Material "+x.toString(d));break}}if(!1===_){c.push(s.materialUniqueId||s.materialId);var A=Yv((function(e){return s.materialUniqueId&&e.uniqueId===s.materialUniqueId||e.id===s.materialId}),h,t,r);A&&A.material?(jv[A.parsedMaterial.uniqueId||A.parsedMaterial.id]=A.material,u+="\n\tMaterial "+A.material.toString(d)):ae.Warn("Material not found for mesh "+s.id)}}if(null!==s.skeletonId&&void 0!==s.skeletonId&&-1!==h.skeletonId&&void 0!==h.skeletons&&null!==h.skeletons&&!(b.indexOf(s.skeletonId)>-1))for(var C=0,R=h.skeletons.length;C<R;C++){var P=h.skeletons[C];if(P.id===s.skeletonId){var I=rs.Parse(P,t);a.push(I),b.push(P.id),u+="\n\tSkeleton "+I.toString(d)}}if(s.morphTargetManagerId>-1&&void 0!==h.morphTargetManagers&&null!==h.morphTargetManagers&&!(S.indexOf(s.morphTargetManagerId)>-1))for(var M=0,O=h.morphTargetManagers.length;M<O;M++){var D=h.morphTargetManagers[M];if(D.id===s.morphTargetManagerId){var N=Ov.Parse(D,t);S.push(N.uniqueId),u+="\nMorph target "+N.toString()}}var F=Fa.Parse(s,t,r);n.push(F),f.set(F._waitingParsedUniqueId,F),F._waitingParsedUniqueId=null,u+="\n\tMesh "+F.toString(d)}};for(m=0,g=h.meshes.length;m<g;m++)x(m);for(t.multiMaterials.forEach((function(e){e._waitingSubMaterialsUniqueIds.forEach((function(i){e.subMaterials.push(Zv(i,t))})),e._waitingSubMaterialsUniqueIds=[]})),t.meshes.forEach((function(e){null!==e._waitingMaterialId&&(e.material=Zv(e._waitingMaterialId,t),e._waitingMaterialId=null)})),m=0,g=t.transformNodes.length;m<g;m++)if(null!==(D=t.transformNodes[m])._waitingParentId){var A=f.get(parseInt(D._waitingParentId))||null;null===A&&(A=t.getLastEntryById(D._waitingParentId));var C=A;D._waitingParentInstanceIndex&&(C=A.instances[parseInt(D._waitingParentInstanceIndex)],D._waitingParentInstanceIndex=null),D.parent=C,D._waitingParentId=null}var R=void 0;for(m=0,g=t.meshes.length;m<g;m++){if((R=t.meshes[m])._waitingParentId){var P=f.get(parseInt(R._waitingParentId))||null;if(null===P&&(P=t.getLastEntryById(R._waitingParentId)),C=P,R._waitingParentInstanceIndex&&(C=P.instances[parseInt(R._waitingParentInstanceIndex)],R._waitingParentInstanceIndex=null),R.parent=C,"TransformNode"===(null===(l=R.parent)||void 0===l?void 0:l.getClassName())){var I=_.indexOf(R.parent);I>-1&&_.splice(I,1)}R._waitingParentId=null}R._waitingData.lods&&Qv(t,R)}for(var M=0,O=_;M<O.length;M++){var D;(D=O[M]).dispose()}for(m=0,g=t.skeletons.length;m<g;m++){var N=t.skeletons[m];N._hasWaitingData&&(null!=N.bones&&N.bones.forEach((function(e){if(e._waitingTransformNodeId){var i=t.getLastEntryById(e._waitingTransformNodeId);i&&e.linkTransformNode(i),e._waitingTransformNodeId=null}})),N._hasWaitingData=null)}for(m=0,g=t.meshes.length;m<g;m++)(R=t.meshes[m])._waitingData.freezeWorldMatrix?(R.freezeWorldMatrix(),R._waitingData.freezeWorldMatrix=null):R.computeWorldMatrix(!0)}if(void 0!==h.particleSystems&&null!==h.particleSystems){var F=c.GetIndividualParser(Vr.NAME_PARTICLESYSTEM);if(F)for(m=0,g=h.particleSystems.length;m<g;m++){var L=h.particleSystems[m];-1!==p.indexOf(L.emitterId)&&o.push(F(L,t,r))}}return t.geometries.forEach((function(e){e._loadedUniqueId=""})),!0}catch(e){var w=Kv("importMesh",h?h.producer:"Unknown")+u;if(!s)throw ae.Log(w),e;s(w,e)}finally{null!==u&&Ls.loggingLevel!==Ls.NO_LOGGING&&ae.Log(Kv("importMesh",h?h.producer:"Unknown")+(Ls.loggingLevel!==Ls.MINIMAL_LOGGING?u:"")),jv={}}return!1},load:function(e,t,i,r){var n="importScene has failed JSON parse";try{var o=JSON.parse(t);switch(n="",void 0!==o.useDelayedTextureLoading&&null!==o.useDelayedTextureLoading&&(e.useDelayedTextureLoading=o.useDelayedTextureLoading&&!Ls.ForceFullSceneLoadingForIncremental),void 0!==o.autoClear&&null!==o.autoClear&&(e.autoClear=o.autoClear),void 0!==o.clearColor&&null!==o.clearColor&&(e.clearColor=J.FromArray(o.clearColor)),void 0!==o.ambientColor&&null!==o.ambientColor&&(e.ambientColor=Z.FromArray(o.ambientColor)),void 0!==o.gravity&&null!==o.gravity&&(e.gravity=V.FromArray(o.gravity)),void 0!==o.useRightHandedSystem&&(e.useRightHandedSystem=!!o.useRightHandedSystem),void 0!==o.fogMode&&null!==o.fogMode&&(e.fogMode=o.fogMode),void 0!==o.fogColor&&null!==o.fogColor&&(e.fogColor=Z.FromArray(o.fogColor)),void 0!==o.fogStart&&null!==o.fogStart&&(e.fogStart=o.fogStart),void 0!==o.fogEnd&&null!==o.fogEnd&&(e.fogEnd=o.fogEnd),void 0!==o.fogDensity&&null!==o.fogDensity&&(e.fogDensity=o.fogDensity),n+="\tFog mode for scene: ",e.fogMode){case 0:n+="none\n";break;case 1:n+="exp\n";break;case 2:n+="exp2\n";break;case 3:n+="linear\n"}if(o.physicsEnabled){var a=void 0;"cannon"===o.physicsEngine||o.physicsEngine===Lv.name?a=new Lv(void 0,void 0,Hv.LoaderInjectedPhysicsEngine):"oimo"===o.physicsEngine||o.physicsEngine===wv.name?a=new wv(void 0,Hv.LoaderInjectedPhysicsEngine):"ammo"!==o.physicsEngine&&o.physicsEngine!==Bv.name||(a=new Bv(void 0,Hv.LoaderInjectedPhysicsEngine,void 0)),n="\tPhysics engine "+(o.physicsEngine?o.physicsEngine:"oimo")+" enabled\n";var s=o.physicsGravity?V.FromArray(o.physicsGravity):null;e.enablePhysics(s,a)}return void 0!==o.metadata&&null!==o.metadata&&(e.metadata=o.metadata),void 0!==o.collisionsEnabled&&null!==o.collisionsEnabled&&(e.collisionsEnabled=o.collisionsEnabled),!!Jv(e,t,i,r,!0)&&(o.autoAnimate&&e.beginAnimation(e,o.autoAnimateFrom,o.autoAnimateTo,o.autoAnimateLoop,o.autoAnimateSpeed||1),void 0!==o.activeCameraID&&null!==o.activeCameraID&&e.setActiveCameraById(o.activeCameraID),!0)}catch(e){var l=Kv("importScene",o?o.producer:"Unknown")+n;if(!r)throw ae.Log(l),e;r(l,e)}finally{null!==n&&Ls.loggingLevel!==Ls.NO_LOGGING&&ae.Log(Kv("importScene",o?o.producer:"Unknown")+(Ls.loggingLevel!==Ls.MINIMAL_LOGGING?n:""))}return!1},loadAssetContainer:function(e,t,i,r){return Jv(e,t,i,r)}});var $v=function(){function e(e){void 0===e&&(e={}),this._isEnabled=!0,this.bias=void 0===e.bias?0:e.bias,this.power=void 0===e.power?1:e.power,this.leftColor=e.leftColor||Z.White(),this.rightColor=e.rightColor||Z.Black(),!1===e.isEnabled&&(this.isEnabled=!1)}return Object.defineProperty(e.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled!==e&&(this._isEnabled=e,Do.MarkAllMaterialsAsDirty(u.MATERIAL_FresnelDirtyFlag|u.MATERIAL_MiscDirtyFlag))},enumerable:!1,configurable:!0}),e.prototype.clone=function(){var t=new e;return ye.DeepCopy(this,t),t},e.prototype.equals=function(e){return e&&this.bias===e.bias&&this.power===e.power&&this.leftColor.equals(e.leftColor)&&this.rightColor.equals(e.rightColor)&&this.isEnabled===e.isEnabled},e.prototype.serialize=function(){return{isEnabled:this.isEnabled,leftColor:this.leftColor.asArray(),rightColor:this.rightColor.asArray(),bias:this.bias,power:this.power}},e.Parse=function(t){return new e({isEnabled:t.isEnabled,leftColor:Z.FromArray(t.leftColor),rightColor:Z.FromArray(t.rightColor),bias:t.bias,power:t.power||1})},e}();Ke._FresnelParametersParser=$v.Parse;var ey=function(){function e(){}return e.BindSceneUniformBuffer=ea,e.PrepareDefinesForMergedUV=ta,e.BindTextureMatrix=ia,e.GetFogState=ha,e.PrepareDefinesForMisc=da,e.PrepareDefinesForCamera=Sa,e.PrepareDefinesForFrameBoundValues=_a,e.PrepareDefinesForBones=ma,e.PrepareDefinesForMorphTargets=ga,e.PrepareDefinesForBakedVertexAnimation=va,e.PrepareDefinesForAttributes=ya,e.PrepareDefinesForMultiview=ba,e.PrepareDefinesForOIT=Ta,e.PrepareDefinesForPrePass=Ea,e.PrepareDefinesForLight=fa,e.PrepareDefinesForLights=pa,e.PrepareUniformsAndSamplersForLight=xa,e.PrepareUniformsAndSamplersList=Aa,e.HandleFallbacksForShadows=ua,e.PrepareAttributesForMorphTargetsInfluencers=qo,e.PrepareAttributesForMorphTargets=Zo,e.PrepareAttributesForBakedVertexAnimation=ra,e.PrepareAttributesForBones=la,e.PrepareAttributesForInstances=ca,e.PushAttributesForInstances=Jo,e.BindLightProperties=oa,e.BindLight=aa,e.BindLights=sa,e.BindFogParameters=Qo,e.BindBonesParameters=na,e.BindMorphTargetParameters=$o,e.BindLogDepth=Ko,e}(),ty=function(e){function t(t,i){var r=e.call(this,t,i,"color",{attributes:["position"],uniforms:["world","viewProjection","color"]})||this;return r.disableColorWrite=!0,r.forceDepthWrite=!0,r.setColor4("color",new J(0,0,0,1)),r}return m(t,e),t}(ld),iy=function(e){function t(t,i){var r=e.call(this,t,i)||this;return r.maxSimultaneousLights=4,r.disableLighting=!1,r.invertNormalMapX=!1,r.invertNormalMapY=!1,r.emissiveColor=new Z(0,0,0),r.occlusionStrength=1,r.useLightmapAsShadowmap=!1,r._useAlphaFromAlbedoTexture=!0,r._useAmbientInGrayScale=!0,r}return m(t,e),Object.defineProperty(t.prototype,"doubleSided",{get:function(){return this._twoSidedLighting},set:function(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"PBRBaseSimpleMaterial"},v([Ie(),Pe("_markAllSubMeshesAsLightsDirty")],t.prototype,"maxSimultaneousLights",void 0),v([Ie(),Pe("_markAllSubMeshesAsLightsDirty")],t.prototype,"disableLighting",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],t.prototype,"environmentTexture",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"invertNormalMapX",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"invertNormalMapY",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],t.prototype,"normalTexture",void 0),v([Oe("emissive"),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"emissiveColor",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"emissiveTexture",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],t.prototype,"occlusionStrength",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],t.prototype,"occlusionTexture",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],t.prototype,"alphaCutOff",void 0),v([Ie()],t.prototype,"doubleSided",null),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty",null)],t.prototype,"lightmapTexture",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useLightmapAsShadowmap",void 0),t}(ig),ry=function(e){function t(t,i){var r=e.call(this,t,i)||this;return r._useRoughnessFromMetallicTextureAlpha=!1,r._useRoughnessFromMetallicTextureGreen=!0,r._useMetallnessFromMetallicTextureBlue=!0,r.metallic=1,r.roughness=1,r}return m(t,e),t.prototype.getClassName=function(){return"PBRMetallicRoughnessMaterial"},t.prototype.clone=function(e){var i=this,r=Ke.Clone((function(){return new t(e,i.getScene())}),this);return r.id=e,r.name=e,this.clearCoat.copyTo(r.clearCoat),this.anisotropy.copyTo(r.anisotropy),this.brdf.copyTo(r.brdf),this.sheen.copyTo(r.sheen),this.subSurface.copyTo(r.subSurface),r},t.prototype.serialize=function(){var e=Ke.Serialize(this);return e.customType="BABYLON.PBRMetallicRoughnessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e},t.Parse=function(e,i,r){var n=Ke.Parse((function(){return new t(e.name,i)}),e,i,r);return e.clearCoat&&n.clearCoat.parse(e.clearCoat,i,r),e.anisotropy&&n.anisotropy.parse(e.anisotropy,i,r),e.brdf&&n.brdf.parse(e.brdf,i,r),e.sheen&&n.sheen.parse(e.sheen,i,r),e.subSurface&&n.subSurface.parse(e.subSurface,i,r),e.iridescence&&n.iridescence.parse(e.iridescence,i,r),n},v([Oe(),Pe("_markAllSubMeshesAsTexturesDirty","_albedoColor")],t.prototype,"baseColor",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],t.prototype,"baseTexture",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"metallic",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"roughness",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],t.prototype,"metallicRoughnessTexture",void 0),t}(iy);a("BABYLON.PBRMetallicRoughnessMaterial",ry);var ny=function(e){function t(t,i){var r=e.call(this,t,i)||this;return r._useMicroSurfaceFromReflectivityMapAlpha=!0,r}return m(t,e),Object.defineProperty(t.prototype,"useMicroSurfaceFromReflectivityMapAlpha",{get:function(){return this._useMicroSurfaceFromReflectivityMapAlpha},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"PBRSpecularGlossinessMaterial"},t.prototype.clone=function(e){var i=this,r=Ke.Clone((function(){return new t(e,i.getScene())}),this);return r.id=e,r.name=e,this.clearCoat.copyTo(r.clearCoat),this.anisotropy.copyTo(r.anisotropy),this.brdf.copyTo(r.brdf),this.sheen.copyTo(r.sheen),this.subSurface.copyTo(r.subSurface),r},t.prototype.serialize=function(){var e=Ke.Serialize(this);return e.customType="BABYLON.PBRSpecularGlossinessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e},t.Parse=function(e,i,r){var n=Ke.Parse((function(){return new t(e.name,i)}),e,i,r);return e.clearCoat&&n.clearCoat.parse(e.clearCoat,i,r),e.anisotropy&&n.anisotropy.parse(e.anisotropy,i,r),e.brdf&&n.brdf.parse(e.brdf,i,r),e.sheen&&n.sheen.parse(e.sheen,i,r),e.subSurface&&n.subSurface.parse(e.subSurface,i,r),e.iridescence&&n.iridescence.parse(e.iridescence,i,r),n},v([Oe("diffuse"),Pe("_markAllSubMeshesAsTexturesDirty","_albedoColor")],t.prototype,"diffuseColor",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],t.prototype,"diffuseTexture",void 0),v([Oe("specular"),Pe("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],t.prototype,"specularColor",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty","_microSurface")],t.prototype,"glossiness",void 0),v([Me(),Pe("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],t.prototype,"specularGlossinessTexture",void 0),t}(iy);a("BABYLON.PBRSpecularGlossinessMaterial",ny);var oy=function(e){function t(t,i,r){void 0===r&&(r=null);var n=e.call(this,i)||this;if(!t)return n;if(n._textureMatrix=z.Identity(),n.name=t,n.url=t,n._onLoad=r,n._texture=n._getFromCache(t,!0),n._texture)n._triggerOnLoad();else{var o=n.getScene();o&&o.useDelayedTextureLoading?n.delayLoadState=u.DELAYLOADSTATE_NOTLOADED:n._loadTexture()}return n}return m(t,e),t.prototype._triggerOnLoad=function(){this._onLoad&&this._onLoad()},t.prototype.getTextureMatrix=function(){return this._textureMatrix},t.prototype._load3dlTexture=function(){var e,i=this,r=this._getEngine();e=r._features.support3DTextures?r.createRawTexture3D(null,1,1,1,u.TEXTUREFORMAT_RGBA,!1,!1,u.TEXTURE_BILINEAR_SAMPLINGMODE,null,u.TEXTURETYPE_UNSIGNED_INT):r.createRawTexture(null,1,1,u.TEXTUREFORMAT_RGBA,!1,!1,u.TEXTURE_BILINEAR_SAMPLINGMODE,null,u.TEXTURETYPE_UNSIGNED_INT),this._texture=e,this._texture.isReady=!1,this.isCube=!1,this.is3D=r._features.support3DTextures,this.wrapU=u.TEXTURE_CLAMP_ADDRESSMODE,this.wrapV=u.TEXTURE_CLAMP_ADDRESSMODE,this.wrapR=u.TEXTURE_CLAMP_ADDRESSMODE,this.anisotropicFilteringLevel=1;var n=function(n){if("string"==typeof n){for(var o,a=null,s=null,l=n.split("\n"),c=0,h=0,d=0,p=0,f=0,_=0;_<l.length;_++)if(o=l[_],t._NoneEmptyLineRegex.test(o)&&0!==o.indexOf("#")){var m=o.split(" ");if(0!==c){if(0!=c){var g=Math.max(parseInt(m[0]),0),v=Math.max(parseInt(m[1]),0),y=Math.max(parseInt(m[2]),0);f=Math.max(g,f),f=Math.max(v,f),f=Math.max(y,f);var b=4*(h+p*c+d*c*c);s&&(s[b+0]=g,s[b+1]=v,s[b+2]=y),++d%c==0&&(d=0,++p%c==0&&(h++,p=0))}}else c=m.length,a=new Uint8Array(c*c*c*4),s=new Float32Array(c*c*c*4)}if(s&&a)for(_=0;_<s.length;_++)if(_>0&&(_+1)%4==0)a[_]=255;else{var T=s[_];a[_]=T/f*255}e.is3D?(e.updateSize(c,c,c),r.updateRawTexture3D(e,a,u.TEXTUREFORMAT_RGBA,!1)):(e.updateSize(c*c,c),r.updateRawTexture(e,a,u.TEXTUREFORMAT_RGBA,!1)),e.isReady=!0,i._triggerOnLoad()}},o=this.getScene();return o?o._loadFile(this.url,n):r._loadFile(this.url,n),this._texture},t.prototype._loadTexture=function(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this._load3dlTexture()},t.prototype.clone=function(){var e=new t(this.url,this.getScene()||this._getEngine());return e.level=this.level,e},t.prototype.delayLoad=function(){this.delayLoadState===u.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=u.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,!0),this._texture||this._loadTexture())},t.Parse=function(e,i){var r=null;return e.name&&!e.isRenderTarget&&((r=new t(e.name,i)).name=e.name,r.level=e.level),r},t.prototype.serialize=function(){if(!this.name)return null;var e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e},t._NoneEmptyLineRegex=/\S+/,t}(Ya);a("BABYLON.ColorGradingTexture",oy);var ay=function(e){function t(t,i,r,n,o,a,s,l){void 0===n&&(n=!1),void 0===o&&(o=!0),void 0===a&&(a=null),void 0===s&&(s=null),void 0===l&&(l=!1);var c=e.call(this,i)||this;if(c._onLoad=null,c._onError=null,!t)throw new Error("Image url is not set");return c._coordinatesMode=Ja.CUBIC_MODE,c.name=t,c.url=t,c._size=r,c._supersample=l,c._noMipmap=n,c.gammaSpace=o,c._onLoad=a,c._onError=s,c.hasAlpha=!1,c.isCube=!0,c._texture=c._getFromCache(t,c._noMipmap,void 0,void 0,void 0,c.isCube),c._texture?a&&(c._texture.isReady?rr.SetImmediate((function(){return a()})):c._texture.onLoadedObservable.add(a)):i.useDelayedTextureLoading?c.delayLoadState=u.DELAYLOADSTATE_NOTLOADED:c._loadImage((function(){return c._loadTexture()}),c._onError),c}return m(t,e),t.prototype._loadImage=function(e,t){var i=this,r=this.getScene();if(r){var n=r.getEngine().createRawCubeTexture(null,this._size,u.TEXTUREFORMAT_RGB,r.getEngine().getCaps().textureFloat?u.TEXTURETYPE_FLOAT:u.TEXTURETYPE_UNSIGNED_INTEGER,!this._noMipmap,!1,u.TEXTURE_TRILINEAR_SAMPLINGMODE);n.generateMipMaps=!this._noMipmap,r.addPendingData(n),n.url=this.url,n.isReady=!1,r.getEngine()._internalTexturesCache.push(n),this._texture=n;var o=document.createElement("canvas");Bi(this.url,(function(t){i._width=t.width,i._height=t.height,o.width=i._width,o.height=i._height;var r=o.getContext("2d");r.drawImage(t,0,0);var n=r.getImageData(0,0,t.width,t.height);i._buffer=n.data.buffer,o.remove(),e()}),(function(e,o){r.removePendingData(n),t&&t("".concat(i.getClassName()," could not be loaded"),o)}),r?r.offlineProvider:null)}},t.prototype._loadTexture=function(){var e=this,i=this.getScene();if(i){var r=function(){for(var i=e._getFloat32ArrayFromArrayBuffer(e._buffer),r=Av.ConvertPanoramaToCubemap(i,e._width,e._height,e._size,e._supersample),n=[],o=0;o<6;o++){var a=r[t._FacesMapping[o]];n.push(a)}return n}(),n=this._texture;i.getEngine().updateRawCubeTexture(n,r,n.format,n.type,n.invertY),n.isReady=!0,i.removePendingData(n),n.onLoadedObservable.notifyObservers(n),n.onLoadedObservable.clear(),this._onLoad&&this._onLoad()}},t.prototype._getFloat32ArrayFromArrayBuffer=function(e){for(var t=new DataView(e),i=new Float32Array(3*e.byteLength/4),r=0,n=0;n<e.byteLength;n++)(n+1)%4!=0&&(i[r++]=t.getUint8(n)/255);return i},t.prototype.getClassName=function(){return"EquiRectangularCubeTexture"},t.prototype.clone=function(){var e=this.getScene();if(!e)return this;var i=new t(this.url,e,this._size,this._noMipmap,this.gammaSpace);return i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i.coordinatesIndex=this.coordinatesIndex,i.coordinatesMode=this.coordinatesMode,i},t._FacesMapping=["right","left","up","down","front","back"],t}(Ya),sy=function(e){function t(i,r,n){var o=e.call(this,n.scene||n.engine)||this;if(o.onLoadObservable=new f,!r||!n.engine&&!n.scene)return o;if(n=g(g({},t._DefaultOptions),n),o._generateMipMaps=n.generateMipMaps,o._samplingMode=n.samplingMode,o._textureMatrix=z.Identity(),o._format=n.format,o.name=i,o.element=r,o._isVideo=!!r.getVideoPlaybackQuality,o._isVideo){var a=o._engine,s=null==a?void 0:a.createExternalTexture;s&&(o._externalTexture=s.call(a,r))}return o.anisotropicFilteringLevel=1,o._createInternalTexture(),o}return m(t,e),t.prototype._createInternalTexture=function(){var e=0,t=0;this._isVideo?(e=this.element.videoWidth,t=this.element.videoHeight):(e=this.element.width,t=this.element.height);var i=this._getEngine();i&&(this._texture=i.createDynamicTexture(e,t,this._generateMipMaps,this._samplingMode),this._texture.format=this._format),this.update()},t.prototype.getTextureMatrix=function(){return this._textureMatrix},t.prototype.update=function(e){void 0===e&&(e=null);var t=this._getEngine();if(null!=this._texture&&null!=t){var i=this.isReady();if(this._isVideo){var r=this.element;if(r.readyState<r.HAVE_CURRENT_DATA)return;t.updateVideoTexture(this._texture,this._externalTexture?this._externalTexture:r,null===e||e)}else{var n=this.element;t.updateDynamicTexture(this._texture,n,null===e||e,!1,this._format)}!i&&this.isReady()&&this.onLoadObservable.notifyObservers(this)}},t.prototype.dispose=function(){this.onLoadObservable.clear(),e.prototype.dispose.call(this)},t._DefaultOptions={generateMipMaps:!1,samplingMode:u.TEXTURE_BILINEAR_SAMPLINGMODE,format:u.TEXTUREFORMAT_RGBA,engine:null,scene:null},t}(Ya),ly=1,cy=2,uy=3,hy=9,dy=10,py=11,fy=48,_y=4,my=0,gy=1,vy=2,yy=3;function by(e){var t=0;return{id_length:e[t++],colormap_type:e[t++],image_type:e[t++],colormap_index:e[t++]|e[t++]<<8,colormap_length:e[t++]|e[t++]<<8,colormap_size:e[t++],origin:[e[t++]|e[t++]<<8,e[t++]|e[t++]<<8],width:e[t++]|e[t++]<<8,height:e[t++]|e[t++]<<8,pixel_size:e[t++],flags:e[t++]}}function Ty(e,t){if(t.length<19)ae.Error("Unable to load TGA file - Not enough data to contain header");else{var i=18,r=by(t);if(r.id_length+i>t.length)ae.Error("Unable to load TGA file - Not enough data");else{i+=r.id_length;var n,o=!1,a=!1,s=!1;switch(r.image_type){case hy:o=!0;case ly:a=!0;break;case dy:o=!0;case cy:break;case py:o=!0;case uy:s=!0}var l,c,u,h,d,p,f,_=r.pixel_size>>3,m=r.width*r.height*_;if(a&&(l=t.subarray(i,i+=r.colormap_length*(r.colormap_size>>3))),o){n=new Uint8Array(m);for(var g=void 0,v=void 0,y=void 0,b=0,T=new Uint8Array(_);i<m&&b<m;)if(v=1+(127&(g=t[i++])),128&g){for(y=0;y<_;++y)T[y]=t[i++];for(y=0;y<v;++y)n.set(T,b+y*_);b+=_*v}else{for(v*=_,y=0;y<v;++y)n[b+y]=t[i++];b+=v}}else n=t.subarray(i,i+=a?r.width*r.height:m);switch((r.flags&fy)>>_y){default:case vy:c=0,h=1,f=r.width,u=0,d=1,p=r.height;break;case my:c=0,h=1,f=r.width,u=r.height-1,d=-1,p=-1;break;case yy:c=r.width-1,h=-1,f=-1,u=0,d=1,p=r.height;break;case gy:c=r.width-1,h=-1,f=-1,u=r.height-1,d=-1,p=-1}var E="_getImageData"+(s?"Grey":"")+r.pixel_size+"bits",S=Ey[E](r,l,n,u,d,p,c,h,f);e.getEngine()._uploadDataToTextureDirectly(e,S)}}}var Ey={GetTGAHeader:by,UploadContent:Ty,_getImageData8bits:function(e,t,i,r,n,o,a,s,l){var c,u,h,d=i,p=t,f=e.width,_=e.height,m=0,g=new Uint8Array(f*_*4);for(h=r;h!==o;h+=n)for(u=a;u!==l;u+=s,m++)c=d[m],g[4*(u+f*h)+3]=255,g[4*(u+f*h)+2]=p[3*c+0],g[4*(u+f*h)+1]=p[3*c+1],g[4*(u+f*h)+0]=p[3*c+2];return g},_getImageData16bits:function(e,t,i,r,n,o,a,s,l){var c,u,h,d=i,p=e.width,f=e.height,_=0,m=new Uint8Array(p*f*4);for(h=r;h!==o;h+=n)for(u=a;u!==l;u+=s,_+=2){var g=255*((31744&(c=d[_+0]+(d[_+1]<<8)))>>10)/31|0,v=255*((992&c)>>5)/31|0,y=255*(31&c)/31|0;m[4*(u+p*h)+0]=g,m[4*(u+p*h)+1]=v,m[4*(u+p*h)+2]=y,m[4*(u+p*h)+3]=32768&c?0:255}return m},_getImageData24bits:function(e,t,i,r,n,o,a,s,l){var c,u,h=i,d=e.width,p=e.height,f=0,_=new Uint8Array(d*p*4);for(u=r;u!==o;u+=n)for(c=a;c!==l;c+=s,f+=3)_[4*(c+d*u)+3]=255,_[4*(c+d*u)+2]=h[f+0],_[4*(c+d*u)+1]=h[f+1],_[4*(c+d*u)+0]=h[f+2];return _},_getImageData32bits:function(e,t,i,r,n,o,a,s,l){var c,u,h=i,d=e.width,p=e.height,f=0,_=new Uint8Array(d*p*4);for(u=r;u!==o;u+=n)for(c=a;c!==l;c+=s,f+=4)_[4*(c+d*u)+2]=h[f+0],_[4*(c+d*u)+1]=h[f+1],_[4*(c+d*u)+0]=h[f+2],_[4*(c+d*u)+3]=h[f+3];return _},_getImageDataGrey8bits:function(e,t,i,r,n,o,a,s,l){var c,u,h,d=i,p=e.width,f=e.height,_=0,m=new Uint8Array(p*f*4);for(h=r;h!==o;h+=n)for(u=a;u!==l;u+=s,_++)c=d[_],m[4*(u+p*h)+0]=c,m[4*(u+p*h)+1]=c,m[4*(u+p*h)+2]=c,m[4*(u+p*h)+3]=255;return m},_getImageDataGrey16bits:function(e,t,i,r,n,o,a,s,l){var c,u,h=i,d=e.width,p=e.height,f=0,_=new Uint8Array(d*p*4);for(u=r;u!==o;u+=n)for(c=a;c!==l;c+=s,f+=2)_[4*(c+d*u)+0]=h[f+0],_[4*(c+d*u)+1]=h[f+0],_[4*(c+d*u)+2]=h[f+0],_[4*(c+d*u)+3]=h[f+1];return _}},Sy=function(){function e(){this.supportCascades=!1}return e.prototype.canLoad=function(e){return e.endsWith(".tga")},e.prototype.loadCubeData=function(){throw".env not supported in Cube."},e.prototype.loadData=function(e,t,i){var r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=by(r);i(n.width,n.height,t.generateMipMaps,!1,(function(){Ty(t,r)}))},e}();Do._TextureLoaders.push(new Sy);var xy=function(){function e(){this.supportCascades=!1}return e.prototype.canLoad=function(e){return e.endsWith(".hdr")},e.prototype.loadCubeData=function(){throw".env not supported in Cube."},e.prototype.loadData=function(e,t,i){for(var r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=Cv.RGBE_ReadHeader(r),o=Cv.RGBE_ReadPixels(r,n),a=n.width*n.height,s=new Float32Array(4*a),l=0;l<a;l+=1)s[4*l]=o[3*l],s[4*l+1]=o[3*l+1],s[4*l+2]=o[3*l+2],s[4*l+3]=1;i(n.width,n.height,t.generateMipMaps,!1,(function(){var e=t.getEngine();t.type=u.TEXTURETYPE_FLOAT,t.format=u.TEXTUREFORMAT_RGBA,t._gammaSpace=!1,e._uploadDataToTextureDirectly(t,s)}))},e}();function Ay(){var e=null;function t(e,t,i,r,n){var o=e.getImageTranscodedSizeInBytes(t,i,r),a=new Uint8Array(o);return e.transcodeImage(a,t,i,r,1,0)?(n&&(a=function(e,t,i,r){for(var n=new Uint16Array(4),o=new Uint16Array(i*r),a=i/4,s=r/4,l=0;l<s;l++)for(var c=0;c<a;c++){var u=0+8*(l*a+c);n[0]=e[u]|e[u+1]<<8,n[1]=e[u+2]|e[u+3]<<8,n[2]=(2*(31&n[0])+1*(31&n[1]))/3|(2*(2016&n[0])+1*(2016&n[1]))/3&2016|(2*(63488&n[0])+1*(63488&n[1]))/3&63488,n[3]=(2*(31&n[1])+1*(31&n[0]))/3|(2*(2016&n[1])+1*(2016&n[0]))/3&2016|(2*(63488&n[1])+1*(63488&n[0]))/3&63488;for(var h=0;h<4;h++){var d=e[u+4+h],p=(4*l+h)*i+4*c;o[p++]=n[3&d],o[p++]=n[d>>2&3],o[p++]=n[d>>4&3],o[p++]=n[d>>6&3]}}return o}(a,0,e.getImageWidth(t,i)+3&-4,e.getImageHeight(t,i)+3&-4)),a):null}onmessage=function(i){if("init"===i.data.action){if(i.data.url)try{importScripts(i.data.url)}catch(e){postMessage({action:"error",error:e})}e||(e=BASIS({wasmBinary:i.data.wasmBinary})),null!==e&&e.then((function(e){BASIS=e,e.initializeBasis(),postMessage({action:"init"})}))}else if("transcode"===i.data.action){var r=i.data.config,n=i.data.imageData,o=new BASIS.BasisFile(n),a=function(e){for(var t=e.getHasAlpha(),i=e.getNumImages(),r=[],n=0;n<i;n++){for(var o={levels:[]},a=e.getNumLevels(n),s=0;s<a;s++){var l={width:e.getImageWidth(n,s),height:e.getImageHeight(n,s)};o.levels.push(l)}r.push(o)}return{hasAlpha:t,images:r}}(o),s=i.data.ignoreSupportedFormats?null:function(e,t){var i=null;return e.supportedCompressionFormats&&(i=e.supportedCompressionFormats.astc?10:e.supportedCompressionFormats.bc7?6:e.supportedCompressionFormats.s3tc?t.hasAlpha?3:2:e.supportedCompressionFormats.pvrtc?t.hasAlpha?9:8:e.supportedCompressionFormats.etc2?1:e.supportedCompressionFormats.etc1?0:14),i}(i.data.config,a),l=!1;null===s&&(l=!0,s=a.hasAlpha?3:2);var c=!0;o.startTranscoding()||(c=!1);for(var u=[],h=0;h<a.images.length&&c;h++){var d=a.images[h];if(void 0===r.loadSingleImage||r.loadSingleImage===h){var p=d.levels.length;!1===r.loadMipmapLevels&&(p=1);for(var f=0;f<p;f++){var _=d.levels[f],m=t(o,h,f,s,l);if(!m){c=!1;break}_.transcodedPixels=m,u.push(_.transcodedPixels.buffer)}}}o.close(),o.delete(),l&&(s=-1),c?postMessage({action:"transcode",success:c,id:i.data.id,fileInfo:a,format:s},u):postMessage({action:"transcode",success:c,id:i.data.id})}}}Do._TextureLoaders.push(new xy);var Cy,Ry=function(){},Py=function(){};!function(e){e[e.cTFETC1=0]="cTFETC1",e[e.cTFETC2=1]="cTFETC2",e[e.cTFBC1=2]="cTFBC1",e[e.cTFBC3=3]="cTFBC3",e[e.cTFBC4=4]="cTFBC4",e[e.cTFBC5=5]="cTFBC5",e[e.cTFBC7=6]="cTFBC7",e[e.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",e[e.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",e[e.cTFASTC_4x4=10]="cTFASTC_4x4",e[e.cTFATC_RGB=11]="cTFATC_RGB",e[e.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",e[e.cTFRGBA32=13]="cTFRGBA32",e[e.cTFRGB565=14]="cTFRGB565",e[e.cTFBGR565=15]="cTFBGR565",e[e.cTFRGBA4444=16]="cTFRGBA4444",e[e.cTFFXT1_RGB=17]="cTFFXT1_RGB",e[e.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",e[e.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",e[e.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",e[e.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11"}(Cy||(Cy={}));var Iy={JSModuleURL:"".concat(rr._DefaultCdnUrl,"/basisTranscoder/1/basis_transcoder.js"),WasmModuleURL:"".concat(rr._DefaultCdnUrl,"/basisTranscoder/1/basis_transcoder.wasm")},My=function(e,t){var i;switch(e){case Cy.cTFETC1:i=u.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL;break;case Cy.cTFBC1:i=u.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1;break;case Cy.cTFBC4:i=u.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5;break;case Cy.cTFASTC_4x4:i=u.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4;break;case Cy.cTFETC2:i=u.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC;break;case Cy.cTFBC7:i=u.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM}if(void 0===i)throw"The chosen Basis transcoder format is not currently supported";return i},Oy=null,Dy=null,Ny=0,Fy=function(e){Dy=e},Ly=function(e,t){var i=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise((function(e,r){(Oy||(Oy=new Promise((function(e,t){Dy?e(Dy):rr.LoadFileAsync(rr.GetBabylonScriptURL(Iy.WasmModuleURL)).then((function(i){if("function"!=typeof URL)return t("Basis transcoder requires an environment with a URL constructor");var r=URL.createObjectURL(new Blob(["(".concat(Ay,")()")],{type:"application/javascript"}));(function(e,t,i){return new Promise((function(r,n){var o=function(t){"init"===t.data.action?(e.removeEventListener("message",o),r(e)):"error"===t.data.action&&n(t.data.error||"error initializing worker")};e.addEventListener("message",o),e.postMessage({action:"init",url:i?rr.GetBabylonScriptURL(i):void 0,wasmBinary:t},[t])}))})(Dy=new Worker(r),i,Iy.JSModuleURL).then(e,t)})).catch(t)}))),Oy).then((function(){var n=Ny++,o=function(t){"transcode"===t.data.action&&t.data.id===n&&(Dy.removeEventListener("message",o),t.data.success?e(t.data):r("Transcode is not supported on this device"))};Dy.addEventListener("message",o);var a=new Uint8Array(i.byteLength);a.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),Dy.postMessage({action:"transcode",id:n,imageData:a,config:t,ignoreSupportedFormats:!1},[a.buffer])}),(function(e){r(e)}))}))},wy=function(e,t){var i,r,n=null===(i=t._gl)||void 0===i?void 0:i.TEXTURE_2D;e.isCube&&(n=null===(r=t._gl)||void 0===r?void 0:r.TEXTURE_CUBE_MAP),t._bindTextureDirectly(n,e,!0)},By=function(e,t){for(var i=e.getEngine(),r=function(r){var n=t.fileInfo.images[r].levels[0];if(e._invertVScale=e.invertY,-1===t.format||t.format===Cy.cTFRGB565)if(e.type=u.TEXTURETYPE_UNSIGNED_SHORT_5_6_5,e.format=u.TEXTUREFORMAT_RGB,!i._features.basisNeedsPOT||j.Log2(n.width)%1==0&&j.Log2(n.height)%1==0)e._invertVScale=!e.invertY,e.width=n.width+3&-4,e.height=n.height+3&-4,e.samplingMode=u.TEXTURE_LINEAR_LINEAR,wy(e,i),i._uploadDataToTextureDirectly(e,new Uint16Array(n.transcodedPixels.buffer),r,0,u.TEXTUREFORMAT_RGB,!0);else{var o=new Pi(i,Ti.Temp);e._invertVScale=e.invertY,o.type=u.TEXTURETYPE_UNSIGNED_SHORT_5_6_5,o.format=u.TEXTUREFORMAT_RGB,o.width=n.width+3&-4,o.height=n.height+3&-4,wy(o,i),i._uploadDataToTextureDirectly(o,new Uint16Array(n.transcodedPixels.buffer),r,0,u.TEXTUREFORMAT_RGB,!0),i._rescaleTexture(o,e,i.scenes[0],i._getInternalFormat(u.TEXTUREFORMAT_RGB),(function(){i._releaseTexture(o),wy(e,i)}))}else{e.width=n.width,e.height=n.height,e.generateMipMaps=t.fileInfo.images[r].levels.length>1;var a=Uy.GetInternalFormatFromBasisFormat(t.format,i);e.format=a,wy(e,i),t.fileInfo.images[r].levels.forEach((function(t,n){i._uploadCompressedDataToTextureDirectly(e,a,t.width,t.height,t.transcodedPixels,r,n)})),!i._features.basisNeedsPOT||j.Log2(e.width)%1==0&&j.Log2(e.height)%1==0||(rr.Warn("Loaded .basis texture width and height are not a power of two. Texture wrapping will be set to Texture.CLAMP_ADDRESSMODE as other modes are not supported with non power of two dimensions in webGL 1."),e._cachedWrapU=Ja.CLAMP_ADDRESSMODE,e._cachedWrapV=Ja.CLAMP_ADDRESSMODE)}},n=0;n<t.fileInfo.images.length;n++)r(n)},Uy={JSModuleURL:Iy.JSModuleURL,WasmModuleURL:Iy.WasmModuleURL,GetInternalFormatFromBasisFormat:My,TranscodeAsync:Ly,LoadTextureFromTranscodeResult:By};Object.defineProperty(Uy,"JSModuleURL",{get:function(){return Iy.JSModuleURL},set:function(e){Iy.JSModuleURL=e}}),Object.defineProperty(Uy,"WasmModuleURL",{get:function(){return Iy.WasmModuleURL},set:function(e){Iy.WasmModuleURL=e}});var Vy=function(){function e(){this.supportCascades=!1}return e.prototype.canLoad=function(e){return e.endsWith(".basis")},e.prototype.loadCubeData=function(e,t,i,r,n){if(!Array.isArray(e)){var o=t.getEngine().getCaps(),a={supportedCompressionFormats:{etc1:!!o.etc1,s3tc:!!o.s3tc,pvrtc:!!o.pvrtc,etc2:!!o.etc2,astc:!!o.astc,bc7:!!o.bptc}};Ly(e,a).then((function(e){var i=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;By(t,e),t.getEngine()._setCubeMapTextureParams(t,i),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()})).catch((function(e){rr.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,n&&n(e)}))}},e.prototype.loadData=function(e,t,i){var r=t.getEngine().getCaps(),n={supportedCompressionFormats:{etc1:!!r.etc1,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,astc:!!r.astc,bc7:!!r.bptc}};Ly(e,n).then((function(e){var r=e.fileInfo.images[0].levels[0],n=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(r.width,r.height,n,-1!==e.format,(function(){By(t,e)}))})).catch((function(e){rr.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),rr.Warn("Failed to transcode Basis file: ".concat(e)),i(0,0,!1,!1,(function(){}),!0)}))},e}();Mi._TextureLoaders.push(new Vy);var ky=function(e){function t(t,i,r,n,o,a){var s=this,l=!(!o||!o.generateMipMaps)&&o.generateMipMaps,c=!(!o||!o.generateDepthTexture)&&o.generateDepthTexture,h=o&&o.depthTextureFormat?o.depthTextureFormat:u.TEXTUREFORMAT_DEPTH16,d=!o||void 0===o.doNotChangeAspectRatio||o.doNotChangeAspectRatio,p=!(!o||!o.drawOnlyOnFirstAttachmentByDefault)&&o.drawOnlyOnFirstAttachmentByDefault;if(!(s=e.call(this,t,i,n,l,d,void 0,void 0,void 0,void 0,void 0,void 0,void 0,!0)||this).isSupported)return s.dispose(),s;s._textureNames=a;var f=[],_=[],m=[],g=[],v=[],y=[],b=[],T=[];s._initTypes(r,f,_,m,g,v,y,b,T,o);var E=!o||void 0===o.generateDepthBuffer||o.generateDepthBuffer,S=!(!o||void 0===o.generateStencilBuffer)&&o.generateStencilBuffer;return s._multiRenderTargetOptions={samplingModes:_,generateMipMaps:l,generateDepthBuffer:E,generateStencilBuffer:S,generateDepthTexture:c,depthTextureFormat:h,types:f,textureCount:r,useSRGBBuffers:m,formats:g,targetTypes:v,faceIndex:y,layerIndex:b,layerCounts:T,labels:a,label:t},s._count=r,s._drawOnlyOnFirstAttachmentByDefault=p,r>0&&(s._createInternalTextures(),s._createTextures(a)),s}return m(t,e),Object.defineProperty(t.prototype,"isSupported",{get:function(){var e,t;return null!==(t=null===(e=this._engine)||void 0===e?void 0:e.getCaps().drawBuffersExtension)&&void 0!==t&&t},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"textures",{get:function(){return this._textures},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"count",{get:function(){return this._count},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"depthTexture",{get:function(){return this._textures[this._textures.length-1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"wrapU",{set:function(e){if(this._textures)for(var t=0;t<this._textures.length;t++)this._textures[t].wrapU=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"wrapV",{set:function(e){if(this._textures)for(var t=0;t<this._textures.length;t++)this._textures[t].wrapV=e},enumerable:!1,configurable:!0}),t.prototype._initTypes=function(e,t,i,r,n,o,a,s,l,c){for(var h=0;h<e;h++)c&&c.types&&void 0!==c.types[h]?t.push(c.types[h]):t.push(c&&c.defaultType?c.defaultType:u.TEXTURETYPE_UNSIGNED_INT),c&&c.samplingModes&&void 0!==c.samplingModes[h]?i.push(c.samplingModes[h]):i.push(Ja.BILINEAR_SAMPLINGMODE),c&&c.useSRGBBuffers&&void 0!==c.useSRGBBuffers[h]?r.push(c.useSRGBBuffers[h]):r.push(!1),c&&c.formats&&void 0!==c.formats[h]?n.push(c.formats[h]):n.push(u.TEXTUREFORMAT_RGBA),c&&c.targetTypes&&void 0!==c.targetTypes[h]?o.push(c.targetTypes[h]):o.push(u.TEXTURE_2D),c&&c.faceIndex&&void 0!==c.faceIndex[h]?a.push(c.faceIndex[h]):a.push(0),c&&c.layerIndex&&void 0!==c.layerIndex[h]?s.push(c.layerIndex[h]):s.push(0),c&&c.layerCounts&&void 0!==c.layerCounts[h]?l.push(c.layerCounts[h]):l.push(1)},t.prototype._createInternaTextureIndexMapping=function(){var e={},t=[];if(!this._renderTarget)return t;for(var i=this._renderTarget.textures,r=0;r<i.length;r++){var n=i[r];if(n){var o=e[n.uniqueId];void 0!==o?t[r]=o:e[n.uniqueId]=r}}return t},t.prototype._rebuild=function(e,t,i){if(void 0===e&&(e=!1),void 0===t&&(t=!1),!(this._count<1||e)){var r=this._createInternaTextureIndexMapping();this.releaseInternalTextures(),this._createInternalTextures(),t&&(this._releaseTextures(),this._createTextures(i));for(var n=this._renderTarget.textures,o=0;o<n.length;o++){var a=this._textures[o];void 0!==r[o]&&this._renderTarget.setTexture(n[r[o]],o),a._texture=n[o],a._texture&&(a._noMipmap=!a._texture.useMipMaps,a._useSRGBBuffer=a._texture._useSRGBBuffer)}1!==this.samples&&this._renderTarget.setSamples(this.samples,!this._drawOnlyOnFirstAttachmentByDefault,!0)}},t.prototype._createInternalTextures=function(){this._renderTarget=this._getEngine().createMultipleRenderTarget(this._size,this._multiRenderTargetOptions,!this._drawOnlyOnFirstAttachmentByDefault),this._texture=this._renderTarget.texture},t.prototype._releaseTextures=function(){if(this._textures)for(var e=0;e<this._textures.length;e++)this._textures[e]._texture=null,this._textures[e].dispose()},t.prototype._createTextures=function(e){var t=this._renderTarget.textures;this._textures=[];for(var i=0;i<t.length;i++){var r=new Ja(null,this.getScene());(null==e?void 0:e[i])&&(r.name=e[i]),r._texture=t[i],r._texture&&(r._noMipmap=!r._texture.useMipMaps,r._useSRGBBuffer=r._texture._useSRGBBuffer),this._textures.push(r)}},t.prototype.setInternalTexture=function(e,t,i){var r,n;if(void 0===i&&(i=!0),this.renderTarget&&(0===t&&(this._texture=e),this.renderTarget.setTexture(e,t,i),this.textures[t]||(this.textures[t]=new Ja(null,this.getScene()),this.textures[t].name=null!==(n=null===(r=this._textureNames)||void 0===r?void 0:r[t])&&void 0!==n?n:this.textures[t].name),this.textures[t]._texture=e,this.textures[t]._noMipmap=!e.useMipMaps,this.textures[t]._useSRGBBuffer=e._useSRGBBuffer,this._count=this.renderTarget.textures?this.renderTarget.textures.length:0,this._multiRenderTargetOptions.types&&(this._multiRenderTargetOptions.types[t]=e.type),this._multiRenderTargetOptions.samplingModes&&(this._multiRenderTargetOptions.samplingModes[t]=e.samplingMode),this._multiRenderTargetOptions.useSRGBBuffers&&(this._multiRenderTargetOptions.useSRGBBuffers[t]=e._useSRGBBuffer),this._multiRenderTargetOptions.targetTypes&&-1!==this._multiRenderTargetOptions.targetTypes[t])){var o;o=e.is2DArray?u.TEXTURE_2D_ARRAY:e.isCube?u.TEXTURE_CUBE_MAP:e.is3D?u.TEXTURE_3D:u.TEXTURE_2D,this._multiRenderTargetOptions.targetTypes[t]=o}},t.prototype.setLayerAndFaceIndex=function(e,t,i){void 0===t&&(t=-1),void 0===i&&(i=-1),this.textures[e]&&this.renderTarget&&(this._multiRenderTargetOptions.layerIndex&&(this._multiRenderTargetOptions.layerIndex[e]=t),this._multiRenderTargetOptions.faceIndex&&(this._multiRenderTargetOptions.faceIndex[e]=i),this.renderTarget.setLayerAndFaceIndex(e,t,i))},t.prototype.setLayerAndFaceIndices=function(e,t){this.renderTarget&&(this._multiRenderTargetOptions.layerIndex=e,this._multiRenderTargetOptions.faceIndex=t,this.renderTarget.setLayerAndFaceIndices(e,t))},Object.defineProperty(t.prototype,"samples",{get:function(){return this._samples},set:function(e){this._renderTarget?this._samples=this._renderTarget.setSamples(e):this._samples=e},enumerable:!1,configurable:!0}),t.prototype.resize=function(e){this._processSizeParameter(e,!1),this._rebuild(!1,void 0,this._textureNames)},t.prototype.updateCount=function(e,t,i){this._multiRenderTargetOptions.textureCount=e,this._count=e;var r=[],n=[],o=[],a=[],s=[],l=[],c=[],u=[];this._textureNames=i,this._initTypes(e,r,n,o,a,s,l,c,u,t),this._multiRenderTargetOptions.types=r,this._multiRenderTargetOptions.samplingModes=n,this._multiRenderTargetOptions.useSRGBBuffers=o,this._multiRenderTargetOptions.formats=a,this._multiRenderTargetOptions.targetTypes=s,this._multiRenderTargetOptions.faceIndex=l,this._multiRenderTargetOptions.layerIndex=c,this._multiRenderTargetOptions.layerCounts=u,this._multiRenderTargetOptions.labels=i,this._rebuild(!1,!0,i)},t.prototype._unbindFrameBuffer=function(e,t){var i=this;this._renderTarget&&e.unBindMultiColorAttachmentFramebuffer(this._renderTarget,this.isCube,(function(){i.onAfterRenderObservable.notifyObservers(t)}))},t.prototype.dispose=function(t){void 0===t&&(t=!1),this._releaseTextures(),t?this._texture=null:this.releaseInternalTextures(),e.prototype.dispose.call(this)},t.prototype.releaseInternalTextures=function(){var e,t,i=null===(e=this._renderTarget)||void 0===e?void 0:e.textures;if(i){for(var r=i.length-1;r>=0;r--)this._textures[r]._texture=null;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null}},t}(Pl),Gy=function(e,t,i){this.id=e,this.scale=t,this.offset=i},zy=function(){function e(t,i,r,n){var o,a,s,l,c,u,h,d,p,f,_,m,g;return this.name=t,this.meshes=i,this.scene=n,this.options=r,this.options.map=null!==(o=this.options.map)&&void 0!==o?o:["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=null!==(a=this.options.uvsIn)&&void 0!==a?a:Nr.UVKind,this.options.uvsOut=null!==(s=this.options.uvsOut)&&void 0!==s?s:Nr.UVKind,this.options.layout=null!==(l=this.options.layout)&&void 0!==l?l:e.LAYOUT_STRIP,this.options.layout===e.LAYOUT_COLNUM&&(this.options.colnum=null!==(c=this.options.colnum)&&void 0!==c?c:8),this.options.updateInputMeshes=null===(u=this.options.updateInputMeshes)||void 0===u||u,this.options.disposeSources=null===(h=this.options.disposeSources)||void 0===h||h,this._expecting=0,this.options.fillBlanks=null===(d=this.options.fillBlanks)||void 0===d||d,!0===this.options.fillBlanks&&(this.options.customFillColor=null!==(p=this.options.customFillColor)&&void 0!==p?p:"black"),this.options.frameSize=null!==(f=this.options.frameSize)&&void 0!==f?f:256,this.options.paddingRatio=null!==(_=this.options.paddingRatio)&&void 0!==_?_:.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!=0&&this._paddingValue++,this.options.paddingMode=null!==(m=this.options.paddingMode)&&void 0!==m?m:e.SUBUV_WRAP,this.options.paddingMode===e.SUBUV_COLOR&&(this.options.paddingColor=null!==(g=this.options.paddingColor)&&void 0!==g?g:new J(0,0,0,1)),this.sets={},this.frames=[],this}return e.prototype._createFrames=function(e){for(var t=this,i=this._calculateSize(),r=new U(1,1).divide(i),n=0,o=this._expecting,a=this.meshes.length,s=Object.keys(this.sets),l=0;l<s.length;l++){var c=s[l],u=new Gu(this.name+".TexturePack."+c+"Set",{width:i.x,height:i.y},this.scene,!0,Ja.TRILINEAR_SAMPLINGMODE,Do.TEXTUREFORMAT_RGBA),h=u.getContext();h.fillStyle="rgba(0,0,0,0)",h.fillRect(0,0,i.x,i.y),u.update(!1),this.sets[c]=u}var d=this.options.frameSize||256,p=this._paddingValue,f=d+2*p;for(l=0;l<a;l++)for(var _=this.meshes[l].material,m=function(a){var c=new Gu("temp",f,g.scene,!0),u=c.getContext(),h=g._getFrameOffset(l),m=function(){n++,c.update(!1);var a=u.getImageData(0,0,f,f),s=t.sets[v];if(s.getContext().putImageData(a,i.x*h.x,i.y*h.y),c.dispose(),s.update(!1),n==o)return t._calculateMeshUVFrames(d,p,i,r,t.options.updateInputMeshes||!1),void e()},v=s[a]||"_blank";if(_&&null!==_[v]){var y=_[v],b=new Image;b.src=y instanceof Gu?y.getContext().canvas.toDataURL("image/png"):y.url,rr.SetCorsBehavior(b.src,b),b.onload=function(){u.fillStyle="rgba(0,0,0,0)",u.fillRect(0,0,f,f),c.update(!1),u.setTransform(1,0,0,-1,0,0);var e=[0,0,1,0,1,1,0,1,-1,1,-1,0,-2,0,-1,1,-1];switch(t.options.paddingMode){case 0:for(var i=0;i<9;i++)u.drawImage(b,0,0,b.width,b.height,p+d*e[i],p+d*e[i+1]-f,d,d);break;case 1:for(var r=0;r<p;r++)u.drawImage(b,0,0,b.width,b.height,r+d*e[0],p-f,d,d),u.drawImage(b,0,0,b.width,b.height,2*p-r,p-f,d,d),u.drawImage(b,0,0,b.width,b.height,p,r-f,d,d),u.drawImage(b,0,0,b.width,b.height,p,2*p-r-f,d,d);u.drawImage(b,0,0,b.width,b.height,p+d*e[0],p+d*e[1]-f,d,d);break;case 2:u.fillStyle=(t.options.paddingColor||Z.Black()).toHexString(),u.fillRect(0,0,f,-f),u.clearRect(p,p,d,d),u.drawImage(b,0,0,b.width,b.height,p+d*e[0],p+d*e[1]-f,d,d)}u.setTransform(1,0,0,1,0,0),m()}}else u.fillStyle="rgba(0,0,0,0)",g.options.fillBlanks&&(u.fillStyle=g.options.customFillColor),u.fillRect(0,0,f,f),m()},g=this,v=0;v<s.length;v++)m(v)},e.prototype._calculateSize=function(){var e=this.meshes.length||0,t=this.options.frameSize||0,i=this._paddingValue||0;switch(this.options.layout){case 0:return new U(t*e+2*i*e,t+2*i);case 1:var r=Math.max(2,Math.ceil(Math.sqrt(e))),n=t*r+2*i*r;return new U(n,n);case 2:var o=this.options.colnum||1,a=Math.max(1,Math.ceil(e/o));return new U(t*o+2*i*o,t*a+2*i*a)}return U.Zero()},e.prototype._calculateMeshUVFrames=function(e,t,i,r,n){for(var o=this.meshes.length,a=0;a<o;a++){var s=this.meshes[a],l=new U(e/i.x,e/i.y),c=r.clone().scale(t),u=this._getFrameOffset(a).add(c),h=new Gy(a,l,u);this.frames.push(h),n&&(this._updateMeshUV(s,a),this._updateTextureReferences(s))}},e.prototype._getFrameOffset=function(e){var t,i,r,n=this.meshes.length;switch(this.options.layout){case 0:return new U(e*(t=1/n),0);case 1:var o=Math.max(2,Math.ceil(Math.sqrt(n)));return i=Math.floor(e/o),new U((r=e-i*o)*(t=1/o),i*t);case 2:var a=this.options.colnum||1,s=Math.max(1,Math.ceil(n/a));return i=e-(r=Math.floor(e/s))*s,t=new U(1/a,1/s),new U(r*t.x,i*t.y)}return U.Zero()},e.prototype._updateMeshUV=function(e,t){var i=this.frames[t],r=e.getVerticesData(this.options.uvsIn||Nr.UVKind),n=[],o=0;r.length&&(o=r.length||0);for(var a=0;a<o;a+=2)n.push(r[a]*i.scale.x+i.offset.x,r[a+1]*i.scale.y+i.offset.y);e.setVerticesData(this.options.uvsOut||Nr.UVKind,n)},e.prototype._updateTextureReferences=function(e,t){void 0===t&&(t=!1);for(var i=e.material,r=Object.keys(this.sets),n=function(e){e.dispose&&e.dispose()},o=0;o<r.length;o++){var a=r[o];if(t)null!==i[a]&&n(i[a]),i[a]=this.sets[a];else{if(!i)return;null!==i[a]&&(n(i[a]),i[a]=this.sets[a])}}},e.prototype.setMeshToFrame=function(e,t,i){void 0===i&&(i=!1),this._updateMeshUV(e,t),i&&this._updateTextureReferences(e,!0)},e.prototype.processAsync=function(){var e=this;return new Promise((function(t,i){try{if(0===e.meshes.length)return void t();for(var r=0,n=function(i){var n=e.meshes[i],o=n.material;if(!o)return++r===e.meshes.length?{value:e._createFrames(t)}:"continue";o.forceCompilationAsync(n).then((function(){!function(i){if(r++,e.options.map){for(var n=0;n<e.options.map.length;n++)null!==i[e.options.map[n]]&&(e.sets[e.options.map[n]]||(e.sets[e.options.map[n]]=!0),e._expecting++);r===e.meshes.length&&e._createFrames(t)}}(o)}))},o=0;o<e.meshes.length;o++){var a=n(o);if("object"==typeof a)return a.value}}catch(e){return i(e)}}))},e.prototype.dispose=function(){for(var e=Object.keys(this.sets),t=0;t<e.length;t++){var i=e[t];this.sets[i].dispose()}},e.prototype.download=function(e,t){var i=this;void 0===e&&(e="png"),void 0===t&&(t=1),setTimeout((function(){var r={name:i.name,sets:{},options:{},frames:[]},n=Object.keys(i.sets),o=Object.keys(i.options);try{for(var a=0;a<n.length;a++){var s=n[a],l=i.sets[s];r.sets[s]=l.getContext().canvas.toDataURL("image/"+e,t)}for(a=0;a<o.length;a++){var c=o[a];r.options[c]=i.options[c]}for(a=0;a<i.frames.length;a++){var u=i.frames[a];r.frames.push(u.scale.x,u.scale.y,u.offset.x,u.offset.y)}}catch(e){return void ae.Warn("Unable to download: "+e)}var h="data:text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(r,null,4)),d=document.createElement("a");d.setAttribute("href",h),d.setAttribute("download",i.name+"_texurePackage.json"),document.body.appendChild(d),d.click(),d.remove()}),0)},e.prototype.updateFromJSON=function(e){try{var t=JSON.parse(e);this.name=t.name;for(var i=Object.keys(t.options),r=0;r<i.length;r++)this.options[i[r]]=t.options[i[r]];for(r=0;r<t.frames.length;r+=4){var n=new Gy(r/4,new U(t.frames[r],t.frames[r+1]),new U(t.frames[r+2],t.frames[r+3]));this.frames.push(n)}var o=Object.keys(t.sets);for(r=0;r<o.length;r++){var a=new Ja(t.sets[o[r]],this.scene,!1,!1);this.sets[o[r]]=a}}catch(e){ae.Warn("Unable to update from JSON: "+e)}},e.LAYOUT_STRIP=0,e.LAYOUT_POWER2=1,e.LAYOUT_COLNUM=2,e.SUBUV_WRAP=0,e.SUBUV_EXTEND=1,e.SUBUV_COLOR=2,e}(),Wy=function(e){function t(t,i,r,n,o,a,s){var l=e.call(this,t,r,null,n,o,a)||this;return l._animate=!0,l._time=0,l._texturePath=i,!o||o instanceof Ja||(s=!!o.skipJson),s?l.setFragment(l._texturePath):l._loadJson(i),l.refreshRate=1,l}return m(t,e),t.prototype._loadJson=function(e){var t=this,i=function(){try{t.setFragment(t._texturePath)}catch(e){ae.Log("No json or ShaderStore or DOM element found for CustomProceduralTexture")}},r=e+"/config.json",n=new Je;n.open("GET",r),n.addEventListener("load",(function(){if(200===n.status||n.responseText&&n.responseText.length>0)try{t._config=JSON.parse(n.response),t.updateShaderUniforms(),t.updateTextures(),t.setFragment(t._texturePath+"/custom"),t._animate=t._config.animate,t.refreshRate=t._config.refreshrate}catch(e){i()}else i()}),!1),n.addEventListener("error",(function(){i()}),!1);try{n.send()}catch(e){ae.Error("CustomProceduralTexture: Error on XHR send request.")}},t.prototype.isReady=function(){if(!e.prototype.isReady.call(this))return!1;for(var t in this._textures)if(!this._textures[t].isReady())return!1;return!0},t.prototype.render=function(t){var i=this.getScene();this._animate&&i&&(this._time+=.03*i.getAnimationRatio(),this.updateShaderUniforms()),e.prototype.render.call(this,t)},t.prototype.updateTextures=function(){for(var e=0;e<this._config.sampler2Ds.length;e++)this.setTexture(this._config.sampler2Ds[e].sample2Dname,new Ja(this._texturePath+"/"+this._config.sampler2Ds[e].textureRelativeUrl,this.getScene()))},t.prototype.updateShaderUniforms=function(){if(this._config)for(var e=0;e<this._config.uniforms.length;e++){var t=this._config.uniforms[e];switch(t.type){case"float":this.setFloat(t.name,t.value);break;case"color3":this.setColor3(t.name,new Z(t.r,t.g,t.b));break;case"color4":this.setColor4(t.name,new J(t.r,t.g,t.b,t.a));break;case"vector2":this.setVector2(t.name,new U(t.x,t.y));break;case"vector3":this.setVector3(t.name,new V(t.x,t.y,t.z))}}this.setFloat("time",this._time)},Object.defineProperty(t.prototype,"animate",{get:function(){return this._animate},set:function(e){this._animate=e},enumerable:!1,configurable:!0}),t}(Ol);li.ShadersStore.noisePixelShader="uniform float brightness;uniform float persistence;uniform float timeScale;varying vec2 vUV;vec2 hash22(vec2 p)\n{p=p*mat2(127.1,311.7,269.5,183.3);p=-1.0+2.0*fract(sin(p)*43758.5453123);return sin(p*6.283+timeScale);}\nfloat interpolationNoise(vec2 p)\n{vec2 pi=floor(p);vec2 pf=p-pi;vec2 w=pf*pf*(3.-2.*pf);float f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));float f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));float f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));float f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));float xm1=mix(f00,f10,w.x);float xm2=mix(f01,f11,w.x);float ym=mix(xm1,xm2,w.y); \nreturn ym;}\nfloat perlinNoise2D(float x,float y)\n{float sum=0.0;float frequency=0.0;float amplitude=0.0;for(int i=0; i<OCTAVES; i++)\n{frequency=pow(2.0,float(i));amplitude=pow(persistence,float(i));sum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;}\nreturn sum;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float x=abs(vUV.x);float y=abs(vUV.y);float noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);gl_FragColor=vec4(noise,noise,noise,1.0);}\n";var Hy=function(e){function t(t,i,r,n,o){void 0===i&&(i=256),void 0===r&&(r=M.LastCreatedScene);var a=e.call(this,t,i,"noise",r,n,o)||this;return a.time=0,a.brightness=.2,a.octaves=3,a.persistence=.8,a.animationSpeedFactor=1,a.autoClear=!1,a._updateShaderUniforms(),a}return m(t,e),t.prototype._updateShaderUniforms=function(){var e=this.getScene();e&&(this.time+=e.getAnimationRatio()*this.animationSpeedFactor*.01,this.setFloat("brightness",this.brightness),this.setFloat("persistence",this.persistence),this.setFloat("timeScale",this.time))},t.prototype._getDefines=function(){return"#define OCTAVES "+(0|this.octaves)},t.prototype.render=function(t){this._updateShaderUniforms(),e.prototype.render.call(this,t)},t.prototype.serialize=function(){var e={customType:"BABYLON.NoiseProceduralTexture"};return e.brightness=this.brightness,e.octaves=this.octaves,e.persistence=this.persistence,e.animationSpeedFactor=this.animationSpeedFactor,e.size=this.getSize().width,e.generateMipMaps=this._generateMipMaps,e.time=this.time,e},t.prototype.clone=function(){var e=this.getSize(),i=new t(this.name,e.width,this.getScene(),this._fallbackTexture?this._fallbackTexture:void 0,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.coordinatesMode=this.coordinatesMode,i.brightness=this.brightness,i.octaves=this.octaves,i.persistence=this.persistence,i.animationSpeedFactor=this.animationSpeedFactor,i.time=this.time,i},t.Parse=function(e,i){var r,n=new t(e.name,e.size,i,void 0,e.generateMipMaps);return n.brightness=e.brightness,n.octaves=e.octaves,n.persistence=e.persistence,n.animationSpeedFactor=e.animationSpeedFactor,n.time=null!==(r=e.time)&&void 0!==r?r:0,n},t}(Ol);a("BABYLON.NoiseProceduralTexture",Hy);var Xy=function(e){function t(t,i,r,n,o,a,s,l,c){void 0===n&&(n=u.TEXTUREFORMAT_RGBA),void 0===o&&(o=u.TEXTURETYPE_UNSIGNED_INT),void 0===a&&(a=!1),void 0===s&&(s=!1),void 0===l&&(l=u.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===c&&(c=null);var h=e.call(this,"",t)||this;return h._texture=t.getEngine().createRawCubeTexture(i,r,n,o,a,s,l,c),h}return m(t,e),t.prototype.update=function(e,t,i,r,n){void 0===n&&(n=null),this._texture.getEngine().updateRawCubeTexture(this._texture,e,t,i,r,n)},t.prototype.updateRGBDAsync=function(e,t,i,r){return void 0===t&&(t=null),void 0===i&&(i=.8),void 0===r&&(r=0),Kp(this._texture,e,t,i,r).then((function(){}))},t.prototype.clone=function(){var e=this;return Ke.Clone((function(){var i=e.getScene(),r=e._texture,n=new t(i,r._bufferViewArray,r.width,r.format,r.type,r.generateMipMaps,r.invertY,r.samplingMode,r._compression);return r.source===Ti.CubeRawRGBD&&n.updateRGBDAsync(r._bufferViewArrayArray,r._sphericalPolynomial,r._lodGenerationScale,r._lodGenerationOffset),n}),this)},t}(Nm),jy=function(e){function t(t,i,r,n,o,a,s,l,c,h,d){void 0===s&&(s=!0),void 0===l&&(l=!1),void 0===c&&(c=Ja.TRILINEAR_SAMPLINGMODE),void 0===h&&(h=u.TEXTURETYPE_UNSIGNED_INT);var p=e.call(this,null,a,!s,l)||this;return p.format=o,p._texture=a.getEngine().createRawTexture3D(t,i,r,n,o,s,l,c,null,h,d),p.is3D=!0,p}return m(t,e),t.prototype.update=function(e){this._texture&&this._getEngine().updateRawTexture3D(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)},t}(Ja),Yy=function(e){function t(t,i,r,n){var o=e.call(this,t,i,r,n,!0)||this;return o.refractionPlane=new sn(0,1,0,1),o.depth=2,o.onBeforeRenderObservable.add((function(){o.getScene().clipPlane=o.refractionPlane})),o.onAfterRenderObservable.add((function(){o.getScene().clipPlane=null})),o}return m(t,e),t.prototype.clone=function(){var e=this.getScene();if(!e)return this;var i=this.getSize(),r=new t(this.name,i.width,e,this._generateMipMaps);return r.hasAlpha=this.hasAlpha,r.level=this.level,r.refractionPlane=this.refractionPlane.clone(),this.renderList&&(r.renderList=this.renderList.slice(0)),r.depth=this.depth,r},t.prototype.serialize=function(){if(!this.name)return null;var t=e.prototype.serialize.call(this);return t.mirrorPlane=this.refractionPlane.asArray(),t.depth=this.depth,t},t}(Pl),Ky=function(e){function t(t,i,r){var n=e.call(this,null)||this;return n._renderTarget=null,n._engine=t,n._renderTargetOptions=r,n.resize(i),n}return m(t,e),Object.defineProperty(t.prototype,"renderTarget",{get:function(){return this._renderTarget},enumerable:!1,configurable:!0}),t.prototype.resize=function(e){var t;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null,this._texture=null,this._size=e,this._engine&&(this._renderTarget=this._engine.createRenderTargetTexture(this._size,this._renderTargetOptions)),this._texture=this.renderTarget.texture},t.prototype.getInternalTexture=function(){return this._texture},t.prototype.getClassName=function(){return"ThinRenderTargetTexture"},t.prototype.dispose=function(t){var i;void 0===t&&(t=!1),null===(i=this._renderTarget)||void 0===i||i.dispose(!0),this._renderTarget=null,t||e.prototype.dispose.call(this)},t}(ja),Qy=function(e){function t(t,i,r,n,o){var a=e.call(this,t,i,r)||this;return a._blockType=n,a._blockName=o,a.needDualDirectionValidation=!0,a}return m(t,e),t.prototype.checkCompatibilityState=function(e){return e instanceof t&&e._blockName===this._blockName?Bs.Compatible:Bs.TypeIncompatible},t.prototype.createCustomInputBlock=function(){return[new this._blockType(this._blockName),this.name]},t}(zs),qy=function(e){function t(t){var i=e.call(this,t,Fs.Vertex)||this;return i.registerInput("matricesIndices",Ns.Vector4),i.registerInput("matricesWeights",Ns.Vector4),i.registerInput("matricesIndicesExtra",Ns.Vector4,!0),i.registerInput("matricesWeightsExtra",Ns.Vector4,!0),i.registerInput("world",Ns.Matrix),i.registerOutput("output",Ns.Matrix),i}return m(t,e),t.prototype.initialize=function(e){e._excludeVariableName("boneSampler"),e._excludeVariableName("boneTextureWidth"),e._excludeVariableName("mBones"),e._excludeVariableName("BonesPerMesh")},t.prototype.getClassName=function(){return"BonesBlock"},Object.defineProperty(t.prototype,"matricesIndices",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"matricesWeights",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"matricesIndicesExtra",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"matricesWeightsExtra",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"world",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(e,t){if(void 0===t&&(t=function(){return!0}),!this.matricesIndices.isConnected){var i=e.getInputBlockByPredicate((function(e){return e.isAttribute&&"matricesIndices"===e.name&&t(e)}));i||(i=new rl("matricesIndices")).setAsAttribute("matricesIndices"),i.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){var r=e.getInputBlockByPredicate((function(e){return e.isAttribute&&"matricesWeights"===e.name&&t(e)}));r||(r=new rl("matricesWeights")).setAsAttribute("matricesWeights"),r.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){var n=e.getInputBlockByPredicate((function(e){return e.systemValue===Qs.World&&t(e)}));n||(n=new rl("world")).setAsSystemValue(Qs.World),n.output.connectTo(this.world)}},t.prototype.provideFallbacks=function(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)},t.prototype.bind=function(e,t,i){na(i,e)},t.prototype.prepareDefines=function(e,t,i){i._areAttributesDirty&&ma(e,i)},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t),t.sharedData.blocksWithFallbacks.push(this),t.sharedData.forcedBindableBlocks.push(this),t.sharedData.blocksWithDefines.push(this),t.uniforms.push("boneTextureWidth"),t.uniforms.push("mBones"),t.samplers.push("boneSampler");var i="//".concat(this.name);t._emitFunctionFromInclude("bonesDeclaration",i,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});var r=t._getFreeVariableName("influence");t.compilationString+=t._emitCodeFromInclude("bonesVertex",i,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:r}]});var n=this._outputs[0],o=this.world;return t.compilationString+="#if NUM_BONE_INFLUENCERS>0\n",t.compilationString+=t._declareOutput(n)+" = ".concat(o.associatedVariableName," * ").concat(r,";\n"),t.compilationString+="#else\n",t.compilationString+=t._declareOutput(n)+" = ".concat(o.associatedVariableName,";\n"),t.compilationString+="#endif\n",this},t}(Ws);a("BABYLON.BonesBlock",qy);var Zy=function(e){function t(t){var i=e.call(this,t,Fs.Vertex)||this;return i.registerInput("world0",Ns.Vector4),i.registerInput("world1",Ns.Vector4),i.registerInput("world2",Ns.Vector4),i.registerInput("world3",Ns.Vector4),i.registerInput("world",Ns.Matrix,!0),i.registerOutput("output",Ns.Matrix),i.registerOutput("instanceID",Ns.Float),i}return m(t,e),t.prototype.getClassName=function(){return"InstancesBlock"},Object.defineProperty(t.prototype,"world0",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"world1",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"world2",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"world3",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"world",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"instanceID",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(e,t){if(void 0===t&&(t=function(){return!0}),!this.world0.connectedPoint){var i=e.getInputBlockByPredicate((function(e){return e.isAttribute&&"world0"===e.name&&t(e)}));i||(i=new rl("world0")).setAsAttribute("world0"),i.output.connectTo(this.world0)}if(!this.world1.connectedPoint){var r=e.getInputBlockByPredicate((function(e){return e.isAttribute&&"world1"===e.name&&t(e)}));r||(r=new rl("world1")).setAsAttribute("world1"),r.output.connectTo(this.world1)}if(!this.world2.connectedPoint){var n=e.getInputBlockByPredicate((function(e){return e.isAttribute&&"world2"===e.name&&t(e)}));n||(n=new rl("world2")).setAsAttribute("world2"),n.output.connectTo(this.world2)}if(!this.world3.connectedPoint){var o=e.getInputBlockByPredicate((function(e){return e.isAttribute&&"world3"===e.name&&t(e)}));o||(o=new rl("world3")).setAsAttribute("world3"),o.output.connectTo(this.world3)}if(!this.world.connectedPoint){var a=e.getInputBlockByPredicate((function(e){return e.isAttribute&&"world"===e.name&&t(e)}));a||(a=new rl("world")).setAsSystemValue(Qs.World),a.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"},t.prototype.prepareDefines=function(e,t,i,r,n){void 0===r&&(r=!1);var o=!1;i.INSTANCES!==r&&(i.setValue("INSTANCES",r),o=!0),n&&i.THIN_INSTANCES!==!!(null==n?void 0:n.getRenderingMesh().hasThinInstances)&&(i.setValue("THIN_INSTANCES",!!(null==n?void 0:n.getRenderingMesh().hasThinInstances)),o=!0),o&&i.markAsUnprocessed()},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=t.sharedData.scene.getEngine();t.sharedData.blocksWithDefines.push(this);var r=this._outputs[0],n=this._outputs[1],o=this.world0,a=this.world1,s=this.world2,l=this.world3;return t.compilationString+="#ifdef INSTANCES\n",t.compilationString+=t._declareOutput(r)+" = mat4(".concat(o.associatedVariableName,", ").concat(a.associatedVariableName,", ").concat(s.associatedVariableName,", ").concat(l.associatedVariableName,");\n"),t.compilationString+="#ifdef THIN_INSTANCES\n",t.compilationString+="".concat(r.associatedVariableName," = ").concat(this.world.associatedVariableName," * ").concat(r.associatedVariableName,";\n"),t.compilationString+="#endif\n",i._caps.canUseGLInstanceID?t.compilationString+=t._declareOutput(n)+" = float(gl_InstanceID);\n":t.compilationString+=t._declareOutput(n)+" = 0.0;\n",t.compilationString+="#else\n",t.compilationString+=t._declareOutput(r)+" = ".concat(this.world.associatedVariableName,";\n"),t.compilationString+=t._declareOutput(n)+" = 0.0;\n",t.compilationString+="#endif\n",this},t}(Ws);a("BABYLON.InstancesBlock",Zy);var Jy=function(e){function t(t){var i=e.call(this,t,Fs.Vertex)||this;return i.registerInput("position",Ns.Vector3),i.registerInput("normal",Ns.Vector3),i.registerInput("tangent",Ns.AutoDetect),i.tangent.addExcludedConnectionPointFromAllowedTypes(Ns.Color4|Ns.Vector4|Ns.Vector3),i.registerInput("uv",Ns.Vector2),i.registerOutput("positionOutput",Ns.Vector3),i.registerOutput("normalOutput",Ns.Vector3),i.registerOutput("tangentOutput",Ns.Vector4),i.registerOutput("uvOutput",Ns.Vector2),i}return m(t,e),t.prototype.getClassName=function(){return"MorphTargetsBlock"},Object.defineProperty(t.prototype,"position",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"normal",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"tangent",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"uv",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"positionOutput",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"normalOutput",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"tangentOutput",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"uvOutput",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),t.prototype.initialize=function(e){e._excludeVariableName("morphTargetInfluences")},t.prototype.autoConfigure=function(e,t){if(void 0===t&&(t=function(){return!0}),!this.position.isConnected){var i=e.getInputBlockByPredicate((function(e){return e.isAttribute&&"position"===e.name&&t(e)}));i||(i=new rl("position")).setAsAttribute(),i.output.connectTo(this.position)}if(!this.normal.isConnected){var r=e.getInputBlockByPredicate((function(e){return e.isAttribute&&"normal"===e.name&&t(e)}));r||(r=new rl("normal")).setAsAttribute("normal"),r.output.connectTo(this.normal)}if(!this.tangent.isConnected){var n=e.getInputBlockByPredicate((function(e){return e.isAttribute&&"tangent"===e.name&&t(e)}));n||(n=new rl("tangent")).setAsAttribute("tangent"),n.output.connectTo(this.tangent)}if(!this.uv.isConnected){var o=e.getInputBlockByPredicate((function(e){return e.isAttribute&&"uv"===e.name&&t(e)}));o||(o=new rl("uv")).setAsAttribute("uv"),o.output.connectTo(this.uv)}},t.prototype.prepareDefines=function(e,t,i){if(e.morphTargetManager){var r=e.morphTargetManager;(null==r?void 0:r.isUsingTextureForTargets)&&(r.numMaxInfluencers||r.numInfluencers)!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&ga(e,i)},t.prototype.bind=function(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&($o(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))},t.prototype.replaceRepeatableContent=function(e,t,i,r){var n=this.position,o=this.normal,a=this.tangent,s=this.uv,l=this.positionOutput,c=this.normalOutput,u=this.tangentOutput,h=this.uvOutput,d=e,p=r.NUM_MORPH_INFLUENCERS,f=i.morphTargetManager,_=f&&f.supportsNormals&&r.NORMAL,m=f&&f.supportsTangents&&r.TANGENT,g=f&&f.supportsUVs&&r.UV1,v="";if((null==f?void 0:f.isUsingTextureForTargets)&&p>0&&(v+="float vertexID;\n"),v+="#ifdef MORPHTARGETS\n",null==f?void 0:f.isUsingTextureForTargets)v+="for (int i = 0; i < NUM_MORPH_INFLUENCERS; i++) {\n",v+="if (i >= morphTargetCount) break;\n",v+="vertexID = float(gl_VertexID) * morphTargetTextureInfo.x;\n",v+="".concat(l.associatedVariableName," += (readVector3FromRawSampler(i, vertexID) - ").concat(n.associatedVariableName,") * morphTargetInfluences[i];\n"),v+="vertexID += 1.0;\n",_&&(v+="#ifdef MORPHTARGETS_NORMAL\n",v+="".concat(c.associatedVariableName," += (readVector3FromRawSampler(i, vertexID) - ").concat(o.associatedVariableName,") * morphTargetInfluences[i];\n"),v+="vertexID += 1.0;\n",v+="#endif\n"),g&&(v+="#ifdef MORPHTARGETS_UV\n",v+="".concat(h.associatedVariableName," += (readVector3FromRawSampler(i, vertexID).xy - ").concat(s.associatedVariableName,") * morphTargetInfluences[i];\n"),v+="vertexID += 1.0;\n",v+="#endif\n"),m&&(v+="#ifdef MORPHTARGETS_TANGENT\n",v+="".concat(u.associatedVariableName,".xyz += (readVector3FromRawSampler(i, vertexID) - ").concat(a.associatedVariableName,".xyz) * morphTargetInfluences[i];\n"),a.type===Ns.Vector4?v+="".concat(u.associatedVariableName,".w = ").concat(a.associatedVariableName,".w;\n"):v+="".concat(u.associatedVariableName,".w = 1.;\n"),v+="#endif\n"),v+="}\n";else for(var y=0;y<p;y++)v+="".concat(l.associatedVariableName," += (position").concat(y," - ").concat(n.associatedVariableName,") * morphTargetInfluences[").concat(y,"];\n"),_&&(v+="#ifdef MORPHTARGETS_NORMAL\n",v+="".concat(c.associatedVariableName," += (normal").concat(y," - ").concat(o.associatedVariableName,") * morphTargetInfluences[").concat(y,"];\n"),v+="#endif\n"),g&&(v+="#ifdef MORPHTARGETS_UV\n",v+="".concat(h.associatedVariableName,".xy += (uv_").concat(y," - ").concat(s.associatedVariableName,".xy) * morphTargetInfluences[").concat(y,"];\n"),v+="#endif\n"),m&&(v+="#ifdef MORPHTARGETS_TANGENT\n",v+="".concat(u.associatedVariableName,".xyz += (tangent").concat(y," - ").concat(a.associatedVariableName,".xyz) * morphTargetInfluences[").concat(y,"];\n"),a.type===Ns.Vector4?v+="".concat(u.associatedVariableName,".w = ").concat(a.associatedVariableName,".w;\n"):v+="".concat(u.associatedVariableName,".w = 1.;\n"),v+="#endif\n");if(v+="#endif\n",d.compilationString=d.compilationString.replace(this._repeatableContentAnchor,v),p>0)for(y=0;y<p;y++)d.attributes.push(Nr.PositionKind+y),_&&d.attributes.push(Nr.NormalKind+y),m&&d.attributes.push(Nr.TangentKind+y),g&&d.attributes.push(Nr.UVKind+"_"+y)},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t),t.sharedData.blocksWithDefines.push(this),t.sharedData.bindableBlocks.push(this),t.sharedData.repeatableContentBlocks.push(this);var i=this.position,r=this.normal,n=this.tangent,o=this.uv,a=this.positionOutput,s=this.normalOutput,l=this.tangentOutput,c=this.uvOutput,u="//".concat(this.name);return t.uniforms.push("morphTargetInfluences"),t.uniforms.push("morphTargetCount"),t.uniforms.push("morphTargetTextureInfo"),t.uniforms.push("morphTargetTextureIndices"),t.samplers.push("morphTargets"),t._emitFunctionFromInclude("morphTargetsVertexGlobalDeclaration",u),t._emitFunctionFromInclude("morphTargetsVertexDeclaration",u,{repeatKey:"maxSimultaneousMorphTargets"}),t.compilationString+="".concat(t._declareOutput(a)," = ").concat(i.associatedVariableName,";\n"),t.compilationString+="#ifdef NORMAL\n",t.compilationString+="".concat(t._declareOutput(s)," = ").concat(r.associatedVariableName,";\n"),t.compilationString+="#else\n",t.compilationString+="".concat(t._declareOutput(s)," = vec3(0., 0., 0.);\n"),t.compilationString+="#endif\n",t.compilationString+="#ifdef TANGENT\n",t.compilationString+="".concat(t._declareOutput(l)," = ").concat(n.associatedVariableName,";\n"),t.compilationString+="#else\n",t.compilationString+="".concat(t._declareOutput(l)," = vec4(0., 0., 0., 0.);\n"),t.compilationString+="#endif\n",t.compilationString+="#ifdef UV1\n",t.compilationString+="".concat(t._declareOutput(c)," = ").concat(o.associatedVariableName,";\n"),t.compilationString+="#else\n",t.compilationString+="".concat(t._declareOutput(c)," = vec2(0., 0.);\n"),t.compilationString+="#endif\n",this._repeatableContentAnchor=t._repeatableContentAnchor,t.compilationString+=this._repeatableContentAnchor,this},t}(Ws);a("BABYLON.MorphTargetsBlock",Jy);var $y=function(e){function t(t){var i=e.call(this,t,Fs.Vertex)||this;return i.registerInput("worldPosition",Ns.Vector4,!1,Fs.Vertex),i.registerOutput("direction",Ns.Vector3),i.registerOutput("color",Ns.Color3),i.registerOutput("intensity",Ns.Float),i.registerOutput("shadowBias",Ns.Float),i.registerOutput("shadowNormalBias",Ns.Float),i.registerOutput("shadowDepthScale",Ns.Float),i.registerOutput("shadowDepthRange",Ns.Vector2),i}return m(t,e),t.prototype.getClassName=function(){return"LightInformationBlock"},Object.defineProperty(t.prototype,"worldPosition",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"direction",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"color",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"intensity",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"shadowBias",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"shadowNormalBias",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"shadowDepthScale",{get:function(){return this._outputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"shadowDepthRange",{get:function(){return this._outputs[6]},enumerable:!1,configurable:!0}),t.prototype.bind=function(e,t,i){if(i){this.light&&this.light.isDisposed()&&(this.light=null);var r=this.light,n=t.getScene();if(!r&&n.lights.length&&(r=this.light=n.lights[0],this._forcePrepareDefines=!0),!r||!r.isEnabled)return e.setFloat3(this._lightDataUniformName,0,0,0),void e.setFloat4(this._lightColorUniformName,0,0,0,0);r.transferToNodeMaterialEffect(e,this._lightDataUniformName),e.setColor4(this._lightColorUniformName,r.diffuse,r.intensity);var o=r.getShadowGenerator();if((this.shadowBias.hasEndpoints||this.shadowNormalBias.hasEndpoints||this.shadowDepthScale.hasEndpoints)&&(o?e.setFloat3(this._lightShadowUniformName,o.bias,o.normalBias,o.depthScale):e.setFloat3(this._lightShadowUniformName,0,0,0)),this.shadowDepthRange)if(o&&n.activeCamera){var a=r;e.setFloat2(this._lightShadowExtraUniformName,a.getDepthMinZ(n.activeCamera),a.getDepthMinZ(n.activeCamera)+a.getDepthMaxZ(n.activeCamera))}else e.setFloat2(this._lightShadowExtraUniformName,0,0)}},t.prototype.prepareDefines=function(e,t,i){if(i._areLightsDirty||this._forcePrepareDefines){this._forcePrepareDefines=!1;var r=this.light;i.setValue(this._lightTypeDefineName,!!(r&&r instanceof Sv),!0)}},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t),t.sharedData.bindableBlocks.push(this),t.sharedData.blocksWithDefines.push(this);var i=this.direction,r=this.color,n=this.intensity,o=this.shadowBias,a=this.shadowNormalBias,s=this.shadowDepthScale,l=this.shadowDepthRange;return this._lightDataUniformName=t._getFreeVariableName("lightData"),this._lightColorUniformName=t._getFreeVariableName("lightColor"),this._lightShadowUniformName=t._getFreeVariableName("shadowData"),this._lightShadowExtraUniformName=t._getFreeVariableName("shadowExtraData"),this._lightTypeDefineName=t._getFreeDefineName("LIGHTPOINTTYPE"),t._emitUniformFromString(this._lightDataUniformName,Ns.Vector3),t._emitUniformFromString(this._lightColorUniformName,Ns.Vector4),t.compilationString+="#ifdef ".concat(this._lightTypeDefineName,"\n"),t.compilationString+=t._declareOutput(i)+" = normalize(".concat(this.worldPosition.associatedVariableName,".xyz - ").concat(this._lightDataUniformName,");\n"),t.compilationString+="#else\n",t.compilationString+=t._declareOutput(i)+" = ".concat(this._lightDataUniformName,";\n"),t.compilationString+="#endif\n",t.compilationString+=t._declareOutput(r)+" = ".concat(this._lightColorUniformName,".rgb;\n"),t.compilationString+=t._declareOutput(n)+" = ".concat(this._lightColorUniformName,".a;\n"),(o.hasEndpoints||a.hasEndpoints||s.hasEndpoints)&&(t._emitUniformFromString(this._lightShadowUniformName,Ns.Vector3),o.hasEndpoints&&(t.compilationString+=t._declareOutput(o)+" = ".concat(this._lightShadowUniformName,".x;\n")),a.hasEndpoints&&(t.compilationString+=t._declareOutput(a)+" = ".concat(this._lightShadowUniformName,".y;\n")),s.hasEndpoints&&(t.compilationString+=t._declareOutput(s)+" = ".concat(this._lightShadowUniformName,".z;\n"))),l.hasEndpoints&&(t._emitUniformFromString(this._lightShadowExtraUniformName,Ns.Vector2),t.compilationString+=t._declareOutput(l)+" = ".concat(this._lightShadowUniformName,";\n")),this},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return this.light&&(t.lightId=this.light.id),t},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),t.lightId&&(this.light=i.getLightById(t.lightId))},t}(Ws);a("BABYLON.LightInformationBlock",$y);var eb=function(e){function t(t){var i=e.call(this,t,Fs.Fragment)||this;return i.convertInputToLinearSpace=!0,i.registerInput("color",Ns.AutoDetect),i.registerOutput("output",Ns.Color4),i.registerOutput("rgb",Ns.Color3),i._inputs[0].addExcludedConnectionPointFromAllowedTypes(Ns.Color3|Ns.Color4|Ns.Vector3|Ns.Vector4),i}return m(t,e),t.prototype.getClassName=function(){return"ImageProcessingBlock"},Object.defineProperty(t.prototype,"color",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rgb",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),t.prototype.initialize=function(e){e._excludeVariableName("exposureLinear"),e._excludeVariableName("contrast"),e._excludeVariableName("vInverseScreenSize"),e._excludeVariableName("vignetteSettings1"),e._excludeVariableName("vignetteSettings2"),e._excludeVariableName("vCameraColorCurveNegative"),e._excludeVariableName("vCameraColorCurveNeutral"),e._excludeVariableName("vCameraColorCurvePositive"),e._excludeVariableName("txColorTransform"),e._excludeVariableName("colorTransformSettings"),e._excludeVariableName("ditherIntensity")},t.prototype.isReady=function(e,t,i){return!(i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())},t.prototype.prepareDefines=function(e,t,i){i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i)},t.prototype.bind=function(e,t,i){i&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)},t.prototype._buildBlock=function(t){var i;e.prototype._buildBlock.call(this,t),t.sharedData.blocksWithDefines.push(this),t.sharedData.blockingBlocks.push(this),t.sharedData.bindableBlocks.push(this),t.uniforms.push("exposureLinear"),t.uniforms.push("contrast"),t.uniforms.push("vInverseScreenSize"),t.uniforms.push("vignetteSettings1"),t.uniforms.push("vignetteSettings2"),t.uniforms.push("vCameraColorCurveNegative"),t.uniforms.push("vCameraColorCurveNeutral"),t.uniforms.push("vCameraColorCurvePositive"),t.uniforms.push("txColorTransform"),t.uniforms.push("colorTransformSettings"),t.uniforms.push("ditherIntensity");var r=this.color,n=this._outputs[0],o="//".concat(this.name);return t._emitFunctionFromInclude("helperFunctions",o),t._emitFunctionFromInclude("imageProcessingDeclaration",o),t._emitFunctionFromInclude("imageProcessingFunctions",o),(null===(i=r.connectedPoint)||void 0===i?void 0:i.isConnected)&&(r.connectedPoint.type===Ns.Color4||r.connectedPoint.type===Ns.Vector4?t.compilationString+="".concat(t._declareOutput(n)," = ").concat(r.associatedVariableName,";\n"):t.compilationString+="".concat(t._declareOutput(n)," = vec4(").concat(r.associatedVariableName,", 1.0);\n"),t.compilationString+="#ifdef IMAGEPROCESSINGPOSTPROCESS\n",this.convertInputToLinearSpace&&(t.compilationString+="".concat(n.associatedVariableName,".rgb = toLinearSpace(").concat(r.associatedVariableName,".rgb);\n")),t.compilationString+="#else\n",t.compilationString+="#ifdef IMAGEPROCESSING\n",this.convertInputToLinearSpace&&(t.compilationString+="".concat(n.associatedVariableName,".rgb = toLinearSpace(").concat(r.associatedVariableName,".rgb);\n")),t.compilationString+="".concat(n.associatedVariableName," = applyImageProcessing(").concat(n.associatedVariableName,");\n"),t.compilationString+="#endif\n",t.compilationString+="#endif\n",this.rgb.hasEndpoints&&(t.compilationString+=t._declareOutput(this.rgb)+" = ".concat(this.output.associatedVariableName,".xyz;\n"))),this},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".convertInputToLinearSpace = ").concat(this.convertInputToLinearSpace,";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.convertInputToLinearSpace=this.convertInputToLinearSpace,t},t.prototype._deserialize=function(t,i,r){var n;e.prototype._deserialize.call(this,t,i,r),this.convertInputToLinearSpace=null===(n=t.convertInputToLinearSpace)||void 0===n||n},v([Ys("Convert input to linear space",Xs.Boolean,"ADVANCED")],t.prototype,"convertInputToLinearSpace",void 0),t}(Ws);a("BABYLON.ImageProcessingBlock",eb);var tb=function(e){function t(i){var r=e.call(this,i,Fs.Fragment,!0)||this;return r.registerInput("normal",Ns.AutoDetect,!1),r.normal.addExcludedConnectionPointFromAllowedTypes(Ns.Color4|Ns.Vector4|Ns.Vector3),r.registerInput("tangent",Ns.Vector4,!1),r.registerInput("world",Ns.Matrix,!1),r.registerOutput("TBN",Ns.Object,Fs.Fragment,new Qy("TBN",r,Us.Output,t,"TBNBlock")),r.registerOutput("row0",Ns.Vector3,Fs.Fragment),r.registerOutput("row1",Ns.Vector3,Fs.Fragment),r.registerOutput("row2",Ns.Vector3,Fs.Fragment),r}return m(t,e),t.prototype.getClassName=function(){return"TBNBlock"},t.prototype.initialize=function(e){e._excludeVariableName("tbnNormal"),e._excludeVariableName("tbnTangent"),e._excludeVariableName("tbnBitangent"),e._excludeVariableName("TBN")},Object.defineProperty(t.prototype,"normal",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"tangent",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"world",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"TBN",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"row0",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"row1",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"row2",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){return Fs.Fragment},set:function(e){},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(e,t){if(void 0===t&&(t=function(){return!0}),!this.world.isConnected){var i=e.getInputBlockByPredicate((function(e){return e.isSystemValue&&e.systemValue===Qs.World&&t(e)}));i||(i=new rl("world")).setAsSystemValue(Qs.World),i.output.connectTo(this.world)}if(!this.normal.isConnected){var r=e.getInputBlockByPredicate((function(e){return e.isAttribute&&"normal"===e.name&&t(e)}));r||(r=new rl("normal")).setAsAttribute("normal"),r.output.connectTo(this.normal)}if(!this.tangent.isConnected){var n=e.getInputBlockByPredicate((function(e){return e.isAttribute&&"tangent"===e.name&&e.type===Ns.Vector4&&t(e)}));n||(n=new rl("tangent")).setAsAttribute("tangent"),n.output.connectTo(this.tangent)}},t.prototype.prepareDefines=function(e,t,i){var r,n,o,a,s=this.normal,l=this.tangent,c=s.isConnected;(null===(r=s.connectInputBlock)||void 0===r?void 0:r.isAttribute)&&!e.isVerticesDataPresent(null===(n=s.connectInputBlock)||void 0===n?void 0:n.name)&&(c=!1);var u=l.isConnected;(null===(o=l.connectInputBlock)||void 0===o?void 0:o.isAttribute)&&!e.isVerticesDataPresent(null===(a=l.connectInputBlock)||void 0===a?void 0:a.name)&&(u=!1);var h=c&&u;i.setValue("TBNBLOCK",h,!0)},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this.normal,r=this.tangent,n=this.world,o=this.TBN,a=this.row0,s=this.row1,l=this.row2;return t.target===Fs.Fragment&&(t.compilationString+="\n // ".concat(this.name,"\n vec3 tbnNormal = normalize(").concat(i.associatedVariableName,").xyz;\n vec3 tbnTangent = normalize(").concat(r.associatedVariableName,".xyz);\n vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ").concat(r.associatedVariableName,".w;\n mat3 ").concat(o.associatedVariableName," = mat3(").concat(n.associatedVariableName,") * mat3(tbnTangent, tbnBitangent, tbnNormal);\n "),a.hasEndpoints&&(t.compilationString+=t._declareOutput(a)+" = vec3(".concat(o.associatedVariableName,"[0][0], ").concat(o.associatedVariableName,"[0][1], ").concat(o.associatedVariableName,"[0][2]);\n")),s.hasEndpoints&&(t.compilationString+=t._declareOutput(s)+" = vec3(".concat(o.associatedVariableName,"[1[0], ").concat(o.associatedVariableName,"[1][1], ").concat(o.associatedVariableName,"[1][2]);\n")),l.hasEndpoints&&(t.compilationString+=t._declareOutput(l)+" = vec3(".concat(o.associatedVariableName,"[2][0], ").concat(o.associatedVariableName,"[2][1], ").concat(o.associatedVariableName,"[2][2]);\n")),t.sharedData.blocksWithDefines.push(this)),this},t}(Ws);a("BABYLON.TBNBlock",tb);var ib=function(e){function t(t){var i=e.call(this,t,Fs.Fragment)||this;return i._tangentSpaceParameterName="",i._tangentCorrectionFactorName="",i._worldMatrixName="",i.invertX=!1,i.invertY=!1,i.useParallaxOcclusion=!1,i.useObjectSpaceNormalMap=!1,i._isUnique=!0,i.registerInput("worldPosition",Ns.Vector4,!1),i.registerInput("worldNormal",Ns.Vector4,!1),i.registerInput("worldTangent",Ns.Vector4,!0),i.registerInput("uv",Ns.Vector2,!1),i.registerInput("normalMapColor",Ns.Color3,!1),i.registerInput("strength",Ns.Float,!1),i.registerInput("viewDirection",Ns.Vector3,!0),i.registerInput("parallaxScale",Ns.Float,!0),i.registerInput("parallaxHeight",Ns.Float,!0),i.registerInput("TBN",Ns.Object,!0,Fs.VertexAndFragment,new Qy("TBN",i,Us.Input,tb,"TBNBlock")),i.registerInput("world",Ns.Matrix,!0),i.registerOutput("output",Ns.Vector4),i.registerOutput("uvOffset",Ns.Vector2),i}return m(t,e),t.prototype.getClassName=function(){return"PerturbNormalBlock"},Object.defineProperty(t.prototype,"worldPosition",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"worldNormal",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"worldTangent",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"uv",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"normalMapColor",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"strength",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"viewDirection",{get:function(){return this._inputs[6]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"parallaxScale",{get:function(){return this._inputs[7]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"parallaxHeight",{get:function(){return this._inputs[8]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"TBN",{get:function(){return this._inputs[9]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"world",{get:function(){return this._inputs[10]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"uvOffset",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),t.prototype.prepareDefines=function(e,t,i){var r=this.normalMapColor.connectedPoint._ownerBlock.samplerName,n=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&r||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",n,!0),i.setValue("PARALLAX_RHS",t.getScene().useRightHandedSystem,!0),i.setValue("PARALLAXOCCLUSION",this.useParallaxOcclusion,!0),i.setValue("OBJECTSPACE_NORMALMAP",this.useObjectSpaceNormalMap,!0)},t.prototype.bind=function(e,t,i){t.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1),i&&(e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1),this.useObjectSpaceNormalMap&&!this.world.isConnected&&e.setMatrix(this._worldMatrixName,i.getWorldMatrix()))},t.prototype.autoConfigure=function(e,t){if(void 0===t&&(t=function(){return!0}),!this.uv.isConnected){var i=e.getInputBlockByPredicate((function(e){return e.isAttribute&&"uv"===e.name&&t(e)}));i||(i=new rl("uv")).setAsAttribute(),i.output.connectTo(this.uv)}if(!this.strength.isConnected){var r=new rl("strength");r.value=1,r.output.connectTo(this.strength)}},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i="//".concat(this.name),r=this.uv,n=this.worldPosition,o=this.worldNormal,a=this.worldTangent;t.sharedData.blocksWithDefines.push(this),t.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=t._getFreeDefineName("tangentSpaceParameter"),t._emitUniformFromString(this._tangentSpaceParameterName,Ns.Vector2),this._tangentCorrectionFactorName=t._getFreeDefineName("tangentCorrectionFactor"),t._emitUniformFromString(this._tangentCorrectionFactorName,Ns.Float),this._worldMatrixName=t._getFreeDefineName("perturbNormalWorldMatrix"),t._emitUniformFromString(this._worldMatrixName,Ns.Matrix);var s=null;this.normalMapColor.connectedPoint&&(s=this.normalMapColor.connectedPoint._ownerBlock.samplerName);var l=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&s||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),c=this.parallaxScale.isConnectedToInputBlock?this.parallaxScale.connectInputBlock.isConstant?t._emitFloat(this.parallaxScale.connectInputBlock.value):this.parallaxScale.associatedVariableName:"0.05",u=this.strength.isConnectedToInputBlock&&this.strength.connectInputBlock.isConstant?"\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n".concat(t._emitFloat(this.strength.connectInputBlock.value)):"\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n".concat(this.strength.associatedVariableName);t._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");var h={search:/defined\(TANGENT\)/g,replace:a.isConnected?"defined(TANGENT)":"defined(IGNORE)"},d=this.TBN;d.isConnected?t.compilationString+="\n #ifdef TBNBLOCK\n mat3 vTBN = ".concat(d.associatedVariableName,";\n #endif\n "):a.isConnected&&(t.compilationString+="vec3 tbnNormal = normalize(".concat(o.associatedVariableName,".xyz);\n"),t.compilationString+="vec3 tbnTangent = normalize(".concat(a.associatedVariableName,".xyz);\n"),t.compilationString+="vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ".concat(this._tangentCorrectionFactorName,";\n"),t.compilationString+="mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\n"),t._emitFunctionFromInclude("bumpFragmentMainFunctions",i,{replaceStrings:[h,{search:/varying mat3 vTBN;/g,replace:""},{search:/uniform mat4 normalMatrix;/g,replace:""}]}),t._emitFunctionFromInclude("bumpFragmentFunctions",i,{replaceStrings:[{search:/#include<samplerFragmentDeclaration>\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,replace:""},{search:/uniform sampler2D bumpSampler;/g,replace:""},{search:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,replace:"#define inline\nvec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)"},{search:/vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g,replace:"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)"},{search:/texture2D\(bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});var p=l&&s?"texture2D(".concat(s,", ").concat(r.associatedVariableName," + uvOffset).xyz"):this.normalMapColor.associatedVariableName;return t.compilationString+=t._declareOutput(this.output)+" = vec4(0.);\n",t.compilationString+=t._emitCodeFromInclude("bumpFragment",i,{replaceStrings:[{search:/texture2D\(bumpSampler,vBumpUV\)/g,replace:"".concat(p)},{search:/#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,replace:"mat4 normalMatrix = toNormalMatrix(".concat(this.world.isConnected?this.world.associatedVariableName:this._worldMatrixName,");")},{search:/perturbNormal\(TBN,texture2D\(bumpSampler,vBumpUV\+uvOffset\).xyz,vBumpInfos.y\)/g,replace:"perturbNormal(TBN, ".concat(p,", vBumpInfos.y)")},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:"parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ".concat(l&&this.useParallaxOcclusion?s:"bumpSampler",")")},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:"parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ".concat(l?this.parallaxHeight.associatedVariableName:"0.",")")},{search:/vTangentSpaceParams/g,replace:this._tangentSpaceParameterName},{search:/vBumpInfos.y/g,replace:u},{search:/vBumpInfos.z/g,replace:c},{search:/vBumpUV/g,replace:r.associatedVariableName},{search:/vPositionW/g,replace:n.associatedVariableName+".xyz"},{search:/normalW=/g,replace:this.output.associatedVariableName+".xyz = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:"mat3(normalMatrix) * "+this.output.associatedVariableName+".xyz"},{search:/normalW/g,replace:o.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:l?this.viewDirection.associatedVariableName:"vec3(0.)"},h]}),this},t.prototype._dumpPropertiesCode=function(){var t=e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".invertX = ").concat(this.invertX,";\n");return t+="".concat(this._codeVariableName,".invertY = ").concat(this.invertY,";\n"),(t+="".concat(this._codeVariableName,".useParallaxOcclusion = ").concat(this.useParallaxOcclusion,";\n"))+"".concat(this._codeVariableName,".useObjectSpaceNormalMap = ").concat(this.useObjectSpaceNormalMap,";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.invertX=this.invertX,t.invertY=this.invertY,t.useParallaxOcclusion=this.useParallaxOcclusion,t.useObjectSpaceNormalMap=this.useObjectSpaceNormalMap,t},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),this.invertX=t.invertX,this.invertY=t.invertY,this.useParallaxOcclusion=!!t.useParallaxOcclusion,this.useObjectSpaceNormalMap=!!t.useObjectSpaceNormalMap},v([Ys("Invert X axis",Xs.Boolean,"PROPERTIES",{notifiers:{update:!1}})],t.prototype,"invertX",void 0),v([Ys("Invert Y axis",Xs.Boolean,"PROPERTIES",{notifiers:{update:!1}})],t.prototype,"invertY",void 0),v([Ys("Use parallax occlusion",Xs.Boolean)],t.prototype,"useParallaxOcclusion",void 0),v([Ys("Object Space Mode",Xs.Boolean,"PROPERTIES",{notifiers:{update:!1}})],t.prototype,"useObjectSpaceNormalMap",void 0),t}(Ws);a("BABYLON.PerturbNormalBlock",ib);var rb=function(e){function t(t){var i=e.call(this,t,Fs.Fragment,!0)||this;return i.registerInput("value",Ns.Float,!0),i.registerInput("cutoff",Ns.Float,!0),i}return m(t,e),t.prototype.getClassName=function(){return"DiscardBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cutoff",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),t.sharedData.hints.needAlphaTesting=!0,this.cutoff.isConnected&&this.value.isConnected)return t.compilationString+="if (".concat(this.value.associatedVariableName," < ").concat(this.cutoff.associatedVariableName,") discard;\n"),this},t}(Ws);a("BABYLON.DiscardBlock",rb);var nb=function(e){function t(t){var i=e.call(this,t,Fs.Fragment)||this;return i.registerOutput("output",Ns.Float,Fs.Fragment),i}return m(t,e),t.prototype.getClassName=function(){return"FrontFacingBlock"},Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),t.target===Fs.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = gl_FrontFacing ? 1.0 : 0.0;\n",this},t}(Ws);a("BABYLON.FrontFacingBlock",nb);var ob=function(e){function t(t){var i=e.call(this,t,Fs.Fragment)||this;return i.registerInput("input",Ns.AutoDetect,!1),i.registerOutput("dx",Ns.BasedOnInput),i.registerOutput("dy",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._outputs[1]._typeConnectionSource=i._inputs[0],i}return m(t,e),t.prototype.getClassName=function(){return"DerivativeBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dx",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dy",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],r=this._outputs[1];t._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");var n="dFdx",o="dFdy";return t.shaderLanguage===pt.WGSL&&(n="dpdx",o="dpdy"),i.hasEndpoints&&(t.compilationString+=t._declareOutput(i)+" = ".concat(n,"(").concat(this.input.associatedVariableName,");\n")),r.hasEndpoints&&(t.compilationString+=t._declareOutput(r)+" = ".concat(o,"(").concat(this.input.associatedVariableName,");\n")),this},t}(Ws);a("BABYLON.DerivativeBlock",ob);var ab=function(e){function t(t){var i=e.call(this,t,Fs.Fragment)||this;return i.registerOutput("xy",Ns.Vector2,Fs.Fragment),i.registerOutput("xyz",Ns.Vector3,Fs.Fragment),i.registerOutput("xyzw",Ns.Vector4,Fs.Fragment),i.registerOutput("x",Ns.Float,Fs.Fragment),i.registerOutput("y",Ns.Float,Fs.Fragment),i.registerOutput("z",Ns.Float,Fs.Fragment),i.registerOutput("w",Ns.Float,Fs.Fragment),i}return m(t,e),t.prototype.getClassName=function(){return"FragCoordBlock"},Object.defineProperty(t.prototype,"xy",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xyz",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xyzw",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"x",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"y",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"z",{get:function(){return this._outputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[6]},enumerable:!1,configurable:!0}),t.prototype.writeOutputs=function(e){for(var t="",i=0,r=this._outputs;i<r.length;i++){var n=r[i];n.hasEndpoints&&(t+="".concat(e._declareOutput(n)," = gl_FragCoord.").concat(n.name,";\n"))}return t},t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),t.target===Fs.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return t.compilationString+=this.writeOutputs(t),this},t}(Ws);a("BABYLON.FragCoordBlock",ab);var sb=function(e){function t(t){var i=e.call(this,t,Fs.Fragment)||this;return i.registerOutput("xy",Ns.Vector2,Fs.Fragment),i.registerOutput("x",Ns.Float,Fs.Fragment),i.registerOutput("y",Ns.Float,Fs.Fragment),i}return m(t,e),t.prototype.getClassName=function(){return"ScreenSizeBlock"},Object.defineProperty(t.prototype,"xy",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"x",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"y",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),t.prototype.bind=function(e){var t=this._scene.getEngine();e.setFloat2(this._varName,t.getRenderWidth(),t.getRenderHeight())},t.prototype.writeOutputs=function(e,t){for(var i="",r=0,n=this._outputs;r<n.length;r++){var o=n[r];o.hasEndpoints&&(i+="".concat(e._declareOutput(o)," = ").concat(t,".").concat(o.name,";\n"))}return i},t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),this._scene=t.sharedData.scene,t.target===Fs.Vertex)throw"ScreenSizeBlock must only be used in a fragment shader";return t.sharedData.bindableBlocks.push(this),this._varName=t._getFreeVariableName("screenSize"),t._emitUniformFromString(this._varName,Ns.Vector2),t.compilationString+=this.writeOutputs(t,this._varName),this},t}(Ws);a("BABYLON.ScreenSizeBlock",sb);var lb=function(e){function t(t){var i=e.call(this,t,Fs.Fragment)||this;return i.registerInput("vector",Ns.AutoDetect),i.registerInput("worldViewProjection",Ns.Matrix),i.registerOutput("output",Ns.Vector2),i.registerOutput("x",Ns.Float),i.registerOutput("y",Ns.Float),i.inputs[0].addExcludedConnectionPointFromAllowedTypes(Ns.Color3|Ns.Vector3|Ns.Vector4),i}return m(t,e),t.prototype.getClassName=function(){return"ScreenSpaceBlock"},Object.defineProperty(t.prototype,"vector",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"worldViewProjection",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"x",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"y",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(e,t){if(void 0===t&&(t=function(){return!0}),!this.worldViewProjection.isConnected){var i=e.getInputBlockByPredicate((function(e){return e.systemValue===Qs.WorldViewProjection&&t(e)}));i||(i=new rl("worldViewProjection")).setAsSystemValue(Qs.WorldViewProjection),i.output.connectTo(this.worldViewProjection)}},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this.vector,r=this.worldViewProjection;if(i.connectedPoint){var n=r.associatedVariableName,o=t._getFreeVariableName("screenSpaceTemp");switch(i.connectedPoint.type){case Ns.Vector3:t.compilationString+="vec4 ".concat(o," = ").concat(n," * vec4(").concat(i.associatedVariableName,", 1.0);\n");break;case Ns.Vector4:t.compilationString+="vec4 ".concat(o," = ").concat(n," * ").concat(i.associatedVariableName,";\n")}return t.compilationString+="".concat(o,".xy /= ").concat(o,".w;"),t.compilationString+="".concat(o,".xy = ").concat(o,".xy * 0.5 + vec2(0.5, 0.5);"),this.output.hasEndpoints&&(t.compilationString+=t._declareOutput(this.output)+" = ".concat(o,".xy;\n")),this.x.hasEndpoints&&(t.compilationString+=t._declareOutput(this.x)+" = ".concat(o,".x;\n")),this.y.hasEndpoints&&(t.compilationString+=t._declareOutput(this.y)+" = ".concat(o,".y;\n")),this}},t}(Ws);a("BABYLON.ScreenSpaceBlock",lb);var cb=function(e){function t(t){var i=e.call(this,t,Fs.Fragment)||this;return i.registerInput("input",Ns.Vector2),i.registerInput("strength",Ns.Float),i.registerInput("center",Ns.Vector2),i.registerInput("offset",Ns.Vector2),i.registerOutput("output",Ns.Vector2),i.registerOutput("x",Ns.Float),i.registerOutput("y",Ns.Float),i}return m(t,e),t.prototype.getClassName=function(){return"TwirlBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"strength",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"center",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"offset",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"x",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"y",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(){if(!this.center.isConnected){var e=new rl("center");e.value=new U(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){var t=new rl("strength");t.value=1,t.output.connectTo(this.strength)}if(!this.offset.isConnected){var i=new rl("offset");i.value=new U(0,0),i.output.connectTo(this.offset)}},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=t._getFreeVariableName("delta"),r=t._getFreeVariableName("angle"),n=t._getFreeVariableName("x"),o=t._getFreeVariableName("y"),a=t._getFreeVariableName("result");return t.compilationString+=" \n ".concat(t._declareLocalVar(i,Ns.Vector2)," = ").concat(this.input.associatedVariableName," - ").concat(this.center.associatedVariableName,";\n ").concat(t._declareLocalVar(r,Ns.Float)," = ").concat(this.strength.associatedVariableName," * length(").concat(i,");\n ").concat(t._declareLocalVar(n,Ns.Float)," = cos(").concat(r,") * ").concat(i,".x - sin(").concat(r,") * ").concat(i,".y;\n ").concat(t._declareLocalVar(o,Ns.Float)," = sin(").concat(r,") * ").concat(i,".x + cos(").concat(r,") * ").concat(i,".y;\n ").concat(t._declareLocalVar(a,Ns.Vector2)," = vec2(").concat(n," + ").concat(this.center.associatedVariableName,".x + ").concat(this.offset.associatedVariableName,".x, ").concat(o," + ").concat(this.center.associatedVariableName,".y + ").concat(this.offset.associatedVariableName,".y);\n "),this.output.hasEndpoints&&(t.compilationString+=t._declareOutput(this.output)+" = ".concat(a,";\n")),this.x.hasEndpoints&&(t.compilationString+=t._declareOutput(this.x)+" = ".concat(a,".x;\n")),this.y.hasEndpoints&&(t.compilationString+=t._declareOutput(this.y)+" = ".concat(a,".y;\n")),this},t}(Ws);a("BABYLON.TwirlBlock",cb);var ub=function(e){function t(t){var i=e.call(this,t,Fs.Fragment)||this;return i.generateInWorldSpace=!1,i.automaticNormalizationNormal=!0,i.automaticNormalizationTangent=!0,i.registerInput("input",Ns.Float),i.registerInput("worldPosition",Ns.Vector3),i.registerInput("worldNormal",Ns.Vector3),i.registerInput("worldTangent",Ns.AutoDetect,!0),i.registerOutput("output",Ns.Vector4),i.registerOutput("xyz",Ns.Vector3),i._inputs[3].addExcludedConnectionPointFromAllowedTypes(Ns.Color3|Ns.Vector3|Ns.Vector4),i}return m(t,e),t.prototype.getClassName=function(){return"HeightToNormalBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"worldPosition",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"worldNormal",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"worldTangent",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xyz",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];this.generateInWorldSpace||this.worldTangent.isConnected||ae.Error("You must connect the 'worldTangent' input of the ".concat(this.name," block!"));var r=this.generateInWorldSpace?"":"\n vec3 biTangent = cross(normal, tangent);\n mat3 TBN = mat3(tangent, biTangent, normal);\n ",n=this.generateInWorldSpace?"":"\n result = TBN * result;\n result = result * vec3(0.5) + vec3(0.5);\n ",o="\n vec4 heightToNormal(in float height, in vec3 position, in vec3 tangent, in vec3 normal) {\n ".concat(this.automaticNormalizationTangent?"tangent = normalize(tangent);":"","\n ").concat(this.automaticNormalizationNormal?"normal = normalize(normal);":"","\n ").concat(r,"\n vec3 worlddX = dFdx(position);\n vec3 worlddY = dFdy(position);\n vec3 crossX = cross(normal, worlddX);\n vec3 crossY = cross(normal, worlddY);\n float d = abs(dot(crossY, worlddX));\n vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d));\n inToNormal.y *= -1.0;\n vec3 result = normalize((d * normal) - inToNormal);\n ").concat(n,"\n return vec4(result, 0.);\n }");return t._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),t._emitFunction("heightToNormal",o,"// heightToNormal"),t.compilationString+=t._declareOutput(i)+" = heightToNormal(".concat(this.input.associatedVariableName,", ").concat(this.worldPosition.associatedVariableName,", ").concat(this.worldTangent.isConnected?this.worldTangent.associatedVariableName:"vec3(0.)",".xyz, ").concat(this.worldNormal.associatedVariableName,");\n"),this.xyz.hasEndpoints&&(t.compilationString+=t._declareOutput(this.xyz)+" = ".concat(this.output.associatedVariableName,".xyz;\n")),this},t.prototype._dumpPropertiesCode=function(){var t=e.prototype._dumpPropertiesCode.call(this);return t+="".concat(this._codeVariableName,".generateInWorldSpace = ").concat(this.generateInWorldSpace,";\n"),(t+="".concat(this._codeVariableName,".automaticNormalizationNormal = ").concat(this.automaticNormalizationNormal,";\n"))+"".concat(this._codeVariableName,".automaticNormalizationTangent = ").concat(this.automaticNormalizationTangent,";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.generateInWorldSpace=this.generateInWorldSpace,t.automaticNormalizationNormal=this.automaticNormalizationNormal,t.automaticNormalizationTangent=this.automaticNormalizationTangent,t},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),this.generateInWorldSpace=t.generateInWorldSpace,this.automaticNormalizationNormal=t.automaticNormalizationNormal,this.automaticNormalizationTangent=t.automaticNormalizationTangent},v([Ys("Generate in world space instead of tangent space",Xs.Boolean,"PROPERTIES",{notifiers:{update:!0}})],t.prototype,"generateInWorldSpace",void 0),v([Ys("Force normalization for the worldNormal input",Xs.Boolean,"PROPERTIES",{notifiers:{update:!0}})],t.prototype,"automaticNormalizationNormal",void 0),v([Ys("Force normalization for the worldTangent input",Xs.Boolean,"PROPERTIES",{notifiers:{update:!0}})],t.prototype,"automaticNormalizationTangent",void 0),t}(Ws);a("BABYLON.HeightToNormalBlock",ub);var hb=function(e){function t(t){var i=e.call(this,t,Fs.Fragment,!0)||this;return i.registerInput("depth",Ns.Float,!0),i.registerInput("worldPos",Ns.Vector4,!0),i.registerInput("viewProjection",Ns.Matrix,!0),i}return m(t,e),t.prototype.getClassName=function(){return"FragDepthBlock"},Object.defineProperty(t.prototype,"depth",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"worldPos",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"viewProjection",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){return e.prototype._buildBlock.call(this,t),this.depth.isConnected?t.compilationString+="gl_FragDepth = ".concat(this.depth.associatedVariableName,";\n"):this.worldPos.isConnected&&this.viewProjection.isConnected?t.compilationString+="\n vec4 p = ".concat(this.viewProjection.associatedVariableName," * ").concat(this.worldPos.associatedVariableName,";\n float v = p.z / p.w;\n #ifndef IS_NDC_HALF_ZRANGE\n v = v * 0.5 + 0.5;\n #endif\n gl_FragDepth = v;\n \n "):ae.Warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this},t}(Ws);a("BABYLON.FragDepthBlock",hb);var db=function(e){function t(t){var i=e.call(this,t,Fs.Fragment)||this;return i.registerInput("worldPosition",Ns.Vector4,!1),i.registerInput("viewProjection",Ns.Matrix,!1),i.registerInput("worldNormal",Ns.AutoDetect,!0),i.registerOutput("depth",Ns.Vector3),i.worldNormal.addExcludedConnectionPointFromAllowedTypes(Ns.Color3|Ns.Vector3|Ns.Vector4),i}return m(t,e),t.prototype.getClassName=function(){return"ShadowMapBlock"},t.prototype.initialize=function(e){e._excludeVariableName("vPositionWSM"),e._excludeVariableName("lightDataSM"),e._excludeVariableName("biasAndScaleSM"),e._excludeVariableName("depthValuesSM"),e._excludeVariableName("clipPos"),e._excludeVariableName("worldPos"),e._excludeVariableName("zSM")},Object.defineProperty(t.prototype,"worldPosition",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"viewProjection",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"worldNormal",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"depth",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i="//".concat(this.name);return t._emitUniformFromString("biasAndScaleSM",Ns.Vector3),t._emitUniformFromString("lightDataSM",Ns.Vector3),t._emitUniformFromString("depthValuesSM",Ns.Vector3),t._emitFunctionFromInclude("packingFunctions",i),t.compilationString+="vec4 worldPos = ".concat(this.worldPosition.associatedVariableName,";\n"),t.compilationString+="vec3 vPositionWSM;\n",t.compilationString+="float vDepthMetricSM = 0.0;\n",t.compilationString+="float zSM;\n",this.worldNormal.isConnected&&(t.compilationString+="vec3 vNormalW = ".concat(this.worldNormal.associatedVariableName,".xyz;\n"),t.compilationString+=t._emitCodeFromInclude("shadowMapVertexNormalBias",i)),t.compilationString+="vec4 clipPos = ".concat(this.viewProjection.associatedVariableName," * worldPos;\n"),t.compilationString+=t._emitCodeFromInclude("shadowMapVertexMetric",i,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"}]}),t.compilationString+=t._emitCodeFromInclude("shadowMapFragment",i,{replaceStrings:[{search:/return;/g,replace:""}]}),t.compilationString+="\n #if SM_DEPTHTEXTURE == 1\n #ifdef IS_NDC_HALF_ZRANGE\n gl_FragDepth = (clipPos.z / clipPos.w);\n #else\n gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5;\n #endif\n #endif\n ",t.compilationString+="".concat(t._declareOutput(this.depth)," = vec3(depthSM, 1., 1.);\n"),this},t}(Ws);a("BABYLON.ShadowMapBlock",db);var pb=function(e){function t(t){var i=e.call(this,t,Fs.Fragment,!0)||this;return i.registerInput("viewDepth",Ns.Float,!0),i.registerInput("worldPosition",Ns.AutoDetect,!0),i.registerInput("viewNormal",Ns.AutoDetect,!0),i.registerInput("reflectivity",Ns.AutoDetect,!0),i.inputs[1].addExcludedConnectionPointFromAllowedTypes(Ns.Vector3|Ns.Vector4),i.inputs[2].addExcludedConnectionPointFromAllowedTypes(Ns.Vector3|Ns.Vector4),i.inputs[3].addExcludedConnectionPointFromAllowedTypes(Ns.Vector3|Ns.Vector4|Ns.Color3|Ns.Color4),i}return m(t,e),t.prototype.getClassName=function(){return"PrePassOutputBlock"},Object.defineProperty(t.prototype,"viewDepth",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"worldPosition",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"viewNormal",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"reflectivity",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this.worldPosition,r=this.viewNormal,n=this.viewDepth,o=this.reflectivity;t.sharedData.blocksWithDefines.push(this);var a="//".concat(this.name);return t._emitFunctionFromInclude("helperFunctions",a),t.compilationString+="#if defined(PREPASS)\r\n",t.compilationString+="#ifdef PREPASS_DEPTH\r\n",n.connectedPoint?t.compilationString+=" gl_FragData[PREPASS_DEPTH_INDEX] = vec4(".concat(n.associatedVariableName,", 0.0, 0.0, 1.0);\r\n"):t.compilationString+=" gl_FragData[PREPASS_DEPTH_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",t.compilationString+="#endif\r\n",t.compilationString+="#ifdef PREPASS_POSITION\r\n",i.connectedPoint?t.compilationString+=" gl_FragData[PREPASS_POSITION_INDEX] = vec4(".concat(i.associatedVariableName,".rgb, ").concat(i.connectedPoint.type===Ns.Vector4?i.associatedVariableName+".a":"1.0",");\r\n"):t.compilationString+=" gl_FragData[PREPASS_POSITION_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",t.compilationString+="#endif\r\n",t.compilationString+="#ifdef PREPASS_NORMAL\r\n",r.connectedPoint?t.compilationString+=" gl_FragData[PREPASS_NORMAL_INDEX] = vec4(".concat(r.associatedVariableName,".rgb, ").concat(r.connectedPoint.type===Ns.Vector4?r.associatedVariableName+".a":"1.0",");\r\n"):t.compilationString+=" gl_FragData[PREPASS_NORMAL_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",t.compilationString+="#endif\r\n",t.compilationString+="#ifdef PREPASS_REFLECTIVITY\r\n",o.connectedPoint?t.compilationString+=" gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(".concat(o.associatedVariableName,".rgb, ").concat(o.connectedPoint.type===Ns.Vector4?o.associatedVariableName+".a":"1.0",");\r\n"):t.compilationString+=" gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(0.0, 0.0, 0.0, 1.0);\r\n",t.compilationString+="#endif\r\n",t.compilationString+="#endif\r\n",this},t}(Ws);a("BABYLON.PrePassOutputBlock",pb);var fb=function(e){function t(t){var i=e.call(this,t,Fs.VertexAndFragment,!1)||this;return i.registerInput("worldPosition",Ns.Vector4,!1,Fs.Vertex),i.registerInput("view",Ns.Matrix,!1,Fs.Vertex),i.registerInput("input",Ns.AutoDetect,!1,Fs.Fragment),i.registerInput("fogColor",Ns.AutoDetect,!1,Fs.Fragment),i.registerOutput("output",Ns.Color3,Fs.Fragment),i.input.addExcludedConnectionPointFromAllowedTypes(Ns.Color3|Ns.Vector3|Ns.Color4),i.fogColor.addExcludedConnectionPointFromAllowedTypes(Ns.Color3|Ns.Vector3|Ns.Color4),i}return m(t,e),t.prototype.getClassName=function(){return"FogBlock"},Object.defineProperty(t.prototype,"worldPosition",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"view",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"fogColor",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(e,t){if(void 0===t&&(t=function(){return!0}),!this.view.isConnected){var i=e.getInputBlockByPredicate((function(e){return e.systemValue===Qs.View&&t(e)}));i||(i=new rl("view")).setAsSystemValue(Qs.View),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){var r=e.getInputBlockByPredicate((function(e){return e.systemValue===Qs.FogColor&&t(e)}));r||(r=new rl("fogColor",void 0,Ns.Color3)).setAsSystemValue(Qs.FogColor),r.output.connectTo(this.fogColor)}},t.prototype.prepareDefines=function(e,t,i){var r=e.getScene();i.setValue("FOG",t.fogEnabled&&ha(e,r))},t.prototype.bind=function(e,t,i){if(i){var r=i.getScene();e.setFloat4(this._fogParameters,r.fogMode,r.fogStart,r.fogEnd,r.fogDensity)}},t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),t.target===Fs.Fragment){t.sharedData.blocksWithDefines.push(this),t.sharedData.bindableBlocks.push(this),t._emitFunctionFromInclude("fogFragmentDeclaration","//".concat(this.name),{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}]});var i=t._getFreeVariableName("fog"),r=this.input,n=this.fogColor;this._fogParameters=t._getFreeVariableName("fogParameters");var o=this._outputs[0];t._emitUniformFromString(this._fogParameters,Ns.Vector4),t.compilationString+="#ifdef FOG\n",t.compilationString+="float ".concat(i," = CalcFogFactor(").concat(this._fogDistanceName,", ").concat(this._fogParameters,");\n"),t.compilationString+=t._declareOutput(o)+" = ".concat(i," * ").concat(r.associatedVariableName,".rgb + (1.0 - ").concat(i,") * ").concat(n.associatedVariableName,".rgb;\n"),t.compilationString+="#else\n".concat(t._declareOutput(o)," = ").concat(r.associatedVariableName,".rgb;\n"),t.compilationString+="#endif\n"}else{var a=this.worldPosition,s=this.view;this._fogDistanceName=t._getFreeVariableName("vFogDistance"),t._emitVaryingFromString(this._fogDistanceName,Ns.Vector3),t.compilationString+="".concat(this._fogDistanceName," = (").concat(s.associatedVariableName," * ").concat(a.associatedVariableName,").xyz;\n")}return this},t}(Ws);a("BABYLON.FogBlock",fb);var _b=function(e){function t(t){var i=e.call(this,t,Fs.VertexAndFragment)||this;return i._lightId=0,i.generateOnlyFragmentCode=!1,i._isUnique=!0,i.registerInput("worldPosition",Ns.Vector4,!1,Fs.Vertex),i.registerInput("worldNormal",Ns.Vector4,!1,Fs.Fragment),i.registerInput("cameraPosition",Ns.Vector3,!1,Fs.Fragment),i.registerInput("glossiness",Ns.Float,!0,Fs.Fragment),i.registerInput("glossPower",Ns.Float,!0,Fs.Fragment),i.registerInput("diffuseColor",Ns.Color3,!0,Fs.Fragment),i.registerInput("specularColor",Ns.Color3,!0,Fs.Fragment),i.registerInput("view",Ns.Matrix,!0),i.registerOutput("diffuseOutput",Ns.Color3,Fs.Fragment),i.registerOutput("specularOutput",Ns.Color3,Fs.Fragment),i.registerOutput("shadow",Ns.Float,Fs.Fragment),i}return m(t,e),t._OnGenerateOnlyFragmentCodeChanged=function(e,t){var i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,ae.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)},t.prototype._setTarget=function(){this._setInitialTarget(this.generateOnlyFragmentCode?Fs.Fragment:Fs.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?Fs.Fragment:Fs.Vertex},t.prototype.getClassName=function(){return"LightBlock"},Object.defineProperty(t.prototype,"worldPosition",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"worldNormal",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraPosition",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"glossiness",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"glossPower",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"diffuseColor",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"specularColor",{get:function(){return this._inputs[6]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"view",{get:function(){return this._inputs[7]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"diffuseOutput",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"specularOutput",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"shadow",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(e,t){if(void 0===t&&(t=function(){return!0}),!this.cameraPosition.isConnected){var i=e.getInputBlockByPredicate((function(e){return e.systemValue===Qs.CameraPosition&&t(e)}));i||(i=new rl("cameraPosition")).setAsSystemValue(Qs.CameraPosition),i.output.connectTo(this.cameraPosition)}},t.prototype.prepareDefines=function(e,t,i){if(i._areLightsDirty){var r=e.getScene();if(this.light){var n={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};fa(r,e,this.light,this._lightId,i,!0,n),n.needRebuild&&i.rebuild()}else pa(r,e,i,!0,t.maxSimultaneousLights)}},t.prototype.updateUniformsAndSamples=function(e,t,i,r){for(var n=0;n<t.maxSimultaneousLights&&i["LIGHT"+n];n++){var o=e.uniforms.indexOf("vLightData"+n)>=0;xa(n,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+n],r,o)}},t.prototype.bind=function(e,t,i){if(i){var r=i.getScene();this.light?aa(this.light,this._lightId,r,e,!0):sa(r,i,e,!0,t.maxSimultaneousLights)}},t.prototype._injectVertexCode=function(e){var t=this.worldPosition,i="//".concat(this.name);this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));var r="v_"+t.associatedVariableName;e._emitVaryingFromString(r,Ns.Vector4)&&(e.compilationString+="".concat(r," = ").concat(t.associatedVariableName,";\n")),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+="vec4 worldPos = ".concat(t.associatedVariableName,";\n"),this.view.isConnected&&(e.compilationString+="mat4 view = ".concat(this.view.associatedVariableName,";\n")),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))},t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),t.target===Fs.Fragment){this.generateOnlyFragmentCode&&t.sharedData.dynamicUniformBlocks.push(this),t.sharedData.forcedBindableBlocks.push(this),t.sharedData.blocksWithDefines.push(this);var i="//".concat(this.name),r=this.worldPosition,n=r.associatedVariableName;this.generateOnlyFragmentCode?(n=t._getFreeVariableName("globalWorldPos"),t._emitFunction("light_globalworldpos","vec3 ".concat(n,";\n"),i),t.compilationString+="".concat(n," = ").concat(r.associatedVariableName,".xyz;\n"),t.compilationString+=t._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"worldPos,".concat(r.associatedVariableName):void 0})):n="v_"+n+".xyz",t._emitFunctionFromInclude("helperFunctions",i),t._emitFunctionFromInclude("lightsFragmentFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:n}]}),t._emitFunctionFromInclude("shadowsFragmentFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:n}]}),this.light?t._emitFunctionFromInclude(t.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):t._emitFunctionFromInclude(t.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),0===this._lightId&&(t._registerTempVariable("viewDirectionW")&&(t.compilationString+="vec3 viewDirectionW = normalize(".concat(this.cameraPosition.associatedVariableName," - ").concat(n,");\n")),t.compilationString+="lightingInfo info;\n",t.compilationString+="float shadow = 1.;\n",t.compilationString+="float aggShadow = 0.;\n",t.compilationString+="float numLights = 0.;\n",t.compilationString+="float glossiness = ".concat(this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"," * ").concat(this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0",";\n"),t.compilationString+="vec3 diffuseBase = vec3(0., 0., 0.);\n",t.compilationString+="vec3 specularBase = vec3(0., 0., 0.);\n",t.compilationString+="vec3 normalW = ".concat(this.worldNormal.associatedVariableName,".xyz;\n")),this.light?t.compilationString+=t._emitCodeFromInclude("lightFragment",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:n+".xyz"}]}):t.compilationString+=t._emitCodeFromInclude("lightFragment",i,{repeatKey:"maxSimultaneousLights",substitutionVars:"vPositionW,".concat(n,".xyz")}),0===this._lightId&&(t.compilationString+="aggShadow = aggShadow / numLights;\n");var o=this.diffuseOutput,a=this.specularOutput;return t.compilationString+=t._declareOutput(o)+" = diffuseBase".concat(this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:"",";\n"),a.hasEndpoints&&(t.compilationString+=t._declareOutput(a)+" = specularBase".concat(this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:"",";\n")),this.shadow.hasEndpoints&&(t.compilationString+=t._declareOutput(this.shadow)+" = aggShadow;\n"),this}this._injectVertexCode(t)},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.generateOnlyFragmentCode=this.generateOnlyFragmentCode,this.light&&(t.lightId=this.light.id),t},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),t.lightId&&(this.light=i.getLightById(t.lightId)),this.generateOnlyFragmentCode=t.generateOnlyFragmentCode,this._setTarget()},v([Ys("Generate only fragment code",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:t._OnGenerateOnlyFragmentCodeChanged}})],t.prototype,"generateOnlyFragmentCode",void 0),t}(Ws);a("BABYLON.LightBlock",_b);var mb=function(e){function t(i){var r=e.call(this,i,Fs.VertexAndFragment)||this;return r.registerOutput("source",Ns.Object,Fs.VertexAndFragment,new Qy("source",r,Us.Output,t,"ImageSourceBlock")),r}return m(t,e),Object.defineProperty(t.prototype,"texture",{get:function(){return this._texture},set:function(e){var t,i=this;if(this._texture!==e){var r=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:M.LastCreatedScene;!e&&r&&r.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(e){return e.hasTexture(i._texture)})),this._texture=e,e&&r&&r.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(t){return t.hasTexture(e)}))}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"samplerName",{get:function(){return this._samplerName},enumerable:!1,configurable:!0}),t.prototype.bind=function(e){this.texture&&e.setTexture(this._samplerName,this.texture)},t.prototype.isReady=function(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())},t.prototype.getClassName=function(){return"ImageSourceBlock"},Object.defineProperty(t.prototype,"source",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){return e.prototype._buildBlock.call(this,t),t.target===Fs.Vertex&&(this._samplerName=t._getFreeVariableName(this.name+"Sampler"),t.sharedData.blockingBlocks.push(this),t.sharedData.textureBlocks.push(this),t.sharedData.bindableBlocks.push(this)),t._emit2DSampler(this._samplerName),this},t.prototype._dumpPropertiesCode=function(){var t=e.prototype._dumpPropertiesCode.call(this);return this.texture?(t+="".concat(this._codeVariableName,'.texture = new BABYLON.Texture("').concat(this.texture.name,'", null, ').concat(this.texture.noMipmap,", ").concat(this.texture.invertY,", ").concat(this.texture.samplingMode,");\n"),t+="".concat(this._codeVariableName,".texture.wrapU = ").concat(this.texture.wrapU,";\n"),t+="".concat(this._codeVariableName,".texture.wrapV = ").concat(this.texture.wrapV,";\n"),t+="".concat(this._codeVariableName,".texture.uAng = ").concat(this.texture.uAng,";\n"),t+="".concat(this._codeVariableName,".texture.vAng = ").concat(this.texture.vAng,";\n"),t+="".concat(this._codeVariableName,".texture.wAng = ").concat(this.texture.wAng,";\n"),t+="".concat(this._codeVariableName,".texture.uOffset = ").concat(this.texture.uOffset,";\n"),t+="".concat(this._codeVariableName,".texture.vOffset = ").concat(this.texture.vOffset,";\n"),t+="".concat(this._codeVariableName,".texture.uScale = ").concat(this.texture.uScale,";\n"),t+="".concat(this._codeVariableName,".texture.vScale = ").concat(this.texture.vScale,";\n"),t+="".concat(this._codeVariableName,".texture.coordinatesMode = ").concat(this.texture.coordinatesMode,";\n")):t},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return this.texture&&!this.texture.isRenderTarget&&"VideoTexture"!==this.texture.getClassName()&&(t.texture=this.texture.serialize()),t},t.prototype._deserialize=function(t,i,r,n){e.prototype._deserialize.call(this,t,i,r,n),t.texture&&!Ll.IgnoreTexturesAtLoadTime&&void 0!==t.texture.url&&(0===t.texture.url.indexOf("data:")?r="":n&&(t.texture.url=n(t.texture.url),t.texture.name=t.texture.url),this.texture=Ja.Parse(t.texture,i,r))},t}(Ws);a("BABYLON.ImageSourceBlock",mb);var gb=function(e){function t(t,i){void 0===i&&(i=!1);var r=e.call(this,t,i?Fs.Fragment:Fs.VertexAndFragment)||this;return r._convertToGammaSpace=!1,r._convertToLinearSpace=!1,r.disableLevelMultiplication=!1,r._fragmentOnly=i,r.registerInput("uv",Ns.AutoDetect,!1,Fs.VertexAndFragment),r.registerInput("source",Ns.Object,!0,Fs.VertexAndFragment,new Qy("source",r,Us.Input,mb,"ImageSourceBlock")),r.registerInput("layer",Ns.Float,!0),r.registerInput("lod",Ns.Float,!0),r.registerOutput("rgba",Ns.Color4,Fs.Neutral),r.registerOutput("rgb",Ns.Color3,Fs.Neutral),r.registerOutput("r",Ns.Float,Fs.Neutral),r.registerOutput("g",Ns.Float,Fs.Neutral),r.registerOutput("b",Ns.Float,Fs.Neutral),r.registerOutput("a",Ns.Float,Fs.Neutral),r.registerOutput("level",Ns.Float,Fs.Neutral),r._inputs[0].addExcludedConnectionPointFromAllowedTypes(Ns.Vector2|Ns.Vector3|Ns.Vector4),r._inputs[0]._prioritizeVertex=!i,r}return m(t,e),Object.defineProperty(t.prototype,"texture",{get:function(){var e;return this.source.isConnected?(null===(e=this.source.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:this._texture},set:function(e){var t,i=this;if(this._texture!==e){var r=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:M.LastCreatedScene;!e&&r&&r.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(e){return e.hasTexture(i._texture)})),this._texture=e,e&&r&&r.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(t){return t.hasTexture(e)}))}},enumerable:!1,configurable:!0}),t._IsPrePassTextureBlock=function(e){return"PrePassTextureBlock"===(null==e?void 0:e.getClassName())},Object.defineProperty(t.prototype,"_isSourcePrePass",{get:function(){return t._IsPrePassTextureBlock(this._imageSource)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"samplerName",{get:function(){if(this._imageSource){if(!t._IsPrePassTextureBlock(this._imageSource))return this._imageSource.samplerName;if(this.source.connectedPoint)return this._imageSource.getSamplerName(this.source.connectedPoint)}return this._samplerName},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hasImageSource",{get:function(){return this.source.isConnected},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"convertToGammaSpace",{get:function(){return this._convertToGammaSpace},set:function(e){var t,i=this;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){var r=null!==(t=this.texture.getScene())&&void 0!==t?t:M.LastCreatedScene;null==r||r.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(e){return e.hasTexture(i.texture)}))}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"convertToLinearSpace",{get:function(){return this._convertToLinearSpace},set:function(e){var t,i=this;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){var r=null!==(t=this.texture.getScene())&&void 0!==t?t:M.LastCreatedScene;null==r||r.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(e){return e.hasTexture(i.texture)}))}},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"TextureBlock"},Object.defineProperty(t.prototype,"uv",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"source",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"layer",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"lod",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rgba",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rgb",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"r",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"g",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"b",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"a",{get:function(){return this._outputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"level",{get:function(){return this._outputs[6]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){if(this._fragmentOnly)return Fs.Fragment;if(!this.uv.isConnected)return Fs.VertexAndFragment;if(this.uv.sourceBlock.isInput)return Fs.VertexAndFragment;for(var e=this.uv.connectedPoint;e;){if(e.target===Fs.Fragment)return Fs.Fragment;if(e.target===Fs.Vertex)return Fs.VertexAndFragment;if(e.target===Fs.Neutral||e.target===Fs.VertexAndFragment){var t=e.ownerBlock;if(t.target===Fs.Fragment)return Fs.Fragment;e=null;for(var i=0,r=t.inputs;i<r.length;i++){var n=r[i];if(n.connectedPoint){e=n.connectedPoint;break}}}}return Fs.VertexAndFragment},set:function(e){},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(e,t){if(void 0===t&&(t=function(){return!0}),!this.uv.isConnected)if(e.mode===fl.PostProcess)(i=e.getBlockByPredicate((function(e){return"uv"===e.name&&t(e)})))&&i.connectTo(this);else{var i,r=e.mode===fl.Particle?"particle_uv":"uv";(i=e.getInputBlockByPredicate((function(e){return e.isAttribute&&e.name===r&&t(e)})))||(i=new rl("uv")).setAsAttribute(r),i.output.connectTo(this.uv)}},t.prototype.initializeDefines=function(e,t,i){i._areTexturesDirty&&void 0!==this._mainUVDefineName&&i.setValue(this._mainUVDefineName,!1,!0)},t.prototype.prepareDefines=function(e,t,i){if(i._areTexturesDirty)if(this.texture&&this.texture.getTextureMatrix){var r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,n=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,n,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),null==i[this._mainUVDefineName]&&i.setValue(this._mainUVDefineName,!1,!0)))}else this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0))},t.prototype.isReady=function(){return!!this._isSourcePrePass||!(this.texture&&!this.texture.isReadyOrNotBlocking())},t.prototype.bind=function(e){if(this._isSourcePrePass&&e.setFloat(this._textureInfoName,1),this.texture&&(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),!this._imageSource))if(this._textureName){var t=e.getEngine();e.setTexture(this._textureName,this.texture);var i=t.setTextureSampler;i&&i.call(t,this._samplerName,this.texture._texture)}else e.setTexture(this._samplerName,this.texture)},Object.defineProperty(t.prototype,"_isMixed",{get:function(){return this.target!==Fs.Fragment},enumerable:!1,configurable:!0}),t.prototype._injectVertexCode=function(e){var t=this.uv;this._defineName=e._getFreeDefineName("UVTRANSFORM"),this._mainUVDefineName="VMAIN"+t.declarationVariableName.toUpperCase(),this._mainUVName="vMain"+t.declarationVariableName,this._transformedUVName=e._getFreeVariableName("transformedUV"),this._textureTransformName=e._getFreeVariableName("textureTransform"),this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,e._emitVaryingFromString(this._transformedUVName,Ns.Vector2,this._defineName),e._emitVaryingFromString(this._mainUVName,Ns.Vector2,this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,Ns.Matrix,this._defineName);var i=e._getShaderType(Ns.Vector4),r=e._getShaderType(Ns.Vector2);if(e.compilationString+="#ifdef ".concat(this._defineName,"\n"),e.compilationString+="".concat(e._getVaryingName(this._transformedUVName)," = ").concat(r,"(").concat(this._textureTransformName," * ").concat(i,"(").concat(t.associatedVariableName,".xy, 1.0, 0.0));\n"),e.compilationString+="#elif defined(".concat(this._mainUVDefineName,")\n"),e.compilationString+="".concat(e._getVaryingName(this._mainUVName)," = ").concat(t.associatedVariableName,".xy;\n"),e.compilationString+="#endif\n",this._outputs.some((function(e){return e.isConnectedInVertexShader}))){this._writeTextureRead(e,!0);for(var n=0,o=this._outputs;n<o.length;n++){var a=o[n];a.hasEndpoints&&"level"!==a.name&&this._writeOutput(e,a,a.name,!0)}}},t.prototype._getUVW=function(e){var t,i,r,n,o,a,s=e,l=null!==(r=null===(i=null===(t=this._texture)||void 0===t?void 0:t._texture)||void 0===i?void 0:i.is2DArray)&&void 0!==r&&r,c=null!==(a=null===(o=null===(n=this._texture)||void 0===n?void 0:n._texture)||void 0===o?void 0:o.is3D)&&void 0!==a&&a;if(l){var u=this.layer.isConnected?this.layer.associatedVariableName:"0";s="vec3(".concat(e,", ").concat(u,")")}else c&&(u=this.layer.isConnected?this.layer.associatedVariableName:"0",s="vec3(".concat(e,", ").concat(u,")"));return s},t.prototype._samplerFunc=function(e){return e.shaderLanguage===pt.WGSL?e.target===Fs.Vertex?"textureSampleLevel":"textureSample":this.lod.isConnected?"texture2DLodEXT":"texture2D"},Object.defineProperty(t.prototype,"_samplerLodSuffix",{get:function(){return this.lod.isConnected?", ".concat(this.lod.associatedVariableName):""},enumerable:!1,configurable:!0}),t.prototype._generateTextureSample=function(e,t){if(t.shaderLanguage===pt.WGSL){var i=t.target===Fs.Vertex;return"".concat(this._samplerFunc(t),"(").concat(this._textureName,",").concat(this.samplerName,", ").concat(this._getUVW(e)).concat(this._samplerLodSuffix).concat(i?", 0":"",")")}return"".concat(this._samplerFunc(t),"(").concat(this.samplerName,", ").concat(this._getUVW(e)).concat(this._samplerLodSuffix,")")},t.prototype._generateTextureLookup=function(e){e.compilationString+="#ifdef ".concat(this._defineName,"\n"),e.compilationString+="".concat(e._declareLocalVar(this._tempTextureRead,Ns.Vector4)," = ").concat(this._generateTextureSample(e._getVaryingName(this._transformedUVName),e),";\n"),e.compilationString+="#elif defined(".concat(this._mainUVDefineName,")\n"),e.compilationString+="".concat(e._declareLocalVar(this._tempTextureRead,Ns.Vector4)," = ").concat(this._generateTextureSample(this._mainUVName?e._getVaryingName(this._mainUVName):this.uv.associatedVariableName,e)).concat(this._samplerLodSuffix,";\n"),e.compilationString+="#endif\n"},t.prototype._writeTextureRead=function(e,t){void 0===t&&(t=!1);var i=this.uv;if(t){if(e.target===Fs.Fragment)return;this._generateTextureLookup(e)}else this.uv.ownerBlock.target!==Fs.Fragment?this._generateTextureLookup(e):e.compilationString+="".concat(e._declareLocalVar(this._tempTextureRead,Ns.Vector4)," = ").concat(this._generateTextureSample(i.associatedVariableName,e)).concat(this._samplerLodSuffix,";\n")},t.prototype._generateConversionCode=function(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+="#ifdef ".concat(this._linearDefineName,"\n ").concat(t.associatedVariableName," = toGammaSpace(").concat(t.associatedVariableName,");\n #endif\n ")),e.compilationString+="#ifdef ".concat(this._gammaDefineName,"\n ").concat(t.associatedVariableName," = toLinearSpace(").concat(t.associatedVariableName,");\n #endif\n "))},t.prototype._writeOutput=function(e,t,i,r){if(void 0===r&&(r=!1),r){if(e.target===Fs.Fragment)return;return e.compilationString+="".concat(e._declareOutput(t)," = ").concat(this._tempTextureRead,".").concat(i,";\n"),void this._generateConversionCode(e,t,i)}if(this.uv.ownerBlock.target===Fs.Fragment)return e.compilationString+="".concat(e._declareOutput(t)," = ").concat(this._tempTextureRead,".").concat(i,";\n"),void this._generateConversionCode(e,t,i);var n="";this.disableLevelMultiplication||(n=" * ".concat((e.shaderLanguage===pt.WGSL?"uniforms.":"")+this._textureInfoName)),e.compilationString+="".concat(e._declareOutput(t)," = ").concat(this._tempTextureRead,".").concat(i).concat(n,";\n"),this._generateConversionCode(e,t,i)},t.prototype._buildBlock=function(t){var i,r,n,o;if(e.prototype._buildBlock.call(this,t),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(t.target===Fs.Vertex||this._fragmentOnly||t.target===Fs.Fragment)&&(this._tempTextureRead=t._getFreeVariableName("tempTextureRead"),this._linearDefineName=t._getFreeDefineName("ISLINEAR"),this._gammaDefineName=t._getFreeDefineName("ISGAMMA")),!this._isMixed&&t.target===Fs.Fragment||this._isMixed&&t.target===Fs.Vertex){if(!this._imageSource){var a=t._getFreeVariableName(this.name);this._samplerName=a+"Sampler",t.shaderLanguage===pt.WGSL&&(this._textureName=a+"Texture"),(null===(r=null===(i=this._texture)||void 0===i?void 0:i._texture)||void 0===r?void 0:r.is2DArray)?t._emit2DArraySampler(this._samplerName):t._emit2DSampler(this._samplerName,this._textureName)}t.sharedData.blockingBlocks.push(this),t.sharedData.textureBlocks.push(this),t.sharedData.blocksWithDefines.push(this),t.sharedData.bindableBlocks.push(this)}if(t.target===Fs.Fragment){if(this._outputs.some((function(e){return e.isConnectedInFragmentShader}))){this._isMixed&&!this._imageSource&&((null===(o=null===(n=this._texture)||void 0===n?void 0:n._texture)||void 0===o?void 0:o.is2DArray)?t._emit2DArraySampler(this._samplerName):t._emit2DSampler(this._samplerName,this._textureName));var s="//".concat(this.name);t._emitFunctionFromInclude("helperFunctions",s),this._isMixed&&t._emitUniformFromString(this._textureInfoName,Ns.Float),this._writeTextureRead(t);for(var l=0,c=this._outputs;l<c.length;l++){var u=c[l];u.hasEndpoints&&"level"!==u.name&&this._writeOutput(t,u,u.name)}return this}}else this._injectVertexCode(t)},t.prototype._dumpPropertiesCode=function(){var t=e.prototype._dumpPropertiesCode.call(this);return t+="".concat(this._codeVariableName,".convertToGammaSpace = ").concat(this.convertToGammaSpace,";\n"),t+="".concat(this._codeVariableName,".convertToLinearSpace = ").concat(this.convertToLinearSpace,";\n"),t+="".concat(this._codeVariableName,".disableLevelMultiplication = ").concat(this.disableLevelMultiplication,";\n"),this.texture?(t+="".concat(this._codeVariableName,'.texture = new BABYLON.Texture("').concat(this.texture.name,'", null, ').concat(this.texture.noMipmap,", ").concat(this.texture.invertY,", ").concat(this.texture.samplingMode,");\n"),t+="".concat(this._codeVariableName,".texture.wrapU = ").concat(this.texture.wrapU,";\n"),t+="".concat(this._codeVariableName,".texture.wrapV = ").concat(this.texture.wrapV,";\n"),t+="".concat(this._codeVariableName,".texture.uAng = ").concat(this.texture.uAng,";\n"),t+="".concat(this._codeVariableName,".texture.vAng = ").concat(this.texture.vAng,";\n"),t+="".concat(this._codeVariableName,".texture.wAng = ").concat(this.texture.wAng,";\n"),t+="".concat(this._codeVariableName,".texture.uOffset = ").concat(this.texture.uOffset,";\n"),t+="".concat(this._codeVariableName,".texture.vOffset = ").concat(this.texture.vOffset,";\n"),t+="".concat(this._codeVariableName,".texture.uScale = ").concat(this.texture.uScale,";\n"),t+="".concat(this._codeVariableName,".texture.vScale = ").concat(this.texture.vScale,";\n"),t+="".concat(this._codeVariableName,".texture.coordinatesMode = ").concat(this.texture.coordinatesMode,";\n")):t},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.convertToGammaSpace=this.convertToGammaSpace,t.convertToLinearSpace=this.convertToLinearSpace,t.fragmentOnly=this._fragmentOnly,t.disableLevelMultiplication=this.disableLevelMultiplication,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(t.texture=this.texture.serialize()),t},t.prototype._deserialize=function(t,i,r,n){e.prototype._deserialize.call(this,t,i,r),this.convertToGammaSpace=t.convertToGammaSpace,this.convertToLinearSpace=!!t.convertToLinearSpace,this._fragmentOnly=!!t.fragmentOnly,this.disableLevelMultiplication=!!t.disableLevelMultiplication,t.texture&&!Ll.IgnoreTexturesAtLoadTime&&void 0!==t.texture.url&&(0===t.texture.url.indexOf("data:")?r="":n&&(t.texture.url=n(t.texture.url),t.texture.name=t.texture.url),this.texture=Ja.Parse(t.texture,i,r))},t}(Ws);a("BABYLON.TextureBlock",gb);var vb=function(e){function t(t){var i=e.call(this,t,Fs.VertexAndFragment)||this;return i.generateOnlyFragmentCode=!1,i}return m(t,e),Object.defineProperty(t.prototype,"texture",{get:function(){return this._texture},set:function(e){var t,i=this;if(this._texture!==e){var r=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:M.LastCreatedScene;!e&&r&&r.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(e){return e.hasTexture(i._texture)})),this._texture=e,e&&r&&r.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(t){return t.hasTexture(e)}))}},enumerable:!1,configurable:!0}),t._OnGenerateOnlyFragmentCodeChanged=function(e,t){return e._onGenerateOnlyFragmentCodeChanged()},t.prototype._onGenerateOnlyFragmentCodeChanged=function(){return this._setTarget(),!0},t.prototype._setTarget=function(){this._setInitialTarget(this.generateOnlyFragmentCode?Fs.Fragment:Fs.VertexAndFragment)},t.prototype.getClassName=function(){return"ReflectionTextureBaseBlock"},t.prototype._getTexture=function(){return this.texture},t.prototype.autoConfigure=function(e,t){if(void 0===t&&(t=function(){return!0}),!this.position.isConnected){var i=e.getInputBlockByPredicate((function(e){return e.isAttribute&&"position"===e.name&&t(e)}));i||(i=new rl("position")).setAsAttribute(),i.output.connectTo(this.position)}if(!this.world.isConnected){var r=e.getInputBlockByPredicate((function(e){return e.systemValue===Qs.World&&t(e)}));r||(r=new rl("world")).setAsSystemValue(Qs.World),r.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){var n=e.getInputBlockByPredicate((function(e){return e.systemValue===Qs.View&&t(e)}));n||(n=new rl("view")).setAsSystemValue(Qs.View),n.output.connectTo(this.view)}},t.prototype.prepareDefines=function(e,t,i){if(i._areTexturesDirty){var r=this._getTexture();r&&r.getTextureMatrix&&(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLocalCubicName,!!r.boundingBoxSize,!0),i.setValue(this._defineExplicitName,r.coordinatesMode===u.TEXTURE_EXPLICIT_MODE,!0),i.setValue(this._defineSkyboxName,r.coordinatesMode===u.TEXTURE_SKYBOX_MODE,!0),i.setValue(this._defineCubicName,r.coordinatesMode===u.TEXTURE_CUBIC_MODE||r.coordinatesMode===u.TEXTURE_INVCUBIC_MODE,!0),i.setValue("INVERTCUBICMAP",r.coordinatesMode===u.TEXTURE_INVCUBIC_MODE,!0),i.setValue(this._defineSphericalName,r.coordinatesMode===u.TEXTURE_SPHERICAL_MODE,!0),i.setValue(this._definePlanarName,r.coordinatesMode===u.TEXTURE_PLANAR_MODE,!0),i.setValue(this._defineProjectionName,r.coordinatesMode===u.TEXTURE_PROJECTION_MODE,!0),i.setValue(this._defineEquirectangularName,r.coordinatesMode===u.TEXTURE_EQUIRECTANGULAR_MODE,!0),i.setValue(this._defineEquirectangularFixedName,r.coordinatesMode===u.TEXTURE_FIXED_EQUIRECTANGULAR_MODE,!0),i.setValue(this._defineMirroredEquirectangularFixedName,r.coordinatesMode===u.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE,!0))}},t.prototype.isReady=function(){var e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())},t.prototype.bind=function(e,t,i,r){var n=this._getTexture();if(i&&n&&(e.setMatrix(this._reflectionMatrixName,n.getReflectionTextureMatrix()),n.isCube?e.setTexture(this._cubeSamplerName,n):e.setTexture(this._2DSamplerName,n),n.boundingBoxSize)){var o=n;e.setVector3(this._reflectionPositionName,o.boundingBoxPosition),e.setVector3(this._reflectionSizeName,o.boundingBoxSize)}},t.prototype.handleVertexSide=function(e){if(this.generateOnlyFragmentCode&&e.target===Fs.Vertex)return"";this._define3DName=e._getFreeDefineName("REFLECTIONMAP_3D"),this._defineCubicName=e._getFreeDefineName("REFLECTIONMAP_CUBIC"),this._defineSphericalName=e._getFreeDefineName("REFLECTIONMAP_SPHERICAL"),this._definePlanarName=e._getFreeDefineName("REFLECTIONMAP_PLANAR"),this._defineProjectionName=e._getFreeDefineName("REFLECTIONMAP_PROJECTION"),this._defineExplicitName=e._getFreeDefineName("REFLECTIONMAP_EXPLICIT"),this._defineEquirectangularName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"),this._defineLocalCubicName=e._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"),this._defineMirroredEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"),this._defineEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"),this._defineSkyboxName=e._getFreeDefineName("REFLECTIONMAP_SKYBOX"),this._defineOppositeZ=e._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ"),this._reflectionMatrixName=e._getFreeVariableName("reflectionMatrix"),e._emitUniformFromString(this._reflectionMatrixName,Ns.Matrix);var t="";this._worldPositionNameInFragmentOnlyMode=e._getFreeVariableName("worldPosition");var i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(i,Ns.Vector4))&&(t+="".concat(this.generateOnlyFragmentCode?"vec4 ":"").concat(i," = ").concat(this.worldPosition.associatedVariableName,";\n")),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,Ns.Vector3,this._defineSkyboxName))&&(t+="#ifdef ".concat(this._defineSkyboxName,"\n"),t+="".concat(this.generateOnlyFragmentCode?"vec3 ":"").concat(this._positionUVWName," = ").concat(this.position.associatedVariableName,".xyz;\n"),t+="#endif\n"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,Ns.Vector3,"defined(".concat(this._defineEquirectangularFixedName,") || defined(").concat(this._defineMirroredEquirectangularFixedName,")")))&&(t+="#if defined(".concat(this._defineEquirectangularFixedName,") || defined(").concat(this._defineMirroredEquirectangularFixedName,")\n"),t+="".concat(this.generateOnlyFragmentCode?"vec3 ":"").concat(this._directionWName," = normalize(vec3(").concat(this.world.associatedVariableName," * vec4(").concat(this.position.associatedVariableName,".xyz, 0.0)));\n"),t+="#endif\n"),t},t.prototype.handleFragmentSideInits=function(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+="#ifdef ".concat(this._define3DName,"\n"),e._samplerDeclaration+="uniform samplerCube ".concat(this._cubeSamplerName,";\n"),e._samplerDeclaration+="#else\n",e._samplerDeclaration+="uniform sampler2D ".concat(this._2DSamplerName,";\n"),e._samplerDeclaration+="#endif\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);var t="//".concat(this.name);e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("reflectionFunction",t,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,Ns.Vector3),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,Ns.Vector3)},t.prototype.handleFragmentSideCodeReflectionCoords=function(e,t,i,r){void 0===i&&(i=!1),void 0===r&&(r=!1),t||(t=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_".concat(this.worldPosition.associatedVariableName));var n=this._reflectionMatrixName,o="normalize(".concat(this._directionWName,")"),a="".concat(this._positionUVWName),s="".concat(this.cameraPosition.associatedVariableName),l="".concat(this.view.associatedVariableName);e+=".xyz";var c="\n #ifdef ".concat(this._defineMirroredEquirectangularFixedName,"\n vec3 ").concat(this._reflectionVectorName," = computeMirroredFixedEquirectangularCoords(").concat(t,", ").concat(e,", ").concat(o,");\n #endif\n\n #ifdef ").concat(this._defineEquirectangularFixedName,"\n vec3 ").concat(this._reflectionVectorName," = computeFixedEquirectangularCoords(").concat(t,", ").concat(e,", ").concat(o,");\n #endif\n\n #ifdef ").concat(this._defineEquirectangularName,"\n vec3 ").concat(this._reflectionVectorName," = computeEquirectangularCoords(").concat(t,", ").concat(e,", ").concat(s,".xyz, ").concat(n,");\n #endif\n\n #ifdef ").concat(this._defineSphericalName,"\n vec3 ").concat(this._reflectionVectorName," = computeSphericalCoords(").concat(t,", ").concat(e,", ").concat(l,", ").concat(n,");\n #endif\n\n #ifdef ").concat(this._definePlanarName,"\n vec3 ").concat(this._reflectionVectorName," = computePlanarCoords(").concat(t,", ").concat(e,", ").concat(s,".xyz, ").concat(n,");\n #endif\n\n #ifdef ").concat(this._defineCubicName,"\n #ifdef ").concat(this._defineLocalCubicName,"\n vec3 ").concat(this._reflectionVectorName," = computeCubicLocalCoords(").concat(t,", ").concat(e,", ").concat(s,".xyz, ").concat(n,", ").concat(this._reflectionSizeName,", ").concat(this._reflectionPositionName,");\n #else\n vec3 ").concat(this._reflectionVectorName," = computeCubicCoords(").concat(t,", ").concat(e,", ").concat(s,".xyz, ").concat(n,");\n #endif\n #endif\n\n #ifdef ").concat(this._defineProjectionName,"\n vec3 ").concat(this._reflectionVectorName," = computeProjectionCoords(").concat(t,", ").concat(l,", ").concat(n,");\n #endif\n\n #ifdef ").concat(this._defineSkyboxName,"\n vec3 ").concat(this._reflectionVectorName," = computeSkyBoxCoords(").concat(a,", ").concat(n,");\n #endif\n\n #ifdef ").concat(this._defineExplicitName,"\n vec3 ").concat(this._reflectionVectorName," = vec3(0, 0, 0);\n #endif\n");return r||(c+="#ifdef ".concat(this._defineOppositeZ,"\n ").concat(this._reflectionVectorName,".z *= -1.0;\n #endif\n")),i||(c+="\n #ifdef ".concat(this._define3DName,"\n vec3 ").concat(this._reflectionCoordsName," = ").concat(this._reflectionVectorName,";\n #else\n vec2 ").concat(this._reflectionCoordsName," = ").concat(this._reflectionVectorName,".xy;\n #ifdef ").concat(this._defineProjectionName,"\n ").concat(this._reflectionCoordsName," /= ").concat(this._reflectionVectorName,".z;\n #endif\n ").concat(this._reflectionCoordsName,".y = 1.0 - ").concat(this._reflectionCoordsName,".y;\n #endif\n")),c},t.prototype.handleFragmentSideCodeReflectionColor=function(e,t){void 0===t&&(t=".rgb");var i="vec"+(0===t.length?"4":t.length-1),r="".concat(i," ").concat(this._reflectionColorName,";\n #ifdef ").concat(this._define3DName,"\n");return r+=e?"".concat(this._reflectionColorName," = textureCubeLodEXT(").concat(this._cubeSamplerName,", ").concat(this._reflectionVectorName,", ").concat(e,")").concat(t,";\n"):"".concat(this._reflectionColorName," = textureCube(").concat(this._cubeSamplerName,", ").concat(this._reflectionVectorName,")").concat(t,";\n"),r+="\n #else\n",(r+=e?"".concat(this._reflectionColorName," = texture2DLodEXT(").concat(this._2DSamplerName,", ").concat(this._reflectionCoordsName,", ").concat(e,")").concat(t,";\n"):"".concat(this._reflectionColorName," = texture2D(").concat(this._2DSamplerName,", ").concat(this._reflectionCoordsName,")").concat(t,";\n"))+"#endif\n"},t.prototype.writeOutputs=function(e,t){var i="";if(e.target===Fs.Fragment)for(var r=0,n=this._outputs;r<n.length;r++){var o=n[r];o.hasEndpoints&&(i+="".concat(e._declareOutput(o)," = ").concat(t,".").concat(o.name,";\n"))}return i},t.prototype._buildBlock=function(t){return e.prototype._buildBlock.call(this,t),this},t.prototype._dumpPropertiesCode=function(){var t=e.prototype._dumpPropertiesCode.call(this);if(!this.texture)return t;if(this.texture.isCube){var i=this.texture.forcedExtension;t+="".concat(this._codeVariableName,'.texture = new BABYLON.CubeTexture("').concat(this.texture.name,'", undefined, undefined, ').concat(this.texture.noMipmap,", null, undefined, undefined, undefined, ").concat(this.texture._prefiltered,", ").concat(i?'"'+i+'"':"null",");\n")}else t+="".concat(this._codeVariableName,'.texture = new BABYLON.Texture("').concat(this.texture.name,'", null);\n');return t+"".concat(this._codeVariableName,".texture.coordinatesMode = ").concat(this.texture.coordinatesMode,";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return this.texture&&!this.texture.isRenderTarget&&(t.texture=this.texture.serialize()),t.generateOnlyFragmentCode=this.generateOnlyFragmentCode,t},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),t.texture&&!Ll.IgnoreTexturesAtLoadTime&&(r=0===t.texture.url.indexOf("data:")?"":r,t.texture.isCube?this.texture=Nm.Parse(t.texture,i,r):this.texture=Ja.Parse(t.texture,i,r)),this.generateOnlyFragmentCode=t.generateOnlyFragmentCode,this._setTarget()},v([Ys("Generate only fragment code",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:t._OnGenerateOnlyFragmentCodeChanged}})],t.prototype,"generateOnlyFragmentCode",void 0),t}(Ws);a("BABYLON.ReflectionTextureBaseBlock",vb);var yb=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("position",Ns.AutoDetect,!1,Fs.Vertex),i.registerInput("worldPosition",Ns.Vector4,!1,Fs.Vertex),i.registerInput("worldNormal",Ns.Vector4,!1,Fs.Fragment),i.registerInput("world",Ns.Matrix,!1,Fs.Vertex),i.registerInput("cameraPosition",Ns.Vector3,!1,Fs.Fragment),i.registerInput("view",Ns.Matrix,!1,Fs.Fragment),i.registerOutput("rgb",Ns.Color3,Fs.Fragment),i.registerOutput("rgba",Ns.Color4,Fs.Fragment),i.registerOutput("r",Ns.Float,Fs.Fragment),i.registerOutput("g",Ns.Float,Fs.Fragment),i.registerOutput("b",Ns.Float,Fs.Fragment),i.registerOutput("a",Ns.Float,Fs.Fragment),i._inputs[0].addExcludedConnectionPointFromAllowedTypes(Ns.Color3|Ns.Vector3|Ns.Vector4),i}return m(t,e),t.prototype._onGenerateOnlyFragmentCodeChanged=function(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,ae.Error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,ae.Error("The worldPosition input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)},t.prototype._setTarget=function(){e.prototype._setTarget.call(this),this.getInputByName("position").target=this.generateOnlyFragmentCode?Fs.Fragment:Fs.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?Fs.Fragment:Fs.Vertex},t.prototype.getClassName=function(){return"ReflectionTextureBlock"},Object.defineProperty(t.prototype,"position",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"worldPosition",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"worldNormal",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"world",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraPosition",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"view",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rgb",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rgba",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"r",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"g",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"b",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"a",{get:function(){return this._outputs[5]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(t,i){if(void 0===i&&(i=function(){return!0}),e.prototype.autoConfigure.call(this,t),!this.cameraPosition.isConnected){var r=t.getInputBlockByPredicate((function(e){return e.systemValue===Qs.CameraPosition&&i(e)}));r||(r=new rl("cameraPosition")).setAsSystemValue(Qs.CameraPosition),r.output.connectTo(this.cameraPosition)}},t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),!this.texture)return t.compilationString+=this.writeOutputs(t,"vec4(0.)"),this;if(t.target!==Fs.Fragment)return t.compilationString+=this.handleVertexSide(t),this;this.generateOnlyFragmentCode&&(t.compilationString+=this.handleVertexSide(t)),this.handleFragmentSideInits(t);var i=t._getFreeVariableName("normalWUnit");return t.compilationString+="vec4 ".concat(i," = normalize(").concat(this.worldNormal.associatedVariableName,");\n"),t.compilationString+=this.handleFragmentSideCodeReflectionCoords(i),t.compilationString+=this.handleFragmentSideCodeReflectionColor(void 0,""),t.compilationString+=this.writeOutputs(t,this._reflectionColorName),this},t}(vb);a("BABYLON.ReflectionTextureBlock",yb);var bb=function(e){function t(t){var i=e.call(this,t,Fs.VertexAndFragment)||this;return i.useNonLinearDepth=!1,i.storeCameraSpaceZ=!1,i.force32itsFloat=!1,i._isUnique=!0,i.registerInput("uv",Ns.AutoDetect,!1,Fs.VertexAndFragment),i.registerOutput("depth",Ns.Float,Fs.Neutral),i._inputs[0].addExcludedConnectionPointFromAllowedTypes(Ns.Vector2|Ns.Vector3|Ns.Vector4),i._inputs[0]._prioritizeVertex=!1,i}return m(t,e),t.prototype.getClassName=function(){return"SceneDepthBlock"},Object.defineProperty(t.prototype,"uv",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"depth",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.initialize=function(e){e._excludeVariableName("textureSampler")},Object.defineProperty(t.prototype,"target",{get:function(){return this.uv.isConnected?this.uv.sourceBlock.isInput?Fs.VertexAndFragment:Fs.Fragment:Fs.VertexAndFragment},enumerable:!1,configurable:!0}),t.prototype._getTexture=function(e){return e.enableDepthRenderer(void 0,this.useNonLinearDepth,this.force32itsFloat,void 0,this.storeCameraSpaceZ).getDepthMap()},t.prototype.bind=function(e,t){var i=this._getTexture(t.getScene());e.setTexture(this._samplerName,i)},t.prototype._injectVertexCode=function(e){var t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,t.type===Ns.Vector3?Ns.Vector3:t.type===Ns.Vector4?Ns.Vector4:Ns.Vector2)),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,Ns.Vector2),e.compilationString+="".concat(this._mainUVName," = ").concat(t.associatedVariableName,".xy;\n"),this._outputs.some((function(e){return e.isConnectedInVertexShader}))){this._writeTextureRead(e,!0);for(var i=0,r=this._outputs;i<r.length;i++){var n=r[i];n.hasEndpoints&&this._writeOutput(e,n,"r",!0)}}},t.prototype._writeTextureRead=function(e,t){void 0===t&&(t=!1);var i=this.uv;if(t){if(e.target===Fs.Fragment)return;e.compilationString+="vec4 ".concat(this._tempTextureRead," = texture2D(").concat(this._samplerName,", ").concat(i.associatedVariableName,".xy);\n")}else this.uv.ownerBlock.target!==Fs.Fragment?e.compilationString+="vec4 ".concat(this._tempTextureRead," = texture2D(").concat(this._samplerName,", ").concat(this._mainUVName,");\n"):e.compilationString+="vec4 ".concat(this._tempTextureRead," = texture2D(").concat(this._samplerName,", ").concat(i.associatedVariableName,".xy);\n")},t.prototype._writeOutput=function(e,t,i,r){if(void 0===r&&(r=!1),r){if(e.target===Fs.Fragment)return;e.compilationString+="".concat(e._declareOutput(t)," = ").concat(this._tempTextureRead,".").concat(i,";\n")}else this.uv.ownerBlock.target,Fs.Fragment,e.compilationString+="".concat(e._declareOutput(t)," = ").concat(this._tempTextureRead,".").concat(i,";\n")},t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),this._samplerName=t._getFreeVariableName(this.name+"Sampler"),this._tempTextureRead=t._getFreeVariableName("tempTextureRead"),t.sharedData.bindableBlocks.indexOf(this)<0&&t.sharedData.bindableBlocks.push(this),t.target!==Fs.Fragment)return t._emit2DSampler(this._samplerName),void this._injectVertexCode(t);if(this._outputs.some((function(e){return e.isConnectedInFragmentShader}))){t._emit2DSampler(this._samplerName),this._writeTextureRead(t);for(var i=0,r=this._outputs;i<r.length;i++){var n=r[i];n.hasEndpoints&&this._writeOutput(t,n,"r")}return this}},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.useNonLinearDepth=this.useNonLinearDepth,t.storeCameraSpaceZ=this.storeCameraSpaceZ,t.force32itsFloat=this.force32itsFloat,t},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),this.useNonLinearDepth=t.useNonLinearDepth,this.storeCameraSpaceZ=!!t.storeCameraSpaceZ,this.force32itsFloat=t.force32itsFloat},v([Ys("Use non linear depth",Xs.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:function(e,t){var i=t,r=!1;return i.useNonLinearDepth&&(i.storeCameraSpaceZ=!1,r=!0),e&&e.disableDepthRenderer(),r}}})],t.prototype,"useNonLinearDepth",void 0),v([Ys("Store Camera space Z",Xs.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:function(e,t){var i=t,r=!1;return i.storeCameraSpaceZ&&(i.useNonLinearDepth=!1,r=!0),e&&e.disableDepthRenderer(),r}}})],t.prototype,"storeCameraSpaceZ",void 0),v([Ys("Force 32 bits float",Xs.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:function(e){return null==e?void 0:e.disableDepthRenderer()}}})],t.prototype,"force32itsFloat",void 0),t}(Ws);a("BABYLON.SceneDepthBlock",bb);var Tb=function(e){function t(t){var i=e.call(this,t,Fs.VertexAndFragment,!0)||this;return i.registerInput("worldPosition",Ns.Vector4,!1),i}return m(t,e),t.prototype.getClassName=function(){return"ClipPlanesBlock"},t.prototype.initialize=function(e){e._excludeVariableName("vClipPlane"),e._excludeVariableName("fClipDistance"),e._excludeVariableName("vClipPlane2"),e._excludeVariableName("fClipDistance2"),e._excludeVariableName("vClipPlane3"),e._excludeVariableName("fClipDistance3"),e._excludeVariableName("vClipPlane4"),e._excludeVariableName("fClipDistance4"),e._excludeVariableName("vClipPlane5"),e._excludeVariableName("fClipDistance5"),e._excludeVariableName("vClipPlane6"),e._excludeVariableName("fClipDistance6")},Object.defineProperty(t.prototype,"worldPosition",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){return Fs.VertexAndFragment},set:function(e){},enumerable:!1,configurable:!0}),t.prototype.prepareDefines=function(e,t,i){var r,n,o,a,s,l,c=e.getScene(),u=!!(null!==(r=t.clipPlane)&&void 0!==r?r:c.clipPlane),h=!!(null!==(n=t.clipPlane2)&&void 0!==n?n:c.clipPlane2),d=!!(null!==(o=t.clipPlane3)&&void 0!==o?o:c.clipPlane3),p=!!(null!==(a=t.clipPlane4)&&void 0!==a?a:c.clipPlane4),f=!!(null!==(s=t.clipPlane5)&&void 0!==s?s:c.clipPlane5),_=!!(null!==(l=t.clipPlane6)&&void 0!==l?l:c.clipPlane6);i.setValue("CLIPPLANE",u,!0),i.setValue("CLIPPLANE2",h,!0),i.setValue("CLIPPLANE3",d,!0),i.setValue("CLIPPLANE4",p,!0),i.setValue("CLIPPLANE5",f,!0),i.setValue("CLIPPLANE6",_,!0)},t.prototype.bind=function(e,t,i){i&&Ho(e,t,i.getScene())},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i="//".concat(this.name);if(t.target!==Fs.Fragment){var r=this.worldPosition;return t._emitFunctionFromInclude("clipPlaneVertexDeclaration",i,{replaceStrings:[{search:/uniform vec4 vClipPlane\d*;/g,replace:""}]}),t.compilationString+=t._emitCodeFromInclude("clipPlaneVertex",i,{replaceStrings:[{search:/worldPos/g,replace:r.associatedVariableName}]}),t._emitUniformFromString("vClipPlane",Ns.Vector4),t._emitUniformFromString("vClipPlane2",Ns.Vector4),t._emitUniformFromString("vClipPlane3",Ns.Vector4),t._emitUniformFromString("vClipPlane4",Ns.Vector4),t._emitUniformFromString("vClipPlane5",Ns.Vector4),void t._emitUniformFromString("vClipPlane6",Ns.Vector4)}return t.sharedData.bindableBlocks.push(this),t.sharedData.blocksWithDefines.push(this),t._emitFunctionFromInclude("clipPlaneFragmentDeclaration",i),t.compilationString+=t._emitCodeFromInclude("clipPlaneFragment",i),this},t}(Ws);a("BABYLON.ClipPlanesBlock",Tb);var Eb=function(e){function t(t,i){void 0===i&&(i=Fs.VertexAndFragment);var r=e.call(this,t,i,!1)||this;return r.registerOutput("position",Ns.Object,Fs.VertexAndFragment,new Qy("position",r,Us.Output,mb,"ImageSourceBlock")),r.registerOutput("depth",Ns.Object,Fs.VertexAndFragment,new Qy("depth",r,Us.Output,mb,"ImageSourceBlock")),r.registerOutput("normal",Ns.Object,Fs.VertexAndFragment,new Qy("normal",r,Us.Output,mb,"ImageSourceBlock")),r}return m(t,e),Object.defineProperty(t.prototype,"texture",{get:function(){return null},set:function(e){},enumerable:!1,configurable:!0}),t.prototype.getSamplerName=function(e){return e===this._outputs[0]?this._positionSamplerName:e===this._outputs[1]?this._depthSamplerName:e===this._outputs[2]?this._normalSamplerName:""},Object.defineProperty(t.prototype,"position",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"depth",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"normal",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"positionSamplerName",{get:function(){return this._positionSamplerName},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"normalSamplerName",{get:function(){return this._normalSamplerName},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"depthSamplerName",{get:function(){return this._depthSamplerName},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"PrePassTextureBlock"},t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),t.target!==Fs.Vertex)return this._positionSamplerName="prepassPositionSampler",this._depthSamplerName="prepassDepthSampler",this._normalSamplerName="prepassNormalSampler",t.sharedData.variableNames.prepassPositionSampler=0,t.sharedData.variableNames.prepassDepthSampler=0,t.sharedData.variableNames.prepassNormalSampler=0,t.sharedData.textureBlocks.push(this),t.sharedData.bindableBlocks.push(this),t._emit2DSampler(this._positionSamplerName),t._emit2DSampler(this._depthSamplerName),t._emit2DSampler(this._normalSamplerName),this},t.prototype.bind=function(e,t){var i=t.getScene().enablePrePassRenderer();if(i){var r=i.defaultRT;r.textures&&(this.position.isConnected&&e.setTexture(this._positionSamplerName,r.textures[i.getIndex(u.PREPASS_POSITION_TEXTURE_TYPE)]),this.depth.isConnected&&e.setTexture(this._depthSamplerName,r.textures[i.getIndex(u.PREPASS_DEPTH_TEXTURE_TYPE)]),this.normal.isConnected&&e.setTexture(this._normalSamplerName,r.textures[i.getIndex(u.PREPASS_NORMAL_TEXTURE_TYPE)]))}},t}(Ws);a("BABYLON.PrePassTextureBlock",Eb);var Sb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i._endpoints=[],i.registerInput("input",Ns.AutoDetect),i}return m(t,e),Object.defineProperty(t.prototype,"endpoints",{get:function(){return this._endpoints},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){var e=this._inputs[0];if(e.isConnected){var t=e.connectedPoint.ownerBlock;if(t.target!==Fs.VertexAndFragment)return t.target;if(e.connectedPoint.target!==Fs.VertexAndFragment)return e.connectedPoint.target}return this._target},set:function(e){this._target&e||(this._target=e)},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"NodeMaterialTeleportInBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),t.prototype.isConnectedInFragmentShader=function(){return this.endpoints.some((function(e){return e.output.isConnectedInFragmentShader}))},t.prototype._dumpCode=function(t,i){for(var r=e.prototype._dumpCode.call(this,t,i),n=0,o=this.endpoints;n<o.length;n++){var a=o[n];-1===i.indexOf(a)&&(r+=a._dumpCode(t,i))}return r},t.prototype.isAnAncestorOf=function(e){for(var t=0,i=this.endpoints;t<i.length;t++){var r=i[t];if(r===e)return!0;if(r.isAnAncestorOf(e))return!0}return!1},t.prototype.attachToEndpoint=function(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name},t.prototype.detachFromEndpoint=function(e){var t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)},t.prototype.dispose=function(){e.prototype.dispose.call(this);for(var t=0,i=this._endpoints;t<i.length;t++){var r=i[t];this.detachFromEndpoint(r)}this._endpoints=[]},t}(Ws);a("BABYLON.NodeMaterialTeleportInBlock",Sb);var xb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i._entryPoint=null,i._tempEntryPointUniqueId=null,i.registerOutput("output",Ns.BasedOnInput),i}return m(t,e),Object.defineProperty(t.prototype,"entryPoint",{get:function(){return this._entryPoint},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"NodeMaterialTeleportOutBlock"},Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){return this._entryPoint?this._entryPoint.target:this._target},set:function(e){this._target&e||(this._target=e)},enumerable:!1,configurable:!0}),t.prototype.detach=function(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t),this.entryPoint&&(t.compilationString+=t._declareOutput(this.output)+" = ".concat(this.entryPoint.input.associatedVariableName,";\n"))},t.prototype.clone=function(t,i){void 0===i&&(i="");var r=e.prototype.clone.call(this,t,i);return this.entryPoint&&this.entryPoint.attachToEndpoint(r),r},t.prototype._customBuildStep=function(e,t){this.entryPoint&&this.entryPoint.build(e,t)},t.prototype._dumpCode=function(t,i){var r="";return this.entryPoint&&-1===i.indexOf(this.entryPoint)&&(r+=this.entryPoint._dumpCode(t,i)),r+e.prototype._dumpCode.call(this,t,i)},t.prototype._dumpCodeForOutputConnections=function(t){var i=e.prototype._dumpCodeForOutputConnections.call(this,t);return this.entryPoint&&(i+=this.entryPoint._dumpCodeForOutputConnections(t)),i},t.prototype._dumpPropertiesCode=function(){var t=e.prototype._dumpPropertiesCode.call(this);return this.entryPoint&&(t+="".concat(this.entryPoint._codeVariableName,".attachToEndpoint(").concat(this._codeVariableName,");\n")),t},t.prototype.serialize=function(){var t,i,r=e.prototype.serialize.call(this);return r.entryPoint=null!==(i=null===(t=this.entryPoint)||void 0===t?void 0:t.uniqueId)&&void 0!==i?i:"",r},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),this._tempEntryPointUniqueId=t.entryPoint},t}(Ws);a("BABYLON.NodeMaterialTeleportOutBlock",xb);var Ab=function(e){function t(t){return e.call(this,t)||this}return m(t,e),t.prototype.getClassName=function(){return"AddBlock"},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = ".concat(this.left.associatedVariableName," + ").concat(this.right.associatedVariableName,";\n"),this},t}(_l);a("BABYLON.AddBlock",Ab);var Cb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("input",Ns.AutoDetect),i.registerInput("factor",Ns.Float),i.registerOutput("output",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i}return m(t,e),t.prototype.getClassName=function(){return"ScaleBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"factor",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = ".concat(this.input.associatedVariableName," * ").concat(this.factor.associatedVariableName,";\n"),this},t}(Ws);a("BABYLON.ScaleBlock",Cb);var Rb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.minimum=0,i.maximum=1,i.registerInput("value",Ns.AutoDetect),i.registerOutput("output",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i}return m(t,e),t.prototype.getClassName=function(){return"ClampBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = clamp(".concat(this.value.associatedVariableName,", ").concat(this._writeFloat(this.minimum),", ").concat(this._writeFloat(this.maximum),");\n"),this},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".minimum = ").concat(this.minimum,";\n")+"".concat(this._codeVariableName,".maximum = ").concat(this.maximum,";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.minimum=this.minimum,t.maximum=this.maximum,t},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),this.minimum=t.minimum,this.maximum=t.maximum},v([Ys("Minimum",Xs.Float)],t.prototype,"minimum",void 0),v([Ys("Maximum",Xs.Float)],t.prototype,"maximum",void 0),t}(Ws);a("BABYLON.ClampBlock",Rb);var Pb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("left",Ns.AutoDetect),i.registerInput("right",Ns.AutoDetect),i.registerOutput("output",Ns.Vector3),i._linkConnectionTypes(0,1),i._inputs[0].excludedConnectionPointTypes.push(Ns.Float),i._inputs[0].excludedConnectionPointTypes.push(Ns.Matrix),i._inputs[0].excludedConnectionPointTypes.push(Ns.Vector2),i._inputs[1].excludedConnectionPointTypes.push(Ns.Float),i._inputs[1].excludedConnectionPointTypes.push(Ns.Matrix),i._inputs[1].excludedConnectionPointTypes.push(Ns.Vector2),i}return m(t,e),t.prototype.getClassName=function(){return"CrossBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = cross(".concat(this.left.associatedVariableName,".xyz, ").concat(this.right.associatedVariableName,".xyz);\n"),this},t}(Ws);a("BABYLON.CrossBlock",Pb);var Ib=function(e){function t(t){return e.call(this,t)||this}return m(t,e),Object.defineProperty(t.prototype,"options",{get:function(){return this._options},set:function(e){this._deserializeOptions(e)},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"CustomBlock"},t.prototype._buildBlock=function(t){var i=this;e.prototype._buildBlock.call(this,t);var r=this._code,n=this._options.functionName;this._inputs.forEach((function(e){var i=new RegExp("\\{TYPE_"+e.name+"\\}","gm"),o=t._getGLType(e.type);r=r.replace(i,o),n=n.replace(i,o)})),this._outputs.forEach((function(e){var i=new RegExp("\\{TYPE_"+e.name+"\\}","gm"),o=t._getGLType(e.type);r=r.replace(i,o),n=n.replace(i,o)})),t._emitFunction(n,r,""),this._outputs.forEach((function(e){t.compilationString+=t._declareOutput(e)+";\n"})),t.compilationString+=n+"(";var o=!1;return this._inputs.forEach((function(e,r){var n,a,s;r>0&&(t.compilationString+=", "),i._inputSamplers&&-1!==i._inputSamplers.indexOf(e.name)?t.compilationString+=null!==(s=null===(a=null===(n=e.connectedPoint)||void 0===n?void 0:n.ownerBlock)||void 0===a?void 0:a.samplerName)&&void 0!==s?s:e.associatedVariableName:t.compilationString+=e.associatedVariableName,o=!0})),this._outputs.forEach((function(e,i){(i>0||o)&&(t.compilationString+=", "),t.compilationString+=e.associatedVariableName})),t.compilationString+=");\n",this},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".options = ").concat(JSON.stringify(this._options),";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.options=this._options,t},t.prototype._deserialize=function(t,i,r){this._deserializeOptions(t.options),e.prototype._deserialize.call(this,t,i,r)},t.prototype._deserializeOptions=function(e){var t,i,r,n=this;this._options=e,this._code=e.code.join("\n")+"\n",this.name=this.name||e.name,this.target=Fs[e.target],null===(t=e.inParameters)||void 0===t||t.forEach((function(e,t){var i=Ns[e.type];"sampler2D"===e.type||"samplerCube"===e.type?(n._inputSamplers=n._inputSamplers||[],n._inputSamplers.push(e.name),n.registerInput(e.name,Ns.Object,!0,Fs.VertexAndFragment,new Qy(e.name,n,Us.Input,mb,"ImageSourceBlock"))):n.registerInput(e.name,i),Object.defineProperty(n,e.name,{get:function(){return this._inputs[t]},enumerable:!0,configurable:!0})})),null===(i=e.outParameters)||void 0===i||i.forEach((function(e,t){n.registerOutput(e.name,Ns[e.type]),Object.defineProperty(n,e.name,{get:function(){return this._outputs[t]},enumerable:!0,configurable:!0}),"BasedOnInput"===e.type&&(n._outputs[t]._typeConnectionSource=n._findInputByName(e.typeFromInput)[0])})),null===(r=e.inLinkedConnectionTypes)||void 0===r||r.forEach((function(e){n._linkConnectionTypes(n._findInputByName(e.input1)[1],n._findInputByName(e.input2)[1])}))},t.prototype._findInputByName=function(e){if(!e)return null;for(var t=0;t<this._inputs.length;t++)if(this._inputs[t].name===e)return[this._inputs[t],t];return null},t}(Ws);a("BABYLON.CustomBlock",Ib);var Mb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("left",Ns.AutoDetect),i.registerInput("right",Ns.AutoDetect),i.registerOutput("output",Ns.Float),i._linkConnectionTypes(0,1),i._inputs[0].excludedConnectionPointTypes.push(Ns.Float),i._inputs[0].excludedConnectionPointTypes.push(Ns.Matrix),i._inputs[1].excludedConnectionPointTypes.push(Ns.Float),i._inputs[1].excludedConnectionPointTypes.push(Ns.Matrix),i}return m(t,e),t.prototype.getClassName=function(){return"DotBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = dot(".concat(this.left.associatedVariableName,", ").concat(this.right.associatedVariableName,");\n"),this},t}(Ws);a("BABYLON.DotBlock",Mb);var Ob=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("input",Ns.AutoDetect),i.registerOutput("output",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._inputs[0].excludedConnectionPointTypes.push(Ns.Float),i._inputs[0].excludedConnectionPointTypes.push(Ns.Matrix),i}return m(t,e),t.prototype.getClassName=function(){return"NormalizeBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],r=this._inputs[0];return t.compilationString+=t._declareOutput(i)+" = normalize(".concat(r.associatedVariableName,");\n"),this},t}(Ws);a("BABYLON.NormalizeBlock",Ob);var Db=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.rSwizzle="r",i.gSwizzle="g",i.bSwizzle="b",i.aSwizzle="a",i.registerInput("rgb ",Ns.Color3,!0),i.registerInput("r",Ns.Float,!0),i.registerInput("g",Ns.Float,!0),i.registerInput("b",Ns.Float,!0),i.registerInput("a",Ns.Float,!0),i.registerOutput("rgba",Ns.Color4),i.registerOutput("rgb",Ns.Color3),i}return m(t,e),t.prototype.getClassName=function(){return"ColorMergerBlock"},Object.defineProperty(t.prototype,"rgbIn",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"r",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"g",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"b",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"a",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rgba",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rgbOut",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rgb",{get:function(){return this.rgbOut},enumerable:!1,configurable:!0}),t.prototype._inputRename=function(e){return"rgb "===e?"rgbIn":e},t.prototype._buildSwizzle=function(e){return"."+(this.rSwizzle+this.gSwizzle+this.bSwizzle+this.aSwizzle).substr(0,e)},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this.r,r=this.g,n=this.b,o=this.a,a=this.rgbIn,s=this._outputs[0],l=this._outputs[1],c=t._getShaderType(Ns.Vector4),u=t._getShaderType(Ns.Vector3);return a.isConnected?(s.hasEndpoints&&(t.compilationString+=t._declareOutput(s)+" = ".concat(c,"(").concat(a.associatedVariableName,", ").concat(o.isConnected?this._writeVariable(o):"0.0",")").concat(this._buildSwizzle(4),";\n")),l.hasEndpoints&&(t.compilationString+=t._declareOutput(l)+" = ".concat(a.associatedVariableName).concat(this._buildSwizzle(3),";\n"))):(s.hasEndpoints&&(t.compilationString+=t._declareOutput(s)+" = ".concat(c,"(").concat(i.isConnected?this._writeVariable(i):"0.0",", ").concat(r.isConnected?this._writeVariable(r):"0.0",", ").concat(n.isConnected?this._writeVariable(n):"0.0",", ").concat(o.isConnected?this._writeVariable(o):"0.0",")").concat(this._buildSwizzle(4),";\n")),l.hasEndpoints&&(t.compilationString+=t._declareOutput(l)+" = ".concat(u,"(").concat(i.isConnected?this._writeVariable(i):"0.0",", ").concat(r.isConnected?this._writeVariable(r):"0.0",", ").concat(n.isConnected?this._writeVariable(n):"0.0",")").concat(this._buildSwizzle(3),";\n"))),this},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.rSwizzle=this.rSwizzle,t.gSwizzle=this.gSwizzle,t.bSwizzle=this.bSwizzle,t.aSwizzle=this.aSwizzle,t},t.prototype._deserialize=function(t,i,r){var n,o,a,s;e.prototype._deserialize.call(this,t,i,r),this.rSwizzle=null!==(n=t.rSwizzle)&&void 0!==n?n:"r",this.gSwizzle=null!==(o=t.gSwizzle)&&void 0!==o?o:"g",this.bSwizzle=null!==(a=t.bSwizzle)&&void 0!==a?a:"b",this.aSwizzle=null!==(s=t.aSwizzle)&&void 0!==s?s:"a"},t.prototype._dumpPropertiesCode=function(){var t=e.prototype._dumpPropertiesCode.call(this);return t+="".concat(this._codeVariableName,'.rSwizzle = "').concat(this.rSwizzle,'";\n'),t+="".concat(this._codeVariableName,'.gSwizzle = "').concat(this.gSwizzle,'";\n'),(t+="".concat(this._codeVariableName,'.bSwizzle = "').concat(this.bSwizzle,'";\n'))+"".concat(this._codeVariableName,'.aSwizzle = "').concat(this.aSwizzle,'";\n')},t}(Ws);a("BABYLON.ColorMergerBlock",Db);var Nb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("xyzw",Ns.Vector4,!0),i.registerInput("xyz ",Ns.Vector3,!0),i.registerInput("xy ",Ns.Vector2,!0),i.registerOutput("xyz",Ns.Vector3),i.registerOutput("xy",Ns.Vector2),i.registerOutput("zw",Ns.Vector2),i.registerOutput("x",Ns.Float),i.registerOutput("y",Ns.Float),i.registerOutput("z",Ns.Float),i.registerOutput("w",Ns.Float),i.inputsAreExclusive=!0,i}return m(t,e),t.prototype.getClassName=function(){return"VectorSplitterBlock"},Object.defineProperty(t.prototype,"xyzw",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xyzIn",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xyIn",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xyzOut",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xyOut",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"zw",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"x",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"y",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"z",{get:function(){return this._outputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"w",{get:function(){return this._outputs[6]},enumerable:!1,configurable:!0}),t.prototype._inputRename=function(e){switch(e){case"xy ":return"xyIn";case"xyz ":return"xyzIn";default:return e}},t.prototype._outputRename=function(e){switch(e){case"xy":return"xyOut";case"xyz":return"xyzOut";default:return e}},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this.xyzw.isConnected?this.xyzw:this.xyzIn.isConnected?this.xyzIn:this.xyIn,r=this._outputs[0],n=this._outputs[1],o=this._outputs[2],a=this._outputs[3],s=this._outputs[4],l=this._outputs[5],c=this._outputs[6],u=t._getShaderType(Ns.Vector3);return r.hasEndpoints&&(i===this.xyIn?t.compilationString+=t._declareOutput(r)+" = ".concat(u,"(").concat(i.associatedVariableName,", 0.0);\n"):t.compilationString+=t._declareOutput(r)+" = ".concat(i.associatedVariableName,".xyz;\n")),o.hasEndpoints&&this.xyzw.isConnected&&(t.compilationString+=t._declareOutput(o)+" = ".concat(this.xyzw.associatedVariableName,".zw;\n")),n.hasEndpoints&&(t.compilationString+=t._declareOutput(n)+" = ".concat(i.associatedVariableName,".xy;\n")),a.hasEndpoints&&(t.compilationString+=t._declareOutput(a)+" = ".concat(i.associatedVariableName,".x;\n")),s.hasEndpoints&&(t.compilationString+=t._declareOutput(s)+" = ".concat(i.associatedVariableName,".y;\n")),l.hasEndpoints&&(t.compilationString+=t._declareOutput(l)+" = ".concat(i.associatedVariableName,".z;\n")),c.hasEndpoints&&(t.compilationString+=t._declareOutput(c)+" = ".concat(i.associatedVariableName,".w;\n")),this},t}(Ws);a("BABYLON.VectorSplitterBlock",Nb);var Fb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("left",Ns.AutoDetect),i.registerInput("right",Ns.AutoDetect),i.registerInput("gradient",Ns.AutoDetect),i.registerOutput("output",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i._linkConnectionTypes(1,2,!0),i._inputs[2].acceptedConnectionPointTypes.push(Ns.Float),i}return m(t,e),t.prototype.getClassName=function(){return"LerpBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"gradient",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = mix(".concat(this.left.associatedVariableName," , ").concat(this.right.associatedVariableName,", ").concat(this.gradient.associatedVariableName,");\n"),this},t}(Ws);a("BABYLON.LerpBlock",Fb);var Lb=function(e){function t(t){return e.call(this,t)||this}return m(t,e),t.prototype.getClassName=function(){return"DivideBlock"},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = ".concat(this.left.associatedVariableName," / ").concat(this.right.associatedVariableName,";\n"),this},t}(_l);a("BABYLON.DivideBlock",Lb);var wb=function(e){function t(t){return e.call(this,t)||this}return m(t,e),t.prototype.getClassName=function(){return"SubtractBlock"},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = ".concat(this.left.associatedVariableName," - ").concat(this.right.associatedVariableName,";\n"),this},t}(_l);a("BABYLON.SubtractBlock",wb);var Bb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("value",Ns.Float),i.registerInput("edge",Ns.Float),i.registerOutput("output",Ns.Float),i}return m(t,e),t.prototype.getClassName=function(){return"StepBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"edge",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = step(".concat(this.edge.associatedVariableName,", ").concat(this.value.associatedVariableName,");\n"),this},t}(Ws);a("BABYLON.StepBlock",Bb);var Ub=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("input",Ns.AutoDetect),i.registerOutput("output",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._outputs[0].excludedConnectionPointTypes.push(Ns.Matrix),i}return m(t,e),t.prototype.getClassName=function(){return"OneMinusBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = 1. - ".concat(this.input.associatedVariableName,";\n"),this},t}(Ws);a("BABYLON.OneMinusBlock",Ub),a("BABYLON.OppositeBlock",Ub);var Vb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("worldPosition",Ns.Vector4),i.registerInput("cameraPosition",Ns.Vector3),i.registerOutput("output",Ns.Vector3),i}return m(t,e),t.prototype.getClassName=function(){return"ViewDirectionBlock"},Object.defineProperty(t.prototype,"worldPosition",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraPosition",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(e,t){if(void 0===t&&(t=function(){return!0}),!this.cameraPosition.isConnected){var i=e.getInputBlockByPredicate((function(e){return e.systemValue===Qs.CameraPosition&&t(e)}));i||(i=new rl("cameraPosition")).setAsSystemValue(Qs.CameraPosition),i.output.connectTo(this.cameraPosition)}},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = normalize(".concat(this.cameraPosition.associatedVariableName," - ").concat(this.worldPosition.associatedVariableName,".xyz);\n"),this},t}(Ws);a("BABYLON.ViewDirectionBlock",Vb);var kb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("worldNormal",Ns.Vector4),i.registerInput("viewDirection",Ns.Vector3),i.registerInput("bias",Ns.Float),i.registerInput("power",Ns.Float),i.registerOutput("fresnel",Ns.Float),i}return m(t,e),t.prototype.getClassName=function(){return"FresnelBlock"},Object.defineProperty(t.prototype,"worldNormal",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"viewDirection",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"bias",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"power",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"fresnel",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(e){if(!this.viewDirection.isConnected){var t=new Vb("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){var i=new rl("bias");i.value=0,i.output.connectTo(this.bias)}if(!this.power.isConnected){var r=new rl("power");r.value=1,r.output.connectTo(this.power)}},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i="//".concat(this.name);return t._emitFunctionFromInclude("fresnelFunction",i,{removeIfDef:!0}),t.compilationString+=t._declareOutput(this.fresnel)+" = computeFresnelTerm(".concat(this.viewDirection.associatedVariableName,".xyz, ").concat(this.worldNormal.associatedVariableName,".xyz, ").concat(this.bias.associatedVariableName,", ").concat(this.power.associatedVariableName,");\n"),this},t}(Ws);a("BABYLON.FresnelBlock",kb);var Gb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("left",Ns.AutoDetect),i.registerInput("right",Ns.AutoDetect),i.registerOutput("output",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i}return m(t,e),t.prototype.getClassName=function(){return"MaxBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = max(".concat(this.left.associatedVariableName,", ").concat(this.right.associatedVariableName,");\n"),this},t}(Ws);a("BABYLON.MaxBlock",Gb);var zb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("left",Ns.AutoDetect),i.registerInput("right",Ns.AutoDetect),i.registerOutput("output",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i}return m(t,e),t.prototype.getClassName=function(){return"MinBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = min(".concat(this.left.associatedVariableName,", ").concat(this.right.associatedVariableName,");\n"),this},t}(Ws);a("BABYLON.MinBlock",zb);var Wb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("left",Ns.AutoDetect),i.registerInput("right",Ns.AutoDetect),i.registerOutput("output",Ns.Float),i._linkConnectionTypes(0,1),i._inputs[0].excludedConnectionPointTypes.push(Ns.Float),i._inputs[0].excludedConnectionPointTypes.push(Ns.Matrix),i._inputs[1].excludedConnectionPointTypes.push(Ns.Float),i._inputs[1].excludedConnectionPointTypes.push(Ns.Matrix),i}return m(t,e),t.prototype.getClassName=function(){return"DistanceBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = length(".concat(this.left.associatedVariableName," - ").concat(this.right.associatedVariableName,");\n"),this},t}(Ws);a("BABYLON.DistanceBlock",Wb);var Hb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("value",Ns.AutoDetect),i.registerOutput("output",Ns.Float),i._inputs[0].excludedConnectionPointTypes.push(Ns.Float),i._inputs[0].excludedConnectionPointTypes.push(Ns.Matrix),i}return m(t,e),t.prototype.getClassName=function(){return"LengthBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = length(".concat(this.value.associatedVariableName,");\n"),this},t}(Ws);a("BABYLON.LengthBlock",Hb);var Xb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("value",Ns.AutoDetect),i.registerOutput("output",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i}return m(t,e),t.prototype.getClassName=function(){return"NegateBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = -1.0 * ".concat(this.value.associatedVariableName,";\n"),this},t}(Ws);a("BABYLON.NegateBlock",Xb);var jb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("value",Ns.AutoDetect),i.registerInput("power",Ns.AutoDetect),i.registerOutput("output",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i}return m(t,e),t.prototype.getClassName=function(){return"PowBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"power",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = pow(".concat(this.value.associatedVariableName,", ").concat(this.power.associatedVariableName,");\n"),this},t}(Ws);a("BABYLON.PowBlock",jb);var Yb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("seed",Ns.AutoDetect),i.registerOutput("output",Ns.Float),i._inputs[0].addExcludedConnectionPointFromAllowedTypes(Ns.Vector2|Ns.Vector3|Ns.Vector4|Ns.Color3|Ns.Color4),i}return m(t,e),t.prototype.getClassName=function(){return"RandomNumberBlock"},Object.defineProperty(t.prototype,"seed",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],r="//".concat(this.name);return t._emitFunctionFromInclude("helperFunctions",r),t.compilationString+=t._declareOutput(i)+" = getRand(".concat(this.seed.associatedVariableName,".xy);\n"),this},t}(Ws);a("BABYLON.RandomNumberBlock",Yb);var Kb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("x",Ns.Float),i.registerInput("y",Ns.Float),i.registerOutput("output",Ns.Float),i}return m(t,e),t.prototype.getClassName=function(){return"ArcTan2Block"},Object.defineProperty(t.prototype,"x",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"y",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],r=t.shaderLanguage===pt.WGSL?"atan2":"atan";return t.compilationString+=t._declareOutput(i)+" = ".concat(r,"(").concat(this.x.associatedVariableName,", ").concat(this.y.associatedVariableName,");\n"),this},t}(Ws);a("BABYLON.ArcTan2Block",Kb);var Qb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("value",Ns.AutoDetect),i.registerInput("edge0",Ns.Float),i.registerInput("edge1",Ns.Float),i.registerOutput("output",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i}return m(t,e),t.prototype.getClassName=function(){return"SmoothStepBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"edge0",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"edge1",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],r=t._getShaderType(this.value.type);return t.compilationString+=t._declareOutput(i)+" = smoothstep(".concat(r,"(").concat(this.edge0.associatedVariableName,"), ").concat(r,"(").concat(this.edge1.associatedVariableName,"), ").concat(this.value.associatedVariableName,");\n"),this},t}(Ws);a("BABYLON.SmoothStepBlock",Qb);var qb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("input",Ns.AutoDetect),i.registerOutput("output",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i}return m(t,e),t.prototype.getClassName=function(){return"ReciprocalBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return this.input.type===Ns.Matrix?t.compilationString+=t._declareOutput(i)+" = inverse(".concat(this.input.associatedVariableName,");\n"):t.compilationString+=t._declareOutput(i)+" = 1. / ".concat(this.input.associatedVariableName,";\n"),this},t}(Ws);a("BABYLON.ReciprocalBlock",qb);var Zb=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("value",Ns.AutoDetect),i.registerInput("reference",Ns.AutoDetect),i.registerInput("distance",Ns.Float),i.registerInput("replacement",Ns.AutoDetect),i.registerOutput("output",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i._linkConnectionTypes(0,3),i._inputs[0].excludedConnectionPointTypes.push(Ns.Float),i._inputs[0].excludedConnectionPointTypes.push(Ns.Matrix),i._inputs[1].excludedConnectionPointTypes.push(Ns.Float),i._inputs[1].excludedConnectionPointTypes.push(Ns.Matrix),i._inputs[3].excludedConnectionPointTypes.push(Ns.Float),i._inputs[3].excludedConnectionPointTypes.push(Ns.Matrix),i}return m(t,e),t.prototype.getClassName=function(){return"ReplaceColorBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"reference",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"distance",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"replacement",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+";\n",t.compilationString+="if (length(".concat(this.value.associatedVariableName," - ").concat(this.reference.associatedVariableName,") < ").concat(this.distance.associatedVariableName,") {\n"),t.compilationString+="".concat(i.associatedVariableName," = ").concat(this.replacement.associatedVariableName,";\n"),t.compilationString+="} else {\n",t.compilationString+="".concat(i.associatedVariableName," = ").concat(this.value.associatedVariableName,";\n"),t.compilationString+="}\n",this},t}(Ws);a("BABYLON.ReplaceColorBlock",Zb);var Jb,$b=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("value",Ns.AutoDetect),i.registerInput("steps",Ns.AutoDetect),i.registerOutput("output",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i._inputs[0].excludedConnectionPointTypes.push(Ns.Matrix),i._inputs[1].excludedConnectionPointTypes.push(Ns.Matrix),i._inputs[1].acceptedConnectionPointTypes.push(Ns.Float),i}return m(t,e),t.prototype.getClassName=function(){return"PosterizeBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"steps",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = floor(".concat(this.value.associatedVariableName," / (1.0 / ").concat(this.steps.associatedVariableName,")) * (1.0 / ").concat(this.steps.associatedVariableName,");\n"),this},t}(Ws);a("BABYLON.PosterizeBlock",$b),function(e){e[e.SawTooth=0]="SawTooth",e[e.Square=1]="Square",e[e.Triangle=2]="Triangle"}(Jb||(Jb={}));var eT=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.kind=Jb.SawTooth,i.registerInput("input",Ns.AutoDetect),i.registerOutput("output",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._inputs[0].excludedConnectionPointTypes.push(Ns.Matrix),i}return m(t,e),t.prototype.getClassName=function(){return"WaveBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];switch(this.kind){case Jb.SawTooth:t.compilationString+=t._declareOutput(i)+" = ".concat(this.input.associatedVariableName," - floor(0.5 + ").concat(this.input.associatedVariableName,");\n");break;case Jb.Square:t.compilationString+=t._declareOutput(i)+" = 1.0 - 2.0 * round(fract(".concat(this.input.associatedVariableName,"));\n");break;case Jb.Triangle:t.compilationString+=t._declareOutput(i)+" = 2.0 * abs(2.0 * (".concat(this.input.associatedVariableName," - floor(0.5 + ").concat(this.input.associatedVariableName,"))) - 1.0;\n")}return this},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.kind=this.kind,t},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),this.kind=t.kind},t}(Ws);a("BABYLON.WaveBlock",eT);var tT=function(){function e(e,t){this.step=e,this.color=t}return Object.defineProperty(e.prototype,"step",{get:function(){return this._step},set:function(e){this._step=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"color",{get:function(){return this._color},set:function(e){this._color=e},enumerable:!1,configurable:!0}),e}(),iT=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.colorSteps=[new tT(0,Z.Black()),new tT(1,Z.White())],i.onValueChangedObservable=new f,i.registerInput("gradient",Ns.AutoDetect),i.registerOutput("output",Ns.Color3),i._inputs[0].addExcludedConnectionPointFromAllowedTypes(Ns.Float|Ns.Vector2|Ns.Vector3|Ns.Vector4|Ns.Color3|Ns.Color4),i}return m(t,e),t.prototype.colorStepsUpdated=function(){this.onValueChangedObservable.notifyObservers(this)},t.prototype.getClassName=function(){return"GradientBlock"},Object.defineProperty(t.prototype,"gradient",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._writeColorConstant=function(e,t){var i=this.colorSteps[e];return"".concat(t,"(").concat(i.color.r,", ").concat(i.color.g,", ").concat(i.color.b,")")},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],r=t._getShaderType(Ns.Vector3);if(this.colorSteps.length&&this.gradient.connectedPoint){var n=t._getFreeVariableName("gradientTempColor"),o=t._getFreeVariableName("gradientTempPosition");t.compilationString+="".concat(t._declareLocalVar(n,Ns.Vector3)," = ").concat(this._writeColorConstant(0,r),";\n"),t.compilationString+="".concat(t._declareLocalVar(o,Ns.Float),";\n");var a=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==Ns.Float&&(a+=".x");for(var s=1;s<this.colorSteps.length;s++){var l=this.colorSteps[s],c=this.colorSteps[s-1];t.compilationString+="".concat(o," = clamp((").concat(a," - ").concat(t._emitFloat(c.step),") / (").concat(t._emitFloat(l.step)," - ").concat(t._emitFloat(c.step),"), 0.0, 1.0) * step(").concat(t._emitFloat(s),", ").concat(t._emitFloat(this.colorSteps.length-1),");\n"),t.compilationString+="".concat(n," = mix(").concat(n,", ").concat(this._writeColorConstant(s,r),", ").concat(o,");\n")}return t.compilationString+=t._declareOutput(i)+" = ".concat(n,";\n"),this}t.compilationString+=t._declareOutput(i)+" = ".concat(r,"(0., 0., 0.);\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);t.colorSteps=[];for(var i=0,r=this.colorSteps;i<r.length;i++){var n=r[i];t.colorSteps.push({step:n.step,color:{r:n.color.r,g:n.color.g,b:n.color.b}})}return t},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),this.colorSteps.length=0;for(var n=0,o=t.colorSteps;n<o.length;n++){var a=o[n];this.colorSteps.push(new tT(a.step,new Z(a.color.r,a.color.g,a.color.b)))}},t.prototype._dumpPropertiesCode=function(){var t=e.prototype._dumpPropertiesCode.call(this);t+="".concat(this._codeVariableName,".colorSteps = [];\n");for(var i=0,r=this.colorSteps;i<r.length;i++){var n=r[i];t+="".concat(this._codeVariableName,".colorSteps.push(new BABYLON.GradientBlockColorStep(").concat(n.step,", new BABYLON.Color3(").concat(n.color.r,", ").concat(n.color.g,", ").concat(n.color.b,")));\n")}return t},t}(Ws);a("BABYLON.GradientBlock",iT);var rT=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("left",Ns.AutoDetect),i.registerInput("right",Ns.AutoDetect),i.registerInput("gradient",Ns.AutoDetect),i.registerOutput("output",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i._linkConnectionTypes(1,2,!0),i._inputs[2].acceptedConnectionPointTypes.push(Ns.Float),i}return m(t,e),t.prototype.getClassName=function(){return"NLerpBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"gradient",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = normalize(mix(".concat(this.left.associatedVariableName," , ").concat(this.right.associatedVariableName,", ").concat(this.gradient.associatedVariableName,"));\n"),this},t}(Ws);a("BABYLON.NLerpBlock",rT);var nT=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.manhattanDistance=!1,i.registerInput("seed",Ns.Vector3),i.registerInput("jitter",Ns.Float),i.registerOutput("output",Ns.Vector2),i.registerOutput("x",Ns.Float),i.registerOutput("y",Ns.Float),i}return m(t,e),t.prototype.getClassName=function(){return"WorleyNoise3DBlock"},Object.defineProperty(t.prototype,"seed",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"jitter",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"x",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"y",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),this.seed.isConnected&&(this.output.hasEndpoints||this.x.hasEndpoints||this.y.hasEndpoints)){t._emitFunction("worley3D","vec3 permute(vec3 x){\n return mod((34.0 * x + 1.0) * x, 289.0);\n}\n\nvec3 dist(vec3 x, vec3 y, vec3 z, bool manhattanDistance){\n return manhattanDistance ? abs(x) + abs(y) + abs(z) : (x * x + y * y + z * z);\n}\n\nvec2 worley(vec3 P, float jitter, bool manhattanDistance){\n float K = 0.142857142857; // 1/7\n float Ko = 0.428571428571; // 1/2-K/2\n float K2 = 0.020408163265306; // 1/(7*7)\n float Kz = 0.166666666667; // 1/6\n float Kzo = 0.416666666667; // 1/2-1/6*2\n\n vec3 Pi = mod(floor(P), 289.0);\n vec3 Pf = fract(P) - 0.5;\n\n vec3 Pfx = Pf.x + vec3(1.0, 0.0, -1.0);\n vec3 Pfy = Pf.y + vec3(1.0, 0.0, -1.0);\n vec3 Pfz = Pf.z + vec3(1.0, 0.0, -1.0);\n\n vec3 p = permute(Pi.x + vec3(-1.0, 0.0, 1.0));\n vec3 p1 = permute(p + Pi.y - 1.0);\n vec3 p2 = permute(p + Pi.y);\n vec3 p3 = permute(p + Pi.y + 1.0);\n\n vec3 p11 = permute(p1 + Pi.z - 1.0);\n vec3 p12 = permute(p1 + Pi.z);\n vec3 p13 = permute(p1 + Pi.z + 1.0);\n\n vec3 p21 = permute(p2 + Pi.z - 1.0);\n vec3 p22 = permute(p2 + Pi.z);\n vec3 p23 = permute(p2 + Pi.z + 1.0);\n\n vec3 p31 = permute(p3 + Pi.z - 1.0);\n vec3 p32 = permute(p3 + Pi.z);\n vec3 p33 = permute(p3 + Pi.z + 1.0);\n\n vec3 ox11 = fract(p11*K) - Ko;\n vec3 oy11 = mod(floor(p11*K), 7.0)*K - Ko;\n vec3 oz11 = floor(p11*K2)*Kz - Kzo; // p11 < 289 guaranteed\n\n vec3 ox12 = fract(p12*K) - Ko;\n vec3 oy12 = mod(floor(p12*K), 7.0)*K - Ko;\n vec3 oz12 = floor(p12*K2)*Kz - Kzo;\n\n vec3 ox13 = fract(p13*K) - Ko;\n vec3 oy13 = mod(floor(p13*K), 7.0)*K - Ko;\n vec3 oz13 = floor(p13*K2)*Kz - Kzo;\n\n vec3 ox21 = fract(p21*K) - Ko;\n vec3 oy21 = mod(floor(p21*K), 7.0)*K - Ko;\n vec3 oz21 = floor(p21*K2)*Kz - Kzo;\n\n vec3 ox22 = fract(p22*K) - Ko;\n vec3 oy22 = mod(floor(p22*K), 7.0)*K - Ko;\n vec3 oz22 = floor(p22*K2)*Kz - Kzo;\n\n vec3 ox23 = fract(p23*K) - Ko;\n vec3 oy23 = mod(floor(p23*K), 7.0)*K - Ko;\n vec3 oz23 = floor(p23*K2)*Kz - Kzo;\n\n vec3 ox31 = fract(p31*K) - Ko;\n vec3 oy31 = mod(floor(p31*K), 7.0)*K - Ko;\n vec3 oz31 = floor(p31*K2)*Kz - Kzo;\n\n vec3 ox32 = fract(p32*K) - Ko;\n vec3 oy32 = mod(floor(p32*K), 7.0)*K - Ko;\n vec3 oz32 = floor(p32*K2)*Kz - Kzo;\n\n vec3 ox33 = fract(p33*K) - Ko;\n vec3 oy33 = mod(floor(p33*K), 7.0)*K - Ko;\n vec3 oz33 = floor(p33*K2)*Kz - Kzo;\n\n vec3 dx11 = Pfx + jitter*ox11;\n vec3 dy11 = Pfy.x + jitter*oy11;\n vec3 dz11 = Pfz.x + jitter*oz11;\n\n vec3 dx12 = Pfx + jitter*ox12;\n vec3 dy12 = Pfy.x + jitter*oy12;\n vec3 dz12 = Pfz.y + jitter*oz12;\n\n vec3 dx13 = Pfx + jitter*ox13;\n vec3 dy13 = Pfy.x + jitter*oy13;\n vec3 dz13 = Pfz.z + jitter*oz13;\n\n vec3 dx21 = Pfx + jitter*ox21;\n vec3 dy21 = Pfy.y + jitter*oy21;\n vec3 dz21 = Pfz.x + jitter*oz21;\n\n vec3 dx22 = Pfx + jitter*ox22;\n vec3 dy22 = Pfy.y + jitter*oy22;\n vec3 dz22 = Pfz.y + jitter*oz22;\n\n vec3 dx23 = Pfx + jitter*ox23;\n vec3 dy23 = Pfy.y + jitter*oy23;\n vec3 dz23 = Pfz.z + jitter*oz23;\n\n vec3 dx31 = Pfx + jitter*ox31;\n vec3 dy31 = Pfy.z + jitter*oy31;\n vec3 dz31 = Pfz.x + jitter*oz31;\n\n vec3 dx32 = Pfx + jitter*ox32;\n vec3 dy32 = Pfy.z + jitter*oy32;\n vec3 dz32 = Pfz.y + jitter*oz32;\n\n vec3 dx33 = Pfx + jitter*ox33;\n vec3 dy33 = Pfy.z + jitter*oy33;\n vec3 dz33 = Pfz.z + jitter*oz33;\n\n vec3 d11 = dist(dx11, dy11, dz11, manhattanDistance);\n vec3 d12 =dist(dx12, dy12, dz12, manhattanDistance);\n vec3 d13 = dist(dx13, dy13, dz13, manhattanDistance);\n vec3 d21 = dist(dx21, dy21, dz21, manhattanDistance);\n vec3 d22 = dist(dx22, dy22, dz22, manhattanDistance);\n vec3 d23 = dist(dx23, dy23, dz23, manhattanDistance);\n vec3 d31 = dist(dx31, dy31, dz31, manhattanDistance);\n vec3 d32 = dist(dx32, dy32, dz32, manhattanDistance);\n vec3 d33 = dist(dx33, dy33, dz33, manhattanDistance);\n\n vec3 d1a = min(d11, d12);\n d12 = max(d11, d12);\n d11 = min(d1a, d13); // Smallest now not in d12 or d13\n d13 = max(d1a, d13);\n d12 = min(d12, d13); // 2nd smallest now not in d13\n vec3 d2a = min(d21, d22);\n d22 = max(d21, d22);\n d21 = min(d2a, d23); // Smallest now not in d22 or d23\n d23 = max(d2a, d23);\n d22 = min(d22, d23); // 2nd smallest now not in d23\n vec3 d3a = min(d31, d32);\n d32 = max(d31, d32);\n d31 = min(d3a, d33); // Smallest now not in d32 or d33\n d33 = max(d3a, d33);\n d32 = min(d32, d33); // 2nd smallest now not in d33\n vec3 da = min(d11, d21);\n d21 = max(d11, d21);\n d11 = min(da, d31); // Smallest now in d11\n d31 = max(da, d31); // 2nd smallest now not in d31\n d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx;\n d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx; // d11.x now smallest\n d12 = min(d12, d21); // 2nd smallest now not in d21\n d12 = min(d12, d22); // nor in d22\n d12 = min(d12, d31); // nor in d31\n d12 = min(d12, d32); // nor in d32\n d11.yz = min(d11.yz,d12.xy); // nor in d12.yz\n d11.y = min(d11.y,d12.z); // Only two more to go\n d11.y = min(d11.y,d11.z); // Done! (Phew!)\n return sqrt(d11.xy); // F1, F2\n}\n\n","// Worley3D");var i=t._getFreeVariableName("worleyTemp");return t.compilationString+="vec2 ".concat(i," = worley(").concat(this.seed.associatedVariableName,", ").concat(this.jitter.associatedVariableName,", ").concat(this.manhattanDistance,");\n"),this.output.hasEndpoints&&(t.compilationString+=t._declareOutput(this.output)+" = ".concat(i,";\n")),this.x.hasEndpoints&&(t.compilationString+=t._declareOutput(this.x)+" = ".concat(i,".x;\n")),this.y.hasEndpoints&&(t.compilationString+=t._declareOutput(this.y)+" = ".concat(i,".y;\n")),this}},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".manhattanDistance = ").concat(this.manhattanDistance,";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.manhattanDistance=this.manhattanDistance,t},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),this.manhattanDistance=t.manhattanDistance},v([Ys("Use Manhattan Distance",Xs.Boolean,"PROPERTIES",{notifiers:{update:!1}})],t.prototype,"manhattanDistance",void 0),t}(Ws);a("BABYLON.WorleyNoise3DBlock",nT);var oT=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("seed",Ns.Vector3),i.registerOutput("output",Ns.Float),i}return m(t,e),t.prototype.getClassName=function(){return"SimplexPerlin3DBlock"},Object.defineProperty(t.prototype,"seed",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),this.seed.isConnected&&this._outputs[0].hasEndpoints)return t._emitFunction("SimplexPerlin3D","const float SKEWFACTOR = 1.0/3.0;\nconst float UNSKEWFACTOR = 1.0/6.0;\nconst float SIMPLEX_CORNER_POS = 0.5;\nconst float SIMPLEX_TETRAHADRON_HEIGHT = 0.70710678118654752440084436210485;\nfloat SimplexPerlin3D( vec3 P ){\n P.x = P == vec3(0., 0., 0.) ? 0.00001 : P.x;\n P *= SIMPLEX_TETRAHADRON_HEIGHT;\n vec3 Pi = floor( P + dot( P, vec3( SKEWFACTOR) ) ); vec3 x0 = P - Pi + dot(Pi, vec3( UNSKEWFACTOR ) );\n vec3 g = step(x0.yzx, x0.xyz);\n vec3 l = 1.0 - g;\n vec3 Pi_1 = min( g.xyz, l.zxy );\n vec3 Pi_2 = max( g.xyz, l.zxy );\n vec3 x1 = x0 - Pi_1 + UNSKEWFACTOR;\n vec3 x2 = x0 - Pi_2 + SKEWFACTOR;\n vec3 x3 = x0 - SIMPLEX_CORNER_POS;\n vec4 v1234_x = vec4( x0.x, x1.x, x2.x, x3.x );\n vec4 v1234_y = vec4( x0.y, x1.y, x2.y, x3.y );\n vec4 v1234_z = vec4( x0.z, x1.z, x2.z, x3.z );\n Pi.xyz = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0;\n vec3 Pi_inc1 = step( Pi, vec3( 69.0 - 1.5 ) ) * ( Pi + 1.0 );\n vec4 Pt = vec4( Pi.xy, Pi_inc1.xy ) + vec2( 50.0, 161.0 ).xyxy;\n Pt *= Pt;\n vec4 V1xy_V2xy = mix( Pt.xyxy, Pt.zwzw, vec4( Pi_1.xy, Pi_2.xy ) );\n Pt = vec4( Pt.x, V1xy_V2xy.xz, Pt.z ) * vec4( Pt.y, V1xy_V2xy.yw, Pt.w );\n const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 );\n const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 );\n vec3 lowz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi.zzz * ZINC.xyz ) );\n vec3 highz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi_inc1.zzz * ZINC.xyz ) );\n Pi_1 = ( Pi_1.z < 0.5 ) ? lowz_mods : highz_mods;\n Pi_2 = ( Pi_2.z < 0.5 ) ? lowz_mods : highz_mods;\n vec4 hash_0 = fract( Pt * vec4( lowz_mods.x, Pi_1.x, Pi_2.x, highz_mods.x ) ) - 0.49999;\n vec4 hash_1 = fract( Pt * vec4( lowz_mods.y, Pi_1.y, Pi_2.y, highz_mods.y ) ) - 0.49999;\n vec4 hash_2 = fract( Pt * vec4( lowz_mods.z, Pi_1.z, Pi_2.z, highz_mods.z ) ) - 0.49999;\n vec4 grad_results = inversesqrt( hash_0 * hash_0 + hash_1 * hash_1 + hash_2 * hash_2 ) * ( hash_0 * v1234_x + hash_1 * v1234_y + hash_2 * v1234_z );\n const float FINAL_NORMALIZATION = 37.837227241611314102871574478976;\n vec4 kernel_weights = v1234_x * v1234_x + v1234_y * v1234_y + v1234_z * v1234_z;\n kernel_weights = max(0.5 - kernel_weights, 0.0);\n kernel_weights = kernel_weights*kernel_weights*kernel_weights;\n return dot( kernel_weights, grad_results ) * FINAL_NORMALIZATION;\n}\n","// SimplexPerlin3D"),t.compilationString+=t._declareOutput(this._outputs[0])+" = SimplexPerlin3D(".concat(this.seed.associatedVariableName,");\n"),this},t}(Ws);a("BABYLON.SimplexPerlin3DBlock",oT);var aT=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("normalMap0",Ns.AutoDetect),i.registerInput("normalMap1",Ns.AutoDetect),i.registerOutput("output",Ns.Vector3),i._inputs[0].addExcludedConnectionPointFromAllowedTypes(Ns.Color3|Ns.Color4|Ns.Vector3|Ns.Vector4),i._inputs[1].addExcludedConnectionPointFromAllowedTypes(Ns.Color3|Ns.Color4|Ns.Vector3|Ns.Vector4),i}return m(t,e),t.prototype.getClassName=function(){return"NormalBlendBlock"},Object.defineProperty(t.prototype,"normalMap0",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"normalMap1",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],r=this._inputs[0],n=this._inputs[1],o=t._getFreeVariableName("stepR"),a=t._getFreeVariableName("stepG");return t.compilationString+="float ".concat(o," = step(0.5, ").concat(r.associatedVariableName,".r);\n"),t.compilationString+="float ".concat(a," = step(0.5, ").concat(r.associatedVariableName,".g);\n"),t.compilationString+=t._declareOutput(i)+";\n",t.compilationString+="".concat(i.associatedVariableName,".r = (1.0 - ").concat(o,") * ").concat(r.associatedVariableName,".r * ").concat(n.associatedVariableName,".r * 2.0 + ").concat(o," * (1.0 - (1.0 - ").concat(r.associatedVariableName,".r) * (1.0 - ").concat(n.associatedVariableName,".r) * 2.0);\n"),t.compilationString+="".concat(i.associatedVariableName,".g = (1.0 - ").concat(a,") * ").concat(r.associatedVariableName,".g * ").concat(n.associatedVariableName,".g * 2.0 + ").concat(a," * (1.0 - (1.0 - ").concat(r.associatedVariableName,".g) * (1.0 - ").concat(n.associatedVariableName,".g) * 2.0);\n"),t.compilationString+="".concat(i.associatedVariableName,".b = ").concat(r.associatedVariableName,".b * ").concat(n.associatedVariableName,".b;\n"),this},t}(Ws);a("BABYLON.NormalBlendBlock",aT);var sT=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("input",Ns.Vector2),i.registerInput("angle",Ns.Float),i.registerOutput("output",Ns.Vector2),i}return m(t,e),t.prototype.getClassName=function(){return"Rotate2dBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"angle",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(){if(!this.angle.isConnected){var e=new rl("angle");e.value=0,e.output.connectTo(this.angle)}},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],r=this.angle,n=this.input;return t.compilationString+=t._declareOutput(i)+" = vec2(cos(".concat(r.associatedVariableName,") * ").concat(n.associatedVariableName,".x - sin(").concat(r.associatedVariableName,") * ").concat(n.associatedVariableName,".y, sin(").concat(r.associatedVariableName,") * ").concat(n.associatedVariableName,".x + cos(").concat(r.associatedVariableName,") * ").concat(n.associatedVariableName,".y);\n"),this},t}(Ws);a("BABYLON.Rotate2dBlock",sT);var lT=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("incident",Ns.AutoDetect),i.registerInput("normal",Ns.AutoDetect),i.registerOutput("output",Ns.Vector3),i._inputs[0].addExcludedConnectionPointFromAllowedTypes(Ns.Vector3|Ns.Vector4|Ns.Color3|Ns.Color4),i._inputs[1].addExcludedConnectionPointFromAllowedTypes(Ns.Vector3|Ns.Vector4|Ns.Color3|Ns.Color4),i}return m(t,e),t.prototype.getClassName=function(){return"ReflectBlock"},Object.defineProperty(t.prototype,"incident",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"normal",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = reflect(".concat(this.incident.associatedVariableName,".xyz, ").concat(this.normal.associatedVariableName,".xyz);\n"),this},t}(Ws);a("BABYLON.ReflectBlock",lT);var cT=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("incident",Ns.AutoDetect),i.registerInput("normal",Ns.AutoDetect),i.registerInput("ior",Ns.Float),i.registerOutput("output",Ns.Vector3),i._inputs[0].addExcludedConnectionPointFromAllowedTypes(Ns.Vector3|Ns.Vector4|Ns.Color3|Ns.Color4),i._inputs[1].addExcludedConnectionPointFromAllowedTypes(Ns.Vector3|Ns.Vector4|Ns.Color3|Ns.Color4),i}return m(t,e),t.prototype.getClassName=function(){return"RefractBlock"},Object.defineProperty(t.prototype,"incident",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"normal",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"ior",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=t._declareOutput(i)+" = refract(".concat(this.incident.associatedVariableName,".xyz, ").concat(this.normal.associatedVariableName,".xyz, ").concat(this.ior.associatedVariableName,");\n"),this},t}(Ws);a("BABYLON.RefractBlock",cT);var uT=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("color",Ns.Color3),i.registerInput("level",Ns.Float),i.registerOutput("output",Ns.Color3),i}return m(t,e),t.prototype.getClassName=function(){return"DesaturateBlock"},Object.defineProperty(t.prototype,"color",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"level",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],r=this.color.associatedVariableName,n=t._getFreeVariableName("colorMin"),o=t._getFreeVariableName("colorMax"),a=t._getFreeVariableName("colorMerge");return t.compilationString+="".concat(t._declareLocalVar(n,Ns.Float)," = min(min(").concat(r,".x, ").concat(r,".y), ").concat(r,".z);\n"),t.compilationString+="".concat(t._declareLocalVar(o,Ns.Float)," = max(max(").concat(r,".x, ").concat(r,".y), ").concat(r,".z);\n"),t.compilationString+="".concat(t._declareLocalVar(a,Ns.Float)," = 0.5 * (").concat(n," + ").concat(o,");\n"),t.compilationString+=t._declareOutput(i)+" = mix(".concat(r,", ").concat(t._getShaderType(Ns.Vector3),"(").concat(a,", ").concat(a,", ").concat(a,"), ").concat(this.level.associatedVariableName,");\n"),this},t}(Ws);a("BABYLON.DesaturateBlock",uT);var hT=function(e){function t(i){var r=e.call(this,i,Fs.Fragment)||this;return r.albedoScaling=!1,r.linkSheenWithAlbedo=!1,r._isUnique=!0,r.registerInput("intensity",Ns.Float,!0,Fs.Fragment),r.registerInput("color",Ns.Color3,!0,Fs.Fragment),r.registerInput("roughness",Ns.Float,!0,Fs.Fragment),r.registerOutput("sheen",Ns.Object,Fs.Fragment,new Qy("sheen",r,Us.Output,t,"SheenBlock")),r}return m(t,e),t.prototype.initialize=function(e){e._excludeVariableName("sheenOut"),e._excludeVariableName("sheenMapData"),e._excludeVariableName("vSheenColor"),e._excludeVariableName("vSheenRoughness")},t.prototype.getClassName=function(){return"SheenBlock"},Object.defineProperty(t.prototype,"intensity",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"color",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"roughness",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"sheen",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.prepareDefines=function(t,i,r){e.prototype.prepareDefines.call(this,t,i,r),r.setValue("SHEEN",!0),r.setValue("SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),r.setValue("SHEEN_LINKWITHALBEDO",this.linkSheenWithAlbedo,!0),r.setValue("SHEEN_ROUGHNESS",this.roughness.isConnected,!0),r.setValue("SHEEN_ALBEDOSCALING",this.albedoScaling,!0)},t.prototype.getCode=function(e){var t=this.color.isConnected?this.color.associatedVariableName:"vec3(1.)",i=this.intensity.isConnected?this.intensity.associatedVariableName:"1.",r=this.roughness.isConnected?this.roughness.associatedVariableName:"0.";return"#ifdef SHEEN\n sheenOutParams sheenOut;\n\n vec4 vSheenColor = vec4(".concat(t,", ").concat(i,");\n\n sheenBlock(\n vSheenColor,\n #ifdef SHEEN_ROUGHNESS\n ").concat(r,",\n #endif\n roughness,\n #ifdef SHEEN_TEXTURE\n ").concat("vec4(0.)",",\n 1.0,\n #endif\n reflectance,\n #ifdef SHEEN_LINKWITHALBEDO\n baseColor,\n surfaceAlbedo,\n #endif\n #ifdef ENVIRONMENTBRDF\n NdotV,\n environmentBrdf,\n #endif\n #if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\n AARoughnessFactors,\n ").concat(null==e?void 0:e._vReflectionMicrosurfaceInfosName,",\n ").concat(null==e?void 0:e._vReflectionInfosName,",\n ").concat(null==e?void 0:e.reflectionColor,",\n vLightingIntensity,\n #ifdef ").concat(null==e?void 0:e._define3DName,"\n ").concat(null==e?void 0:e._cubeSamplerName,",\n #else\n ").concat(null==e?void 0:e._2DSamplerName,",\n #endif\n reflectionOut.reflectionCoords,\n NdotVUnclamped,\n #ifndef LODBASEDMICROSFURACE\n #ifdef ").concat(null==e?void 0:e._define3DName,"\n ").concat(null==e?void 0:e._cubeSamplerName,",\n ").concat(null==e?void 0:e._cubeSamplerName,",\n #else\n ").concat(null==e?void 0:e._2DSamplerName,",\n ").concat(null==e?void 0:e._2DSamplerName,",\n #endif\n #endif\n #if !defined(").concat(null==e?void 0:e._defineSkyboxName,") && defined(RADIANCEOCCLUSION)\n seo,\n #endif\n #if !defined(").concat(null==e?void 0:e._defineSkyboxName,") && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(").concat(null==e?void 0:e._define3DName,")\n eho,\n #endif\n #endif\n sheenOut\n );\n\n #ifdef SHEEN_LINKWITHALBEDO\n surfaceAlbedo = sheenOut.surfaceAlbedo;\n #endif\n #endif\n")},t.prototype._buildBlock=function(e){return e.target===Fs.Fragment&&e.sharedData.blocksWithDefines.push(this),this},t.prototype._dumpPropertiesCode=function(){var t=e.prototype._dumpPropertiesCode.call(this);return(t+="".concat(this._codeVariableName,".albedoScaling = ").concat(this.albedoScaling,";\n"))+"".concat(this._codeVariableName,".linkSheenWithAlbedo = ").concat(this.linkSheenWithAlbedo,";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.albedoScaling=this.albedoScaling,t.linkSheenWithAlbedo=this.linkSheenWithAlbedo,t},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),this.albedoScaling=t.albedoScaling,this.linkSheenWithAlbedo=t.linkSheenWithAlbedo},v([Ys("Albedo scaling",Xs.Boolean,"PROPERTIES",{notifiers:{update:!0}})],t.prototype,"albedoScaling",void 0),v([Ys("Link sheen with albedo",Xs.Boolean,"PROPERTIES",{notifiers:{update:!0}})],t.prototype,"linkSheenWithAlbedo",void 0),t}(Ws);a("BABYLON.SheenBlock",hT);var dT=function(e){function t(i){var r=e.call(this,i,Fs.Fragment)||this;return r._tangentCorrectionFactorName="",r._isUnique=!0,r.registerInput("intensity",Ns.Float,!0,Fs.Fragment),r.registerInput("direction",Ns.Vector2,!0,Fs.Fragment),r.registerInput("uv",Ns.Vector2,!0),r.registerInput("worldTangent",Ns.Vector4,!0),r.registerInput("TBN",Ns.Object,!0,Fs.VertexAndFragment,new Qy("TBN",r,Us.Input,tb,"TBNBlock")),r.registerInput("roughness",Ns.Float,!0,Fs.Fragment),r.registerOutput("anisotropy",Ns.Object,Fs.Fragment,new Qy("anisotropy",r,Us.Output,t,"AnisotropyBlock")),r}return m(t,e),t.prototype.initialize=function(e){e._excludeVariableName("anisotropicOut"),e._excludeVariableName("TBN")},t.prototype.getClassName=function(){return"AnisotropyBlock"},Object.defineProperty(t.prototype,"intensity",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"direction",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"uv",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"worldTangent",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"TBN",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"roughness",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"anisotropy",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._generateTBNSpace=function(e){var t="",i="//".concat(this.name),r=this.uv,n=this.worldPositionConnectionPoint,o=this.worldNormalConnectionPoint,a=this.worldTangent;r.isConnected||ae.Error("You must connect the 'uv' input of the Anisotropy block!"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");var s={search:/defined\(TANGENT\)/g,replace:a.isConnected?"defined(TANGENT)":"defined(IGNORE)"},l=this.TBN;return l.isConnected?e.compilationString+="\n #ifdef TBNBLOCK\n mat3 vTBN = ".concat(l.associatedVariableName,";\n #endif\n "):a.isConnected&&(t+="vec3 tbnNormal = normalize(".concat(o.associatedVariableName,".xyz);\n"),t+="vec3 tbnTangent = normalize(".concat(a.associatedVariableName,".xyz);\n"),t+="vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ".concat(this._tangentCorrectionFactorName,";\n"),t+="mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\n"),t+="\n #if defined(".concat(a.isConnected?"TANGENT":"IGNORE",") && defined(NORMAL)\n mat3 TBN = vTBN;\n #else\n mat3 TBN = cotangent_frame(").concat(o.associatedVariableName+".xyz",", ").concat("v_"+n.associatedVariableName+".xyz",", ").concat(r.isConnected?r.associatedVariableName:"vec2(0.)",", vec2(1., 1.));\n #endif\n"),e._emitFunctionFromInclude("bumpFragmentMainFunctions",i,{replaceStrings:[s]}),t},t.prototype.getCode=function(e,t){void 0===t&&(t=!1);var i="";t&&(i+=this._generateTBNSpace(e));var r=this.intensity.isConnected?this.intensity.associatedVariableName:"1.0",n=this.direction.isConnected?this.direction.associatedVariableName:"vec2(1., 0.)",o=this.roughness.isConnected?this.roughness.associatedVariableName:"0.";return i+"anisotropicOutParams anisotropicOut;\n anisotropicBlock(\n vec3(".concat(n,", ").concat(r,"),\n ").concat(o,",\n #ifdef ANISOTROPIC_TEXTURE\n vec3(0.),\n #endif\n TBN,\n normalW,\n viewDirectionW,\n anisotropicOut\n );\n")},t.prototype.prepareDefines=function(t,i,r){e.prototype.prepareDefines.call(this,t,i,r),r.setValue("ANISOTROPIC",!0),r.setValue("ANISOTROPIC_TEXTURE",!1,!0),r.setValue("ANISOTROPIC_LEGACY",!this.roughness.isConnected)},t.prototype.bind=function(t,i,r){e.prototype.bind.call(this,t,i,r),r&&t.setFloat(this._tangentCorrectionFactorName,r.getWorldMatrix().determinant()<0?-1:1)},t.prototype._buildBlock=function(e){return e.target===Fs.Fragment&&(e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,Ns.Float)),this},t}(Ws);a("BABYLON.AnisotropyBlock",dT);var pT=function(e){function t(i){var r=e.call(this,i)||this;return r.useSphericalHarmonics=!0,r.forceIrradianceInFragment=!1,r._isUnique=!0,r.registerInput("position",Ns.AutoDetect,!1,Fs.Vertex),r.registerInput("world",Ns.Matrix,!1,Fs.Vertex),r.registerInput("color",Ns.Color3,!0,Fs.Fragment),r.registerOutput("reflection",Ns.Object,Fs.Fragment,new Qy("reflection",r,Us.Output,t,"ReflectionBlock")),r.position.addExcludedConnectionPointFromAllowedTypes(Ns.Color3|Ns.Vector3|Ns.Vector4),r}return m(t,e),t.prototype._onGenerateOnlyFragmentCodeChanged=function(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,ae.Error("The position input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)},t.prototype._setTarget=function(){e.prototype._setTarget.call(this),this.getInputByName("position").target=this.generateOnlyFragmentCode?Fs.Fragment:Fs.Vertex,this.generateOnlyFragmentCode&&(this.forceIrradianceInFragment=!0)},t.prototype.getClassName=function(){return"ReflectionBlock"},Object.defineProperty(t.prototype,"position",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"worldPosition",{get:function(){return this.worldPositionConnectionPoint},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"worldNormal",{get:function(){return this.worldNormalConnectionPoint},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"world",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraPosition",{get:function(){return this.cameraPositionConnectionPoint},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"view",{get:function(){return this.viewConnectionPoint},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"color",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"reflection",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hasTexture",{get:function(){return!!this._getTexture()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"reflectionColor",{get:function(){return this.color.isConnected?this.color.associatedVariableName:"vec3(1., 1., 1.)"},enumerable:!1,configurable:!0}),t.prototype._getTexture=function(){return this.texture?this.texture:this._scene.environmentTexture},t.prototype.prepareDefines=function(t,i,r){e.prototype.prepareDefines.call(this,t,i,r);var n=this._getTexture(),o=n&&n.getTextureMatrix;r.setValue("REFLECTION",o,!0),o&&(r.setValue(this._defineLODReflectionAlpha,n.lodLevelInAlpha,!0),r.setValue(this._defineLinearSpecularReflection,n.linearSpecularLOD,!0),r.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem?!n.invertZ:n.invertZ,!0),r.setValue("SPHERICAL_HARMONICS",this.useSphericalHarmonics,!0),r.setValue("GAMMAREFLECTION",n.gammaSpace,!0),r.setValue("RGBDREFLECTION",n.isRGBD,!0),n&&n.coordinatesMode!==Ja.SKYBOX_MODE&&n.isCube&&(r.setValue("USESPHERICALFROMREFLECTIONMAP",!0),r.setValue("USEIRRADIANCEMAP",!1),this.forceIrradianceInFragment||this._scene.getEngine().getCaps().maxVaryingVectors<=8?r.setValue("USESPHERICALINVERTEX",!1):r.setValue("USESPHERICALINVERTEX",!0)))},t.prototype.bind=function(t,i,r,n){e.prototype.bind.call(this,t,i,r);var o=this._getTexture();if(o&&n){o.isCube?t.setTexture(this._cubeSamplerName,o):t.setTexture(this._2DSamplerName,o);var a=o.getSize().width;t.setFloat3(this._vReflectionMicrosurfaceInfosName,a,o.lodGenerationScale,o.lodGenerationOffset),t.setFloat2(this._vReflectionFilteringInfoName,a,j.Log2(a));var s=n.materialDefines,l=o.sphericalPolynomial;if(s.USESPHERICALFROMREFLECTIONMAP&&l)if(s.SPHERICAL_HARMONICS){var c=l.preScaledHarmonics;t.setVector3("vSphericalL00",c.l00),t.setVector3("vSphericalL1_1",c.l1_1),t.setVector3("vSphericalL10",c.l10),t.setVector3("vSphericalL11",c.l11),t.setVector3("vSphericalL2_2",c.l2_2),t.setVector3("vSphericalL2_1",c.l2_1),t.setVector3("vSphericalL20",c.l20),t.setVector3("vSphericalL21",c.l21),t.setVector3("vSphericalL22",c.l22)}else t.setFloat3("vSphericalX",l.x.x,l.x.y,l.x.z),t.setFloat3("vSphericalY",l.y.x,l.y.y,l.y.z),t.setFloat3("vSphericalZ",l.z.x,l.z.y,l.z.z),t.setFloat3("vSphericalXX_ZZ",l.xx.x-l.zz.x,l.xx.y-l.zz.y,l.xx.z-l.zz.z),t.setFloat3("vSphericalYY_ZZ",l.yy.x-l.zz.x,l.yy.y-l.zz.y,l.yy.z-l.zz.z),t.setFloat3("vSphericalZZ",l.zz.x,l.zz.y,l.zz.z),t.setFloat3("vSphericalXY",l.xy.x,l.xy.y,l.xy.z),t.setFloat3("vSphericalYZ",l.yz.x,l.yz.y,l.yz.z),t.setFloat3("vSphericalZX",l.zx.x,l.zx.y,l.zx.z)}},t.prototype.handleVertexSide=function(t){var i=e.prototype.handleVertexSide.call(this,t);t._emitFunctionFromInclude("harmonicsFunctions","//".concat(this.name),{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]});var r=t._getFreeVariableName("reflectionVector");return this._vEnvironmentIrradianceName=t._getFreeVariableName("vEnvironmentIrradiance"),t._emitVaryingFromString(this._vEnvironmentIrradianceName,Ns.Vector3,"defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)"),t._emitUniformFromString("vSphericalL00",Ns.Vector3,"SPHERICAL_HARMONICS"),t._emitUniformFromString("vSphericalL1_1",Ns.Vector3,"SPHERICAL_HARMONICS"),t._emitUniformFromString("vSphericalL10",Ns.Vector3,"SPHERICAL_HARMONICS"),t._emitUniformFromString("vSphericalL11",Ns.Vector3,"SPHERICAL_HARMONICS"),t._emitUniformFromString("vSphericalL2_2",Ns.Vector3,"SPHERICAL_HARMONICS"),t._emitUniformFromString("vSphericalL2_1",Ns.Vector3,"SPHERICAL_HARMONICS"),t._emitUniformFromString("vSphericalL20",Ns.Vector3,"SPHERICAL_HARMONICS"),t._emitUniformFromString("vSphericalL21",Ns.Vector3,"SPHERICAL_HARMONICS"),t._emitUniformFromString("vSphericalL22",Ns.Vector3,"SPHERICAL_HARMONICS"),t._emitUniformFromString("vSphericalX",Ns.Vector3,"SPHERICAL_HARMONICS",!0),t._emitUniformFromString("vSphericalY",Ns.Vector3,"SPHERICAL_HARMONICS",!0),t._emitUniformFromString("vSphericalZ",Ns.Vector3,"SPHERICAL_HARMONICS",!0),t._emitUniformFromString("vSphericalXX_ZZ",Ns.Vector3,"SPHERICAL_HARMONICS",!0),t._emitUniformFromString("vSphericalYY_ZZ",Ns.Vector3,"SPHERICAL_HARMONICS",!0),t._emitUniformFromString("vSphericalZZ",Ns.Vector3,"SPHERICAL_HARMONICS",!0),t._emitUniformFromString("vSphericalXY",Ns.Vector3,"SPHERICAL_HARMONICS",!0),t._emitUniformFromString("vSphericalYZ",Ns.Vector3,"SPHERICAL_HARMONICS",!0),t._emitUniformFromString("vSphericalZX",Ns.Vector3,"SPHERICAL_HARMONICS",!0),i+"#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\n vec3 ".concat(r," = vec3(").concat(this._reflectionMatrixName," * vec4(normalize(").concat(this.worldNormal.associatedVariableName,").xyz, 0)).xyz;\n #ifdef ").concat(this._defineOppositeZ,"\n ").concat(r,".z *= -1.0;\n #endif\n ").concat(this._vEnvironmentIrradianceName," = computeEnvironmentIrradiance(").concat(r,");\n #endif\n")},t.prototype.getCode=function(e,t){var i="";this.handleFragmentSideInits(e),e._emitFunctionFromInclude("harmonicsFunctions","//".concat(this.name),{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]}),e._emitFunction("sampleReflection","\n #ifdef ".concat(this._define3DName,"\n #define sampleReflection(s, c) textureCube(s, c)\n #else\n #define sampleReflection(s, c) texture2D(s, c)\n #endif\n"),"//".concat(this.name)),e._emitFunction("sampleReflectionLod","\n #ifdef ".concat(this._define3DName,"\n #define sampleReflectionLod(s, c, l) textureCubeLodEXT(s, c, l)\n #else\n #define sampleReflectionLod(s, c, l) texture2DLodEXT(s, c, l)\n #endif\n"),"//".concat(this.name));var r="\n vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) {\n ".concat(this.handleFragmentSideCodeReflectionCoords("worldNormal","worldPos",!0,!0),"\n return ").concat(this._reflectionVectorName,";\n }\n");return e._emitFunction("computeReflectionCoordsPBR",r,"//".concat(this.name)),this._vReflectionMicrosurfaceInfosName=e._getFreeVariableName("vReflectionMicrosurfaceInfos"),e._emitUniformFromString(this._vReflectionMicrosurfaceInfosName,Ns.Vector3),this._vReflectionInfosName=e._getFreeVariableName("vReflectionInfos"),this._vReflectionFilteringInfoName=e._getFreeVariableName("vReflectionFilteringInfo"),e._emitUniformFromString(this._vReflectionFilteringInfoName,Ns.Vector2),i+"#ifdef REFLECTION\n vec2 ".concat(this._vReflectionInfosName," = vec2(1., 0.);\n\n reflectionOutParams reflectionOut;\n\n reflectionBlock(\n ").concat(this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName,".xyz,\n ").concat(t,",\n alphaG,\n ").concat(this._vReflectionMicrosurfaceInfosName,",\n ").concat(this._vReflectionInfosName,",\n ").concat(this.reflectionColor,",\n #ifdef ANISOTROPIC\n anisotropicOut,\n #endif\n #if defined(").concat(this._defineLODReflectionAlpha,") && !defined(").concat(this._defineSkyboxName,")\n NdotVUnclamped,\n #endif\n #ifdef ").concat(this._defineLinearSpecularReflection,"\n roughness,\n #endif\n #ifdef ").concat(this._define3DName,"\n ").concat(this._cubeSamplerName,",\n #else\n ").concat(this._2DSamplerName,",\n #endif\n #if defined(NORMAL) && defined(USESPHERICALINVERTEX)\n ").concat(this._vEnvironmentIrradianceName,",\n #endif\n #ifdef USESPHERICALFROMREFLECTIONMAP\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n ").concat(this._reflectionMatrixName,",\n #endif\n #endif\n #ifdef USEIRRADIANCEMAP\n irradianceSampler, // ** not handled **\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef ").concat(this._define3DName,"\n ").concat(this._cubeSamplerName,",\n ").concat(this._cubeSamplerName,",\n #else\n ").concat(this._2DSamplerName,",\n ").concat(this._2DSamplerName,",\n #endif\n #endif\n #ifdef REALTIME_FILTERING\n ").concat(this._vReflectionFilteringInfoName,",\n #endif\n reflectionOut\n );\n #endif\n")},t.prototype._buildBlock=function(e){return this._scene=e.sharedData.scene,e.target!==Fs.Fragment&&(this._defineLODReflectionAlpha=e._getFreeDefineName("LODINREFLECTIONALPHA"),this._defineLinearSpecularReflection=e._getFreeDefineName("LINEARSPECULARREFLECTION")),this},t.prototype._dumpPropertiesCode=function(){var t=e.prototype._dumpPropertiesCode.call(this);return this.texture&&(t+="".concat(this._codeVariableName,".texture.gammaSpace = ").concat(this.texture.gammaSpace,";\n")),(t+="".concat(this._codeVariableName,".useSphericalHarmonics = ").concat(this.useSphericalHarmonics,";\n"))+"".concat(this._codeVariableName,".forceIrradianceInFragment = ").concat(this.forceIrradianceInFragment,";\n")},t.prototype.serialize=function(){var t,i,r=e.prototype.serialize.call(this);return r.useSphericalHarmonics=this.useSphericalHarmonics,r.forceIrradianceInFragment=this.forceIrradianceInFragment,r.gammaSpace=null===(i=null===(t=this.texture)||void 0===t?void 0:t.gammaSpace)||void 0===i||i,r},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),this.useSphericalHarmonics=t.useSphericalHarmonics,this.forceIrradianceInFragment=t.forceIrradianceInFragment,this.texture&&(this.texture.gammaSpace=t.gammaSpace)},v([Ys("Spherical Harmonics",Xs.Boolean,"ADVANCED",{notifiers:{update:!0}})],t.prototype,"useSphericalHarmonics",void 0),v([Ys("Force irradiance in fragment",Xs.Boolean,"ADVANCED",{notifiers:{update:!0}})],t.prototype,"forceIrradianceInFragment",void 0),t}(vb);a("BABYLON.ReflectionBlock",pT);var fT=function(e){function t(i){var r=e.call(this,i,Fs.Fragment)||this;return r._tangentCorrectionFactorName="",r.remapF0OnInterfaceChange=!0,r._isUnique=!0,r.registerInput("intensity",Ns.Float,!1,Fs.Fragment),r.registerInput("roughness",Ns.Float,!0,Fs.Fragment),r.registerInput("indexOfRefraction",Ns.Float,!0,Fs.Fragment),r.registerInput("normalMapColor",Ns.Color3,!0,Fs.Fragment),r.registerInput("uv",Ns.Vector2,!0,Fs.Fragment),r.registerInput("tintColor",Ns.Color3,!0,Fs.Fragment),r.registerInput("tintAtDistance",Ns.Float,!0,Fs.Fragment),r.registerInput("tintThickness",Ns.Float,!0,Fs.Fragment),r.registerInput("worldTangent",Ns.Vector4,!0),r.registerInput("worldNormal",Ns.AutoDetect,!0),r.worldNormal.addExcludedConnectionPointFromAllowedTypes(Ns.Color4|Ns.Vector4|Ns.Vector3),r.registerInput("TBN",Ns.Object,!0,Fs.VertexAndFragment,new Qy("TBN",r,Us.Input,tb,"TBNBlock")),r.registerOutput("clearcoat",Ns.Object,Fs.Fragment,new Qy("clearcoat",r,Us.Output,t,"ClearCoatBlock")),r}return m(t,e),t.prototype.initialize=function(e){e._excludeVariableName("clearcoatOut"),e._excludeVariableName("vClearCoatParams"),e._excludeVariableName("vClearCoatTintParams"),e._excludeVariableName("vClearCoatRefractionParams"),e._excludeVariableName("vClearCoatTangentSpaceParams"),e._excludeVariableName("vGeometricNormaClearCoatW")},t.prototype.getClassName=function(){return"ClearCoatBlock"},Object.defineProperty(t.prototype,"intensity",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"roughness",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"indexOfRefraction",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"normalMapColor",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"uv",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"tintColor",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"tintAtDistance",{get:function(){return this._inputs[6]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"tintThickness",{get:function(){return this._inputs[7]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"worldTangent",{get:function(){return this._inputs[8]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"worldNormal",{get:function(){return this._inputs[9]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"TBN",{get:function(){return this._inputs[10]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"clearcoat",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(){if(!this.intensity.isConnected){var e=new rl("ClearCoat intensity",Fs.Fragment,Ns.Float);e.value=1,e.output.connectTo(this.intensity)}},t.prototype.prepareDefines=function(t,i,r){e.prototype.prepareDefines.call(this,t,i,r),r.setValue("CLEARCOAT",!0),r.setValue("CLEARCOAT_TEXTURE",!1,!0),r.setValue("CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),r.setValue("CLEARCOAT_TINT",this.tintColor.isConnected||this.tintThickness.isConnected||this.tintAtDistance.isConnected,!0),r.setValue("CLEARCOAT_BUMP",this.normalMapColor.isConnected,!0),r.setValue("CLEARCOAT_DEFAULTIOR",!this.indexOfRefraction.isConnected||this.indexOfRefraction.connectInputBlock.value===Xm._DefaultIndexOfRefraction,!0),r.setValue("CLEARCOAT_REMAP_F0",this.remapF0OnInterfaceChange,!0)},t.prototype.bind=function(t,i,r){var n,o;e.prototype.bind.call(this,t,i,r);var a=null!==(o=null===(n=this.indexOfRefraction.connectInputBlock)||void 0===n?void 0:n.value)&&void 0!==o?o:Xm._DefaultIndexOfRefraction,s=1-a,l=1+a,c=Math.pow(-s/l,2),u=1/a;t.setFloat4("vClearCoatRefractionParams",c,u,s,l);var h=this.clearcoat.hasEndpoints?this.clearcoat.endpoints[0].ownerBlock:null,d=(null==h?void 0:h.perturbedNormal.isConnected)?h.perturbedNormal.connectedPoint.ownerBlock:null;this._scene._mirroredCameraPosition?t.setFloat2("vClearCoatTangentSpaceParams",(null==d?void 0:d.invertX)?1:-1,(null==d?void 0:d.invertY)?1:-1):t.setFloat2("vClearCoatTangentSpaceParams",(null==d?void 0:d.invertX)?-1:1,(null==d?void 0:d.invertY)?-1:1),r&&t.setFloat(this._tangentCorrectionFactorName,r.getWorldMatrix().determinant()<0?-1:1)},t.prototype._generateTBNSpace=function(e,t,i){var r="",n="//".concat(this.name),o=this.worldTangent;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");var a={search:/defined\(TANGENT\)/g,replace:o.isConnected?"defined(TANGENT)":"defined(IGNORE)"},s=this.TBN;return s.isConnected?e.compilationString+="\n #ifdef TBNBLOCK\n mat3 vTBN = ".concat(s.associatedVariableName,";\n #endif\n "):o.isConnected&&(r+="vec3 tbnNormal = normalize(".concat(i,".xyz);\n"),r+="vec3 tbnTangent = normalize(".concat(o.associatedVariableName,".xyz);\n"),r+="vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ".concat(this._tangentCorrectionFactorName,";\n"),r+="mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\n"),e._emitFunctionFromInclude("bumpFragmentMainFunctions",n,{replaceStrings:[a]}),r},t.GetCode=function(e,t,i,r,n,o,a){var s="",l=(null==t?void 0:t.intensity.isConnected)?t.intensity.associatedVariableName:"1.",c=(null==t?void 0:t.roughness.isConnected)?t.roughness.associatedVariableName:"0.",u=(null==t?void 0:t.normalMapColor.isConnected)?t.normalMapColor.associatedVariableName:"vec3(0.)",h=(null==t?void 0:t.uv.isConnected)?t.uv.associatedVariableName:"vec2(0.)",d=(null==t?void 0:t.tintColor.isConnected)?t.tintColor.associatedVariableName:"vec3(1.)",p=(null==t?void 0:t.tintThickness.isConnected)?t.tintThickness.associatedVariableName:"1.",f=(null==t?void 0:t.tintAtDistance.isConnected)?t.tintAtDistance.associatedVariableName:"1.";if(t){e._emitUniformFromString("vClearCoatRefractionParams",Ns.Vector4),e._emitUniformFromString("vClearCoatTangentSpaceParams",Ns.Vector2);var _=t.worldNormal;s+="vec3 vGeometricNormaClearCoatW = ".concat(_.isConnected?"normalize("+_.associatedVariableName+".xyz)":"geometricNormalW",";\n")}else s+="vec3 vGeometricNormaClearCoatW = geometricNormalW;\n";return n&&t&&(s+=t._generateTBNSpace(e,r,a),o=t.worldTangent.isConnected),s+"clearcoatOutParams clearcoatOut;\n\n #ifdef CLEARCOAT\n vec2 vClearCoatParams = vec2(".concat(l,", ").concat(c,");\n vec4 vClearCoatTintParams = vec4(").concat(d,", ").concat(p,");\n\n clearcoatBlock(\n ").concat(r,".xyz,\n vGeometricNormaClearCoatW,\n viewDirectionW,\n vClearCoatParams,\n specularEnvironmentR0,\n #ifdef CLEARCOAT_TEXTURE\n vec2(0.),\n #endif\n #ifdef CLEARCOAT_TINT\n vClearCoatTintParams,\n ").concat(f,",\n vClearCoatRefractionParams,\n #ifdef CLEARCOAT_TINT_TEXTURE\n ").concat("vec4(0.)",",\n #endif\n #endif\n #ifdef CLEARCOAT_BUMP\n vec2(0., 1.),\n vec4(").concat(u,", 0.),\n ").concat(h,",\n #if defined(").concat(o?"TANGENT":"IGNORE",") && defined(NORMAL)\n vTBN,\n #else\n vClearCoatTangentSpaceParams,\n #endif\n #ifdef OBJECTSPACE_NORMALMAP\n normalMatrix,\n #endif\n #endif\n #if defined(FORCENORMALFORWARD) && defined(NORMAL)\n faceNormal,\n #endif\n #ifdef REFLECTION\n ").concat(null==i?void 0:i._vReflectionMicrosurfaceInfosName,",\n ").concat(null==i?void 0:i._vReflectionInfosName,",\n ").concat(null==i?void 0:i.reflectionColor,",\n vLightingIntensity,\n #ifdef ").concat(null==i?void 0:i._define3DName,"\n ").concat(null==i?void 0:i._cubeSamplerName,",\n #else\n ").concat(null==i?void 0:i._2DSamplerName,",\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef ").concat(null==i?void 0:i._define3DName,"\n ").concat(null==i?void 0:i._cubeSamplerName,",\n ").concat(null==i?void 0:i._cubeSamplerName,",\n #else\n ").concat(null==i?void 0:i._2DSamplerName,",\n ").concat(null==i?void 0:i._2DSamplerName,",\n #endif\n #endif\n #endif\n #if defined(ENVIRONMENTBRDF) && !defined(").concat(null==i?void 0:i._defineSkyboxName,")\n #ifdef RADIANCEOCCLUSION\n ambientMonochrome,\n #endif\n #endif\n #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)\n (gl_FrontFacing ? 1. : -1.),\n #endif\n clearcoatOut\n );\n #else\n clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0;\n #endif\n")},t.prototype._buildBlock=function(e){return this._scene=e.sharedData.scene,e.target===Fs.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,Ns.Float)),this},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".remapF0OnInterfaceChange = ").concat(this.remapF0OnInterfaceChange,";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.remapF0OnInterfaceChange=this.remapF0OnInterfaceChange,t},t.prototype._deserialize=function(t,i,r){var n;e.prototype._deserialize.call(this,t,i,r),this.remapF0OnInterfaceChange=null===(n=t.remapF0OnInterfaceChange)||void 0===n||n},v([Ys("Remap F0 on interface change",Xs.Boolean,"ADVANCED")],t.prototype,"remapF0OnInterfaceChange",void 0),t}(Ws);a("BABYLON.ClearCoatBlock",fT);var _T=function(e){function t(i){var r=e.call(this,i,Fs.Fragment)||this;return r._isUnique=!0,r.registerInput("intensity",Ns.Float,!0,Fs.Fragment),r.registerInput("indexOfRefraction",Ns.Float,!0,Fs.Fragment),r.registerInput("thickness",Ns.Float,!0,Fs.Fragment),r.registerOutput("iridescence",Ns.Object,Fs.Fragment,new Qy("iridescence",r,Us.Output,t,"IridescenceBlock")),r}return m(t,e),t.prototype.initialize=function(e){e._excludeVariableName("iridescenceOut"),e._excludeVariableName("vIridescenceParams")},t.prototype.getClassName=function(){return"IridescenceBlock"},Object.defineProperty(t.prototype,"intensity",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"indexOfRefraction",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"thickness",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"iridescence",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(){if(!this.intensity.isConnected){var e=new rl("Iridescence intensity",Fs.Fragment,Ns.Float);e.value=1,e.output.connectTo(this.intensity);var t=new rl("Iridescence ior",Fs.Fragment,Ns.Float);t.value=1.3,t.output.connectTo(this.indexOfRefraction);var i=new rl("Iridescence thickness",Fs.Fragment,Ns.Float);i.value=400,i.output.connectTo(this.thickness)}},t.prototype.prepareDefines=function(t,i,r){e.prototype.prepareDefines.call(this,t,i,r),r.setValue("IRIDESCENCE",!0,!0),r.setValue("IRIDESCENCE_TEXTURE",!1,!0),r.setValue("IRIDESCENCE_THICKNESS_TEXTURE",!1,!0)},t.GetCode=function(e){var t="",i=(null==e?void 0:e.intensity.isConnected)?e.intensity.associatedVariableName:"1.",r=(null==e?void 0:e.indexOfRefraction.isConnected)?e.indexOfRefraction.associatedVariableName:Ym._DefaultIndexOfRefraction,n=(null==e?void 0:e.thickness.isConnected)?e.thickness.associatedVariableName:Ym._DefaultMaximumThickness;return t+"iridescenceOutParams iridescenceOut;\n\n #ifdef IRIDESCENCE\n iridescenceBlock(\n vec4(".concat(i,", ").concat(r,", 1., ").concat(n,"),\n NdotV,\n specularEnvironmentR0,\n #ifdef CLEARCOAT\n NdotVUnclamped,\n #endif\n iridescenceOut\n );\n\n float iridescenceIntensity = iridescenceOut.iridescenceIntensity;\n specularEnvironmentR0 = iridescenceOut.specularEnvironmentR0;\n #endif\n")},t.prototype._buildBlock=function(e){return e.target===Fs.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this)),this},t.prototype.serialize=function(){return e.prototype.serialize.call(this)},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r)},t}(Ws);a("BABYLON.IridescenceBlock",_T);var mT=function(e){function t(i){var r=e.call(this,i,Fs.Fragment)||this;return r.linkRefractionWithTransparency=!1,r.invertRefractionY=!1,r.useThicknessAsDepth=!1,r._isUnique=!0,r.registerInput("intensity",Ns.Float,!1,Fs.Fragment),r.registerInput("tintAtDistance",Ns.Float,!0,Fs.Fragment),r.registerInput("volumeIndexOfRefraction",Ns.Float,!0,Fs.Fragment),r.registerOutput("refraction",Ns.Object,Fs.Fragment,new Qy("refraction",r,Us.Output,t,"RefractionBlock")),r}return m(t,e),t.prototype.initialize=function(e){e._excludeVariableName("vRefractionPosition"),e._excludeVariableName("vRefractionSize")},t.prototype.getClassName=function(){return"RefractionBlock"},Object.defineProperty(t.prototype,"intensity",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"tintAtDistance",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"volumeIndexOfRefraction",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"view",{get:function(){return this.viewConnectionPoint},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"refraction",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hasTexture",{get:function(){return!!this._getTexture()},enumerable:!1,configurable:!0}),t.prototype._getTexture=function(){return this.texture?this.texture:this._scene.environmentTexture},t.prototype.autoConfigure=function(e,t){if(void 0===t&&(t=function(){return!0}),!this.intensity.isConnected){var i=new rl("Refraction intensity",Fs.Fragment,Ns.Float);i.value=1,i.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){var r=e.getInputBlockByPredicate((function(e){return e.systemValue===Qs.View&&t(e)}));r||(r=new rl("view")).setAsSystemValue(Qs.View),r.output.connectTo(this.view)}},t.prototype.prepareDefines=function(t,i,r){e.prototype.prepareDefines.call(this,t,i,r);var n=this._getTexture(),o=n&&n.getTextureMatrix;r.setValue("SS_REFRACTION",o,!0),o&&(r.setValue(this._define3DName,n.isCube,!0),r.setValue(this._defineLODRefractionAlpha,n.lodLevelInAlpha,!0),r.setValue(this._defineLinearSpecularRefraction,n.linearSpecularLOD,!0),r.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&n.isCube?!n.invertZ:n.invertZ,!0),r.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),r.setValue("SS_GAMMAREFRACTION",n.gammaSpace,!0),r.setValue("SS_RGBDREFRACTION",n.isRGBD,!0),r.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!n.boundingBoxSize,!0),r.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))},t.prototype.isReady=function(){var e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())},t.prototype.bind=function(t,i,r){var n,o,a,s;e.prototype.bind.call(this,t,i,r);var l=this._getTexture();if(l){l.isCube?t.setTexture(this._cubeSamplerName,l):t.setTexture(this._2DSamplerName,l),t.setMatrix(this._refractionMatrixName,l.getRefractionTextureMatrix());var c=1;l.isCube||l.depth&&(c=l.depth);var u=null!==(s=null!==(o=null===(n=this.volumeIndexOfRefraction.connectInputBlock)||void 0===n?void 0:n.value)&&void 0!==o?o:null===(a=this.indexOfRefractionConnectionPoint.connectInputBlock)||void 0===a?void 0:a.value)&&void 0!==s?s:1.5;t.setFloat4(this._vRefractionInfosName,l.level,1/u,c,this.invertRefractionY?-1:1),t.setFloat4(this._vRefractionMicrosurfaceInfosName,l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset,1/u);var h=l.getSize().width;if(t.setFloat2(this._vRefractionFilteringInfoName,h,j.Log2(h)),l.boundingBoxSize){var d=l;t.setVector3("vRefractionPosition",d.boundingBoxPosition),t.setVector3("vRefractionSize",d.boundingBoxSize)}}},t.prototype.getCode=function(e){return e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),this._define3DName=e._getFreeDefineName("SS_REFRACTIONMAP_3D"),e._samplerDeclaration+="#ifdef ".concat(this._define3DName,"\n"),e._samplerDeclaration+="uniform samplerCube ".concat(this._cubeSamplerName,";\n"),e._samplerDeclaration+="#else\n",e._samplerDeclaration+="uniform sampler2D ".concat(this._2DSamplerName,";\n"),e._samplerDeclaration+="#endif\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._defineLODRefractionAlpha=e._getFreeDefineName("SS_LODINREFRACTIONALPHA"),this._defineLinearSpecularRefraction=e._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),this._defineOppositeZ=e._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),this._refractionMatrixName=e._getFreeVariableName("refractionMatrix"),e._emitUniformFromString(this._refractionMatrixName,Ns.Matrix),e._emitFunction("sampleRefraction","\n #ifdef ".concat(this._define3DName,"\n #define sampleRefraction(s, c) textureCube(s, c)\n #else\n #define sampleRefraction(s, c) texture2D(s, c)\n #endif\n"),"//".concat(this.name)),e._emitFunction("sampleRefractionLod","\n #ifdef ".concat(this._define3DName,"\n #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l)\n #else\n #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l)\n #endif\n"),"//".concat(this.name)),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,Ns.Vector4),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,Ns.Vector4),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,Ns.Vector2),e._emitUniformFromString("vRefractionPosition",Ns.Vector3),e._emitUniformFromString("vRefractionSize",Ns.Vector3),""},t.prototype._buildBlock=function(e){return this._scene=e.sharedData.scene,this},t.prototype._dumpPropertiesCode=function(){var t=e.prototype._dumpPropertiesCode.call(this);return this.texture&&(t=this.texture.isCube?"".concat(this._codeVariableName,'.texture = new BABYLON.CubeTexture("').concat(this.texture.name,'");\n'):"".concat(this._codeVariableName,'.texture = new BABYLON.Texture("').concat(this.texture.name,'");\n'),t+="".concat(this._codeVariableName,".texture.coordinatesMode = ").concat(this.texture.coordinatesMode,";\n")),t+="".concat(this._codeVariableName,".linkRefractionWithTransparency = ").concat(this.linkRefractionWithTransparency,";\n"),(t+="".concat(this._codeVariableName,".invertRefractionY = ").concat(this.invertRefractionY,";\n"))+"".concat(this._codeVariableName,".useThicknessAsDepth = ").concat(this.useThicknessAsDepth,";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return this.texture&&!this.texture.isRenderTarget&&(t.texture=this.texture.serialize()),t.linkRefractionWithTransparency=this.linkRefractionWithTransparency,t.invertRefractionY=this.invertRefractionY,t.useThicknessAsDepth=this.useThicknessAsDepth,t},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),t.texture&&(r=0===t.texture.url.indexOf("data:")?"":r,t.texture.isCube?this.texture=Nm.Parse(t.texture,i,r):this.texture=Ja.Parse(t.texture,i,r)),this.linkRefractionWithTransparency=t.linkRefractionWithTransparency,this.invertRefractionY=t.invertRefractionY,this.useThicknessAsDepth=!!t.useThicknessAsDepth},v([Ys("Link refraction to transparency",Xs.Boolean,"ADVANCED",{notifiers:{update:!0}})],t.prototype,"linkRefractionWithTransparency",void 0),v([Ys("Invert refraction Y",Xs.Boolean,"ADVANCED",{notifiers:{update:!0}})],t.prototype,"invertRefractionY",void 0),v([Ys("Use thickness as depth",Xs.Boolean,"ADVANCED",{notifiers:{update:!0}})],t.prototype,"useThicknessAsDepth",void 0),t}(Ws);a("BABYLON.RefractionBlock",mT);var gT=function(e){function t(i){var r=e.call(this,i,Fs.Fragment)||this;return r._isUnique=!0,r.registerInput("thickness",Ns.Float,!1,Fs.Fragment),r.registerInput("tintColor",Ns.Color3,!0,Fs.Fragment),r.registerInput("translucencyIntensity",Ns.Float,!0,Fs.Fragment),r.registerInput("translucencyDiffusionDist",Ns.Color3,!0,Fs.Fragment),r.registerInput("refraction",Ns.Object,!0,Fs.Fragment,new Qy("refraction",r,Us.Input,mT,"RefractionBlock")),r.registerInput("dispersion",Ns.Float,!0,Fs.Fragment),r.registerOutput("subsurface",Ns.Object,Fs.Fragment,new Qy("subsurface",r,Us.Output,t,"SubSurfaceBlock")),r}return m(t,e),t.prototype.initialize=function(e){e._excludeVariableName("subSurfaceOut"),e._excludeVariableName("vThicknessParam"),e._excludeVariableName("vTintColor"),e._excludeVariableName("vTranslucencyColor"),e._excludeVariableName("vSubSurfaceIntensity"),e._excludeVariableName("dispersion")},t.prototype.getClassName=function(){return"SubSurfaceBlock"},Object.defineProperty(t.prototype,"thickness",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"tintColor",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"translucencyIntensity",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"translucencyDiffusionDist",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"refraction",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dispersion",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subsurface",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(){if(!this.thickness.isConnected){var e=new rl("SubSurface thickness",Fs.Fragment,Ns.Float);e.value=0,e.output.connectTo(this.thickness)}},t.prototype.prepareDefines=function(t,i,r){e.prototype.prepareDefines.call(this,t,i,r);var n=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;r.setValue("SUBSURFACE",n||this.refraction.isConnected,!0),r.setValue("SS_TRANSLUCENCY",n,!0),r.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),r.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),r.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),r.setValue("SS_USE_GLTF_TEXTURES",!1,!0),r.setValue("SS_DISPERSION",this.dispersion.isConnected,!0)},t.GetCode=function(e,t,i,r){var n,o,a,s,l,c,u,h,d,p,f,_,m,g,v,y,b="",T=(null==t?void 0:t.thickness.isConnected)?t.thickness.associatedVariableName:"0.",E=(null==t?void 0:t.tintColor.isConnected)?t.tintColor.associatedVariableName:"vec3(1.)",S=(null==t?void 0:t.translucencyIntensity.isConnected)?null==t?void 0:t.translucencyIntensity.associatedVariableName:"1.",x=(null==t?void 0:t.translucencyDiffusionDist.isConnected)?null==t?void 0:t.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",A=(null==t?void 0:t.refraction.isConnected)?null===(n=null==t?void 0:t.refraction.connectedPoint)||void 0===n?void 0:n.ownerBlock:null,C=(null==A?void 0:A.tintAtDistance.isConnected)?A.tintAtDistance.associatedVariableName:"1.",R=(null==A?void 0:A.intensity.isConnected)?A.intensity.associatedVariableName:"1.",P=(null==A?void 0:A.view.isConnected)?A.view.associatedVariableName:"",I=(null==t?void 0:t.dispersion.isConnected)?null==t?void 0:t.dispersion.associatedVariableName:"0.0";return(b+=null!==(o=null==A?void 0:A.getCode(e))&&void 0!==o?o:"")+"subSurfaceOutParams subSurfaceOut;\n\n #ifdef SUBSURFACE\n vec2 vThicknessParam = vec2(0., ".concat(T,");\n vec4 vTintColor = vec4(").concat(E,", ").concat(C,");\n vec3 vSubSurfaceIntensity = vec3(").concat(R,", ").concat(S,", 0.);\n float dispersion = ").concat(I,";\n subSurfaceBlock(\n vSubSurfaceIntensity,\n vThicknessParam,\n vTintColor,\n normalW,\n specularEnvironmentReflectance,\n #ifdef SS_THICKNESSANDMASK_TEXTURE\n vec4(0.),\n #endif\n #ifdef REFLECTION\n #ifdef SS_TRANSLUCENCY\n ").concat(null==i?void 0:i._reflectionMatrixName,",\n #ifdef USESPHERICALFROMREFLECTIONMAP\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n reflectionOut.irradianceVector,\n #endif\n #if defined(REALTIME_FILTERING)\n ").concat(null==i?void 0:i._cubeSamplerName,",\n ").concat(null==i?void 0:i._vReflectionFilteringInfoName,",\n #endif\n #endif\n #ifdef USEIRRADIANCEMAP\n irradianceSampler,\n #endif\n #endif\n #endif\n #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\n surfaceAlbedo,\n #endif\n #ifdef SS_REFRACTION\n ").concat(r,".xyz,\n viewDirectionW,\n ").concat(P,",\n ").concat(null!==(a=null==A?void 0:A._vRefractionInfosName)&&void 0!==a?a:"",",\n ").concat(null!==(s=null==A?void 0:A._refractionMatrixName)&&void 0!==s?s:"",",\n ").concat(null!==(l=null==A?void 0:A._vRefractionMicrosurfaceInfosName)&&void 0!==l?l:"",",\n vLightingIntensity,\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha,\n #endif\n #ifdef ").concat(null!==(c=null==A?void 0:A._defineLODRefractionAlpha)&&void 0!==c?c:"IGNORE","\n NdotVUnclamped,\n #endif\n #ifdef ").concat(null!==(u=null==A?void 0:A._defineLinearSpecularRefraction)&&void 0!==u?u:"IGNORE","\n roughness,\n #endif\n alphaG,\n #ifdef ").concat(null!==(h=null==A?void 0:A._define3DName)&&void 0!==h?h:"IGNORE","\n ").concat(null!==(d=null==A?void 0:A._cubeSamplerName)&&void 0!==d?d:"",",\n #else\n ").concat(null!==(p=null==A?void 0:A._2DSamplerName)&&void 0!==p?p:"",",\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef ").concat(null!==(f=null==A?void 0:A._define3DName)&&void 0!==f?f:"IGNORE","\n ").concat(null!==(_=null==A?void 0:A._cubeSamplerName)&&void 0!==_?_:"",",\n ").concat(null!==(m=null==A?void 0:A._cubeSamplerName)&&void 0!==m?m:"",",\n #else\n ").concat(null!==(g=null==A?void 0:A._2DSamplerName)&&void 0!==g?g:"",",\n ").concat(null!==(v=null==A?void 0:A._2DSamplerName)&&void 0!==v?v:"",",\n #endif\n #endif\n #ifdef ANISOTROPIC\n anisotropicOut,\n #endif\n #ifdef REALTIME_FILTERING\n ").concat(null!==(y=null==A?void 0:A._vRefractionFilteringInfoName)&&void 0!==y?y:"",",\n #endif\n #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n vRefractionPosition,\n vRefractionSize,\n #endif\n #ifdef SS_DISPERSION\n dispersion,\n #endif\n #endif\n #ifdef SS_TRANSLUCENCY\n ").concat(x,",\n vTintColor,\n #ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\n vec4(0.),\n #endif\n #endif\n subSurfaceOut\n );\n\n #ifdef SS_REFRACTION\n surfaceAlbedo = subSurfaceOut.surfaceAlbedo;\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha = subSurfaceOut.alpha;\n #endif\n #endif\n #else\n subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance;\n #endif\n")},t.prototype._buildBlock=function(e){return e.target===Fs.Fragment&&e.sharedData.blocksWithDefines.push(this),this},t}(Ws);a("BABYLON.SubSurfaceBlock",gT);var vT={ambientClr:["finalAmbient",""],diffuseDir:["finalDiffuse",""],specularDir:["finalSpecularScaled","!defined(UNLIT) && defined(SPECULARTERM)"],clearcoatDir:["finalClearCoatScaled","!defined(UNLIT) && defined(CLEARCOAT)"],sheenDir:["finalSheenScaled","!defined(UNLIT) && defined(SHEEN)"],diffuseInd:["finalIrradiance","!defined(UNLIT) && defined(REFLECTION)"],specularInd:["finalRadianceScaled","!defined(UNLIT) && defined(REFLECTION)"],clearcoatInd:["clearcoatOut.finalClearCoatRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],sheenInd:["sheenOut.finalSheenRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],refraction:["subSurfaceOut.finalRefraction","!defined(UNLIT) && defined(SS_REFRACTION)"],lighting:["finalColor.rgb",""],shadow:["aggShadow",""],alpha:["alpha",""]},yT=function(e){function t(t){var i=e.call(this,t,Fs.VertexAndFragment)||this;return i._environmentBRDFTexture=null,i._metallicReflectanceColor=Z.White(),i._metallicF0Factor=1,i.directIntensity=1,i.environmentIntensity=1,i.specularIntensity=1,i.lightFalloff=0,i.useAlphaTest=!1,i.alphaTestCutoff=.5,i.useAlphaBlending=!1,i.useRadianceOverAlpha=!0,i.useSpecularOverAlpha=!0,i.enableSpecularAntiAliasing=!1,i.realTimeFiltering=!1,i.realTimeFilteringQuality=u.TEXTURE_FILTERING_QUALITY_LOW,i.useEnergyConservation=!0,i.useRadianceOcclusion=!0,i.useHorizonOcclusion=!0,i.unlit=!1,i.forceNormalForward=!1,i.generateOnlyFragmentCode=!1,i.debugMode=0,i.debugLimit=0,i.debugFactor=1,i._isUnique=!0,i.registerInput("worldPosition",Ns.Vector4,!1,Fs.Vertex),i.registerInput("worldNormal",Ns.Vector4,!1,Fs.Fragment),i.registerInput("view",Ns.Matrix,!1),i.registerInput("cameraPosition",Ns.Vector3,!1,Fs.Fragment),i.registerInput("perturbedNormal",Ns.Vector4,!0,Fs.Fragment),i.registerInput("baseColor",Ns.Color3,!0,Fs.Fragment),i.registerInput("metallic",Ns.Float,!1,Fs.Fragment),i.registerInput("roughness",Ns.Float,!1,Fs.Fragment),i.registerInput("ambientOcc",Ns.Float,!0,Fs.Fragment),i.registerInput("opacity",Ns.Float,!0,Fs.Fragment),i.registerInput("indexOfRefraction",Ns.Float,!0,Fs.Fragment),i.registerInput("ambientColor",Ns.Color3,!0,Fs.Fragment),i.registerInput("reflection",Ns.Object,!0,Fs.Fragment,new Qy("reflection",i,Us.Input,pT,"ReflectionBlock")),i.registerInput("clearcoat",Ns.Object,!0,Fs.Fragment,new Qy("clearcoat",i,Us.Input,fT,"ClearCoatBlock")),i.registerInput("sheen",Ns.Object,!0,Fs.Fragment,new Qy("sheen",i,Us.Input,hT,"SheenBlock")),i.registerInput("subsurface",Ns.Object,!0,Fs.Fragment,new Qy("subsurface",i,Us.Input,gT,"SubSurfaceBlock")),i.registerInput("anisotropy",Ns.Object,!0,Fs.Fragment,new Qy("anisotropy",i,Us.Input,dT,"AnisotropyBlock")),i.registerInput("iridescence",Ns.Object,!0,Fs.Fragment,new Qy("iridescence",i,Us.Input,_T,"IridescenceBlock")),i.registerOutput("ambientClr",Ns.Color3,Fs.Fragment),i.registerOutput("diffuseDir",Ns.Color3,Fs.Fragment),i.registerOutput("specularDir",Ns.Color3,Fs.Fragment),i.registerOutput("clearcoatDir",Ns.Color3,Fs.Fragment),i.registerOutput("sheenDir",Ns.Color3,Fs.Fragment),i.registerOutput("diffuseInd",Ns.Color3,Fs.Fragment),i.registerOutput("specularInd",Ns.Color3,Fs.Fragment),i.registerOutput("clearcoatInd",Ns.Color3,Fs.Fragment),i.registerOutput("sheenInd",Ns.Color3,Fs.Fragment),i.registerOutput("refraction",Ns.Color3,Fs.Fragment),i.registerOutput("lighting",Ns.Color3,Fs.Fragment),i.registerOutput("shadow",Ns.Float,Fs.Fragment),i.registerOutput("alpha",Ns.Float,Fs.Fragment),i}return m(t,e),t._OnGenerateOnlyFragmentCodeChanged=function(e,t){var i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,ae.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)},t.prototype._setTarget=function(){this._setInitialTarget(this.generateOnlyFragmentCode?Fs.Fragment:Fs.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?Fs.Fragment:Fs.Vertex},t.prototype.initialize=function(e){e._excludeVariableName("vLightingIntensity"),e._excludeVariableName("geometricNormalW"),e._excludeVariableName("normalW"),e._excludeVariableName("faceNormal"),e._excludeVariableName("albedoOpacityOut"),e._excludeVariableName("surfaceAlbedo"),e._excludeVariableName("alpha"),e._excludeVariableName("aoOut"),e._excludeVariableName("baseColor"),e._excludeVariableName("reflectivityOut"),e._excludeVariableName("microSurface"),e._excludeVariableName("roughness"),e._excludeVariableName("NdotVUnclamped"),e._excludeVariableName("NdotV"),e._excludeVariableName("alphaG"),e._excludeVariableName("AARoughnessFactors"),e._excludeVariableName("environmentBrdf"),e._excludeVariableName("ambientMonochrome"),e._excludeVariableName("seo"),e._excludeVariableName("eho"),e._excludeVariableName("environmentRadiance"),e._excludeVariableName("irradianceVector"),e._excludeVariableName("environmentIrradiance"),e._excludeVariableName("diffuseBase"),e._excludeVariableName("specularBase"),e._excludeVariableName("preInfo"),e._excludeVariableName("info"),e._excludeVariableName("shadow"),e._excludeVariableName("finalDiffuse"),e._excludeVariableName("finalAmbient"),e._excludeVariableName("ambientOcclusionForDirectDiffuse"),e._excludeVariableName("finalColor"),e._excludeVariableName("vClipSpacePosition"),e._excludeVariableName("vDebugMode")},t.prototype.getClassName=function(){return"PBRMetallicRoughnessBlock"},Object.defineProperty(t.prototype,"worldPosition",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"worldNormal",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"view",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cameraPosition",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"perturbedNormal",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"baseColor",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"metallic",{get:function(){return this._inputs[6]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"roughness",{get:function(){return this._inputs[7]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"ambientOcc",{get:function(){return this._inputs[8]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"opacity",{get:function(){return this._inputs[9]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"indexOfRefraction",{get:function(){return this._inputs[10]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"ambientColor",{get:function(){return this._inputs[11]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"reflection",{get:function(){return this._inputs[12]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"clearcoat",{get:function(){return this._inputs[13]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"sheen",{get:function(){return this._inputs[14]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subsurface",{get:function(){return this._inputs[15]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"anisotropy",{get:function(){return this._inputs[16]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"iridescence",{get:function(){return this._inputs[17]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"ambientClr",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"diffuseDir",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"specularDir",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"clearcoatDir",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"sheenDir",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"diffuseInd",{get:function(){return this._outputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"specularInd",{get:function(){return this._outputs[6]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"clearcoatInd",{get:function(){return this._outputs[7]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"sheenInd",{get:function(){return this._outputs[8]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"refraction",{get:function(){return this._outputs[9]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"lighting",{get:function(){return this._outputs[10]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"shadow",{get:function(){return this._outputs[11]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"alpha",{get:function(){return this._outputs[12]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(e,t){if(void 0===t&&(t=function(){return!0}),!this.cameraPosition.isConnected){var i=e.getInputBlockByPredicate((function(e){return e.systemValue===Qs.CameraPosition&&t(e)}));i||(i=new rl("cameraPosition")).setAsSystemValue(Qs.CameraPosition),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){var r=e.getInputBlockByPredicate((function(e){return e.systemValue===Qs.View&&t(e)}));r||(r=new rl("view")).setAsSystemValue(Qs.View),r.output.connectTo(this.view)}},t.prototype.prepareDefines=function(e,t,i){i.setValue("PBR",!0),i.setValue("METALLICWORKFLOW",!0),i.setValue("DEBUGMODE",this.debugMode,!0),i.setValue("DEBUGMODE_FORCERETURN",!0),i.setValue("NORMALXYSCALE",!0),i.setValue("BUMP",this.perturbedNormal.isConnected,!0),i.setValue("LODBASEDMICROSFURACE",this._scene.getEngine().getCaps().textureLOD),i.setValue("ALBEDO",!1,!0),i.setValue("OPACITY",this.opacity.isConnected,!0),i.setValue("AMBIENT",!0,!0),i.setValue("AMBIENTINGRAYSCALE",!1,!0),i.setValue("REFLECTIVITY",!1,!0),i.setValue("AOSTOREINMETALMAPRED",!1,!0),i.setValue("METALLNESSSTOREINMETALMAPBLUE",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPALPHA",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPGREEN",!1,!0),this.lightFalloff===ig.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===ig.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));var r=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",r.indexOf(".")<0?r+".":r,!0),i.setValue("OPACITYRGB",!1,!0),i.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),i.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),i.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),i.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);var n=e.getScene();if(n.getEngine()._features.needTypeSuffixInShaderConstants?i.setValue("NUM_SAMPLES",this.realTimeFilteringQuality+"u",!0):i.setValue("NUM_SAMPLES",""+this.realTimeFilteringQuality,!0),i.setValue("BRDF_V_HEIGHT_CORRELATED",!0),i.setValue("MS_BRDF_ENERGY_CONSERVATION",this.useEnergyConservation,!0),i.setValue("RADIANCEOCCLUSION",this.useRadianceOcclusion,!0),i.setValue("HORIZONOCCLUSION",this.useHorizonOcclusion,!0),i.setValue("UNLIT",this.unlit,!0),i.setValue("FORCENORMALFORWARD",this.forceNormalForward,!0),this._environmentBRDFTexture&&xu.ReflectionTextureEnabled?(i.setValue("ENVIRONMENTBRDF",!0),i.setValue("ENVIRONMENTBRDF_RGBD",this._environmentBRDFTexture.isRGBD,!0)):(i.setValue("ENVIRONMENTBRDF",!1),i.setValue("ENVIRONMENTBRDF_RGBD",!1)),i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i),i._areLightsDirty)if(this.light){var o={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};fa(n,e,this.light,this._lightId,i,!0,o),o.needRebuild&&i.rebuild()}else pa(n,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,ba(n,i)},t.prototype.updateUniformsAndSamples=function(e,t,i,r){for(var n=0;n<t.maxSimultaneousLights&&i["LIGHT"+n];n++){var o=e.uniforms.indexOf("vLightData"+n)>=0;xa(n,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+n],r,o)}},t.prototype.isReady=function(e,t,i){return!(this._environmentBRDFTexture&&!this._environmentBRDFTexture.isReady()||i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())},t.prototype.bind=function(e,t,i){var r,n;if(i){var o=i.getScene();this.light?aa(this.light,this._lightId,o,e,!0):sa(o,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);var a=this._scene.ambientColor;a&&e.setColor3("ambientFromScene",a);var s=o.useRightHandedSystem===(null!=o._mirroredCameraPosition);e.setFloat(this._invertNormalName,s?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);var l=null!==(n=null===(r=this.indexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==n?n:1.5,c=Math.pow((l-1)/(l+1),2);this._metallicReflectanceColor.scaleToRef(c*this._metallicF0Factor,$.Color3[0]);var u=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,$.Color3[0],u),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}},t.prototype._injectVertexCode=function(e){var t,i,r=this.worldPosition,n="//".concat(this.name);this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",n,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",n,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));var o="v_"+r.associatedVariableName;e._emitVaryingFromString(o,Ns.Vector4)&&(e.compilationString+="".concat(o," = ").concat(r.associatedVariableName,";\n"));var a=this.reflection.isConnected?null===(t=this.reflection.connectedPoint)||void 0===t?void 0:t.ownerBlock:null;a&&(a.viewConnectionPoint=this.view),e.compilationString+=null!==(i=null==a?void 0:a.handleVertexSide(e))&&void 0!==i?i:"",e._emitVaryingFromString("vClipSpacePosition",Ns.Vector4,"defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+="#if DEBUGMODE > 0\n",e._injectAtEnd+="vClipSpacePosition = gl_Position;\n",e._injectAtEnd+="#endif\n"),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",n,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:r.associatedVariableName}]}):(e.compilationString+="vec4 worldPos = ".concat(r.associatedVariableName,";\n"),this.view.isConnected&&(e.compilationString+="mat4 view = ".concat(this.view.associatedVariableName,";\n")),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",n,{repeatKey:"maxSimultaneousLights"}))},t.prototype._getAlbedoOpacityCode=function(){var e="albedoOpacityOutParams albedoOpacityOut;\n",t=this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)",i=this.opacity.isConnected?this.opacity.associatedVariableName:"1.";return e+"albedoOpacityBlock(\n vec4(".concat(t,", 1.),\n #ifdef ALBEDO\n vec4(1.),\n vec2(1., 1.),\n #endif\n #ifdef OPACITY\n vec4(").concat(i,"),\n vec2(1., 1.),\n #endif\n albedoOpacityOut\n );\n\n vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo;\n float alpha = albedoOpacityOut.alpha;\n")},t.prototype._getAmbientOcclusionCode=function(){var e="ambientOcclusionOutParams aoOut;\n",t=this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1.";return e+"ambientOcclusionBlock(\n #ifdef AMBIENT\n vec3(".concat(t,"),\n vec4(0., 1.0, 1.0, 0.),\n #endif\n aoOut\n );\n")},t.prototype._getReflectivityCode=function(e){var t="reflectivityOutParams reflectivityOut;\n";return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,Ns.Vector4),t+"vec3 baseColor = surfaceAlbedo;\n\n reflectivityBlock(\n vec4(".concat(this.metallic.associatedVariableName,", ").concat(this.roughness.associatedVariableName,", 0., 0.),\n #ifdef METALLICWORKFLOW\n surfaceAlbedo,\n ").concat(this._vMetallicReflectanceFactorsName,",\n #endif\n #ifdef REFLECTIVITY\n vec3(0., 0., ").concat("1.","),\n vec4(1.),\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor,\n #endif\n #ifdef MICROSURFACEMAP\n microSurfaceTexel, <== not handled!\n #endif\n reflectivityOut\n );\n\n float microSurface = reflectivityOut.microSurface;\n float roughness = reflectivityOut.roughness;\n\n #ifdef METALLICWORKFLOW\n surfaceAlbedo = reflectivityOut.surfaceAlbedo;\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor;\n #endif\n")},t.prototype._buildBlock=function(t){var i,r,n,o,a,s,l,c,u,h,d,p,f,_,m,g,v,y,b,T,E,S,x,A,C,R,P,I,M,O,D,N,F,L,w,B,U,V,k,G,z;e.prototype._buildBlock.call(this,t),this._scene=t.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=km(this._scene));var W=this.reflection.isConnected?null===(i=this.reflection.connectedPoint)||void 0===i?void 0:i.ownerBlock:null;if(W&&(W.worldPositionConnectionPoint=this.worldPosition,W.cameraPositionConnectionPoint=this.cameraPosition,W.worldNormalConnectionPoint=this.worldNormal,W.viewConnectionPoint=this.view),t.target!==Fs.Fragment)return this._injectVertexCode(t),this;t.sharedData.forcedBindableBlocks.push(this),t.sharedData.blocksWithDefines.push(this),t.sharedData.blockingBlocks.push(this),this.generateOnlyFragmentCode&&t.sharedData.dynamicUniformBlocks.push(this);var H="//".concat(this.name),X=this.perturbedNormal,j=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(j=t._getFreeVariableName("globalWorldPos"),t._emitFunction("pbr_globalworldpos","vec3 ".concat(j,";\n"),H),t.compilationString+="".concat(j," = ").concat(this.worldPosition.associatedVariableName,".xyz;\n"),t.compilationString+=t._emitCodeFromInclude("shadowsVertex",H,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"worldPos,".concat(this.worldPosition.associatedVariableName):void 0}),t.compilationString+="#if DEBUGMODE > 0\n",t.compilationString+="vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0);\n",t.compilationString+="#endif\n"):j="v_"+j,this._environmentBrdfSamplerName=t._getFreeVariableName("environmentBrdfSampler"),t._emit2DSampler(this._environmentBrdfSamplerName),t.sharedData.hints.needAlphaBlending=t.sharedData.hints.needAlphaBlending||this.useAlphaBlending,t.sharedData.hints.needAlphaTesting=t.sharedData.hints.needAlphaTesting||this.useAlphaTest,t._emitExtension("lod","#extension GL_EXT_shader_texture_lod : enable","defined(LODBASEDMICROSFURACE)"),t._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),t._emitUniformFromString("vDebugMode",Ns.Vector2,"defined(IGNORE) || DEBUGMODE > 0"),t._emitUniformFromString("ambientFromScene",Ns.Vector3),t.uniforms.push("exposureLinear"),t.uniforms.push("contrast"),t.uniforms.push("vInverseScreenSize"),t.uniforms.push("vignetteSettings1"),t.uniforms.push("vignetteSettings2"),t.uniforms.push("vCameraColorCurveNegative"),t.uniforms.push("vCameraColorCurveNeutral"),t.uniforms.push("vCameraColorCurvePositive"),t.uniforms.push("txColorTransform"),t.uniforms.push("colorTransformSettings"),t.uniforms.push("ditherIntensity"),this.light?t._emitFunctionFromInclude(t.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",H,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):t._emitFunctionFromInclude(t.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",H,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),t._emitFunctionFromInclude("helperFunctions",H),t._emitFunctionFromInclude("importanceSampling",H),t._emitFunctionFromInclude("pbrHelperFunctions",H),t._emitFunctionFromInclude("imageProcessingDeclaration",H),t._emitFunctionFromInclude("imageProcessingFunctions",H),t._emitFunctionFromInclude("shadowsFragmentFunctions",H),t._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",H,{replaceStrings:[{search:/vPositionW/g,replace:j+".xyz"}]}),t._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",H),t._emitFunctionFromInclude("pbrBRDFFunctions",H,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(r=null==W?void 0:W._defineSkyboxName)&&void 0!==r?r:"REFLECTIONMAP_SKYBOX"}]}),t._emitFunctionFromInclude("hdrFilteringFunctions",H),t._emitFunctionFromInclude("pbrDirectLightingFunctions",H,{replaceStrings:[{search:/vPositionW/g,replace:j+".xyz"}]}),t._emitFunctionFromInclude("pbrIBLFunctions",H),t._emitFunctionFromInclude("pbrBlockAlbedoOpacity",H),t._emitFunctionFromInclude("pbrBlockReflectivity",H),t._emitFunctionFromInclude("pbrBlockAmbientOcclusion",H),t._emitFunctionFromInclude("pbrBlockAlphaFresnel",H),t._emitFunctionFromInclude("pbrBlockAnisotropic",H),t._emitUniformFromString("vLightingIntensity",Ns.Vector4),(null==W?void 0:W.generateOnlyFragmentCode)&&(t.compilationString+=W.handleVertexSide(t)),this._vNormalWName=t._getFreeVariableName("vNormalW"),t.compilationString+="vec4 ".concat(this._vNormalWName," = normalize(").concat(this.worldNormal.associatedVariableName,");\n"),t._registerTempVariable("viewDirectionW")&&(t.compilationString+="vec3 viewDirectionW = normalize(".concat(this.cameraPosition.associatedVariableName," - ").concat(j,".xyz);\n")),t.compilationString+="vec3 geometricNormalW = ".concat(this._vNormalWName,".xyz;\n"),t.compilationString+="vec3 normalW = ".concat(X.isConnected?"normalize("+X.associatedVariableName+".xyz)":"geometricNormalW",";\n"),this._invertNormalName=t._getFreeVariableName("invertNormal"),t._emitUniformFromString(this._invertNormalName,Ns.Float),t.compilationString+=t._emitCodeFromInclude("pbrBlockNormalFinal",H,{replaceStrings:[{search:/vPositionW/g,replace:j+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),t.compilationString+=this._getAlbedoOpacityCode(),t.compilationString+=t._emitCodeFromInclude("depthPrePass",H),t.compilationString+=this._getAmbientOcclusionCode(),t.compilationString+=t._emitCodeFromInclude("pbrBlockLightmapInit",H),t.compilationString+="#ifdef UNLIT\n vec3 diffuseBase = vec3(1., 1., 1.);\n #else\n",t.compilationString+=this._getReflectivityCode(t),t.compilationString+=t._emitCodeFromInclude("pbrBlockGeometryInfo",H,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(n=null==W?void 0:W._defineSkyboxName)&&void 0!==n?n:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:null!==(o=null==W?void 0:W._define3DName)&&void 0!==o?o:"REFLECTIONMAP_3D"}]});var Y=this.anisotropy.isConnected?null===(a=this.anisotropy.connectedPoint)||void 0===a?void 0:a.ownerBlock:null;Y&&(Y.worldPositionConnectionPoint=this.worldPosition,Y.worldNormalConnectionPoint=this.worldNormal,t.compilationString+=Y.getCode(t,!this.perturbedNormal.isConnected)),W&&W.hasTexture&&(t.compilationString+=W.getCode(t,Y?"anisotropicOut.anisotropicNormal":"normalW")),t._emitFunctionFromInclude("pbrBlockReflection",H,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:null!==(s=null==W?void 0:W._define3DName)&&void 0!==s?s:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(l=null==W?void 0:W._defineOppositeZ)&&void 0!==l?l:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(c=null==W?void 0:W._defineProjectionName)&&void 0!==c?c:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(u=null==W?void 0:W._defineSkyboxName)&&void 0!==u?u:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(h=null==W?void 0:W._defineLODReflectionAlpha)&&void 0!==h?h:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(d=null==W?void 0:W._defineLinearSpecularReflection)&&void 0!==d?d:"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:null!==(p=null==W?void 0:W._vReflectionFilteringInfoName)&&void 0!==p?p:"vReflectionFilteringInfo"}]}),t.compilationString+=t._emitCodeFromInclude("pbrBlockReflectance0",H,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});var K=this.sheen.isConnected?null===(f=this.sheen.connectedPoint)||void 0===f?void 0:f.ownerBlock:null;K&&(t.compilationString+=K.getCode(W)),t._emitFunctionFromInclude("pbrBlockSheen",H,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:null!==(_=null==W?void 0:W._define3DName)&&void 0!==_?_:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(m=null==W?void 0:W._defineSkyboxName)&&void 0!==m?m:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(g=null==W?void 0:W._defineLODReflectionAlpha)&&void 0!==g?g:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(v=null==W?void 0:W._defineLinearSpecularReflection)&&void 0!==v?v:"LINEARSPECULARREFLECTION"}]});var Q=this.iridescence.isConnected?null===(y=this.iridescence.connectedPoint)||void 0===y?void 0:y.ownerBlock:null;t.compilationString+=_T.GetCode(Q),t._emitFunctionFromInclude("pbrBlockIridescence",H,{replaceStrings:[]});var q=this.clearcoat.isConnected?null===(b=this.clearcoat.connectedPoint)||void 0===b?void 0:b.ownerBlock:null,Z=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,J=this.perturbedNormal.isConnected&&(null===(E=(null===(T=this.perturbedNormal.connectedPoint)||void 0===T?void 0:T.ownerBlock).worldTangent)||void 0===E?void 0:E.isConnected),$=this.anisotropy.isConnected&&(null===(S=this.anisotropy.connectedPoint)||void 0===S?void 0:S.ownerBlock).worldTangent.isConnected,ee=J||!this.perturbedNormal.isConnected&&$;t.compilationString+=fT.GetCode(t,q,W,j,Z,ee,this.worldNormal.associatedVariableName),Z&&(ee=null!==(x=null==q?void 0:q.worldTangent.isConnected)&&void 0!==x&&x),t._emitFunctionFromInclude("pbrBlockClearcoat",H,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:null!==(A=null==W?void 0:W._define3DName)&&void 0!==A?A:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(C=null==W?void 0:W._defineOppositeZ)&&void 0!==C?C:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(R=null==W?void 0:W._defineProjectionName)&&void 0!==R?R:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(P=null==W?void 0:W._defineSkyboxName)&&void 0!==P?P:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(I=null==W?void 0:W._defineLODReflectionAlpha)&&void 0!==I?I:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(M=null==W?void 0:W._defineLinearSpecularReflection)&&void 0!==M?M:"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:ee?"defined(TANGENT)":"defined(IGNORE)"}]}),t.compilationString+=t._emitCodeFromInclude("pbrBlockReflectance",H,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(O=null==W?void 0:W._defineSkyboxName)&&void 0!==O?O:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:null!==(D=null==W?void 0:W._define3DName)&&void 0!==D?D:"REFLECTIONMAP_3D"}]});var te=this.subsurface.isConnected?null===(N=this.subsurface.connectedPoint)||void 0===N?void 0:N.ownerBlock:null,ie=this.subsurface.isConnected?null===(L=(null===(F=this.subsurface.connectedPoint)||void 0===F?void 0:F.ownerBlock).refraction.connectedPoint)||void 0===L?void 0:L.ownerBlock:null;ie&&(ie.viewConnectionPoint=this.view,ie.indexOfRefractionConnectionPoint=this.indexOfRefraction),t.compilationString+=gT.GetCode(t,te,W,j),t._emitFunctionFromInclude("pbrBlockSubSurface",H,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:null!==(w=null==W?void 0:W._define3DName)&&void 0!==w?w:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(B=null==W?void 0:W._defineOppositeZ)&&void 0!==B?B:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(U=null==W?void 0:W._defineProjectionName)&&void 0!==U?U:"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:null!==(V=null==ie?void 0:ie._define3DName)&&void 0!==V?V:"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:null!==(k=null==ie?void 0:ie._defineLODRefractionAlpha)&&void 0!==k?k:"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:null!==(G=null==ie?void 0:ie._defineLinearSpecularRefraction)&&void 0!==G?G:"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:null!==(z=null==ie?void 0:ie._defineOppositeZ)&&void 0!==z?z:"SS_REFRACTIONMAP_OPPOSITEZ"}]}),t.compilationString+=t._emitCodeFromInclude("pbrBlockDirectLighting",H),this.light?t.compilationString+=t._emitCodeFromInclude("lightFragment",H,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:j+".xyz"}]}):t.compilationString+=t._emitCodeFromInclude("lightFragment",H,{repeatKey:"maxSimultaneousLights",substitutionVars:"vPositionW,".concat(j,".xyz")}),t.compilationString+=t._emitCodeFromInclude("pbrBlockFinalLitComponents",H),t.compilationString+="#endif\n";var re=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)",ne=ig.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();-1===ne.indexOf(".")&&(ne+="."),t.compilationString+=t._emitCodeFromInclude("pbrBlockFinalUnlitComponents",H,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:re+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:ne}]}),t.compilationString+=t._emitCodeFromInclude("pbrBlockFinalColorComposition",H,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),t.compilationString+=t._emitCodeFromInclude("pbrBlockImageProcessing",H,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),t.compilationString+=t._emitCodeFromInclude("pbrDebug",H,{replaceStrings:[{search:/vNormalW/g,replace:this._vNormalWName},{search:/vPositionW/g,replace:j},{search:/albedoTexture\.rgb;/g,replace:"vec3(1.);\ngl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\n"}]});for(var oe=0,se=this._outputs;oe<se.length;oe++){var le=se[oe];if(le.hasEndpoints){var ce=vT[le.name];if(ce){var ue=ce[0],he=ce[1];he&&(t.compilationString+="#if ".concat(he,"\n")),t.compilationString+="".concat(t._declareOutput(le)," = ").concat(ue,";\n"),he&&(t.compilationString+="#else\n",t.compilationString+="".concat(t._declareOutput(le)," = vec3(0.);\n"),t.compilationString+="#endif\n")}else ae.Error("There's no remapping for the ".concat(le.name," end point! No code generated"))}}return this},t.prototype._dumpPropertiesCode=function(){var t=e.prototype._dumpPropertiesCode.call(this);return t+="".concat(this._codeVariableName,".lightFalloff = ").concat(this.lightFalloff,";\n"),t+="".concat(this._codeVariableName,".useAlphaTest = ").concat(this.useAlphaTest,";\n"),t+="".concat(this._codeVariableName,".alphaTestCutoff = ").concat(this.alphaTestCutoff,";\n"),t+="".concat(this._codeVariableName,".useAlphaBlending = ").concat(this.useAlphaBlending,";\n"),t+="".concat(this._codeVariableName,".useRadianceOverAlpha = ").concat(this.useRadianceOverAlpha,";\n"),t+="".concat(this._codeVariableName,".useSpecularOverAlpha = ").concat(this.useSpecularOverAlpha,";\n"),t+="".concat(this._codeVariableName,".enableSpecularAntiAliasing = ").concat(this.enableSpecularAntiAliasing,";\n"),t+="".concat(this._codeVariableName,".realTimeFiltering = ").concat(this.realTimeFiltering,";\n"),t+="".concat(this._codeVariableName,".realTimeFilteringQuality = ").concat(this.realTimeFilteringQuality,";\n"),t+="".concat(this._codeVariableName,".useEnergyConservation = ").concat(this.useEnergyConservation,";\n"),t+="".concat(this._codeVariableName,".useRadianceOcclusion = ").concat(this.useRadianceOcclusion,";\n"),t+="".concat(this._codeVariableName,".useHorizonOcclusion = ").concat(this.useHorizonOcclusion,";\n"),t+="".concat(this._codeVariableName,".unlit = ").concat(this.unlit,";\n"),t+="".concat(this._codeVariableName,".forceNormalForward = ").concat(this.forceNormalForward,";\n"),t+="".concat(this._codeVariableName,".debugMode = ").concat(this.debugMode,";\n"),(t+="".concat(this._codeVariableName,".debugLimit = ").concat(this.debugLimit,";\n"))+"".concat(this._codeVariableName,".debugFactor = ").concat(this.debugFactor,";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return this.light&&(t.lightId=this.light.id),t.lightFalloff=this.lightFalloff,t.useAlphaTest=this.useAlphaTest,t.alphaTestCutoff=this.alphaTestCutoff,t.useAlphaBlending=this.useAlphaBlending,t.useRadianceOverAlpha=this.useRadianceOverAlpha,t.useSpecularOverAlpha=this.useSpecularOverAlpha,t.enableSpecularAntiAliasing=this.enableSpecularAntiAliasing,t.realTimeFiltering=this.realTimeFiltering,t.realTimeFilteringQuality=this.realTimeFilteringQuality,t.useEnergyConservation=this.useEnergyConservation,t.useRadianceOcclusion=this.useRadianceOcclusion,t.useHorizonOcclusion=this.useHorizonOcclusion,t.unlit=this.unlit,t.forceNormalForward=this.forceNormalForward,t.debugMode=this.debugMode,t.debugLimit=this.debugLimit,t.debugFactor=this.debugFactor,t.generateOnlyFragmentCode=this.generateOnlyFragmentCode,t},t.prototype._deserialize=function(t,i,r){var n,o;e.prototype._deserialize.call(this,t,i,r),t.lightId&&(this.light=i.getLightById(t.lightId)),this.lightFalloff=null!==(n=t.lightFalloff)&&void 0!==n?n:0,this.useAlphaTest=t.useAlphaTest,this.alphaTestCutoff=t.alphaTestCutoff,this.useAlphaBlending=t.useAlphaBlending,this.useRadianceOverAlpha=t.useRadianceOverAlpha,this.useSpecularOverAlpha=t.useSpecularOverAlpha,this.enableSpecularAntiAliasing=t.enableSpecularAntiAliasing,this.realTimeFiltering=!!t.realTimeFiltering,this.realTimeFilteringQuality=null!==(o=t.realTimeFilteringQuality)&&void 0!==o?o:u.TEXTURE_FILTERING_QUALITY_LOW,this.useEnergyConservation=t.useEnergyConservation,this.useRadianceOcclusion=t.useRadianceOcclusion,this.useHorizonOcclusion=t.useHorizonOcclusion,this.unlit=t.unlit,this.forceNormalForward=!!t.forceNormalForward,this.debugMode=t.debugMode,this.debugLimit=t.debugLimit,this.debugFactor=t.debugFactor,this.generateOnlyFragmentCode=!!t.generateOnlyFragmentCode,this._setTarget()},v([Ys("Direct lights",Xs.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],t.prototype,"directIntensity",void 0),v([Ys("Environment lights",Xs.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],t.prototype,"environmentIntensity",void 0),v([Ys("Specular highlights",Xs.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],t.prototype,"specularIntensity",void 0),v([Ys("Light falloff",Xs.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:ig.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:ig.LIGHTFALLOFF_GLTF},{label:"Standard",value:ig.LIGHTFALLOFF_STANDARD}]})],t.prototype,"lightFalloff",void 0),v([Ys("Alpha Testing",Xs.Boolean,"OPACITY")],t.prototype,"useAlphaTest",void 0),v([Ys("Alpha CutOff",Xs.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],t.prototype,"alphaTestCutoff",void 0),v([Ys("Alpha blending",Xs.Boolean,"OPACITY")],t.prototype,"useAlphaBlending",void 0),v([Ys("Radiance over alpha",Xs.Boolean,"RENDERING",{notifiers:{update:!0}})],t.prototype,"useRadianceOverAlpha",void 0),v([Ys("Specular over alpha",Xs.Boolean,"RENDERING",{notifiers:{update:!0}})],t.prototype,"useSpecularOverAlpha",void 0),v([Ys("Specular anti-aliasing",Xs.Boolean,"RENDERING",{notifiers:{update:!0}})],t.prototype,"enableSpecularAntiAliasing",void 0),v([Ys("Realtime filtering",Xs.Boolean,"RENDERING",{notifiers:{update:!0}})],t.prototype,"realTimeFiltering",void 0),v([Ys("Realtime filtering quality",Xs.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:u.TEXTURE_FILTERING_QUALITY_LOW},{label:"Medium",value:u.TEXTURE_FILTERING_QUALITY_MEDIUM},{label:"High",value:u.TEXTURE_FILTERING_QUALITY_HIGH}]})],t.prototype,"realTimeFilteringQuality",void 0),v([Ys("Energy Conservation",Xs.Boolean,"ADVANCED",{notifiers:{update:!0}})],t.prototype,"useEnergyConservation",void 0),v([Ys("Radiance occlusion",Xs.Boolean,"ADVANCED",{notifiers:{update:!0}})],t.prototype,"useRadianceOcclusion",void 0),v([Ys("Horizon occlusion",Xs.Boolean,"ADVANCED",{notifiers:{update:!0}})],t.prototype,"useHorizonOcclusion",void 0),v([Ys("Unlit",Xs.Boolean,"ADVANCED",{notifiers:{update:!0}})],t.prototype,"unlit",void 0),v([Ys("Force normal forward",Xs.Boolean,"ADVANCED",{notifiers:{update:!0}})],t.prototype,"forceNormalForward",void 0),v([Ys("Generate only fragment code",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:t._OnGenerateOnlyFragmentCodeChanged}})],t.prototype,"generateOnlyFragmentCode",void 0),v([Ys("Debug mode",Xs.List,"DEBUG",{notifiers:{update:!0},options:[{label:"None",value:0},{label:"Normalized position",value:1},{label:"Normals",value:2},{label:"Tangents",value:3},{label:"Bitangents",value:4},{label:"Bump Normals",value:5},{label:"ClearCoat Normals",value:8},{label:"ClearCoat Tangents",value:9},{label:"ClearCoat Bitangents",value:10},{label:"Anisotropic Normals",value:11},{label:"Anisotropic Tangents",value:12},{label:"Anisotropic Bitangents",value:13},{label:"Env Refraction",value:40},{label:"Env Reflection",value:41},{label:"Env Clear Coat",value:42},{label:"Direct Diffuse",value:50},{label:"Direct Specular",value:51},{label:"Direct Clear Coat",value:52},{label:"Direct Sheen",value:53},{label:"Env Irradiance",value:54},{label:"Surface Albedo",value:60},{label:"Reflectance 0",value:61},{label:"Metallic",value:62},{label:"Metallic F0",value:71},{label:"Roughness",value:63},{label:"AlphaG",value:64},{label:"NdotV",value:65},{label:"ClearCoat Color",value:66},{label:"ClearCoat Roughness",value:67},{label:"ClearCoat NdotV",value:68},{label:"Transmittance",value:69},{label:"Refraction Transmittance",value:70},{label:"SEO",value:80},{label:"EHO",value:81},{label:"Energy Factor",value:82},{label:"Specular Reflectance",value:83},{label:"Clear Coat Reflectance",value:84},{label:"Sheen Reflectance",value:85},{label:"Luminance Over Alpha",value:86},{label:"Alpha",value:87},{label:"Albedo color",value:88},{label:"Ambient occlusion color",value:89}]})],t.prototype,"debugMode",void 0),v([Ys("Split position",Xs.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],t.prototype,"debugLimit",void 0),v([Ys("Output factor",Xs.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],t.prototype,"debugFactor",void 0),t}(Ws);a("BABYLON.PBRMetallicRoughnessBlock",yT);var bT=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("left",Ns.AutoDetect),i.registerInput("right",Ns.AutoDetect),i.registerOutput("output",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i._inputs[1].acceptedConnectionPointTypes.push(Ns.Float),i}return m(t,e),t.prototype.getClassName=function(){return"ModBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.shaderLanguage===pt.GLSL?t.compilationString+=t._declareOutput(i)+" = mod(".concat(this.left.associatedVariableName,", ").concat(this.right.associatedVariableName,");\n"):t.compilationString+=t._declareOutput(i)+" = (".concat(this.left.associatedVariableName," % ").concat(this.right.associatedVariableName,");\n"),this},t}(Ws);a("BABYLON.ModBlock",bT);var TT,ET=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("row0",Ns.Vector4),i.registerInput("row1",Ns.Vector4),i.registerInput("row2",Ns.Vector4),i.registerInput("row3",Ns.Vector4),i.registerOutput("output",Ns.Matrix),i}return m(t,e),t.prototype.getClassName=function(){return"MatrixBuilder"},Object.defineProperty(t.prototype,"row0",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"row1",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"row2",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"row3",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(){if(!this.row0.isConnected){var e=new rl("row0");e.value=new k(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){var t=new rl("row1");t.value=new k(0,1,0,0),t.output.connectTo(this.row1)}if(!this.row2.isConnected){var i=new rl("row2");i.value=new k(0,0,1,0),i.output.connectTo(this.row2)}if(!this.row3.isConnected){var r=new rl("row3");r.value=new k(0,0,0,1),r.output.connectTo(this.row3)}},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],r=this.row0,n=this.row1,o=this.row2,a=this.row3;return t.compilationString+=t._declareOutput(i)+" = mat4(".concat(r.associatedVariableName,", ").concat(n.associatedVariableName,", ").concat(o.associatedVariableName,", ").concat(a.associatedVariableName,");\n"),this},t}(Ws);a("BABYLON.MatrixBuilder",ET),function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(TT||(TT={}));var ST=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.condition=TT.LessThan,i.registerInput("a",Ns.Float),i.registerInput("b",Ns.Float),i.registerInput("true",Ns.AutoDetect,!0),i.registerInput("false",Ns.AutoDetect,!0),i.registerOutput("output",Ns.BasedOnInput),i._linkConnectionTypes(2,3),i._outputs[0]._typeConnectionSource=i._inputs[2],i._outputs[0]._defaultConnectionPointType=Ns.Float,i}return m(t,e),t.prototype.getClassName=function(){return"ConditionalBlock"},Object.defineProperty(t.prototype,"a",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"b",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"true",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"false",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],r=this.true.isConnected?this.true.associatedVariableName:"1.0",n=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case TT.Equal:t.compilationString+=t._declareOutput(i)+" = ".concat(t._generateTertiary(r,n,"".concat(this.a.associatedVariableName," == ").concat(this.b.associatedVariableName)),";\n");break;case TT.NotEqual:t.compilationString+=t._declareOutput(i)+" = ".concat(t._generateTertiary(r,n,"".concat(this.a.associatedVariableName," != ").concat(this.b.associatedVariableName)),";\n");break;case TT.LessThan:t.compilationString+=t._declareOutput(i)+" = ".concat(t._generateTertiary(r,n,"".concat(this.a.associatedVariableName," < ").concat(this.b.associatedVariableName)),";\n");break;case TT.LessOrEqual:t.compilationString+=t._declareOutput(i)+" = ".concat(t._generateTertiary(r,n,"".concat(this.a.associatedVariableName," <= ").concat(this.b.associatedVariableName)),";\n");break;case TT.GreaterThan:t.compilationString+=t._declareOutput(i)+" = ".concat(t._generateTertiary(r,n,"".concat(this.a.associatedVariableName," > ").concat(this.b.associatedVariableName)),";\n");break;case TT.GreaterOrEqual:t.compilationString+=t._declareOutput(i)+" = ".concat(t._generateTertiary(r,n,"".concat(this.a.associatedVariableName," >= ").concat(this.b.associatedVariableName)),";\n");break;case TT.Xor:t.compilationString+=t._declareOutput(i)+" = ".concat(t._generateTertiary(r,n,"(((".concat(this.a.associatedVariableName," + ").concat(this.b.associatedVariableName,") % 2.0) > 0.0)")),";\n");break;case TT.Or:t.compilationString+=t._declareOutput(i)+" = ".concat(t._generateTertiary(r,n,"(min(".concat(this.a.associatedVariableName," + ").concat(this.b.associatedVariableName,", 1.0) > 0.0)")),";\n");break;case TT.And:t.compilationString+=t._declareOutput(i)+" = ".concat(t._generateTertiary(r,n,"(".concat(this.a.associatedVariableName," * ").concat(this.b.associatedVariableName," > 0.0)")),";\n")}return this},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.condition=this.condition,t},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),this.condition=t.condition},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".condition = BABYLON.ConditionalBlockConditions.").concat(TT[this.condition],";\n")},t}(Ws);a("BABYLON.ConditionalBlock",ST);var xT=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.octaves=6,i.registerInput("seed",Ns.AutoDetect),i.registerInput("chaos",Ns.AutoDetect,!0),i.registerInput("offsetX",Ns.Float,!0),i.registerInput("offsetY",Ns.Float,!0),i.registerInput("offsetZ",Ns.Float,!0),i.registerOutput("output",Ns.Float),i._inputs[0].acceptedConnectionPointTypes.push(Ns.Vector2),i._inputs[0].acceptedConnectionPointTypes.push(Ns.Vector3),i._linkConnectionTypes(0,1),i}return m(t,e),t.prototype.getClassName=function(){return"CloudBlock"},Object.defineProperty(t.prototype,"seed",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"chaos",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"offsetX",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"offsetY",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"offsetZ",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){var i,r;if(e.prototype._buildBlock.call(this,t),this.seed.isConnected&&this._outputs[0].hasEndpoints){var n="fbm".concat(this.octaves);t._emitFunction("CloudBlockCode","\n\n float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); }\n\n // Based on Morgan McGuire @morgan3d\n // https://www.shadertoy.com/view/4dS3Wd\n float cloudNoise(in vec2 x, in vec2 chaos) {\n vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.);\n\n vec2 i = floor(x);\n vec2 f = fract(x);\n\n float n = dot(i, step);\n\n vec2 u = f * f * (3.0 - 2.0 * f);\n return mix(\n mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x),\n mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x),\n u.y\n );\n }\n\n float cloudNoise(in vec3 x, in vec3 chaos) {\n vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.);\n\n vec3 i = floor(x);\n vec3 f = fract(x);\n\n float n = dot(i, step);\n\n vec3 u = f * f * (3.0 - 2.0 * f);\n return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y),\n mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z);\n }","// CloudBlockCode"),t._emitFunction("CloudBlockCodeFBM"+this.octaves,"\n float fbm(in vec2 st, in vec2 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = .5;\n float frequency = 0.;\n\n // Loop of octaves\n for (int i = 0; i < OCTAVES; i++) {\n value += amplitude * cloudNoise(st, chaos);\n st *= 2.0;\n amplitude *= 0.5;\n }\n return value;\n }\n\n float fbm(in vec3 x, in vec3 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = 0.5;\n for (int i = 0; i < OCTAVES; ++i) {\n value += amplitude * cloudNoise(x, chaos);\n x = x * 2.0;\n amplitude *= 0.5;\n }\n return value;\n }".replace(/fbm/gi,n).replace(/OCTAVES/gi,(0|this.octaves).toString()),"// CloudBlockCode FBM");var o=t._getFreeVariableName("st"),a=(null===(i=this.seed.connectedPoint)||void 0===i?void 0:i.type)===Ns.Vector2?"vec2":"vec3";t.compilationString+="".concat(a," ").concat(o," = ").concat(this.seed.associatedVariableName,";\n"),this.offsetX.isConnected&&(t.compilationString+="".concat(o,".x += 0.1 * ").concat(this.offsetX.associatedVariableName,";\n")),this.offsetY.isConnected&&(t.compilationString+="".concat(o,".y += 0.1 * ").concat(this.offsetY.associatedVariableName,";\n")),this.offsetZ.isConnected&&"vec3"===a&&(t.compilationString+="".concat(o,".z += 0.1 * ").concat(this.offsetZ.associatedVariableName,";\n"));var s;return s=this.chaos.isConnected?this.chaos.associatedVariableName:(null===(r=this.seed.connectedPoint)||void 0===r?void 0:r.type)===Ns.Vector2?"vec2(0., 0.)":"vec3(0., 0., 0.)",t.compilationString+=t._declareOutput(this._outputs[0])+" = ".concat(n,"(").concat(o,", ").concat(s,");\n"),this}},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".octaves = ").concat(this.octaves,";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.octaves=this.octaves,t},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),this.octaves=t.octaves},v([Ys("Octaves",Xs.Int)],t.prototype,"octaves",void 0),t}(Ws);a("BABYLON.CloudBlock",xT);var AT=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("seed",Ns.Vector2),i.registerInput("offset",Ns.Float),i.registerInput("density",Ns.Float),i.registerOutput("output",Ns.Float),i.registerOutput("cells",Ns.Float),i}return m(t,e),t.prototype.getClassName=function(){return"VoronoiNoiseBlock"},Object.defineProperty(t.prototype,"seed",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"offset",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"density",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"cells",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),this.seed.isConnected){var i="vec2 voronoiRandom(vec2 seed, float offset){\n mat2 m = mat2(15.27, 47.63, 99.41, 89.98);\n vec2 uv = fract(sin(m * seed) * 46839.32);\n return vec2(sin(uv.y * offset) * 0.5 + 0.5, cos(uv.x * offset) * 0.5 + 0.5);\n }\n ";t.shaderLanguage===pt.WGSL&&(i=t._babylonSLtoWGSL(i)),t._emitFunction("voronoiRandom",i,"// Voronoi random generator"),i="void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){\n vec2 g = floor(seed * density);\n vec2 f = fract(seed * density);\n float t = 8.0;\n vec3 res = vec3(8.0, 0.0, 0.0);\n\n for(int y=-1; y<=1; y++)\n {\n for(int x=-1; x<=1; x++)\n {\n vec2 lattice = vec2(float(x),float(y));\n vec2 randomOffset = voronoiRandom(lattice + g, offset);\n float d = distance(lattice + randomOffset, f);\n if(d < res.x)\n {\n res = vec3(d, randomOffset.x, randomOffset.y);\n [*]outValue = res.x;\n [*]cells = res.y;\n }\n }\n }\n }\n ",i=t.shaderLanguage===pt.WGSL?t._babylonSLtoWGSL(i):t._babylonSLtoGLSL(i),t._emitFunction("voronoi",i,"// Voronoi");var r=t._getFreeVariableName("tempOutput"),n=t._getFreeVariableName("tempCells"),o=t.shaderLanguage===pt.WGSL?"&":"";return t.compilationString+="".concat(t._declareLocalVar(r,Ns.Float)," = 0.0;\n"),t.compilationString+="".concat(t._declareLocalVar(n,Ns.Float)," = 0.0;\n"),t.compilationString+="voronoi(".concat(this.seed.associatedVariableName,", ").concat(this.offset.associatedVariableName,", ").concat(this.density.associatedVariableName,", ").concat(o).concat(r,", ").concat(o).concat(n,");\n"),this.output.hasEndpoints&&(t.compilationString+=t._declareOutput(this.output)+" = ".concat(r,";\n")),this.cells.hasEndpoints&&(t.compilationString+=t._declareOutput(this.cells)+" = ".concat(n,";\n")),this}},t}(Ws);a("BABYLON.VoronoiNoiseBlock",AT);var CT=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("input",Ns.AutoDetect),i.registerOutput("output",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i}return m(t,e),t.prototype.getClassName=function(){return"ElbowBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){var e=this._inputs[0];if(e.isConnected){var t=e.connectedPoint.ownerBlock;if(t.target!==Fs.VertexAndFragment)return t.target;if(e.connectedPoint.target!==Fs.VertexAndFragment)return e.connectedPoint.target}return this._target},set:function(e){this._target&e||(this._target=e)},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],r=this._inputs[0];return t.compilationString+=t._declareOutput(i)+" = ".concat(r.associatedVariableName,";\n"),this},t}(Ws);a("BABYLON.ElbowBlock",CT);var RT=function(e){function t(t,i){void 0===i&&(i=!1);var r=e.call(this,t,Fs.Neutral)||this;return r.projectAsCube=!1,r._convertToGammaSpace=!1,r._convertToLinearSpace=!1,r.disableLevelMultiplication=!1,r.registerInput("position",Ns.AutoDetect,!1),r.registerInput("normal",Ns.AutoDetect,!1),r.registerInput("sharpness",Ns.Float,!0),r.registerInput("source",Ns.Object,!0,Fs.VertexAndFragment,new Qy("source",r,Us.Input,mb,"ImageSourceBlock")),r.registerInput("sourceY",Ns.Object,!0,Fs.VertexAndFragment,new Qy("sourceY",r,Us.Input,mb,"ImageSourceBlock")),i||r.registerInput("sourceZ",Ns.Object,!0,Fs.VertexAndFragment,new Qy("sourceZ",r,Us.Input,mb,"ImageSourceBlock")),r.registerOutput("rgba",Ns.Color4,Fs.Neutral),r.registerOutput("rgb",Ns.Color3,Fs.Neutral),r.registerOutput("r",Ns.Float,Fs.Neutral),r.registerOutput("g",Ns.Float,Fs.Neutral),r.registerOutput("b",Ns.Float,Fs.Neutral),r.registerOutput("a",Ns.Float,Fs.Neutral),r.registerOutput("level",Ns.Float,Fs.Neutral),r._inputs[0].addExcludedConnectionPointFromAllowedTypes(Ns.Color3|Ns.Vector3|Ns.Vector4),r._inputs[1].addExcludedConnectionPointFromAllowedTypes(Ns.Color3|Ns.Vector3|Ns.Vector4),r}return m(t,e),Object.defineProperty(t.prototype,"texture",{get:function(){var e;return this.source.isConnected?(null===(e=this.source.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:this._texture},set:function(e){var t,i=this;if(this._texture!==e){var r=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:M.LastCreatedScene;!e&&r&&r.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(e){return e.hasTexture(i._texture)})),this._texture=e,e&&r&&r.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(t){return t.hasTexture(e)}))}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"textureY",{get:function(){var e;return this.sourceY.isConnected?(null===(e=this.sourceY.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"textureZ",{get:function(){var e,t;return(null===(e=this.sourceZ)||void 0===e?void 0:e.isConnected)?(null===(t=this.sourceY.connectedPoint)||void 0===t?void 0:t.ownerBlock).texture:null},enumerable:!1,configurable:!0}),t.prototype._getImageSourceBlock=function(e){return(null==e?void 0:e.isConnected)?e.connectedPoint.ownerBlock:null},Object.defineProperty(t.prototype,"samplerName",{get:function(){var e=this._getImageSourceBlock(this.source);return e?e.samplerName:this._samplerName},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"samplerYName",{get:function(){var e,t;return null!==(t=null===(e=this._getImageSourceBlock(this.sourceY))||void 0===e?void 0:e.samplerName)&&void 0!==t?t:null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"samplerZName",{get:function(){var e,t;return null!==(t=null===(e=this._getImageSourceBlock(this.sourceZ))||void 0===e?void 0:e.samplerName)&&void 0!==t?t:null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hasImageSource",{get:function(){return this.source.isConnected},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"convertToGammaSpace",{get:function(){return this._convertToGammaSpace},set:function(e){var t,i=this;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){var r=null!==(t=this.texture.getScene())&&void 0!==t?t:M.LastCreatedScene;null==r||r.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(e){return e.hasTexture(i.texture)}))}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"convertToLinearSpace",{get:function(){return this._convertToLinearSpace},set:function(e){var t,i=this;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){var r=null!==(t=this.texture.getScene())&&void 0!==t?t:M.LastCreatedScene;null==r||r.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag,(function(e){return e.hasTexture(i.texture)}))}},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"TriPlanarBlock"},Object.defineProperty(t.prototype,"position",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"normal",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"sharpness",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"source",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"sourceY",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"sourceZ",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rgba",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rgb",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"r",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"g",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"b",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"a",{get:function(){return this._outputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"level",{get:function(){return this._outputs[6]},enumerable:!1,configurable:!0}),t.prototype.prepareDefines=function(e,t,i){if(i._areTexturesDirty){var r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,n=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,n,!0)}},t.prototype.isReady=function(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())},t.prototype.bind=function(e){this.texture&&(e.setFloat(this._textureInfoName,this.texture.level),this._imageSource||e.setTexture(this._samplerName,this.texture))},t.prototype._generateTextureLookup=function(e){var t,i,r=this.samplerName,n=null!==(t=this.samplerYName)&&void 0!==t?t:r,o=null!==(i=this.samplerZName)&&void 0!==i?i:r,a=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",s=e._getFreeVariableName("x"),l=e._getFreeVariableName("y"),c=e._getFreeVariableName("z"),u=e._getFreeVariableName("w"),h=e._getFreeVariableName("n"),d=e._getFreeVariableName("uvx"),p=e._getFreeVariableName("uvy"),f=e._getFreeVariableName("uvz");e.compilationString+="\n vec3 ".concat(h," = ").concat(this.normal.associatedVariableName,".xyz;\n\n vec2 ").concat(d," = ").concat(this.position.associatedVariableName,".yz;\n vec2 ").concat(p," = ").concat(this.position.associatedVariableName,".zx;\n vec2 ").concat(f," = ").concat(this.position.associatedVariableName,".xy;\n "),this.projectAsCube&&(e.compilationString+="\n ".concat(d,".xy = ").concat(d,".yx;\n\n if (").concat(h,".x >= 0.0) {\n ").concat(d,".x = -").concat(d,".x;\n }\n if (").concat(h,".y < 0.0) {\n ").concat(p,".y = -").concat(p,".y;\n }\n if (").concat(h,".z < 0.0) {\n ").concat(f,".x = -").concat(f,".x;\n }\n ")),e.compilationString+="\n vec4 ".concat(s," = texture2D(").concat(r,", ").concat(d,");\n vec4 ").concat(l," = texture2D(").concat(n,", ").concat(p,");\n vec4 ").concat(c," = texture2D(").concat(o,", ").concat(f,");\n \n // blend weights\n vec3 ").concat(u," = pow(abs(").concat(h,"), vec3(").concat(a,"));\n\n // blend and return\n vec4 ").concat(this._tempTextureRead," = (").concat(s,"*").concat(u,".x + ").concat(l,"*").concat(u,".y + ").concat(c,"*").concat(u,".z) / (").concat(u,".x + ").concat(u,".y + ").concat(u,".z); \n ")},t.prototype._generateConversionCode=function(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+="#ifdef ".concat(this._linearDefineName,"\n ").concat(t.associatedVariableName," = toGammaSpace(").concat(t.associatedVariableName,");\n #endif\n ")),e.compilationString+="#ifdef ".concat(this._gammaDefineName,"\n ").concat(t.associatedVariableName," = toLinearSpace(").concat(t.associatedVariableName,");\n #endif\n "))},t.prototype._writeOutput=function(e,t,i){var r="";this.disableLevelMultiplication||(r=" * ".concat(this._textureInfoName)),e.compilationString+="".concat(e._declareOutput(t)," = ").concat(this._tempTextureRead,".").concat(i).concat(r,";\n"),this._generateConversionCode(e,t,i)},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,this._textureInfoName=t._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,this._tempTextureRead=t._getFreeVariableName("tempTextureRead"),this._linearDefineName=t._getFreeDefineName("ISLINEAR"),this._gammaDefineName=t._getFreeDefineName("ISGAMMA"),this._imageSource||(this._samplerName=t._getFreeVariableName(this.name+"Sampler"),t._emit2DSampler(this._samplerName)),t.sharedData.blockingBlocks.push(this),t.sharedData.textureBlocks.push(this),t.sharedData.blocksWithDefines.push(this),t.sharedData.bindableBlocks.push(this);var i="//".concat(this.name);t._emitFunctionFromInclude("helperFunctions",i),t._emitUniformFromString(this._textureInfoName,Ns.Float),this._generateTextureLookup(t);for(var r=0,n=this._outputs;r<n.length;r++){var o=n[r];o.hasEndpoints&&"level"!==o.name&&this._writeOutput(t,o,o.name)}return this},t.prototype._dumpPropertiesCode=function(){var t=e.prototype._dumpPropertiesCode.call(this);return t+="".concat(this._codeVariableName,".convertToGammaSpace = ").concat(this.convertToGammaSpace,";\n"),t+="".concat(this._codeVariableName,".convertToLinearSpace = ").concat(this.convertToLinearSpace,";\n"),t+="".concat(this._codeVariableName,".disableLevelMultiplication = ").concat(this.disableLevelMultiplication,";\n"),t+="".concat(this._codeVariableName,".projectAsCube = ").concat(this.projectAsCube,";\n"),this.texture?(t+="".concat(this._codeVariableName,'.texture = new BABYLON.Texture("').concat(this.texture.name,'", null, ').concat(this.texture.noMipmap,", ").concat(this.texture.invertY,", ").concat(this.texture.samplingMode,");\n"),t+="".concat(this._codeVariableName,".texture.wrapU = ").concat(this.texture.wrapU,";\n"),t+="".concat(this._codeVariableName,".texture.wrapV = ").concat(this.texture.wrapV,";\n"),t+="".concat(this._codeVariableName,".texture.uAng = ").concat(this.texture.uAng,";\n"),t+="".concat(this._codeVariableName,".texture.vAng = ").concat(this.texture.vAng,";\n"),t+="".concat(this._codeVariableName,".texture.wAng = ").concat(this.texture.wAng,";\n"),t+="".concat(this._codeVariableName,".texture.uOffset = ").concat(this.texture.uOffset,";\n"),t+="".concat(this._codeVariableName,".texture.vOffset = ").concat(this.texture.vOffset,";\n"),t+="".concat(this._codeVariableName,".texture.uScale = ").concat(this.texture.uScale,";\n"),t+="".concat(this._codeVariableName,".texture.vScale = ").concat(this.texture.vScale,";\n"),t+="".concat(this._codeVariableName,".texture.coordinatesMode = ").concat(this.texture.coordinatesMode,";\n")):t},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.convertToGammaSpace=this.convertToGammaSpace,t.convertToLinearSpace=this.convertToLinearSpace,t.disableLevelMultiplication=this.disableLevelMultiplication,t.projectAsCube=this.projectAsCube,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(t.texture=this.texture.serialize()),t},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),this.convertToGammaSpace=t.convertToGammaSpace,this.convertToLinearSpace=!!t.convertToLinearSpace,this.disableLevelMultiplication=!!t.disableLevelMultiplication,this.projectAsCube=!!t.projectAsCube,t.texture&&!Ll.IgnoreTexturesAtLoadTime&&void 0!==t.texture.url&&(r=0===t.texture.url.indexOf("data:")?"":r,this.texture=Ja.Parse(t.texture,i,r))},v([Ys("Project as cube",Xs.Boolean,"ADVANCED",{notifiers:{update:!0}})],t.prototype,"projectAsCube",void 0),t}(Ws);a("BABYLON.TriPlanarBlock",RT);var PT=function(e){function t(t){return e.call(this,t,!0)||this}return m(t,e),t.prototype.getClassName=function(){return"BiPlanarBlock"},t.prototype._generateTextureLookup=function(e){var t,i=this.samplerName,r=null!==(t=this.samplerYName)&&void 0!==t?t:this.samplerName,n=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",o=e._getFreeVariableName("dpdx"),a=e._getFreeVariableName("dpdy"),s=e._getFreeVariableName("n"),l=e._getFreeVariableName("ma"),c=e._getFreeVariableName("mi"),u=e._getFreeVariableName("me"),h=e._getFreeVariableName("x"),d=e._getFreeVariableName("y"),p=e._getFreeVariableName("y");e.compilationString+="\n // grab coord derivatives for texturing\n vec3 ".concat(o," = dFdx(").concat(this.position.associatedVariableName,".xyz);\n vec3 ").concat(a," = dFdy(").concat(this.position.associatedVariableName,".xyz);\n vec3 ").concat(s," = abs(").concat(this.normal.associatedVariableName,".xyz);\n \n // determine major axis (in x; yz are following axis)\n ivec3 ").concat(l," = (").concat(s,".x>").concat(s,".y && ").concat(s,".x>").concat(s,".z) ? ivec3(0,1,2) :\n (").concat(s,".y>").concat(s,".z) ? ivec3(1,2,0) :\n ivec3(2,0,1) ;\n // determine minor axis (in x; yz are following axis)\n ivec3 ").concat(c," = (").concat(s,".x<").concat(s,".y && ").concat(s,".x<").concat(s,".z) ? ivec3(0,1,2) :\n (").concat(s,".y<").concat(s,".z) ? ivec3(1,2,0) :\n ivec3(2,0,1) ;\n // determine median axis (in x; yz are following axis)\n ivec3 ").concat(u," = ivec3(3) - ").concat(c," - ").concat(l,";\n \n // project+fetch\n vec4 ").concat(h," = textureGrad( ").concat(i,", vec2( ").concat(this.position.associatedVariableName,"[").concat(l,".y], ").concat(this.position.associatedVariableName,"[").concat(l,".z]), \n vec2(").concat(o,"[").concat(l,".y],").concat(o,"[").concat(l,".z]), \n vec2(").concat(a,"[").concat(l,".y],").concat(a,"[").concat(l,".z]) );\n vec4 ").concat(d," = textureGrad( ").concat(r,", vec2( ").concat(this.position.associatedVariableName,"[").concat(u,".y], ").concat(this.position.associatedVariableName,"[").concat(u,".z]), \n vec2(").concat(o,"[").concat(u,".y],").concat(o,"[").concat(u,".z]),\n vec2(").concat(a,"[").concat(u,".y],").concat(a,"[").concat(u,".z]) );\n \n // blend factors\n vec2 ").concat(p," = vec2(").concat(s,"[").concat(l,".x],").concat(s,"[").concat(u,".x]);\n // make local support\n ").concat(p," = clamp( (").concat(p,"-0.5773)/(1.0-0.5773), 0.0, 1.0 );\n // shape transition\n ").concat(p," = pow( ").concat(p,", vec2(").concat(n,"/8.0) );\n // blend and return\n vec4 ").concat(this._tempTextureRead," = (").concat(h,"*").concat(p,".x + ").concat(d,"*").concat(p,".y) / (").concat(p,".x + ").concat(p,".y);\n ")},t}(RT);a("BABYLON.BiPlanarBlock",PT);var IT=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("input",Ns.Matrix),i.registerOutput("output",Ns.Float),i}return m(t,e),t.prototype.getClassName=function(){return"MatrixDeterminantBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this.output,r=this.input;return t.compilationString+=t._declareOutput(i)+" = determinant(".concat(r.associatedVariableName,");\n"),this},t}(Ws);a("BABYLON.MatrixDeterminantBlock",IT);var MT,OT=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.registerInput("input",Ns.Matrix),i.registerOutput("output",Ns.Matrix),i}return m(t,e),t.prototype.getClassName=function(){return"MatrixTransposeBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this.output,r=this.input;return t.compilationString+=t._declareOutput(i)+"".concat(i.associatedVariableName," = transpose(").concat(r.associatedVariableName,");\n"),this},t}(Ws);a("BABYLON.MatrixTransposeBlock",OT),function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Tangent=2]="Tangent",e[e.VertexColor=3]="VertexColor",e[e.UV1=4]="UV1",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6"}(MT||(MT={}));var DT,NT=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.attributeType=MT.None,i.registerInput("input",Ns.AutoDetect),i.registerInput("fallback",Ns.AutoDetect),i.registerOutput("output",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i._inputs[0].onConnectionObservable.add((function(e){var t;if(!i.attributeType){var r=e.ownerBlock;if(r instanceof rl&&r.isAttribute)switch(r.name){case"color":i.attributeType=MT.VertexColor;break;case"normal":i.attributeType=MT.Normal;break;case"tangent":i.attributeType=MT.Tangent;break;case"uv":i.attributeType=MT.UV1;break;case"uv2":i.attributeType=MT.UV2;break;case"uv3":i.attributeType=MT.UV3;break;case"uv4":i.attributeType=MT.UV4;break;case"uv5":i.attributeType=MT.UV5;break;case"uv6":i.attributeType=MT.UV6}else if(r instanceof Jy)switch(null===(t=i.input.connectedPoint)||void 0===t?void 0:t.name){case"normalOutput":i.attributeType=MT.Normal;break;case"tangentOutput":i.attributeType=MT.Tangent;break;case"uvOutput":i.attributeType=MT.UV1}}})),i}return m(t,e),t.prototype.getClassName=function(){return"MeshAttributeExistsBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"fallback",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=null;switch(this.attributeType){case MT.VertexColor:i="VERTEXCOLOR_NME";break;case MT.Normal:i="NORMAL";break;case MT.Tangent:i="TANGENT";break;case MT.UV1:i="UV1";break;case MT.UV2:i="UV2";break;case MT.UV3:i="UV3";break;case MT.UV4:i="UV4";break;case MT.UV5:i="UV5";break;case MT.UV6:i="UV6"}var r=t._declareOutput(this.output);return i&&(t.compilationString+="#ifdef ".concat(i,"\n")),t.compilationString+="".concat(r," = ").concat(this.input.associatedVariableName,";\n"),i&&(t.compilationString+="#else\n",t.compilationString+="".concat(r," = ").concat(this.fallback.associatedVariableName,";\n"),t.compilationString+="#endif\n"),this},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.attributeType=this.attributeType,t},t.prototype._deserialize=function(t,i,r){var n;e.prototype._deserialize.call(this,t,i,r),this.attributeType=null!==(n=t.attributeType)&&void 0!==n?n:MT.None},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".attributeType = ").concat(this.attributeType,";\n")},v([Ys("Attribute lookup",Xs.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:MT.None},{label:"Normal",value:MT.Normal},{label:"Tangent",value:MT.Tangent},{label:"Vertex Color",value:MT.VertexColor},{label:"UV1",value:MT.UV1},{label:"UV2",value:MT.UV2},{label:"UV3",value:MT.UV3},{label:"UV4",value:MT.UV4},{label:"UV5",value:MT.UV5},{label:"UV6",value:MT.UV6}]})],t.prototype,"attributeType",void 0),t}(Ws);a("BABYLON.MeshAttributeExistsBlock",NT),function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(DT||(DT={}));var FT=function(e){function t(t){var i=e.call(this,t,Fs.Neutral)||this;return i.type=DT.EaseInOutSine,i.registerInput("input",Ns.AutoDetect),i.registerOutput("output",Ns.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._inputs[0].excludedConnectionPointTypes.push(Ns.Matrix),i._inputs[0].excludedConnectionPointTypes.push(Ns.Object),i._inputs[0].excludedConnectionPointTypes.push(Ns.Int),i}return m(t,e),t.prototype.getClassName=function(){return"CurveBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._duplicateEntry=function(e,t){return"ret.".concat(t," = ").concat(e.replace(/VAL/g,"v."+t))},t.prototype._duplicateEntryDirect=function(e){return"return ".concat(e.replace(/VAL/g,"v"))},t.prototype._duplicateVector=function(e,t,i){if("float"===t||"f32"===t)return this._duplicateEntryDirect(e);for(var r=parseInt(t.replace("vec","")),n=i?"\n var ret: vec".concat(r,"f = vec").concat(r,"f(0.0);\n "):"\n vec".concat(r," ret = vec").concat(r,"(0.0);\n "),o=1;o<=r;o++)n+=this._duplicateEntry(e,1===o?"x":2===o?"y":3===o?"z":"w")+";\n";return n+"return ret;\n"},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i,r=this._outputs[0],n="",o=t._getShaderType(this.input.type),a=t.shaderLanguage===pt.WGSL;switch(i=DT[this.type]+"_"+o.replace("<","").replace(">",""),this.type){case DT.EaseInSine:n="return 1.0 - cos((v * 3.1415) / 2.0)";break;case DT.EaseOutSine:n="return sin((v * 3.1415) / 2.0)";break;case DT.EaseInOutSine:n="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case DT.EaseInQuad:n="return v * v";break;case DT.EaseOutQuad:n="return (1.0 - v) * (1.0 - v)";break;case DT.EaseInOutQuad:var s=t._generateTertiary("2.0 * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0","VAL < 0.5");n=this._duplicateVector(s,o,a);break;case DT.EaseInCubic:n="return v * v * v";break;case DT.EaseOutCubic:s="1.0 - pow(1.0 - VAL, 3.0)",n=this._duplicateVector(s,o,a);break;case DT.EaseInOutCubic:s=t._generateTertiary("4.0 * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0","VAL < 0.5"),n=this._duplicateVector(s,o,a);break;case DT.EaseInQuart:n="return v * v * v * v";break;case DT.EaseOutQuart:s="1.0 - pow(1.0 - VAL, 4.0)",n=this._duplicateVector(s,o,a);break;case DT.EaseInOutQuart:s=t._generateTertiary("8.0 * VAL * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0","VAL < 0.5"),n=this._duplicateVector(s,o,a);break;case DT.EaseInQuint:n="return v * v * v * v * v";break;case DT.EaseOutQuint:s="1.0 - pow(1.0 - VAL, 5.0)",n=this._duplicateVector(s,o,a);break;case DT.EaseInOutQuint:s=t._generateTertiary("16.0 * VAL * VAL * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0","VAL < 0.5"),n=this._duplicateVector(s,o,a);break;case DT.EaseInExpo:s=t._generateTertiary("0.0","pow(2.0, 10.0 * VAL - 10.0)","VAL == 0.0"),n=this._duplicateVector(s,o,a);break;case DT.EaseOutExpo:s=t._generateTertiary("1.0","1.0 - pow(2.0, -10.0 * VAL)","VAL == 1.0"),n=this._duplicateVector(s,o,a);break;case DT.EaseInOutExpo:s=t._generateTertiary("0.0",t._generateTertiary("1.0",t._generateTertiary("pow(2.0, 20.0 * VAL - 10.0) / 2.0","(2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0","VAL < 0.5"),"VAL == 1.0"),"VAL == 0.0"),n=this._duplicateVector(s,o,a);break;case DT.EaseInCirc:s="1.0 - sqrt(1.0 - pow(VAL, 2.0))",n=this._duplicateVector(s,o,a);break;case DT.EaseOutCirc:s="sqrt(1.0 - pow(VAL - 1.0, 2.0))",n=this._duplicateVector(s,o,a);break;case DT.EaseInOutCirc:s=t._generateTertiary("(1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0","(sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0","VAL < 0.5"),n=this._duplicateVector(s,o,a);break;case DT.EaseInBack:n="return 2.70158 * v * v * v - 1.70158 * v * v";break;case DT.EaseOutBack:s="2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)",n=this._duplicateVector(s,o,a);break;case DT.EaseInOutBack:s=t._generateTertiary("(pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0","(pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0","VAL < 0.5"),n=this._duplicateVector(s,o,a);break;case DT.EaseInElastic:s=t._generateTertiary("0.0",t._generateTertiary("1.0","-pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))","VAL == 1.0"),"VAL == 0.0"),n=this._duplicateVector(s,o,a);break;case DT.EaseOutElastic:s=t._generateTertiary("0.0",t._generateTertiary("1.0","pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0","VAL == 1.0"),"VAL == 0.0"),n=this._duplicateVector(s,o,a);break;case DT.EaseInOutElastic:s=t._generateTertiary("0.0",t._generateTertiary("1.0",t._generateTertiary("-(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0","(pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0","VAL < 0.5"),"VAL == 1.0"),"VAL == 0.0"),n=this._duplicateVector(s,o,a)}return a?t._emitFunction(i,"fn ".concat(i,"(v: ").concat(o,") -> ").concat(o," {").concat(n,";}\n"),""):t._emitFunction(i,"".concat(o," ").concat(i,"(").concat(o," v) {").concat(n,";}\n"),""),t.compilationString+=t._declareOutput(r)+" = ".concat(i,"(").concat(this.input.associatedVariableName,");\n"),this},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.curveType=this.type,t},t.prototype._deserialize=function(t,i,r){e.prototype._deserialize.call(this,t,i,r),this.type=t.curveType},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".type = BABYLON.CurveBlockTypes.").concat(DT[this.type],";\n")},t}(Ws);a("BABYLON.CurveBlock",FT);var LT,wT,BT,UT=function(){function e(){}return e.prototype.optimize=function(e,t){},e}(),VT=function(){function e(){this.mm=new Map}return e.prototype.get=function(e,t){var i=this.mm.get(e);if(void 0!==i)return i.get(t)},e.prototype.set=function(e,t,i){var r=this.mm.get(e);void 0===r&&this.mm.set(e,r=new Map),r.set(t,i)},e}(),kT=function(){function e(e,t,i){var r=this;this._baseMaterial=e,this._scene=null!=t?t:M.LastCreatedScene,this._options=i,this._subMeshToEffect=new Map,this._subMeshToDepthWrapper=new VT,this._meshes=new Map,this._onEffectCreatedObserver=this._baseMaterial.onEffectCreatedObservable.add((function(e){var t,i,n=null===(t=e.subMesh)||void 0===t?void 0:t.getMesh();n&&!r._meshes.has(n)&&r._meshes.set(n,n.onDisposeObservable.add((function(e){for(var t=r._subMeshToEffect.keys(),i=t.next();!0!==i.done;i=t.next()){var n=i.value;(null==n?void 0:n.getMesh())===e&&(r._subMeshToEffect.delete(n),r._deleteDepthWrapperEffect(n))}}))),(null===(i=r._subMeshToEffect.get(e.subMesh))||void 0===i?void 0:i[0])!==e.effect&&(r._subMeshToEffect.set(e.subMesh,[e.effect,r._scene.getEngine().currentRenderPassId]),r._deleteDepthWrapperEffect(e.subMesh))}))}return Object.defineProperty(e.prototype,"standalone",{get:function(){var e,t;return null!==(t=null===(e=this._options)||void 0===e?void 0:e.standalone)&&void 0!==t&&t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"baseMaterial",{get:function(){return this._baseMaterial},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"doNotInjectCode",{get:function(){var e,t;return null!==(t=null===(e=this._options)||void 0===e?void 0:e.doNotInjectCode)&&void 0!==t&&t},enumerable:!1,configurable:!0}),e.prototype._deleteDepthWrapperEffect=function(e){var t=this._subMeshToDepthWrapper.mm.get(e);t&&(t.forEach((function(e){var t;null===(t=e.mainDrawWrapper.effect)||void 0===t||t.dispose()})),this._subMeshToDepthWrapper.mm.delete(e))},e.prototype.getEffect=function(e,t,i){var r,n=null===(r=this._subMeshToDepthWrapper.mm.get(e))||void 0===r?void 0:r.get(t);if(!n)return null;var o=n.drawWrapper[i];return o||(o=n.drawWrapper[i]=new ho(this._scene.getEngine())).setEffect(n.mainDrawWrapper.effect,n.mainDrawWrapper.defines),o},e.prototype.isReadyForSubMesh=function(e,t,i,r,n){var o,a;return!(this.standalone&&!this._baseMaterial.isReadyForSubMesh(e.getMesh(),e,r))&&null!==(a=null===(o=this._makeEffect(e,t,i,n))||void 0===o?void 0:o.isReady())&&void 0!==a&&a},e.prototype.dispose=function(){this._baseMaterial.onEffectCreatedObservable.remove(this._onEffectCreatedObserver),this._onEffectCreatedObserver=null;for(var e=this._meshes.entries(),t=e.next();!0!==t.done;t=e.next()){var i=t.value,r=i[0],n=i[1];r.onDisposeObservable.remove(n)}},e.prototype._makeEffect=function(e,t,i,r){var n,o,a,s=this._scene.getEngine(),l=this._subMeshToEffect.get(e);if(!l)return null;var c=l[0],u=l[1],h=this._subMeshToDepthWrapper.get(e,i);if(!h){var d=new ho(s);d.defines=null!==(o=null===(n=e._getDrawWrapper(u))||void 0===n?void 0:n.defines)&&void 0!==o?o:null,(h={drawWrapper:[],mainDrawWrapper:d,depthDefines:"",token:Qi()}).drawWrapper[r]=d,this._subMeshToDepthWrapper.set(e,i,h)}var p=t.join("\n");if(h.mainDrawWrapper.effect&&p===h.depthDefines)return h.mainDrawWrapper.effect;h.depthDefines=p;var f=c.getUniformNames().slice(),_=c.vertexSourceCodeBeforeMigration,m=c.fragmentSourceCodeBeforeMigration;if(!this.doNotInjectCode){var g=this._options&&this._options.remappedVariables?"#include<shadowMapVertexNormalBias>(".concat(this._options.remappedVariables.join(","),")"):"#include<shadowMapVertexNormalBias>",v=this._options&&this._options.remappedVariables?"#include<shadowMapVertexMetric>(".concat(this._options.remappedVariables.join(","),")"):"#include<shadowMapVertexMetric>",y=this._options&&this._options.remappedVariables?"#include<shadowMapFragmentSoftTransparentShadow>(".concat(this._options.remappedVariables.join(","),")"):"#include<shadowMapFragmentSoftTransparentShadow>",b="#include<shadowMapFragment>",T="#include<shadowMapVertexExtraDeclaration>";_=(_=-1!==(_=(_=c.shaderLanguage===pt.GLSL?_.replace(/void\s+?main/g,"\n".concat(T,"\nvoid main")):_.replace(/@vertex/g,"\n".concat(T,"\n@vertex"))).replace(/#define SHADOWDEPTH_NORMALBIAS|#define CUSTOM_VERTEX_UPDATE_WORLDPOS/g,g)).indexOf("#define SHADOWDEPTH_METRIC")?_.replace(/#define SHADOWDEPTH_METRIC/g,v):_.replace(/}\s*$/g,v+"\n}")).replace(/#define SHADER_NAME.*?\n|out vec4 glFragColor;\n/g,"");var E=m.indexOf("#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW")>=0||m.indexOf("#define CUSTOM_FRAGMENT_BEFORE_FOG")>=0,S=-1!==m.indexOf("#define SHADOWDEPTH_FRAGMENT"),x="";E?m=m.replace(/#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW|#define CUSTOM_FRAGMENT_BEFORE_FOG/g,y):x=y+"\n",m=m.replace(/void\s+?main/g,Ei.IncludesShadersStore.shadowMapFragmentExtraDeclaration+"\nvoid main"),S?m=m.replace(/#define SHADOWDEPTH_FRAGMENT/g,b):x+=b+"\n",x&&(m=m.replace(/}\s*$/g,x+"}")),f.push("biasAndScaleSM","depthValuesSM","lightDataSM","softTransparentShadowSM")}h.mainDrawWrapper.effect=s.createEffect({vertexSource:_,fragmentSource:m,vertexToken:h.token,fragmentToken:h.token},{attributes:c.getAttributesNames(),uniformsNames:f,uniformBuffersNames:c.getUniformBuffersNames(),samplers:c.getSamplers(),defines:p+"\n"+c.defines.replace("#define SHADOWS","").replace(/#define SHADOW\d/g,""),indexParameters:c.getIndexParameters(),shaderLanguage:c.shaderLanguage},s);for(var A=0;A<h.drawWrapper.length;++A)A!==r&&(null===(a=h.drawWrapper[A])||void 0===a||a.setEffect(h.mainDrawWrapper.effect,h.mainDrawWrapper.defines));return h.mainDrawWrapper.effect},e}(),GT=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.DECAL=!1,t.DECALDIRECTUV=0,t.DECAL_SMOOTHALPHA=!1,t.GAMMADECAL=!1,t}return m(t,e),t}(Gs),zT=function(e){function t(t,i){void 0===i&&(i=!0);var r=e.call(this,t,"DecalMap",150,new GT,i)||this;return r._isEnabled=!1,r.isEnabled=!1,r._smoothAlpha=!1,r.smoothAlpha=!1,r.registerForExtraEvents=!0,r._internalMarkAllSubMeshesAsTexturesDirty=t._dirtyCallbacks[u.MATERIAL_TextureDirtyFlag],r}return m(t,e),t.prototype._markAllSubMeshesAsTexturesDirty=function(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()},t.prototype.isReadyForSubMesh=function(e,t,i,r){var n=r.getMesh().decalMap;return!(this._isEnabled&&(null==n?void 0:n.texture)&&xu.DecalMapEnabled&&t.texturesEnabled)||n.isReady()},t.prototype.prepareDefines=function(e,t,i){var r=i.decalMap;this._isEnabled&&(null==r?void 0:r.texture)&&xu.DecalMapEnabled&&t.texturesEnabled?((!e.DECAL||e.GAMMADECAL!==r.texture.gammaSpace)&&e.markAsTexturesDirty(),e.DECAL=!0,e.GAMMADECAL=r.texture.gammaSpace,e.DECAL_SMOOTHALPHA=this._smoothAlpha,ta(r.texture,e,"DECAL")):(e.DECAL&&e.markAsTexturesDirty(),e.DECAL=!1)},t.prototype.hardBindForSubMesh=function(e,t,i,r){var n=r.getMesh().decalMap;if(this._isEnabled&&(null==n?void 0:n.texture)&&xu.DecalMapEnabled&&t.texturesEnabled){var o=this._material.isFrozen,a=n.texture;e.useUbo&&o&&e.isSync||(e.updateFloat4("vDecalInfos",a.coordinatesIndex,0,0,0),ia(a,e,"decal")),e.setTexture("decalSampler",a)}},t.prototype.getClassName=function(){return"DecalMapConfiguration"},t.prototype.getSamplers=function(e){e.push("decalSampler")},t.prototype.getUniforms=function(){return{ubo:[{name:"vDecalInfos",size:4,type:"vec4"},{name:"decalMatrix",size:16,type:"mat4"}]}},v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"isEnabled",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"smoothAlpha",void 0),t}(Nu);function WT(e){return e instanceof ig?new Qm(e):null}function HT(e){return e instanceof ig?new Wm(e):null}function XT(e){return e instanceof ig?new Xm(e):null}function jT(e){return e instanceof ig?new Ym(e):null}function YT(e){return e instanceof ig?new Zm(e):null}function KT(e){return e instanceof ig?new $m(e):null}function QT(e){return e instanceof ig||e instanceof Uu?new Lu(e):null}a("BABYLON.DecalMapConfiguration",zT),function(e){e[e.MATERIAL_TYPE_STANDARD=0]="MATERIAL_TYPE_STANDARD",e[e.MATERIAL_TYPE_PBR=1]="MATERIAL_TYPE_PBR",e[e.MATERIAL_TYPE_SIMPLE=2]="MATERIAL_TYPE_SIMPLE"}(LT||(LT={})),function(e){e[e.COLOR_MODE_SET=0]="COLOR_MODE_SET",e[e.COLOR_MODE_ADD=1]="COLOR_MODE_ADD",e[e.COLOR_MODE_MULTIPLY=2]="COLOR_MODE_MULTIPLY"}(wT||(wT={})),function(e){e[e.COLOR_DISTRIBUTION_TYPE_SEGMENT=0]="COLOR_DISTRIBUTION_TYPE_SEGMENT",e[e.COLOR_DISTRIBUTION_TYPE_LINE=1]="COLOR_DISTRIBUTION_TYPE_LINE"}(BT||(BT={}));var qT=function(){function e(){}return e.DEFAULT_COLOR=Z.White(),e.DEFAULT_WIDTH_ATTENUATED=1,e.DEFAULT_WIDTH=.1,e}(),ZT=function(){function e(){}return e.ConvertPoints=function(e){if(e.length&&Array.isArray(e)&&"number"==typeof e[0])return[e];if(e.length&&Array.isArray(e[0])&&"number"==typeof e[0][0])return e;if(e.length&&!Array.isArray(e[0])&&e[0]instanceof V){for(var t=[],i=0;i<e.length;i++){var r=e[i];t.push(r.x,r.y,r.z)}return[t]}if(e.length>0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof V){var n=[];return e.forEach((function(e){n.push(e.flatMap((function(e){return[e.x,e.y,e.z]})))})),n}if(e instanceof Float32Array)return[Array.from(e)];if(e.length&&e[0]instanceof Float32Array){var o=[];return e.forEach((function(e){o.push(Array.from(e))})),o}return[]},e.OmitZeroLengthPredicate=function(e,t,i){var r=[];return t.subtract(e).lengthSquared()>0&&r.push([e,t]),i.subtract(t).lengthSquared()>0&&r.push([t,i]),e.subtract(i).lengthSquared()>0&&r.push([i,e]),0===r.length?null:r},e.OmitDuplicatesPredicate=function(t,i,r,n){var o=[];return e._SearchInPoints(t,i,n)||o.push([t,i]),e._SearchInPoints(i,r,n)||o.push([i,r]),e._SearchInPoints(r,t,n)||o.push([r,t]),0===o.length?null:o},e._SearchInPoints=function(e,t,i){for(var r,n,o,a=0,s=i;a<s.length;a++)for(var l=s[a],c=0;c<l.length;c++)if((null===(r=l[c])||void 0===r?void 0:r.equals(e))&&((null===(n=l[c+1])||void 0===n?void 0:n.equals(t))||(null===(o=l[c-1])||void 0===o?void 0:o.equals(t))))return!0;return!1},e.MeshesToLines=function(e,t){var i=[];return e.forEach((function(e,r){var n=e.getVerticesData(Nr.PositionKind),o=e.getIndices();if(n&&o)for(var a=0,s=0;a<o.length;a++){var l=3*o[s++],c=3*o[s++],u=3*o[s++],h=new V(n[l],n[l+1],n[l+2]),d=new V(n[c],n[c+1],n[c+2]),p=new V(n[u],n[u+1],n[u+2]);if(t){var f=t(h,d,p,i,a,l,e,r,n,o);if(f)for(var _=0,m=f;_<m.length;_++){var g=m[_];i.push(g)}}else i.push([h,d],[d,p],[p,h])}})),i},e.ToVector3Array=function(e){if(Array.isArray(e[0])){for(var t=[],i=0,r=e;i<r.length;i++){for(var n=r[i],o=[],a=0;a<n.length;a+=3)o.push(new V(n[a],n[a+1],n[a+2]));t.push(o)}return t}var s=e,l=[];for(a=0;a<s.length;a+=3)l.push(new V(s[a],s[a+1],s[a+2]));return l},e.ToNumberArray=function(e){return e.flatMap((function(e){return[e.x,e.y,e.z]}))},e.GetPointsCountInfo=function(e){for(var t=new Array(e.length),i=0,r=e.length;r--;)t[r]=e[r].length/3,i+=t[r];return{total:i,counts:t}},e.GetLineLength=function(t){if(0===t.length)return 0;var i;i="number"==typeof t[0]?e.ToVector3Array(t):t;for(var r=H.Vector3[0],n=0,o=0;o<i.length-1;o++){var a=i[o];n+=i[o+1].subtractToRef(a,r).length()}return n},e.GetLineLengthArray=function(e){for(var t=new Float32Array(e.length/3),i=0,r=0,n=e.length/3-1;r<n;r++){var o=e[3*r+0],a=e[3*r+1],s=e[3*r+2];o-=e[3*r+3],a-=e[3*r+4],s-=e[3*r+5],i+=Math.sqrt(o*o+a*a+s*s),t[r+1]=i}return t},e.SegmentizeSegmentByCount=function(e,t,i){var r=[],n=t.subtract(e),o=H.Vector3[0];o.setAll(i);var a=H.Vector3[1];n.divideToRef(o,a);var s=e.clone();r.push(s);for(var l=0;l<i;l++)s=s.clone(),r.push(s.addInPlace(a));return r},e.SegmentizeLineBySegmentLength=function(t,i){var r=t[0]instanceof V?e.GetLineSegments(t):"number"==typeof t[0]?e.GetLineSegments(e.ToVector3Array(t)):t,n=[];return r.forEach((function(t){t.length>i?e.SegmentizeSegmentByCount(t.point1,t.point2,Math.ceil(t.length/i)).forEach((function(e){n.push(e)})):(n.push(t.point1),n.push(t.point2))})),n},e.SegmentizeLineBySegmentCount=function(t,i){var r="number"==typeof t[0]?e.ToVector3Array(t):t,n=e.GetLineLength(r)/i;return e.SegmentizeLineBySegmentLength(r,n)},e.GetLineSegments=function(e){for(var t=[],i=0;i<e.length-1;i++){var r=e[i],n=e[i+1],o=n.subtract(r).length();t.push({point1:r,point2:n,length:o})}return t},e.GetMinMaxSegmentLength=function(t){var i=e.GetLineSegments(t).sort((function(e){return e.length}));return{min:i[0].length,max:i[i.length-1].length}},e.GetPositionOnLineByVisibility=function(e,t,i,r){void 0===r&&(r=!1);for(var n=t*i,o=0,a=0,s=e.length,l=0;l<s;l++){if(n<=o+e[l].length){a=l;break}o+=e[l].length}var c=(n-o)/e[a].length;return e[a].point2.subtractToRef(e[a].point1,H.Vector3[0]),H.Vector3[1]=H.Vector3[0].multiplyByFloats(c,c,c),r||H.Vector3[1].addInPlace(e[a].point1),H.Vector3[1].clone()},e.GetCircleLinePoints=function(e,t,i,r,n){void 0===i&&(i=0),void 0===r&&(r=e),void 0===n&&(n=2*Math.PI/t);for(var o=[],a=0;a<=t;a++)o.push(new V(Math.cos(a*n)*e,Math.sin(a*n)*r,i));return o},e.GetBezierLinePoints=function(e,t,i,r){return Cn.CreateQuadraticBezier(e,t,i,r).getPoints().flatMap((function(e){return[e.x,e.y,e.z]}))},e.GetArrowCap=function(e,t,i,r,n,o,a){return void 0===o&&(o=0),void 0===a&&(a=0),{points:[e.clone(),e.add(t.multiplyByFloats(i,i,i))],widths:[r,n,o,a]}},e.GetPointsFromText=function(e,t,i,r,n,o){void 0===n&&(n=0),void 0===o&&(o=!0);for(var a=[],s=0,l=tp(e,t,i,r);s<l.length;s++){for(var c=l[s],u=0,h=c.paths;u<h.length;u++){for(var d=[],p=0,f=h[u].getPoints();p<f.length;p++){var _=f[p];d.push(_.x,_.y,n)}a.push(d)}if(o)for(var m=0,g=c.holes;m<g.length;m++){for(var v=[],y=0,b=g[m].getPoints();y<b.length;y++)_=b[y],v.push(_.x,_.y,n);a.push(v)}}return a},e.Color3toRGBAUint8=function(e){for(var t=new Uint8Array(4*e.length),i=0,r=0;i<e.length;i++)t[r++]=255*e[i].r,t[r++]=255*e[i].g,t[r++]=255*e[i].b,t[r++]=255;return t},e.CreateColorsTexture=function(t,i,r,n){var o,a=null!==(o=n.getEngine().getCaps().maxTextureSize)&&void 0!==o?o:1,s=i.length>a?a:i.length,l=Math.ceil(i.length/a);l>1&&(i=T(T([],i,!0),Array(s*l-i.length).fill(i[0]),!0));var c=e.Color3toRGBAUint8(i),u=new is(c,s,l,Do.TEXTUREFORMAT_RGBA,n,!1,!0,r);return u.name=t,u},e.PrepareEmptyColorsTexture=function(e){if(!qT.EmptyColorsTexture){var t=new Uint8Array(4);qT.EmptyColorsTexture=new is(t,1,1,Do.TEXTUREFORMAT_RGBA,e,!1,!1,is.NEAREST_NEAREST),qT.EmptyColorsTexture.name="grlEmptyColorsTexture"}return qT.EmptyColorsTexture},e.DisposeEmptyColorsTexture=function(){var e;null===(e=qT.EmptyColorsTexture)||void 0===e||e.dispose(),qT.EmptyColorsTexture=null},e.BooleanToNumber=function(e){return e?1:0},e}(),JT=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.GREASED_LINE_HAS_COLOR=!1,t.GREASED_LINE_SIZE_ATTENUATION=!1,t.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=!1,t.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=!1,t.GREASED_LINE_CAMERA_FACING=!0,t}return m(t,e),t}(Gs),$T=function(e){function t(i,r,n){var o,a,s,l,c,u,h,d,p,f,_,m,g,v,y,b,T,E=this;n=n||{color:qT.DEFAULT_COLOR};var S=new JT;return S.GREASED_LINE_HAS_COLOR=!!n.color&&!n.useColors,S.GREASED_LINE_SIZE_ATTENUATION=null!==(o=n.sizeAttenuation)&&void 0!==o&&o,S.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=n.colorDistributionType===BT.COLOR_DISTRIBUTION_TYPE_LINE,S.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=(null!=r?r:i.getScene()).useRightHandedSystem,S.GREASED_LINE_CAMERA_FACING=null===(a=n.cameraFacing)||void 0===a||a,(E=e.call(this,i,t.GREASED_LINE_MATERIAL_NAME,200,S)||this).colorsTexture=null,E._scene=null!=r?r:i.getScene(),E._engine=E._scene.getEngine(),E._cameraFacing=null===(s=n.cameraFacing)||void 0===s||s,E.visibility=null!==(l=n.visibility)&&void 0!==l?l:1,E.useDash=null!==(c=n.useDash)&&void 0!==c&&c,E.dashRatio=null!==(u=n.dashRatio)&&void 0!==u?u:.5,E.dashOffset=null!==(h=n.dashOffset)&&void 0!==h?h:0,E.width=n.width?n.width:n.sizeAttenuation?qT.DEFAULT_WIDTH_ATTENUATED:qT.DEFAULT_WIDTH,E._sizeAttenuation=null!==(d=n.sizeAttenuation)&&void 0!==d&&d,E.colorMode=null!==(p=n.colorMode)&&void 0!==p?p:wT.COLOR_MODE_SET,E._color=null!==(f=n.color)&&void 0!==f?f:null,E.useColors=null!==(_=n.useColors)&&void 0!==_&&_,E._colorsDistributionType=null!==(m=n.colorDistributionType)&&void 0!==m?m:BT.COLOR_DISTRIBUTION_TYPE_SEGMENT,E.colorsSampling=null!==(g=n.colorsSampling)&&void 0!==g?g:is.NEAREST_NEAREST,E._colors=null!==(v=n.colors)&&void 0!==v?v:null,E.dashCount=null!==(y=n.dashCount)&&void 0!==y?y:1,E.resolution=null!==(b=n.resolution)&&void 0!==b?b:new U(E._engine.getRenderWidth(),E._engine.getRenderHeight()),n.colorsTexture?E.colorsTexture=n.colorsTexture:E._colors?E.colorsTexture=ZT.CreateColorsTexture("".concat(i.name,"-colors-texture"),E._colors,E.colorsSampling,E._scene):(E._color=null!==(T=E._color)&&void 0!==T?T:qT.DEFAULT_COLOR,ZT.PrepareEmptyColorsTexture(E._scene)),E._engine.onDisposeObservable.add((function(){ZT.DisposeEmptyColorsTexture()})),E._enable(!0),E}return m(t,e),t.prototype.getAttributes=function(e){e.push("grl_offsets"),e.push("grl_widths"),e.push("grl_colorPointers"),e.push("grl_counters"),this._cameraFacing?(e.push("grl_previousAndSide"),e.push("grl_nextAndCounters")):e.push("grl_slopes")},t.prototype.getSamplers=function(e){e.push("grl_colors")},t.prototype.getActiveTextures=function(e){this.colorsTexture&&e.push(this.colorsTexture)},t.prototype.getUniforms=function(){var e=[{name:"grl_singleColor",size:3,type:"vec3"},{name:"grl_textureSize",size:2,type:"vec2"},{name:"grl_dashOptions",size:4,type:"vec4"},{name:"grl_colorMode_visibility_colorsWidth_useColors",size:4,type:"vec4"}];return this._cameraFacing&&e.push({name:"grl_projection",size:16,type:"mat4"},{name:"grl_aspect_resolution_lineWidth",size:4,type:"vec4"}),{ubo:e,vertex:this._cameraFacing?"\n uniform vec4 grl_aspect_resolution_lineWidth;\n uniform mat4 grl_projection;\n ":"",fragment:"\n uniform vec4 grl_dashOptions;\n uniform vec2 grl_textureSize;\n uniform vec4 grl_colorMode_visibility_colorsWidth_useColors;\n uniform vec3 grl_singleColor;\n "}},Object.defineProperty(t.prototype,"isEnabled",{get:function(){return!0},enumerable:!1,configurable:!0}),t.prototype.bindForSubMesh=function(e){var t,i,r;if(this._cameraFacing){var n=this._scene.activeCamera;if(!n)throw Error("GreasedLinePluginMaterial requires an active camera.");var o=n.getProjectionMatrix();e.updateMatrix("grl_projection",o);var a=H.Vector4[0];a.x=this._aspect,a.y=this._resolution.x,a.z=this._resolution.y,a.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",a)}var s=H.Vector4[0];s.x=ZT.BooleanToNumber(this.useDash),s.y=this._dashArray,s.z=this.dashOffset,s.w=this.dashRatio,e.updateVector4("grl_dashOptions",s);var l=H.Vector4[1];l.x=this.colorMode,l.y=this.visibility,l.z=this.colorsTexture?this.colorsTexture.getSize().width:0,l.w=ZT.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",l),this._color&&e.updateColor3("grl_singleColor",this._color);var c=null!==(t=this.colorsTexture)&&void 0!==t?t:qT.EmptyColorsTexture;e.setTexture("grl_colors",c),e.updateFloat2("grl_textureSize",null!==(i=null==c?void 0:c.getSize().width)&&void 0!==i?i:1,null!==(r=null==c?void 0:c.getSize().height)&&void 0!==r?r:1)},t.prototype.prepareDefines=function(e,t,i){e.GREASED_LINE_HAS_COLOR=!!this.color&&!this.useColors,e.GREASED_LINE_SIZE_ATTENUATION=this._sizeAttenuation,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=this._colorsDistributionType===BT.COLOR_DISTRIBUTION_TYPE_LINE,e.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem,e.GREASED_LINE_CAMERA_FACING=this._cameraFacing},t.prototype.getClassName=function(){return t.GREASED_LINE_MATERIAL_NAME},t.prototype.getCustomCode=function(e){if("vertex"===e){var t={CUSTOM_VERTEX_DEFINITIONS:"\n attribute float grl_widths;\n attribute vec3 grl_offsets;\n attribute float grl_colorPointers;\n varying float grlCounters;\n varying float grlColorPointer;\n\n #ifdef GREASED_LINE_CAMERA_FACING\n attribute vec4 grl_previousAndSide;\n attribute vec4 grl_nextAndCounters;\n\n vec2 grlFix( vec4 i, float aspect ) {\n vec2 res = i.xy / i.w;\n res.x *= aspect;\n return res;\n }\n #else\n attribute vec3 grl_slopes;\n attribute float grl_counters;\n #endif\n ",CUSTOM_VERTEX_UPDATE_POSITION:"\n #ifdef GREASED_LINE_CAMERA_FACING\n vec3 grlPositionOffset = grl_offsets;\n positionUpdated += grlPositionOffset;\n #else\n positionUpdated = (positionUpdated + grl_offsets) + (grl_slopes * grl_widths);\n #endif\n ",CUSTOM_VERTEX_MAIN_END:"\n grlColorPointer = grl_colorPointers;\n\n #ifdef GREASED_LINE_CAMERA_FACING\n\n float grlAspect = grl_aspect_resolution_lineWidth.x;\n float grlBaseWidth = grl_aspect_resolution_lineWidth.w;\n\n\n vec3 grlPrevious = grl_previousAndSide.xyz;\n float grlSide = grl_previousAndSide.w;\n\n vec3 grlNext = grl_nextAndCounters.xyz;\n grlCounters = grl_nextAndCounters.w;\n\n mat4 grlMatrix = viewProjection * finalWorld;\n vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 );\n vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 );\n vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 );\n\n vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect );\n vec2 grlPrevP = grlFix( grlPrevPos, grlAspect );\n vec2 grlNextP = grlFix( grlNextPos, grlAspect );\n\n float grlWidth = grlBaseWidth * grl_widths;\n\n vec2 grlDir;\n if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP );\n else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP );\n else {\n vec2 grlDir1 = normalize( grlCurrentP - grlPrevP );\n vec2 grlDir2 = normalize( grlNextP - grlCurrentP );\n grlDir = normalize( grlDir1 + grlDir2 );\n }\n vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. );\n #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM\n grlNormal.xy *= -.5 * grlWidth;\n #else\n grlNormal.xy *= .5 * grlWidth;\n #endif\n\n grlNormal *= grl_projection;\n\n #ifdef GREASED_LINE_SIZE_ATTENUATION\n grlNormal.xy *= grlFinalPosition.w;\n grlNormal.xy /= ( vec4( grl_aspect_resolution_lineWidth.yz, 0., 1. ) * grl_projection ).xy;\n #endif\n\n grlFinalPosition.xy += grlNormal.xy * grlSide;\n gl_Position = grlFinalPosition;\n\n vPositionW = vec3(grlFinalPosition);\n #else\n grlCounters = grl_counters;\n #endif\n "};return this._cameraFacing&&(t["!gl_Position\\=viewProjection\\*worldPos;"]="//"),t}return"fragment"===e?{CUSTOM_FRAGMENT_DEFINITIONS:"\n varying float grlCounters;\n varying float grlColorPointer;\n uniform sampler2D grl_colors;\n ",CUSTOM_FRAGMENT_MAIN_END:"\n float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x;\n float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y;\n float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z;\n float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w;\n\n float grlUseDash = grl_dashOptions.x;\n float grlDashArray = grl_dashOptions.y;\n float grlDashOffset = grl_dashOptions.z;\n float grlDashRatio = grl_dashOptions.w;\n\n gl_FragColor.a *= step(grlCounters, grlVisibility);\n if( gl_FragColor.a == 0. ) discard;\n\n if(grlUseDash == 1.){\n gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio));\n if (gl_FragColor.a == 0.) discard;\n }\n\n #ifdef GREASED_LINE_HAS_COLOR\n if (grlColorMode == ".concat(wT.COLOR_MODE_SET,".) {\n gl_FragColor.rgb = grl_singleColor;\n } else if (grlColorMode == ").concat(wT.COLOR_MODE_ADD,".) {\n gl_FragColor.rgb += grl_singleColor;\n } else if (grlColorMode == ").concat(wT.COLOR_MODE_MULTIPLY,".) {\n gl_FragColor.rgb *= grl_singleColor;\n }\n #else\n if (grlUseColors == 1.) {\n #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE\n vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.);\n #else\n vec2 lookup = vec2(fract(grlColorPointer / grl_textureSize.x), 1.0 - floor(grlColorPointer / grl_textureSize.x) / max(grl_textureSize.y - 1.0, 1.0));\n vec4 grlColor = texture2D(grl_colors, lookup, 0.0);\n #endif\n if (grlColorMode == ").concat(wT.COLOR_MODE_SET,".) {\n gl_FragColor = grlColor;\n } else if (grlColorMode == ").concat(wT.COLOR_MODE_ADD,".) {\n gl_FragColor += grlColor;\n } else if (grlColorMode == ").concat(wT.COLOR_MODE_MULTIPLY,".) {\n gl_FragColor *= grlColor;\n }\n }\n #endif\n\n ")}:null},t.prototype.dispose=function(){var t;null===(t=this.colorsTexture)||void 0===t||t.dispose(),e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"colors",{get:function(){return this._colors},set:function(e){this.setColors(e)},enumerable:!1,configurable:!0}),t.prototype.setColors=function(e,t,i){var r,n,o,a;void 0===t&&(t=!1),void 0===i&&(i=!1);var s=null!==(n=null===(r=this._colors)||void 0===r?void 0:r.length)&&void 0!==n?n:0;if(this._colors=e,null!==e&&0!==e.length){if(!t||i)if(this.colorsTexture&&s===e.length&&!i){var l=ZT.Color3toRGBAUint8(e);this.colorsTexture.update(l)}else null===(a=this.colorsTexture)||void 0===a||a.dispose(),this.colorsTexture=ZT.CreateColorsTexture("".concat(this._material.name,"-colors-texture"),e,this.colorsSampling,this._scene)}else null===(o=this.colorsTexture)||void 0===o||o.dispose()},t.prototype.updateLazy=function(){this._colors&&this.setColors(this._colors,!1,!0)},Object.defineProperty(t.prototype,"dashCount",{get:function(){return this._dashCount},set:function(e){this._dashCount=e,this._dashArray=1/e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"sizeAttenuation",{get:function(){return this._sizeAttenuation},set:function(e){this._sizeAttenuation=e,this.markAllDefinesAsDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"color",{get:function(){return this._color},set:function(e){this.setColor(e)},enumerable:!1,configurable:!0}),t.prototype.setColor=function(e,t){void 0===t&&(t=!1),null===this._color&&null!==e||null!==this._color&&null===e?(this._color=e,!t&&this.markAllDefinesAsDirty()):this._color=e},Object.defineProperty(t.prototype,"colorsDistributionType",{get:function(){return this._colorsDistributionType},set:function(e){this._colorsDistributionType=e,this.markAllDefinesAsDirty()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"resolution",{get:function(){return this._resolution},set:function(e){this._aspect=e.x/e.y,this._resolution=e},enumerable:!1,configurable:!0}),t.prototype.serialize=function(){var t=e.prototype.serialize.call(this),i={colorDistributionType:this._colorsDistributionType,colorsSampling:this.colorsSampling,colorMode:this.colorMode,dashCount:this._dashCount,dashOffset:this.dashOffset,dashRatio:this.dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this.useColors,useDash:this.useDash,visibility:this.visibility,width:this.width};return this._colors&&(i.colors=this._colors),this._color&&(i.color=this._color),t.greasedLineMaterialOptions=i,t},t.prototype.parse=function(t,i,r){var n;e.prototype.parse.call(this,t,i,r);var o=t.greasedLineMaterialOptions;null===(n=this.colorsTexture)||void 0===n||n.dispose(),o.color&&this.setColor(o.color,!0),o.colorDistributionType&&(this.colorsDistributionType=o.colorDistributionType),o.colors&&(this.colors=o.colors),o.colorsSampling&&(this.colorsSampling=o.colorsSampling),o.colorMode&&(this.colorMode=o.colorMode),o.useColors&&(this.useColors=o.useColors),o.visibility&&(this.visibility=o.visibility),o.useDash&&(this.useDash=o.useDash),o.dashCount&&(this.dashCount=o.dashCount),o.dashRatio&&(this.dashRatio=o.dashRatio),o.dashOffset&&(this.dashOffset=o.dashOffset),o.width&&(this.width=o.width),o.sizeAttenuation&&(this.sizeAttenuation=o.sizeAttenuation),o.resolution&&(this.resolution=o.resolution),this.colors?this.colorsTexture=ZT.CreateColorsTexture("".concat(this._material.name,"-colors-texture"),this.colors,this.colorsSampling,i):ZT.PrepareEmptyColorsTexture(i),this.markAllDefinesAsDirty()},t.prototype.copyTo=function(e){var t,i=e;null===(t=i.colorsTexture)||void 0===t||t.dispose(),this._colors&&(i.colorsTexture=ZT.CreateColorsTexture("".concat(i._material.name,"-colors-texture"),this._colors,i.colorsSampling,this._scene)),i.setColor(this.color,!0),i.colorsDistributionType=this.colorsDistributionType,i.colorsSampling=this.colorsSampling,i.colorMode=this.colorMode,i.useColors=this.useColors,i.visibility=this.visibility,i.useDash=this.useDash,i.dashCount=this.dashCount,i.dashRatio=this.dashRatio,i.dashOffset=this.dashOffset,i.width=this.width,i.sizeAttenuation=this.sizeAttenuation,i.resolution=this.resolution,i.markAllDefinesAsDirty()},t.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial",t}(Nu);a("BABYLON.".concat($T.GREASED_LINE_MATERIAL_NAME),$T);li.ShadersStore.greasedLinePixelShader="precision highp float;uniform sampler2D grlColors;uniform float grlUseColors;uniform float grlUseDash;uniform float grlDashArray;uniform float grlDashOffset;uniform float grlDashRatio;uniform float grlVisibility;uniform float grlColorsWidth;uniform vec2 grl_colorModeAndColorDistributionType;uniform vec3 grlColor;varying float grlCounters;varying float grlColorPointer;void main() {float grlColorMode=grl_colorModeAndColorDistributionType.x;float grlColorDistributionType=grl_colorModeAndColorDistributionType.y;gl_FragColor=vec4(grlColor,1.);gl_FragColor.a=step(grlCounters,grlVisibility);if (gl_FragColor.a==0.) discard;if( grlUseDash==1. ){gl_FragColor.a=ceil(mod(grlCounters+grlDashOffset,grlDashArray)-(grlDashArray*grlDashRatio));if (gl_FragColor.a==0.) discard;}\nif (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==COLOR_DISTRIBUTION_TYPE_LINE) { \ntextureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);}\nif (grlColorMode==COLOR_MODE_SET) {gl_FragColor=textureColor;} else if (grlColorMode==COLOR_MODE_ADD) {gl_FragColor+=textureColor;} else if (grlColorMode==COLOR_MODE_MULTIPLY) {gl_FragColor*=textureColor;}}}\n";li.ShadersStore.greasedLineVertexShader="precision highp float;\n#include<instancesDeclaration>\nattribute float grl_widths;attribute vec3 grl_offsets;attribute float grl_colorPointers;attribute vec3 position;uniform mat4 viewProjection;uniform mat4 projection;varying float grlCounters;varying float grlColorPointer;\n#ifdef GREASED_LINE_CAMERA_FACING\nattribute vec4 grl_nextAndCounters;attribute vec4 grl_previousAndSide;uniform vec2 grlResolution;uniform float grlAspect;uniform float grlWidth;uniform float grlSizeAttenuation;vec2 grlFix( vec4 i,float aspect ) {vec2 res=i.xy/i.w;res.x*=aspect;return res;}\n#else\nattribute vec3 grl_slopes;attribute float grl_counters;\n#endif\nvoid main() {\n#include<instancesVertex>\ngrlColorPointer=grl_colorPointers;mat4 grlMatrix=viewProjection*finalWorld ;\n#ifdef GREASED_LINE_CAMERA_FACING\nfloat grlBaseWidth=grlWidth;vec3 grlPrevious=grl_previousAndSide.xyz;float grlSide=grl_previousAndSide.w;vec3 grlNext=grl_nextAndCounters.xyz;grlCounters=grl_nextAndCounters.w;vec3 grlPositionOffset=grl_offsets;vec4 grlFinalPosition=grlMatrix*vec4( position+grlPositionOffset ,1.0 );vec4 grlPrevPos=grlMatrix*vec4( grlPrevious+grlPositionOffset,1.0 );vec4 grlNextPos=grlMatrix*vec4( grlNext+grlPositionOffset,1.0 );vec2 grlCurrentP=grlFix( grlFinalPosition,grlAspect );vec2 grlPrevP=grlFix( grlPrevPos,grlAspect );vec2 grlNextP=grlFix( grlNextPos,grlAspect );float grlWidth=grlBaseWidth*grl_widths;vec2 grlDir;if( grlNextP==grlCurrentP ) grlDir=normalize( grlCurrentP-grlPrevP );else if( grlPrevP==grlCurrentP ) grlDir=normalize( grlNextP-grlCurrentP );else {vec2 grlDir1=normalize( grlCurrentP-grlPrevP );vec2 grlDir2=normalize( grlNextP-grlCurrentP );grlDir=normalize( grlDir1+grlDir2 );}\nvec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. );\n#ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM\ngrlNormal.xy*=-.5*grlWidth;\n#else\ngrlNormal.xy*=.5*grlWidth;\n#endif\ngrlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;}\ngrlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition;\n#else\ngrlCounters=grl_counters;vec4 grlFinalPosition=grlMatrix*vec4( (position+grl_offsets)+grl_slopes*grl_widths ,1.0 ) ;gl_Position=grlFinalPosition;\n#endif\n}\n";var eE,tE=function(e){function t(t,i,r){var n,o,a,s,l,c,u,h,d,p,f,_,m,g,v=this,y=["COLOR_DISTRIBUTION_TYPE_LINE ".concat(BT.COLOR_DISTRIBUTION_TYPE_LINE,"."),"COLOR_DISTRIBUTION_TYPE_SEGMENT ".concat(BT.COLOR_DISTRIBUTION_TYPE_SEGMENT,"."),"COLOR_MODE_SET ".concat(wT.COLOR_MODE_SET,"."),"COLOR_MODE_ADD ".concat(wT.COLOR_MODE_ADD,"."),"COLOR_MODE_MULTIPLY ".concat(wT.COLOR_MODE_MULTIPLY,".")],b=["position","grl_widths","grl_offsets","grl_colorPointers"];i.useRightHandedSystem&&y.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),r.cameraFacing?(y.push("GREASED_LINE_CAMERA_FACING"),b.push("grl_previousAndSide","grl_nextAndCounters")):(b.push("grl_slopes"),b.push("grl_counters")),(v=e.call(this,t,i,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:b,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:y})||this)._color=Z.White(),v._colorsDistributionType=BT.COLOR_DISTRIBUTION_TYPE_SEGMENT,v._colorsTexture=null,r=r||{color:qT.DEFAULT_COLOR};var T=i.getEngine();return v.visibility=null!==(n=r.visibility)&&void 0!==n?n:1,v.useDash=null!==(o=r.useDash)&&void 0!==o&&o,v.dashRatio=null!==(a=r.dashRatio)&&void 0!==a?a:.5,v.dashOffset=null!==(s=r.dashOffset)&&void 0!==s?s:0,v.dashCount=null!==(l=r.dashCount)&&void 0!==l?l:1,v.width=r.width?r.width:r.sizeAttenuation&&r.cameraFacing?qT.DEFAULT_WIDTH_ATTENUATED:qT.DEFAULT_WIDTH,v.sizeAttenuation=null!==(c=r.sizeAttenuation)&&void 0!==c&&c,v.color=null!==(u=r.color)&&void 0!==u?u:Z.White(),v.useColors=null!==(h=r.useColors)&&void 0!==h&&h,v.colorsDistributionType=null!==(d=r.colorDistributionType)&&void 0!==d?d:BT.COLOR_DISTRIBUTION_TYPE_SEGMENT,v.colorsSampling=null!==(p=r.colorsSampling)&&void 0!==p?p:is.NEAREST_NEAREST,v.colorMode=null!==(f=r.colorMode)&&void 0!==f?f:wT.COLOR_MODE_SET,v._colors=null!==(_=r.colors)&&void 0!==_?_:null,v._cameraFacing=null===(m=r.cameraFacing)||void 0===m||m,v.resolution=null!==(g=r.resolution)&&void 0!==g?g:new U(T.getRenderWidth(),T.getRenderHeight()),r.colorsTexture?v.colorsTexture=r.colorsTexture:v.colorsTexture=ZT.PrepareEmptyColorsTexture(i),v._colors&&v.setColors(v._colors),T.onDisposeObservable.add((function(){ZT.DisposeEmptyColorsTexture()})),v}return m(t,e),t.prototype.dispose=function(){var t;null===(t=this._colorsTexture)||void 0===t||t.dispose(),e.prototype.dispose.call(this)},t.prototype._setColorModeAndColorDistributionType=function(){this.setVector2("grl_colorModeAndColorDistributionType",new U(this._colorMode,this._colorsDistributionType))},t.prototype.updateLazy=function(){this._colors&&this.setColors(this._colors,!1,!0)},Object.defineProperty(t.prototype,"colors",{get:function(){return this._colors},set:function(e){this.setColors(e)},enumerable:!1,configurable:!0}),t.prototype.setColors=function(e,t,i){var r,n,o,a;void 0===t&&(t=!1),void 0===i&&(i=!1);var s=null!==(n=null===(r=this._colors)||void 0===r?void 0:r.length)&&void 0!==n?n:0;if(this._colors=e,null!==e&&0!==e.length){if(!t||i)if(this._colorsTexture&&s===e.length&&!i){var l=ZT.Color3toRGBAUint8(e);this._colorsTexture.update(l)}else null===(a=this._colorsTexture)||void 0===a||a.dispose(),this.colorsTexture=ZT.CreateColorsTexture("".concat(this.name,"-colors-texture"),e,this.colorsSampling,this.getScene())}else null===(o=this._colorsTexture)||void 0===o||o.dispose()},Object.defineProperty(t.prototype,"colorsTexture",{get:function(){var e;return null!==(e=this._colorsTexture)&&void 0!==e?e:null},set:function(e){this._colorsTexture=e,this.setFloat("grlColorsWidth",this._colorsTexture.getSize().width),this.setTexture("grlColors",this._colorsTexture)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"width",{get:function(){return this._width},set:function(e){this._width=e,this.setFloat("grlWidth",e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"useColors",{get:function(){return this._useColors},set:function(e){this._useColors=e,this.setFloat("grlUseColors",ZT.BooleanToNumber(e))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"colorsSampling",{get:function(){return this._colorsSampling},set:function(e){this._colorsSampling=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"visibility",{get:function(){return this._visibility},set:function(e){this._visibility=e,this.setFloat("grlVisibility",e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"useDash",{get:function(){return this._useDash},set:function(e){this._useDash=e,this.setFloat("grlUseDash",ZT.BooleanToNumber(e))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dashOffset",{get:function(){return this._dashOffset},set:function(e){this._dashOffset=e,this.setFloat("grlDashOffset",e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dashRatio",{get:function(){return this._dashRatio},set:function(e){this._dashRatio=e,this.setFloat("grlDashRatio",e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dashCount",{get:function(){return this._dashCount},set:function(e){this._dashCount=e,this._dashArray=1/e,this.setFloat("grlDashArray",this._dashArray)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"sizeAttenuation",{get:function(){return this._sizeAttenuation},set:function(e){this._sizeAttenuation=e,this.setFloat("grlSizeAttenuation",ZT.BooleanToNumber(e))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"color",{get:function(){return this.color},set:function(e){this.setColor(e)},enumerable:!1,configurable:!0}),t.prototype.setColor=function(e){e=null!=e?e:qT.DEFAULT_COLOR,this._color=e,this.setColor3("grlColor",e)},Object.defineProperty(t.prototype,"colorsDistributionType",{get:function(){return this._colorsDistributionType},set:function(e){this._colorsDistributionType=e,this._setColorModeAndColorDistributionType()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"colorMode",{get:function(){return this._colorMode},set:function(e){this._colorMode=e,this._setColorModeAndColorDistributionType()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"resolution",{get:function(){return this._resolution},set:function(e){this._resolution=e,this.setVector2("grlResolution",e),this.setFloat("grlAspect",e.x/e.y)},enumerable:!1,configurable:!0}),t.prototype.serialize=function(){var t=e.prototype.serialize.call(this),i={colorDistributionType:this._colorsDistributionType,colorsSampling:this._colorsSampling,colorMode:this._colorMode,color:this._color,dashCount:this._dashCount,dashOffset:this._dashOffset,dashRatio:this._dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this._useColors,useDash:this._useDash,visibility:this._visibility,width:this._width,cameraFacing:this._cameraFacing};return this._colors&&(i.colors=this._colors),t.greasedLineMaterialOptions=i,t},t.prototype.parse=function(e,t,i){var r,n,o=e.greasedLineMaterialOptions;null===(r=this._colorsTexture)||void 0===r||r.dispose(),o.color&&(this.color=o.color),o.colorDistributionType&&(this.colorsDistributionType=o.colorDistributionType),o.colorsSampling&&(this.colorsSampling=o.colorsSampling),o.colorMode&&(this.colorMode=o.colorMode),o.useColors&&(this.useColors=o.useColors),o.visibility&&(this.visibility=o.visibility),o.useDash&&(this.useDash=o.useDash),o.dashCount&&(this.dashCount=o.dashCount),o.dashRatio&&(this.dashRatio=o.dashRatio),o.dashOffset&&(this.dashOffset=o.dashOffset),o.width&&(this.width=o.width),o.sizeAttenuation&&(this.sizeAttenuation=o.sizeAttenuation),o.resolution&&(this.resolution=o.resolution),o.colors?this.colorsTexture=ZT.CreateColorsTexture("".concat(this.name,"-colors-texture"),o.colors,this.colorsSampling,this.getScene()):this.colorsTexture=ZT.PrepareEmptyColorsTexture(t),this._cameraFacing=null===(n=o.cameraFacing)||void 0===n||n,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)},t}(ld),iE=[new Z(.98,.26,.38),new Z(.47,.75,.3),new Z(0,.26,.77),new Z(.97,.6,.76),new Z(.19,.63,.78),new Z(.98,.8,.6),new Z(.65,.43,.15),new Z(.15,.47,.22),new Z(.67,.71,.86),new Z(.09,.46,.56),new Z(.8,.98,.02),new Z(.39,.29,.13),new Z(.53,.63,.06),new Z(.95,.96,.41),new Z(1,.72,.94),new Z(.63,.08,.31),new Z(.66,.96,.95),new Z(.22,.14,.19),new Z(.14,.65,.59),new Z(.93,1,.68),new Z(.93,.14,.44),new Z(.47,.86,.67),new Z(.85,.07,.78),new Z(.53,.64,.98),new Z(.43,.37,.56),new Z(.71,.65,.25),new Z(.66,.19,.01),new Z(.94,.53,.12),new Z(.41,.44,.44),new Z(.24,.71,.96),new Z(.57,.28,.56),new Z(.44,.98,.42)];!function(e){e[e.NONE=0]="NONE",e[e.TRIANGLES=1]="TRIANGLES",e[e.VERTICES=2]="VERTICES",e[e.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",e[e.UV0=4]="UV0",e[e.UV1=5]="UV1",e[e.VERTEXCOLORS=6]="VERTEXCOLORS",e[e.MATERIALIDS=7]="MATERIALIDS"}(eE||(eE={}));var rE=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.DBG_MODE=eE.NONE,t.DBG_MULTIPLY=!0,t.DBG_ENABLED=!0,t}return m(t,e),t}(Gs),nE=function(e){function t(i,r){void 0===r&&(r={});var n,o,a,s,l,c,u,h,d,p,f,_,m,g=this,v=new rE;return v.DBG_MODE=null!==(n=r.mode)&&void 0!==n?n:v.DBG_MODE,v.DBG_MULTIPLY=null!==(o=r.multiply)&&void 0!==o?o:v.DBG_MULTIPLY,(g=e.call(this,i,"MeshDebug",200,v,!0,!0)||this)._mode=v.DBG_MODE,g._multiply=v.DBG_MULTIPLY,g.shadedDiffuseColor=null!==(a=r.shadedDiffuseColor)&&void 0!==a?a:new Z(1,1,1),g.shadedSpecularColor=null!==(s=r.shadedSpecularColor)&&void 0!==s?s:new Z(.8,.8,.8),g.shadedSpecularPower=null!==(l=r.shadedSpecularPower)&&void 0!==l?l:10,g.wireframeThickness=null!==(c=r.wireframeThickness)&&void 0!==c?c:.7,g.wireframeTrianglesColor=null!==(u=r.wireframeTrianglesColor)&&void 0!==u?u:new Z(0,0,0),g.wireframeVerticesColor=null!==(h=r.wireframeVerticesColor)&&void 0!==h?h:new Z(.8,.8,.8),g.vertexColor=null!==(d=r.vertexColor)&&void 0!==d?d:new Z(0,0,0),g.vertexRadius=null!==(p=r.vertexRadius)&&void 0!==p?p:1.2,g.uvScale=null!==(f=r.uvScale)&&void 0!==f?f:20,g.uvPrimaryColor=null!==(_=r.uvPrimaryColor)&&void 0!==_?_:new Z(1,1,1),g.uvSecondaryColor=null!==(m=r.uvSecondaryColor)&&void 0!==m?m:new Z(.5,.5,.5),g._materialColor=t.MaterialColors[t._PluginCount++%t.MaterialColors.length],g.isEnabled=!0,g}return m(t,e),t.prototype._markAllDefinesAsDirty=function(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()},t.prototype.getClassName=function(){return"MeshDebugPluginMaterial"},Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){if(this._isEnabled!==e){if(!this._material.getScene().getEngine().isWebGPU&&1==this._material.getScene().getEngine().version)return ae.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),void(this._isEnabled=!1);this._isEnabled=e,this._markAllDefinesAsDirty()}},enumerable:!1,configurable:!0}),t.prototype.prepareDefines=function(e,t,i){this._mode!=eE.VERTICES&&this._mode!=eE.TRIANGLES&&this._mode!=eE.TRIANGLES_VERTICES||i.isVerticesDataPresent("dbg_initialPass")||ae.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.",1),e.DBG_MODE=this._mode,e.DBG_MULTIPLY=this._multiply,e.DBG_ENABLED=this._isEnabled},t.prototype.getAttributes=function(e){e.push("dbg_initialPass")},t.prototype.getUniforms=function(){return{ubo:[{name:"dbg_shadedDiffuseColor",size:3,type:"vec3"},{name:"dbg_shadedSpecularColorPower",size:4,type:"vec4"},{name:"dbg_thicknessRadiusScale",size:3,type:"vec3"},{name:"dbg_wireframeTrianglesColor",size:3,type:"vec3"},{name:"dbg_wireframeVerticesColor",size:3,type:"vec3"},{name:"dbg_vertexColor",size:3,type:"vec3"},{name:"dbg_uvPrimaryColor",size:3,type:"vec3"},{name:"dbg_uvSecondaryColor",size:3,type:"vec3"},{name:"dbg_materialColor",size:3,type:"vec3"}],fragment:"#if defined(DBG_ENABLED)\nuniform vec3 dbg_shadedDiffuseColor;\nuniform vec4 dbg_shadedSpecularColorPower;\nuniform vec3 dbg_thicknessRadiusScale;\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n uniform vec3 dbg_vertexColor;\n#endif\n\n#if DBG_MODE == 1\n uniform vec3 dbg_wireframeTrianglesColor;\n#elif DBG_MODE == 3\n uniform vec3 dbg_wireframeVerticesColor;\n#elif DBG_MODE == 4 || DBG_MODE == 5\n uniform vec3 dbg_uvPrimaryColor;\n uniform vec3 dbg_uvSecondaryColor;\n#elif DBG_MODE == 7\n uniform vec3 dbg_materialColor;\n#endif\n#endif"}},t.prototype.bindForSubMesh=function(e){this._isEnabled&&(e.updateFloat3("dbg_shadedDiffuseColor",this.shadedDiffuseColor.r,this.shadedDiffuseColor.g,this.shadedDiffuseColor.b),e.updateFloat4("dbg_shadedSpecularColorPower",this.shadedSpecularColor.r,this.shadedSpecularColor.g,this.shadedSpecularColor.b,this.shadedSpecularPower),e.updateFloat3("dbg_thicknessRadiusScale",this.wireframeThickness,this.vertexRadius,this.uvScale),e.updateColor3("dbg_wireframeTrianglesColor",this.wireframeTrianglesColor),e.updateColor3("dbg_wireframeVerticesColor",this.wireframeVerticesColor),e.updateColor3("dbg_vertexColor",this.vertexColor),e.updateColor3("dbg_uvPrimaryColor",this.uvPrimaryColor),e.updateColor3("dbg_uvSecondaryColor",this.uvSecondaryColor),e.updateColor3("dbg_materialColor",this._materialColor))},t.prototype.getCustomCode=function(e){return"vertex"===e?{CUSTOM_VERTEX_DEFINITIONS:"#if defined(DBG_ENABLED)\nattribute float dbg_initialPass;\nvarying vec3 dbg_vBarycentric;\nflat varying vec3 dbg_vVertexWorldPos;\nflat varying float dbg_vPass;\n#endif",CUSTOM_VERTEX_MAIN_END:"#if defined(DBG_ENABLED)\nfloat dbg_vertexIndex = mod(float(gl_VertexID), 3.);\nif (dbg_vertexIndex == 0.0) { \n dbg_vBarycentric = vec3(1.,0.,0.); \n}\nelse if (dbg_vertexIndex == 1.0) { \n dbg_vBarycentric = vec3(0.,1.,0.); \n}\nelse { \n dbg_vBarycentric = vec3(0.,0.,1.); \n}\n\ndbg_vVertexWorldPos = vPositionW;\ndbg_vPass = dbg_initialPass;\n#endif"}:{CUSTOM_FRAGMENT_DEFINITIONS:"#if defined(DBG_ENABLED)\nvarying vec3 dbg_vBarycentric;\nflat varying vec3 dbg_vVertexWorldPos;\nflat varying float dbg_vPass;\n\n#if !defined(DBG_MULTIPLY)\n vec3 dbg_applyShading(vec3 color) {\n vec3 N = vNormalW.xyz;\n vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz);\n vec3 H = normalize(L + L);\n float LdotN = clamp(dot(L,N), 0., 1.);\n float HdotN = clamp(dot(H,N), 0., 1.);\n float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w);\n color *= (LdotN / PI);\n color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI);\n return color;\n }\n#endif\n\n#if DBG_MODE == 1 || DBG_MODE == 3\n float dbg_edgeFactor() {\n vec3 d = fwidth(dbg_vBarycentric);\n vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric);\n return min(min(a3.x, a3.y), a3.z);\n }\n#endif\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n float dbg_cornerFactor() {\n vec3 worldPos = vPositionW;\n float dist = length(worldPos - dbg_vVertexWorldPos);\n float camDist = length(worldPos - vEyePosition.xyz);\n float d = sqrt(camDist) * .001;\n return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist);\n }\n#endif\n\n#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2))\n float dbg_checkerboardFactor(vec2 uv) {\n vec2 f = fract(uv * dbg_thicknessRadiusScale.z);\n f -= .5;\n return (f.x * f.y) > 0. ? 1. : 0.;\n }\n#endif\n#endif",CUSTOM_FRAGMENT_MAIN_END:"#if defined(DBG_ENABLED)\nvec3 dbg_color = vec3(1.);\n#if DBG_MODE == 1\n dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor());\n#elif DBG_MODE == 2 || DBG_MODE == 3\n float dbg_cornerFactor = dbg_cornerFactor();\n if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard;\n dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor);\n #if DBG_MODE == 3\n dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor());\n #endif\n#elif DBG_MODE == 4 && defined(MAINUV1)\n dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1));\n#elif DBG_MODE == 5 && defined(MAINUV2)\n dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2));\n#elif DBG_MODE == 6 && defined(VERTEXCOLOR)\n dbg_color = vColor.rgb;\n#elif DBG_MODE == 7\n dbg_color = dbg_materialColor;\n#endif\n\n#if defined(DBG_MULTIPLY)\n gl_FragColor *= vec4(dbg_color, 1.);\n#else\n #if DBG_MODE != 6\n gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.);\n #else\n gl_FragColor = vec4(dbg_color, 1.);\n #endif\n#endif\n#endif"}},t.Reset=function(){this._PluginCount=0,this.MaterialColors=iE},t.PrepareMeshForTrianglesAndVerticesMode=function(e,t){void 0===t&&(t=!1);var i=function(){};if(0==e.getTotalIndices())return i;if(t){for(var r=e.getVerticesDataKinds(),n=e.getIndices(),o={},a=0,s=r;a<s.length;a++){var l=s[a];o[l]=e.getVerticesData(l)}i=function(){e.setIndices(n);for(var t=0,i=r;t<i.length;t++){var a=i[t],s=e.getVertexBuffer(a).getStrideSize();e.setVerticesData(a,o[a],void 0,s)}e.removeVerticesData("dbg_initialPass")}}for(var c=Array.from(e.getIndices()),u=[],h=0;h<c.length;h+=3)u.push(c[h+1],c[h+2],c[h+0]);e.setIndices(c.concat(u)),e.convertToUnIndexedMesh(),e.isUnIndexed=!1;var d=[];for(h=(c=Array.from(e.getIndices())).length/2;h<c.length;h+=3)d.push(c[h+1],c[h+2],c[h+0]);e.setIndices(c.concat(d));var p=e.getTotalVertices(),f=p/2,_=new Array(p).fill(1,0,f).fill(0,f,p);return e.setVerticesData("dbg_initialPass",_,!1,1),i},t._PluginCount=0,t.MaterialColors=iE,v([Oe()],t.prototype,"_materialColor",void 0),v([Ie()],t.prototype,"_isEnabled",void 0),v([Ie(),Pe("_markAllDefinesAsDirty")],t.prototype,"mode",void 0),v([Ie(),Pe("_markAllDefinesAsDirty")],t.prototype,"multiply",void 0),v([Oe()],t.prototype,"shadedDiffuseColor",void 0),v([Oe()],t.prototype,"shadedSpecularColor",void 0),v([Ie()],t.prototype,"shadedSpecularPower",void 0),v([Ie()],t.prototype,"wireframeThickness",void 0),v([Oe()],t.prototype,"wireframeTrianglesColor",void 0),v([Oe()],t.prototype,"wireframeVerticesColor",void 0),v([Oe()],t.prototype,"vertexColor",void 0),v([Ie()],t.prototype,"vertexRadius",void 0),v([Ie()],t.prototype,"uvScale",void 0),v([Oe()],t.prototype,"uvPrimaryColor",void 0),v([Oe()],t.prototype,"uvSecondaryColor",void 0),t}(Nu);a("BABYLON.MeshDebugPluginMaterial",nE);li.ShadersStore.gaussianSplattingPixelShader="#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvarying vec4 vColor;varying vec2 vPosition;void main () { \n#include<clipPlaneFragment>\nfloat A=-dot(vPosition,vPosition);if (A<-4.0) discard;float B=exp(A)*vColor.a;\n#include<logDepthFragment>\nvec3 color=vColor.rgb;\n#ifdef FOG\n#include<fogFragment>\n#endif\ngl_FragColor=vec4(color,B);}\n";li.IncludesShadersStore.gaussianSplattingVertexDeclaration="uniform mat4 world;uniform mat4 view;uniform mat4 projection;\n";li.IncludesShadersStore.gaussianSplattingUboDeclaration="#include<sceneUboDeclaration>\n#include<meshUboDeclaration>\n";li.ShadersStore.gaussianSplattingVertexShader="#include<__decl__gaussianSplattingVertex>\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<logDepthDeclaration>\nattribute vec2 position;attribute float splatIndex;uniform vec2 viewport;uniform vec2 dataTextureSize;uniform vec2 focal;uniform sampler2D covariancesATexture;uniform sampler2D covariancesBTexture;uniform sampler2D centersTexture;uniform sampler2D colorsTexture;varying vec4 vColor;varying vec2 vPosition;\n#if !defined(WEBGL2) && !defined(WEBGPU) && !defined(NATIVE)\nmat3 transpose(mat3 matrix) {return mat3(matrix[0][0],matrix[1][0],matrix[2][0],\nmatrix[0][1],matrix[1][1],matrix[2][1],\nmatrix[0][2],matrix[1][2],matrix[2][2]);}\n#endif\nvec2 getDataUV(float index,vec2 textureSize) {float y=floor(index/textureSize.x);float x=index-y*textureSize.x;return vec2((x+0.5)/textureSize.x,(y+0.5)/textureSize.y);}\nvoid main () {vec2 splatUV=getDataUV(splatIndex,dataTextureSize);vec3 center=texture2D(centersTexture,splatUV).xyz;vec4 color=texture2D(colorsTexture,splatUV);vec3 covA=texture2D(covariancesATexture,splatUV).xyz;vec3 covB=texture2D(covariancesBTexture,splatUV).xyz;vec4 worldPos=world*vec4(center,1.0);mat4 modelView=view*world;vec4 camspace=view*worldPos;vec4 pos2d=projection*camspace;float bounds=1.2*pos2d.w;if (pos2d.z<-pos2d.w || pos2d.x<-bounds || pos2d.x>bounds\n|| pos2d.y<-bounds || pos2d.y>bounds) {gl_Position=vec4(0.0,0.0,2.0,1.0);return;}\nmat3 Vrk=mat3(\ncovA.x,covA.y,covA.z,\ncovA.y,covB.x,covB.y,\ncovA.z,covB.y,covB.z\n);mat3 J=mat3(\nfocal.x/camspace.z,0.,-(focal.x*camspace.x)/(camspace.z*camspace.z),\n0.,focal.y/camspace.z,-(focal.y*camspace.y)/(camspace.z*camspace.z),\n0.,0.,0.\n);mat3 invy=mat3(1,0,0,0,-1,0,0,0,1);mat3 T=invy*transpose(mat3(modelView))*J;mat3 cov2d=transpose(T)*Vrk*T;float mid=(cov2d[0][0]+cov2d[1][1])/2.0;float radius=length(vec2((cov2d[0][0]-cov2d[1][1])/2.0,cov2d[0][1]));float lambda1=mid+radius,lambda2=mid-radius;if (lambda2<0.0) return;vec2 diagonalVector=normalize(vec2(cov2d[0][1],lambda1-cov2d[0][0]));vec2 majorAxis=min(sqrt(2.0*lambda1),1024.0)*diagonalVector;vec2 minorAxis=min(sqrt(2.0*lambda2),1024.0)*vec2(diagonalVector.y,-diagonalVector.x);vColor=color;vPosition=position;vec2 vCenter=vec2(pos2d);gl_Position=vec4(\nvCenter \n+ (position.x*majorAxis*1./viewport \n+ position.y*minorAxis*1./viewport)*pos2d.w,pos2d.zw);\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<logDepthVertex>\n}\n";var oE=function(e){function t(){var t=e.call(this)||this;return t.FOG=!1,t.THIN_INSTANCES=!0,t.LOGARITHMICDEPTH=!1,t.CLIPPLANE=!1,t.CLIPPLANE2=!1,t.CLIPPLANE3=!1,t.CLIPPLANE4=!1,t.CLIPPLANE5=!1,t.CLIPPLANE6=!1,t.rebuild(),t}return m(t,e),t}(Gs),aE=function(e){function t(t,i){var r=e.call(this,t,i)||this;return r.backFaceCulling=!1,r}return m(t,e),Object.defineProperty(t.prototype,"hasRenderTargetTextures",{get:function(){return!1},enumerable:!1,configurable:!0}),t.prototype.needAlphaTesting=function(){return!1},t.prototype.needAlphaBlending=function(){return!0},t.prototype.isReadyForSubMesh=function(e,t){var i=!0,r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new oE);var n=this.getScene(),o=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;var a=n.getEngine();if(da(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,!1,o),_a(n,a,this,o,i,null,!0),ya(e,o,!1,!1),o.isDirty){o.markAsProcessed(),n.resetCachedMaterial();var s=[Nr.PositionKind,"splatIndex"];ca(s,o);var l=["world","view","projection","vFogInfos","vFogColor","logarithmicDepthConstant","viewport","dataTextureSize","focal"],c=["covariancesATexture","covariancesBTexture","centersTexture","colorsTexture"],u=["Scene","Mesh"];Aa({uniformsNames:l,uniformBuffersNames:u,samplers:c,defines:o}),Go(l);var h=o.toString(),d=n.getEngine().createEffect("gaussianSplatting",{attributes:s,uniformsNames:l,uniformBuffersNames:u,samplers:c,defines:h,onCompiled:this.onCompiled,onError:this.onError},a);t.setEffect(d,o,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(o._renderId=n.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=i,0))},t.prototype.bindForSubMesh=function(e,t,i){var r=this.getScene(),n=i.materialDefines;if(n){var o=i.effect;if(o){if(this._activeEffect=o,t.getMeshUniformBuffer().bindToEffect(o,"Mesh"),t.transferToEffect(e),this._mustRebind(r,o,i,t.visibility)){this.bindView(o),this.bindViewProjection(o);var a=r.getEngine(),s=this.getScene().activeCamera,l=a.getRenderWidth(),c=a.getRenderHeight();this._activeEffect.setFloat2("viewport",l,c);var u=1e3;s&&(u=s.fovMode==$n.FOVMODE_VERTICAL_FIXED?c/2/Math.tan(s.fov/2):l/2/Math.tan(s.fov/2)),this._activeEffect.setFloat2("focal",u,u);var h=t;if(h.covariancesATexture){var d=h.covariancesATexture.getSize();o.setFloat2("dataTextureSize",d.width,d.height),o.setTexture("covariancesATexture",h.covariancesATexture),o.setTexture("covariancesBTexture",h.covariancesBTexture),o.setTexture("centersTexture",h.centersTexture),o.setTexture("colorsTexture",h.colorsTexture)}Ho(o,this,r)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);Qo(r,t,o),this.useLogarithmicDepth&&Ko(n,o,r),this._afterBind(t,this._activeEffect,i)}}},t.prototype.clone=function(e){var i=this;return Ke.Clone((function(){return new t(e,i.getScene())}),this)},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.customType="BABYLON.GaussianSplattingMaterial",t},t.prototype.getClassName=function(){return"GaussianSplattingMaterial"},t.Parse=function(e,i,r){return Ke.Parse((function(){return new t(e.name,i)}),e,i,r)},t}(ws);a("BABYLON.GaussianSplattingMaterial",aE),Object.defineProperty(Uu.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new zT(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(ig.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new zT(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(Uo.prototype,"decalMap",{get:function(){return this._decalMap},set:function(e){this._decalMap=e},enumerable:!0,configurable:!0});var sE=function(){function e(e,t){this.radius=e,this.theta=t,this.radius=e,this.theta=t}return e.prototype.getClassName=function(){return"Polar"},e.prototype.toString=function(){return JSON.stringify(this)},e.prototype.asArray=function(){return[this.radius,this.theta]},e.prototype.addToRef=function(e,t){return t.radius=this.radius+e.radius,t.theta=this.theta+e.theta,t},e.prototype.add=function(t){var i=new e(0,0);return this.addToRef(t,i),i},e.prototype.addInPlace=function(e){return this.addToRef(e,this),this},e.prototype.addInPlaceFromFloats=function(e,t){return this.radius+=e,this.theta+=t,this},e.prototype.subtractToRef=function(e,t){return t.radius=this.radius-e.radius,t.theta=this.theta-e.theta,t},e.prototype.subtract=function(t){var i=new e(0,0);return this.subtractToRef(t,i),i},e.prototype.subtractInPlace=function(e){return this.subtractToRef(e,this),this},e.prototype.subtractFromFloatsToRef=function(e,t,i){return i.radius=this.radius-e,i.theta=this.theta-t,i},e.prototype.subtractFromFloats=function(t,i){var r=new e(0,0);return this.subtractFromFloatsToRef(t,i,r),r},e.prototype.multiplyToRef=function(e,t){return t.radius=this.radius*e.radius,t.theta=this.theta*e.theta,t},e.prototype.multiply=function(t){var i=new e(0,0);return this.multiplyToRef(t,i),i},e.prototype.multiplyInPlace=function(e){return this.multiplyToRef(e,this),this},e.prototype.divideToRef=function(e,t){return t.radius=this.radius/e.radius,t.theta=this.theta/e.theta,t},e.prototype.divide=function(t){var i=new e(0,0);return this.divideToRef(t,i),i},e.prototype.divideInPlace=function(e){return this.divideToRef(e,this),this},e.prototype.clone=function(){return new e(this.radius,this.theta)},e.prototype.copyFrom=function(e){return this.radius=e.radius,this.theta=e.theta,this},e.prototype.copyFromFloats=function(e,t){return this.radius=e,this.theta=t,this},e.prototype.scaleToRef=function(e,t){return t.radius=this.radius*e,t.theta=this.theta*e,t},e.prototype.scale=function(t){var i=new e(0,0);return this.scaleToRef(t,i),i},e.prototype.scaleInPlace=function(e){return this.scaleToRef(e,this),this},e.prototype.set=function(e,t){return this.radius=e,this.theta=t,this},e.prototype.setAll=function(e){return this.set(e,e),this},e.prototype.toVector2ToRef=function(e){var t=this.radius*Math.cos(this.theta),i=this.radius*Math.sin(this.theta);return e.set(t,i),e},e.prototype.toVector2=function(){var e=new U(0,0);return this.toVector2ToRef(e)},e.FromVector2ToRef=function(e,t){var i=Math.sign(e.y)*Math.acos(e.x/e.length());return t.radius=e.length(),t.theta=i,t},e.FromVector2=function(t){var i=new e(0,0);return e.FromVector2ToRef(t,i),i},e.FromArray=function(t){return new e(t[0],t[1])},e}(),lE=function(){function e(e,t,i){this.radius=e,this.theta=t,this.phi=i,this.radius=e,this.theta=t,this.phi=i}return e.prototype.getClassName=function(){return"Spherical"},e.prototype.toString=function(){return JSON.stringify(this)},e.prototype.asArray=function(){return[this.radius,this.theta,this.phi]},e.prototype.addToRef=function(e,t){return t.radius=this.radius+e.radius,t.theta=this.theta+e.theta,t.phi=this.phi+e.phi,t},e.prototype.add=function(t){var i=new e(0,0,0);return this.addToRef(t,i),i},e.prototype.addInPlace=function(e){return this.addToRef(e,this),this},e.prototype.addInPlaceFromFloats=function(e,t,i){return this.radius+=e,this.theta+=t,this.phi+=i,this},e.prototype.subtractToRef=function(e,t){return t.radius=this.radius-e.radius,t.theta=this.theta-e.theta,t.phi=this.phi-e.phi,t},e.prototype.subtract=function(t){var i=new e(0,0,0);return this.subtractToRef(t,i),i},e.prototype.subtractInPlace=function(e){return this.subtractToRef(e,this),this},e.prototype.subtractFromFloatsToRef=function(e,t,i,r){return r.radius=this.radius-e,r.theta=this.theta-t,r.phi=this.phi-i,r},e.prototype.subtractFromFloats=function(t,i,r){var n=new e(0,0,0);return this.subtractFromFloatsToRef(t,i,r,n),n},e.prototype.multiplyToRef=function(e,t){return t.radius=this.radius*e.radius,t.theta=this.theta*e.theta,t.phi=this.phi*e.phi,t},e.prototype.multiply=function(t){var i=new e(0,0,0);return this.multiplyToRef(t,i),i},e.prototype.multiplyInPlace=function(e){return this.multiplyToRef(e,this),this},e.prototype.divideToRef=function(e,t){return t.radius=this.radius/e.radius,t.theta=this.theta/e.theta,t.phi=this.phi/e.phi,t},e.prototype.divide=function(t){var i=new e(0,0,0);return this.divideToRef(t,i),i},e.prototype.divideInPlace=function(e){return this.divideToRef(e,this),this},e.prototype.clone=function(){return new e(this.radius,this.theta,this.phi)},e.prototype.copyFrom=function(e){return this.radius=e.radius,this.theta=e.theta,this.phi=e.phi,this},e.prototype.copyFromFloats=function(e,t,i){return this.radius=e,this.theta=t,this.phi=i,this},e.prototype.scaleToRef=function(e,t){return t.radius=this.radius*e,t.theta=this.theta*e,t.phi=this.phi*e,t},e.prototype.scale=function(t){var i=new e(0,0,0);return this.scaleToRef(t,i),i},e.prototype.scaleInPlace=function(e){return this.scaleToRef(e,this),this},e.prototype.set=function(e,t,i){return this.radius=e,this.theta=t,this.phi=i,this},e.prototype.setAll=function(e){return this.set(e,e,e),this},e.prototype.toVector3ToRef=function(e){var t=this.radius*Math.sin(this.theta)*Math.cos(this.phi),i=this.radius*Math.cos(this.theta),r=this.radius*Math.sin(this.theta)*Math.sin(this.phi);return e.set(t,i,r),e},e.prototype.toVector3=function(){var e=new V(0,0,0);return this.toVector3ToRef(e)},e.FromVector3ToRef=function(e,t){return t.radius=e.length(),t.theta=Math.acos(e.y/t.radius),t.phi=Math.atan2(e.z,e.x),t},e.FromVector3=function(t){var i=new e(0,0,0);return e.FromVector3ToRef(t,i),i},e.FromArray=function(t){return new e(t[0],t[1],t[2])},e}(),cE=function(){function e(e,t,i,r,n){void 0===t&&(t=2),void 0===i&&(i=3),void 0===r&&(r=1),void 0===n&&(n=1),this._curIndex=0,this._sequence=[],this._numSamples=0,this.x=0,this.y=0,this._width=r,this._height=n,this._baseX=t,this._baseY=i,this._generateSequence(e),this.next()}return e.prototype.regenerate=function(e){this._generateSequence(e),this.next()},e.prototype.setDimensions=function(e,t){this._width=e,this._height=t},e.prototype.next=function(){this.x=this._sequence[this._curIndex]/this._width,this.y=this._sequence[this._curIndex+1]/this._height,this._curIndex+=2,this._curIndex>=2*this._numSamples&&(this._curIndex=0)},e.prototype._generateSequence=function(e){this._sequence=[],this._curIndex=0,this._numSamples=e;for(var t=1;t<=e;++t)this._sequence.push(this._halton(t,this._baseX)-.5,this._halton(t,this._baseY)-.5)},e.prototype._halton=function(e,t){for(var i=1,r=0;e>0;)r+=(i/=t)*(e%t),e=~~(e/t);return r},e}();function uE(e,t){return"{X: ".concat(e.x.toFixed(t)," Y: ").concat(e.y.toFixed(t),"}")}function hE(e,t){return"{X: ".concat(e._x.toFixed(t)," Y: ").concat(e._y.toFixed(t)," Z: ").concat(e._z.toFixed(t),"}")}function dE(e,t){return"{X: ".concat(e.x.toFixed(t)," Y: ").concat(e.y.toFixed(t)," Z: ").concat(e.z.toFixed(t)," W: ").concat(e.w.toFixed(t),"}")}function pE(e,t,i,r,n){var o=null,a=null,s=null;try{var l;o=new e.Decoder,(a=new e.DecoderBuffer).Init(t,t.byteLength);var c=o.GetEncodedGeometryType(a);switch(c){case e.TRIANGULAR_MESH:var u=new e.Mesh;if(!(l=o.DecodeBufferToMesh(a,u)).ok()||0===u.ptr)throw new Error(l.error_msg());var h=3*u.num_faces(),d=4*h,p=e._malloc(d);try{o.GetTrianglesUInt32Array(u,d,p);var f=new Uint32Array(h);f.set(new Uint32Array(e.HEAPF32.buffer,p,h)),r(f)}finally{e._free(p)}s=u;break;case e.POINT_CLOUD:var _=new e.PointCloud;if(!(l=o.DecodeBufferToPointCloud(a,_)).ok()||!_.ptr)throw new Error(l.error_msg());s=_;break;default:throw new Error("Invalid geometry type ".concat(c))}var m=s.num_points(),g=function(t,i,r,o){var a,s=o.data_type(),l=o.num_components(),c=o.normalized(),u=o.byte_stride(),h=o.byte_offset(),d=((a={})[e.DT_FLOAT32]={typedArrayConstructor:Float32Array,heap:e.HEAPF32},a[e.DT_INT8]={typedArrayConstructor:Int8Array,heap:e.HEAP8},a[e.DT_INT16]={typedArrayConstructor:Int16Array,heap:e.HEAP16},a[e.DT_INT32]={typedArrayConstructor:Int32Array,heap:e.HEAP32},a[e.DT_UINT8]={typedArrayConstructor:Uint8Array,heap:e.HEAPU8},a[e.DT_UINT16]={typedArrayConstructor:Uint16Array,heap:e.HEAPU16},a[e.DT_UINT32]={typedArrayConstructor:Uint32Array,heap:e.HEAPU32},a)[s];if(!d)throw new Error("Invalid data type ".concat(s));var p=m*l,f=p*d.typedArrayConstructor.BYTES_PER_ELEMENT,_=e._malloc(f);try{t.GetAttributeDataArrayForAllPoints(i,o,s,f,_);var g=new d.typedArrayConstructor(d.heap.buffer,_,p);n(r,g.slice(),l,h,u,c)}finally{e._free(_)}};if(i)for(var v in i){var y=i[v],b=o.GetAttributeByUniqueId(s,y);g(o,s,v,b)}else{var T={position:e.POSITION,normal:e.NORMAL,color:e.COLOR,uv:e.TEX_COORD};for(var v in T)-1!==(y=o.GetAttributeId(s,T[v]))&&(b=o.GetAttribute(s,y),g(o,s,v,b))}return m}finally{s&&e.destroy(s),a&&e.destroy(a),o&&e.destroy(o)}}function fE(){var e;onmessage=function(t){var i=t.data;switch(i.id){case"init":var r=i.decoder;r.url&&importScripts(r.url);var n=r.wasmBinary?{wasmBinary:r.wasmBinary}:{};e=DracoDecoderModule(n),postMessage({id:"initDone"});break;case"decodeMesh":if(!e)throw new Error("Draco decoder module is not available");e.then((function(e){var t=pE(e,i.dataView,i.attributes,(function(e){postMessage({id:"indices",data:e},[e.buffer])}),(function(e,t,i,r,n,o){postMessage({id:"attribute",kind:e,data:t,size:i,byteOffset:r,byteStride:n,normalized:o},[t.buffer])}));postMessage({id:"decodeMeshDone",totalVertices:t})}))}}}var _E=function(){function e(t){void 0===t&&(t=e.DefaultNumWorkers);var i=this,r=e.Configuration.decoder;if(r.workerPool||"object"==typeof t&&t.workerPool)this._workerPoolPromise=Promise.resolve(r.workerPool||t.workerPool);else{var n=r.wasmBinary||"object"==typeof t&&t.wasmBinary,o="number"==typeof t?t:t.numWorkers,a=o&&"function"==typeof Worker&&"function"==typeof URL,s=a||!a&&!r.jsModule,l=r.wasmUrl&&r.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:s?rr.GetBabylonScriptURL(r.wasmUrl,!0):"",wasmBinaryPromise:n?Promise.resolve(n):rr.LoadFileAsync(rr.GetBabylonScriptURL(r.wasmBinaryUrl,!0))}:{url:s?rr.GetBabylonScriptURL(r.fallbackUrl):"",wasmBinaryPromise:Promise.resolve(void 0)};a?this._workerPoolPromise=l.wasmBinaryPromise.then((function(e){var t="".concat(pE,"(").concat(fE,")()"),i=URL.createObjectURL(new Blob([t],{type:"application/javascript"}));return new yg(o,(function(){return function(e,t,i){return new Promise((function(r,n){var o=function(t){e.removeEventListener("error",o),e.removeEventListener("message",a),n(t)},a=function(t){"initDone"===t.data.id&&(e.removeEventListener("error",o),e.removeEventListener("message",a),r(e))};if(e.addEventListener("error",o),e.addEventListener("message",a),t){var s=t.slice(0);e.postMessage({id:"init",decoder:{url:i,wasmBinary:s}},[s])}else e.postMessage({id:"init",decoder:{url:i}})}))}(new Worker(i),e,l.url)}))})):this._decoderModulePromise=l.wasmBinaryPromise.then((function(e){return y(i,void 0,void 0,(function(){return b(this,(function(t){switch(t.label){case 0:if("undefined"!=typeof DracoDecoderModule)return[3,2];if(r.jsModule)return[3,2];if(!l.url)throw new Error("Draco decoder module is not available");return[4,rr.LoadBabylonScriptAsync(l.url)];case 1:t.sent(),t.label=2;case 2:return[4,(i=e,n=r.jsModule,new Promise((function(e){(n||DracoDecoderModule)({wasmBinary:i}).then((function(t){e({module:t})}))})))];case 3:return[2,t.sent()]}var i,n}))}))}))}}return Object.defineProperty(e,"DecoderAvailable",{get:function(){var t=e.Configuration.decoder;return!!(t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly||t.fallbackUrl)},enumerable:!1,configurable:!0}),e.GetDefaultNumWorkers=function(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1},Object.defineProperty(e,"Default",{get:function(){return e._Default||(e._Default=new e),e._Default},enumerable:!1,configurable:!0}),e.ResetDefault=function(t){e._Default&&(t||e._Default.dispose(),e._Default=null)},e.prototype.dispose=function(){this._workerPoolPromise&&this._workerPoolPromise.then((function(e){e.dispose()})),delete this._workerPoolPromise,delete this._decoderModulePromise},e.prototype.whenReadyAsync=function(){return y(this,void 0,void 0,(function(){return b(this,(function(e){switch(e.label){case 0:return this._workerPoolPromise?[4,this._workerPoolPromise]:[3,2];case 1:case 3:return e.sent(),[2];case 2:return this._decoderModulePromise?[4,this._decoderModulePromise]:[3,4];case 4:return[2]}}))}))},e.prototype.decodeMeshToMeshDataAsync=function(e,t,i){var r=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength);if(this._workerPoolPromise)return this._workerPoolPromise.then((function(e){return new Promise((function(n,o){e.push((function(e,a){var s=null,l=[],c=function(t){e.removeEventListener("error",c),e.removeEventListener("message",u),o(t),a()},u=function(t){var r,o,h=t.data;switch(h.id){case"decodeMeshDone":e.removeEventListener("error",c),e.removeEventListener("message",u),n({indices:s,attributes:l,totalVertices:h.totalVertices}),a();break;case"indices":s=h.data;break;case"attribute":l.push({kind:h.kind,data:h.data,size:h.size,byteOffset:h.byteOffset,byteStride:h.byteStride,normalized:(r=h.kind,o=h.normalized,i&&void 0!==i[r]?(o!==i[r]&&ae.Warn("Normalized flag from Draco data (".concat(o,") does not match normalized flag from glTF accessor (").concat(i[r],"). Using flag from glTF accessor.")),i[r]):o)})}};e.addEventListener("error",c),e.addEventListener("message",u);var h=r.slice();e.postMessage({id:"decodeMesh",dataView:h,attributes:t},[h.buffer])}))}))}));if(this._decoderModulePromise)return this._decoderModulePromise.then((function(e){var i=null,n=[],o=pE(e.module,r,t,(function(e){i=e}),(function(e,t,i,r,o,a){n.push({kind:e,data:t,size:i,byteOffset:r,byteStride:o,normalized:a})}));return{indices:i,attributes:n,totalVertices:o}}));throw new Error("Draco decoder module is not available")},e.prototype.decodeMeshToGeometryAsync=function(e,t,i,r){return y(this,void 0,void 0,(function(){var n,o,a,s,l;return b(this,(function(c){switch(c.label){case 0:return[4,this.decodeMeshToMeshDataAsync(i,r)];case 1:for(n=c.sent(),o=new vo(e,t),n.indices&&o.setIndices(n.indices),a=0,s=n.attributes;a<s.length;a++)l=s[a],o.setVerticesBuffer(new Nr(t.getEngine(),l.data,l.kind,!1,void 0,l.byteStride,void 0,l.byteOffset,l.size,void 0,l.normalized,!0),n.totalVertices);return[2,o]}}))}))},e.prototype._decodeMeshToGeometryForGltfAsync=function(e,t,i,r,n){return y(this,void 0,void 0,(function(){var o,a,s,l,c;return b(this,(function(u){switch(u.label){case 0:return[4,this.decodeMeshToMeshDataAsync(i,r,n)];case 1:for(o=u.sent(),a=new vo(e,t),o.indices&&a.setIndices(o.indices),s=0,l=o.attributes;s<l.length;s++)c=l[s],a.setVerticesBuffer(new Nr(t.getEngine(),c.data,c.kind,!1,void 0,c.byteStride,void 0,c.byteOffset,c.size,void 0,c.normalized,!0),o.totalVertices);return[2,a]}}))}))},e.prototype.decodeMeshAsync=function(e,t){return y(this,void 0,void 0,(function(){var i,r,n,o,a,s;return b(this,(function(l){switch(l.label){case 0:return[4,this.decodeMeshToMeshDataAsync(e,t)];case 1:for(i=l.sent(),r=new _o,i.indices&&(r.indices=i.indices),n=0,o=i.attributes;n<o.length;n++)a=o[n],s=Nr.GetFloatData(a.data,a.size,Nr.GetDataType(a.data),a.byteOffset,a.byteStride,a.normalized,i.totalVertices),r.set(s,a.kind);return[2,r]}}))}))},e.Configuration={decoder:{wasmUrl:"".concat(rr._DefaultCdnUrl,"/draco_wasm_wrapper_gltf.js"),wasmBinaryUrl:"".concat(rr._DefaultCdnUrl,"/draco_decoder_gltf.wasm"),fallbackUrl:"".concat(rr._DefaultCdnUrl,"/draco_decoder_gltf.js")}},e.DefaultNumWorkers=e.GetDefaultNumWorkers(),e._Default=null,e}(),mE=function(){function e(){var t=e.Configuration.decoder;this._decoderModulePromise=rr.LoadBabylonScriptAsync(t.url).then((function(){return MeshoptDecoder.ready}))}return Object.defineProperty(e,"Default",{get:function(){return e._Default||(e._Default=new e),e._Default},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){delete this._decoderModulePromise},e.prototype.decodeGltfBufferAsync=function(e,t,i,r,n){var o=this;return this._decoderModulePromise.then((function(){return y(o,void 0,void 0,(function(){var o;return b(this,(function(a){switch(a.label){case 0:return MeshoptDecoder.useWorkers(1),[4,MeshoptDecoder.decodeGltfBufferAsync(t,i,e,r,n)];case 1:return o=a.sent(),MeshoptDecoder.useWorkers(0),[2,o]}}))}))}))},e.Configuration={decoder:{url:"".concat(rr._DefaultCdnUrl,"/meshopt_decoder.js")}},e._Default=null,e}(),gE=0,vE=function(){function e(e,t,i,r){this.pos=e,this.normal=t,this.uv=i,this.vertColor=r}return e.prototype.clone=function(){var t,i;return new e(this.pos.clone(),this.normal.clone(),null===(t=this.uv)||void 0===t?void 0:t.clone(),null===(i=this.vertColor)||void 0===i?void 0:i.clone())},e.prototype.flip=function(){this.normal=this.normal.scale(-1)},e.prototype.interpolate=function(t,i){return new e(V.Lerp(this.pos,t.pos,i),V.Lerp(this.normal,t.normal,i),this.uv&&t.uv?U.Lerp(this.uv,t.uv,i):void 0,this.vertColor&&t.vertColor?J.Lerp(this.vertColor,t.vertColor,i):void 0)},e}(),yE=function(){function e(e,t){this.normal=e,this.w=t}return e.FromPoints=function(t,i,r){var n=r.subtract(t),o=i.subtract(t);if(0===n.lengthSquared()||0===o.lengthSquared())return null;var a=V.Normalize(V.Cross(n,o));return new e(a,V.Dot(a,t))},e.prototype.clone=function(){return new e(this.normal.clone(),this.w)},e.prototype.flip=function(){this.normal.scaleInPlace(-1),this.w=-this.w},e.prototype.splitPolygon=function(t,i,r,n,o){var a,s,l=0,c=[];for(a=0;a<t.vertices.length;a++){var u=(s=V.Dot(this.normal,t.vertices[a].pos)-this.w)<-e.EPSILON?2:s>e.EPSILON?1:0;l|=u,c.push(u)}switch(l){case 0:(V.Dot(this.normal,t.plane.normal)>0?i:r).push(t);break;case 1:n.push(t);break;case 2:o.push(t);break;case 3:var h=[],d=[];for(a=0;a<t.vertices.length;a++){var p=(a+1)%t.vertices.length,f=c[a],_=c[p],m=t.vertices[a],g=t.vertices[p];if(2!==f&&h.push(m),1!==f&&d.push(2!==f?m.clone():m),3==(f|_)){s=(this.w-V.Dot(this.normal,m.pos))/V.Dot(this.normal,g.pos.subtract(m.pos));var v=m.interpolate(g,s);h.push(v),d.push(v.clone())}}var y=void 0;h.length>=3&&(y=new bE(h,t.shared)).plane&&n.push(y),d.length>=3&&(y=new bE(d,t.shared)).plane&&o.push(y)}},e.EPSILON=1e-5,e}(),bE=function(){function e(e,t){this.vertices=e,this.shared=t,this.plane=yE.FromPoints(e[0].pos,e[1].pos,e[2].pos)}return e.prototype.clone=function(){return new e(this.vertices.map((function(e){return e.clone()})),this.shared)},e.prototype.flip=function(){this.vertices.reverse().map((function(e){e.flip()})),this.plane.flip()},e}(),TE=function(){function e(e){this._plane=null,this._front=null,this._back=null,this._polygons=new Array,e&&this.build(e)}return e.prototype.clone=function(){var t=new e;return t._plane=this._plane&&this._plane.clone(),t._front=this._front&&this._front.clone(),t._back=this._back&&this._back.clone(),t._polygons=this._polygons.map((function(e){return e.clone()})),t},e.prototype.invert=function(){for(var e=0;e<this._polygons.length;e++)this._polygons[e].flip();this._plane&&this._plane.flip(),this._front&&this._front.invert(),this._back&&this._back.invert();var t=this._front;this._front=this._back,this._back=t},e.prototype.clipPolygons=function(e){if(!this._plane)return e.slice();for(var t=[],i=[],r=0;r<e.length;r++)this._plane.splitPolygon(e[r],t,i,t,i);return this._front&&(t=this._front.clipPolygons(t)),i=this._back?this._back.clipPolygons(i):[],t.concat(i)},e.prototype.clipTo=function(e){this._polygons=e.clipPolygons(this._polygons),this._front&&this._front.clipTo(e),this._back&&this._back.clipTo(e)},e.prototype.allPolygons=function(){var e=this._polygons.slice();return this._front&&(e=e.concat(this._front.allPolygons())),this._back&&(e=e.concat(this._back.allPolygons())),e},e.prototype.build=function(t){if(t.length){this._plane||(this._plane=t[0].plane.clone());for(var i=[],r=[],n=0;n<t.length;n++)this._plane.splitPolygon(t[n],this._polygons,this._polygons,i,r);i.length&&(this._front||(this._front=new e),this._front.build(i)),r.length&&(this._back||(this._back=new e),this._back.build(r))}},e}(),EE=function(){function e(){this._polygons=new Array}return e.FromVertexData=function(t){var i,r,n,o=[],a=t.indices,s=t.positions,l=t.normals,c=t.uvs,u=t.colors;if(!a||!s)throw"BABYLON.CSG: VertexData must at least contain positions and indices";for(var h=0;h<a.length;h+=3){n=[];for(var d=0;d<3;d++){var p=a[h+d],f=l?V.FromArray(l,3*p):V.Zero(),_=c?U.FromArray(c,2*p):void 0,m=u?J.FromArray(u,4*p):void 0,g=V.FromArray(s,3*p);i=new vE(g,f,_,m),n.push(i)}(r=new bE(n,{subMeshId:0,meshId:gE,materialIndex:0})).plane&&o.push(r)}var v=e._FromPolygons(o);return v.matrix=z.Identity(),v.position=V.Zero(),v.rotation=V.Zero(),v.scaling=V.One(),v.rotationQuaternion=G.Identity(),gE++,v},e.FromMesh=function(t,i){void 0===i&&(i=!1);var r,n,o,a,s,l,c,h,d,p=void 0,f=void 0,_=[],m=null,g=!1;if(!(t instanceof Fa))throw"BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh";t.computeWorldMatrix(!0),l=t.getWorldMatrix(),c=t.position.clone(),h=t.rotation.clone(),t.rotationQuaternion&&(m=t.rotationQuaternion.clone()),d=t.scaling.clone(),t.material&&i&&(g=t.material.sideOrientation===u.MATERIAL_ClockWiseSideOrientation);for(var v=t.getIndices(),y=t.getVerticesData(Nr.PositionKind),b=t.getVerticesData(Nr.NormalKind),T=t.getVerticesData(Nr.UVKind),E=t.getVerticesData(Nr.ColorKind),S=t.subMeshes,x=0,A=S.length;x<A;x++)for(var C=S[x].indexStart,R=S[x].indexCount+S[x].indexStart;C<R;C+=3){s=[];for(var P=0;P<3;P++){var I=0===P?C+P:g?C+3-P:C+P,M=new V(b[3*v[I]],b[3*v[I]+1],b[3*v[I]+2]);T&&(p=new U(T[2*v[I]],T[2*v[I]+1])),E&&(f=new J(E[4*v[I]],E[4*v[I]+1],E[4*v[I]+2],E[4*v[I]+3]));var O=new V(y[3*v[I]],y[3*v[I]+1],y[3*v[I]+2]);o=V.TransformCoordinates(O,l),n=V.TransformNormal(M,l),r=new vE(o,n,p,f),s.push(r)}(a=new bE(s,{subMeshId:x,meshId:gE,materialIndex:S[x].materialIndex})).plane&&_.push(a)}var D=e._FromPolygons(_);return D.matrix=i?z.Identity():l,D.position=i?V.Zero():c,D.rotation=i?V.Zero():h,D.scaling=i?V.One():d,D.rotationQuaternion=i&&m?G.Identity():m,gE++,D},e._FromPolygons=function(t){var i=new e;return i._polygons=t,i},e.prototype.clone=function(){var t=new e;return t._polygons=this._polygons.map((function(e){return e.clone()})),t.copyTransformAttributes(this),t},e.prototype.union=function(t){var i=new TE(this.clone()._polygons),r=new TE(t.clone()._polygons);return i.clipTo(r),r.clipTo(i),r.invert(),r.clipTo(i),r.invert(),i.build(r.allPolygons()),e._FromPolygons(i.allPolygons()).copyTransformAttributes(this)},e.prototype.unionInPlace=function(e){var t=new TE(this._polygons),i=new TE(e._polygons);t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),this._polygons=t.allPolygons()},e.prototype.subtract=function(t){var i=new TE(this.clone()._polygons),r=new TE(t.clone()._polygons);return i.invert(),i.clipTo(r),r.clipTo(i),r.invert(),r.clipTo(i),r.invert(),i.build(r.allPolygons()),i.invert(),e._FromPolygons(i.allPolygons()).copyTransformAttributes(this)},e.prototype.subtractInPlace=function(e){var t=new TE(this._polygons),i=new TE(e._polygons);t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()},e.prototype.intersect=function(t){var i=new TE(this.clone()._polygons),r=new TE(t.clone()._polygons);return i.invert(),r.clipTo(i),r.invert(),i.clipTo(r),r.clipTo(i),i.build(r.allPolygons()),i.invert(),e._FromPolygons(i.allPolygons()).copyTransformAttributes(this)},e.prototype.intersectInPlace=function(e){var t=new TE(this._polygons),i=new TE(e._polygons);t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()},e.prototype.inverse=function(){var e=this.clone();return e.inverseInPlace(),e},e.prototype.inverseInPlace=function(){this._polygons.map((function(e){e.flip()}))},e.prototype.copyTransformAttributes=function(e){return this.matrix=e.matrix,this.position=e.position,this.rotation=e.rotation,this.scaling=e.scaling,this.rotationQuaternion=e.rotationQuaternion,this},e.prototype.toVertexData=function(e,t){void 0===e&&(e=null),void 0===t&&(t=null);var i=this.matrix.clone();i.invert();for(var r,n=this._polygons,o=[],a=[],s=[],l=null,c=null,u=V.Zero(),h=V.Zero(),d=U.Zero(),p=new J(0,0,0,0),f=[0,0,0],_={},m=0,g=n.length;m<g;m++){var v=n[m];e&&e(v);for(var y=2,b=v.vertices.length;y<b;y++){f[0]=0,f[1]=y-1,f[2]=y;for(var T=0;T<3;T++){u.copyFrom(v.vertices[f[T]].pos),h.copyFrom(v.vertices[f[T]].normal),v.vertices[f[T]].uv&&(l||(l=[]),d.copyFrom(v.vertices[f[T]].uv)),v.vertices[f[T]].vertColor&&(c||(c=[]),p.copyFrom(v.vertices[f[T]].vertColor));var E=V.TransformCoordinates(u,i),S=V.TransformNormal(h,i);r=_[E.x+","+E.y+","+E.z];var x=!1;l&&l[2*r]!==d.x&&l[2*r+1]!==d.y&&(x=!0);var A=!1;c&&c[4*r]!==p.r&&c[4*r+1]!==p.g&&c[4*r+2]!==p.b&&c[4*r+3]!==p.a&&(A=!0),(void 0===r||s[3*r]!==S.x||s[3*r+1]!==S.y||s[3*r+2]!==S.z||x||A)&&(o.push(E.x,E.y,E.z),l&&l.push(d.x,d.y),s.push(h.x,h.y,h.z),c&&c.push(p.r,p.g,p.b,p.a),r=_[E.x+","+E.y+","+E.z]=o.length/3-1),a.push(r),t&&t()}}}var C=new _o;return C.positions=o,C.normals=s,l&&(C.uvs=l),c&&(C.colors=c),C.indices=a,C},e.prototype.buildMeshGeometry=function(e,t,i){var r,n=new Fa(e,t),o=this._polygons,a=0,s={};if(i&&o.sort((function(e,t){return e.shared.meshId===t.shared.meshId?e.shared.subMeshId-t.shared.subMeshId:e.shared.meshId-t.shared.meshId})),this.toVertexData((function(e){s[e.shared.meshId]||(s[e.shared.meshId]={}),s[e.shared.meshId][e.shared.subMeshId]||(s[e.shared.meshId][e.shared.subMeshId]={indexStart:1/0,indexEnd:-1/0,materialIndex:e.shared.materialIndex}),r=s[e.shared.meshId][e.shared.subMeshId]}),(function(){r.indexStart=Math.min(a,r.indexStart),r.indexEnd=Math.max(a,r.indexEnd),a++})).applyToMesh(n),i){var l=0,c=void 0;for(var u in n.subMeshes=[],s){for(var h in c=-1,s[u])r=s[u][h],po.CreateFromIndices(r.materialIndex+l,r.indexStart,r.indexEnd-r.indexStart+1,n),c=Math.max(r.materialIndex,c);l+=++c}}return n},e.prototype.toMesh=function(e,t,i,r){void 0===t&&(t=null);var n=this.buildMeshGeometry(e,i,r);return n.material=t,n.position.copyFrom(this.position),n.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(n.rotationQuaternion=this.rotationQuaternion.clone()),n.scaling.copyFrom(this.scaling),n.computeWorldMatrix(!0),n},e}();li.ShadersStore.meshUVSpaceRendererVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC;\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#include<instancesDeclaration>\nvoid main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#include<morphTargetsVertexGlobal>\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW;\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvNormalW=normalize(normWorldSM*normalUpdated);\n#endif\nvec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);vec3 decalTC=(projMatrix*worldPos).xyz;vDecalTC=decalTC.xy;gl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);}";li.ShadersStore.meshUVSpaceRendererPixelShader="precision highp float;varying vec2 vDecalTC;uniform sampler2D textureSampler;void main(void) {if (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {discard;}\ngl_FragColor=texture2D(textureSampler,vDecalTC);}\n";li.ShadersStore.meshUVSpaceRendererMaskerVertexShader="attribute vec2 uv;varying vec2 vUV;void main(void) {gl_Position=vec4(vec2(uv.x,uv.y)*2.0-1.0,0.,1.0);vUV=uv;}";li.ShadersStore.meshUVSpaceRendererMaskerPixelShader="varying vec2 vUV;void main(void) {gl_FragColor=vec4(1.0,1.0,1.0,1.0);}\n";li.ShadersStore.meshUVSpaceRendererFinaliserPixelShader="precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D maskTextureSampler;uniform vec2 textureSize;void main() {vec4 mask=texture2D(maskTextureSampler,vUV).rgba;if (mask.r>0.5) {gl_FragColor=texture2D(textureSampler,vUV);} else {vec2 texelSize=4.0/textureSize;vec2 uv_p01=vUV+vec2(-1.0,0.0)*texelSize;vec2 uv_p21=vUV+vec2(1.0,0.0)*texelSize;vec2 uv_p10=vUV+vec2(0.0,-1.0)*texelSize;vec2 uv_p12=vUV+vec2(0.0,1.0)*texelSize;float mask_p01=texture2D(maskTextureSampler,uv_p01).r;float mask_p21=texture2D(maskTextureSampler,uv_p21).r;float mask_p10=texture2D(maskTextureSampler,uv_p10).r;float mask_p12=texture2D(maskTextureSampler,uv_p12).r;vec4 col=vec4(0.0,0.0,0.0,0.0);float total_weight=0.0;if (mask_p01>0.5) {col+=texture2D(textureSampler,uv_p01);total_weight+=1.0;}\nif (mask_p21>0.5) {col+=texture2D(textureSampler,uv_p21);total_weight+=1.0;}\nif (mask_p10>0.5) {col+=texture2D(textureSampler,uv_p10);total_weight+=1.0;}\nif (mask_p12>0.5) {col+=texture2D(textureSampler,uv_p12);total_weight+=1.0;}\nif (total_weight>0.0) {gl_FragColor=col/total_weight;} else {gl_FragColor=col;}}}\n";li.ShadersStore.meshUVSpaceRendererFinaliserVertexShader="precision highp float;attribute vec3 position;attribute vec2 uv;uniform mat4 worldViewProjection;varying vec2 vUV;void main() {gl_Position=worldViewProjection*vec4(position,1.0);vUV=uv;}\n";var SE=function(){function e(e,t,i){this._textureCreatedInternally=!1,this._configureUserCreatedTexture=!0,this._maskTexture=null,this._finalPostProcess=null,this.clearColor=new J(0,0,0,0),this._mesh=e,this._scene=t,this._options=g({width:1024,height:1024,textureType:u.TEXTURETYPE_UNSIGNED_BYTE,generateMipMaps:!0,optimizeUVAllocation:!0,uvEdgeBlending:!1},i)}return e._GetShader=function(e){if(!e._meshUVSpaceRendererShader){var t=new ld("meshUVSpaceRendererShader",e,{vertex:"meshUVSpaceRenderer",fragment:"meshUVSpaceRenderer"},{attributes:["position","normal","uv"],uniforms:["world","projMatrix"],samplers:["textureSampler"],needAlphaBlending:!0});t.backFaceCulling=!1,t.alphaMode=u.ALPHA_COMBINE,e.onDisposeObservable.add((function(){var t;null===(t=e._meshUVSpaceRendererShader)||void 0===t||t.dispose(),e._meshUVSpaceRendererShader=null})),e._meshUVSpaceRendererShader=t}return e._meshUVSpaceRendererShader},e._GetMaskShader=function(e){if(!e._meshUVSpaceRendererMaskShader){var t=new ld("meshUVSpaceRendererMaskShader",e,{vertex:"meshUVSpaceRendererMasker",fragment:"meshUVSpaceRendererMasker"},{attributes:["position","uv"],uniforms:["worldViewProjection"]});t.backFaceCulling=!1,t.alphaMode=u.ALPHA_COMBINE,e.onDisposeObservable.add((function(){var t;null===(t=e._meshUVSpaceRendererMaskShader)||void 0===t||t.dispose(),e._meshUVSpaceRendererMaskShader=null})),e._meshUVSpaceRendererMaskShader=t}return e._meshUVSpaceRendererMaskShader},e._IsRenderTargetTexture=function(e){return void 0!==e.renderList},e.prototype.isReady=function(){var t,i,r,n;this.texture||this._createDiffuseRTT();var o=e._IsRenderTargetTexture(this.texture)?this.texture.isReadyForRendering():this.texture.isReady(),a=null===(i=null===(t=this._maskTexture)||void 0===t?void 0:t.isReadyForRendering())||void 0===i||i,s=null===(n=null===(r=this._finalPostProcess)||void 0===r?void 0:r.isReady())||void 0===n||n;return o&&a&&s},e.prototype.renderTexture=function(t,i,r,n,o){if(void 0===o&&(o=0),this.texture?this._configureUserCreatedTexture&&this._configureUserCreatedRTT():this._createDiffuseRTT(),e._IsRenderTargetTexture(this.texture)){var a=this._createProjectionMatrix(i,r,n,o),s=e._GetShader(this._scene);s.setTexture("textureSampler",t),s.setMatrix("projMatrix",a),this.texture.render()}},e.prototype.clear=function(){var t,i,r,n;e._IsRenderTargetTexture(this.texture)&&this.texture.renderTarget&&((n=this._scene.getEngine()).bindFramebuffer(this.texture.renderTarget),n.clear(this.clearColor,!0,!0,!0),n.unBindFramebuffer(this.texture.renderTarget)),(null===(t=this._finalPostProcess)||void 0===t?void 0:t.inputTexture)&&((n=this._scene.getEngine()).bindFramebuffer(null===(i=this._finalPostProcess)||void 0===i?void 0:i.inputTexture),n.clear(this.clearColor,!0,!0,!0),n.unBindFramebuffer(null===(r=this._finalPostProcess)||void 0===r?void 0:r.inputTexture))},e.prototype.dispose=function(){var e,t;this._textureCreatedInternally&&(this.texture.dispose(),this._textureCreatedInternally=!1),this._configureUserCreatedTexture=!0,null===(e=this._maskTexture)||void 0===e||e.dispose(),this._maskTexture=null,null===(t=this._finalPostProcess)||void 0===t||t.dispose(),this._finalPostProcess=null},e.prototype._configureUserCreatedRTT=function(){this._configureUserCreatedTexture=!1,e._IsRenderTargetTexture(this.texture)&&(this.texture.setMaterialForRendering(this._mesh,e._GetShader(this._scene)),this.texture.onClearObservable.add((function(){})),this.texture.renderList=[this._mesh],this._options.uvEdgeBlending&&(this._createMaskTexture(),this._createPostProcess(),this.texture.addPostProcess(this._finalPostProcess)))},e.prototype._createDiffuseRTT=function(){this._textureCreatedInternally=!0;var t=this._createRenderTargetTexture(this._options.width,this._options.height);t.setMaterialForRendering(this._mesh,e._GetShader(this._scene)),this.texture=t,this._configureUserCreatedTexture=!1,this._options.uvEdgeBlending&&(this._createMaskTexture(),this._createPostProcess(),t.addPostProcess(this._finalPostProcess))},e.prototype._createMaskTexture=function(){this._maskTexture||(this._maskTexture=new Pl(this._mesh.name+"_maskTexture",{width:this._options.width,height:this._options.height},this._scene,!1,!0,u.TEXTURETYPE_UNSIGNED_BYTE,!1,u.TEXTURE_BILINEAR_SAMPLINGMODE,void 0,void 0,void 0,u.TEXTUREFORMAT_R),this._maskTexture.clearColor=new J(0,0,0,0),this._maskTexture.renderList.push(this._mesh),this._maskTexture.setMaterialForRendering(this._mesh,e._GetMaskShader(this._scene)),this._maskTexture.refreshRate=Pl.REFRESHRATE_RENDER_ONCE,this._scene.customRenderTargets.push(this._maskTexture))},e.prototype._createPostProcess=function(){var e=this;this._finalPostProcess||(this._finalPostProcess=new hl(this._mesh.name+"_fixSeamsPostProcess","meshUVSpaceRendererFinaliser",["textureSize"],["textureSampler","maskTextureSampler"],1,null,u.TEXTURE_NEAREST_SAMPLINGMODE,this._scene.getEngine(),!1,null,this._options.textureType),this._finalPostProcess.onApplyObservable.add((function(t){t.setTexture("maskTextureSampler",e._maskTexture),t.setFloat2("textureSize",e._options.width,e._options.height)})))},e.prototype._createRenderTargetTexture=function(e,t){var i=this,r=new Pl(this._mesh.name+"_uvspaceTexture",{width:e,height:t},this._scene,this._options.generateMipMaps,!0,this._options.textureType,!1,this._options.generateMipMaps?u.TEXTURE_TRILINEAR_SAMPLINGMODE:u.TEXTURE_BILINEAR_SAMPLINGMODE,!1,!1,!1,u.TEXTUREFORMAT_RGBA);return r.renderParticles=!1,r.optimizeUVAllocation=!!this._options.optimizeUVAllocation,r.onClearObservable.addOnce((function(){i._scene.getEngine().clear(i.clearColor,!0,!0,!0),r.onClearObservable.add((function(){}))})),r.renderList=[this._mesh],r},e.prototype._createProjectionMatrix=function(e,t,i,r){void 0===r&&(r=0);var n=-Math.atan2(t.z,t.x)-Math.PI/2,o=Math.sqrt(t.x*t.x+t.z*t.z),a=Math.atan2(t.y,o),s=e.add(t.scale(.5*i.z)),l=z.RotationYawPitchRoll(n,a,r).multiply(z.Translation(s.x,s.y,s.z)),c=z.Invert(l),u=z.FromArray([2/i.x,0,0,0,0,2/i.y,0,0,0,0,1/i.z,0,0,0,0,1]),h=z.FromArray([.5,0,0,0,0,.5,0,0,0,0,1,0,.5,.5,0,1]);return c.multiply(u).multiply(h)},e}();Fa._TrailMeshParser=function(e,t){return AE.Parse(e,t)};var xE,AE=function(e){function t(t,i,r,n,o,a){void 0===n&&(n=1),void 0===o&&(o=60),void 0===a&&(a=!0);var s=e.call(this,t,r)||this;s._sectionPolygonPointsCount=4,s._running=!1,s._autoStart=a,s._generator=i,s.diameter=n,s._length=o,s._sectionVectors=[],s._sectionNormalVectors=[];for(var l=0;l<=s._sectionPolygonPointsCount;l++)s._sectionVectors[l]=V.Zero(),s._sectionNormalVectors[l]=V.Zero();return s._createMesh(),s}return m(t,e),t.prototype.getClassName=function(){return"TrailMesh"},t.prototype._createMesh=function(){var e=new _o,t=[],i=[],r=[],n=[],o=V.Zero();o=this._generator instanceof Uo&&this._generator.hasBoundingInfo?this._generator.getBoundingInfo().boundingBox.centerWorld:this._generator.absolutePosition;for(var a=2*Math.PI/this._sectionPolygonPointsCount,s=0;s<=this._sectionPolygonPointsCount;s++){var l=s!==this._sectionPolygonPointsCount?s*a:0;t.push(o.x+Math.cos(l)*this.diameter,o.y+Math.sin(l)*this.diameter,o.z),n.push(s/this._sectionPolygonPointsCount,0)}for(s=1;s<=this._length;s++){for(var c=0;c<=this._sectionPolygonPointsCount;c++)l=c!==this._sectionPolygonPointsCount?c*a:0,t.push(o.x+Math.cos(l)*this.diameter,o.y+Math.sin(l)*this.diameter,o.z),n.push(c/this._sectionPolygonPointsCount,s/this._length);var u=t.length/3-2*(this._sectionPolygonPointsCount+1);for(c=0;c<=this._sectionPolygonPointsCount;c++)r.push(u+c,u+c+this._sectionPolygonPointsCount,u+c+this._sectionPolygonPointsCount+1),r.push(u+c,u+c+this._sectionPolygonPointsCount+1,u+c+1)}_o.ComputeNormals(t,r,i),e.positions=t,e.normals=i,e.indices=r,e.uvs=n,e.applyToMesh(this,!0),this._autoStart&&this.start()},t.prototype.start=function(){var e=this;this._running||(this._running=!0,this._beforeRenderObserver=this.getScene().onBeforeRenderObservable.add((function(){e.update()})))},t.prototype.stop=function(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))},t.prototype.update=function(){var e=this.getVerticesData(Nr.PositionKind),t=this.getVerticesData(Nr.NormalKind),i=this._generator.getWorldMatrix();if(e&&t){for(var r=3*(this._sectionPolygonPointsCount+1);r<e.length;r++)e[r-3*(this._sectionPolygonPointsCount+1)]=e[r]-t[r]/this._length*this.diameter;for(r=3*(this._sectionPolygonPointsCount+1);r<t.length;r++)t[r-3*(this._sectionPolygonPointsCount+1)]=t[r];var n=e.length-3*(this._sectionPolygonPointsCount+1),o=2*Math.PI/this._sectionPolygonPointsCount;for(r=0;r<=this._sectionPolygonPointsCount;r++){var a=r!==this._sectionPolygonPointsCount?r*o:0;this._sectionVectors[r].copyFromFloats(Math.cos(a)*this.diameter,Math.sin(a)*this.diameter,0),this._sectionNormalVectors[r].copyFromFloats(Math.cos(a),Math.sin(a),0),V.TransformCoordinatesToRef(this._sectionVectors[r],i,this._sectionVectors[r]),V.TransformNormalToRef(this._sectionNormalVectors[r],i,this._sectionNormalVectors[r])}for(r=0;r<=this._sectionPolygonPointsCount;r++)e[n+3*r]=this._sectionVectors[r].x,e[n+3*r+1]=this._sectionVectors[r].y,e[n+3*r+2]=this._sectionVectors[r].z,t[n+3*r]=this._sectionNormalVectors[r].x,t[n+3*r+1]=this._sectionNormalVectors[r].y,t[n+3*r+2]=this._sectionNormalVectors[r].z;this.updateVerticesData(Nr.PositionKind,e,!0,!1),this.updateVerticesData(Nr.NormalKind,t,!0,!1)}},t.prototype.clone=function(e,i){return void 0===e&&(e=""),new t(e,null!=i?i:this._generator,this.getScene(),this.diameter,this._length,this._autoStart)},t.prototype.serialize=function(t){e.prototype.serialize.call(this,t),t.generatorId=this._generator.id},t.Parse=function(e,i){var r,n,o=null!==(r=i.getLastMeshById(e.generatorId))&&void 0!==r?r:i.getLastTransformNodeById(e.generatorId);if(!o)throw new Error("TrailMesh: generator not found with ID "+e.generatorId);return new t(e.name,o,i,null!==(n=e.diameter)&&void 0!==n?n:e._diameter,e._length,e._autoStart)},t}(Fa),CE=function(e,t,i){this.quality=e,this.distance=t,this.optimizeMesh=i},RE=function(){function e(){this.running=!1,this._simplificationArray=[]}return e.prototype.addTask=function(e){this._simplificationArray.push(e)},e.prototype.executeNext=function(){var e=this._simplificationArray.pop();e?(this.running=!0,this.runSimplification(e)):this.running=!1},e.prototype.runSimplification=function(e){var t=this;if(e.parallelProcessing)e.settings.forEach((function(i){t._getSimplifier(e).simplify(i,(function(r){void 0!==i.distance&&e.mesh.addLODLevel(i.distance,r),r.isVisible=!0,i.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),t.executeNext()}))}));else{var i=this._getSimplifier(e);or.Run(e.settings.length,(function(t){var r,n;r=e.settings[t.index],n=function(){t.executeNext()},i.simplify(r,(function(t){void 0!==r.distance&&e.mesh.addLODLevel(r.distance,t),t.isVisible=!0,n()}))}),(function(){e.successCallback&&e.successCallback(),t.executeNext()}))}},e.prototype._getSimplifier=function(e){return e.simplificationType,xE.QUADRATIC,new DE(e.mesh)},e}();!function(e){e[e.QUADRATIC=0]="QUADRATIC"}(xE||(xE={}));var PE=function(e){this._vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0},IE=function(){function e(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new ME,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}return e.prototype.updatePosition=function(e){this.position.copyFrom(e)},e}(),ME=function(){function e(e){this.data=new Array(10);for(var t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}return e.prototype.det=function(e,t,i,r,n,o,a,s,l){return this.data[e]*this.data[n]*this.data[l]+this.data[i]*this.data[r]*this.data[s]+this.data[t]*this.data[o]*this.data[a]-this.data[i]*this.data[n]*this.data[a]-this.data[e]*this.data[o]*this.data[s]-this.data[t]*this.data[r]*this.data[l]},e.prototype.addInPlace=function(e){for(var t=0;t<10;++t)this.data[t]+=e.data[t]},e.prototype.addArrayInPlace=function(e){for(var t=0;t<10;++t)this.data[t]+=e[t]},e.prototype.add=function(t){for(var i=new e,r=0;r<10;++r)i.data[r]=this.data[r]+t.data[r];return i},e.FromData=function(t,i,r,n){return new e(e.DataFromNumbers(t,i,r,n))},e.DataFromNumbers=function(e,t,i,r){return[e*e,e*t,e*i,e*r,t*t,t*i,t*r,i*i,i*r,r*r]},e}(),OE=function(e,t){this.vertexId=e,this.triangleId=t},DE=function(){function e(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=A}return e.prototype.simplify=function(e,t){var i=this;this._initDecimatedMesh(),or.Run(this._mesh.subMeshes.length,(function(t){i._initWithMesh(t.index,(function(){i._runDecimation(e,t.index,(function(){t.executeNext()}))}),e.optimizeMesh)}),(function(){setTimeout((function(){t(i._reconstructedMesh)}),0)}))},e.prototype._runDecimation=function(e,t,i){var r=this,n=~~(this._triangles.length*e.quality),o=0,a=this._triangles.length;or.Run(this.decimationIterations,(function(e){var t,i;a-o<=n?e.breakLoop():(t=e.index,i=function(){e.executeNext()},setTimeout((function(){t%5==0&&r._updateMesh(0===t);for(var e=0;e<r._triangles.length;++e)r._triangles[e].isDirty=!1;var s=1e-9*Math.pow(t+3,r.aggressiveness);or.SyncAsyncForLoop(r._triangles.length,r.syncIterations,(function(e){var t=~~((r._triangles.length/2+e)%r._triangles.length),i=r._triangles[t];if(i&&!(i.error[3]>s||i.deleted||i.isDirty))for(var n=function(e){if(i.error[e]<s){var t=[],n=[],a=i._vertices[e],l=i._vertices[(e+1)%3];if(a.isBorder||l.isBorder)return"continue";var c=V.Zero();r._calculateError(a,l,c);var u=[];if(r._isFlipped(a,l,c,t,u))return"continue";if(r._isFlipped(l,a,c,n,u))return"continue";if(t.indexOf(!0)<0||n.indexOf(!0)<0)return"continue";var h=[];if(u.forEach((function(e){-1===h.indexOf(e)&&(e.deletePending=!0,h.push(e))})),h.length%2!=0)return"continue";a.q=l.q.add(a.q),a.updatePosition(c);var d=r._references.length;o=r._updateTriangles(a,a,t,o),o=r._updateTriangles(a,l,n,o);var p=r._references.length-d;if(p<=a.triangleCount){if(p)for(var f=0;f<p;f++)r._references[a.triangleStart+f]=r._references[d+f]}else a.triangleStart=d;return a.triangleCount=p,"break"}},a=0;a<3&&"break"!==n(a);++a);}),i,(function(){return a-o<=n}))}),0))}),(function(){setTimeout((function(){r._reconstructMesh(t),i()}),0)}))},e.prototype._initWithMesh=function(e,t,i){var r=this;this._vertices=[],this._triangles=[];var n=this._mesh.getVerticesData(Nr.PositionKind),o=this._mesh.getIndices(),a=this._mesh.subMeshes[e],s=[],l=a.verticesCount;or.SyncAsyncForLoop(l,this.syncIterations/4|0,(function(e){if(n){var t=e+a.verticesStart,o=V.FromArray(n,3*t),l=function(e){if(i)for(var t=0;t<r._vertices.length;++t)if(r._vertices[t].position.equalsWithEpsilon(e,1e-4))return r._vertices[t];return null}(o)||new IE(o,r._vertices.length);l.originalOffsets.push(t),l.id===r._vertices.length&&r._vertices.push(l),s.push(l.id)}}),(function(){or.SyncAsyncForLoop(a.indexCount/3,r.syncIterations,(function(e){if(o){var t=3*(a.indexStart/3+e),i=o[t+0],n=o[t+1],l=o[t+2],c=r._vertices[s[i-a.verticesStart]],u=r._vertices[s[n-a.verticesStart]],h=r._vertices[s[l-a.verticesStart]],d=new PE([c,u,h]);d.originalOffset=t,r._triangles.push(d)}}),(function(){r._init(t)}))}))},e.prototype._init=function(e){var t=this;or.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(function(e){var i=t._triangles[e];i.normal=V.Cross(i._vertices[1].position.subtract(i._vertices[0].position),i._vertices[2].position.subtract(i._vertices[0].position)).normalize();for(var r=0;r<3;r++)i._vertices[r].q.addArrayInPlace(ME.DataFromNumbers(i.normal.x,i.normal.y,i.normal.z,-V.Dot(i.normal,i._vertices[0].position)))}),(function(){or.SyncAsyncForLoop(t._triangles.length,t.syncIterations,(function(e){for(var i=t._triangles[e],r=0;r<3;++r)i.error[r]=t._calculateError(i._vertices[r],i._vertices[(r+1)%3]);i.error[3]=Math.min(i.error[0],i.error[1],i.error[2])}),(function(){e()}))}))},e.prototype._reconstructMesh=function(e){var t,i,r,n=[];for(t=0;t<this._vertices.length;++t)this._vertices[t].triangleCount=0;for(t=0;t<this._triangles.length;++t)if(!this._triangles[t].deleted){for(i=this._triangles[t],r=0;r<3;++r)i._vertices[r].triangleCount=1;n.push(i)}var o=this._reconstructedMesh.getVerticesData(Nr.PositionKind)||[],a=this._reconstructedMesh.getVerticesData(Nr.NormalKind)||[],s=this._reconstructedMesh.getVerticesData(Nr.UVKind)||[],l=this._reconstructedMesh.getVerticesData(Nr.ColorKind)||[],c=this._mesh.getVerticesData(Nr.NormalKind),u=this._mesh.getVerticesData(Nr.UVKind),h=this._mesh.getVerticesData(Nr.ColorKind),d=0,p=function(){var e=f._vertices[t];e.id=d,e.triangleCount&&e.originalOffsets.forEach((function(t){o.push(e.position.x),o.push(e.position.y),o.push(e.position.z),c&&c.length&&(a.push(c[3*t]),a.push(c[3*t+1]),a.push(c[3*t+2])),u&&u.length&&(s.push(u[2*t]),s.push(u[2*t+1])),h&&h.length&&(l.push(h[4*t]),l.push(h[4*t+1]),l.push(h[4*t+2]),l.push(h[4*t+3])),++d}))},f=this;for(t=0;t<this._vertices.length;++t)p();var _=this._reconstructedMesh.getTotalIndices(),m=this._reconstructedMesh.getTotalVertices(),g=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];var v=this._reconstructedMesh.getIndices(),y=this._mesh.getIndices();for(t=0;t<n.length;++t)i=n[t],[0,1,2].forEach((function(e){var t=y[i.originalOffset+e],r=i._vertices[e].originalOffsets.indexOf(t);r<0&&(r=0),v.push(i._vertices[e].id+r+m)}));this._reconstructedMesh.setIndices(v),this._reconstructedMesh.setVerticesData(Nr.PositionKind,o),a.length>0&&this._reconstructedMesh.setVerticesData(Nr.NormalKind,a),s.length>0&&this._reconstructedMesh.setVerticesData(Nr.UVKind,s),l.length>0&&this._reconstructedMesh.setVerticesData(Nr.ColorKind,l);var b=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],g.forEach((function(e){po.AddToMesh(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,e.getMesh())})),po.AddToMesh(b.materialIndex,m,d,_,3*n.length,this._reconstructedMesh))},e.prototype._initDecimatedMesh=function(){this._reconstructedMesh=new Fa(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId},e.prototype._isFlipped=function(e,t,i,r,n){for(var o=0;o<e.triangleCount;++o){var a=this._triangles[this._references[e.triangleStart+o].triangleId];if(!a.deleted){var s=this._references[e.triangleStart+o].vertexId,l=a._vertices[(s+1)%3],c=a._vertices[(s+2)%3];if(l!==t&&c!==t){var u=l.position.subtract(i);u=u.normalize();var h=c.position.subtract(i);if(h=h.normalize(),Math.abs(V.Dot(u,h))>.999)return!0;var d=V.Cross(u,h).normalize();if(r[o]=!1,V.Dot(d,a.normal)<.2)return!0}else r[o]=!0,n.push(a)}}return!1},e.prototype._updateTriangles=function(e,t,i,r){for(var n=r,o=0;o<t.triangleCount;++o){var a=this._references[t.triangleStart+o],s=this._triangles[a.triangleId];s.deleted||(i[o]&&s.deletePending?(s.deleted=!0,n++):(s._vertices[a.vertexId]=e,s.isDirty=!0,s.error[0]=this._calculateError(s._vertices[0],s._vertices[1])+s.borderFactor/2,s.error[1]=this._calculateError(s._vertices[1],s._vertices[2])+s.borderFactor/2,s.error[2]=this._calculateError(s._vertices[2],s._vertices[0])+s.borderFactor/2,s.error[3]=Math.min(s.error[0],s.error[1],s.error[2]),this._references.push(a)))}return n},e.prototype._identifyBorder=function(){for(var e=0;e<this._vertices.length;++e){var t=[],i=[],r=this._vertices[e],n=void 0;for(n=0;n<r.triangleCount;++n)for(var o=this._triangles[this._references[r.triangleStart+n].triangleId],a=0;a<3;a++){for(var s=0,l=o._vertices[a];s<t.length&&i[s]!==l.id;)++s;s===t.length?(t.push(1),i.push(l.id)):t[s]++}for(n=0;n<t.length;++n)1===t[n]?this._vertices[i[n]].isBorder=!0:this._vertices[i[n]].isBorder=!1}},e.prototype._updateMesh=function(e){var t,i,r,n;if(void 0===e&&(e=!1),!e){var o=[];for(t=0;t<this._triangles.length;++t)this._triangles[t].deleted||o.push(this._triangles[t]);this._triangles=o}for(t=0;t<this._vertices.length;++t)this._vertices[t].triangleCount=0,this._vertices[t].triangleStart=0;for(t=0;t<this._triangles.length;++t)for(i=this._triangles[t],r=0;r<3;++r)(n=i._vertices[r]).triangleCount++;var a=0;for(t=0;t<this._vertices.length;++t)this._vertices[t].triangleStart=a,a+=this._vertices[t].triangleCount,this._vertices[t].triangleCount=0;var s=new Array(3*this._triangles.length);for(t=0;t<this._triangles.length;++t)for(i=this._triangles[t],r=0;r<3;++r)s[(n=i._vertices[r]).triangleStart+n.triangleCount]=new OE(r,t),n.triangleCount++;this._references=s,e&&this._identifyBorder()},e.prototype._vertexError=function(e,t){var i=t.x,r=t.y,n=t.z;return e.data[0]*i*i+2*e.data[1]*i*r+2*e.data[2]*i*n+2*e.data[3]*i+e.data[4]*r*r+2*e.data[5]*r*n+2*e.data[6]*r+e.data[7]*n*n+2*e.data[8]*n+e.data[9]},e.prototype._calculateError=function(e,t,i){var r=e.q.add(t.q),n=e.isBorder&&t.isBorder,o=0,a=r.det(0,1,2,1,4,5,2,5,7);if(0===a||n){var s=e.position.add(t.position).divide(new V(2,2,2)),l=this._vertexError(r,e.position),c=this._vertexError(r,t.position),u=this._vertexError(r,s);(o=Math.min(l,c,u))===l?i&&i.copyFrom(e.position):o===c?i&&i.copyFrom(t.position):i&&i.copyFrom(s)}else i||(i=V.Zero()),i.x=-1/a*r.det(1,2,3,4,5,6,5,7,8),i.y=1/a*r.det(0,2,3,1,5,6,2,7,8),i.z=-1/a*r.det(0,1,3,1,4,6,2,5,8),o=this._vertexError(r,i);return o},e}();Object.defineProperty(pn.prototype,"simplificationQueue",{get:function(){if(!this._simplificationQueue){this._simplificationQueue=new RE;var e=this._getComponent(Vr.NAME_SIMPLIFICATIONQUEUE);e||(e=new wE(this),this._addComponent(e))}return this._simplificationQueue},set:function(e){this._simplificationQueue=e},enumerable:!0,configurable:!0}),Fa.prototype.simplify=function(e,t,i,r){return void 0===t&&(t=!0),void 0===i&&(i=xE.QUADRATIC),this.getScene().simplificationQueue.addTask({settings:e,parallelProcessing:t,mesh:this,simplificationType:i,successCallback:r}),this};var NE,FE,LE,wE=function(){function e(e){this.name=Vr.NAME_SIMPLIFICATIONQUEUE,this.scene=e}return e.prototype.register=function(){this.scene._beforeCameraUpdateStage.registerStep(Vr.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE,this,this._beforeCameraUpdate)},e.prototype.rebuild=function(){},e.prototype.dispose=function(){},e.prototype._beforeCameraUpdate=function(){this.scene._simplificationQueue&&!this.scene._simplificationQueue.running&&this.scene._simplificationQueue.executeNext()},e}();!function(e){e[e.POINTS_MODE_POINTS=0]="POINTS_MODE_POINTS",e[e.POINTS_MODE_PATHS=1]="POINTS_MODE_PATHS"}(NE||(NE={})),function(e){e[e.FACES_MODE_SINGLE_SIDED=0]="FACES_MODE_SINGLE_SIDED",e[e.FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING=1]="FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING",e[e.FACES_MODE_DOUBLE_SIDED=2]="FACES_MODE_DOUBLE_SIDED"}(FE||(FE={})),function(e){e[e.AUTO_DIRECTIONS_FROM_FIRST_SEGMENT=0]="AUTO_DIRECTIONS_FROM_FIRST_SEGMENT",e[e.AUTO_DIRECTIONS_FROM_ALL_SEGMENTS=1]="AUTO_DIRECTIONS_FROM_ALL_SEGMENTS",e[e.AUTO_DIRECTIONS_ENHANCED=2]="AUTO_DIRECTIONS_ENHANCED",e[e.AUTO_DIRECTIONS_FACE_TO=3]="AUTO_DIRECTIONS_FACE_TO",e[e.AUTO_DIRECTIONS_NONE=99]="AUTO_DIRECTIONS_NONE"}(LE||(LE={}));var BE=function(e){function t(t,i,r){var n,o,a,s,l=this;return(l=e.call(this,t,i,null,null,!1,!1)||this).name=t,l._options=r,l._lazy=!1,l._updatable=!1,l._engine=i.getEngine(),l._lazy=null!==(n=r.lazy)&&void 0!==n&&n,l._updatable=null!==(o=r.updatable)&&void 0!==o&&o,l._vertexPositions=[],l._indices=[],l._uvs=[],l._points=[],l._colorPointers=null!==(a=r.colorPointers)&&void 0!==a?a:[],l._widths=null!==(s=r.widths)&&void 0!==s?s:new Array(r.points.length).fill(1),l}return m(t,e),t.prototype.getClassName=function(){return"GreasedLineMesh"},t.prototype._updateWidthsWithValue=function(e){for(var t=0,i=0,r=this._points;i<r.length;i++)t+=r[i].length;for(var n=t/3*2-this._widths.length,o=0;o<n;o++)this._widths.push(e)},t.prototype.updateLazy=function(){var e,t;this._setPoints(this._points),this._options.colorPointers||this._updateColorPointers(),this._createVertexBuffers(null===(e=this._options.ribbonOptions)||void 0===e?void 0:e.smoothShading),this.refreshBoundingInfo(),null===(t=this.greasedLineMaterial)||void 0===t||t.updateLazy()},t.prototype.addPoints=function(e,t){for(var i=0,r=e;i<r.length;i++){var n=r[i];this._points.push(n)}this._lazy||this.setPoints(this._points,t)},t.prototype.dispose=function(t,i){void 0===i&&(i=!1),e.prototype.dispose.call(this,t,i)},t.prototype.isLazy=function(){return this._lazy},Object.defineProperty(t.prototype,"uvs",{get:function(){return this._uvs},set:function(e){this._uvs=e instanceof Float32Array?e:new Float32Array(e),this._createVertexBuffers()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"offsets",{get:function(){return this._offsets},set:function(e){this._offsets=e,this._offsetsBuffer?this._offsetsBuffer.update(e):this._createOffsetsBuffer(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"widths",{get:function(){return this._widths},set:function(e){this._widths=e,this._lazy||this._widthsBuffer&&this._widthsBuffer.update(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"colorPointers",{get:function(){return this._colorPointers},set:function(e){this._colorPointers=e,this._lazy||this._colorPointersBuffer&&this._colorPointersBuffer.update(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"greasedLineMaterial",{get:function(){var e,t;return this.material&&this.material instanceof tE?this.material:(null===(t=null===(e=this.material)||void 0===e?void 0:e.pluginManager)||void 0===t?void 0:t.getPlugin($T.GREASED_LINE_MATERIAL_NAME))||void 0},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"points",{get:function(){var e=[];return ye.DeepCopy(this._points,e),e},enumerable:!1,configurable:!0}),t.prototype.setPoints=function(e,t){this._points=e,this._updateWidths(),(null==t?void 0:t.colorPointers)||this._updateColorPointers(),this._setPoints(e,t)},t.prototype._initGreasedLine=function(){this._vertexPositions=[],this._indices=[],this._uvs=[]},t.prototype._createLineOptions=function(){return{points:this._points,colorPointers:this._colorPointers,lazy:this._lazy,updatable:this._updatable,uvs:this._uvs,widths:this._widths,ribbonOptions:this._options.ribbonOptions}},t.prototype.serialize=function(t){e.prototype.serialize.call(this,t),t.type=this.getClassName(),t.lineOptions=this._createLineOptions()},t.prototype._createVertexBuffers=function(e){void 0===e&&(e=!1);var t=new _o;return t.positions=this._vertexPositions,t.indices=this._indices,t.uvs=this._uvs,e&&(t.normals=[],_o.ComputeNormals(this._vertexPositions,this._indices,t.normals)),t.applyToMesh(this,this._options.updatable),t},t.prototype._createOffsetsBuffer=function(e){var t=this._scene.getEngine(),i=new Dr(t,e,this._updatable,3);this.setVerticesBuffer(i.createVertexBuffer("grl_offsets",0,3)),this._offsetsBuffer=i},t}(Fa);Fa._GreasedLineMeshParser=function(e,t){return UE.Parse(e,t)};var UE=function(e){function t(t,i,r){var n=e.call(this,t,i,r)||this;return n.name=t,n.intersectionThreshold=.1,n._previousAndSide=[],n._nextAndCounters=[],r.points&&n.addPoints(ZT.ConvertPoints(r.points)),n}return m(t,e),t.prototype.getClassName=function(){return"GreasedLineMesh"},t.prototype._updateColorPointers=function(){var e=this;if(!this._options.colorPointers){var t=0;this._colorPointers=[],this._points.forEach((function(i){for(var r=0;r<i.length;r+=3)e._colorPointers.push(t),e._colorPointers.push(t++)}))}},t.prototype._updateWidths=function(){},t.prototype._setPoints=function(e){var i=this;this._points=e,this._options.points=e,this._initGreasedLine();var r=0,n=0,o=0,a=0,s=0;e.forEach((function(e){n+=2*e.length,o+=2*(e.length-3),a+=4*e.length/3,s+=8*e.length/3}));var l=new Float32Array(n),c=n>65535?new Uint32Array(o):new Uint16Array(o),u=new Float32Array(a),h=new Float32Array(s),d=new Float32Array(s),p=0,f=0,_=0,m=0,g=0;e.forEach((function(e){for(var n=ZT.GetLineLengthArray(e),o=n[n.length-1],a=0,s=0;s<e.length;a++,s+=3){var v=p+2*s;if(l[v+0]=e[s+0],l[v+1]=e[s+1],l[v+2]=e[s+2],l[v+3]=e[s+0],l[v+4]=e[s+1],l[v+5]=e[s+2],s<e.length-3){var y=2*a+r,b=f+2*s;c[b+0]=y,c[b+1]=y+1,c[b+2]=y+2,c[b+3]=y+2,c[b+4]=y+1,c[b+5]=y+3}}r+=e.length/3*2;var T=2*e.length,E=l.subarray(p,p+T);p+=T,f+=2*(e.length-3);var S,x=new Float32Array(E.length),A=new Float32Array(E.length),C=E.length/6;S=t._CompareV3(0,C-1,E)?E.subarray(6*(C-2),6*(C-1)):E.subarray(0,6),x.set(S),x.set(E.subarray(0,E.length-6),6),A.set(E.subarray(6)),S=t._CompareV3(C-1,0,E)?E.subarray(6,12):E.subarray(6*(C-1),6*C),A.set(S,A.length-6);for(var R=0,P=E.length/3;R<P;R++)h[m++]=x[3*R],h[m++]=x[3*R+1],h[m++]=x[3*R+2],h[m++]=1-((1&R)<<1),d[g++]=A[3*R],d[g++]=A[3*R+1],d[g++]=A[3*R+2],d[g++]=n[R>>1]/o;if(i._options.uvs)for(R=0;R<i._options.uvs.length;R++)u[_++]=i._options.uvs[R];else{for(a=0;a<C;a++){var I=_+4*a;u[I+0]=a/(C-1),u[I+1]=0,u[I+2]=a/(C-1),u[I+3]=1}_+=4*C}})),this._vertexPositions=l,this._indices=c,this._uvs=u,this._previousAndSide=h,this._nextAndCounters=d,this._lazy||(this._options.colorPointers||this._updateColorPointers(),this._createVertexBuffers(),this.refreshBoundingInfo())},t.prototype.clone=function(e,i){void 0===e&&(e="".concat(this.name,"-cloned"));var r=this._createLineOptions(),n={};ye.DeepCopy(r,n,["instance"],void 0,!0);var o=new t(e,this._scene,n);return i&&(o.parent=i),o.material=this.material,o},t.prototype.serialize=function(t){e.prototype.serialize.call(this,t),t.type=this.getClassName(),t.lineOptions=this._createLineOptions()},t.Parse=function(e,i){var r=e.lineOptions;return new t(e.name,i,r)},t.prototype._initGreasedLine=function(){e.prototype._initGreasedLine.call(this),this._previousAndSide=[],this._nextAndCounters=[]},t.prototype.intersects=function(e,t,i,r,n,o){void 0===r&&(r=!1),void 0===o&&(o=!1);var a=new Fr,s=this.findAllIntersections(e,t,i,r,n,o,!0);if(1===(null==s?void 0:s.length)){var l=s[0];a.hit=!0,a.distance=l.distance,a.ray=e,a.pickedMesh=this,a.pickedPoint=l.point}return a},t.prototype.findAllIntersections=function(e,i,r,n,o,a,s){var l,c;if(void 0===n&&(n=!1),void 0===a&&(a=!1),void 0===s&&(s=!1),!n||a||!1!==e.intersectsSphere(this._boundingSphere,this.intersectionThreshold)){var u=this.getIndices(),h=this.getVerticesData(Nr.PositionKind),d=this._widths,p=null!==(c=null===(l=this.greasedLineMaterial)||void 0===l?void 0:l.width)&&void 0!==c?c:1,f=[];if(u&&h&&d){var _,m=0;for(m=0,_=u.length-1;m<_;m+=3){var g=u[m],v=u[m+1];t._V_START.fromArray(h,3*g),t._V_END.fromArray(h,3*v),this._offsets&&(t._V_OFFSET_START.fromArray(this._offsets,3*g),t._V_OFFSET_END.fromArray(this._offsets,3*v),t._V_START.addInPlace(t._V_OFFSET_START),t._V_END.addInPlace(t._V_OFFSET_END));var y=Math.floor(m/3),b=void 0!==d[y]?d[y]:1,T=this.intersectionThreshold*(p*b)/2,E=e.intersectionSegment(t._V_START,t._V_END,T);if(-1!==E&&(f.push({distance:E,point:e.direction.normalize().multiplyByFloats(E,E,E).add(e.origin)}),s))return f}m=_}return f}},Object.defineProperty(t.prototype,"_boundingSphere",{get:function(){return this.getBoundingInfo().boundingSphere},enumerable:!1,configurable:!0}),t._CompareV3=function(e,t,i){var r=6*e,n=6*t;return i[r]===i[n]&&i[r+1]===i[n+1]&&i[r+2]===i[n+2]},t.prototype._createVertexBuffers=function(){var t=e.prototype._createVertexBuffers.call(this),i=this._scene.getEngine(),r=new Dr(i,this._previousAndSide,!1,4);this.setVerticesBuffer(r.createVertexBuffer("grl_previousAndSide",0,4));var n=new Dr(i,this._nextAndCounters,!1,4);this.setVerticesBuffer(n.createVertexBuffer("grl_nextAndCounters",0,4));var o=new Dr(i,this._widths,this._updatable,1);this.setVerticesBuffer(o.createVertexBuffer("grl_widths",0,1)),this._widthsBuffer=o;var a=new Dr(i,this._colorPointers,this._updatable,1);return this.setVerticesBuffer(a.createVertexBuffer("grl_colorPointers",0,1)),this._colorPointersBuffer=a,t},t._V_START=new V,t._V_END=new V,t._V_OFFSET_START=new V,t._V_OFFSET_END=new V,t}(BE);Fa._GreasedLineRibbonMeshParser=function(e,t){return HE.Parse(e,t)};var VE,kE,GE,zE,WE,HE=function(e){function t(t,i,r,n){var o,a=this;if((a=e.call(this,t,i,r)||this).name=t,!r.ribbonOptions)throw"'GreasedLineMeshOptions.ribbonOptions' is not set.";return a._paths=[],a._counters=[],a._slopes=[],a._widths=null!==(o=r.widths)&&void 0!==o?o:[],a._ribbonWidths=[],a._pathsOptions=null!=n?n:[],r.points&&a.addPoints(ZT.ConvertPoints(r.points),r,!!n),a}return m(t,e),t.prototype.addPoints=function(t,i,r){if(void 0===r&&(r=!1),!i.ribbonOptions)throw"addPoints() on GreasedLineRibbonMesh instance requires 'GreasedLineMeshOptions.ribbonOptions'.";r||this._pathsOptions.push({options:i,pathCount:t.length}),e.prototype.addPoints.call(this,t,i)},t.prototype.getClassName=function(){return"GreasedLineRibbonMesh"},Object.defineProperty(t.prototype,"isFlatLine",{get:function(){return this._paths.length<3},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"slopes",{get:function(){return this._slopes},set:function(e){this._slopes=e},enumerable:!1,configurable:!0}),t.prototype._updateColorPointers=function(){var e;if(!this._options.colorPointers){var t=0;this._colorPointers=[];for(var i=0;i<this._pathsOptions.length;i++){var r=(e=this._pathsOptions[i]).options,n=e.pathCount,o=this._points[i];if(r.ribbonOptions.pointsMode===NE.POINTS_MODE_POINTS)for(var a=0;a<n;a++)for(var s=0;s<o.length;s+=3)this._colorPointers.push(t),this._colorPointers.push(t++);else for(s=0;s<o.length;s+=3){for(a=0;a<n;a++)this._colorPointers.push(t);t++}}}},t.prototype._updateWidths=function(){e.prototype._updateWidthsWithValue.call(this,1)},t.prototype._setPoints=function(e,i){var r,n,o=this;if(!this._options.ribbonOptions)throw"No 'GreasedLineMeshOptions.ribbonOptions' provided.";this._points=e,this._options.points=e,this._initGreasedLine();for(var a,s,l=0,c=function(i,c){var h,d=(h=u._pathsOptions[i]).options,p=h.pathCount,f=e.slice(c,c+p);if(c+=p,(null===(r=d.ribbonOptions)||void 0===r?void 0:r.pointsMode)===NE.POINTS_MODE_PATHS)l=u._preprocess(ZT.ToVector3Array(f),l,d);else{if((null===(n=d.ribbonOptions)||void 0===n?void 0:n.directionsAutoMode)===LE.AUTO_DIRECTIONS_NONE){if(!d.ribbonOptions.directions)throw"In GreasedLineRibbonAutoDirectionMode.AUTO_DIRECTIONS_NONE 'GreasedLineMeshOptions.ribbonOptions.directions' must be defined.";a=t._GetDirectionPlanesFromDirectionsOption(f.length,d.ribbonOptions.directions)}f.forEach((function(e,i){var r=t._ConvertToRibbonPath(e,d.ribbonOptions,o._scene.useRightHandedSystem,a?a[i]:a);l=o._preprocess(r,l,d)}))}s=c},u=this,h=0,d=0;h<this._pathsOptions.length;h++)c(h,d),d=s;this._lazy||(this._createVertexBuffers(),this.refreshBoundingInfo())},t._GetDirectionPlanesFromDirectionsOption=function(e,t){return Array.isArray(t)?t:new Array(e).fill(t)},t._CreateRibbonVertexData=function(e,t){var i,r,n,o=e.length;if(o<2)throw"Minimum of two paths are required to create a GreasedLineRibbonMesh.";for(var a=[],s=[],l=e[0],c=0;c<l.length;c++)for(var u=0;u<e.length;u++){var h=e[u][c];a.push(h.x,h.y,h.z)}var d=[1,0,o],p=null!==(r=(null===(i=t.ribbonOptions)||void 0===i?void 0:i.facesMode)===FE.FACES_MODE_DOUBLE_SIDED)&&void 0!==r&&r,f=(null===(n=t.ribbonOptions)||void 0===n?void 0:n.pointsMode)===NE.POINTS_MODE_PATHS&&t.ribbonOptions.closePath;if(o>2)for(c=0;c<l.length-1;c++)for(d[0]=1+o*c,d[1]=o*c,d[2]=(c+1)*o,u=0;u<2*(o-1);u++)u%2!=0&&(d[2]+=1),u%2==0&&u>0&&(d[0]+=1,d[1]+=1),s.push(d[1]+(u%2!=0?o:0),d[0],d[2]),p&&s.push(d[0],d[1]+(u%2!=0?o:0),d[2]);else for(c=0;c<a.length/3-3;c+=2)s.push(c,c+1,c+2),s.push(c+2,c+1,c+3),p&&(s.push(c+1,c,c+2),s.push(c+1,c+2,c+3));if(f){var _=o*(l.length-1);for(u=0;u<o-1;u++)s.push(_,u+1,u),s.push(_+1,u+1,_),p&&(s.push(u,u+1,_),s.push(_,u+1,_+1)),_++}return{positions:a,indices:s}},t.prototype._preprocess=function(e,i,r){var n,o,a,s;this._paths=e;var l=t._CreateRibbonVertexData(e,r),c=l.positions;if(!this._options.widths)throw"No 'GreasedLineMeshOptions.widths' table is specified.";var u=Array.isArray(this._vertexPositions)?this._vertexPositions:Array.from(this._vertexPositions);this._vertexPositions=u;var h=Array.isArray(this._uvs)?this._uvs:Array.from(this._uvs);this._uvs=h;var d=Array.isArray(this._indices)?this._indices:Array.from(this._indices);this._indices=d;for(var p=0,f=c;p<f.length;p++){var _=f[p];u.push(_)}var m=e;if((null===(n=r.ribbonOptions)||void 0===n?void 0:n.pointsMode)===NE.POINTS_MODE_PATHS&&r.ribbonOptions.closePath){m=[];for(var g=0;g<e.length;g++){var v=e[g].slice();v.push(e[g][0].clone()),m.push(v)}}this._calculateSegmentLengths(m);var y=m.length,b=new Array(y).fill(0);for(g=0;g<m[0].length;g++)for(var T=0,E=0;E<y;E++){var S=b[E]+this._vSegmentLengths[E][g]/this._vTotalLengths[E];this._counters.push(S),h.push(S,T),b[E]=S,T+=this._uSegmentLengths[g][E]/this._uTotalLengths[g]}g=0;for(var x=0;g<m[0].length;g++){var A=this._uSegmentLengths[g][0]/2,C=this._uSegmentLengths[g][y-1]/2;for(this._ribbonWidths.push(((null!==(o=this._widths[x++])&&void 0!==o?o:1)-1)*A),E=0;E<y-2;E++)this._ribbonWidths.push(0);this._ribbonWidths.push(((null!==(a=this._widths[x++])&&void 0!==a?a:1)-1)*C)}for(var R=0,P=(null===(s=r.ribbonOptions)||void 0===s?void 0:s.pointsMode)===NE.POINTS_MODE_PATHS?new Array(m[0].length*m.length*6).fill(0):t._CalculateSlopes(m);R<P.length;R++){var I=P[R];this._slopes.push(I)}if(l.indices)for(g=0;g<l.indices.length;g++)d.push(l.indices[g]+i);return i+c.length/3},t._ConvertToRibbonPath=function(e,i,r,n){if(i.pointsMode===NE.POINTS_MODE_POINTS&&!i.width)throw"'GreasedLineMeshOptions.ribbonOptiosn.width' must be specified in GreasedLineRibbonPointsMode.POINTS_MODE_POINTS.";var o=[],a=[];if(i.pointsMode===NE.POINTS_MODE_POINTS){var s=i.width/2,l=ZT.ToVector3Array(e),c=null,u=null;if(i.directionsAutoMode===LE.AUTO_DIRECTIONS_FROM_FIRST_SEGMENT&&(n=t._GetDirectionFromPoints(l[0],l[1],null)),i.directionsAutoMode===LE.AUTO_DIRECTIONS_FACE_TO&&!(i.directions instanceof V))throw"In GreasedLineRibbonAutoDirectionMode.AUTO_DIRECTIONS_FACE_TO 'GreasedLineMeshOptions.ribbonOptions.directions' must be a Vector3.";H.Vector3[1]=i.directions instanceof V?i.directions:t.DIRECTION_XZ;for(var h=0;h<l.length-(n?0:1);h++){var d=l[h],p=l[h+1];if(n)c=n;else if(i.directionsAutoMode===LE.AUTO_DIRECTIONS_FACE_TO)p.subtractToRef(d,H.Vector3[0]),c=V.CrossToRef(H.Vector3[0],H.Vector3[1],H.Vector3[2]).normalize();else if(i.directionsAutoMode===LE.AUTO_DIRECTIONS_FROM_ALL_SEGMENTS)c=t._GetDirectionFromPoints(d,p,c);else{var f=p.subtract(d);f.applyRotationQuaternionInPlace(f.x>f.y&&f.x>f.z?r?t._RightHandedForwardReadOnlyQuaternion:t._LeftHandedForwardReadOnlyQuaternion:t._LeftReadOnlyQuaternion),c=f.normalize()}u=c.multiplyByFloats(s,s,s),o.push(d.add(u)),a.push(d.subtract(u))}n||(o.push(l[l.length-1].add(u)),a.push(l[l.length-1].subtract(u)))}return[o,a]},t._GetDirectionFromPoints=function(e,i,r){return e.x!==i.x||r&&1!==(null==r?void 0:r.x)?e.y===i.y?t.DIRECTION_XZ:e.z===i.z?t.DIRECTION_XY:t.DIRECTION_XZ:t.DIRECTION_YZ},t.prototype.clone=function(e,i){void 0===e&&(e="".concat(this.name,"-cloned"));var r=this._createLineOptions(),n={},o=[];ye.DeepCopy(this._pathsOptions,o,void 0,void 0,!0),ye.DeepCopy(r,n,["instance"],void 0,!0);var a=new t(e,this._scene,n,o);return i&&(a.parent=i),a.material=this.material,a},t.prototype.serialize=function(t){e.prototype.serialize.call(this,t),t.type=this.getClassName(),t.lineOptions=this._createLineOptions(),t.pathsOptions=this._pathsOptions},t.Parse=function(e,i){var r=e.lineOptions;return new t(e.name,i,r,e.pathOptions)},t.prototype._initGreasedLine=function(){e.prototype._initGreasedLine.call(this),this._paths=[],this._counters=[],this._slopes=[],this._ribbonWidths=[]},t.prototype._calculateSegmentLengths=function(e){var t=e.length;this._vSegmentLengths=new Array(t),this._vTotalLengths=new Array(t);for(var i=0,r=0;r<t;r++){var n=e[r];this._vSegmentLengths[r]=[0],i=0;for(var o=0;o<n.length-1;o++)i+=l=Math.abs(n[o].subtract(n[o+1]).lengthSquared()),this._vSegmentLengths[r].push(l);this._vTotalLengths[r]=i}var a=e[0].length;this._uSegmentLengths=new Array(a).fill([]),this._uTotalLengths=new Array(a).fill([]);var s=new V;for(o=0;o<a;o++){for(i=0,r=1;r<t;r++){var l;e[r][o].subtractToRef(e[r-1][o],s),i+=l=s.length(),this._uSegmentLengths[o].push(l)}this._uTotalLengths[o]=i}},t._CalculateSlopes=function(e){for(var t=e[0],i=2===e.length?e[1]:e[e.length-1],r=[],n=new V,o=0;o<t.length;o++)for(var a=0;a<e.length;a++)0===a||a===e.length-1?(t[o].subtract(i[o]).normalizeToRef(n),r.push(n.x,n.y,n.z),r.push(-n.x,-n.y,-n.z)):r.push(0,0,0,0,0,0);return r},t.prototype._createVertexBuffers=function(){var t,i;this._uvs=null!==(t=this._options.uvs)&&void 0!==t?t:this._uvs;var r=e.prototype._createVertexBuffers.call(this,null===(i=this._options.ribbonOptions)||void 0===i?void 0:i.smoothShading),n=new Dr(this._engine,this._counters,this._updatable,1);this.setVerticesBuffer(n.createVertexBuffer("grl_counters",0,1));var o=new Dr(this._engine,this._colorPointers,this._updatable,1);this.setVerticesBuffer(o.createVertexBuffer("grl_colorPointers",0,1));var a=new Dr(this._engine,this._slopes,this._updatable,3);this.setVerticesBuffer(a.createVertexBuffer("grl_slopes",0,3));var s=new Dr(this._engine,this._ribbonWidths,this._updatable,1);return this.setVerticesBuffer(s.createVertexBuffer("grl_widths",0,1)),this._widthsBuffer=s,r},t.DEFAULT_WIDTH=.1,t._RightHandedForwardReadOnlyQuaternion=G.RotationAxis(V.RightHandedForwardReadOnly,Math.PI/2),t._LeftHandedForwardReadOnlyQuaternion=G.RotationAxis(V.LeftHandedForwardReadOnly,Math.PI/2),t._LeftReadOnlyQuaternion=G.RotationAxis(V.LeftReadOnly,Math.PI/2),t.DIRECTION_XY=V.LeftHandedForwardReadOnly,t.DIRECTION_XZ=V.UpReadOnly,t.DIRECTION_YZ=V.LeftReadOnly,t}(BE);function XE(e,t,i){var r;switch(i=null!=i?i:M.LastCreatedScene,t.materialType){case LT.MATERIAL_TYPE_PBR:r=new rg(e,i),new $T(r,i,t);break;case LT.MATERIAL_TYPE_SIMPLE:r=new tE(e,i,t);break;default:r=new Uu(e,i),new $T(r,i,t)}return r}function jE(e,t,i,r){var n,o,a,s,l,c,u,h,d,p,f,_,m;r=null!=r?r:M.LastCreatedScene;var g=ZT.ConvertPoints(t.points);t.widthDistribution=null!==(n=t.widthDistribution)&&void 0!==n?n:kE.WIDTH_DISTRIBUTION_START,t.ribbonOptions&&(t.ribbonOptions.facesMode=null!==(o=t.ribbonOptions.facesMode)&&void 0!==o?o:FE.FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING,t.ribbonOptions.pointsMode=null!==(a=t.ribbonOptions.pointsMode)&&void 0!==a?a:NE.POINTS_MODE_POINTS,t.ribbonOptions.directionsAutoMode=null!==(s=t.ribbonOptions.directionsAutoMode)&&void 0!==s?s:t.ribbonOptions.directions?LE.AUTO_DIRECTIONS_NONE:LE.AUTO_DIRECTIONS_FROM_FIRST_SEGMENT),(i=null!=i?i:{color:qT.DEFAULT_COLOR}).createAndAssignMaterial=null===(l=i.createAndAssignMaterial)||void 0===l||l,i.colorDistribution=null!==(c=null==i?void 0:i.colorDistribution)&&void 0!==c?c:VE.COLOR_DISTRIBUTION_START,i.materialType=null!==(u=i.materialType)&&void 0!==u?u:LT.MATERIAL_TYPE_STANDARD;var v=YE(g),y=KE(v,null!==(h=t.widths)&&void 0!==h?h:[],t.widthDistribution),b=(null==i?void 0:i.colors)?QE(v,i.colors,i.colorDistribution,null!==(d=i.color)&&void 0!==d?d:qT.DEFAULT_COLOR):void 0,T={points:g,updatable:t.updatable,widths:y,lazy:t.lazy,ribbonOptions:t.ribbonOptions,uvs:t.uvs,colorPointers:t.colorPointers};if(T.ribbonOptions&&T.ribbonOptions.pointsMode===NE.POINTS_MODE_POINTS&&(T.ribbonOptions.width=null!==(f=null!==(p=i.width)&&void 0!==p?p:T.ribbonOptions.width)&&void 0!==f?f:qT.DEFAULT_WIDTH),t.instance)if((m=t.instance)instanceof HE)m.addPoints(g,T);else{var E=m.widths;if(E){for(var S=E.slice(),x=0,A=y;x<A.length;x++){var C=A[x];S.push(C)}m.widths=S}else m.widths=y;if(m.addPoints(g),t.uvs){var R=m.uvs;if(R){var P=new Float32Array(R.length+t.uvs.length);P.set(R,0),P.set(t.uvs,R.length),m.uvs=P}else m.uvs=t.uvs}}else if(m=T.ribbonOptions?new HE(e,r,T):new UE(e,r,T),i){var I={materialType:i.materialType,dashCount:i.dashCount,dashOffset:i.dashOffset,dashRatio:i.dashRatio,resolution:i.resolution,sizeAttenuation:i.sizeAttenuation,useColors:i.useColors,useDash:i.useDash,visibility:i.visibility,width:i.width,color:i.color,colorMode:i.colorMode,colorsSampling:i.colorsSampling,colorDistributionType:i.colorDistributionType,colors:b,cameraFacing:!t.ribbonOptions,colorsTexture:i.colorsTexture};if(i.createAndAssignMaterial){var O=XE(e,I,r);m.material=O,(null===(_=t.ribbonOptions)||void 0===_?void 0:_.facesMode)===FE.FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING&&(O.backFaceCulling=!1)}}if(b&&t.instance&&t.instance.greasedLineMaterial){var D=t.instance.greasedLineMaterial.colors;if(D){var N=D.concat(b);t.instance.greasedLineMaterial.setColors(N,m.isLazy())}}return m}function YE(e){for(var t=0,i=0,r=e;i<r.length;i++)t+=r[i].length/3;return t}function KE(e,t,i,r,n){void 0===r&&(r=1),void 0===n&&(n=1);var o=e-t.length/2,a=[];if(o<0)return t.slice(0,2*e);if(o>0){if(t.length%2!=0&&t.push(r),i===kE.WIDTH_DISTRIBUTION_START_END){for(var s=Math.floor(t.length/2),l=0,c=0;l<s-1;l++)a.push(t[c++]),a.push(t[c++]);var u=t[s/2],h=t[s/2+1];for(l=0;l<o;l++)a.push(h),a.push(u);for(l=s;l<t.length;l+=2)a.push(t[l]),a.push(t[l+1])}else if(i===kE.WIDTH_DISTRIBUTION_START){for(l=0;l<t.length;l+=2)a.push(t[l]),a.push(t[l+1]);for(l=0;l<o;l++)a.push(r),a.push(n)}else if(i===kE.WIDTH_DISTRIBUTION_END){for(l=0;l<o;l++)a.push(r),a.push(n);for(l=0;l<t.length;l+=2)a.push(t[l]),a.push(t[l+1])}else if(i===kE.WIDTH_DISTRIBUTION_REPEAT){l=0;for(var d=0;d<e;d++)a.push(t[l++]),a.push(t[l++]),l===t.length&&(l=0)}else if(i===kE.WIDTH_DISTRIBUTION_EVEN){c=0;var p=t.length/(2*(e-1));for(d=0;d<e;d++)l=Math.floor(c),a.push(t[l]),a.push(t[l+1]),c+=p}}else for(l=0;l<t.length;l++)a.push(t[l]);return a}function QE(e,t,i,r){var n=(e=Math.max(t.length,e))-t.length;if(n<0)return t.slice(0,e);var o=[];if(n>0){if(i===VE.COLOR_DISTRIBUTION_START_END){for(var a=Math.floor(t.length/2),s=0;s<a;s++)o.push(t[s]);for(s=0;s<n-1;s++)o.push(r);for(s=a;s<t.length;s++)o.push(t[s])}else if(i===VE.COLOR_DISTRIBUTION_START){for(s=0;s<t.length;s++)o.push(t[s]);for(s=0;s<n;s++)o.push(r)}else if(i===VE.COLOR_DISTRIBUTION_END){for(s=0;s<n-1;s++)o.push(r);for(s=0;s<t.length;s++)o.push(t[s])}else if(i===VE.COLOR_DISTRIBUTION_REPEAT){s=0;for(var l=0;l<e;l++)o.push(t[s]),++s===t.length&&(s=0)}else if(i===VE.COLOR_DISTRIBUTION_EVEN){var c=0,u=t.length/(e-1);for(l=0;l<e-1;l++)s=Math.floor(c),o.push(t[s]),c+=u}else if(i===VE.COLOR_DISTRIBUTION_NONE)for(s=0;s<t.length;s++)o.push(t[s])}else for(s=0;s<e;s++)o.push(t[s]);return o}!function(e){e[e.COLOR_DISTRIBUTION_NONE=0]="COLOR_DISTRIBUTION_NONE",e[e.COLOR_DISTRIBUTION_REPEAT=1]="COLOR_DISTRIBUTION_REPEAT",e[e.COLOR_DISTRIBUTION_EVEN=2]="COLOR_DISTRIBUTION_EVEN",e[e.COLOR_DISTRIBUTION_START=3]="COLOR_DISTRIBUTION_START",e[e.COLOR_DISTRIBUTION_END=4]="COLOR_DISTRIBUTION_END",e[e.COLOR_DISTRIBUTION_START_END=5]="COLOR_DISTRIBUTION_START_END"}(VE||(VE={})),function(e){e[e.WIDTH_DISTRIBUTION_NONE=0]="WIDTH_DISTRIBUTION_NONE",e[e.WIDTH_DISTRIBUTION_REPEAT=1]="WIDTH_DISTRIBUTION_REPEAT",e[e.WIDTH_DISTRIBUTION_EVEN=2]="WIDTH_DISTRIBUTION_EVEN",e[e.WIDTH_DISTRIBUTION_START=3]="WIDTH_DISTRIBUTION_START",e[e.WIDTH_DISTRIBUTION_END=4]="WIDTH_DISTRIBUTION_END",e[e.WIDTH_DISTRIBUTION_START_END=5]="WIDTH_DISTRIBUTION_START_END"}(kE||(kE={})),Fa.prototype.thinInstanceAdd=function(e,t){if(void 0===t&&(t=!0),!this.getScene().getEngine().getCaps().instancedArrays)return ae.Error("Thin Instances are not supported on this device as Instanced Array extension not supported"),-1;this._thinInstanceUpdateBufferSize("matrix",Array.isArray(e)?e.length:1);var i=this._thinInstanceDataStorage.instancesCount;if(Array.isArray(e))for(var r=0;r<e.length;++r)this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++,e[r],r===e.length-1&&t);else this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++,e,t);return i},Fa.prototype.thinInstanceAddSelf=function(e){return void 0===e&&(e=!0),this.thinInstanceAdd(z.IdentityReadOnly,e)},Fa.prototype.thinInstanceRegisterAttribute=function(e,t){e===Nr.ColorKind&&(e=Nr.ColorInstanceKind),this.removeVerticesData(e),this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.strides[e]=t,this._userThinInstanceBuffersStorage.sizes[e]=t*Math.max(32,this._thinInstanceDataStorage.instancesCount),this._userThinInstanceBuffersStorage.data[e]=new Float32Array(this._userThinInstanceBuffersStorage.sizes[e]),this._userThinInstanceBuffersStorage.vertexBuffers[e]=new Nr(this.getEngine(),this._userThinInstanceBuffersStorage.data[e],e,!0,!1,t,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])},Fa.prototype.thinInstanceSetMatrixAt=function(e,t,i){if(void 0===i&&(i=!0),!this._thinInstanceDataStorage.matrixData||e>=this._thinInstanceDataStorage.instancesCount)return!1;var r=this._thinInstanceDataStorage.matrixData;return t.copyToArray(r,16*e),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[e]=t),i&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},Fa.prototype.thinInstanceSetAttributeAt=function(e,t,i,r){return void 0===r&&(r=!0),e===Nr.ColorKind&&(e=Nr.ColorInstanceKind),!(!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[e]||t>=this._thinInstanceDataStorage.instancesCount||(this._thinInstanceUpdateBufferSize(e,0),this._userThinInstanceBuffersStorage.data[e].set(i,t*this._userThinInstanceBuffersStorage.strides[e]),r&&this.thinInstanceBufferUpdated(e),0))},Object.defineProperty(Fa.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){var t,i,r=null!==(t=this._thinInstanceDataStorage.matrixData)&&void 0!==t?t:null===(i=this.source)||void 0===i?void 0:i._thinInstanceDataStorage.matrixData;e<=(r?r.length/16:0)&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),Fa.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i){void 0===i&&(i=!0);for(var r=new Dr(this.getEngine(),t,!i,16,!1,!0),n=0;n<4;n++)this.setVerticesBuffer(r.createVertexBuffer(e+n,4*n,4));return r},Fa.prototype.thinInstanceSetBuffer=function(e,t,i,r){var n,o,a;void 0===i&&(i=0),void 0===r&&(r=!0),i=i||16,"matrix"===e?(null===(n=this._thinInstanceDataStorage.matrixBuffer)||void 0===n||n.dispose(),this._thinInstanceDataStorage.matrixBuffer=null,this._thinInstanceDataStorage.matrixBufferSize=t?t.length:32*i,this._thinInstanceDataStorage.matrixData=t,this._thinInstanceDataStorage.worldMatrices=null,null!==t?(this._thinInstanceDataStorage.instancesCount=t.length/i,this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",t,r),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):"previousMatrix"===e?(null===(o=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===o||o.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,r))):(e===Nr.ColorKind&&(e=Nr.ColorInstanceKind),null===t?(null===(a=this._userThinInstanceBuffersStorage)||void 0===a?void 0:a.data[e])&&(this.removeVerticesData(e),delete this._userThinInstanceBuffersStorage.data[e],delete this._userThinInstanceBuffersStorage.strides[e],delete this._userThinInstanceBuffersStorage.sizes[e],delete this._userThinInstanceBuffersStorage.vertexBuffers[e]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[e]=t,this._userThinInstanceBuffersStorage.strides[e]=i,this._userThinInstanceBuffersStorage.sizes[e]=t.length,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new Nr(this.getEngine(),t,e,!r,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},Fa.prototype.thinInstanceBufferUpdated=function(e){var t,i,r;"matrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.matrixBuffer&&!this._thinInstanceDataStorage.matrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),null===(t=this._thinInstanceDataStorage.matrixBuffer)||void 0===t||t.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount)):"previousMatrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.previousMatrixBuffer&&!this._thinInstanceDataStorage.previousMatrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),null===(i=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===i||i.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount)):(e===Nr.ColorKind&&(e=Nr.ColorInstanceKind),(null===(r=this._userThinInstanceBuffersStorage)||void 0===r?void 0:r.vertexBuffers[e])&&(this.thinInstanceAllowAutomaticStaticBufferRecreation&&!this._userThinInstanceBuffersStorage.vertexBuffers[e].isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0)))},Fa.prototype.thinInstancePartialBufferUpdate=function(e,t,i){var r;"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===Nr.ColorKind&&(e=Nr.ColorInstanceKind),(null===(r=this._userThinInstanceBuffersStorage)||void 0===r?void 0:r.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},Fa.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];var e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(var t=0;t<this._thinInstanceDataStorage.instancesCount;++t)this._thinInstanceDataStorage.worldMatrices[t]=z.FromArray(e,16*t)}return this._thinInstanceDataStorage.worldMatrices},Fa.prototype.thinInstanceRefreshBoundingInfo=function(e,t,i){if(void 0===e&&(e=!1),void 0===t&&(t=!1),void 0===i&&(i=!1),this._thinInstanceDataStorage.matrixData&&this._thinInstanceDataStorage.matrixBuffer){var r=this._thinInstanceDataStorage.boundingVectors;if(e||!this.rawBoundingInfo){r.length=0,this.refreshBoundingInfo(t,i);var n=this.getBoundingInfo();this.rawBoundingInfo=new so(n.minimum,n.maximum)}var o=this.getBoundingInfo(),a=this._thinInstanceDataStorage.matrixData;if(0===r.length)for(var s=0;s<o.boundingBox.vectors.length;++s)r.push(o.boundingBox.vectors[s].clone());H.Vector3[0].setAll(Number.POSITIVE_INFINITY),H.Vector3[1].setAll(Number.NEGATIVE_INFINITY);for(var l=0;l<this._thinInstanceDataStorage.instancesCount;++l)for(z.FromArrayToRef(a,16*l,H.Matrix[0]),s=0;s<r.length;++s)V.TransformCoordinatesToRef(r[s],H.Matrix[0],H.Vector3[2]),H.Vector3[0].minimizeInPlace(H.Vector3[2]),H.Vector3[1].maximizeInPlace(H.Vector3[2]);o.reConstruct(H.Vector3[0],H.Vector3[1]),this._updateBoundingInfo()}},Fa.prototype._thinInstanceRecreateBuffer=function(e,t){var i,r,n,o;void 0===t&&(t=!0),"matrix"===e?(null===(i=this._thinInstanceDataStorage.matrixBuffer)||void 0===i||i.dispose(),this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",this._thinInstanceDataStorage.matrixData,t)):"previousMatrix"===e?this._scene.needsPreviousWorldMatrices&&(null===(r=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===r||r.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",null!==(n=this._thinInstanceDataStorage.previousMatrixData)&&void 0!==n?n:this._thinInstanceDataStorage.matrixData,t)):(e===Nr.ColorKind&&(e=Nr.ColorInstanceKind),null===(o=this._userThinInstanceBuffersStorage.vertexBuffers[e])||void 0===o||o.dispose(),this._userThinInstanceBuffersStorage.vertexBuffers[e]=new Nr(this.getEngine(),this._userThinInstanceBuffersStorage.data[e],e,!t,!1,this._userThinInstanceBuffersStorage.strides[e],!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e]))},Fa.prototype._thinInstanceUpdateBufferSize=function(e,t){var i,r,n;void 0===t&&(t=1),e===Nr.ColorKind&&(e=Nr.ColorInstanceKind);var o="matrix"===e;if(o||this._userThinInstanceBuffersStorage&&this._userThinInstanceBuffersStorage.strides[e]){for(var a=o?16:this._userThinInstanceBuffersStorage.strides[e],s=o?this._thinInstanceDataStorage.matrixBufferSize:this._userThinInstanceBuffersStorage.sizes[e],l=o?this._thinInstanceDataStorage.matrixData:this._userThinInstanceBuffersStorage.data[e],c=(this._thinInstanceDataStorage.instancesCount+t)*a,u=s;u<c;)u*=2;if(!l||s!=u){if(l){var h=new Float32Array(u);h.set(l,0),l=h}else l=new Float32Array(u);o?(null===(i=this._thinInstanceDataStorage.matrixBuffer)||void 0===i||i.dispose(),this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",l,!1),this._thinInstanceDataStorage.matrixData=l,this._thinInstanceDataStorage.matrixBufferSize=u,this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&(null===(r=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===r||r.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",l,!1))):(null===(n=this._userThinInstanceBuffersStorage.vertexBuffers[e])||void 0===n||n.dispose(),this._userThinInstanceBuffersStorage.data[e]=l,this._userThinInstanceBuffersStorage.sizes[e]=u,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new Nr(this.getEngine(),l,e,!0,!1,a,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e]))}}},Fa.prototype._thinInstanceInitializeUserStorage=function(){this._userThinInstanceBuffersStorage||(this._userThinInstanceBuffersStorage={data:{},sizes:{},vertexBuffers:{},strides:{}})},Fa.prototype._disposeThinInstanceSpecificData=function(){var e;(null===(e=this._thinInstanceDataStorage)||void 0===e?void 0:e.matrixBuffer)&&(this._thinInstanceDataStorage.matrixBuffer.dispose(),this._thinInstanceDataStorage.matrixBuffer=null)},function(e){e[e.Int=1]="Int",e[e.Float=2]="Float",e[e.Vector2=4]="Vector2",e[e.Vector3=8]="Vector3",e[e.Vector4=16]="Vector4",e[e.Matrix=32]="Matrix",e[e.Geometry=64]="Geometry",e[e.Texture=128]="Texture",e[e.AutoDetect=1024]="AutoDetect",e[e.BasedOnInput=2048]="BasedOnInput",e[e.Undefined=4096]="Undefined",e[e.All=4095]="All"}(GE||(GE={})),function(e){e[e.Compatible=0]="Compatible",e[e.TypeIncompatible=1]="TypeIncompatible",e[e.HierarchyIssue=2]="HierarchyIssue"}(zE||(zE={})),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(WE||(WE={}));var qE,ZE=function(){function e(e,t,i){this._connectedPoint=null,this._storedValue=null,this._storedFunction=null,this._acceptedConnectionPointType=null,this._endpoints=new Array,this._type=GE.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new f,this.onDisconnectionObservable=new f,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this.defaultValue=null,this.value=null,this.valueMin=null,this.valueMax=null,this._callCount=0,this._executionCount=0,this._ownerBlock=t,this.name=e,this._direction=i}return Object.defineProperty(e.prototype,"direction",{get:function(){return this._direction},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"type",{get:function(){if(this._type===GE.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.type}if(this._type===GE.BasedOnInput){if(this._typeConnectionSource)return!this._typeConnectionSource.isConnected&&this._defaultConnectionPointType?this._defaultConnectionPointType:this._typeConnectionSource.type;if(this._defaultConnectionPointType)return this._defaultConnectionPointType}return this._type},set:function(e){this._type=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isConnected",{get:function(){return null!==this.connectedPoint||this.hasEndpoints},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connectedPoint",{get:function(){return this._connectedPoint},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"ownerBlock",{get:function(){return this._ownerBlock},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sourceBlock",{get:function(){return this._connectedPoint?this._connectedPoint.ownerBlock:null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connectedBlocks",{get:function(){return 0===this._endpoints.length?[]:this._endpoints.map((function(e){return e.ownerBlock}))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"endpoints",{get:function(){return this._endpoints},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hasEndpoints",{get:function(){return this._endpoints&&this._endpoints.length>0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"innerType",{get:function(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type},enumerable:!1,configurable:!0}),e.prototype._resetCounters=function(){this._callCount=0,this._executionCount=0},Object.defineProperty(e.prototype,"callCount",{get:function(){return this._callCount},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"executionCount",{get:function(){return this._executionCount},enumerable:!1,configurable:!0}),e.prototype.getConnectedValue=function(e){var t;return this.isConnected?(null===(t=this._connectedPoint)||void 0===t?void 0:t._storedFunction)?(this._connectedPoint._callCount++,this._connectedPoint._executionCount++,this._connectedPoint._storedFunction(e)):(this._connectedPoint._callCount++,this._connectedPoint._executionCount=1,this._connectedPoint._storedValue):(this._callCount++,this._executionCount=1,this.value)},e.prototype.getClassName=function(){return"NodeGeometryConnectionPoint"},e.prototype.canConnectTo=function(e){return this.checkCompatibilityState(e)===zE.Compatible},e.prototype.checkCompatibilityState=function(e){var t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==GE.AutoDetect)return e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)?zE.Compatible:zE.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return zE.TypeIncompatible;var r=i,n=t;return this.direction===WE.Input&&(r=t,n=i),r.isAnAncestorOf(n)?zE.HierarchyIssue:zE.Compatible},e.prototype.connectTo=function(e,t){if(void 0===t&&(t=!1),!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this},e.prototype.disconnectFrom=function(e){var t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this.onDisconnectionObservable.notifyObservers(e),e.onDisconnectionObservable.notifyObservers(this)),this},e.prototype.addExcludedConnectionPointFromAllowedTypes=function(e){for(var t=1;t<GE.All;)e&t||this.excludedConnectionPointTypes.push(t),t<<=1},e.prototype.serialize=function(e){void 0===e&&(e=!0);var t={};return t.name=this.name,t.displayName=this.displayName,void 0!==this.value&&null!==this.value&&(this.value.asArray?(t.valueType="BABYLON."+this.value.getClassName(),t.value=this.value.asArray()):(t.valueType="number",t.value=this.value)),e&&this.connectedPoint&&(t.inputName=this.name,t.targetBlockId=this.connectedPoint.ownerBlock.uniqueId,t.targetConnectionName=this.connectedPoint.name,t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),(this.isExposedOnFrame||this.exposedPortPosition>=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t},e.prototype.dispose=function(){this.onConnectionObservable.clear(),this.onDisconnectionObservable.clear()},e}(),JE=function(){function e(e){this._name="",this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._isDebug=!1,this._isUnique=!1,this._buildExecutionTime=0,this.onBuildObservable=new f,this._inputs=new Array,this._outputs=new Array,this._codeVariableName="",this.visibleOnFrame=!1,this._name=e,this.uniqueId=cn.UniqueId}return Object.defineProperty(e.prototype,"buildExecutionTime",{get:function(){return this._buildExecutionTime},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"inputs",{get:function(){return this._inputs},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"outputs",{get:function(){return this._outputs},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"name",{get:function(){return this._name},set:function(e){this._name=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isInput",{get:function(){return this._isInput},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isTeleportOut",{get:function(){return this._isTeleportOut},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isTeleportIn",{get:function(){return this._isTeleportIn},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isDebug",{get:function(){return this._isDebug},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isUnique",{get:function(){return this._isUnique},enumerable:!1,configurable:!0}),e.prototype.getClassName=function(){return"NodeGeometryBlock"},e.prototype._inputRename=function(e){return e},e.prototype._outputRename=function(e){return e},e.prototype.isAnAncestorOf=function(e){for(var t=0,i=this._outputs;t<i.length;t++){var r=i[t];if(r.hasEndpoints)for(var n=0,o=r.endpoints;n<o.length;n++){var a=o[n];if(a.ownerBlock===e)return!0;if(a.ownerBlock.isAnAncestorOf(e))return!0}}return!1},e.prototype.isAnAncestorOfType=function(e){if(this.getClassName()===e)return!0;for(var t=0,i=this._outputs;t<i.length;t++){var r=i[t];if(r.hasEndpoints)for(var n=0,o=r.endpoints;n<o.length;n++)if(o[n].ownerBlock.isAnAncestorOfType(e))return!0}return!1},e.prototype.getDescendantOfPredicate=function(e){if(e(this))return this;for(var t=0,i=this._outputs;t<i.length;t++){var r=i[t];if(r.hasEndpoints)for(var n=0,o=r.endpoints;n<o.length;n++){var a=o[n].ownerBlock.getDescendantOfPredicate(e);if(a)return a}}return null},e.prototype.registerInput=function(e,t,i,r,n,o){void 0===i&&(i=!1);var a=new ZE(e,this,WE.Input);return a.type=t,a.isOptional=i,a.defaultValue=r,a.value=r,a.valueMin=n,a.valueMax=o,this._inputs.push(a),this},e.prototype.registerOutput=function(e,t,i){return(i=null!=i?i:new ZE(e,this,WE.Output)).type=t,this._outputs.push(i),this},e.prototype._buildBlock=function(e){},e.prototype._customBuildStep=function(e){},e.prototype.build=function(e){if(this._buildId===e.buildId)return!0;if(this._outputs.length>0){if(!this._outputs.some((function(e){return e.hasEndpoints}))&&!this.isDebug)return!1;this.outputs.forEach((function(e){return e._resetCounters()}))}this._buildId=e.buildId;for(var t=0,i=this._inputs;t<i.length;t++){var r=i[t];r.connectedPoint?(c=r.connectedPoint.ownerBlock)&&c!==this&&c.build(e):r.isOptional||e.notConnectedNonOptionalInputs.push(r)}this._customBuildStep(e),e.verbose&&ae.Log("Building ".concat(this.name," [").concat(this.getClassName(),"]"));var n=_t.Now;this._buildBlock(e),this._buildExecutionTime=_t.Now-n;for(var o=0,a=this._outputs;o<a.length;o++)for(var s=0,l=a[o].endpoints;s<l.length;s++){var c;(c=l[s].ownerBlock)&&c.build(e)}return this.onBuildObservable.notifyObservers(this),!1},e.prototype._linkConnectionTypes=function(e,t,i){void 0===i&&(i=!1),i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]},e.prototype.initialize=function(){},e.prototype.autoConfigure=function(){},e.prototype.getInputByName=function(e){var t=this._inputs.filter((function(t){return t.name===e}));return t.length?t[0]:null},e.prototype.getOutputByName=function(e){var t=this._outputs.filter((function(t){return t.name===e}));return t.length?t[0]:null},e.prototype.serialize=function(){var e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.visibleOnFrame=this.visibleOnFrame,e.inputs=[],e.outputs=[];for(var t=0,i=this.inputs;t<i.length;t++){var r=i[t];e.inputs.push(r.serialize())}for(var n=0,o=this.outputs;n<o.length;n++){var a=o[n];e.outputs.push(a.serialize(!1))}return e},e.prototype._deserialize=function(e){this._name=e.name,this.comments=e.comments,this.visibleOnFrame=!!e.visibleOnFrame,this._deserializePortDisplayNamesAndExposedOnFrame(e)},e.prototype._deserializePortDisplayNamesAndExposedOnFrame=function(e){var t=this,i=e.inputs,r=e.outputs;i&&i.forEach((function(e){var i=t.inputs.find((function(t){return t.name===e.name}));if(i&&(e.displayName&&(i.displayName=e.displayName),e.isExposedOnFrame&&(i.isExposedOnFrame=e.isExposedOnFrame,i.exposedPortPosition=e.exposedPortPosition),void 0!==e.value&&null!==e.value))if("number"===e.valueType)i.value=e.value;else{var r=s(e.valueType);r&&(i.value=r.FromArray(e.value))}})),r&&r.forEach((function(e,i){e.displayName&&(t.outputs[i].displayName=e.displayName),e.isExposedOnFrame&&(t.outputs[i].isExposedOnFrame=e.isExposedOnFrame,t.outputs[i].exposedPortPosition=e.exposedPortPosition)}))},e.prototype._dumpPropertiesCode=function(){var e=this._codeVariableName;return"".concat(e,".visibleOnFrame = ").concat(this.visibleOnFrame,";\n")},e.prototype._dumpCodeForOutputConnections=function(e){var t="";if(-1!==e.indexOf(this))return t;e.push(this);for(var i=0,r=this.inputs;i<r.length;i++){var n=r[i];if(n.isConnected){var o=n.connectedPoint,a=o.ownerBlock;t+=a._dumpCodeForOutputConnections(e),t+="".concat(a._codeVariableName,".").concat(a._outputRename(o.name),".connectTo(").concat(this._codeVariableName,".").concat(this._inputRename(n.name),");\n")}}return t},e.prototype._dumpCode=function(e,t){t.push(this);var i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||"".concat(this.getClassName(),"_").concat(this.uniqueId),-1!==e.indexOf(this._codeVariableName)){var r=0;do{r++,this._codeVariableName=i+r}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);var n="\n// ".concat(this.getClassName(),"\n");this.comments&&(n+="// ".concat(this.comments,"\n"));var o=this.getClassName();if("GeometryInputBlock"===o){var a=this.type;n+="var ".concat(this._codeVariableName,' = new BABYLON.GeometryInputBlock("').concat(this.name,'", ').concat(a,");\n")}else n+="var ".concat(this._codeVariableName," = new BABYLON.").concat(o,'("').concat(this.name,'");\n');n+=this._dumpPropertiesCode();for(var s=0,l=this.inputs;s<l.length;s++){var c=l[s];if(c.isConnected){var u=c.connectedPoint.ownerBlock;-1===t.indexOf(u)&&(n+=u._dumpCode(e,t))}}for(var h=0,d=this.outputs;h<d.length;h++){var p=d[h];if(p.hasEndpoints)for(var f=0,_=p.endpoints;f<_.length;f++)(u=_[f].ownerBlock)&&-1===t.indexOf(u)&&(n+=u._dumpCode(e,t))}return n},e.prototype.clone=function(){var e=this.serialize(),t=s(e.customType);if(t){var i=new t;return i._deserialize(e),i}return null},e.prototype.dispose=function(){for(var e=0,t=this.inputs;e<t.length;e++)t[e].dispose();for(var i=0,r=this.outputs;i<r.length;i++)r[i].dispose();this.onBuildObservable.clear()},v([Ie("comment")],e.prototype,"comments",void 0),e}(),$E=function(e){function t(t){var i=e.call(this,t)||this;return i._vertexData=null,i._isUnique=!0,i.registerInput("geometry",GE.Geometry),i}return m(t,e),Object.defineProperty(t.prototype,"currentVertexData",{get:function(){return this._vertexData},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"GeometryOutputBlock"},Object.defineProperty(t.prototype,"geometry",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData},t}(JE);a("BABYLON.GeometryOutputBlock",$E),function(e){e[e.None=0]="None",e[e.Positions=1]="Positions",e[e.Normals=2]="Normals",e[e.Tangents=3]="Tangents",e[e.UV=4]="UV",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6",e[e.Colors=10]="Colors",e[e.VertexID=11]="VertexID",e[e.FaceID=12]="FaceID",e[e.GeometryID=13]="GeometryID",e[e.CollectionID=14]="CollectionID",e[e.LoopID=15]="LoopID",e[e.InstanceID=16]="InstanceID"}(qE||(qE={}));var eS=function(){function e(){this._rotationMatrix=new z,this._scalingMatrix=new z,this._positionMatrix=new z,this._scalingRotationMatrix=new z,this._transformMatrix=new z,this._tempVector3=new V,this.notConnectedNonOptionalInputs=[],this.noContextualData=[],this.vertexData=null,this._geometryContext=null,this._executionContext=null,this._instancingContext=null,this._geometryContextStack=[],this._executionContextStack=[],this._instancingContextStack=[]}return Object.defineProperty(e.prototype,"geometryContext",{get:function(){return this._geometryContext},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"executionContext",{get:function(){return this._executionContext},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"instancingContext",{get:function(){return this._instancingContext},enumerable:!1,configurable:!0}),e.prototype.pushGeometryContext=function(e){this._geometryContext=e,this._geometryContextStack.push(this._geometryContext)},e.prototype.pushExecutionContext=function(e){this._executionContext=e,this._executionContextStack.push(this._executionContext)},e.prototype.pushInstancingContext=function(e){this._instancingContext=e,this._instancingContextStack.push(this._instancingContext)},e.prototype.restoreGeometryContext=function(){this._geometryContextStack.pop(),this._geometryContext=this._geometryContextStack.length>0?this._geometryContextStack[this._geometryContextStack.length-1]:null},e.prototype.restoreExecutionContext=function(){this._executionContextStack.pop(),this._executionContext=this._executionContextStack.length>0?this._executionContextStack[this._executionContextStack.length-1]:null},e.prototype.restoreInstancingContext=function(){this._instancingContextStack.pop(),this._instancingContext=this._instancingContextStack.length>0?this._instancingContextStack[this._instancingContextStack.length-1]:null},e.prototype.getContextualValue=function(e,t){if(void 0===t&&(t=!1),!this.executionContext)return t||this.noContextualData.push(e),null;var i=this.executionContext.getExecutionIndex();switch(e){case qE.Positions:return this.executionContext.getOverridePositionsContextualValue?this.executionContext.getOverridePositionsContextualValue():this.geometryContext&&this.geometryContext.positions?V.FromArray(this.geometryContext.positions,3*i):V.Zero();case qE.Normals:return this.executionContext.getOverrideNormalsContextualValue?this.executionContext.getOverrideNormalsContextualValue():this.geometryContext&&this.geometryContext.normals?V.FromArray(this.geometryContext.normals,3*i):V.Zero();case qE.Colors:return this.geometryContext&&this.geometryContext.colors?k.FromArray(this.geometryContext.colors,4*i):k.Zero();case qE.Tangents:return this.geometryContext&&this.geometryContext.tangents?k.FromArray(this.geometryContext.tangents,4*i):k.Zero();case qE.UV:return this.executionContext.getOverrideUVs1ContextualValue?this.executionContext.getOverrideUVs1ContextualValue():this.geometryContext&&this.geometryContext.uvs?U.FromArray(this.geometryContext.uvs,2*i):U.Zero();case qE.UV2:return this.geometryContext&&this.geometryContext.uvs2?U.FromArray(this.geometryContext.uvs2,2*i):U.Zero();case qE.UV3:return this.geometryContext&&this.geometryContext.uvs3?U.FromArray(this.geometryContext.uvs3,2*i):U.Zero();case qE.UV4:return this.geometryContext&&this.geometryContext.uvs4?U.FromArray(this.geometryContext.uvs4,2*i):U.Zero();case qE.UV5:return this.geometryContext&&this.geometryContext.uvs5?U.FromArray(this.geometryContext.uvs5,2*i):U.Zero();case qE.UV6:return this.geometryContext&&this.geometryContext.uvs6?U.FromArray(this.geometryContext.uvs6,2*i):U.Zero();case qE.VertexID:return i;case qE.FaceID:return this.executionContext.getExecutionFaceIndex();case qE.LoopID:return this.executionContext.getExecutionLoopIndex();case qE.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case qE.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case qE.CollectionID:return this.geometryContext&&this.geometryContext.metadata&&this.geometryContext.metadata.collectionId||0}return null},e.prototype.adapt=function(e,t){var i=e.getConnectedValue(this)||0;if(e.type===t)return i;switch(t){case GE.Vector2:return new U(i,i);case GE.Vector3:return new V(i,i,i);case GE.Vector4:return new k(i,i,i,i)}return null},e.prototype.adaptInput=function(e,t,i){var r;if(!e.isConnected)return e.value||i;var n=e.getConnectedValue(this);if((null===(r=e._connectedPoint)||void 0===r?void 0:r.type)===t)return n;switch(t){case GE.Vector2:return new U(n,n);case GE.Vector3:return new V(n,n,n);case GE.Vector4:return new k(n,n,n,n)}return null},e.prototype.emitErrors=function(){for(var e="",t=0,i=this.notConnectedNonOptionalInputs;t<i.length;t++){var r=i[t];e+="input ".concat(r.name," from block ").concat(r.ownerBlock.name,"[").concat(r.ownerBlock.getClassName(),"] is not connected and is not optional.\n")}for(var n=0,o=this.noContextualData;n<o.length;n++){var a=o[n];e+="Contextual input ".concat(qE[a]," has no context to pull data from (must be connected to a setXXX block or a instantiateXXX block).\n")}if(e)throw"Build of NodeGeometry failed:\n"+e},e.prototype._instantiate=function(e,t,i,r,n){z.ScalingToRef(r.x,r.y,r.z,this._scalingMatrix),z.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),z.TranslationToRef(t.x,t.y,t.z,this._positionMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._positionMatrix,this._transformMatrix);for(var o=0;o<e.positions.length;o+=3)this._tempVector3.fromArray(e.positions,o),V.TransformCoordinatesToRef(this._tempVector3,this._transformMatrix,this._tempVector3),this._tempVector3.toArray(e.positions,o),e.normals&&(this._tempVector3.fromArray(e.normals,o),V.TransformNormalToRef(this._tempVector3,this._scalingRotationMatrix,this._tempVector3),this._tempVector3.toArray(e.normals,o));n.push(e)},e.prototype._instantiateWithMatrix=function(e,t,i){for(var r=0;r<e.positions.length;r+=3)this._tempVector3.fromArray(e.positions,r),V.TransformCoordinatesToRef(this._tempVector3,t,this._tempVector3),this._tempVector3.toArray(e.positions,r),e.normals&&(this._tempVector3.fromArray(e.normals,r),V.TransformNormalToRef(this._tempVector3,t,this._tempVector3),this._tempVector3.toArray(e.normals,r));i.push(e)},e.prototype._instantiateWithPositionAndMatrix=function(e,t,i,r){z.TranslationToRef(t.x,t.y,t.z,this._positionMatrix),i.multiplyToRef(this._positionMatrix,this._transformMatrix);for(var n=0;n<e.positions.length;n+=3)this._tempVector3.fromArray(e.positions,n),V.TransformCoordinatesToRef(this._tempVector3,this._transformMatrix,this._tempVector3),this._tempVector3.toArray(e.positions,n),e.normals&&(this._tempVector3.fromArray(e.normals,n),V.TransformNormalToRef(this._tempVector3,this._transformMatrix,this._tempVector3),this._tempVector3.toArray(e.normals,n));r.push(e)},e}(),tS=function(e){function t(t,i){void 0===i&&(i=GE.AutoDetect);var r=e.call(this,t)||this;return r._type=GE.Undefined,r._contextualSource=qE.None,r.min=0,r.max=0,r.groupInInspector="",r.onValueChangedObservable=new f,r._type=i,r._isInput=!0,r.setDefaultValue(),r.registerOutput("output",i),r}return m(t,e),Object.defineProperty(t.prototype,"type",{get:function(){if(this._type===GE.AutoDetect&&null!=this.value){if(!isNaN(this.value))return this._type=GE.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=GE.Vector2,this._type;case"Vector3":return this._type=GE.Vector3,this._type;case"Vector4":return this._type=GE.Vector4,this._type;case"Matrix":return this._type=GE.Matrix,this._type}}return this._type},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isContextual",{get:function(){return this._contextualSource!==qE.None},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"contextualValue",{get:function(){return this._contextualSource},set:function(e){switch(this._contextualSource=e,e){case qE.Positions:case qE.Normals:this._type=GE.Vector3;break;case qE.Colors:case qE.Tangents:this._type=GE.Vector4;break;case qE.UV:case qE.UV2:case qE.UV3:case qE.UV4:case qE.UV5:case qE.UV6:this._type=GE.Vector2;break;case qE.VertexID:case qE.GeometryID:case qE.CollectionID:case qE.FaceID:case qE.LoopID:case qE.InstanceID:this._type=GE.Int}this.output&&(this.output.type=this._type)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"value",{get:function(){return this._storedValue},set:function(e){this.type===GE.Float&&this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e)),this._storedValue=e,this.onValueChangedObservable.notifyObservers(this)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"valueCallback",{get:function(){return this._valueCallback},set:function(e){this._valueCallback=e},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"GeometryInputBlock"},Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.setDefaultValue=function(){switch(this.contextualValue=qE.None,this.type){case GE.Int:case GE.Float:this.value=0;break;case GE.Vector2:this.value=U.Zero();break;case GE.Vector3:this.value=V.Zero();break;case GE.Vector4:this.value=k.Zero();break;case GE.Matrix:this.value=z.Identity()}},t.prototype._buildBlock=function(t){var i=this;e.prototype._buildBlock.call(this,t),this.isContextual?(this.output._storedValue=null,this.output._storedFunction=function(e){return e.getContextualValue(i._contextualSource)}):(this.output._storedFunction=null,this.output._storedValue=this.value)},t.prototype.dispose=function(){this.onValueChangedObservable.clear(),e.prototype.dispose.call(this)},t.prototype._dumpPropertiesCode=function(){var t=this._codeVariableName;if(this.isContextual)return e.prototype._dumpPropertiesCode.call(this)+"".concat(t,".contextualValue = BABYLON.NodeGeometryContextualSources.").concat(qE[this._contextualSource],";\n");var i=[],r="";switch(this.type){case GE.Float:case GE.Int:r="".concat(this.value);break;case GE.Vector2:r="new BABYLON.Vector2(".concat(this.value.x,", ").concat(this.value.y,")");break;case GE.Vector3:r="new BABYLON.Vector3(".concat(this.value.x,", ").concat(this.value.y,", ").concat(this.value.z,")");break;case GE.Vector4:r="new BABYLON.Vector4(".concat(this.value.x,", ").concat(this.value.y,", ").concat(this.value.z,", ").concat(this.value.w,")")}return i.push("".concat(t,".value = ").concat(r)),this.type!==GE.Float&&this.type!==GE.Int||i.push("".concat(t,".min = ").concat(this.min),"".concat(t,".max = ").concat(this.max)),i.push(""),e.prototype._dumpPropertiesCode.call(this)+i.join(";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.type=this.type,t.contextualValue=this.contextualValue,t.min=this.min,t.max=this.max,t.groupInInspector=this.groupInInspector,null===this._storedValue||this.isContextual||(this._storedValue.asArray?(t.valueType="BABYLON."+this._storedValue.getClassName(),t.value=this._storedValue.asArray()):(t.valueType="number",t.value=this._storedValue)),t},t.prototype._deserialize=function(t){if(e.prototype._deserialize.call(this,t),this._type=t.type,this.contextualValue=t.contextualValue,this.min=t.min||0,this.max=t.max||0,this.groupInInspector=t.groupInInspector||"",t.valueType)if("number"===t.valueType)this._storedValue=t.value;else{var i=s(t.valueType);i&&(this._storedValue=i.FromArray(t.value))}},t}(JE);a("BABYLON.GeometryInputBlock",tS);var iS=function(e){function t(t){var i=e.call(this,t)||this;return i.evaluateContext=!1,i.registerInput("size",GE.Float,!0,1),i.registerInput("width",GE.Float,!0,0),i.registerInput("height",GE.Float,!0,0),i.registerInput("depth",GE.Float,!0,0),i.registerInput("subdivisions",GE.Int,!0,1),i.registerInput("subdivisionsX",GE.Int,!0,0),i.registerInput("subdivisionsY",GE.Int,!0,0),i.registerInput("subdivisionsZ",GE.Int,!0,0),i.registerOutput("geometry",GE.Geometry),i}return m(t,e),t.prototype.getClassName=function(){return"BoxBlock"},Object.defineProperty(t.prototype,"size",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"width",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"height",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"depth",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subdivisions",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subdivisionsX",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subdivisionsY",{get:function(){return this._inputs[6]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subdivisionsZ",{get:function(){return this._inputs[7]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected&&!this.depth.isConnected){var e=new tS("Size");return e.value=1,void e.output.connectTo(this.size)}if(!this.width.isConnected){var t=new tS("Width");t.value=1,t.output.connectTo(this.width)}if(!this.height.isConnected){var i=new tS("Height");i.value=1,i.output.connectTo(this.height)}if(!this.depth.isConnected){var r=new tS("Depth");r.value=1,r.output.connectTo(this.depth)}}},t.prototype._buildBlock=function(e){var t=this,i={},r=function(e){i.size=t.size.getConnectedValue(e),i.width=t.width.getConnectedValue(e),i.height=t.height.getConnectedValue(e),i.depth=t.depth.getConnectedValue(e);var r=t.subdivisions.getConnectedValue(e),n=t.subdivisionsX.getConnectedValue(e),o=t.subdivisionsY.getConnectedValue(e),a=t.subdivisionsZ.getConnectedValue(e);return r&&(i.segments=r),n&&(i.widthSegments=n),o&&(i.heightSegments=o),a&&(i.depthSegments=a),Bh(i)};if(this.evaluateContext)this.geometry._storedFunction=r;else{var n=r(e);this.geometry._storedFunction=function(){return t.geometry._executionCount=1,n.clone()}}},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.evaluateContext=t.evaluateContext},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),t}(JE);a("BABYLON.BoxBlock",iS);var rS=function(){function e(t){this._buildId=e._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new f,this.outputBlock=null,this.name=t}return e.prototype._getGlobalNodeGeometryEditor=function(){return"undefined"!=typeof NODEGEOMETRYEDITOR?NODEGEOMETRYEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeGeometryEditor?BABYLON:void 0},Object.defineProperty(e.prototype,"buildExecutionTime",{get:function(){return this._buildExecutionTime},enumerable:!1,configurable:!0}),e.prototype.getClassName=function(){return"NodeGeometry"},e.prototype.getBlockByName=function(e){for(var t=null,i=0,r=this.attachedBlocks;i<r.length;i++){var n=r[i];if(n.name===e){if(t)return rr.Warn("More than one block was found with the name `"+e+"`"),t;t=n}}return t},e.prototype.getBlockByPredicate=function(e){for(var t=0,i=this.attachedBlocks;t<i.length;t++){var r=i[t];if(e(r))return r}return null},e.prototype.getInputBlocks=function(){for(var e=[],t=0,i=this.attachedBlocks;t<i.length;t++){var r=i[t];r.isInput&&e.push(r)}return e},e.prototype.edit=function(t){var i=this;return new Promise((function(r){if(i.BJSNODEGEOMETRYEDITOR=i.BJSNODEGEOMETRYEDITOR||i._getGlobalNodeGeometryEditor(),void 0===i.BJSNODEGEOMETRYEDITOR){var n=t&&t.editorURL?t.editorURL:e.EditorURL;rr.LoadBabylonScript(n,(function(){i.BJSNODEGEOMETRYEDITOR=i.BJSNODEGEOMETRYEDITOR||i._getGlobalNodeGeometryEditor(),i._createNodeEditor(null==t?void 0:t.nodeGeometryEditorConfig),r()}))}else i._createNodeEditor(null==t?void 0:t.nodeGeometryEditorConfig),r()}))},e.prototype._createNodeEditor=function(e){var t=g({nodeGeometry:this},e);this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(t)},e.prototype.build=function(t,i,r){if(void 0===t&&(t=!1),void 0===i&&(i=!0),void 0===r&&(r=!1),this._buildWasSuccessful=!1,!this.outputBlock)throw"You must define the outputBlock property before building the geometry";var n=_t.Now;this._initializeBlock(this.outputBlock,r);var o=new eS;o.buildId=this._buildId,o.verbose=t,this.outputBlock.build(o),i&&(this._buildId=e._BuildIdGenerator++),this._buildExecutionTime=_t.Now-n,o.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=o.vertexData,this.onBuildObservable.notifyObservers(this)},e.prototype.createMesh=function(e,t){if(void 0===t&&(t=null),this._buildWasSuccessful||this.build(),!this._vertexData)return null;var i=new Fa(e,t);return this._vertexData.applyToMesh(i),i._internalMetadata=i._internalMetadata||{},i._internalMetadata.nodeGeometry=this,i},e.prototype.updateMesh=function(e){return this._buildWasSuccessful||this.build(),!!this._vertexData&&(this._vertexData.applyToMesh(e),e._internalMetadata=e._internalMetadata||{},e._internalMetadata.nodeGeometry=this,e)},e.prototype._initializeBlock=function(e,t){void 0===t&&(t=!0),e.initialize(),t&&e.autoConfigure(),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)&&this.attachedBlocks.push(e);for(var i=0,r=e.inputs;i<r.length;i++){var n=r[i].connectedPoint;if(n){var o=n.ownerBlock;o!==e&&this._initializeBlock(o,t)}}},e.prototype.clear=function(){this.outputBlock=null,this.attachedBlocks.length=0},e.prototype.removeBlock=function(e){var t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e===this.outputBlock&&(this.outputBlock=null)},e.prototype.parseSerializedObject=function(e,t){void 0===t&&(t=!1),t||this.clear();for(var i={},r=0,n=e.blocks;r<n.length;r++){var o=s((p=n[r]).customType);o&&((f=new o)._deserialize(p),i[p.id]=f,this.attachedBlocks.push(f))}for(var a=0,l=this.attachedBlocks;a<l.length;a++)if((f=l[a]).isTeleportOut){var c=f,u=c._tempEntryPointUniqueId;if(u){var h=i[u];h&&h.attachToEndpoint(c)}}for(var d=0;d<e.blocks.length;d++){var p,f;(f=i[(p=e.blocks[d]).id])&&(f.inputs.length&&p.inputs.some((function(e){return e.targetConnectionName}))&&!t||this._restoreConnections(f,e,i))}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){for(var _=e.locations||e.editorData.locations,m=0,g=_;m<g.length;m++){var v=g[m];i[v.blockId]&&(v.blockId=i[v.blockId].uniqueId)}t&&this.editorData&&this.editorData.locations&&_.concat(this.editorData.locations),e.locations?this.editorData={locations:_}:(this.editorData=e.editorData,this.editorData.locations=_);var y=[];for(var b in i)y[b]=i[b].uniqueId;this.editorData.map=y}this.comment=e.comment},e.prototype._restoreConnections=function(e,t,i){for(var r=0,n=e.outputs;r<n.length;r++)for(var o=n[r],a=0,s=t.blocks;a<s.length;a++){var l=s[a],c=i[l.id];if(c)for(var u=0,h=l.inputs;u<h.length;u++){var d=h[u];if(i[d.targetBlockId]!==e||d.targetConnectionName!==o.name);else{var p=c.getInputByName(d.inputName);if(!p||p.isConnected)continue;o.connectTo(p,!0),this._restoreConnections(c,t,i)}}}},e.prototype.generateCode=function(){var e=[],t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);for(var r='let nodeGeometry = new BABYLON.NodeGeometry("'.concat(this.name||"node geometry",'");\n'),n=0,o=t;n<o.length;n++){var a=o[n];a.isInput&&-1===e.indexOf(a)&&(r+=a._dumpCode(i,e))}return this.outputBlock&&(e=[],r+="// Connections\n",r+=this.outputBlock._dumpCodeForOutputConnections(e),r+="// Output nodes\n",r+="nodeGeometry.outputBlock = ".concat(this.outputBlock._codeVariableName,";\n"),r+="nodeGeometry.build();\n"),r},e.prototype._gatherBlocks=function(e,t){if(-1===t.indexOf(e)){t.push(e);for(var i=0,r=e.inputs;i<r.length;i++){var n=r[i].connectedPoint;n&&(o=n.ownerBlock)!==e&&this._gatherBlocks(o,t)}var o;e.isTeleportOut&&(o=e).entryPoint&&this._gatherBlocks(o.entryPoint,t)}},e.prototype.setToDefault=function(){this.clear(),this.editorData=null;var e=new iS("Box");e.autoConfigure();var t=new $E("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t},e.prototype.clone=function(t){var i=this.serialize(),r=Ke.Clone((function(){return new e(t)}),this);return r.name=t,r.parseSerializedObject(i),r._buildId=this._buildId,r.build(!1),r},e.prototype.serialize=function(e){var t=e?{}:Ke.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));var i=[];e?i=e:(t.customType="BABYLON.NodeGeometry",this.outputBlock&&(t.outputNodeId=this.outputBlock.uniqueId)),t.blocks=[];for(var r=0,n=i;r<n.length;r++){var o=n[r];t.blocks.push(o.serialize())}if(!e)for(var a=0,s=this.attachedBlocks;a<s.length;a++)o=s[a],-1===i.indexOf(o)&&t.blocks.push(o.serialize());return t},e.prototype.dispose=function(){for(var e=0,t=this.attachedBlocks;e<t.length;e++)t[e].dispose();this.attachedBlocks.length=0,this.onBuildObservable.clear()},e.CreateDefault=function(t){var i=new e(t);return i.setToDefault(),i.build(),i},e.Parse=function(t){var i=Ke.Parse((function(){return new e(t.name)}),t,null);return i.parseSerializedObject(t),i.build(),i},e.ParseFromSnippetAsync=function(t,i,r){var n=this;return void 0===r&&(r=!1),"_BLANK"===t?Promise.resolve(e.CreateDefault("blank")):new Promise((function(o,a){var s=new Je;s.addEventListener("readystatechange",(function(){if(4==s.readyState)if(200==s.status){var n=JSON.parse(JSON.parse(s.responseText).jsonPayload),l=JSON.parse(n.nodeGeometry);i||(i=Ke.Parse((function(){return new e(t)}),l,null)),i.parseSerializedObject(l),i.snippetId=t;try{r||i.build(),o(i)}catch(e){a(e)}}else a("Unable to load the snippet "+t)})),s.open("GET",n.SnippetUrl+"/"+t.replace(/#/g,"/")),s.send()}))},e._BuildIdGenerator=0,e.EditorURL="".concat(rr._DefaultCdnUrl,"/v").concat(Do.Version,"/nodeGeometryEditor/babylon.nodeGeometryEditor.js"),e.SnippetUrl=u.SnippetUrl,v([Ie()],e.prototype,"name",void 0),v([Ie("comment")],e.prototype,"comment",void 0),e}(),nS=function(e){function t(t){var i=e.call(this,t)||this;return i.evaluateContext=!0,i.epsilon=A,i.registerInput("geometry",GE.Geometry),i.registerOutput("output",GE.Geometry),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryOptimizeBlock"},Object.defineProperty(t.prototype,"geometry",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(e){var t=this,i=function(e){if(!t.geometry.isConnected)return null;for(var i=t.geometry.getConnectedValue(e),r=[],n={},o=0;o<i.positions.length;o+=3){for(var a=i.positions[o],s=i.positions[o+1],l=i.positions[o+2],c=!1,u=0;u<r.length;u+=3)j.WithinEpsilon(a,r[u],t.epsilon)&&j.WithinEpsilon(s,r[u+1],t.epsilon)&&j.WithinEpsilon(l,r[u+2],t.epsilon)&&(n[o/3]=u/3,c=!0);c||(n[o/3]=r.length/3,r.push(a,s,l))}var h=new _o;return h.positions=r,h.indices=i.indices.map((function(e){return n[e]})),h};this.evaluateContext?this.output._storedFunction=i:(this.output._storedFunction=null,this.output._storedValue=i(e))},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")+"".concat(this._codeVariableName,".epsilon = ").concat(this.epsilon,";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t.epsilon=this.epsilon,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.evaluateContext=t.evaluateContext,this.epsilon=t.epsilon},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),v([Ys("Epsilon",Xs.Float,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"epsilon",void 0),t}(JE);a("BABYLON.GeometryOptimizeBlock",nS);var oS=function(e){function t(t){var i=e.call(this,t)||this;return i.evaluateContext=!1,i.registerInput("size",GE.Float,!0,1),i.registerInput("width",GE.Float,!0,0),i.registerInput("height",GE.Float,!0,0),i.registerOutput("geometry",GE.Geometry),i}return m(t,e),t.prototype.getClassName=function(){return"PlaneBlock"},Object.defineProperty(t.prototype,"size",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"width",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"height",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected){var e=new tS("Size");return e.value=1,void e.output.connectTo(this.size)}if(!this.width.isConnected){var t=new tS("Width");t.value=1,t.output.connectTo(this.width)}if(!this.height.isConnected){var i=new tS("Height");i.value=1,i.output.connectTo(this.height)}}},t.prototype._buildBlock=function(e){var t=this,i={},r=function(e){return i.size=t.size.getConnectedValue(e),i.width=t.width.getConnectedValue(e),i.height=t.height.getConnectedValue(e),ps(i)};if(this.evaluateContext)this.geometry._storedFunction=r;else{var n=r(e);this.geometry._storedFunction=function(){return t.geometry._executionCount=1,n.clone()}}},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.evaluateContext=t.evaluateContext},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),t}(JE);a("BABYLON.PlaneBlock",oS);var aS=function(e){function t(t){var i=e.call(this,t)||this;return i._cachedVertexData=null,i.reverseWindingOrder=!1,i.serializedCachedData=!1,i.registerOutput("geometry",GE.Geometry),i}return m(t,e),Object.defineProperty(t.prototype,"mesh",{get:function(){return this._mesh},set:function(e){this._mesh=e},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"MeshBlock"},Object.defineProperty(t.prototype,"isUsingCachedData",{get:function(){return!this.mesh&&!!this._cachedVertexData},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.cleanData=function(){this._mesh=null,this._cachedVertexData=null},t.prototype._buildBlock=function(){if(this._mesh){var e=_o.ExtractFromMesh(this._mesh,!1,!0);if(this._cachedVertexData=null,this.reverseWindingOrder&&e.indices)for(var t=0;t<e.indices.length;t+=3){var i=e.indices[t];e.indices[t]=e.indices[t+2],e.indices[t+2]=i}this.geometry._storedFunction=function(){return e.clone()}}else this._cachedVertexData?this.geometry._storedValue=this._cachedVertexData.clone():this.geometry._storedValue=null},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.serializedCachedData=this.serializedCachedData,this.serializedCachedData&&(this._mesh?t.cachedVertexData=_o.ExtractFromMesh(this._mesh,!1,!0).serialize():this._cachedVertexData&&(t.cachedVertexData=this._cachedVertexData.serialize())),t.reverseWindingOrder=this.reverseWindingOrder,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),t.cachedVertexData&&(this._cachedVertexData=_o.Parse(t.cachedVertexData)),this.serializedCachedData=!!t.serializedCachedData,this.reverseWindingOrder=t.reverseWindingOrder},v([Ys("Serialize cached data",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"serializedCachedData",void 0),t}(JE);a("BABYLON.MeshBlock",aS);var sS=function(e){function t(t){var i=e.call(this,t)||this;return i.evaluateContext=!1,i.registerInput("radius",GE.Float,!0,1),i.registerInput("radiusX",GE.Float,!0,0),i.registerInput("radiusY",GE.Float,!0,0),i.registerInput("radiusZ",GE.Float,!0,0),i.registerInput("subdivisions",GE.Int,!0,4),i.registerOutput("geometry",GE.Geometry),i}return m(t,e),t.prototype.getClassName=function(){return"IcoSphereBlock"},Object.defineProperty(t.prototype,"radius",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"radiusX",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"radiusY",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"radiusZ",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subdivisions",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(){if(!this.radius.isConnected){var e=new tS("Radius");e.value=.2,e.output.connectTo(this.radius)}},t.prototype._buildBlock=function(e){var t=this,i={},r=function(e){return i.radius=t.radius.getConnectedValue(e),i.subdivisions=t.subdivisions.getConnectedValue(e),i.radiusX=t.radiusX.getConnectedValue(e),i.radiusY=t.radiusY.getConnectedValue(e),i.radiusZ=t.radiusZ.getConnectedValue(e),wl(i)};if(this.evaluateContext)this.geometry._storedFunction=r;else{var n=r(e);this.geometry._storedFunction=function(){return t.geometry._executionCount=1,n.clone()}}},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.evaluateContext=t.evaluateContext},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),t}(JE);a("BABYLON.IcoSphereBlock",sS);var lS=function(e){function t(t){var i=e.call(this,t)||this;return i.evaluateContext=!1,i.registerInput("segments",GE.Int,!0,32),i.registerInput("diameter",GE.Float,!0,1),i.registerInput("diameterX",GE.Float,!0,0),i.registerInput("diameterY",GE.Float,!0,0),i.registerInput("diameterZ",GE.Float,!0,0),i.registerInput("arc",GE.Float,!0,1),i.registerInput("slice",GE.Float,!0,1),i.registerOutput("geometry",GE.Geometry),i}return m(t,e),t.prototype.getClassName=function(){return"SphereBlock"},Object.defineProperty(t.prototype,"segments",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"diameter",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"diameterX",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"diameterY",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"diameterZ",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"arc",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"slice",{get:function(){return this._inputs[6]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(){if(!this.diameter.isConnected){var e=new tS("Diameter");e.value=1,e.output.connectTo(this.diameter)}},t.prototype._buildBlock=function(e){var t=this,i={},r=function(e){return i.segments=t.segments.getConnectedValue(e),i.diameter=t.diameter.getConnectedValue(e),i.diameterX=t.diameterX.getConnectedValue(e),i.diameterY=t.diameterY.getConnectedValue(e),i.diameterZ=t.diameterZ.getConnectedValue(e),i.arc=t.arc.getConnectedValue(e),i.slice=t.slice.getConnectedValue(e),kh(i)};if(this.evaluateContext)this.geometry._storedFunction=r;else{var n=r(e);this.geometry._storedFunction=function(){return t.geometry._executionCount=1,n.clone()}}},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.evaluateContext=t.evaluateContext},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),t}(JE);a("BABYLON.SphereBlock",lS);var cS=function(e){function t(t){var i=e.call(this,t)||this;return i.evaluateContext=!1,i.registerInput("width",GE.Float,!0,1),i.registerInput("height",GE.Float,!0,1),i.registerInput("subdivisions",GE.Int,!0,1),i.registerInput("subdivisionsX",GE.Int,!0,0),i.registerInput("subdivisionsY",GE.Int,!0,0),i.registerOutput("geometry",GE.Geometry),i}return m(t,e),t.prototype.getClassName=function(){return"GridBlock"},Object.defineProperty(t.prototype,"width",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"height",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subdivisions",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subdivisionsX",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subdivisionsY",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(){if(!this.width.isConnected){var e=new tS("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){var t=new tS("Height");t.value=1,t.output.connectTo(this.height)}},t.prototype._buildBlock=function(e){var t=this,i={},r=function(e){return i.width=t.width.getConnectedValue(e),i.height=t.height.getConnectedValue(e),i.subdivisions=t.subdivisions.getConnectedValue(e),i.subdivisionsX=t.subdivisionsX.getConnectedValue(e),i.subdivisionsY=t.subdivisionsY.getConnectedValue(e),$u(i)};if(this.evaluateContext)this.geometry._storedFunction=r;else{var n=r(e);this.geometry._storedFunction=function(){return t.geometry._executionCount=1,n.clone()}}},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.evaluateContext=t.evaluateContext},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),t}(JE);a("BABYLON.GridBlock",cS);var uS=function(e){function t(t){var i=e.call(this,t)||this;return i.evaluateContext=!1,i.registerInput("diameter",GE.Float,!0,1),i.registerInput("thickness",GE.Float,!0,.5),i.registerInput("tessellation",GE.Int,!0,16),i.registerOutput("geometry",GE.Geometry),i}return m(t,e),t.prototype.getClassName=function(){return"TorusBlock"},Object.defineProperty(t.prototype,"diameter",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"thickness",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"tessellation",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(){if(!this.diameter.isConnected){var e=new tS("Diameter");e.value=1,e.output.connectTo(this.diameter)}},t.prototype._buildBlock=function(e){var t=this,i={},r=function(e){return i.thickness=t.thickness.getConnectedValue(e),i.diameter=t.diameter.getConnectedValue(e),i.tessellation=t.tessellation.getConnectedValue(e),ah(i)};if(this.evaluateContext)this.geometry._storedFunction=r;else{var n=r(e);this.geometry._storedFunction=function(){return t.geometry._executionCount=1,n.clone()}}},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.evaluateContext=t.evaluateContext},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),t}(JE);a("BABYLON.TorusBlock",uS);var hS=function(e){function t(t){var i=e.call(this,t)||this;return i.evaluateContext=!1,i.registerInput("height",GE.Float,!0,25),i.registerInput("diameter",GE.Float,!0,1),i.registerInput("diameterTop",GE.Float,!0,-1),i.registerInput("diameterBottom",GE.Float,!0,-1),i.registerInput("subdivisions",GE.Int,!0,1),i.registerInput("tessellation",GE.Int,!0,24),i.registerInput("arc",GE.Float,!0,1),i.registerOutput("geometry",GE.Geometry),i}return m(t,e),t.prototype.getClassName=function(){return"CylinderBlock"},Object.defineProperty(t.prototype,"height",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"diameter",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"diameterTop",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"diameterBottom",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subdivisions",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"tessellation",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"arc",{get:function(){return this._inputs[6]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(){if(!this.diameter.isConnected){var e=new tS("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){var t=new tS("Height");t.value=1,t.output.connectTo(this.height)}},t.prototype._buildBlock=function(e){var t=this,i={},r=function(e){return i.height=t.height.getConnectedValue(e),i.diameter=t.diameter.getConnectedValue(e),i.diameterTop=t.diameterTop.getConnectedValue(e),i.diameterBottom=t.diameterBottom.getConnectedValue(e),-1===i.diameterTop&&(i.diameterTop=i.diameter),-1===i.diameterBottom&&(i.diameterBottom=i.diameter),i.tessellation=t.tessellation.getConnectedValue(e),i.subdivisions=t.subdivisions.getConnectedValue(e),i.arc=t.arc.getConnectedValue(e),Sh(i)};if(this.evaluateContext)this.geometry._storedFunction=r;else{var n=r(e);this.geometry._storedFunction=function(){return t.geometry._executionCount=1,n.clone()}}},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.evaluateContext=t.evaluateContext},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),t}(JE);a("BABYLON.CylinderBlock",hS);var dS=function(e){function t(t){var i=e.call(this,t)||this;return i.evaluateContext=!1,i.registerInput("height",GE.Float,!0,1),i.registerInput("radius",GE.Float,!0,.25),i.registerInput("tessellation",GE.Int,!0,16),i.registerInput("subdivisions",GE.Int,!0,2),i.registerOutput("geometry",GE.Geometry),i}return m(t,e),t.prototype.getClassName=function(){return"CapsuleBlock"},Object.defineProperty(t.prototype,"height",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"radius",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"tessellation",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"subdivisions",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(){if(!this.height.isConnected){var e=new tS("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){var t=new tS("Radius");t.value=.2,t.output.connectTo(this.radius)}},t.prototype._buildBlock=function(e){var t=this,i={},r=function(e){return i.height=t.height.getConnectedValue(e),i.radius=t.radius.getConnectedValue(e),i.tessellation=t.tessellation.getConnectedValue(e),i.subdivisions=t.subdivisions.getConnectedValue(e),Wh(i)};if(this.evaluateContext)this.geometry._storedFunction=r;else{var n=r(e);this.geometry._storedFunction=function(){return t.geometry._executionCount=1,n.clone()}}},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.evaluateContext=t.evaluateContext},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),t}(JE);a("BABYLON.CapsuleBlock",dS);var pS=function(e){function t(t){var i=e.call(this,t)||this;return i.evaluateContext=!1,i.registerInput("radius",GE.Float,!0,.5),i.registerInput("tessellation",GE.Int,!0,64),i.registerInput("arc",GE.Float,!0,1),i.registerOutput("geometry",GE.Geometry),i}return m(t,e),t.prototype.getClassName=function(){return"DiscBlock"},Object.defineProperty(t.prototype,"radius",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"tessellation",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"arc",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(){if(!this.radius.isConnected){var e=new tS("Radius");e.value=.2,e.output.connectTo(this.radius)}},t.prototype._buildBlock=function(e){var t=this,i={},r=function(e){return i.radius=t.radius.getConnectedValue(e),i.tessellation=t.tessellation.getConnectedValue(e),i.arc=t.arc.getConnectedValue(e),Qh(i)};if(this.evaluateContext)this.geometry._storedFunction=r;else{var n=r(e);this.geometry._storedFunction=function(){return t.geometry._executionCount=1,n.clone()}}},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.evaluateContext=t.evaluateContext},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),t}(JE);a("BABYLON.DiscBlock",pS);var fS=function(e){function t(t){var i=e.call(this,t)||this;return i.registerOutput("geometry",GE.Geometry),i}return m(t,e),t.prototype.getClassName=function(){return"NullBlock"},Object.defineProperty(t.prototype,"geometry",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){this.geometry._storedValue=null},t}(JE);a("BABYLON.NullBlock",fS);var _S=function(e){function t(t){var i=e.call(this,t)||this;return i.evaluateContext=!0,i.registerInput("geometry",GE.Geometry),i.registerInput("positions",GE.Vector3),i.registerOutput("output",GE.Geometry),i}return m(t,e),t.prototype.getExecutionIndex=function(){return this._currentIndex},t.prototype.getExecutionLoopIndex=function(){return this._currentIndex},t.prototype.getExecutionFaceIndex=function(){return 0},t.prototype.getClassName=function(){return"SetPositionsBlock"},Object.defineProperty(t.prototype,"geometry",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"positions",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(e){var t=this,i=function(e){if(e.pushExecutionContext(t),t._vertexData=t.geometry.getConnectedValue(e),t._vertexData&&(t._vertexData=t._vertexData.clone()),e.pushGeometryContext(t._vertexData),!t._vertexData||!t._vertexData.positions||!t.positions.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(t.output._storedValue=null);var i=t._vertexData.positions.length/3;for(t._currentIndex=0;t._currentIndex<i;t._currentIndex++){var r=t.positions.getConnectedValue(e);r&&r.toArray(t._vertexData.positions,3*t._currentIndex)}return e.restoreGeometryContext(),e.restoreExecutionContext(),t._vertexData};this.evaluateContext?this.output._storedFunction=i:(this.output._storedFunction=null,this.output._storedValue=i(e))},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),void 0!==t.evaluateContext&&(this.evaluateContext=t.evaluateContext)},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),t}(JE);a("BABYLON.SetPositionsBlock",_S);var mS=function(e){function t(t){var i=e.call(this,t)||this;return i.evaluateContext=!0,i.registerInput("geometry",GE.Geometry),i.registerInput("normals",GE.Vector3),i.registerOutput("output",GE.Geometry),i}return m(t,e),t.prototype.getExecutionIndex=function(){return this._currentIndex},t.prototype.getExecutionLoopIndex=function(){return this._currentIndex},t.prototype.getExecutionFaceIndex=function(){return 0},t.prototype.getClassName=function(){return"SetNormalsBlock"},Object.defineProperty(t.prototype,"geometry",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"normals",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(e){var t=this,i=function(e){if(e.pushExecutionContext(t),t._vertexData=t.geometry.getConnectedValue(e),t._vertexData&&(t._vertexData=t._vertexData.clone()),e.pushGeometryContext(t._vertexData),!t._vertexData||!t._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(t.output._storedValue=null);if(!t.normals.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(t.output._storedValue=t._vertexData);t._vertexData.normals||(t._vertexData.normals=[]);var i=t._vertexData.positions.length/3;for(t._currentIndex=0;t._currentIndex<i;t._currentIndex++){var r=t.normals.getConnectedValue(e);r&&r.toArray(t._vertexData.normals,3*t._currentIndex)}return e.restoreGeometryContext(),e.restoreExecutionContext(),t._vertexData};this.evaluateContext?this.output._storedFunction=i:(this.output._storedFunction=null,this.output._storedValue=i(e))},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),void 0!==t.evaluateContext&&(this.evaluateContext=t.evaluateContext)},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),t}(JE);a("BABYLON.SetNormalsBlock",mS);var gS=function(e){function t(t){var i=e.call(this,t)||this;return i.evaluateContext=!0,i.textureCoordinateIndex=0,i.registerInput("geometry",GE.Geometry),i.registerInput("uvs",GE.Vector2),i.registerOutput("output",GE.Geometry),i}return m(t,e),t.prototype.getExecutionIndex=function(){return this._currentIndex},t.prototype.getExecutionLoopIndex=function(){return this._currentIndex},t.prototype.getExecutionFaceIndex=function(){return 0},t.prototype.getClassName=function(){return"SetUVsBlock"},Object.defineProperty(t.prototype,"geometry",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"uvs",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(e){var t=this,i=function(e){if(e.pushExecutionContext(t),t._vertexData=t.geometry.getConnectedValue(e),t._vertexData&&(t._vertexData=t._vertexData.clone()),e.pushGeometryContext(t._vertexData),!t._vertexData||!t._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(t.output._storedValue=null);if(!t.uvs.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(t.output._storedValue=t._vertexData);var i=[],r=t._vertexData.positions.length/3;for(t._currentIndex=0;t._currentIndex<r;t._currentIndex++){var n=t.uvs.getConnectedValue(e);n&&n.toArray(i,2*t._currentIndex)}switch(t.textureCoordinateIndex){case 0:t._vertexData.uvs=i;break;case 1:t._vertexData.uvs2=i;break;case 2:t._vertexData.uvs3=i;break;case 3:t._vertexData.uvs4=i;break;case 4:t._vertexData.uvs5=i;break;case 5:t._vertexData.uvs6=i}return e.restoreGeometryContext(),e.restoreExecutionContext(),t._vertexData};this.evaluateContext?this.output._storedFunction=i:(this.output._storedFunction=null,this.output._storedValue=i(e))},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".textureCoordinateIndex};\n")+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t.textureCoordinateIndex=this.textureCoordinateIndex,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.textureCoordinateIndex=t.textureCoordinateIndex,void 0!==t.evaluateContext&&(this.evaluateContext=t.evaluateContext)},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),v([Ys("Texture coordinates index",Xs.List,"ADVANCED",{notifiers:{update:!0},options:[{label:"UV1",value:0},{label:"UV2",value:1},{label:"UV3",value:2},{label:"UV4",value:3},{label:"UV5",value:4},{label:"UV6",value:5}]})],t.prototype,"textureCoordinateIndex",void 0),t}(JE);a("BABYLON.SetUVsBlock",gS);var vS=function(e){function t(t){var i=e.call(this,t)||this;return i.evaluateContext=!0,i.registerInput("geometry",GE.Geometry),i.registerInput("colors",GE.AutoDetect),i.registerOutput("output",GE.Geometry),i._inputs[1].excludedConnectionPointTypes.push(GE.Int),i._inputs[1].excludedConnectionPointTypes.push(GE.Float),i._inputs[1].excludedConnectionPointTypes.push(GE.Vector2),i._inputs[1].excludedConnectionPointTypes.push(GE.Texture),i._inputs[1].excludedConnectionPointTypes.push(GE.Texture),i}return m(t,e),t.prototype.getExecutionIndex=function(){return this._currentIndex},t.prototype.getExecutionLoopIndex=function(){return this._currentIndex},t.prototype.getExecutionFaceIndex=function(){return 0},t.prototype.getClassName=function(){return"SetColorsBlock"},Object.defineProperty(t.prototype,"geometry",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"colors",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(e){var t=this,i=function(e){var i;if(e.pushExecutionContext(t),t._vertexData=t.geometry.getConnectedValue(e),t._vertexData&&(t._vertexData=t._vertexData.clone()),e.pushGeometryContext(t._vertexData),!t._vertexData||!t._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(t.output._storedValue=null);if(!t.colors.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(t.output._storedValue=t._vertexData);t._vertexData.colors||(t._vertexData.colors=[]);var r=t._vertexData.positions.length/3;for(t._currentIndex=0;t._currentIndex<r;t._currentIndex++)if((null===(i=t.colors.connectedPoint)||void 0===i?void 0:i.type)===GE.Vector3){var n=t.colors.getConnectedValue(e);n&&(n.toArray(t._vertexData.colors,4*t._currentIndex),t._vertexData.colors[4*t._currentIndex+3]=1,t._vertexData.hasVertexAlpha=!1)}else{var o=t.colors.getConnectedValue(e);o&&(o.toArray(t._vertexData.colors,4*t._currentIndex),t._vertexData.hasVertexAlpha=!0)}return e.restoreGeometryContext(),e.restoreExecutionContext(),t._vertexData};this.evaluateContext?this.output._storedFunction=i:(this.output._storedFunction=null,this.output._storedValue=i(e))},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),void 0!==t.evaluateContext&&(this.evaluateContext=t.evaluateContext)},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),t}(JE);a("BABYLON.SetColorsBlock",vS);var yS,bS=function(e){function t(t){var i=e.call(this,t)||this;return i.evaluateContext=!0,i.registerInput("geometry",GE.Geometry),i.registerInput("tangents",GE.Vector4),i.registerOutput("output",GE.Geometry),i}return m(t,e),t.prototype.getExecutionIndex=function(){return this._currentIndex},t.prototype.getExecutionLoopIndex=function(){return this._currentIndex},t.prototype.getExecutionFaceIndex=function(){return 0},t.prototype.getClassName=function(){return"SetTangentsBlock"},Object.defineProperty(t.prototype,"geometry",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"tangents",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(e){var t=this,i=function(e){if(e.pushExecutionContext(t),t._vertexData=t.geometry.getConnectedValue(e),t._vertexData&&(t._vertexData=t._vertexData.clone()),e.pushGeometryContext(t._vertexData),!t._vertexData||!t._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(t.output._storedValue=null);if(!t.tangents.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(t.output._storedValue=t._vertexData);t._vertexData.tangents||(t._vertexData.tangents=[]);var i=t._vertexData.positions.length/3;for(t._currentIndex=0;t._currentIndex<i;t._currentIndex++){var r=t.tangents.getConnectedValue(e);r&&r.toArray(t._vertexData.tangents,4*t._currentIndex)}return e.restoreGeometryContext(),e.restoreExecutionContext(),t._vertexData};this.evaluateContext?this.output._storedFunction=i:(this.output._storedFunction=null,this.output._storedValue=i(e))},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),void 0!==t.evaluateContext&&(this.evaluateContext=t.evaluateContext)},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),t}(JE);a("BABYLON.SetTangentsBlock",bS),function(e){e[e.Add=0]="Add",e[e.Subtract=1]="Subtract",e[e.Multiply=2]="Multiply",e[e.Divide=3]="Divide",e[e.Max=4]="Max",e[e.Min=5]="Min"}(yS||(yS={}));var TS=function(e){function t(t){var i,r,n=e.call(this,t)||this;n.operation=yS.Add,n.registerInput("left",GE.AutoDetect),n.registerInput("right",GE.AutoDetect),n.registerOutput("output",GE.BasedOnInput),n.output._typeConnectionSource=n.left;var o=[GE.Matrix,GE.Geometry,GE.Texture];return(i=n.left.excludedConnectionPointTypes).push.apply(i,o),(r=n.right.excludedConnectionPointTypes).push.apply(r,o),n._linkConnectionTypes(0,1),n._connectionObservers=[n.left.onConnectionObservable.add((function(){return n._updateInputOutputTypes()})),n.left.onDisconnectionObservable.add((function(){return n._updateInputOutputTypes()})),n.right.onConnectionObservable.add((function(){return n._updateInputOutputTypes()})),n.right.onDisconnectionObservable.add((function(){return n._updateInputOutputTypes()}))],n}return m(t,e),t.prototype.getClassName=function(){return"MathBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e,t,i,r=this.left,n=this.right;if(!r.isConnected||!n.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);var o=r.type===GE.Float||r.type===GE.Int,a=n.type===GE.Float||n.type===GE.Int,s=o&&a;switch(this.operation){case yS.Add:i=s?function(e){return r.getConnectedValue(e)+n.getConnectedValue(e)}:o?function(e){return e.adapt(r,n.type).add(n.getConnectedValue(e))}:function(e){return r.getConnectedValue(e).add(e.adapt(n,r.type))};break;case yS.Subtract:i=s?function(e){return r.getConnectedValue(e)-n.getConnectedValue(e)}:o?function(e){return e.adapt(r,n.type).subtract(n.getConnectedValue(e))}:function(e){return r.getConnectedValue(e).subtract(e.adapt(n,r.type))};break;case yS.Multiply:i=s?function(e){return r.getConnectedValue(e)*n.getConnectedValue(e)}:o?function(e){return e.adapt(r,n.type).multiply(n.getConnectedValue(e))}:function(e){return r.getConnectedValue(e).multiply(e.adapt(n,r.type))};break;case yS.Divide:i=s?function(e){return r.getConnectedValue(e)/n.getConnectedValue(e)}:o?function(e){return e.adapt(r,n.type).divide(n.getConnectedValue(e))}:function(e){return r.getConnectedValue(e).divide(e.adapt(n,r.type))};break;case yS.Min:if(s)i=function(e){return Math.min(r.getConnectedValue(e),n.getConnectedValue(e))};else{var l=(e=o?[n,r]:[r,n])[0],c=e[1];switch(l.type){case GE.Vector2:i=function(e){return U.Minimize(l.getConnectedValue(e),e.adapt(c,l.type))};break;case GE.Vector3:i=function(e){return V.Minimize(l.getConnectedValue(e),e.adapt(c,l.type))};break;case GE.Vector4:i=function(e){return k.Minimize(l.getConnectedValue(e),e.adapt(c,l.type))}}}break;case yS.Max:if(!s){var u=(t=o?[n,r]:[r,n])[0],h=t[1];switch(u.type){case GE.Vector2:i=function(e){return U.Maximize(u.getConnectedValue(e),e.adapt(h,u.type))};break;case GE.Vector3:i=function(e){return V.Maximize(u.getConnectedValue(e),e.adapt(h,u.type))};break;case GE.Vector4:i=function(e){return k.Maximize(u.getConnectedValue(e),e.adapt(h,u.type))}}break}i=function(e){return Math.max(r.getConnectedValue(e),n.getConnectedValue(e))}}this.output._storedFunction=function(e){return r.type===GE.Int?0|i(e):i(e)}},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".operation = BABYLON.MathBlockOperations.").concat(yS[this.operation],";\n")},t.prototype._updateInputOutputTypes=function(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===GE.Int||this.left.type===GE.Float&&this.right.type!==GE.Int)&&(this.output._typeConnectionSource=this.right):this.left.isConnected!==this.right.isConnected&&(this.output._typeConnectionSource=this.left.isConnected?this.left:this.right),this.left.isConnected||this.right.isConnected)for(var e=0,t=[[this.left,this.right],[this.right,this.left]];e<t.length;e++){var i=t[e],r=i[0],n=i[1];r.acceptedConnectionPointTypes=[GE.Int,GE.Float],n.isConnected&&(r.acceptedConnectionPointTypes.push(n.type),n.type!==GE.Int&&n.type!==GE.Float||r.acceptedConnectionPointTypes.push(GE.Vector2,GE.Vector3,GE.Vector4))}},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._connectionObservers.forEach((function(e){return e.remove()})),this._connectionObservers.length=0},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.operation=this.operation,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.operation=t.operation},v([Ys("Operation",Xs.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:yS.Add},{label:"Subtract",value:yS.Subtract},{label:"Multiply",value:yS.Multiply},{label:"Divide",value:yS.Divide},{label:"Max",value:yS.Max},{label:"Min",value:yS.Min}]})],t.prototype,"operation",void 0),t}(JE);a("BABYLON.MathBlock",TS);var ES,SS=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("value",GE.AutoDetect),i.registerInput("fromMin",GE.Float,!0,0),i.registerInput("fromMax",GE.Float,!0,1),i.registerInput("toMin",GE.Float,!0,0),i.registerInput("toMax",GE.Float,!0,1),i.registerOutput("output",GE.BasedOnInput),i._inputs[0].excludedConnectionPointTypes.push(GE.Vector2),i._inputs[0].excludedConnectionPointTypes.push(GE.Vector3),i._inputs[0].excludedConnectionPointTypes.push(GE.Vector4),i._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),i._inputs[0].excludedConnectionPointTypes.push(GE.Texture),i._outputs[0]._typeConnectionSource=i._inputs[0],i}return m(t,e),t.prototype.getClassName=function(){return"MapRangeBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"fromMin",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"fromMax",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"toMin",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"toMax",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);this.output._storedFunction=function(t){var i=e.value.getConnectedValue(t),r=e.fromMin.getConnectedValue(t),n=e.fromMax.getConnectedValue(t),o=e.toMin.getConnectedValue(t),a=(i-r)/(n-r)*(e.toMax.getConnectedValue(t)-o)+o;return e.output.type===GE.Int?Math.floor(a):a}},t}(JE);a("BABYLON.MapRangeBlock",SS),function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(ES||(ES={}));var xS,AS=function(e){function t(t){var i=e.call(this,t)||this;return i.test=ES.Equal,i.registerInput("left",GE.Float),i.registerInput("right",GE.Float,!0,0),i.registerInput("ifTrue",GE.AutoDetect,!0,1),i.registerInput("ifFalse",GE.AutoDetect,!0,0),i.registerOutput("output",GE.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[2],i._outputs[0]._defaultConnectionPointType=GE.Float,i._inputs[0].acceptedConnectionPointTypes.push(GE.Int),i._inputs[1].acceptedConnectionPointTypes.push(GE.Int),i._linkConnectionTypes(2,3),i}return m(t,e),t.prototype.getClassName=function(){return"ConditionBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"ifTrue",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"ifFalse",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;if(!this.left.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);this.output._storedFunction=function(t){return function(t){var i=e.left.getConnectedValue(t),r=e.right.getConnectedValue(t),n=!1;switch(e.test){case ES.Equal:n=j.WithinEpsilon(i,r,A);break;case ES.NotEqual:n=i!==r;break;case ES.LessThan:n=i<r;break;case ES.GreaterThan:n=i>r;break;case ES.LessOrEqual:n=i<=r;break;case ES.GreaterOrEqual:n=i>=r;break;case ES.Xor:n=!!i&&!r||!i&&!!r;break;case ES.Or:n=!!i||!!r;break;case ES.And:n=!!i&&!!r}return n}(t)?e.ifTrue.getConnectedValue(t):e.ifFalse.getConnectedValue(t)}},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".test = BABYLON.ConditionBlockTests.").concat(ES[this.test],";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.test=this.test,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.test=t.test},v([Ys("Test",Xs.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:ES.Equal},{label:"NotEqual",value:ES.NotEqual},{label:"LessThan",value:ES.LessThan},{label:"GreaterThan",value:ES.GreaterThan},{label:"LessOrEqual",value:ES.LessOrEqual},{label:"GreaterOrEqual",value:ES.GreaterOrEqual},{label:"Xor",value:ES.Xor},{label:"Or",value:ES.Or},{label:"And",value:ES.And}]})],t.prototype,"test",void 0),t}(JE);a("BABYLON.ConditionBlock",AS),function(e){e[e.None=0]="None",e[e.LoopID=1]="LoopID",e[e.InstanceID=2]="InstanceID"}(xS||(xS={}));var CS=function(e){function t(t){var i=e.call(this,t)||this;return i._currentLockId=-1,i.lockMode=xS.None,i.registerInput("min",GE.AutoDetect),i.registerInput("max",GE.AutoDetect),i.registerOutput("output",GE.BasedOnInput),i._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),i._inputs[0].excludedConnectionPointTypes.push(GE.Texture),i._inputs[1].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[1].excludedConnectionPointTypes.push(GE.Geometry),i._inputs[1].excludedConnectionPointTypes.push(GE.Texture),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i}return m(t,e),t.prototype.getClassName=function(){return"RandomBlock"},Object.defineProperty(t.prototype,"min",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"max",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(){if(!this.min.isConnected){var e=new tS("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){var t=new tS("Max");t.value=1,t.output.connectTo(this.max)}},t.prototype._buildBlock=function(){var e=this,t=null;switch(this._currentLockId=-1,this.min.type){case GE.Int:case GE.Float:t=function(t){var i=e.min.getConnectedValue(t)||0,r=e.max.getConnectedValue(t)||0;return i+Math.random()*(r-i)};break;case GE.Vector2:t=function(t){var i=e.min.getConnectedValue(t)||U.Zero(),r=e.max.getConnectedValue(t)||U.Zero();return new U(i.x+Math.random()*(r.x-i.x),i.y+Math.random()*(r.y-i.y))};break;case GE.Vector3:t=function(t){var i=e.min.getConnectedValue(t)||V.Zero(),r=e.max.getConnectedValue(t)||V.Zero();return new V(i.x+Math.random()*(r.x-i.x),i.y+Math.random()*(r.y-i.y),i.z+Math.random()*(r.z-i.z))};break;case GE.Vector4:t=function(t){var i=e.min.getConnectedValue(t)||k.Zero(),r=e.max.getConnectedValue(t)||k.Zero();return new k(i.x+Math.random()*(r.x-i.x),i.y+Math.random()*(r.y-i.y),i.z+Math.random()*(r.z-i.z),i.w+Math.random()*(r.w-i.w))}}this.lockMode!==xS.None&&t?this.output._storedFunction=function(i){var r=0;switch(e.lockMode){case xS.InstanceID:r=i.getContextualValue(qE.InstanceID,!0)||0;break;case xS.LoopID:r=i.getContextualValue(qE.LoopID,!0)||0}return e._currentLockId===r&&e.lockMode!==xS.None||(e._currentLockId=r,e.output._storedValue=t(i)),e.output._storedValue}:this.output._storedFunction=t},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".lockMode = BABYLON.RandomBlockLocks.").concat(xS[this.lockMode],";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.lockMode=this.lockMode,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.lockMode=t.lockMode},v([Ys("LockMode",Xs.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"None",value:xS.None},{label:"LoopID",value:xS.LoopID},{label:"InstanceID",value:xS.InstanceID}]})],t.prototype,"lockMode",void 0),t}(JE);a("BABYLON.RandomBlock",CS);var RS=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("offset",GE.Vector3,!0,V.Zero()),i.registerInput("scale",GE.Float,!0,1),i.registerInput("octaves",GE.Float,!0,2,0,16),i.registerInput("roughness",GE.Float,!0,.5,0,1),i.registerOutput("output",GE.Float),i}return m(t,e),t.prototype.getClassName=function(){return"NoiseBlock"},Object.defineProperty(t.prototype,"offset",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scale",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"octaves",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"roughness",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._negateIf=function(e,t){return 0!==t?-e:e},t.prototype._noiseGrad=function(e,t,i,r){var n=15&e,o=n<8?t:i,a=n<4?i:12===n||14==n?t:r;return this._negateIf(o,n&o)+this._negateIf(a,2&n)},t.prototype._fade=function(e){return e*e*e*(e*(6*e-15)+10)},t.prototype._hashBitRotate=function(e,t){return e<<t|e>>32-t},t.prototype._hash=function(e,t,i){var r,n,o;return r=n=o=3735928584,o+=i,r+=e,o^=n+=t,r^=o-=this._hashBitRotate(n,14),n^=r-=this._hashBitRotate(o,11),o^=n-=this._hashBitRotate(r,25),r^=o-=this._hashBitRotate(n,16),n^=r-=this._hashBitRotate(o,4),(o^=n-=this._hashBitRotate(r,14))-this._hashBitRotate(n,24)},t.prototype._mix=function(e,t,i,r,n,o,a,s,l,c,u){var h=1-l,d=1-c;return(1-u)*(d*(e*h+t*l)+c*(i*h+r*l))+u*(d*(n*h+o*l)+c*(a*h+s*l))},t.prototype._perlinNoise=function(e){var t=(0|e.x)-(e.x<0?1:0),i=(0|e.y)-(e.y<0?1:0),r=(0|e.z)-(e.z<0?1:0),n=e.x-t,o=e.y-i,a=e.z-r,s=this._fade(n),l=this._fade(o),c=this._fade(a);return this._mix(this._noiseGrad(this._hash(t,i,r),n,o,a),this._noiseGrad(this._hash(t+1,i,r),n-1,o,a),this._noiseGrad(this._hash(t,i+1,r),n,o-1,a),this._noiseGrad(this._hash(t+1,i+1,r),n-1,o-1,a),this._noiseGrad(this._hash(t,i,r+1),n,o,a-1),this._noiseGrad(this._hash(t+1,i,r+1),n-1,o,a-1),this._noiseGrad(this._hash(t,i+1,r+1),n,o-1,a-1),this._noiseGrad(this._hash(t+1,i+1,r+1),n-1,o-1,a-1),s,l,c)},t.prototype._perlinSigned=function(e){return.982*this._perlinNoise(e)},t.prototype._perlin=function(e){return this._perlinSigned(e)/2+.5},t.prototype.noise=function(e,t,i,r,n){for(var o=new V(i.x*n+r.x,i.y*n+r.y,i.z*n+r.z),a=1,s=1,l=0,c=0,u=0|(e=j.Clamp(e,0,15)),h=0;h<=u;h++)c+=this._perlin(o.scale(a))*s,l+=s,s*=j.Clamp(t,0,1),a*=2;var d=e-Math.floor(e);if(0==d)return c/l;var p=c+this._perlin(o.scale(a))*s;return(1-d)*(c/=l)+d*(p/(l+s))},t.prototype._buildBlock=function(){var e=this;this.output._storedFunction=function(t){var i=t.getContextualValue(qE.Positions),r=e.octaves.getConnectedValue(t),n=e.roughness.getConnectedValue(t),o=e.offset.getConnectedValue(t),a=e.scale.getConnectedValue(t);return e.noise(r,n,i,o,a)}},t}(JE);a("BABYLON.NoiseBlock",RS);var PS=function(e){function t(t){var i=e.call(this,t)||this;return i.evaluateContext=!1,i.registerInput("geometry0",GE.Geometry),i.registerInput("geometry1",GE.Geometry,!0),i.registerInput("geometry2",GE.Geometry,!0),i.registerInput("geometry3",GE.Geometry,!0),i.registerInput("geometry4",GE.Geometry,!0),i.registerOutput("output",GE.Geometry),i}return m(t,e),t.prototype.getClassName=function(){return"MergeGeometryBlock"},Object.defineProperty(t.prototype,"geometry0",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry1",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry2",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry3",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry4",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(e){var t=this,i=function(e){var i,r=t.geometry0.getConnectedValue(e),n=[];return r?(r=r.clone(),t.geometry1.isConnected&&(i=t.geometry1.getConnectedValue(e))&&n.push(i),t.geometry2.isConnected&&(i=t.geometry2.getConnectedValue(e))&&n.push(i),t.geometry3.isConnected&&(i=t.geometry3.getConnectedValue(e))&&n.push(i),t.geometry4.isConnected&&(i=t.geometry4.getConnectedValue(e))&&n.push(i),n.length&&r&&(r=r.merge(n,!0,!1,!0,!0)),r):null};this.evaluateContext?this.output._storedFunction=i:(this.output._storedFunction=null,this.output._storedValue=i(e))},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.evaluateContext=t.evaluateContext},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),t}(JE);a("BABYLON.MergeGeometryBlock",PS);var IS=function(e){function t(t){var i=e.call(this,t)||this;return i.evaluateContext=!0,i.registerInput("geometry0",GE.Geometry,!0),i.registerInput("geometry1",GE.Geometry,!0),i.registerInput("geometry2",GE.Geometry,!0),i.registerInput("geometry3",GE.Geometry,!0),i.registerInput("geometry4",GE.Geometry,!0),i.registerInput("geometry5",GE.Geometry,!0),i.registerInput("geometry6",GE.Geometry,!0),i.registerInput("geometry7",GE.Geometry,!0),i.registerInput("geometry8",GE.Geometry,!0),i.registerInput("geometry9",GE.Geometry,!0),i.registerOutput("output",GE.Geometry),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryCollectionBlock"},Object.defineProperty(t.prototype,"geometry0",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry1",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry2",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry3",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry4",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry5",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry6",{get:function(){return this._inputs[6]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry7",{get:function(){return this._inputs[7]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry8",{get:function(){return this._inputs[8]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry9",{get:function(){return this._inputs[9]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._storeGeometry=function(e,t,i,r){if(e.isConnected){var n=e.getConnectedValue(t);if(!n)return;n.metadata=n.metadata||{},n.metadata.collectionId=i,r.push(n)}},t.prototype._buildBlock=function(e){var t=this,i=function(e){var i=[];return t._storeGeometry(t.geometry0,e,0,i),t._storeGeometry(t.geometry1,e,1,i),t._storeGeometry(t.geometry2,e,2,i),t._storeGeometry(t.geometry3,e,3,i),t._storeGeometry(t.geometry4,e,4,i),t._storeGeometry(t.geometry5,e,5,i),t._storeGeometry(t.geometry6,e,6,i),t._storeGeometry(t.geometry7,e,7,i),t._storeGeometry(t.geometry8,e,8,i),t._storeGeometry(t.geometry9,e,9,i),i.length?i[Math.round(Math.random()*(i.length-1))]:null};this.evaluateContext?this.output._storedFunction=i:(this.output._storedFunction=null,this.output._storedValue=i(e))},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.evaluateContext=t.evaluateContext},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),t}(JE);a("BABYLON.GeometryCollectionBlock",IS);var MS=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("input",GE.AutoDetect),i.registerOutput("output",GE.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i}return m(t,e),Object.defineProperty(t.prototype,"buildExecutionTime",{get:function(){return 0},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"GeometryElbowBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],r=this._inputs[0];i._storedFunction=function(e){return r.getConnectedValue(e)}},t}(JE);a("BABYLON.GeometryElbowBlock",MS);var OS=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("geometry",GE.Geometry),i.registerOutput("output",GE.Geometry),i}return m(t,e),t.prototype.getClassName=function(){return"ComputeNormalsBlock"},Object.defineProperty(t.prototype,"geometry",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;this.output._storedFunction=function(t){if(!e.geometry.isConnected)return null;var i=e.geometry.getConnectedValue(t);return i.normals||(i.normals=[]),_o.ComputeNormals(i.positions,i.indices,i.normals),i}},t}(JE);a("BABYLON.ComputeNormalsBlock",OS);var DS=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("xyzw ",GE.Vector4,!0),i.registerInput("xyz ",GE.Vector3,!0),i.registerInput("xy ",GE.Vector2,!0),i.registerInput("zw ",GE.Vector2,!0),i.registerInput("x ",GE.Float,!0),i.registerInput("y ",GE.Float,!0),i.registerInput("z ",GE.Float,!0),i.registerInput("w ",GE.Float,!0),i.registerOutput("xyzw",GE.Vector4),i.registerOutput("xyz",GE.Vector3),i.registerOutput("xy",GE.Vector2),i.registerOutput("zw",GE.Vector2),i.registerOutput("x",GE.Float),i.registerOutput("y",GE.Float),i.registerOutput("z",GE.Float),i.registerOutput("w",GE.Float),i}return m(t,e),t.prototype.getClassName=function(){return"VectorConverterBlock"},Object.defineProperty(t.prototype,"xyzwIn",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xyzIn",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xyIn",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"zwIn",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xIn",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"yIn",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"zIn",{get:function(){return this._inputs[6]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"wIn",{get:function(){return this._inputs[7]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xyzwOut",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xyzOut",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xyOut",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"zwOut",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xOut",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"yOut",{get:function(){return this._outputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"zOut",{get:function(){return this._outputs[6]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"wOut",{get:function(){return this._outputs[7]},enumerable:!1,configurable:!0}),t.prototype._inputRename=function(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":"x "===e?"xIn":"y "===e?"yIn":"z "===e?"zIn":"w "===e?"wIn":e},t.prototype._outputRename=function(e){switch(e){case"x":return"xOut";case"y":return"yOut";case"z":return"zOut";case"w":return"wOut";case"xy":return"xyOut";case"zw":return"zwOut";case"xyz":return"xyzOut";case"xyzw":return"xyzwOut";default:return e}},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this.xIn,r=this.yIn,n=this.zIn,o=this.wIn,a=this.xyIn,s=this.zwIn,l=this.xyzIn,c=this.xyzwIn,u=this.xyzwOut,h=this.xyzOut,d=this.xyOut,p=this.zwOut,f=this.xOut,_=this.yOut,m=this.zOut,g=this.wOut,v=function(e){if(c.isConnected)return c.getConnectedValue(e);var t,u=0,h=0,d=0,p=0;return i.isConnected&&(u=i.getConnectedValue(e)),r.isConnected&&(h=r.getConnectedValue(e)),n.isConnected&&(d=n.getConnectedValue(e)),o.isConnected&&(p=o.getConnectedValue(e)),a.isConnected&&(t=a.getConnectedValue(e))&&(u=t.x,h=t.y),s.isConnected&&(t=s.getConnectedValue(e))&&(d=t.x,p=t.y),l.isConnected&&(t=l.getConnectedValue(e))&&(u=t.x,h=t.y,d=t.z),new k(u,h,d,p)};u._storedFunction=function(e){return v(e)},h._storedFunction=function(e){var t=v(e);return new V(t.x,t.y,t.z)},d._storedFunction=function(e){var t=v(e);return new U(t.x,t.y)},p._storedFunction=function(e){var t=v(e);return new U(t.z,t.w)},f._storedFunction=function(e){return v(e).x},_._storedFunction=function(e){return v(e).y},m._storedFunction=function(e){return v(e).z},g._storedFunction=function(e){return v(e).w}},t}(JE);a("BABYLON.VectorConverterBlock",DS);var NS=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("input",GE.AutoDetect),i.registerOutput("output",GE.BasedOnInput),i._inputs[0].excludedConnectionPointTypes.push(GE.Float),i._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),i._inputs[0].excludedConnectionPointTypes.push(GE.Texture),i._outputs[0]._typeConnectionSource=i._inputs[0],i}return m(t,e),t.prototype.getClassName=function(){return"NormalizeVectorBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){var i=this;e.prototype._buildBlock.call(this,t),this.output._storedFunction=null,this.input.isConnected?this.output._storedFunction=function(e){return i.input.getConnectedValue(e).normalize()}:this.output._storedValue=null},t}(JE);a("BABYLON.NormalizeVectorBlock",NS);var FS,LS=function(e){function t(t){var i=e.call(this,t)||this;return i.evaluateContext=!0,i.registerInput("geometry",GE.Geometry),i.registerInput("id",GE.Int,!0,0),i.registerOutput("output",GE.Geometry),i.id.acceptedConnectionPointTypes.push(GE.Float),i}return m(t,e),t.prototype.getClassName=function(){return"SetMaterialIDBlock"},Object.defineProperty(t.prototype,"geometry",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"id",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(e){var t=this;if(!this.geometry.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);var i=function(e){var i=t.geometry.getConnectedValue(e);if(!i||!i.indices||!i.positions)return i;var r=new fo;return r.materialIndex=0|t.id.getConnectedValue(e),r.indexStart=0,r.indexCount=i.indices.length,r.verticesStart=0,r.verticesCount=i.positions.length/3,i.materialInfos=[r],i};this.evaluateContext?this.output._storedFunction=i:(this.output._storedFunction=null,this.output._storedValue=i(e))},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),void 0!==t.evaluateContext&&(this.evaluateContext=t.evaluateContext)},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),t}(JE);a("BABYLON.SetMaterialIDBlock",LS),function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Round=4]="Round",e[e.Floor=5]="Floor",e[e.Ceiling=6]="Ceiling",e[e.Sqrt=7]="Sqrt",e[e.Log=8]="Log",e[e.Tan=9]="Tan",e[e.ArcTan=10]="ArcTan",e[e.ArcCos=11]="ArcCos",e[e.ArcSin=12]="ArcSin",e[e.Sign=13]="Sign",e[e.Negate=14]="Negate",e[e.OneMinus=15]="OneMinus",e[e.Reciprocal=16]="Reciprocal",e[e.ToDegrees=17]="ToDegrees",e[e.ToRadians=18]="ToRadians",e[e.Fract=19]="Fract",e[e.Exp2=20]="Exp2"}(FS||(FS={}));var wS=function(e){function t(t){var i=e.call(this,t)||this;return i.operation=FS.Cos,i.registerInput("input",GE.AutoDetect),i.registerOutput("output",GE.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),i._inputs[0].excludedConnectionPointTypes.push(GE.Texture),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryTrigonometryBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){var i=this;e.prototype._buildBlock.call(this,t);var r=null;switch(this.operation){case FS.Cos:r=function(e){return Math.cos(e)};break;case FS.Sin:r=function(e){return Math.sin(e)};break;case FS.Abs:r=function(e){return Math.abs(e)};break;case FS.Exp:r=function(e){return Math.exp(e)};break;case FS.Exp2:r=function(e){return Math.pow(2,e)};break;case FS.Round:r=function(e){return Math.round(e)};break;case FS.Floor:r=function(e){return Math.floor(e)};break;case FS.Ceiling:r=function(e){return Math.ceil(e)};break;case FS.Sqrt:r=function(e){return Math.sqrt(e)};break;case FS.Log:r=function(e){return Math.log(e)};break;case FS.Tan:r=function(e){return Math.tan(e)};break;case FS.ArcTan:r=function(e){return Math.atan(e)};break;case FS.ArcCos:r=function(e){return Math.acos(e)};break;case FS.ArcSin:r=function(e){return Math.asin(e)};break;case FS.Sign:r=function(e){return Math.sign(e)};break;case FS.Negate:r=function(e){return-e};break;case FS.OneMinus:r=function(e){return 1-e};break;case FS.Reciprocal:r=function(e){return 1/e};break;case FS.ToRadians:r=function(e){return e*Math.PI/180};break;case FS.ToDegrees:r=function(e){return 180*e/Math.PI};break;case FS.Fract:r=function(e){return e>=0?e-Math.floor(e):e-Math.ceil(e)}}if(!r)return this.output._storedFunction=null,void(this.output._storedValue=null);switch(this.input.type){case GE.Int:case GE.Float:this.output._storedFunction=function(e){var t=i.input.getConnectedValue(e);return r(t)};break;case GE.Vector2:this.output._storedFunction=function(e){var t=i.input.getConnectedValue(e);return new U(r(t.x),r(t.y))};break;case GE.Vector3:this.output._storedFunction=function(e){var t=i.input.getConnectedValue(e);return new V(r(t.x),r(t.y),r(t.z))};break;case GE.Vector4:this.output._storedFunction=function(e){var t=i.input.getConnectedValue(e);return new k(r(t.x),r(t.y),r(t.z),r(t.w))}}return this},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.operation=this.operation,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.operation=t.operation},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".operation = BABYLON.GeometryTrigonometryBlockOperations.").concat(FS[this.operation],";\n")},v([Ys("Operation",Xs.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:FS.Cos},{label:"Sin",value:FS.Sin},{label:"Abs",value:FS.Abs},{label:"Exp",value:FS.Exp},{label:"Exp2",value:FS.Exp2},{label:"Round",value:FS.Round},{label:"Floor",value:FS.Floor},{label:"Ceiling",value:FS.Ceiling},{label:"Sqrt",value:FS.Sqrt},{label:"Log",value:FS.Log},{label:"Tan",value:FS.Tan},{label:"ArcTan",value:FS.ArcTan},{label:"ArcCos",value:FS.ArcCos},{label:"ArcSin",value:FS.ArcSin},{label:"Sign",value:FS.Sign},{label:"Negate",value:FS.Negate},{label:"OneMinus",value:FS.OneMinus},{label:"Reciprocal",value:FS.Reciprocal},{label:"ToDegrees",value:FS.ToDegrees},{label:"ToRadians",value:FS.ToRadians},{label:"Fract",value:FS.Fract}]})],t.prototype,"operation",void 0),t}(JE);a("BABYLON.GeometryTrigonometryBlock",wS);var BS=function(e){function t(t){var i=e.call(this,t)||this;return i._rotationMatrix=new z,i._scalingMatrix=new z,i._translationMatrix=new z,i._scalingRotationMatrix=new z,i._transformMatrix=new z,i.evaluateContext=!0,i.registerInput("value",GE.AutoDetect),i.registerInput("matrix",GE.Matrix,!0),i.registerInput("translation",GE.Vector3,!0,V.Zero()),i.registerInput("rotation",GE.Vector3,!0,V.Zero()),i.registerInput("scaling",GE.Vector3,!0,V.One()),i.registerOutput("output",GE.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._inputs[0].excludedConnectionPointTypes.push(GE.Float),i._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[0].excludedConnectionPointTypes.push(GE.Texture),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryTransformBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"matrix",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"translation",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rotation",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scaling",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(e){var t=this;if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);var i=function(e){var i,r=t.value.getConnectedValue(e);if(!r)return null;if(t.matrix.isConnected)i=t.matrix.getConnectedValue(e);else{var n=t.scaling.getConnectedValue(e),o=t.rotation.getConnectedValue(e),a=t.translation.getConnectedValue(e);z.ScalingToRef(n.x,n.y,n.z,t._scalingMatrix),z.RotationYawPitchRollToRef(o.y,o.x,o.z,t._rotationMatrix),z.TranslationToRef(a.x,a.y,a.z,t._translationMatrix),t._scalingMatrix.multiplyToRef(t._rotationMatrix,t._scalingRotationMatrix),t._scalingRotationMatrix.multiplyToRef(t._translationMatrix,t._transformMatrix),i=t._transformMatrix}switch(t.value.type){case GE.Geometry:var s=r.clone();return s.transform(i),s;case GE.Vector2:return U.Transform(r,i);case GE.Vector3:return V.TransformCoordinates(r,i);case GE.Vector4:return k.TransformCoordinates(r,i)}return null};this.evaluateContext?this.output._storedFunction=i:(this.output._storedFunction=null,this.output._storedValue=i(e))},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),void 0!==t.evaluateContext&&(this.evaluateContext=t.evaluateContext)},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),t}(JE);a("BABYLON.GeometryTransformBlock",BS);var US=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("angle",GE.Float,!1,0),i.registerOutput("matrix",GE.Matrix),i}return m(t,e),t.prototype.getClassName=function(){return"RotationXBlock"},Object.defineProperty(t.prototype,"angle",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"matrix",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(){if(!this.angle.isConnected){var e=new tS("Angle");e.value=0,e.output.connectTo(this.angle)}},t.prototype._buildBlock=function(t){var i=this;e.prototype._buildBlock.call(this,t),this.matrix._storedFunction=function(e){return z.RotationX(i.angle.getConnectedValue(e))}},t}(JE);a("BABYLON.RotationXBlock",US);var VS=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("angle",GE.Float,!1,0),i.registerOutput("matrix",GE.Matrix),i}return m(t,e),t.prototype.getClassName=function(){return"RotationYBlock"},Object.defineProperty(t.prototype,"angle",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"matrix",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(){if(!this.angle.isConnected){var e=new tS("Angle");e.value=0,e.output.connectTo(this.angle)}},t.prototype._buildBlock=function(t){var i=this;e.prototype._buildBlock.call(this,t),this.matrix._storedFunction=function(e){return z.RotationY(i.angle.getConnectedValue(e))}},t}(JE);a("BABYLON.RotationYBlock",VS);var kS=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("angle",GE.Float,!1,0),i.registerOutput("matrix",GE.Matrix),i}return m(t,e),t.prototype.getClassName=function(){return"RotationZBlock"},Object.defineProperty(t.prototype,"angle",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"matrix",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(){if(!this.angle.isConnected){var e=new tS("Angle");e.value=0,e.output.connectTo(this.angle)}},t.prototype._buildBlock=function(t){var i=this;e.prototype._buildBlock.call(this,t),this.matrix._storedFunction=function(e){return z.RotationZ(i.angle.getConnectedValue(e))}},t}(JE);a("BABYLON.RotationZBlock",kS);var GS=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("scale",GE.Vector3,!1,V.One()),i.registerOutput("matrix",GE.Matrix),i}return m(t,e),t.prototype.getClassName=function(){return"ScalingBlock"},Object.defineProperty(t.prototype,"scale",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"matrix",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(){if(!this.scale.isConnected){var e=new tS("Scale");e.value=new V(1,1,1),e.output.connectTo(this.scale)}},t.prototype._buildBlock=function(t){var i=this;e.prototype._buildBlock.call(this,t),this.matrix._storedFunction=function(e){var t=i.scale.getConnectedValue(e);return z.Scaling(t.x,t.y,t.z)}},t}(JE);a("BABYLON.ScalingBlock",GS);var zS=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("source",GE.Vector3,!0,V.Up()),i.registerInput("target",GE.Vector3,!0,V.Left()),i.registerOutput("matrix",GE.Matrix),i}return m(t,e),t.prototype.getClassName=function(){return"AlignBlock"},Object.defineProperty(t.prototype,"source",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"target",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"matrix",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(t){var i=this;e.prototype._buildBlock.call(this,t),this.matrix._storedFunction=function(e){var t=i.source.getConnectedValue(e).clone(),r=i.target.getConnectedValue(e).clone(),n=new z;return t.normalize(),r.normalize(),z.RotationAlignToRef(t,r,n,!0),n}},t}(JE);a("BABYLON.AlignBlock",zS);var WS=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("translation",GE.Vector3,!1,V.Zero()),i.registerOutput("matrix",GE.Matrix),i}return m(t,e),t.prototype.getClassName=function(){return"TranslationBlock"},Object.defineProperty(t.prototype,"translation",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"matrix",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.autoConfigure=function(){if(!this.translation.isConnected){var e=new tS("Translation");e.value=new V(0,0,0),e.output.connectTo(this.translation)}},t.prototype._buildBlock=function(t){var i=this;e.prototype._buildBlock.call(this,t),this.matrix._storedFunction=function(e){var t=i.translation.getConnectedValue(e);return z.Translation(t.x,t.y,t.z)}},t}(JE);a("BABYLON.TranslationBlock",WS);var HS=function(e){function t(t){var i=e.call(this,t)||this;return i._indexTranslation=null,i.evaluateContext=!0,i.removeDuplicatedPositions=!0,i.registerInput("geometry",GE.Geometry),i.registerInput("instance",GE.Geometry,!0),i.registerInput("density",GE.Float,!0,1,0,1),i.registerInput("matrix",GE.Matrix,!0),i.registerInput("rotation",GE.Vector3,!0,V.Zero()),i.registerInput("scaling",GE.Vector3,!0,V.One()),i.scaling.acceptedConnectionPointTypes.push(GE.Float),i.registerOutput("output",GE.Geometry),i}return m(t,e),t.prototype.getInstanceIndex=function(){return this._currentLoopIndex},t.prototype.getExecutionIndex=function(){return this._indexTranslation?this._indexTranslation[this._currentIndex]:this._currentIndex},t.prototype.getExecutionLoopIndex=function(){return this._currentLoopIndex},t.prototype.getExecutionFaceIndex=function(){return 0},t.prototype.getClassName=function(){return"InstantiateOnVerticesBlock"},Object.defineProperty(t.prototype,"geometry",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"instance",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"density",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"matrix",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rotation",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scaling",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(e){var t=this,i=function(e){if(e.pushExecutionContext(t),e.pushInstancingContext(t),t._vertexData=t.geometry.getConnectedValue(e),e.pushGeometryContext(t._vertexData),!t._vertexData||!t._vertexData.positions||!t.instance.isConnected)return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(t.output._storedValue=null);var i=t._vertexData.positions.length/3,r=[],n=new V,o=[],a=t._vertexData.positions;if(t._currentLoopIndex=0,t.removeDuplicatedPositions){for(t._indexTranslation={},t._currentIndex=0;t._currentIndex<i;t._currentIndex++){for(var s=a[3*t._currentIndex],l=a[3*t._currentIndex+1],c=a[3*t._currentIndex+2],u=!1,h=0;h<o.length;h+=3)if(Math.abs(o[h]-s)<A&&Math.abs(o[h+1]-l)<A&&Math.abs(o[h+2]-c)<A){u=!0;break}u||(t._indexTranslation[o.length/3]=t._currentIndex,o.push(s,l,c))}i=(a=o).length/3}else t._indexTranslation=null;for(t._currentIndex=0;t._currentIndex<i;t._currentIndex++){var d=t.instance.getConnectedValue(e);if(d&&d.positions&&0!==d.positions.length){var p=t.density.getConnectedValue(e);if(!(p<1&&Math.random()>p)){n.fromArray(a,3*t._currentIndex);var f=d.clone();if(t.matrix.isConnected){var _=t.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(f,n,_,r)}else{var m=e.adaptInput(t.scaling,GE.Vector3,V.OneReadOnly),g=t.rotation.getConnectedValue(e)||V.ZeroReadOnly;e._instantiate(f,n,g,m,r)}t._currentLoopIndex++}}}if(e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),!r.length)return null;if(1===r.length)t._vertexData=r[0];else{var v=r.splice(0,1)[0];t._vertexData=v.merge(r,!0,!1,!0,!0)}return t._vertexData};this.evaluateContext?this.output._storedFunction=i:(this.output._storedFunction=null,this.output._storedValue=i(e))},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".removeDuplicatedPositions = ").concat(this.removeDuplicatedPositions?"true":"false",";\n")+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.removeDuplicatedPositions=this.removeDuplicatedPositions,t.evaluateContext=this.evaluateContext,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.removeDuplicatedPositions=t.removeDuplicatedPositions,void 0!==t.evaluateContext&&(this.evaluateContext=t.evaluateContext)},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),v([Ys("Remove duplicated positions",Xs.Boolean,"ADVANCED",{notifiers:{update:!0}})],t.prototype,"removeDuplicatedPositions",void 0),t}(JE);a("BABYLON.InstantiateOnVerticesBlock",HS);var XS=function(e){function t(t){var i=e.call(this,t)||this;return i._currentPosition=new V,i._currentUV=new U,i._vertex0=new V,i._vertex1=new V,i._vertex2=new V,i._tempVector0=new V,i._tempVector1=new V,i._uv0=new U,i._uv1=new U,i._uv2=new U,i.evaluateContext=!0,i.registerInput("geometry",GE.Geometry),i.registerInput("instance",GE.Geometry,!0),i.registerInput("count",GE.Int,!0,256),i.registerInput("matrix",GE.Matrix,!0),i.registerInput("rotation",GE.Vector3,!0,V.Zero()),i.registerInput("scaling",GE.Vector3,!0,V.One()),i.scaling.acceptedConnectionPointTypes.push(GE.Float),i.registerOutput("output",GE.Geometry),i}return m(t,e),t.prototype.getInstanceIndex=function(){return this._currentLoopIndex},t.prototype.getExecutionIndex=function(){return 0},t.prototype.getExecutionFaceIndex=function(){return this._currentFaceIndex},t.prototype.getExecutionLoopIndex=function(){return this._currentLoopIndex},t.prototype.getOverridePositionsContextualValue=function(){return this._currentPosition},t.prototype.getOverrideNormalsContextualValue=function(){return this._vertex1.subtractToRef(this._vertex0,this._tempVector0),this._vertex2.subtractToRef(this._vertex1,this._tempVector1),this._tempVector0.normalize(),this._tempVector1.normalize(),V.Cross(this._tempVector1,this._tempVector0)},t.prototype.getOverrideUVs1ContextualValue=function(){return this._currentUV},t.prototype.getClassName=function(){return"InstantiateOnFacesBlock"},Object.defineProperty(t.prototype,"geometry",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"instance",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"count",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"matrix",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rotation",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scaling",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(e){var t=this,i=function(e){if(e.pushExecutionContext(t),e.pushInstancingContext(t),t._vertexData=t.geometry.getConnectedValue(e),e.pushGeometryContext(t._vertexData),!(t._vertexData&&t._vertexData.positions&&t._vertexData.indices&&t.instance.isConnected))return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(t.output._storedValue=null);var i=null,r=t.count.getConnectedValue(e),n=t._vertexData.indices.length/3,o=r/n,a=0,s=[],l=0;for(t._currentLoopIndex=0,t._currentFaceIndex=0;t._currentFaceIndex<n;t._currentFaceIndex++){var c=(0|(a+=o))-l;if(!(c<1)){var u=t._vertexData.indices[3*t._currentFaceIndex],h=t._vertexData.indices[3*t._currentFaceIndex+1],d=t._vertexData.indices[3*t._currentFaceIndex+2];t._vertex0.fromArray(t._vertexData.positions,3*u),t._vertex1.fromArray(t._vertexData.positions,3*h),t._vertex2.fromArray(t._vertexData.positions,3*d),t._vertexData.uvs&&(t._uv0.fromArray(t._vertexData.uvs,2*u),t._uv1.fromArray(t._vertexData.uvs,2*h),t._uv2.fromArray(t._vertexData.uvs,2*d));for(var p=0;p<c&&!(l>=r);p++){var f=Math.random(),_=Math.random();if(f>_){var m=f;f=_,_=m}var g=f,v=_-f,y=1-g-v;if(t._currentPosition.set(g*t._vertex0.x+v*t._vertex1.x+y*t._vertex2.x,g*t._vertex0.y+v*t._vertex1.y+y*t._vertex2.y,g*t._vertex0.z+v*t._vertex1.z+y*t._vertex2.z),t._vertexData.uvs&&t._currentUV.set(g*t._uv0.x+v*t._uv1.x+y*t._uv2.x,g*t._uv0.y+v*t._uv1.y+y*t._uv2.y),(i=t.instance.getConnectedValue(e))&&i.positions&&0!==i.positions.length){var b=i.clone();if(t.matrix.isConnected){var T=t.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(b,t._currentPosition,T,s)}else{var E=e.adaptInput(t.scaling,GE.Vector3,V.OneReadOnly),S=t.rotation.getConnectedValue(e)||V.ZeroReadOnly;e._instantiate(b,t._currentPosition,S,E,s)}l++,t._currentLoopIndex++}else a-=o}}}if(s.length)if(1===s.length)t._vertexData=s[0];else{var x=s.splice(0,1)[0];t._vertexData=x.merge(s,!0,!1,!0,!0)}return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),t._vertexData};this.evaluateContext?this.output._storedFunction=i:(this.output._storedFunction=null,this.output._storedValue=i(e))},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),void 0!==t.evaluateContext&&(this.evaluateContext=t.evaluateContext)},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),t}(JE);a("BABYLON.InstantiateOnFacesBlock",XS);var jS=function(e){function t(t){var i=e.call(this,t)||this;return i._currentPosition=new V,i._vertex0=new V,i._vertex1=new V,i._vertex2=new V,i.evaluateContext=!0,i.registerInput("geometry",GE.Geometry),i.registerInput("instance",GE.Geometry,!0),i.registerInput("count",GE.Int,!0,256),i.registerInput("matrix",GE.Matrix,!0),i.registerInput("rotation",GE.Vector3,!0,V.Zero()),i.registerInput("scaling",GE.Vector3,!0,V.One()),i.scaling.acceptedConnectionPointTypes.push(GE.Float),i.registerOutput("output",GE.Geometry),i}return m(t,e),t.prototype.getInstanceIndex=function(){return this._currentLoopIndex},t.prototype.getExecutionIndex=function(){return 0},t.prototype.getExecutionFaceIndex=function(){return 0},t.prototype.getExecutionLoopIndex=function(){return this._currentLoopIndex},t.prototype.getOverridePositionsContextualValue=function(){return this._currentPosition},t.prototype.getClassName=function(){return"InstantiateOnVolumeBlock"},Object.defineProperty(t.prototype,"geometry",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"instance",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"count",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"matrix",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rotation",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scaling",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(e){var t=this,i=function(e){if(e.pushExecutionContext(t),e.pushInstancingContext(t),t._vertexData=t.geometry.getConnectedValue(e),e.pushGeometryContext(t._vertexData),!(t._vertexData&&t._vertexData.positions&&t._vertexData.indices&&t.instance.isConnected))return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(t.output._storedValue=null);var i=null,r=t.count.getConnectedValue(e),n=[],o=uo(t._vertexData.positions,0,t._vertexData.positions.length/3),a=o.minimum,s=o.maximum,l=new V(1,0,0),c=t._vertexData.indices.length/3;t._currentLoopIndex=0;for(var u=0;u<r;u++){t._currentPosition.set(Math.random()*(s.x-a.x)+a.x,Math.random()*(s.y-a.y)+a.y,Math.random()*(s.z-a.z)+a.z);for(var h=new hs(t._currentPosition,l),d=0,p=0;p<c;p++){t._vertex0.fromArray(t._vertexData.positions,3*t._vertexData.indices[3*p]),t._vertex1.fromArray(t._vertexData.positions,3*t._vertexData.indices[3*p+1]),t._vertex2.fromArray(t._vertexData.positions,3*t._vertexData.indices[3*p+2]);var f=h.intersectsTriangle(t._vertex0,t._vertex1,t._vertex2);f&&f.distance>0&&d++}if(d%2!=0){if((i=t.instance.getConnectedValue(e))&&i.positions&&0!==i.positions.length){var _=i.clone();if(t.matrix.isConnected){var m=t.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(_,t._currentPosition,m,n)}else{var g=e.adaptInput(t.scaling,GE.Vector3,V.OneReadOnly),v=t.rotation.getConnectedValue(e)||V.ZeroReadOnly;e._instantiate(_,t._currentPosition,v,g,n)}t._currentLoopIndex++}}else u--}if(n.length)if(1===n.length)t._vertexData=n[0];else{var y=n.splice(0,1)[0];t._vertexData=y.merge(n,!0,!1,!0,!0)}return e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),t._vertexData};this.evaluateContext?this.output._storedFunction=i:(this.output._storedFunction=null,this.output._storedValue=i(e))},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),void 0!==t.evaluateContext&&(this.evaluateContext=t.evaluateContext)},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),t}(JE);a("BABYLON.InstantiateOnVolumeBlock",jS);var YS=function(e){function t(t){var i=e.call(this,t)||this;return i.evaluateContext=!0,i.registerInput("instance",GE.Geometry,!0),i.registerInput("count",GE.Int,!0,1),i.registerOutput("output",GE.Geometry),i}return m(t,e),t.prototype.getInstanceIndex=function(){return this._currentIndex},t.prototype.getExecutionIndex=function(){return this._currentIndex},t.prototype.getExecutionLoopIndex=function(){return this._currentIndex},t.prototype.getExecutionFaceIndex=function(){return 0},t.prototype.getClassName=function(){return"InstantiateBaseBlock"},Object.defineProperty(t.prototype,"instance",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"count",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),void 0!==t.evaluateContext&&(this.evaluateContext=t.evaluateContext)},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),t}(JE),KS=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("matrix",GE.Matrix,!0),i.registerInput("position",GE.Vector3,!0,V.Zero()),i.registerInput("rotation",GE.Vector3,!0,V.Zero()),i.registerInput("scaling",GE.Vector3,!0,V.One()),i.scaling.acceptedConnectionPointTypes.push(GE.Float),i}return m(t,e),t.prototype.getInstanceIndex=function(){return this._currentIndex},t.prototype.getExecutionIndex=function(){return this._currentIndex},t.prototype.getExecutionLoopIndex=function(){return this._currentIndex},t.prototype.getExecutionFaceIndex=function(){return 0},t.prototype.getClassName=function(){return"InstantiateBlock"},Object.defineProperty(t.prototype,"matrix",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"position",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rotation",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scaling",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(e){var t=this,i=function(e){e.pushExecutionContext(t),e.pushInstancingContext(t);var i=t.count.getConnectedValue(e),r=[];for(t._currentIndex=0;t._currentIndex<i;t._currentIndex++){var n=t.instance.getConnectedValue(e);if(n&&n.positions&&0!==n.positions.length){var o=n.clone();if(t.matrix.isConnected){var a=t.matrix.getConnectedValue(e);e._instantiateWithMatrix(o,a,r)}else{var s=t.position.getConnectedValue(e)||V.ZeroReadOnly,l=e.adaptInput(t.scaling,GE.Vector3,V.OneReadOnly),c=t.rotation.getConnectedValue(e)||V.ZeroReadOnly;e._instantiate(o,s,c,l,r)}}}if(r.length)if(1===r.length)t._vertexData=r[0];else{var u=r.splice(0,1)[0];t._vertexData=u.merge(r,!0,!1,!0,!0)}return e.restoreExecutionContext(),e.restoreInstancingContext(),t._vertexData};this.evaluateContext?this.output._storedFunction=i:(this.output._storedFunction=null,this.output._storedValue=i(e))},t}(YS);a("BABYLON.InstantiateBlock",KS);var QS=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("direction",GE.Vector3,!0,new V(1,0,0)),i.registerInput("rotation",GE.Vector3,!0,new V(0,0,0)),i.registerInput("scaling",GE.Vector3,!0,new V(0,0,0)),i.scaling.acceptedConnectionPointTypes.push(GE.Float),i}return m(t,e),t.prototype.getClassName=function(){return"InstantiateLinearBlock"},Object.defineProperty(t.prototype,"direction",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rotation",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scaling",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(e){var t=this,i=function(e){e.pushExecutionContext(t),e.pushInstancingContext(t);var i=t.count.getConnectedValue(e),r=[],n=z.Identity(),o=V.Zero(),a=V.Zero(),s=V.Zero();for(t._currentIndex=0;t._currentIndex<i;t._currentIndex++){var l=t.instance.getConnectedValue(e);if(l&&l.positions&&0!==l.positions.length){var c=l.clone(),u=t.direction.getConnectedValue(e),h=t.rotation.getConnectedValue(e),d=e.adaptInput(t.scaling,GE.Vector3,V.OneReadOnly);o.copyFrom(u.clone().scale(t._currentIndex)),a.copyFrom(h.clone().scale(t._currentIndex)),s.copyFrom(d.clone().scale(t._currentIndex)),s.addInPlaceFromFloats(1,1,1),z.ComposeToRef(s,G.FromEulerAngles(a.x,a.y,a.z),o,n),e._instantiateWithMatrix(c,n,r)}}if(r.length)if(1===r.length)t._vertexData=r[0];else{var p=r.splice(0,1)[0];t._vertexData=p.merge(r,!0,!1,!0,!0)}return e.restoreExecutionContext(),e.restoreInstancingContext(),t._vertexData};this.evaluateContext?this.output._storedFunction=i:(this.output._storedFunction=null,this.output._storedValue=i(e))},t}(YS);a("BABYLON.InstantiateLinearBlock",QS);var qS=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("radius",GE.Int,!0,0,0),i.registerInput("angleStart",GE.Float,!0,0),i.registerInput("angleEnd",GE.Float,!0,2*Math.PI),i.registerInput("transform",GE.Vector3,!0,new V(0,0,0)),i.registerInput("rotation",GE.Vector3,!0,new V(0,0,0)),i.registerInput("scaling",GE.Vector3,!0,new V(0,0,0)),i.scaling.acceptedConnectionPointTypes.push(GE.Float),i}return m(t,e),t.prototype.getClassName=function(){return"InstantiateRadialBlock"},Object.defineProperty(t.prototype,"radius",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"angleStart",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"angleEnd",{get:function(){return this._inputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"transform",{get:function(){return this._inputs[5]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rotation",{get:function(){return this._inputs[6]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scaling",{get:function(){return this._inputs[7]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(e){var t=this,i=function(e){e.pushExecutionContext(t),e.pushInstancingContext(t);var i=t.count.getConnectedValue(e),r=[],n=z.Identity(),o=z.Identity(),a=z.Identity(),s=V.Zero(),l=V.Zero(),c=V.Zero();for(t._currentIndex=0;t._currentIndex<i;t._currentIndex++){var u=t.instance.getConnectedValue(e);if(u&&u.positions&&0!==u.positions.length){var h=u.clone(),d=t.radius.getConnectedValue(e),p=t.angleStart.getConnectedValue(e),f=t.angleEnd.getConnectedValue(e),_=t.transform.getConnectedValue(e),m=t.rotation.getConnectedValue(e),g=e.adaptInput(t.scaling,GE.Vector3,V.OneReadOnly),v=p+(f-p)/i*t._currentIndex,y=G.FromEulerAngles(0,v,0);s.copyFrom(_.clone().scale(t._currentIndex)),l.copyFrom(m.clone().scale(t._currentIndex)),c.copyFrom(g.clone().scale(t._currentIndex)),c.addInPlaceFromFloats(1,1,1),z.RotationYawPitchRollToRef(l.y,l.x,l.z,n),o.setTranslationFromFloats(0,0,d),z.ComposeToRef(c,y,s,a),n.multiplyToRef(o,o),o.multiplyToRef(a,a),e._instantiateWithMatrix(h,a,r)}}if(r.length)if(1===r.length)t._vertexData=r[0];else{var b=r.splice(0,1)[0];t._vertexData=b.merge(r,!0,!1,!0,!0)}return e.restoreExecutionContext(),e.restoreInstancingContext(),t._vertexData};this.evaluateContext?this.output._storedFunction=i:(this.output._storedFunction=null,this.output._storedValue=i(e))},t}(YS);a("BABYLON.InstantiateRadialBlock",qS);var ZS=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("float ",GE.Float,!0),i.registerInput("int ",GE.Int,!0),i.registerOutput("float",GE.Float),i.registerOutput("int",GE.Int),i}return m(t,e),t.prototype.getClassName=function(){return"IntFloatConverterBlock"},Object.defineProperty(t.prototype,"floatIn",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"intIn",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"floatOut",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"intOut",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),t.prototype._inputRename=function(e){return"float "===e?"floatIn":"int "===e?"intIn":e},t.prototype._buildBlock=function(){var e=this;this.floatOut._storedFunction=function(t){return e.floatIn.isConnected?e.floatIn.getConnectedValue(t):e.intIn.isConnected?e.intIn.getConnectedValue(t):0},this.intOut._storedFunction=function(t){return e.floatIn.isConnected?Math.floor(e.floatIn.getConnectedValue(t)):e.intIn.isConnected?Math.floor(e.intIn.getConnectedValue(t)):0}},t}(JE);a("BABYLON.IntFloatConverterBlock",ZS);var JS=function(e){function t(t){var i=e.call(this,t)||this;return i.log=[],i._isDebug=!0,i.registerInput("input",GE.AutoDetect),i.registerOutput("output",GE.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),i._inputs[0].excludedConnectionPointTypes.push(GE.Texture),i}return m(t,e),Object.defineProperty(t.prototype,"buildExecutionTime",{get:function(){return 0},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"DebugBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(e){var t=this;if(!this.input.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);this.log=[];var i=function(e){var i=t.input.getConnectedValue(e);if(null==i)return t.log.push(["null",""]),i;switch(t.input.type){case GE.Vector2:t.log.push([uE(i,4),i.toString()]);break;case GE.Vector3:t.log.push([hE(i,4),i.toString()]);break;case GE.Vector4:t.log.push([dE(i,4),i.toString()]);break;default:t.log.push([i.toString(),i.toString()])}return i};this.output.isConnected?this.output._storedFunction=i:this.output._storedValue=i(e)},t}(JE);a("BABYLON.DebugBlock",JS);var $S,ex=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("geometry",GE.Geometry),i.registerOutput("output",GE.Geometry),i.registerOutput("id",GE.Int),i.registerOutput("collectionId",GE.Int),i.registerOutput("verticesCount",GE.Int),i.registerOutput("facesCount",GE.Int),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryInfoBlock"},Object.defineProperty(t.prototype,"geometry",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"id",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"collectionId",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"verticesCount",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"facesCount",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;if(!this.geometry.isConnected)return this.id._storedValue=0,this.collectionId._storedValue=0,this.verticesCount._storedValue=0,this.facesCount._storedValue=0,this.output._storedValue=0,this.id._storedFunction=null,this.collectionId._storedFunction=null,this.verticesCount._storedFunction=null,this.facesCount._storedFunction=null,void(this.output._storedFunction=null);this.output._storedFunction=function(t){return e._currentVertexData=e.geometry.getConnectedValue(t),e._currentVertexData},this.id._storedFunction=function(t){return e._currentVertexData=e._currentVertexData||e.geometry.getConnectedValue(t),e._currentVertexData.uniqueId},this.collectionId._storedFunction=function(t){return e._currentVertexData=e._currentVertexData||e.geometry.getConnectedValue(t),e._currentVertexData.metadata?e._currentVertexData.metadata.collectionId:0},this.verticesCount._storedFunction=function(t){return e._currentVertexData=e._currentVertexData||e.geometry.getConnectedValue(t),e._currentVertexData.positions?e._currentVertexData.positions.length/3:0},this.facesCount._storedFunction=function(t){return e._currentVertexData=e._currentVertexData||e.geometry.getConnectedValue(t),e._currentVertexData.indices?e._currentVertexData.indices.length/3:0}},t}(JE);a("BABYLON.GeometryInfoBlock",ex),function(e){e[e.Spherical=0]="Spherical",e[e.Cylindrical=1]="Cylindrical",e[e.Cubic=2]="Cubic"}($S||($S={}));var tx=function(e){function t(t){var i=e.call(this,t)||this;return i.mapping=$S.Spherical,i.registerInput("position",GE.Vector3),i.registerInput("normal",GE.Vector3),i.registerInput("center",GE.Vector3,!0,V.Zero()),i.registerOutput("uv",GE.Vector2),i}return m(t,e),t.prototype.getClassName=function(){return"MappingBlock"},Object.defineProperty(t.prototype,"position",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"normal",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"center",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"uv",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;if(!this.position.isConnected)return this.uv._storedFunction=null,void(this.uv._storedValue=null);var t=V.Zero();this.uv._storedFunction=function(i){return function(i){var r=e.position.getConnectedValue(i)||V.Zero(),n=e.normal.getConnectedValue(i)||V.Zero(),o=e.center.getConnectedValue(i),a=U.Zero();switch(e.mapping){case $S.Spherical:r.subtractToRef(o,t),(s=t.length())>0&&(a.x=Math.acos(t.y/s)/Math.PI,0===t.x&&0===t.z||(a.y=Math.atan2(t.x,t.z)/(2*Math.PI)));break;case $S.Cylindrical:var s;r.subtractToRef(o,t),(s=t.length())>0&&(a.x=Math.atan2(t.x/s,t.z/s)/(2*Math.PI),a.y=(t.y+1)/2);break;case $S.Cubic:var l=Math.abs(n.x),c=Math.abs(n.y),u=Math.abs(n.z),h=Math.max(Math.abs(r.x),Math.abs(r.y),Math.abs(r.z)),d=0,p=0;l>=c&&l>=u?(d=r.y/h-o.y,p=r.z/h-o.z):c>=l&&c>=u?(d=r.x/h-o.x,p=r.z/h-o.z):(d=r.x/h-o.x,p=r.y/h-o.y),a.x=(d+1)/2,a.y=(p+1)/2}return a}(i)}},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".mapping = BABYLON.MappingTypes.").concat($S[this.mapping],";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.mapping=this.mapping,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.mapping=t.mapping},v([Ys("Mapping",Xs.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Spherical",value:$S.Spherical},{label:"Cylindrical",value:$S.Cylindrical},{label:"Cubic",value:$S.Cubic}]})],t.prototype,"mapping",void 0),t}(JE);a("BABYLON.MappingBlock",tx);var ix=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("matrix0",GE.Matrix),i.registerInput("matrix1",GE.Matrix),i.registerOutput("output",GE.Matrix),i}return m(t,e),t.prototype.getClassName=function(){return"MatrixComposeBlock"},Object.defineProperty(t.prototype,"matrix0",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"matrix1",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;this.output._storedFunction=function(t){if(!e.matrix0.isConnected||!e.matrix1.isConnected)return null;var i=e.matrix0.getConnectedValue(t),r=e.matrix1.getConnectedValue(t);return i&&r?i.multiply(r):null}},t}(JE);a("BABYLON.MatrixComposeBlock",ix);var rx=function(e){function t(t){var i=e.call(this,t)||this;return i._endpoints=[],i._isTeleportIn=!0,i.registerInput("input",GE.AutoDetect),i}return m(t,e),Object.defineProperty(t.prototype,"endpoints",{get:function(){return this._endpoints},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"TeleportInBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),t.prototype._dumpCode=function(t,i){for(var r=e.prototype._dumpCode.call(this,t,i),n=0,o=this.endpoints;n<o.length;n++){var a=o[n];-1===i.indexOf(a)&&(r+=a._dumpCode(t,i))}return r},t.prototype.isAnAncestorOfType=function(e){if(this.getClassName()===e)return!0;for(var t=0,i=this.endpoints;t<i.length;t++)if(i[t].isAnAncestorOfType(e))return!0;return!1},t.prototype.isAnAncestorOf=function(e){for(var t=0,i=this.endpoints;t<i.length;t++){var r=i[t];if(r===e)return!0;if(r.isAnAncestorOf(e))return!0}return!1},t.prototype.getDescendantOfPredicate=function(e){if(e(this))return this;for(var t=0,i=this.endpoints;t<i.length;t++){var r=i[t].getDescendantOfPredicate(e);if(r)return r}return null},t.prototype.attachToEndpoint=function(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name},t.prototype.detachFromEndpoint=function(e){var t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)},t.prototype._buildBlock=function(){for(var e=this,t=0,i=this._endpoints;t<i.length;t++)i[t].output._storedFunction=function(t){return e.input.getConnectedValue(t)}},t}(JE);a("BABYLON.TeleportInBlock",rx);var nx=function(e){function t(t){var i=e.call(this,t)||this;return i._entryPoint=null,i._tempEntryPointUniqueId=null,i._isTeleportOut=!0,i.registerOutput("output",GE.BasedOnInput),i}return m(t,e),Object.defineProperty(t.prototype,"entryPoint",{get:function(){return this._entryPoint},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"TeleportOutBlock"},Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype.detach=function(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)},t.prototype._buildBlock=function(){},t.prototype._customBuildStep=function(e){this.entryPoint&&this.entryPoint.build(e)},t.prototype._dumpCode=function(t,i){var r="";return this.entryPoint&&-1===i.indexOf(this.entryPoint)&&(r+=this.entryPoint._dumpCode(t,i)),r+e.prototype._dumpCode.call(this,t,i)},t.prototype._dumpCodeForOutputConnections=function(t){var i=e.prototype._dumpCodeForOutputConnections.call(this,t);return this.entryPoint&&(i+=this.entryPoint._dumpCodeForOutputConnections(t)),i},t.prototype.clone=function(){var t=e.prototype.clone.call(this);return this.entryPoint&&this.entryPoint.attachToEndpoint(t),t},t.prototype._dumpPropertiesCode=function(){var t=e.prototype._dumpPropertiesCode.call(this);return this.entryPoint&&(t+="".concat(this.entryPoint._codeVariableName,".attachToEndpoint(").concat(this._codeVariableName,");\n")),t},t.prototype.serialize=function(){var t,i,r=e.prototype.serialize.call(this);return r.entryPoint=null!==(i=null===(t=this.entryPoint)||void 0===t?void 0:t.uniqueId)&&void 0!==i?i:"",r},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this._tempEntryPointUniqueId=t.entryPoint},t}(JE);a("BABYLON.TeleportOutBlock",nx);var ox=function(e){function t(t){var i=e.call(this,t)||this;return i._data=null,i.serializedCachedData=!1,i.registerOutput("texture",GE.Texture),i}return m(t,e),Object.defineProperty(t.prototype,"textureData",{get:function(){return this._data},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"textureWidth",{get:function(){return this._width},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"textureHeight",{get:function(){return this._height},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"GeometryTextureBlock"},Object.defineProperty(t.prototype,"texture",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._prepareImgToLoadAsync=function(e){var t=this;return new Promise((function(i,r){var n=new Image,o=document.createElement("canvas"),a=o.getContext("2d");n.onload=function(){o.width=n.width,o.height=n.height,a.drawImage(n,0,0);for(var e=a.getImageData(0,0,n.width,n.height).data,r=new Float32Array(e.length),s=0;s<e.length;s++)r[s]=e[s]/255;t._data=r,t._width=n.width,t._height=n.height,i()},n.onerror=function(){t._data=null,r()},n.src=e}))},t.prototype.cleanData=function(){this._data=null},t.prototype.loadTextureFromFileAsync=function(e){return this._prepareImgToLoadAsync(URL.createObjectURL(e))},t.prototype.loadTextureFromUrlAsync=function(e){return this._prepareImgToLoadAsync(e)},t.prototype.extractFromTextureAsync=function(e){var t=this;return new Promise((function(i,r){if(e.isReady()){var n=e.getSize();Dp.GetTextureDataAsync(e,n.width,n.height).then((function(e){return y(t,void 0,void 0,(function(){var t,r;return b(this,(function(o){for(t=new Float32Array(e.length),r=0;r<e.length;r++)t[r]=e[r]/255;return this._data=t,this._width=n.width,this._height=n.height,i(),[2]}))}))})).catch(r)}else e.onLoadObservable.addOnce((function(){return t.extractFromTextureAsync(e).then(i).catch(r)}))}))},t.prototype._buildBlock=function(){if(this._data){var e={data:this._data,width:this._width,height:this._height};this.texture._storedValue=e}else this.texture._storedValue=null},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.width=this._width,t.height=this._height,t.serializedCachedData=this.serializedCachedData,this._data&&this.serializedCachedData&&(t.data=Array.from(this._data)),t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this._width=t.width,this._height=t.height,t.data?(this._data=new Float32Array(t.data),this.serializedCachedData=!0):this.serializedCachedData=!!t.serializedCachedData},v([Ys("Serialize cached data",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"serializedCachedData",void 0),t}(JE);a("BABYLON.GeometryTextureBlock",ox);var ax=function(e){function t(t){var i=e.call(this,t)||this;return i.clampCoordinates=!0,i.registerInput("texture",GE.Texture),i.registerInput("coordinates",GE.Vector2),i.registerOutput("rgba",GE.Vector4),i.registerOutput("rgb",GE.Vector3),i.registerOutput("r",GE.Float),i.registerOutput("g",GE.Float),i.registerOutput("b",GE.Float),i.registerOutput("a",GE.Float),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryTextureFetchBlock"},Object.defineProperty(t.prototype,"texture",{get:function(){return this.inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"coordinates",{get:function(){return this.inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rgba",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rgb",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"r",{get:function(){return this._outputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"g",{get:function(){return this._outputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"b",{get:function(){return this._outputs[4]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"a",{get:function(){return this._outputs[5]},enumerable:!1,configurable:!0}),t.prototype._repeatClamp=function(e){return e>=0?e%1:1-Math.abs(e)%1},t.prototype._buildBlock=function(){var e=this,t=function(t){var i=e.texture.getConnectedValue(t);if(!i||!i.data)return null;var r=e.coordinates.getConnectedValue(t);if(!r)return null;var n=e.clampCoordinates?Math.max(0,Math.min(r.x,1)):e._repeatClamp(r.x),o=e.clampCoordinates?Math.max(0,Math.min(r.y,1)):e._repeatClamp(r.y),a=Math.floor(n*(i.width-1)),s=Math.floor(o*(i.height-1)),l=a+i.width*s;return k.FromArray(i.data,4*l)};this.rgba._storedFunction=function(e){return t(e)},this.rgb._storedFunction=function(e){var i=t(e);return i?i.toVector3():null},this.r._storedFunction=function(e){var i=t(e);return i?i.x:null},this.g._storedFunction=function(e){var i=t(e);return i?i.y:null},this.b._storedFunction=function(e){var i=t(e);return i?i.z:null},this.a._storedFunction=function(e){var i=t(e);return i?i.w:null}},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".clampCoordinates = ").concat(this.clampCoordinates,";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.clampCoordinates=this.clampCoordinates,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.clampCoordinates=t.clampCoordinates},v([Ys("Clamp Coordinates",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"clampCoordinates",void 0),t}(JE);a("BABYLON.GeometryTextureFetchBlock",ax);var sx,lx=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("geometry",GE.Geometry),i.registerOutput("min",GE.Vector3),i.registerOutput("max",GE.Vector3),i}return m(t,e),t.prototype.getClassName=function(){return"BoundingBlock"},Object.defineProperty(t.prototype,"geometry",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"min",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"max",{get:function(){return this._outputs[1]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;this.min._storedFunction=function(t){var i=e.geometry.getConnectedValue(t);return i?uo(i.positions,0,i.positions.length/3).minimum:null},this.max._storedFunction=function(t){var i=e.geometry.getConnectedValue(t);return i?uo(i.positions,0,i.positions.length/3).maximum:null}},t}(JE);a("BABYLON.BoundingBlock",lx),function(e){e[e.Intersect=0]="Intersect",e[e.Subtract=1]="Subtract",e[e.Union=2]="Union"}(sx||(sx={}));var cx=function(e){function t(t){var i=e.call(this,t)||this;return i.evaluateContext=!1,i.operation=sx.Intersect,i.registerInput("geometry0",GE.Geometry),i.registerInput("geometry1",GE.Geometry),i.registerOutput("output",GE.Geometry),i}return m(t,e),t.prototype.getClassName=function(){return"BooleanGeometryBlock"},Object.defineProperty(t.prototype,"geometry0",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"geometry1",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(e){var t=this,i=function(e){var i=t.geometry0.getConnectedValue(e),r=t.geometry1.getConnectedValue(e);if(!i||!r)return null;var n=i.positions.length/3;!i.normals&&r.normals&&(i.normals=new Array(i.positions.length)),!r.normals&&i.normals&&(r.normals=new Array(r.positions.length)),!i.uvs&&r.uvs&&(i.uvs=new Array(2*n)),!r.uvs&&i.uvs&&(r.uvs=new Array(2*n)),!i.colors&&r.colors&&(i.colors=new Array(4*n)),!r.colors&&i.colors&&(r.colors=new Array(4*n));var o,a=EE.FromVertexData(i),s=EE.FromVertexData(r);switch(t.operation){case sx.Intersect:o=a.intersect(s);break;case sx.Subtract:o=a.subtract(s);break;case sx.Union:o=a.union(s)}return o.toVertexData()};this.evaluateContext?this.output._storedFunction=i:(this.output._storedFunction=null,this.output._storedValue=i(e))},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".evaluateContext = ").concat(this.evaluateContext?"true":"false",";\n")+"".concat(this._codeVariableName,".operation = BABYLON.BooleanGeometryOperations.").concat(sx[this.operation],";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.evaluateContext=this.evaluateContext,t.operation=this.operation,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.evaluateContext=t.evaluateContext,t.operation&&(this.operation=t.operation)},v([Ys("Evaluate context",Xs.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],t.prototype,"evaluateContext",void 0),v([Ys("Operation",Xs.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Intersect",value:sx.Intersect},{label:"Subtract",value:sx.Subtract},{label:"Union",value:sx.Union}]})],t.prototype,"operation",void 0),t}(JE);a("BABYLON.BooleanGeometryBlock",cx);var ux=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("x",GE.AutoDetect),i.registerInput("y",GE.AutoDetect),i.registerOutput("output",GE.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),i._inputs[0].excludedConnectionPointTypes.push(GE.Texture),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryArcTan2Block"},Object.defineProperty(t.prototype,"x",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"y",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;if(!this.x.isConnected||!this.y.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);var t=function(e,t){return Math.atan2(e,t)};this.output._storedFunction=function(i){var r=e.x.getConnectedValue(i),n=e.y.getConnectedValue(i);switch(e.x.type){case GE.Int:case GE.Float:return t(r,n);case GE.Vector2:return new U(t(r.x,n.x),t(r.y,n.y));case GE.Vector3:return new V(t(r.x,n.x),t(r.y,n.y),t(r.z,n.z));case GE.Vector4:return new k(t(r.x,n.x),t(r.y,n.y),t(r.z,n.z),t(r.w,n.w))}return 0}},t}(JE);a("BABYLON.GeometryArcTan2Block",ux);var hx=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("left",GE.AutoDetect),i.registerInput("right",GE.AutoDetect),i.registerInput("gradient",GE.Float),i.registerOutput("output",GE.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),i._inputs[0].excludedConnectionPointTypes.push(GE.Texture),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryLerpBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"gradient",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;if(!this.left.isConnected||!this.right.isConnected||!this.gradient.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);var t=function(e,t,i){return(1-e)*t+e*i};return this.output._storedFunction=function(i){var r=e.left.getConnectedValue(i),n=e.right.getConnectedValue(i),o=e.gradient.getConnectedValue(i);switch(e.left.type){case GE.Int:case GE.Float:return t(o,r,n);case GE.Vector2:return new U(t(o,r.x,n.x),t(o,r.y,n.y));case GE.Vector3:return new V(t(o,r.x,n.x),t(o,r.y,n.y),t(o,r.z,n.z));case GE.Vector4:return new k(t(o,r.x,n.x),t(o,r.y,n.y),t(o,r.z,n.z),t(o,r.w,n.w))}return 0},this},t}(JE);a("BABYLON.GeometryLerpBlock",hx);var dx=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("left",GE.AutoDetect),i.registerInput("right",GE.AutoDetect),i.registerInput("gradient",GE.Float),i.registerOutput("output",GE.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),i._inputs[0].excludedConnectionPointTypes.push(GE.Texture),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryNLerpBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"gradient",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;if(!this.left.isConnected||!this.right.isConnected||!this.gradient.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);var t=function(e,t,i){return(1-e)*t+e*i};return this.output._storedFunction=function(i){var r=e.left.getConnectedValue(i),n=e.right.getConnectedValue(i),o=e.gradient.getConnectedValue(i);switch(e.left.type){case GE.Int:case GE.Float:return t(o,r,n);case GE.Vector2:return(a=new U(t(o,r.x,n.x),t(o,r.y,n.y))).normalize(),a;case GE.Vector3:return(a=new V(t(o,r.x,n.x),t(o,r.y,n.y),t(o,r.z,n.z))).normalize(),a;case GE.Vector4:var a;return(a=new k(t(o,r.x,n.x),t(o,r.y,n.y),t(o,r.z,n.z),t(o,r.w,n.w))).normalize(),a}return 0},this},t}(JE);a("BABYLON.GeometryNLerpBlock",dx);var px=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("value",GE.AutoDetect),i.registerInput("edge",GE.Float),i.registerOutput("output",GE.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),i._inputs[0].excludedConnectionPointTypes.push(GE.Texture),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryStepBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"edge",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;if(!this.value.isConnected||!this.edge.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);var t=function(e,t){return e<t?0:1};return this.output._storedFunction=function(i){var r=e.value.getConnectedValue(i),n=e.edge.getConnectedValue(i);switch(e.value.type){case GE.Int:case GE.Float:return t(r,n);case GE.Vector2:return new U(t(r.x,n),t(r.y,n));case GE.Vector3:return new V(t(r.x,n),t(r.y,n),t(r.z,n));case GE.Vector4:return new k(t(r.x,n),t(r.y,n),t(r.z,n),t(r.w,n))}return 0},this},t}(JE);a("BABYLON.GeometryStepBlock",px);var fx=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("value",GE.AutoDetect),i.registerInput("edge0",GE.Float),i.registerInput("edge1",GE.Float),i.registerOutput("output",GE.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),i._inputs[0].excludedConnectionPointTypes.push(GE.Texture),i}return m(t,e),t.prototype.getClassName=function(){return"GeometrySmoothStepBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"edge0",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"edge1",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;if(!this.value.isConnected||!this.edge0.isConnected||!this.edge1.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);var t=function(e,t,i){var r=Math.max(0,Math.min((e-t)/(i-t),1));return r*r*(3-2*r)};return this.output._storedFunction=function(i){var r=e.value.getConnectedValue(i),n=e.edge0.getConnectedValue(i),o=e.edge1.getConnectedValue(i);switch(e.value.type){case GE.Int:case GE.Float:return t(r,n,o);case GE.Vector2:return new U(t(r.x,n,o),t(r.y,n,o));case GE.Vector3:return new V(t(r.x,n,o),t(r.y,n,o),t(r.z,n,o));case GE.Vector4:return new k(t(r.x,n,o),t(r.y,n,o),t(r.z,n,o),t(r.w,n,o))}return 0},this},t}(JE);a("BABYLON.GeometrySmoothStepBlock",fx);var _x=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("left",GE.AutoDetect),i.registerInput("right",GE.AutoDetect),i.registerOutput("output",GE.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),i._inputs[0].excludedConnectionPointTypes.push(GE.Texture),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryModBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;if(!this.left.isConnected||!this.right.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);var t=function(e,t){return e-Math.floor(e/t)*t};return this.output._storedFunction=function(i){var r=e.left.getConnectedValue(i),n=e.right.getConnectedValue(i);switch(e.left.type){case GE.Int:case GE.Float:return t(r,n);case GE.Vector2:return new U(t(r.x,n.x),t(r.y,n.y));case GE.Vector3:return new V(t(r.x,n.x),t(r.y,n.y),t(r.z,n.z));case GE.Vector4:return new k(t(r.x,n.x),t(r.y,n.y),t(r.z,n.z),t(r.w,n.w))}return 0},this},t}(JE);a("BABYLON.GeometryModBlock",_x);var mx=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("value",GE.AutoDetect),i.registerInput("power",GE.AutoDetect),i.registerOutput("output",GE.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),i._inputs[0].excludedConnectionPointTypes.push(GE.Texture),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryPowBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"power",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;if(!this.value.isConnected||!this.power.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);var t=function(e,t){return Math.pow(e,t)};return this.output._storedFunction=function(i){var r=e.value.getConnectedValue(i),n=e.power.getConnectedValue(i);switch(e.value.type){case GE.Int:case GE.Float:return t(r,n);case GE.Vector2:return new U(t(r.x,n),t(r.y,n));case GE.Vector3:return new V(t(r.x,n),t(r.y,n),t(r.z,n));case GE.Vector4:return new k(t(r.x,n),t(r.y,n),t(r.z,n),t(r.w,n))}return 0},this},t}(JE);a("BABYLON.GeometryPowBlock",mx);var gx=function(e){function t(t){var i=e.call(this,t)||this;return i.minimum=0,i.maximum=1,i.registerInput("value",GE.AutoDetect),i.registerOutput("output",GE.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[0].excludedConnectionPointTypes.push(GE.Geometry),i._inputs[0].excludedConnectionPointTypes.push(GE.Texture),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryClampBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);var t=function(t){return Math.max(e.minimum,Math.min(t,e.maximum))};return this.output._storedFunction=function(i){var r=e.value.getConnectedValue(i);switch(e.value.type){case GE.Int:case GE.Float:return t(r);case GE.Vector2:return new U(t(r.x),t(r.y));case GE.Vector3:return new V(t(r.x),t(r.y),t(r.z));case GE.Vector4:return new k(t(r.x),t(r.y),t(r.z),t(r.w))}return 0},this},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".minimum = ").concat(this.minimum,";\n")+"".concat(this._codeVariableName,".maximum = ").concat(this.maximum,";\n")},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.minimum=this.minimum,t.maximum=this.maximum,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.minimum=t.minimum,this.maximum=t.maximum},v([Ys("Minimum",Xs.Float)],t.prototype,"minimum",void 0),v([Ys("Maximum",Xs.Float)],t.prototype,"maximum",void 0),t}(JE);a("BABYLON.GeometryClampBlock",gx);var vx,yx=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("left",GE.AutoDetect),i.registerInput("right",GE.AutoDetect),i.registerOutput("output",GE.Vector3),i._linkConnectionTypes(0,1),i._inputs[0].excludedConnectionPointTypes.push(GE.Int),i._inputs[0].excludedConnectionPointTypes.push(GE.Float),i._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[0].excludedConnectionPointTypes.push(GE.Vector2),i._inputs[1].excludedConnectionPointTypes.push(GE.Int),i._inputs[1].excludedConnectionPointTypes.push(GE.Float),i._inputs[1].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[1].excludedConnectionPointTypes.push(GE.Vector2),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryCrossBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;return this.left.isConnected&&this.right.isConnected?(this.output._storedFunction=function(t){var i=e.left.getConnectedValue(t),r=e.right.getConnectedValue(t);switch(e.left.type){case GE.Vector3:return V.Cross(i,r);case GE.Vector4:return V.Cross(i.toVector3(),r.toVector3())}return 0},this):(this.output._storedFunction=null,void(this.output._storedValue=null))},t}(JE);a("BABYLON.GeometryCrossBlock",yx),function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(vx||(vx={}));var bx=function(e){function t(t){var i=e.call(this,t)||this;return i.type=vx.EaseInOutSine,i.registerInput("input",GE.AutoDetect),i.registerOutput("output",GE.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[0].excludedConnectionPointTypes.push(GE.Int),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryCurveBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e,t=this;if(!this.input.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);switch(this.type){case vx.EaseInSine:e=function(e){return 1-Math.cos(3.1415*e/2)};break;case vx.EaseOutSine:e=function(e){return Math.sin(3.1415*e/2)};break;case vx.EaseInOutSine:e=function(e){return-(Math.cos(3.1415*e)-1)/2};break;case vx.EaseInQuad:e=function(e){return e*e};break;case vx.EaseOutQuad:e=function(e){return(1-e)*(1-e)};break;case vx.EaseInOutQuad:e=function(e){return e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2};break;case vx.EaseInCubic:e=function(e){return e*e*e};break;case vx.EaseOutCubic:e=function(e){return 1-Math.pow(1-e,3)};break;case vx.EaseInOutCubic:e=function(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2};break;case vx.EaseInQuart:e=function(e){return e*e*e*e};break;case vx.EaseOutQuart:e=function(e){return 1-Math.pow(1-e,4)};break;case vx.EaseInOutQuart:e=function(e){return e<.5?8*e*e*e*e:1-Math.pow(-2*e+2,4)/2};break;case vx.EaseInQuint:e=function(e){return e*e*e*e*e};break;case vx.EaseOutQuint:e=function(e){return 1-Math.pow(1-e,5)};break;case vx.EaseInOutQuint:e=function(e){return e<.5?16*e*e*e*e*e:1-Math.pow(-2*e+2,5)/2};break;case vx.EaseInExpo:e=function(e){return 0===e?0:Math.pow(2,10*e-10)};break;case vx.EaseOutExpo:e=function(e){return 1===e?1:1-Math.pow(2,-10*e)};break;case vx.EaseInOutExpo:e=function(e){return 0===e?0:1===e?1:e<.5?Math.pow(2,20*e-10)/2:(2-Math.pow(2,-20*e+10))/2};break;case vx.EaseInCirc:e=function(e){return 1-Math.sqrt(1-Math.pow(e,2))};break;case vx.EaseOutCirc:e=function(e){return Math.sqrt(1-Math.pow(e-1,2))};break;case vx.EaseInOutCirc:e=function(e){return e<.5?(1-Math.sqrt(1-Math.pow(2*e,2)))/2:(Math.sqrt(1-Math.pow(-2*e+2,2))+1)/2};break;case vx.EaseInBack:e=function(e){return 2.70158*e*e*e-1.70158*e*e};break;case vx.EaseOutBack:e=function(e){return 2.70158*Math.pow(e-1,3)+1.70158*Math.pow(e-1,2)};break;case vx.EaseInOutBack:e=function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-2.5949095)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+3.5949095)+2)/2};break;case vx.EaseInElastic:e=function(e){return 0===e?0:1===e?1:-Math.pow(2,10*e-10)*Math.sin(6.283/3*(10*e-10.75))};break;case vx.EaseOutElastic:e=function(e){return 0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin(6.283/3*(10*e-.75))+1};break;case vx.EaseInOutElastic:e=function(e){return 0===e?0:1==e?1:e<.5?-Math.pow(2,20*e-10)*Math.sin(6.283/4.5*(20*e-11.125))/2:Math.pow(2,-20*e+10)*Math.sin(6.283/4.5*(20*e-11.125))/2+1}}return this.output._storedFunction=function(i){var r=t.input.getConnectedValue(i);switch(t.input.type){case GE.Float:return e(r);case GE.Vector2:return new U(e(r.x),e(r.y));case GE.Vector3:return new V(e(r.x),e(r.y),e(r.z));case GE.Vector4:return new k(e(r.x),e(r.y),e(r.z),e(r.w))}return 0},this},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.curveType=this.type,t},t.prototype._deserialize=function(t){e.prototype._deserialize.call(this,t),this.type=t.curveType},t.prototype._dumpPropertiesCode=function(){return e.prototype._dumpPropertiesCode.call(this)+"".concat(this._codeVariableName,".type = BABYLON.GeometryCurveBlockTypes.").concat(vx[this.type],";\n")},v([Ys("Type",Xs.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"EaseInSine",value:vx.EaseInSine},{label:"EaseOutSine",value:vx.EaseOutSine},{label:"EaseInOutSine",value:vx.EaseInOutSine},{label:"EaseInQuad",value:vx.EaseInQuad},{label:"EaseOutQuad",value:vx.EaseOutQuad},{label:"EaseInOutQuad",value:vx.EaseInOutQuad},{label:"EaseInCubic",value:vx.EaseInCubic},{label:"EaseOutCubic",value:vx.EaseOutCubic},{label:"EaseInOutCubic",value:vx.EaseInOutCubic},{label:"EaseInQuart",value:vx.EaseInQuart},{label:"EaseOutQuart",value:vx.EaseOutQuart},{label:"EaseInOutQuart",value:vx.EaseInOutQuart},{label:"EaseInQuint",value:vx.EaseInQuint},{label:"EaseOutQuint",value:vx.EaseOutQuint},{label:"EaseInOutQuint",value:vx.EaseInOutQuint},{label:"EaseInExpo",value:vx.EaseInExpo},{label:"EaseOutExpo",value:vx.EaseOutExpo},{label:"EaseInOutExpo",value:vx.EaseInOutExpo},{label:"EaseInCirc",value:vx.EaseInCirc},{label:"EaseOutCirc",value:vx.EaseOutCirc},{label:"EaseInOutCirc",value:vx.EaseInOutCirc},{label:"EaseInBack",value:vx.EaseInBack},{label:"EaseOutBack",value:vx.EaseOutBack},{label:"EaseInOutBack",value:vx.EaseInOutBack},{label:"EaseInElastic",value:vx.EaseInElastic},{label:"EaseOutElastic",value:vx.EaseOutElastic},{label:"EaseInOutElastic",value:vx.EaseInOutElastic}]})],t.prototype,"type",void 0),t}(JE);a("BABYLON.GeometryCurveBlock",bx);var Tx=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("color",GE.Vector3),i.registerInput("level",GE.Float,!0,0),i.registerOutput("output",GE.Vector3),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryDesaturateBlock"},Object.defineProperty(t.prototype,"color",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"level",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;return this.color.isConnected?(this.output._storedFunction=function(t){var i=e.color.getConnectedValue(t),r=e.level.getConnectedValue(t),n=.5*(Math.min(i.x,i.y,i.z)+Math.max(i.x,i.y,i.z));return new V(i.x*(1-r)+n*r,i.y*(1-r)+n*r,i.z*(1-r)+n*r)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))},t}(JE);a("BABYLON.GeometryDesaturateBlock",Tx);var Ex=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("value",GE.AutoDetect),i.registerInput("steps",GE.AutoDetect),i.registerOutput("output",GE.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[1].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[1].acceptedConnectionPointTypes.push(GE.Float),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryPosterizeBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"steps",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;return this.value.isConnected&&this.steps.isConnected?(this.output._storedFunction=function(t){var i=e.value.getConnectedValue(t),r=e.steps.getConnectedValue(t),n=r;if(e.steps.type===GE.Float)switch(e.value.type){case GE.Vector2:n=new U(r,r);break;case GE.Vector3:n=new V(r,r,r);break;case GE.Vector4:n=new k(r,r,r,r)}switch(e.value.type){case GE.Vector2:return new U(i.x/(1/n.x)*(1/n.x),i.y/(1/n.y)*(1/n.y));case GE.Vector3:return new V(i.x/(1/n.x)*(1/n.x),i.y/(1/n.y)*(1/n.y),i.z/(1/n.z)*(1/n.z));case GE.Vector4:return new k(i.x/(1/n.x)*(1/n.x),i.y/(1/n.y)*(1/n.y),i.z/(1/n.z)*(1/n.z),i.w/(1/n.w)*(1/n.w));default:return Math.floor(i/(1/r)*(1/r))}},this):(this.output._storedFunction=null,void(this.output._storedValue=null))},t}(JE);a("BABYLON.GeometryPosterizeBlock",Ex);var Sx=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("value",GE.AutoDetect),i.registerInput("reference",GE.AutoDetect),i.registerInput("distance",GE.Float),i.registerInput("replacement",GE.AutoDetect),i.registerOutput("output",GE.BasedOnInput),i._outputs[0]._typeConnectionSource=i._inputs[0],i._linkConnectionTypes(0,1),i._linkConnectionTypes(0,3),i._inputs[0].excludedConnectionPointTypes.push(GE.Float),i._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[1].excludedConnectionPointTypes.push(GE.Float),i._inputs[1].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[3].excludedConnectionPointTypes.push(GE.Float),i._inputs[3].excludedConnectionPointTypes.push(GE.Matrix),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryReplaceColorBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"reference",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"distance",{get:function(){return this._inputs[2]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"replacement",{get:function(){return this._inputs[3]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;return this.value.isConnected&&this.reference.isConnected&&this.distance.isConnected&&this.replacement.isConnected?(this.output._storedFunction=function(t){var i=e.value.getConnectedValue(t),r=e.reference.getConnectedValue(t),n=e.distance.getConnectedValue(t),o=e.replacement.getConnectedValue(t);return i.subtract(r).length()<n?o:i},this):(this.output._storedFunction=null,void(this.output._storedValue=null))},t}(JE);a("BABYLON.GeometryReplaceColorBlock",Sx);var xx=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("left",GE.AutoDetect),i.registerInput("right",GE.AutoDetect),i.registerOutput("output",GE.Float),i._linkConnectionTypes(0,1),i._inputs[0].excludedConnectionPointTypes.push(GE.Int),i._inputs[0].excludedConnectionPointTypes.push(GE.Float),i._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[1].excludedConnectionPointTypes.push(GE.Float),i._inputs[1].excludedConnectionPointTypes.push(GE.Matrix),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryDistanceBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;return this.left.isConnected&&this.right.isConnected?(this.output._storedFunction=function(t){var i=e.left.getConnectedValue(t),r=e.right.getConnectedValue(t);return i.subtract(r).length()},this):(this.output._storedFunction=null,void(this.output._storedValue=null))},t}(JE);a("BABYLON.GeometryDistanceBlock",xx);var Ax=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("left",GE.AutoDetect),i.registerInput("right",GE.AutoDetect),i.registerOutput("output",GE.Float),i._linkConnectionTypes(0,1),i._inputs[0].excludedConnectionPointTypes.push(GE.Int),i._inputs[0].excludedConnectionPointTypes.push(GE.Float),i._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),i._inputs[1].excludedConnectionPointTypes.push(GE.Float),i._inputs[1].excludedConnectionPointTypes.push(GE.Matrix),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryDotBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;return this.left.isConnected&&this.right.isConnected?(this.output._storedFunction=function(t){var i=e.left.getConnectedValue(t),r=e.right.getConnectedValue(t);return i.dot(r)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))},t}(JE);a("BABYLON.GeometryDotBlock",Ax);var Cx=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("value",GE.AutoDetect),i.registerOutput("output",GE.Float),i._inputs[0].excludedConnectionPointTypes.push(GE.Int),i._inputs[0].excludedConnectionPointTypes.push(GE.Float),i._inputs[0].excludedConnectionPointTypes.push(GE.Matrix),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryLengthBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;return this.value.isConnected?(this.output._storedFunction=function(t){return e.value.getConnectedValue(t).length()},this):(this.output._storedFunction=null,void(this.output._storedValue=null))},t}(JE);a("BABYLON.GeometryLengthBlock",Cx);var Rx=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("input",GE.Vector2),i.registerInput("angle",GE.Float),i.registerOutput("output",GE.Vector2),i}return m(t,e),t.prototype.getClassName=function(){return"GeometryRotate2dBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"angle",{get:function(){return this._inputs[1]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){return this._outputs[0]},enumerable:!1,configurable:!0}),t.prototype._buildBlock=function(){var e=this;return this.angle.isConnected&&this.input.isConnected?(this.output._storedFunction=function(t){var i=e.input.getConnectedValue(t),r=e.angle.getConnectedValue(t);return new U(Math.cos(r)*i.x-Math.sin(r)*i.y,Math.sin(r)*i.x+Math.cos(r)*i.y)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))},t}(JE);a("BABYLON.GeometryRotate2dBlock",Rx);var Px=function(e){function t(t,i,r){void 0===i&&(i=null),void 0===r&&(r=null);var n=e.call(this,t,r)||this;n._vertexCount=0,n._worker=null,n._frameIdLastUpdate=-1,n._modelViewMatrix=z.Identity(),n._material=null,n._canPostToWorker=!0,n._covariancesATexture=null,n._covariancesBTexture=null,n._centersTexture=null,n._colorsTexture=null;var o=new _o;return o.positions=[-2,-2,0,2,-2,0,2,2,0,-2,2,0],o.indices=[0,1,2,0,2,3],o.applyToMesh(n),n.subMeshes=[],new po(0,0,4,0,6,n),n.doNotSyncBoundingInfo=!0,n.setEnabled(!1),n._lastProj=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],i&&n.loadFileAsync(i),n}return m(t,e),Object.defineProperty(t.prototype,"covariancesATexture",{get:function(){return this._covariancesATexture},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"covariancesBTexture",{get:function(){return this._covariancesBTexture},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"centersTexture",{get:function(){return this._centersTexture},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"colorsTexture",{get:function(){return this._colorsTexture},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"GaussianSplattingMesh"},t.prototype.getTotalVertices=function(){return this._vertexCount},t.prototype.render=function(t,i,r){this.material||(this._material=new aE(this.name+"_material",this._scene),this.material=this._material);var n=this.getScene().getFrameId();if(n!==this._frameIdLastUpdate&&this._worker&&this._scene.activeCamera&&this._canPostToWorker){this.getWorldMatrix().multiplyToRef(this._scene.activeCamera.getViewMatrix(),this._modelViewMatrix);var o=this._lastProj[2]*this._modelViewMatrix.m[2]+this._lastProj[6]*this._modelViewMatrix.m[6]+this._lastProj[10]*this._modelViewMatrix.m[10];Math.abs(o-1)>=.01&&(this._frameIdLastUpdate=n,this._canPostToWorker=!1,this._lastProj=this._modelViewMatrix.m.slice(0),this._worker.postMessage({view:this._modelViewMatrix.m,depthMix:this._depthMix},[this._depthMix.buffer]))}return e.prototype.render.call(this,t,i,r)},t.ConvertPLYToSplat=function(e){var t,i=new Uint8Array(e),r=(new TextDecoder).decode(i.slice(0,10240)),n=r.indexOf("end_header\n");if(n<0||!r)return e;for(var o=parseInt(/element vertex (\d+)\n/.exec(r)[1]),a=0,s={double:8,int:4,uint:4,float:4,short:2,ushort:2,uchar:1},l=[],c=0,u=r.slice(0,n).split("\n").filter((function(e){return e.startsWith("property ")}));c<u.length;c++){var h=(t=u[c].split(" "))[1],d=t[2];if(l.push({name:d,type:h,offset:a}),!s[h])return ae.Error("Unsupported property type: ".concat(h,". Are you sure it's a valid Gaussian Splatting file?")),new ArrayBuffer(0);a+=s[h]}for(var p=.28209479177387814,f=new DataView(e,n+11),_=new ArrayBuffer(32*o),m=new G,g=0;g<o;g++){for(var v=new Float32Array(_,32*g,3),y=new Float32Array(_,32*g+12,3),b=new Uint8ClampedArray(_,32*g+24,4),T=new Uint8ClampedArray(_,32*g+28,4),E=255,S=0,x=0,A=0,C=0;C<l.length;C++){var R=l[C],P=void 0;switch(R.type){case"float":P=f.getFloat32(R.offset+g*a,!0);break;case"int":P=f.getInt32(R.offset+g*a,!0);break;default:throw new Error("Unsupported property type: ".concat(R.type))}switch(R.name){case"x":v[0]=P;break;case"y":v[1]=P;break;case"z":v[2]=P;break;case"scale_0":y[0]=Math.exp(P);break;case"scale_1":y[1]=Math.exp(P);break;case"scale_2":y[2]=Math.exp(P);break;case"red":b[0]=P;break;case"green":b[1]=P;break;case"blue":b[2]=P;break;case"f_dc_0":b[0]=255*(.5+p*P);break;case"f_dc_1":b[1]=255*(.5+p*P);break;case"f_dc_2":b[2]=255*(.5+p*P);break;case"f_dc_3":b[3]=255*(.5+p*P);break;case"opacity":b[3]=1/(1+Math.exp(-P))*255;break;case"rot_0":E=P;break;case"rot_1":S=P;break;case"rot_2":x=P;break;case"rot_3":A=P}}m.set(S,x,A,E),m.normalize(),T[0]=128*m.w+128,T[1]=128*m.x+128,T[2]=128*m.y+128,T[3]=128*m.z+128}return _},t.prototype.loadDataAsync=function(e){return Promise.resolve(this._loadData(e))},t.prototype.loadFileAsync=function(e){var i=this;return rr.LoadFileAsync(e,!0).then((function(e){i._loadData(t.ConvertPLYToSplat(e))}))},t.prototype.dispose=function(t){var i,r,n,o,a,s;null===(i=this._covariancesATexture)||void 0===i||i.dispose(),null===(r=this._covariancesBTexture)||void 0===r||r.dispose(),null===(n=this._centersTexture)||void 0===n||n.dispose(),null===(o=this._colorsTexture)||void 0===o||o.dispose(),this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null,null===(a=this._material)||void 0===a||a.dispose(!1,!0),this._material=null,null===(s=this._worker)||void 0===s||s.terminate(),this._worker=null,e.prototype.dispose.call(this,t)},t.prototype._loadData=function(e){var i,r=this;if(e.byteLength){var n=new Uint8Array(e),o=new Float32Array(n.buffer),a=n.length/32;this._vertexCount=a;for(var s=this._getTextureSize(a),l=s.x*s.y,c=new Float32Array(3*l),h=new Float32Array(3*l),d=new Float32Array(3*l),p=H.Matrix[0],f=H.Matrix[1],_=H.Quaternion[0],m=new V(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),g=new V(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),v=0;v<a;v++){var y=o[8*v+0],b=-o[8*v+1],T=o[8*v+2];c[3*v+0]=y,c[3*v+1]=b,c[3*v+2]=T,m.minimizeInPlaceFromFloats(y,b,T),g.maximizeInPlaceFromFloats(y,b,T),_.set((n[32*v+28+1]-128)/128,(n[32*v+28+2]-128)/128,(n[32*v+28+3]-128)/128,-(n[32*v+28+0]-128)/128),_.toRotationMatrix(p),z.ScalingToRef(2*o[8*v+3+0],2*o[8*v+3+1],2*o[8*v+3+2],f);var E=p.multiplyToRef(f,H.Matrix[0]).m;h[3*v+0]=E[0]*E[0]+E[1]*E[1]+E[2]*E[2],h[3*v+1]=E[0]*E[4]+E[1]*E[5]+E[2]*E[6],h[3*v+2]=E[0]*E[8]+E[1]*E[9]+E[2]*E[10],d[3*v+0]=E[4]*E[4]+E[5]*E[5]+E[6]*E[6],d[3*v+1]=E[4]*E[8]+E[5]*E[9]+E[6]*E[10],d[3*v+2]=E[8]*E[8]+E[9]*E[9]+E[10]*E[10]}var S=this.getBoundingInfo();S.reConstruct(m,g,this.getWorldMatrix()),S.isLocked=!0,this.forcedInstanceCount=this._vertexCount,this.setEnabled(!0);var x=new Float32Array(1*this._vertexCount);this.thinInstanceSetBuffer("splatIndex",x,1,!1);var A=function(e,t,i,n){return new is(e,t,i,n,r._scene,!1,!1,u.TEXTURE_BILINEAR_SAMPLINGMODE,u.TEXTURETYPE_FLOAT)},C=function(e){for(var t=e.length/3,i=new Float32Array(4*t),r=0;r<t;++r)i[4*r+0]=e[3*r+0],i[4*r+1]=e[3*r+1],i[4*r+2]=e[3*r+2],i[4*r+3]=1;return i},R=new Float32Array(s.x*s.y*4);for(v=0;v<this._vertexCount;++v)R[4*v+0]=n[32*v+24+0]/255,R[4*v+1]=n[32*v+24+1]/255,R[4*v+2]=n[32*v+24+2]/255,R[4*v+3]=n[32*v+24+3]/255;this._covariancesATexture=A(C(h),s.x,s.y,u.TEXTUREFORMAT_RGBA),this._covariancesBTexture=A(C(d),s.x,s.y,u.TEXTUREFORMAT_RGBA),this._centersTexture=A(C(c),s.x,s.y,u.TEXTUREFORMAT_RGBA),this._colorsTexture=A(R,s.x,s.y,u.TEXTUREFORMAT_RGBA),null===(i=this._worker)||void 0===i||i.terminate(),this._worker=new Worker(URL.createObjectURL(new Blob(["(",t._CreateWorker.toString(),")(self)"],{type:"application/javascript"}))),this._depthMix=new BigInt64Array(a),this._worker.postMessage({positions:c,vertexCount:a},[c.buffer]),this._worker.onmessage=function(e){r._depthMix=e.data.depthMix;for(var t=new Uint32Array(e.data.depthMix.buffer),i=0;i<r._vertexCount;i++)x[i]=t[2*i];r.thinInstanceBufferUpdated("splatIndex"),r._canPostToWorker=!0}}},t.prototype._getTextureSize=function(e){var t=this._scene.getEngine(),i=t.getCaps().maxTextureSize,r=1;if(1!==t.version||t.isWebGPU)r=Math.ceil(e/i);else for(;i*r<e;)r*=2;return r>i&&(ae.Error("GaussianSplatting texture size: ("+i+", "+r+"), maxTextureSize: "+i),r=i),new U(i,r)},t._CreateWorker=function(e){var t,i,r,n,o=0;e.onmessage=function(a){if(a.data.positions)t=a.data.positions,o=a.data.vertexCount;else{var s=a.data.view;if(!t||!s)throw new Error("positions or view is not defined!");i=a.data.depthMix,r=new Uint32Array(i.buffer),n=new Float32Array(i.buffer);for(var l=0;l<o;l++)r[2*l]=l;for(l=0;l<o;l++)n[2*l+1]=1e4-(s[2]*t[3*l+0]+s[6]*t[3*l+1]+s[10]*t[3*l+2]);i.sort(),e.postMessage({depthMix:i},[i.buffer])}}},t}(Fa),Ix=function(){function e(e){void 0===e&&(e=Recast),this.bjsRECAST={},this.name="RecastJSPlugin",this._maximumSubStepCount=10,this._timeStep=1/60,this._timeFactor=1,this._worker=null,"function"==typeof e?ae.Error("RecastJS is not ready. Please make sure you await Recast() before using the plugin."):this.bjsRECAST=e,this.isSupported()?(this.setTimeStep(),this._tempVec1=new this.bjsRECAST.Vec3,this._tempVec2=new this.bjsRECAST.Vec3):ae.Error("RecastJS is not available. Please make sure you included the js file.")}return e.prototype.setWorkerURL=function(e){return!(!window||!window.Worker||(this._worker=new Worker(e),0))},e.prototype.setTimeStep=function(e){void 0===e&&(e=1/60),this._timeStep=e},e.prototype.getTimeStep=function(){return this._timeStep},e.prototype.setMaximumSubStepCount=function(e){void 0===e&&(e=10),this._maximumSubStepCount=e},e.prototype.getMaximumSubStepCount=function(){return this._maximumSubStepCount},Object.defineProperty(e.prototype,"timeFactor",{get:function(){return this._timeFactor},set:function(e){this._timeFactor=Math.max(e,0)},enumerable:!1,configurable:!0}),e.prototype.createNavMesh=function(e,t,i){var r,n,o;this._worker&&!i?ae.Warn("A worker is avaible but no completion callback. Defaulting to blocking navmesh creation"):!this._worker&&i&&ae.Warn("A completion callback is avaible but no worker. Defaulting to blocking navmesh creation"),this.navMesh=new this.bjsRECAST.NavMesh;var a=[],s=[],l=0;for(r=0;r<e.length;r++)if(e[r]){var c=e[r],u=c.getIndices();if(!u)continue;var h=c.getVerticesData(Nr.PositionKind,!1,!1);if(!h)continue;var d=[],p=c.computeWorldMatrix(!0);if(c.hasThinInstances)for(var f=c.thinInstanceGetWorldMatrices(),_=0;_<f.length;_++){var m=new z;f[_].multiplyToRef(p,m),d.push(m)}else d.push(p);for(var g=0;g<d.length;g++){var v=d[g];for(n=0;n<u.length;n++)a.push(u[n]+l);var y=V.Zero(),b=V.Zero();for(o=0;o<h.length;o+=3)V.FromArrayToRef(h,o,b),V.TransformCoordinatesToRef(b,v,y),s.push(y.x,y.y,y.z);l+=h.length/3}}if(this._worker&&i)this._worker.postMessage([s,l,a,a.length,t]),this._worker.onmessage=function(e){i(e.data)};else{var T=new this.bjsRECAST.rcConfig;T.cs=t.cs,T.ch=t.ch,T.borderSize=t.borderSize?t.borderSize:0,T.tileSize=t.tileSize?t.tileSize:0,T.walkableSlopeAngle=t.walkableSlopeAngle,T.walkableHeight=t.walkableHeight,T.walkableClimb=t.walkableClimb,T.walkableRadius=t.walkableRadius,T.maxEdgeLen=t.maxEdgeLen,T.maxSimplificationError=t.maxSimplificationError,T.minRegionArea=t.minRegionArea,T.mergeRegionArea=t.mergeRegionArea,T.maxVertsPerPoly=t.maxVertsPerPoly,T.detailSampleDist=t.detailSampleDist,T.detailSampleMaxError=t.detailSampleMaxError,this.navMesh.build(s,l,a,a.length,T)}},e.prototype.createDebugNavMesh=function(e){var t,i,r=this.navMesh.getDebugNavMesh(),n=r.getTriangleCount(),o=[],a=[];for(t=0;t<3*n;t++)o.push(t);for(t=0;t<n;t++)for(i=0;i<3;i++){var s=r.getTriangle(t).getPoint(i);a.push(s.x,s.y,s.z)}var l=new Fa("NavMeshDebug",e),c=new _o;return c.indices=o,c.positions=a,c.applyToMesh(l,!1),l},e.prototype.getClosestPoint=function(e){this._tempVec1.x=e.x,this._tempVec1.y=e.y,this._tempVec1.z=e.z;var t=this.navMesh.getClosestPoint(this._tempVec1);return new V(t.x,t.y,t.z)},e.prototype.getClosestPointToRef=function(e,t){this._tempVec1.x=e.x,this._tempVec1.y=e.y,this._tempVec1.z=e.z;var i=this.navMesh.getClosestPoint(this._tempVec1);t.set(i.x,i.y,i.z)},e.prototype.getRandomPointAround=function(e,t){this._tempVec1.x=e.x,this._tempVec1.y=e.y,this._tempVec1.z=e.z;var i=this.navMesh.getRandomPointAround(this._tempVec1,t);return new V(i.x,i.y,i.z)},e.prototype.getRandomPointAroundToRef=function(e,t,i){this._tempVec1.x=e.x,this._tempVec1.y=e.y,this._tempVec1.z=e.z;var r=this.navMesh.getRandomPointAround(this._tempVec1,t);i.set(r.x,r.y,r.z)},e.prototype.moveAlong=function(e,t){this._tempVec1.x=e.x,this._tempVec1.y=e.y,this._tempVec1.z=e.z,this._tempVec2.x=t.x,this._tempVec2.y=t.y,this._tempVec2.z=t.z;var i=this.navMesh.moveAlong(this._tempVec1,this._tempVec2);return new V(i.x,i.y,i.z)},e.prototype.moveAlongToRef=function(e,t,i){this._tempVec1.x=e.x,this._tempVec1.y=e.y,this._tempVec1.z=e.z,this._tempVec2.x=t.x,this._tempVec2.y=t.y,this._tempVec2.z=t.z;var r=this.navMesh.moveAlong(this._tempVec1,this._tempVec2);i.set(r.x,r.y,r.z)},e.prototype._convertNavPathPoints=function(e){var t,i=e.getPointCount(),r=[];for(t=0;t<i;t++){var n=e.getPoint(t);r.push(new V(n.x,n.y,n.z))}return r},e.prototype.computePath=function(e,t){this._tempVec1.x=e.x,this._tempVec1.y=e.y,this._tempVec1.z=e.z,this._tempVec2.x=t.x,this._tempVec2.y=t.y,this._tempVec2.z=t.z;var i=this.navMesh.computePath(this._tempVec1,this._tempVec2);return this._convertNavPathPoints(i)},e.prototype.computePathSmooth=function(e,t){this._tempVec1.x=e.x,this._tempVec1.y=e.y,this._tempVec1.z=e.z,this._tempVec2.x=t.x,this._tempVec2.y=t.y,this._tempVec2.z=t.z;var i=this.navMesh.computePathSmooth(this._tempVec1,this._tempVec2);return this._convertNavPathPoints(i)},e.prototype.createCrowd=function(e,t,i){return new Mx(this,e,t,i)},e.prototype.setDefaultQueryExtent=function(e){this._tempVec1.x=e.x,this._tempVec1.y=e.y,this._tempVec1.z=e.z,this.navMesh.setDefaultQueryExtent(this._tempVec1)},e.prototype.getDefaultQueryExtent=function(){var e=this.navMesh.getDefaultQueryExtent();return new V(e.x,e.y,e.z)},e.prototype.buildFromNavmeshData=function(e){var t=e.length*e.BYTES_PER_ELEMENT,i=this.bjsRECAST._malloc(t),r=new Uint8Array(this.bjsRECAST.HEAPU8.buffer,i,t);r.set(e);var n=new this.bjsRECAST.NavmeshData;n.dataPointer=r.byteOffset,n.size=e.length,this.navMesh=new this.bjsRECAST.NavMesh,this.navMesh.buildFromNavmeshData(n),this.bjsRECAST._free(r.byteOffset)},e.prototype.getNavmeshData=function(){var e=this.navMesh.getNavmeshData(),t=new Uint8Array(this.bjsRECAST.HEAPU8.buffer,e.dataPointer,e.size),i=new Uint8Array(e.size);return i.set(t),this.navMesh.freeNavmeshData(e),i},e.prototype.getDefaultQueryExtentToRef=function(e){var t=this.navMesh.getDefaultQueryExtent();e.set(t.x,t.y,t.z)},e.prototype.dispose=function(){},e.prototype.addCylinderObstacle=function(e,t,i){return this._tempVec1.x=e.x,this._tempVec1.y=e.y,this._tempVec1.z=e.z,this.navMesh.addCylinderObstacle(this._tempVec1,t,i)},e.prototype.addBoxObstacle=function(e,t,i){return this._tempVec1.x=e.x,this._tempVec1.y=e.y,this._tempVec1.z=e.z,this._tempVec2.x=t.x,this._tempVec2.y=t.y,this._tempVec2.z=t.z,this.navMesh.addBoxObstacle(this._tempVec1,this._tempVec2,i)},e.prototype.removeObstacle=function(e){this.navMesh.removeObstacle(e)},e.prototype.isSupported=function(){return void 0!==this.bjsRECAST},e.prototype.getRandomSeed=function(){return this.bjsRECAST._getRandomSeed()},e.prototype.setRandomSeed=function(e){this.bjsRECAST._setRandomSeed(e)},e}(),Mx=function(){function e(e,t,i,r){var n=this;this.recastCrowd={},this.transforms=new Array,this.agents=new Array,this.reachRadii=new Array,this._agentDestinationArmed=new Array,this._agentDestination=new Array,this._onBeforeAnimationsObserver=null,this.onReachTargetObservable=new f,this.bjsRECASTPlugin=e,this.recastCrowd=new this.bjsRECASTPlugin.bjsRECAST.Crowd(t,i,this.bjsRECASTPlugin.navMesh.getNavMesh()),this._scene=r,this._onBeforeAnimationsObserver=r.onBeforeAnimationsObservable.add((function(){n.update(.001*r.getEngine().getDeltaTime()*e.timeFactor)}))}return e.prototype.addAgent=function(e,t,i){var r=new this.bjsRECASTPlugin.bjsRECAST.dtCrowdAgentParams;r.radius=t.radius,r.height=t.height,r.maxAcceleration=t.maxAcceleration,r.maxSpeed=t.maxSpeed,r.collisionQueryRange=t.collisionQueryRange,r.pathOptimizationRange=t.pathOptimizationRange,r.separationWeight=t.separationWeight,r.updateFlags=7,r.obstacleAvoidanceType=0,r.queryFilterType=0,r.userData=0;var n=this.recastCrowd.addAgent(new this.bjsRECASTPlugin.bjsRECAST.Vec3(e.x,e.y,e.z),r);return this.transforms.push(i),this.agents.push(n),this.reachRadii.push(t.reachRadius?t.reachRadius:t.radius),this._agentDestinationArmed.push(!1),this._agentDestination.push(new V(0,0,0)),n},e.prototype.getAgentPosition=function(e){var t=this.recastCrowd.getAgentPosition(e);return new V(t.x,t.y,t.z)},e.prototype.getAgentPositionToRef=function(e,t){var i=this.recastCrowd.getAgentPosition(e);t.set(i.x,i.y,i.z)},e.prototype.getAgentVelocity=function(e){var t=this.recastCrowd.getAgentVelocity(e);return new V(t.x,t.y,t.z)},e.prototype.getAgentVelocityToRef=function(e,t){var i=this.recastCrowd.getAgentVelocity(e);t.set(i.x,i.y,i.z)},e.prototype.getAgentNextTargetPath=function(e){var t=this.recastCrowd.getAgentNextTargetPath(e);return new V(t.x,t.y,t.z)},e.prototype.getAgentNextTargetPathToRef=function(e,t){var i=this.recastCrowd.getAgentNextTargetPath(e);t.set(i.x,i.y,i.z)},e.prototype.getAgentState=function(e){return this.recastCrowd.getAgentState(e)},e.prototype.overOffmeshConnection=function(e){return this.recastCrowd.overOffmeshConnection(e)},e.prototype.agentGoto=function(e,t){this.recastCrowd.agentGoto(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z));var i=this.agents.indexOf(e);i>-1&&(this._agentDestinationArmed[i]=!0,this._agentDestination[i].set(t.x,t.y,t.z))},e.prototype.agentTeleport=function(e,t){this.recastCrowd.agentTeleport(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z))},e.prototype.updateAgentParameters=function(e,t){var i=this.recastCrowd.getAgentParameters(e);void 0!==t.radius&&(i.radius=t.radius),void 0!==t.height&&(i.height=t.height),void 0!==t.maxAcceleration&&(i.maxAcceleration=t.maxAcceleration),void 0!==t.maxSpeed&&(i.maxSpeed=t.maxSpeed),void 0!==t.collisionQueryRange&&(i.collisionQueryRange=t.collisionQueryRange),void 0!==t.pathOptimizationRange&&(i.pathOptimizationRange=t.pathOptimizationRange),void 0!==t.separationWeight&&(i.separationWeight=t.separationWeight),this.recastCrowd.setAgentParameters(e,i)},e.prototype.removeAgent=function(e){this.recastCrowd.removeAgent(e);var t=this.agents.indexOf(e);t>-1&&(this.agents.splice(t,1),this.transforms.splice(t,1),this.reachRadii.splice(t,1),this._agentDestinationArmed.splice(t,1),this._agentDestination.splice(t,1))},e.prototype.getAgents=function(){return this.agents},e.prototype.update=function(e){if(this.bjsRECASTPlugin.navMesh.update(),!(e<=A)){var t=this.bjsRECASTPlugin.getTimeStep(),i=this.bjsRECASTPlugin.getMaximumSubStepCount();if(t<=A)this.recastCrowd.update(e);else{var r=Math.floor(e/t);i&&r>i&&(r=i),r<1&&(r=1);for(var n=e/r,o=0;o<r;o++)this.recastCrowd.update(n)}for(var a=0;a<this.agents.length;a++){var s=this.agents[a],l=this.getAgentPosition(s);if(this.transforms[a].position=l,this._agentDestinationArmed[a]){var c=l.x-this._agentDestination[a].x,u=l.z-this._agentDestination[a].z,h=this.reachRadii[a],d=this._agentDestination[a].y-this.reachRadii[a],p=this._agentDestination[a].y+this.reachRadii[a],f=c*c+u*u;l.y>d&&l.y<p&&f<h*h&&(this._agentDestinationArmed[a]=!1,this.onReachTargetObservable.notifyObservers({agentIndex:s,destination:this._agentDestination[a]}))}}}},e.prototype.setDefaultQueryExtent=function(e){var t=new this.bjsRECASTPlugin.bjsRECAST.Vec3(e.x,e.y,e.z);this.recastCrowd.setDefaultQueryExtent(t)},e.prototype.getDefaultQueryExtent=function(){var e=this.recastCrowd.getDefaultQueryExtent();return new V(e.x,e.y,e.z)},e.prototype.getDefaultQueryExtentToRef=function(e){var t=this.recastCrowd.getDefaultQueryExtent();e.set(t.x,t.y,t.z)},e.prototype.getCorners=function(e){var t,i=this.recastCrowd.getCorners(e),r=i.getPointCount(),n=[];for(t=0;t<r;t++){var o=i.getPoint(t);n.push(new V(o.x,o.y,o.z))}return n},e.prototype.dispose=function(){this.recastCrowd.destroy(),this._scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver),this._onBeforeAnimationsObserver=null,this.onReachTargetObservable.clear()},e}();Do.OfflineProviderFactory=function(e,t,i){return void 0===i&&(i=!1),new Ox(e,t,i)};var Ox=function(){function e(t,i,r){void 0===r&&(r=!1),this._idbFactory="undefined"!=typeof indexedDB?indexedDB:void 0,this._currentSceneUrl=e._ReturnFullUrlLocation(t),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,e.IDBStorageEnabled?r?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,rr.SetImmediate((function(){i(!0)}))):this._checkManifestFile(i):i(!0)}return Object.defineProperty(e.prototype,"enableSceneOffline",{get:function(){return this._enableSceneOffline},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"enableTexturesOffline",{get:function(){return this._enableTexturesOffline},enumerable:!1,configurable:!0}),e.prototype._checkManifestFile=function(t){var i=this,r=function(){i._enableSceneOffline=!1,i._enableTexturesOffline=!1,t(!1)},n=function(){try{if("function"==typeof URL&&0===i._currentSceneUrl.indexOf("http")){var e=new URL(i._currentSceneUrl);return e.pathname+=".manifest",e.toString()}}catch(e){}return"".concat(i._currentSceneUrl,".manifest")},o=!1,a=n(),s=new Je;navigator.onLine&&(o=!0,a=a+(null==a.match(/\?/)?"?":"&")+Date.now()),s.open("GET",a),s.addEventListener("load",(function(){if(200===s.status||e._ValidateXHRData(s,1))try{var n=JSON.parse(s.response);i._enableSceneOffline=n.enableSceneOffline,i._enableTexturesOffline=n.enableTexturesOffline&&e._IsUASupportingBlobStorage,n.version&&!isNaN(parseInt(n.version))&&(i._manifestVersionFound=n.version),t(!0)}catch(e){r()}else r()}),!1),s.addEventListener("error",(function(){if(o){o=!1;var e=n();s.open("GET",e),s.send()}else r()}),!1);try{s.send()}catch(e){ae.Error("Error on XHR send request."),t(!1)}},e.prototype.open=function(e,t){var i=this,r=function(){i._isSupported=!1,t&&t()};if(this._idbFactory&&(this._enableSceneOffline||this._enableTexturesOffline))if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;var n=this._idbFactory.open("babylonjs",1);n.onerror=function(){r()},n.onblocked=function(){ae.Error("IDB request blocked. Please reload the page."),r()},n.onsuccess=function(){i._db=n.result,e()},n.onupgradeneeded=function(e){if(i._db=e.target.result,i._db)try{i._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),i._db.createObjectStore("versions",{keyPath:"sceneUrl"}),i._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(e){ae.Error("Error while creating object stores. Exception: "+e.message),r()}}}else this._isSupported=!1,t&&t()},e.prototype.loadImage=function(t,i){var r=this,n=e._ReturnFullUrlLocation(t),o=function(){r._hasReachedQuota||null===r._db?i.src=t:r._saveImageIntoDBAsync(n,i)};this._mustUpdateRessources?o():this._loadImageFromDBAsync(n,i,o)},e.prototype._loadImageFromDBAsync=function(e,t,i){if(this._isSupported&&null!==this._db){var r,n=this._db.transaction(["textures"]);n.onabort=function(){t.src=e},n.oncomplete=function(){var n;r&&"function"==typeof URL?(n=URL.createObjectURL(r.data),t.onerror=function(){ae.Error("Error loading image from blob URL: "+n+" switching back to web url: "+e),t.src=e},t.src=n):i()};var o=n.objectStore("textures").get(e);o.onsuccess=function(e){r=e.target.result},o.onerror=function(){ae.Error("Error loading texture "+e+" from DB."),t.src=e}}else ae.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t.src=e},e.prototype._saveImageIntoDBAsync=function(t,i){var r,n=this;if(this._isSupported){var o=function(){var e;if(r&&"function"==typeof URL)try{e=URL.createObjectURL(r)}catch(t){e=URL.createObjectURL(r)}e&&(i.src=e)};if(e._IsUASupportingBlobStorage){var a=new Je;a.open("GET",t),a.responseType="blob",a.addEventListener("load",(function(){if(200===a.status&&n._db){r=a.response;var s=n._db.transaction(["textures"],"readwrite");s.onabort=function(e){try{var t=e.target.error;t&&"QuotaExceededError"===t.name&&(n._hasReachedQuota=!0)}catch(e){}o()},s.oncomplete=function(){o()};var l={textureUrl:t,data:r};try{var c=s.objectStore("textures").put(l);c.onsuccess=function(){},c.onerror=function(){o()}}catch(r){25===r.code&&(e._IsUASupportingBlobStorage=!1,n._enableTexturesOffline=!1),i.src=t}}else i.src=t}),!1),a.addEventListener("error",(function(){ae.Error("Error in XHR request in BABYLON.Database."),i.src=t}),!1),a.send()}else i.src=t}else ae.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),i.src=t},e.prototype._checkVersionFromDB=function(e,t){var i=this;this._loadVersionFromDBAsync(e,t,(function(){i._saveVersionIntoDBAsync(e,t)}))},e.prototype._loadVersionFromDBAsync=function(e,t,i){var r,n=this;if(this._isSupported&&this._db)try{var o=this._db.transaction(["versions"]);o.oncomplete=function(){r?n._manifestVersionFound!==r.data?(n._mustUpdateRessources=!0,i()):t(r.data):(n._mustUpdateRessources=!0,i())},o.onabort=function(){t(-1)};var a=o.objectStore("versions").get(e);a.onsuccess=function(e){r=e.target.result},a.onerror=function(){ae.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(e){ae.Error("Error while accessing 'versions' object store (READ OP). Exception: "+e.message),t(-1)}else ae.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t(-1)},e.prototype._saveVersionIntoDBAsync=function(e,t){var i=this;if(this._isSupported&&!this._hasReachedQuota&&this._db)try{var r=this._db.transaction(["versions"],"readwrite");r.onabort=function(e){try{var r=e.target.error;r&&"QuotaExceededError"===r.name&&(i._hasReachedQuota=!0)}catch(e){}t(-1)},r.oncomplete=function(){t(i._manifestVersionFound)};var n={sceneUrl:e,data:this._manifestVersionFound},o=r.objectStore("versions").put(n);o.onsuccess=function(){},o.onerror=function(){ae.Error("Error in DB add version request in BABYLON.Database.")}}catch(e){ae.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+e.message),t(-1)}else t(-1)},e.prototype.loadFile=function(t,i,r,n,o){var a=this,s=e._ReturnFullUrlLocation(t),l=function(){a._saveFileAsync(s,i,r,o,n)};this._checkVersionFromDB(s,(function(e){-1!==e?a._mustUpdateRessources?a._saveFileAsync(s,i,r,o,n):a._loadFileAsync(s,i,l):n&&n()}))},e.prototype._loadFileAsync=function(e,t,i){if(this._isSupported&&this._db){var r,n;n=-1!==e.indexOf(".babylon")?"scenes":"textures";var o=this._db.transaction([n]);o.oncomplete=function(){r?t(r.data):i()},o.onabort=function(){i()};var a=o.objectStore(n).get(e);a.onsuccess=function(e){r=e.target.result},a.onerror=function(){ae.Error("Error loading file "+e+" from DB."),i()}}else ae.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()},e.prototype._saveFileAsync=function(t,i,r,n,o){var a=this;if(this._isSupported){var s;s=-1!==t.indexOf(".babylon")?"scenes":"textures";var l,c=new Je;c.open("GET",t+(null==t.match(/\?/)?"?":"&")+Date.now()),n&&(c.responseType="arraybuffer"),r&&(c.onprogress=r),c.addEventListener("load",(function(){if(200===c.status||c.status<400&&e._ValidateXHRData(c,n?6:1))if(l=n?c.response:c.responseText,!a._hasReachedQuota&&a._db){var r=a._db.transaction([s],"readwrite");r.onabort=function(e){try{var t=e.target.error;t&&"QuotaExceededError"===t.name&&(a._hasReachedQuota=!0)}catch(e){}i(l)},r.oncomplete=function(){i(l)};var u;u="scenes"===s?{sceneUrl:t,data:l,version:a._manifestVersionFound}:{textureUrl:t,data:l};try{var h=r.objectStore(s).put(u);h.onsuccess=function(){},h.onerror=function(){ae.Error("Error in DB add file request in BABYLON.Database.")}}catch(e){i(l)}}else i(l);else c.status>=400&&o?o(c):i()}),!1),c.addEventListener("error",(function(){ae.Error("error on XHR request."),o&&o()}),!1),c.send()}else ae.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),o&&o()},e._ValidateXHRData=function(e,t){void 0===t&&(t=7);try{if(1&t){if(e.responseText&&e.responseText.length>0)return!0;if(1===t)return!1}if(2&t){var i=by(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(2===t)return!1}if(4&t){var r=new Uint8Array(e.response,0,3);return 68===r[0]&&68===r[1]&&83===r[2]}}catch(e){}return!1},e._IsUASupportingBlobStorage=!0,e.IDBStorageEnabled=!1,e._ParseURL=function(e){document.createElement("a").href=e;var t=e.substring(0,e.lastIndexOf("#")),i=e.substring(t.lastIndexOf("/")+1,e.length);return e.substring(0,e.indexOf(i,0))},e._ReturnFullUrlLocation=function(t){return-1===t.indexOf("http:/")&&-1===t.indexOf("https:/")&&"undefined"!=typeof window?e._ParseURL(window.location.href)+t:t},e}(),Dx=function(){function e(){this.direction1=new V(0,1,0),this.direction2=new V(0,1,0),this.minEmitBox=new V(-.5,-.5,-.5),this.maxEmitBox=new V(.5,.5,.5)}return e.prototype.startDirectionFunction=function(e,t,i,r){var n=D(this.direction1.x,this.direction2.x),o=D(this.direction1.y,this.direction2.y),a=D(this.direction1.z,this.direction2.z);if(r)return t.x=n,t.y=o,void(t.z=a);V.TransformNormalFromFloatsToRef(n,o,a,e,t)},e.prototype.startPositionFunction=function(e,t,i,r){var n=D(this.minEmitBox.x,this.maxEmitBox.x),o=D(this.minEmitBox.y,this.maxEmitBox.y),a=D(this.minEmitBox.z,this.maxEmitBox.z);if(r)return t.x=n,t.y=o,void(t.z=a);V.TransformCoordinatesFromFloatsToRef(n,o,a,e,t)},e.prototype.clone=function(){var t=new e;return ye.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)},e.prototype.buildUniformLayout=function(e){e.addUniform("direction1",3),e.addUniform("direction2",3),e.addUniform("minEmitBox",3),e.addUniform("maxEmitBox",3)},e.prototype.getEffectDefines=function(){return"#define BOXEMITTER"},e.prototype.getClassName=function(){return"BoxParticleEmitter"},e.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e},e.prototype.parse=function(e){V.FromArrayToRef(e.direction1,0,this.direction1),V.FromArrayToRef(e.direction2,0,this.direction2),V.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),V.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)},e}(),Nx=function(){function e(e,t,i){void 0===e&&(e=1),void 0===t&&(t=Math.PI),void 0===i&&(i=0),this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}return Object.defineProperty(e.prototype,"radius",{get:function(){return this._radius},set:function(e){this._radius=e,this._buildHeight()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"angle",{get:function(){return this._angle},set:function(e){this._angle=e,this._buildHeight()},enumerable:!1,configurable:!0}),e.prototype._buildHeight=function(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1},e.prototype.startDirectionFunction=function(e,t,i,r){r?H.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),H.Vector3[0]).normalize();var n=j.RandomRange(0,this.directionRandomizer),o=j.RandomRange(0,this.directionRandomizer),a=j.RandomRange(0,this.directionRandomizer);t.x=H.Vector3[0].x+n,t.y=H.Vector3[0].y+o,t.z=H.Vector3[0].z+a,t.normalize()},e.prototype.startPositionFunction=function(e,t,i,r){var n,o=j.RandomRange(0,2*Math.PI);n=this.emitFromSpawnPointOnly?1e-4:1-(n=j.RandomRange(0,this.heightRange))*n;var a=this._radius-j.RandomRange(0,this._radius*this.radiusRange),s=(a*=n)*Math.sin(o),l=a*Math.cos(o),c=n*this._height;if(r)return t.x=s,t.y=c,void(t.z=l);V.TransformCoordinatesFromFloatsToRef(s,c,l,e,t)},e.prototype.clone=function(){var t=new e(this._radius,this._angle,this.directionRandomizer);return ye.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)},e.prototype.buildUniformLayout=function(e){e.addUniform("radius",2),e.addUniform("coneAngle",1),e.addUniform("height",2),e.addUniform("directionRandomizer",1)},e.prototype.getEffectDefines=function(){var e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+="\n#define CONEEMITTERSPAWNPOINT"),e},e.prototype.getClassName=function(){return"ConeParticleEmitter"},e.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e.radiusRange=this.radiusRange,e.heightRange=this.heightRange,e.emitFromSpawnPointOnly=this.emitFromSpawnPointOnly,e},e.prototype.parse=function(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer,this.radiusRange=void 0!==e.radiusRange?e.radiusRange:1,this.heightRange=void 0!==e.radiusRange?e.heightRange:1,this.emitFromSpawnPointOnly=void 0!==e.emitFromSpawnPointOnly&&e.emitFromSpawnPointOnly},e}(),Fx=function(){function e(e,t,i,r){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=1),void 0===r&&(r=0),this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=r,this._tempVector=V.Zero()}return e.prototype.startDirectionFunction=function(e,t,i,r,n){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),V.TransformNormalToRef(this._tempVector,n,this._tempVector);var o=j.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2),a=Math.atan2(this._tempVector.x,this._tempVector.z);a+=j.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=o,this._tempVector.x=Math.sin(a),this._tempVector.z=Math.cos(a),this._tempVector.normalize(),r?t.copyFrom(this._tempVector):V.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)},e.prototype.startPositionFunction=function(e,t,i,r){var n=j.RandomRange(-this.height/2,this.height/2),o=j.RandomRange(0,2*Math.PI),a=j.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),s=Math.sqrt(a)*this.radius,l=s*Math.cos(o),c=s*Math.sin(o);r?t.copyFromFloats(l,n,c):V.TransformCoordinatesFromFloatsToRef(l,n,c,e,t)},e.prototype.clone=function(){var t=new e(this.radius,this.directionRandomizer);return ye.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)},e.prototype.buildUniformLayout=function(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)},e.prototype.getEffectDefines=function(){return"#define CYLINDEREMITTER"},e.prototype.getClassName=function(){return"CylinderParticleEmitter"},e.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this.radius,e.height=this.height,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e},e.prototype.parse=function(e){this.radius=e.radius,this.height=e.height,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer},e}(),Lx=function(e){function t(t,i,r,n,o){void 0===t&&(t=1),void 0===i&&(i=1),void 0===r&&(r=1),void 0===n&&(n=new V(0,1,0)),void 0===o&&(o=new V(0,1,0));var a=e.call(this,t,i,r)||this;return a.direction1=n,a.direction2=o,a}return m(t,e),t.prototype.startDirectionFunction=function(e,t,i,r){var n=j.RandomRange(this.direction1.x,this.direction2.x),o=j.RandomRange(this.direction1.y,this.direction2.y),a=j.RandomRange(this.direction1.z,this.direction2.z);r?t.copyFromFloats(n,o,a):V.TransformNormalFromFloatsToRef(n,o,a,e,t)},t.prototype.clone=function(){var e=new t(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return ye.DeepCopy(this,e),e},t.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)},t.prototype.buildUniformLayout=function(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)},t.prototype.getEffectDefines=function(){return"#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER"},t.prototype.getClassName=function(){return"CylinderDirectedParticleEmitter"},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.direction1=this.direction1.asArray(),t.direction2=this.direction2.asArray(),t},t.prototype.parse=function(t){e.prototype.parse.call(this,t),V.FromArrayToRef(t.direction1,0,this.direction1),V.FromArrayToRef(t.direction2,0,this.direction2)},t}(Fx),wx=function(){function e(e,t,i){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=0),this.radius=e,this.radiusRange=t,this.directionRandomizer=i}return e.prototype.startDirectionFunction=function(e,t,i,r){var n=i.position.subtract(e.getTranslation()).normalize(),o=j.RandomRange(0,this.directionRandomizer),a=j.RandomRange(0,this.directionRandomizer),s=j.RandomRange(0,this.directionRandomizer);n.x+=o,n.y+=a,n.z+=s,n.normalize(),r?t.copyFrom(n):V.TransformNormalFromFloatsToRef(n.x,n.y,n.z,e,t)},e.prototype.startPositionFunction=function(e,t,i,r){var n=this.radius-j.RandomRange(0,this.radius*this.radiusRange),o=j.RandomRange(0,1),a=j.RandomRange(0,2*Math.PI),s=Math.acos(2*o-1),l=n*Math.cos(a)*Math.sin(s),c=n*Math.cos(s),u=n*Math.sin(a)*Math.sin(s);r?t.copyFromFloats(l,Math.abs(c),u):V.TransformCoordinatesFromFloatsToRef(l,Math.abs(c),u,e,t)},e.prototype.clone=function(){var t=new e(this.radius,this.directionRandomizer);return ye.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)},e.prototype.buildUniformLayout=function(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)},e.prototype.getEffectDefines=function(){return"#define HEMISPHERICEMITTER"},e.prototype.getClassName=function(){return"HemisphericParticleEmitter"},e.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e},e.prototype.parse=function(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer},e}(),Bx=function(){function e(){this.direction1=new V(0,1,0),this.direction2=new V(0,1,0)}return e.prototype.startDirectionFunction=function(e,t,i,r){var n=j.RandomRange(this.direction1.x,this.direction2.x),o=j.RandomRange(this.direction1.y,this.direction2.y),a=j.RandomRange(this.direction1.z,this.direction2.z);r?t.copyFromFloats(n,o,a):V.TransformNormalFromFloatsToRef(n,o,a,e,t)},e.prototype.startPositionFunction=function(e,t,i,r){r?t.copyFromFloats(0,0,0):V.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)},e.prototype.clone=function(){var t=new e;return ye.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)},e.prototype.buildUniformLayout=function(e){e.addUniform("direction1",3),e.addUniform("direction2",3)},e.prototype.getEffectDefines=function(){return"#define POINTEMITTER"},e.prototype.getClassName=function(){return"PointParticleEmitter"},e.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e},e.prototype.parse=function(e){V.FromArrayToRef(e.direction1,0,this.direction1),V.FromArrayToRef(e.direction2,0,this.direction2)},e}(),Ux=function(){function e(e,t,i){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=0),this.radius=e,this.radiusRange=t,this.directionRandomizer=i}return e.prototype.startDirectionFunction=function(e,t,i,r){var n=i.position.subtract(e.getTranslation()).normalize(),o=j.RandomRange(0,this.directionRandomizer),a=j.RandomRange(0,this.directionRandomizer),s=j.RandomRange(0,this.directionRandomizer);n.x+=o,n.y+=a,n.z+=s,n.normalize(),r?t.copyFrom(n):V.TransformNormalFromFloatsToRef(n.x,n.y,n.z,e,t)},e.prototype.startPositionFunction=function(e,t,i,r){var n=this.radius-j.RandomRange(0,this.radius*this.radiusRange),o=j.RandomRange(0,1),a=j.RandomRange(0,2*Math.PI),s=Math.acos(2*o-1),l=n*Math.cos(a)*Math.sin(s),c=n*Math.cos(s),u=n*Math.sin(a)*Math.sin(s);r?t.copyFromFloats(l,c,u):V.TransformCoordinatesFromFloatsToRef(l,c,u,e,t)},e.prototype.clone=function(){var t=new e(this.radius,this.directionRandomizer);return ye.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)},e.prototype.buildUniformLayout=function(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)},e.prototype.getEffectDefines=function(){return"#define SPHEREEMITTER"},e.prototype.getClassName=function(){return"SphereParticleEmitter"},e.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e},e.prototype.parse=function(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer},e}(),Vx=function(e){function t(t,i,r){void 0===t&&(t=1),void 0===i&&(i=new V(0,1,0)),void 0===r&&(r=new V(0,1,0));var n=e.call(this,t)||this;return n.direction1=i,n.direction2=r,n}return m(t,e),t.prototype.startDirectionFunction=function(e,t){var i=j.RandomRange(this.direction1.x,this.direction2.x),r=j.RandomRange(this.direction1.y,this.direction2.y),n=j.RandomRange(this.direction1.z,this.direction2.z);V.TransformNormalFromFloatsToRef(i,r,n,e,t)},t.prototype.clone=function(){var e=new t(this.radius,this.direction1,this.direction2);return ye.DeepCopy(this,e),e},t.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)},t.prototype.buildUniformLayout=function(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)},t.prototype.getEffectDefines=function(){return"#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"},t.prototype.getClassName=function(){return"SphereDirectedParticleEmitter"},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.direction1=this.direction1.asArray(),t.direction2=this.direction2.asArray(),t},t.prototype.parse=function(t){e.prototype.parse.call(this,t),this.direction1.copyFrom(t.direction1),this.direction2.copyFrom(t.direction2)},t}(Ux),kx=function(){function e(){this.particlePositionGenerator=function(){},this.particleDestinationGenerator=function(){}}return e.prototype.startDirectionFunction=function(e,t,i,r){var n=H.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,n);var o=H.Vector3[1];n.subtractToRef(i.position,o),o.scaleToRef(1/i.lifeTime,n)}else n.set(0,0,0);r?t.copyFrom(n):V.TransformNormalToRef(n,e,t)},e.prototype.startPositionFunction=function(e,t,i,r){var n=H.Vector3[0];this.particlePositionGenerator?this.particlePositionGenerator(-1,i,n):n.set(0,0,0),r?t.copyFrom(n):V.TransformCoordinatesToRef(n,e,t)},e.prototype.clone=function(){var t=new e;return ye.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){},e.prototype.buildUniformLayout=function(e){},e.prototype.getEffectDefines=function(){return"#define CUSTOMEMITTER"},e.prototype.getClassName=function(){return"CustomParticleEmitter"},e.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.particlePositionGenerator=this.particlePositionGenerator,e.particleDestinationGenerator=this.particleDestinationGenerator,e},e.prototype.parse=function(e){e.particlePositionGenerator&&(this.particlePositionGenerator=e.particlePositionGenerator),e.particleDestinationGenerator&&(this.particleDestinationGenerator=e.particleDestinationGenerator)},e}(),Gx=function(){function e(e){void 0===e&&(e=null),this._indices=null,this._positions=null,this._normals=null,this._storedNormal=V.Zero(),this._mesh=null,this.direction1=new V(0,1,0),this.direction2=new V(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}return Object.defineProperty(e.prototype,"mesh",{get:function(){return this._mesh},set:function(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(Nr.PositionKind),this._normals=e.getVerticesData(Nr.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))},enumerable:!1,configurable:!0}),e.prototype.startDirectionFunction=function(e,t,i,r){if(this.useMeshNormalsForDirection&&this._normals)V.TransformNormalToRef(this._storedNormal,e,t);else{var n=j.RandomRange(this.direction1.x,this.direction2.x),o=j.RandomRange(this.direction1.y,this.direction2.y),a=j.RandomRange(this.direction1.z,this.direction2.z);r?t.copyFromFloats(n,o,a):V.TransformNormalFromFloatsToRef(n,o,a,e,t)}},e.prototype.startPositionFunction=function(e,t,i,r){if(this._indices&&this._positions){var n=3*Math.random()*(this._indices.length/3)|0,o=Math.random(),a=Math.random()*(1-o),s=1-o-a,l=this._indices[n],c=this._indices[n+1],u=this._indices[n+2],h=H.Vector3[0],d=H.Vector3[1],p=H.Vector3[2],f=H.Vector3[3];V.FromArrayToRef(this._positions,3*l,h),V.FromArrayToRef(this._positions,3*c,d),V.FromArrayToRef(this._positions,3*u,p),f.x=o*h.x+a*d.x+s*p.x,f.y=o*h.y+a*d.y+s*p.y,f.z=o*h.z+a*d.z+s*p.z,r?t.copyFromFloats(f.x,f.y,f.z):V.TransformCoordinatesFromFloatsToRef(f.x,f.y,f.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(V.FromArrayToRef(this._normals,3*l,h),V.FromArrayToRef(this._normals,3*c,d),V.FromArrayToRef(this._normals,3*u,p),this._storedNormal.x=o*h.x+a*d.x+s*p.x,this._storedNormal.y=o*h.y+a*d.y+s*p.y,this._storedNormal.z=o*h.z+a*d.z+s*p.z)}},e.prototype.clone=function(){var t=new e(this.mesh);return ye.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)},e.prototype.buildUniformLayout=function(e){e.addUniform("direction1",3),e.addUniform("direction2",3)},e.prototype.getEffectDefines=function(){return""},e.prototype.getClassName=function(){return"MeshParticleEmitter"},e.prototype.serialize=function(){var e,t={};return t.type=this.getClassName(),t.direction1=this.direction1.asArray(),t.direction2=this.direction2.asArray(),t.meshId=null===(e=this.mesh)||void 0===e?void 0:e.id,t.useMeshNormalsForDirection=this.useMeshNormalsForDirection,t},e.prototype.parse=function(e,t){V.FromArrayToRef(e.direction1,0,this.direction1),V.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection},e}(),zx=function(){function e(e){this._isUbo(e)?(this.setMatrix3x3=e.updateMatrix3x3.bind(e),this.setMatrix2x2=e.updateMatrix2x2.bind(e),this.setFloat=e.updateFloat.bind(e),this.setFloat2=e.updateFloat2.bind(e),this.setFloat3=e.updateFloat3.bind(e),this.setFloat4=e.updateFloat4.bind(e),this.setFloatArray=e.updateFloatArray.bind(e),this.setArray=e.updateArray.bind(e),this.setIntArray=e.updateIntArray.bind(e),this.setMatrix=e.updateMatrix.bind(e),this.setMatrices=e.updateMatrices.bind(e),this.setVector3=e.updateVector3.bind(e),this.setVector4=e.updateVector4.bind(e),this.setColor3=e.updateColor3.bind(e),this.setColor4=e.updateColor4.bind(e),this.setDirectColor4=e.updateDirectColor4.bind(e),this.setInt=e.updateInt.bind(e),this.setInt2=e.updateInt2.bind(e),this.setInt3=e.updateInt3.bind(e),this.setInt4=e.updateInt4.bind(e)):(this.setMatrix3x3=e.setMatrix3x3.bind(e),this.setMatrix2x2=e.setMatrix2x2.bind(e),this.setFloat=e.setFloat.bind(e),this.setFloat2=e.setFloat2.bind(e),this.setFloat3=e.setFloat3.bind(e),this.setFloat4=e.setFloat4.bind(e),this.setFloatArray=e.setFloatArray.bind(e),this.setArray=e.setArray.bind(e),this.setIntArray=e.setIntArray.bind(e),this.setMatrix=e.setMatrix.bind(e),this.setMatrices=e.setMatrices.bind(e),this.setVector3=e.setVector3.bind(e),this.setVector4=e.setVector4.bind(e),this.setColor3=e.setColor3.bind(e),this.setColor4=e.setColor4.bind(e),this.setDirectColor4=e.setDirectColor4.bind(e),this.setInt=e.setInt.bind(e),this.setInt2=e.setInt2.bind(e),this.setInt3=e.setInt3.bind(e),this.setInt4=e.setInt4.bind(e))}return e.prototype._isUbo=function(e){return void 0!==e.addUniform},e}();li.ShadersStore.gpuUpdateParticlesPixelShader="#version 300 es\nvoid main() {discard;}\n";li.ShadersStore.gpuUpdateParticlesVertexShader="#version 300 es\n#define PI 3.14159\nuniform float currentCount;uniform float timeDelta;uniform float stopFactor;\n#ifndef LOCAL\nuniform mat4 emitterWM;\n#endif\nuniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;uniform vec4 color2;\n#endif\nuniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;uniform float radiusRange;uniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;uniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;uniform float height;uniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;uniform float coneAngle;uniform vec2 height;uniform float directionRandomizer;\n#endif\nin vec3 position;\n#ifdef CUSTOMEMITTER\nin vec3 initialPosition;\n#endif\nin float age;in float life;in vec4 seed;in vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;in vec3 noiseCoordinates2;\n#endif\nout vec3 outPosition;\n#ifdef CUSTOMEMITTER\nout vec3 outInitialPosition;\n#endif\nout float outAge;out float outLife;out vec4 outSeed;out vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;uniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec4 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;}\nvec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));}\nvoid main() {float newAge=age+timeDelta; \nif (newAge>=life && stopFactor != 0.) {vec3 newPosition;vec3 newDirection;vec4 randoms=getRandomVec4(seed.x);outLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;outAge=newAge-life;outSeed=seed;\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=newPosition+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\nnewDirection=normalize(direction1+(direction2-direction1)*randoms3);\n#else\nnewDirection=normalize(newPosition+directionRandomizer*randoms3);\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float yPos=(randoms2.x-0.5)*height;float angle=randoms2.y*PI*2.;float inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));float positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));float xPos=positionRadius*cos(angle);float zPos=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\nnewDirection=direction1+(direction2-direction1)*randoms3;\n#else\nangle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.0001;\n#else\nfloat h=randoms2.y*height.y;h=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;lRadius=lRadius*h;float randX=lRadius*sin(s);float randZ=lRadius*cos(s);float randY=h *height.x;newPosition=vec3(randX,randY,randZ); \nif (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {vec3 randoms3=getRandomVec3(seed.z);newDirection=normalize(newPosition+directionRandomizer*randoms3); }\n#elif defined(CUSTOMEMITTER)\nnewPosition=initialPosition;outInitialPosition=initialPosition;\n#else \nnewPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\n#ifdef LOCAL\noutPosition=newPosition;\n#else\noutPosition=(emitterWM*vec4(newPosition,1.)).xyz;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#ifndef BILLBOARD \noutInitialDirection=direction;\n#endif\n#else\n#ifdef LOCAL\nvec3 initial=newDirection;\n#else \nvec3 initial=(emitterWM*vec4(newDirection,0.)).xyz;\n#endif\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#if defined(CUSTOMEMITTER)\noutPosition=position+(direction-position)*ageGradient; \noutInitialPosition=initialPosition;\n#else\noutPosition=position+direction*directionScale;\n#endif\noutLife=life;outSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#else\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;float fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;float fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;vec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;outDirection=outDirection+force*timeDelta;outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2;\n#endif \n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;float dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset;\n#else\nfloat cellStartOffset=0.;\n#endif \nfloat ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);}\nelse {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);}\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}}";var Wx=function(){function e(e,t){this._renderVAO=[],this._updateVAO=[],this.alignDataInBuffer=!1,this._parent=e,this._engine=t,this._updateEffectOptions={attributes:["position","initialPosition","age","life","seed","size","color","direction","initialDirection","angle","cellIndex","cellStartOffset","noiseCoordinates1","noiseCoordinates2"],uniformsNames:["currentCount","timeDelta","emitterWM","lifeTime","color1","color2","sizeRange","scaleRange","gravity","emitPower","direction1","direction2","minEmitBox","maxEmitBox","radius","directionRandomizer","height","coneAngle","stopFactor","angleRange","radiusRange","cellInfos","noiseStrength","limitVelocityDamping"],uniformBuffersNames:[],samplers:["randomSampler","randomSampler2","sizeGradientSampler","angularSpeedGradientSampler","velocityGradientSampler","limitVelocityGradientSampler","noiseSampler","dragGradientSampler"],defines:"",fallbacks:null,onCompiled:null,onError:null,indexParameters:null,maxSimultaneousLights:0,transformFeedbackVaryings:[]}}return e.prototype.contextLost=function(){this._updateEffect=void 0,this._renderVAO.length=0,this._updateVAO.length=0},e.prototype.isUpdateBufferCreated=function(){return!!this._updateEffect},e.prototype.isUpdateBufferReady=function(){var e,t;return null!==(t=null===(e=this._updateEffect)||void 0===e?void 0:e.isReady())&&void 0!==t&&t},e.prototype.createUpdateBuffer=function(e){return this._updateEffectOptions.transformFeedbackVaryings=["outPosition"],this._updateEffectOptions.transformFeedbackVaryings.push("outAge"),this._updateEffectOptions.transformFeedbackVaryings.push("outSize"),this._updateEffectOptions.transformFeedbackVaryings.push("outLife"),this._updateEffectOptions.transformFeedbackVaryings.push("outSeed"),this._updateEffectOptions.transformFeedbackVaryings.push("outDirection"),this._parent.particleEmitterType instanceof kx&&this._updateEffectOptions.transformFeedbackVaryings.push("outInitialPosition"),this._parent._colorGradientsTexture||this._updateEffectOptions.transformFeedbackVaryings.push("outColor"),this._parent._isBillboardBased||this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection"),this._parent.noiseTexture&&(this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1"),this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2")),this._updateEffectOptions.transformFeedbackVaryings.push("outAngle"),this._parent.isAnimationSheetEnabled&&(this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex"),this._parent.spriteRandomStartCell&&this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset")),this._updateEffectOptions.defines=e,this._updateEffect=new Ei("gpuUpdateParticles",this._updateEffectOptions,this._engine),new zx(this._updateEffect)},e.prototype.createVertexBuffers=function(e,t){this._updateVAO.push(this._createUpdateVAO(e)),this._renderVAO.push(this._engine.recordVertexArrayObject(t,null,this._parent._getWrapper(this._parent.blendMode).effect)),this._engine.bindArrayBuffer(null),this._renderVertexBuffers=t},e.prototype.createParticleBuffer=function(e){return e},e.prototype.bindDrawBuffers=function(e,t,i){i?this._engine.bindBuffers(this._renderVertexBuffers,i,t):this._engine.bindVertexArrayObject(this._renderVAO[e],null)},e.prototype.preUpdateParticleBuffer=function(){var e=this._engine;if(this._engine.enableEffect(this._updateEffect),!e.setState)throw new Error("GPU particles cannot work without a full Engine. ThinEngine is not supported")},e.prototype.updateParticleBuffer=function(e,t,i){this._updateEffect.setTexture("randomSampler",this._parent._randomTexture),this._updateEffect.setTexture("randomSampler2",this._parent._randomTexture2),this._parent._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateEffect.setTexture("limitVelocityGradientSampler",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateEffect.setTexture("dragGradientSampler",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateEffect.setTexture("noiseSampler",this._parent.noiseTexture),this._engine.bindVertexArrayObject(this._updateVAO[e],null);var r=this._engine;r.bindTransformFeedbackBuffer(t.getBuffer()),r.setRasterizerState(!1),r.beginTransformFeedback(!0),r.drawArraysType(u.MATERIAL_PointListDrawMode,0,i),r.endTransformFeedback(),r.setRasterizerState(!0),r.bindTransformFeedbackBuffer(null)},e.prototype.releaseBuffers=function(){},e.prototype.releaseVertexBuffers=function(){for(var e=0;e<this._updateVAO.length;e++)this._engine.releaseVertexArrayObject(this._updateVAO[e]);for(this._updateVAO.length=0,e=0;e<this._renderVAO.length;e++)this._engine.releaseVertexArrayObject(this._renderVAO[e]);this._renderVAO.length=0},e.prototype._createUpdateVAO=function(e){var t={};t.position=e.createVertexBuffer("position",0,3);var i=3;t.age=e.createVertexBuffer("age",i,1),i+=1,t.size=e.createVertexBuffer("size",i,3),i+=3,t.life=e.createVertexBuffer("life",i,1),i+=1,t.seed=e.createVertexBuffer("seed",i,4),i+=4,t.direction=e.createVertexBuffer("direction",i,3),i+=3,this._parent.particleEmitterType instanceof kx&&(t.initialPosition=e.createVertexBuffer("initialPosition",i,3),i+=3),this._parent._colorGradientsTexture||(t.color=e.createVertexBuffer("color",i,4),i+=4),this._parent._isBillboardBased||(t.initialDirection=e.createVertexBuffer("initialDirection",i,3),i+=3),this._parent.noiseTexture&&(t.noiseCoordinates1=e.createVertexBuffer("noiseCoordinates1",i,3),i+=3,t.noiseCoordinates2=e.createVertexBuffer("noiseCoordinates2",i,3),i+=3),this._parent._angularSpeedGradientsTexture?(t.angle=e.createVertexBuffer("angle",i,1),i+=1):(t.angle=e.createVertexBuffer("angle",i,2),i+=2),this._parent._isAnimationSheetEnabled&&(t.cellIndex=e.createVertexBuffer("cellIndex",i,1),i+=1,this._parent.spriteRandomStartCell&&(t.cellStartOffset=e.createVertexBuffer("cellStartOffset",i,1),i+=1));var r=this._engine.recordVertexArrayObject(t,null,this._updateEffect);return this._engine.bindArrayBuffer(null),r},e}();a("BABYLON.WebGL2ParticleSystem",Wx);li.ShadersStoreWGSL.gpuUpdateParticlesComputeShader="struct Particle {position : vec3<f32>,\nage : f32,\nsize : vec3<f32>,\nlife : f32,\nseed : vec4<f32>,\ndirection : vec3<f32>,\ndummy0: f32,\n#ifdef CUSTOMEMITTER\ninitialPosition : vec3<f32>,\ndummy1: f32,\n#endif\n#ifndef COLORGRADIENTS\ncolor : vec4<f32>,\n#endif\n#ifndef BILLBOARD\ninitialDirection : vec3<f32>,\ndummy2: f32,\n#endif\n#ifdef NOISE\nnoiseCoordinates1 : vec3<f32>,\ndummy3: f32,\nnoiseCoordinates2 : vec3<f32>,\ndummy4: f32,\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nangle : f32,\n#else\nangle : vec2<f32>,\n#endif\n#ifdef ANIMATESHEET\ncellIndex : f32,\n#ifdef ANIMATESHEETRANDOMSTART\ncellStartOffset : f32,\n#endif\n#endif\n};struct Particles {particles : array<Particle>,};struct SimParams {currentCount : f32,\ntimeDelta : f32,\nstopFactor : f32,\nrandomTextureSize: i32,\nlifeTime : vec2<f32>,\nemitPower : vec2<f32>,\n#ifndef COLORGRADIENTS\ncolor1 : vec4<f32>,\ncolor2 : vec4<f32>,\n#endif\nsizeRange : vec2<f32>,\nscaleRange : vec4<f32>,\nangleRange : vec4<f32>,\ngravity : vec3<f32>,\n#ifdef LIMITVELOCITYGRADIENTS\nlimitVelocityDamping : f32,\n#endif\n#ifdef ANIMATESHEET\ncellInfos : vec4<f32>,\n#endif\n#ifdef NOISE\nnoiseStrength : vec3<f32>,\n#endif\n#ifndef LOCAL\nemitterWM : mat4x4<f32>,\n#endif\n#ifdef BOXEMITTER\ndirection1 : vec3<f32>,\ndirection2 : vec3<f32>,\nminEmitBox : vec3<f32>,\nmaxEmitBox : vec3<f32>,\n#endif\n#ifdef CONEEMITTER\nradius : vec2<f32>,\nconeAngle : f32,\nheight : vec2<f32>,\ndirectionRandomizer : f32,\n#endif\n#ifdef CYLINDEREMITTER\nradius : f32,\nheight : f32,\nradiusRange : f32,\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection1 : vec3<f32>,\ndirection2 : vec3<f32>,\n#else\ndirectionRandomizer : f32,\n#endif\n#endif\n#ifdef HEMISPHERICEMITTER\nradius : f32,\nradiusRange : f32,\ndirectionRandomizer : f32,\n#endif\n#ifdef POINTEMITTER\ndirection1 : vec3<f32>,\ndirection2 : vec3<f32>,\n#endif\n#ifdef SPHEREEMITTER\nradius : f32,\nradiusRange : f32,\n#ifdef DIRECTEDSPHEREEMITTER\ndirection1 : vec3<f32>,\ndirection2 : vec3<f32>,\n#else\ndirectionRandomizer : f32,\n#endif\n#endif\n};@binding(0) @group(0) var<uniform> params : SimParams;@binding(1) @group(0) var<storage,read> particlesIn : Particles;@binding(2) @group(0) var<storage,read_write> particlesOut : Particles;@binding(3) @group(0) var randomTexture : texture_2d<f32>;@binding(4) @group(0) var randomTexture2 : texture_2d<f32>;\n#ifdef SIZEGRADIENTS\n@binding(0) @group(1) var sizeGradientSampler : sampler;@binding(1) @group(1) var sizeGradientTexture : texture_2d<f32>;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\n@binding(2) @group(1) var angularSpeedGradientSampler : sampler;@binding(3) @group(1) var angularSpeedGradientTexture : texture_2d<f32>;\n#endif \n#ifdef VELOCITYGRADIENTS\n@binding(4) @group(1) var velocityGradientSampler : sampler;@binding(5) @group(1) var velocityGradientTexture : texture_2d<f32>;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\n@binding(6) @group(1) var limitVelocityGradientSampler : sampler;@binding(7) @group(1) var limitVelocityGradientTexture : texture_2d<f32>;\n#endif\n#ifdef DRAGGRADIENTS\n@binding(8) @group(1) var dragGradientSampler : sampler;@binding(9) @group(1) var dragGradientTexture : texture_2d<f32>;\n#endif\n#ifdef NOISE\n@binding(10) @group(1) var noiseSampler : sampler;@binding(11) @group(1) var noiseTexture : texture_2d<f32>;\n#endif\nfn getRandomVec3(offset : f32,vertexID : f32)->vec3<f32> {return textureLoad(randomTexture2,vec2<i32>(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0).rgb;}\nfn getRandomVec4(offset : f32,vertexID : f32)->vec4<f32> {return textureLoad(randomTexture,vec2<i32>(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0);}\n@compute @workgroup_size(64)\nfn main(@builtin(global_invocation_id) GlobalInvocationID : vec3<u32>) {let index : u32=GlobalInvocationID.x;let vertexID : f32=f32(index);if (index>=u32(params.currentCount)) {return;}\nlet PI : f32=3.14159;let timeDelta : f32=params.timeDelta;let newAge : f32=particlesIn.particles[index].age+timeDelta;let life : f32=particlesIn.particles[index].life;let seed : vec4<f32>=particlesIn.particles[index].seed;let direction : vec3<f32>=particlesIn.particles[index].direction;if (newAge>=life && params.stopFactor != 0.) {var newPosition : vec3<f32>;var newDirection : vec3<f32>;let randoms : vec4<f32>=getRandomVec4(seed.x,vertexID);let outLife : f32=params.lifeTime.x+(params.lifeTime.y-params.lifeTime.x)*randoms.r;particlesOut.particles[index].life=outLife;particlesOut.particles[index].age=newAge-life;particlesOut.particles[index].seed=seed;var sizex : f32;\n#ifdef SIZEGRADIENTS \nsizex=textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2<f32>(0.,0.),0.).r;\n#else\nsizex=params.sizeRange.x+(params.sizeRange.y-params.sizeRange.x)*randoms.g;\n#endif\nparticlesOut.particles[index].size=vec3<f32>(\nsizex,\nparams.scaleRange.x+(params.scaleRange.y-params.scaleRange.x)*randoms.b,\nparams.scaleRange.z+(params.scaleRange.w-params.scaleRange.z)*randoms.a);\n#ifndef COLORGRADIENTS\nparticlesOut.particles[index].color=params.color1+(params.color2-params.color1)*randoms.b;\n#endif\n#ifndef ANGULARSPEEDGRADIENTS \nparticlesOut.particles[index].angle=vec2<f32>(\nparams.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r,\nparams.angleRange.x+(params.angleRange.y-params.angleRange.x)*randoms.a);\n#else\nparticlesOut.particles[index].angle=params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r;\n#endif \n#if defined(POINTEMITTER)\nlet randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);newPosition=vec3<f32>(0.,0.,0.);newDirection=params.direction1+(params.direction2-params.direction1)*randoms3;\n#elif defined(BOXEMITTER)\nlet randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);newPosition=params.minEmitBox+(params.maxEmitBox-params.minEmitBox)*randoms2;newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nlet randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3<f32>(randX,abs(randY),randZ);newDirection=normalize(newPosition+params.directionRandomizer*randoms3);\n#elif defined(SPHEREEMITTER)\nlet randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3<f32>(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\nnewDirection=normalize(params.direction1+(params.direction2-params.direction1)*randoms3);\n#else\nnewDirection=normalize(newPosition+params.directionRandomizer*randoms3);\n#endif\n#elif defined(CYLINDEREMITTER)\nlet randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);let yPos : f32=(-0.5+randoms2.x)*params.height;var angle : f32=randoms2.y*PI*2.;let inverseRadiusRangeSquared : f32=(1.-params.radiusRange)*(1.-params.radiusRange);let positionRadius : f32=params.radius*sqrt(inverseRadiusRangeSquared+randoms2.z*(1.-inverseRadiusRangeSquared));let xPos : f32=positionRadius*cos(angle);let zPos : f32=positionRadius*sin(angle);newPosition=vec3<f32>(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\nnewDirection=params.direction1+(params.direction2-params.direction1)*randoms3;\n#else\nangle=angle+(-0.5+randoms3.x)*PI*params.directionRandomizer;newDirection=vec3<f32>(cos(angle),(-0.5+randoms3.y)*params.directionRandomizer,sin(angle));newDirection=normalize(newDirection);\n#endif\n#elif defined(CONEEMITTER)\nlet randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let s : f32=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nlet h : f32=0.0001;\n#else\nvar h : f32=randoms2.y*params.height.y;h=1.-h*h; \n#endif\nvar lRadius : f32=params.radius.x-params.radius.x*randoms2.z*params.radius.y;lRadius=lRadius*h;let randX : f32=lRadius*sin(s);let randZ : f32=lRadius*cos(s);let randY : f32=h *params.height.x;newPosition=vec3<f32>(randX,randY,randZ); \nif (abs(cos(params.coneAngle))==1.0) {newDirection=vec3<f32>(0.,1.0,0.);} else {let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); }\n#elif defined(CUSTOMEMITTER)\nnewPosition=particlesIn.particles[index].initialPosition;particlesOut.particles[index].initialPosition=newPosition;\n#else \nnewPosition=vec3<f32>(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w,vertexID)-vec3<f32>(0.5,0.5,0.5));\n#endif\nlet power : f32=params.emitPower.x+(params.emitPower.y-params.emitPower.x)*randoms.a;\n#ifdef LOCAL\nparticlesOut.particles[index].position=newPosition;\n#else\nparticlesOut.particles[index].position=(params.emitterWM*vec4<f32>(newPosition,1.)).xyz;\n#endif\n#ifdef CUSTOMEMITTER\nparticlesOut.particles[index].direction=direction;\n#ifndef BILLBOARD \nparticlesOut.particles[index].initialDirection=direction;\n#endif\n#else\n#ifdef LOCAL\nlet initial : vec3<f32>=newDirection;\n#else \nlet initial : vec3<f32>=(params.emitterWM*vec4<f32>(newDirection,0.)).xyz;\n#endif\nparticlesOut.particles[index].direction=initial*power;\n#ifndef BILLBOARD \nparticlesOut.particles[index].initialDirection=initial;\n#endif\n#endif\n#ifdef ANIMATESHEET \nparticlesOut.particles[index].cellIndex=params.cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\nparticlesOut.particles[index].cellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\nparticlesOut.particles[index].noiseCoordinates1=particlesIn.particles[index].noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=particlesIn.particles[index].noiseCoordinates2;\n#endif\n} else {var directionScale : f32=timeDelta;particlesOut.particles[index].age=newAge;let ageGradient : f32=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale=directionScale*textureSampleLevel(velocityGradientTexture,velocityGradientSampler,vec2<f32>(ageGradient,0.),0.).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale=directionScale*(1.0-textureSampleLevel(dragGradientTexture,dragGradientSampler,vec2<f32>(ageGradient,0.),0.).r);\n#endif\nlet position : vec3<f32>=particlesIn.particles[index].position;\n#if defined(CUSTOMEMITTER)\nparticlesOut.particles[index].position=position+(direction-position)*ageGradient; \nparticlesOut.particles[index].initialPosition=particlesIn.particles[index].initialPosition;\n#else\nparticlesOut.particles[index].position=position+direction*directionScale;\n#endif\nparticlesOut.particles[index].life=life;particlesOut.particles[index].seed=seed;\n#ifndef COLORGRADIENTS \nparticlesOut.particles[index].color=particlesIn.particles[index].color;\n#endif\n#ifdef SIZEGRADIENTS\nparticlesOut.particles[index].size=vec3<f32>(\ntextureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2<f32>(ageGradient,0.),0.).r,\nparticlesIn.particles[index].size.yz);\n#else\nparticlesOut.particles[index].size=particlesIn.particles[index].size;\n#endif \n#ifndef BILLBOARD \nparticlesOut.particles[index].initialDirection=particlesIn.particles[index].initialDirection;\n#endif\n#ifdef CUSTOMEMITTER\nparticlesOut.particles[index].direction=direction;\n#else\nvar updatedDirection : vec3<f32>=direction+params.gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nlet limitVelocity : f32=textureSampleLevel(limitVelocityGradientTexture,limitVelocityGradientSampler,vec2<f32>(ageGradient,0.),0.).r;let currentVelocity : f32=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*params.limitVelocityDamping;}\n#endif\nparticlesOut.particles[index].direction=updatedDirection;\n#ifdef NOISE\nlet noiseCoordinates1 : vec3<f32>=particlesIn.particles[index].noiseCoordinates1;let noiseCoordinates2 : vec3<f32>=particlesIn.particles[index].noiseCoordinates2;let fetchedR : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates1.x,noiseCoordinates1.y)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;let fetchedG : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates1.z,noiseCoordinates2.x)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;let fetchedB : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates2.y,noiseCoordinates2.z)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;let force : vec3<f32>=vec3<f32>(-1.+2.*fetchedR,-1.+2.*fetchedG,-1.+2.*fetchedB)*params.noiseStrength;particlesOut.particles[index].direction=particlesOut.particles[index].direction+force*timeDelta;particlesOut.particles[index].noiseCoordinates1=noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=noiseCoordinates2;\n#endif \n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nlet angularSpeed : f32=textureSampleLevel(angularSpeedGradientTexture,angularSpeedGradientSampler,vec2<f32>(ageGradient,0.),0.).r;particlesOut.particles[index].angle=particlesIn.particles[index].angle+angularSpeed*timeDelta;\n#else\nlet angle : vec2<f32>=particlesIn.particles[index].angle;particlesOut.particles[index].angle=vec2<f32>(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nvar offsetAge : f32=particlesOut.particles[index].age;let dist : f32=params.cellInfos.y-params.cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\nlet cellStartOffset : f32=particlesIn.particles[index].cellStartOffset;particlesOut.particles[index].cellStartOffset=cellStartOffset;offsetAge=offsetAge+cellStartOffset;\n#else\nlet cellStartOffset : f32=0.;\n#endif \nvar ratio : f32;if (params.cellInfos.w==1.0) {ratio=clamp(((cellStartOffset+params.cellInfos.z*offsetAge) % life)/life,0.,1.0);}\nelse {ratio=clamp((cellStartOffset+params.cellInfos.z*offsetAge)/life,0.,1.0);}\nparticlesOut.particles[index].cellIndex=f32(i32(params.cellInfos.x+ratio*dist));\n#endif\n}}\n";var Hx=function(){function e(e,t){this._bufferComputeShader=[],this._renderVertexBuffers=[],this.alignDataInBuffer=!0,this._parent=e,this._engine=t}return e.prototype.contextLost=function(){this._updateComputeShader=void 0,this._bufferComputeShader.length=0,this._renderVertexBuffers.length=0},e.prototype.isUpdateBufferCreated=function(){return!!this._updateComputeShader},e.prototype.isUpdateBufferReady=function(){var e,t;return null!==(t=null===(e=this._updateComputeShader)||void 0===e?void 0:e.isReady())&&void 0!==t&&t},e.prototype.createUpdateBuffer=function(e){var t,i={params:{group:0,binding:0},particlesIn:{group:0,binding:1},particlesOut:{group:0,binding:2},randomTexture:{group:0,binding:3},randomTexture2:{group:0,binding:4}};return this._parent._sizeGradientsTexture&&(i.sizeGradientTexture={group:1,binding:1}),this._parent._angularSpeedGradientsTexture&&(i.angularSpeedGradientTexture={group:1,binding:3}),this._parent._velocityGradientsTexture&&(i.velocityGradientTexture={group:1,binding:5}),this._parent._limitVelocityGradientsTexture&&(i.limitVelocityGradientTexture={group:1,binding:7}),this._parent._dragGradientsTexture&&(i.dragGradientTexture={group:1,binding:9}),this._parent.noiseTexture&&(i.noiseTexture={group:1,binding:11}),this._updateComputeShader=new yh("updateParticles",this._engine,"gpuUpdateParticles",{bindingsMapping:i,defines:e.split("\n")}),null===(t=this._simParamsComputeShader)||void 0===t||t.dispose(),this._simParamsComputeShader=new Or(this._engine,void 0,void 0,"ComputeShaderParticleSystemUBO"),this._simParamsComputeShader.addUniform("currentCount",1),this._simParamsComputeShader.addUniform("timeDelta",1),this._simParamsComputeShader.addUniform("stopFactor",1),this._simParamsComputeShader.addUniform("randomTextureSize",1),this._simParamsComputeShader.addUniform("lifeTime",2),this._simParamsComputeShader.addUniform("emitPower",2),this._parent._colorGradientsTexture||(this._simParamsComputeShader.addUniform("color1",4),this._simParamsComputeShader.addUniform("color2",4)),this._simParamsComputeShader.addUniform("sizeRange",2),this._simParamsComputeShader.addUniform("scaleRange",4),this._simParamsComputeShader.addUniform("angleRange",4),this._simParamsComputeShader.addUniform("gravity",3),this._parent._limitVelocityGradientsTexture&&this._simParamsComputeShader.addUniform("limitVelocityDamping",1),this._parent.isAnimationSheetEnabled&&this._simParamsComputeShader.addUniform("cellInfos",4),this._parent.noiseTexture&&this._simParamsComputeShader.addUniform("noiseStrength",3),this._parent.isLocal||this._simParamsComputeShader.addUniform("emitterWM",16),this._parent.particleEmitterType&&this._parent.particleEmitterType.buildUniformLayout(this._simParamsComputeShader),this._updateComputeShader.setUniformBuffer("params",this._simParamsComputeShader),new zx(this._simParamsComputeShader)},e.prototype.createVertexBuffers=function(e,t){this._renderVertexBuffers.push(t)},e.prototype.createParticleBuffer=function(e){var t=new $l(this._engine,4*e.length,u.BUFFER_CREATIONFLAG_READWRITE|u.BUFFER_CREATIONFLAG_VERTEX,"ComputeShaderParticleSystemBuffer");return t.update(e),this._bufferComputeShader.push(t),t.getBuffer()},e.prototype.bindDrawBuffers=function(e,t,i){this._engine.bindBuffers(this._renderVertexBuffers[e],i,t)},e.prototype.preUpdateParticleBuffer=function(){},e.prototype.updateParticleBuffer=function(e,t,i){this._simParamsComputeShader.update(),this._updateComputeShader.setTexture("randomTexture",this._parent._randomTexture,!1),this._updateComputeShader.setTexture("randomTexture2",this._parent._randomTexture2,!1),this._parent._sizeGradientsTexture&&this._updateComputeShader.setTexture("sizeGradientTexture",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateComputeShader.setTexture("angularSpeedGradientTexture",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateComputeShader.setTexture("velocityGradientTexture",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateComputeShader.setTexture("limitVelocityGradientTexture",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateComputeShader.setTexture("dragGradientTexture",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateComputeShader.setTexture("noiseTexture",this._parent.noiseTexture),this._updateComputeShader.setStorageBuffer("particlesIn",this._bufferComputeShader[e]),this._updateComputeShader.setStorageBuffer("particlesOut",this._bufferComputeShader[1^e]),this._updateComputeShader.dispatch(Math.ceil(i/64))},e.prototype.releaseBuffers=function(){for(var e,t=0;t<this._bufferComputeShader.length;++t)this._bufferComputeShader[t].dispose();this._bufferComputeShader.length=0,null===(e=this._simParamsComputeShader)||void 0===e||e.dispose(),this._simParamsComputeShader=null,this._updateComputeShader=null},e.prototype.releaseVertexBuffers=function(){this._renderVertexBuffers.length=0},e}();a("BABYLON.ComputeShaderParticleSystem",Hx);var Xx=function(){function e(e,t,i){this.gradient=e,this.color1=t,this.color2=i}return e.prototype.getColorToRef=function(e){this.color2?J.LerpToRef(this.color1,this.color2,Math.random(),e):e.copyFrom(this.color1)},e}(),jx=function(e,t){this.gradient=e,this.color=t},Yx=function(){function e(e,t,i){this.gradient=e,this.factor1=t,this.factor2=i}return e.prototype.getFactor=function(){return void 0===this.factor2||this.factor2===this.factor1?this.factor1:this.factor1+(this.factor2-this.factor1)*Math.random()},e}(),Kx=function(){function e(){}return e.GetCurrentGradient=function(e,t,i){if(t[0].gradient>e)i(t[0],t[0],1);else{for(var r=0;r<t.length-1;r++){var n=t[r],o=t[r+1];if(e>=n.gradient&&e<=o.gradient)return void i(n,o,(e-n.gradient)/(o.gradient-n.gradient))}var a=t.length-1;i(t[a],t[a],1)}},e}(),Qx=function(){function e(t){this.particleSystem=t,this.position=V.Zero(),this.direction=V.Zero(),this.color=new J(0,0,0,0),this.colorStep=new J(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new U(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new J(0,0,0,0),this._currentColor2=new J(0,0,0,0),this._currentSize1=0,this._currentSize2=0,this._currentAngularSpeed1=0,this._currentAngularSpeed2=0,this._currentVelocity1=0,this._currentVelocity2=0,this._currentLimitVelocity1=0,this._currentLimitVelocity2=0,this._currentDrag1=0,this._currentDrag2=0,this.id=e._Count++,this.particleSystem.isAnimationSheetEnabled&&this._updateCellInfoFromSystem()}return e.prototype._updateCellInfoFromSystem=function(){this.cellIndex=this.particleSystem.startSpriteCellID},e.prototype.updateCellIndex=function(){var e=this.age,t=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(void 0===this._randomCellOffset&&(this._randomCellOffset=Math.random()*this.lifeTime),0===t?(t=1,e=this._randomCellOffset):e+=this._randomCellOffset);var i,r=this._initialEndSpriteCellID-this._initialStartSpriteCellID+1;i=this._initialSpriteCellLoop?F(e*t%this.lifeTime/this.lifeTime):F(e*t/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+i*r|0},e.prototype._inheritParticleInfoToSubEmitter=function(e){if(e.particleSystem.emitter.position){var t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){var i=H.Vector3[0];this.direction.normalizeToRef(i),t.setDirection(i,0,Math.PI/2)}}else e.particleSystem.emitter.copyFrom(this.position);this.direction.scaleToRef(e.inheritedVelocityAmount/2,H.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(H.Vector3[0])},e.prototype._inheritParticleInfoToSubEmitters=function(){var e=this;this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach((function(t){e._inheritParticleInfoToSubEmitter(t)}))},e.prototype._reset=function(){this.age=0,this.id=e._Count++,this._currentColorGradient=null,this._currentSizeGradient=null,this._currentAngularSpeedGradient=null,this._currentVelocityGradient=null,this._currentLimitVelocityGradient=null,this._currentDragGradient=null,this.cellIndex=this.particleSystem.startSpriteCellID,this._randomCellOffset=void 0},e.prototype.copyTo=function(e){e.position.copyFrom(this.position),this._initialDirection?e._initialDirection?e._initialDirection.copyFrom(this._initialDirection):e._initialDirection=this._initialDirection.clone():e._initialDirection=null,e.direction.copyFrom(this.direction),this._localPosition&&(e._localPosition?e._localPosition.copyFrom(this._localPosition):e._localPosition=this._localPosition.clone()),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e._randomCellOffset=this._randomCellOffset,e.size=this.size,e.scale.copyFrom(this.scale),e.angle=this.angle,e.angularSpeed=this.angularSpeed,e.particleSystem=this.particleSystem,e.cellIndex=this.cellIndex,e.id=this.id,e._attachedSubEmitters=this._attachedSubEmitters,this._currentColorGradient&&(e._currentColorGradient=this._currentColorGradient,e._currentColor1.copyFrom(this._currentColor1),e._currentColor2.copyFrom(this._currentColor2)),this._currentSizeGradient&&(e._currentSizeGradient=this._currentSizeGradient,e._currentSize1=this._currentSize1,e._currentSize2=this._currentSize2),this._currentAngularSpeedGradient&&(e._currentAngularSpeedGradient=this._currentAngularSpeedGradient,e._currentAngularSpeed1=this._currentAngularSpeed1,e._currentAngularSpeed2=this._currentAngularSpeed2),this._currentVelocityGradient&&(e._currentVelocityGradient=this._currentVelocityGradient,e._currentVelocity1=this._currentVelocity1,e._currentVelocity2=this._currentVelocity2),this._currentLimitVelocityGradient&&(e._currentLimitVelocityGradient=this._currentLimitVelocityGradient,e._currentLimitVelocity1=this._currentLimitVelocity1,e._currentLimitVelocity2=this._currentLimitVelocity2),this._currentDragGradient&&(e._currentDragGradient=this._currentDragGradient,e._currentDrag1=this._currentDrag1,e._currentDrag2=this._currentDrag2),this.particleSystem.isAnimationSheetEnabled&&(e._initialStartSpriteCellID=this._initialStartSpriteCellID,e._initialEndSpriteCellID=this._initialEndSpriteCellID,e._initialSpriteCellLoop=this._initialSpriteCellLoop),this.particleSystem.useRampGradients&&(e.remapData&&this.remapData?e.remapData.copyFrom(this.remapData):e.remapData=new k(0,0,0,0)),this._randomNoiseCoordinates1&&(e._randomNoiseCoordinates1?(e._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),e._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)):(e._randomNoiseCoordinates1=this._randomNoiseCoordinates1.clone(),e._randomNoiseCoordinates2=this._randomNoiseCoordinates2.clone()))},e._Count=0,e}();li.ShadersStore.particlesPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nvarying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<logDepthDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;uniform sampler2D rampSampler;\n#endif\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));baseColor.rgb*=rampColor.rgb;float finalAlpha=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n#include<logDepthFragment>\n#include<fogFragment>(color,baseColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";li.ShadersStore.particlesVertexShader="attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD\nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;\n#ifdef ANIMATESHEET\nuniform vec3 particlesInfos; \n#endif\nvarying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<logDepthDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\n#ifdef BILLBOARDSTRETCHED_LOCAL\nvec3 row1=direction;\n#else\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\n#endif\nmat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;}\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size;\n#ifdef BILLBOARD\nvec3 rotatedCorner;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=position-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=position-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;vPositionW=(invView*vec4(viewPos,1)).xyz;\n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\ngl_Position=projection*vec4(viewPos,1.0);\n#else\nvec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(direction);vPositionW=rotate(yaxis,rotatedCorner);gl_Position=projection*view*vec4(vPositionW,1.0);\n#endif\nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex*particlesInfos.z);float columnOffset=cellIndex-rowOffset/particlesInfos.z;vec2 uvScale=particlesInfos.xy;vec2 uvOffset=vec2(offset.x ,1.0-offset.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}";var qx,Zx=function(e){function t(t,i,r,n,o,a){void 0===n&&(n=null),void 0===o&&(o=!1),void 0===a&&(a=.01);var s=e.call(this,t)||this;s._emitterInverseWorldMatrix=z.Identity(),s._inheritedVelocityOffset=new V,s.onDisposeObservable=new f,s.onStoppedObservable=new f,s._particles=new Array,s._stockParticles=new Array,s._newPartsExcess=0,s._vertexBuffers={},s._scaledColorStep=new J(0,0,0,0),s._colorDiff=new J(0,0,0,0),s._scaledDirection=V.Zero(),s._scaledGravity=V.Zero(),s._currentRenderId=-1,s._useInstancing=!1,s._started=!1,s._stopped=!1,s._actualFrame=0,s._currentEmitRate1=0,s._currentEmitRate2=0,s._currentStartSize1=0,s._currentStartSize2=0,s.updateInAnimate=!0,s._rawTextureWidth=256,s._useRampGradients=!1,s.isLocal=!1,s.isGPU=!1,s._onBeforeDrawParticlesObservable=null,s._emitFromParticle=function(e){},s.recycleParticle=function(e){var t=s._particles.pop();t!==e&&t.copyTo(e),s._stockParticles.push(t)},s._createParticle=function(){var e;return 0!==s._stockParticles.length?(e=s._stockParticles.pop())._reset():e=new Qx(s),s._prepareParticle(e),e},s._capacity=i,s._epsilon=a,s._isAnimationSheetEnabled=o,r&&"Scene"!==r.getClassName()?(s._engine=r,s.defaultProjectionMatrix=z.PerspectiveFovLH(.8,1,.1,100,s._engine.isNDCHalfZRange)):(s._scene=r||M.LastCreatedScene,s._engine=s._scene.getEngine(),s.uniqueId=s._scene.getUniqueId(),s._scene.particleSystems.push(s)),s._engine.getCaps().vertexArrayObject&&(s._vertexArrayObject=null),s._attachImageProcessingConfiguration(null),s._customWrappers={0:new ho(s._engine)},s._customWrappers[0].effect=n,s._drawWrappers=[],s._useInstancing=s._engine.getCaps().instancedArrays,s._createIndexBuffer(),s._createVertexBuffers(),s.particleEmitterType=new Dx;var l=null;return s.updateFunction=function(e){var t,i=null;s.noiseTexture&&(i=s.noiseTexture.getSize(),null===(t=s.noiseTexture.getContent())||void 0===t||t.then((function(e){l=e})));for(var r,n=e===s._particles,o=function(t){var o=e[t],a=s._scaledUpdateSpeed,c=o.age;if(o.age+=a,o.age>o.lifeTime){var u=o.age-c;a=(o.lifeTime-c)*a/u,o.age=o.lifeTime}var h=o.age/o.lifeTime;s._colorGradients&&s._colorGradients.length>0?Kx.GetCurrentGradient(h,s._colorGradients,(function(e,t,i){e!==o._currentColorGradient&&(o._currentColor1.copyFrom(o._currentColor2),t.getColorToRef(o._currentColor2),o._currentColorGradient=e),J.LerpToRef(o._currentColor1,o._currentColor2,i,o.color)})):(o.colorStep.scaleToRef(a,s._scaledColorStep),o.color.addInPlace(s._scaledColorStep),o.color.a<0&&(o.color.a=0)),s._angularSpeedGradients&&s._angularSpeedGradients.length>0&&Kx.GetCurrentGradient(h,s._angularSpeedGradients,(function(e,t,i){e!==o._currentAngularSpeedGradient&&(o._currentAngularSpeed1=o._currentAngularSpeed2,o._currentAngularSpeed2=t.getFactor(),o._currentAngularSpeedGradient=e),o.angularSpeed=N(o._currentAngularSpeed1,o._currentAngularSpeed2,i)})),o.angle+=o.angularSpeed*a;var d=a;if(s._velocityGradients&&s._velocityGradients.length>0&&Kx.GetCurrentGradient(h,s._velocityGradients,(function(e,t,i){e!==o._currentVelocityGradient&&(o._currentVelocity1=o._currentVelocity2,o._currentVelocity2=t.getFactor(),o._currentVelocityGradient=e),d*=N(o._currentVelocity1,o._currentVelocity2,i)})),o.direction.scaleToRef(d,s._scaledDirection),s._limitVelocityGradients&&s._limitVelocityGradients.length>0&&Kx.GetCurrentGradient(h,s._limitVelocityGradients,(function(e,t,i){e!==o._currentLimitVelocityGradient&&(o._currentLimitVelocity1=o._currentLimitVelocity2,o._currentLimitVelocity2=t.getFactor(),o._currentLimitVelocityGradient=e);var r=N(o._currentLimitVelocity1,o._currentLimitVelocity2,i);o.direction.length()>r&&o.direction.scaleInPlace(s.limitVelocityDamping)})),s._dragGradients&&s._dragGradients.length>0&&Kx.GetCurrentGradient(h,s._dragGradients,(function(e,t,i){e!==o._currentDragGradient&&(o._currentDrag1=o._currentDrag2,o._currentDrag2=t.getFactor(),o._currentDragGradient=e);var r=N(o._currentDrag1,o._currentDrag2,i);s._scaledDirection.scaleInPlace(1-r)})),s.isLocal&&o._localPosition?(o._localPosition.addInPlace(s._scaledDirection),V.TransformCoordinatesToRef(o._localPosition,s._emitterWorldMatrix,o.position)):o.position.addInPlace(s._scaledDirection),l&&i&&o._randomNoiseCoordinates1){var p=s._fetchR(o._randomNoiseCoordinates1.x,o._randomNoiseCoordinates1.y,i.width,i.height,l),f=s._fetchR(o._randomNoiseCoordinates1.z,o._randomNoiseCoordinates2.x,i.width,i.height,l),_=s._fetchR(o._randomNoiseCoordinates2.y,o._randomNoiseCoordinates2.z,i.width,i.height,l),m=H.Vector3[0],g=H.Vector3[1];m.copyFromFloats((2*p-1)*s.noiseStrength.x,(2*f-1)*s.noiseStrength.y,(2*_-1)*s.noiseStrength.z),m.scaleToRef(a,g),o.direction.addInPlace(g)}if(s.gravity.scaleToRef(a,s._scaledGravity),o.direction.addInPlace(s._scaledGravity),s._sizeGradients&&s._sizeGradients.length>0&&Kx.GetCurrentGradient(h,s._sizeGradients,(function(e,t,i){e!==o._currentSizeGradient&&(o._currentSize1=o._currentSize2,o._currentSize2=t.getFactor(),o._currentSizeGradient=e),o.size=N(o._currentSize1,o._currentSize2,i)})),s._useRampGradients&&(s._colorRemapGradients&&s._colorRemapGradients.length>0&&Kx.GetCurrentGradient(h,s._colorRemapGradients,(function(e,t,i){var r=N(e.factor1,t.factor1,i),n=N(e.factor2,t.factor2,i);o.remapData.x=r,o.remapData.y=n-r})),s._alphaRemapGradients&&s._alphaRemapGradients.length>0&&Kx.GetCurrentGradient(h,s._alphaRemapGradients,(function(e,t,i){var r=N(e.factor1,t.factor1,i),n=N(e.factor2,t.factor2,i);o.remapData.z=r,o.remapData.w=n-r}))),s._isAnimationSheetEnabled&&o.updateCellIndex(),o._inheritParticleInfoToSubEmitters(),o.age>=o.lifeTime)return s._emitFromParticle(o),o._attachedSubEmitters&&(o._attachedSubEmitters.forEach((function(e){e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()})),o._attachedSubEmitters=null),s.recycleParticle(o),n&&t--,r=t,"continue";r=t},a=0;a<e.length;a++)o(a),a=r},s}return m(t,e),Object.defineProperty(t.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"useRampGradients",{get:function(){return this._useRampGradients},set:function(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"particles",{get:function(){return this._particles},enumerable:!1,configurable:!0}),t.prototype.getActiveCount=function(){return this._particles.length},t.prototype.getClassName=function(){return"ParticleSystem"},t.prototype.isStopping=function(){return this._stopped&&this.isAlive()},t.prototype.getCustomEffect=function(e){var t,i;return void 0===e&&(e=0),null!==(i=null===(t=this._customWrappers[e])||void 0===t?void 0:t.effect)&&void 0!==i?i:this._customWrappers[0].effect},t.prototype._getCustomDrawWrapper=function(e){var t;return void 0===e&&(e=0),null!==(t=this._customWrappers[e])&&void 0!==t?t:this._customWrappers[0]},t.prototype.setCustomEffect=function(e,t){void 0===t&&(t=0),this._customWrappers[t]=new ho(this._engine),this._customWrappers[t].effect=e,this._customWrappers[t].drawContext&&(this._customWrappers[t].drawContext.useInstancing=this._useInstancing)},Object.defineProperty(t.prototype,"onBeforeDrawParticlesObservable",{get:function(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new f),this._onBeforeDrawParticlesObservable},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vertexShaderName",{get:function(){return"particles"},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vertexBuffers",{get:function(){return this._vertexBuffers},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"indexBuffer",{get:function(){return this._indexBuffer},enumerable:!1,configurable:!0}),t.prototype.serialize=function(e){throw new Error("Method not implemented.")},t.prototype.clone=function(e,t,i){throw void 0===i&&(i=!1),new Error("Method not implemented.")},t.prototype._addFactorGradient=function(e,t,i,r){var n=new Yx(t,i,r);e.push(n),e.sort((function(e,t){return e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0}))},t.prototype._removeFactorGradient=function(e,t){if(e)for(var i=0,r=0,n=e;r<n.length;r++){if(n[r].gradient===t){e.splice(i,1);break}i++}},t.prototype.addLifeTimeGradient=function(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this},t.prototype.removeLifeTimeGradient=function(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this},t.prototype.addSizeGradient=function(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this},t.prototype.removeSizeGradient=function(e){return this._removeFactorGradient(this._sizeGradients,e),this},t.prototype.addColorRemapGradient=function(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this},t.prototype.removeColorRemapGradient=function(e){return this._removeFactorGradient(this._colorRemapGradients,e),this},t.prototype.addAlphaRemapGradient=function(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this},t.prototype.removeAlphaRemapGradient=function(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this},t.prototype.addAngularSpeedGradient=function(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this},t.prototype.removeAngularSpeedGradient=function(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this},t.prototype.addVelocityGradient=function(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this},t.prototype.removeVelocityGradient=function(e){return this._removeFactorGradient(this._velocityGradients,e),this},t.prototype.addLimitVelocityGradient=function(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this},t.prototype.removeLimitVelocityGradient=function(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this},t.prototype.addDragGradient=function(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this},t.prototype.removeDragGradient=function(e){return this._removeFactorGradient(this._dragGradients,e),this},t.prototype.addEmitRateGradient=function(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this},t.prototype.removeEmitRateGradient=function(e){return this._removeFactorGradient(this._emitRateGradients,e),this},t.prototype.addStartSizeGradient=function(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this},t.prototype.removeStartSizeGradient=function(e){return this._removeFactorGradient(this._startSizeGradients,e),this},t.prototype._createRampGradientTexture=function(){if(this._rampGradients&&this._rampGradients.length&&!this._rampGradientsTexture&&this._scene){for(var e=new Uint8Array(4*this._rawTextureWidth),t=$.Color3[0],i=function(i){var n=i/r._rawTextureWidth;Kx.GetCurrentGradient(n,r._rampGradients,(function(r,n,o){Z.LerpToRef(r.color,n.color,o,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255}))},r=this,n=0;n<this._rawTextureWidth;n++)i(n);this._rampGradientsTexture=is.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,u.TEXTURE_NEAREST_SAMPLINGMODE)}},t.prototype.getRampGradients=function(){return this._rampGradients},t.prototype.forceRefreshGradients=function(){this._syncRampGradientTexture()},t.prototype._syncRampGradientTexture=function(){this._rampGradients&&(this._rampGradients.sort((function(e,t){return e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0})),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())},t.prototype.addRampGradient=function(e,t){this._rampGradients||(this._rampGradients=[]);var i=new jx(e,t);return this._rampGradients.push(i),this._syncRampGradientTexture(),this},t.prototype.removeRampGradient=function(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this},t.prototype.addColorGradient=function(e,t,i){this._colorGradients||(this._colorGradients=[]);var r=new Xx(e,t,i);return this._colorGradients.push(r),this._colorGradients.sort((function(e,t){return e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0})),this},t.prototype.removeColorGradient=function(e){if(!this._colorGradients)return this;for(var t=0,i=0,r=this._colorGradients;i<r.length;i++){if(r[i].gradient===e){this._colorGradients.splice(t,1);break}t++}return this},t.prototype.resetDrawCache=function(){for(var e=0,t=this._drawWrappers;e<t.length;e++){var i=t[e];if(i)for(var r=0,n=i;r<n.length;r++){var o=n[r];null==o||o.dispose()}}this._drawWrappers=[]},t.prototype._fetchR=function(e,t,i,r,n){return n[4*(((e=.5*Math.abs(e)+.5)*i%i|0)+((t=.5*Math.abs(t)+.5)*r%r|0)*i)]/255},t.prototype._reset=function(){this._resetEffect()},t.prototype._resetEffect=function(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this._createVertexBuffers()},t.prototype._createVertexBuffers=function(){this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),this._isBillboardBased&&this.billboardMode!==u.PARTICLES_BILLBOARDMODE_STRETCHED&&this.billboardMode!==u.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL||(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);var e=this._engine,t=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*t),this._vertexBuffer=new Dr(e,this._vertexData,!0,t);var i=0,r=this._vertexBuffer.createVertexBuffer(Nr.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[Nr.PositionKind]=r,i+=3;var n=this._vertexBuffer.createVertexBuffer(Nr.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[Nr.ColorKind]=n,i+=4;var o=this._vertexBuffer.createVertexBuffer("angle",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=o,i+=1;var a,s=this._vertexBuffer.createVertexBuffer("size",i,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=s,i+=2,this._isAnimationSheetEnabled){var l=this._vertexBuffer.createVertexBuffer("cellIndex",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=l,i+=1}if(!this._isBillboardBased||this.billboardMode===u.PARTICLES_BILLBOARDMODE_STRETCHED||this.billboardMode===u.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL){var c=this._vertexBuffer.createVertexBuffer("direction",i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=c,i+=3}if(this._useRampGradients){var h=this._vertexBuffer.createVertexBuffer("remapData",i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=h,i+=4}if(this._useInstancing){var d=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Dr(e,d,!1,2),a=this._spriteBuffer.createVertexBuffer("offset",0,2)}else a=this._vertexBuffer.createVertexBuffer("offset",i,2,this._vertexBufferSize,this._useInstancing),i+=2;this._vertexBuffers.offset=a,this.resetDrawCache()},t.prototype._createIndexBuffer=function(){if(this._useInstancing)this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]));else{for(var e=[],t=[],i=0,r=0;r<this._capacity;r++)e.push(i),e.push(i+1),e.push(i+2),e.push(i),e.push(i+2),e.push(i+3),t.push(i,i+1,i+1,i+2,i+2,i+3,i+3,i,i,i+3),i+=4;this._indexBuffer=this._engine.createIndexBuffer(e),this._linesIndexBuffer=this._engine.createIndexBuffer(t)}},t.prototype.getCapacity=function(){return this._capacity},t.prototype.isAlive=function(){return this._alive},t.prototype.isStarted=function(){return this._started},t.prototype._preStart=function(){},t.prototype.start=function(e){var t,i=this;if(void 0===e&&(e=this.startDelay),!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e)setTimeout((function(){i.start(0)}),e);else{if(this._started=!0,this._stopped=!1,this._actualFrame=0,this._preStart(),this._emitRateGradients&&(this._emitRateGradients.length>0&&(this._currentEmitRateGradient=this._emitRateGradients[0],this._currentEmitRate1=this._currentEmitRateGradient.getFactor(),this._currentEmitRate2=this._currentEmitRate1),this._emitRateGradients.length>1&&(this._currentEmitRate2=this._emitRateGradients[1].getFactor())),this._startSizeGradients&&(this._startSizeGradients.length>0&&(this._currentStartSizeGradient=this._startSizeGradients[0],this._currentStartSize1=this._currentStartSizeGradient.getFactor(),this._currentStartSize2=this._currentStartSize1),this._startSizeGradients.length>1&&(this._currentStartSize2=this._startSizeGradients[1].getFactor())),this.preWarmCycles){-1!==(null===(t=this.emitter)||void 0===t?void 0:t.getClassName().indexOf("Mesh"))&&this.emitter.computeWorldMatrix(!0);var r=this.noiseTexture;if(r&&r.onGeneratedObservable)r.onGeneratedObservable.addOnce((function(){setTimeout((function(){for(var e=0;e<i.preWarmCycles;e++)i.animate(!0),r.render()}))}));else for(var n=0;n<this.preWarmCycles;n++)this.animate(!0)}this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}},t.prototype.stop=function(e){void 0===e&&(e=!0),this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,this._postStop(e))},t.prototype._postStop=function(e){},t.prototype.reset=function(){this._stockParticles.length=0,this._particles.length=0},t.prototype._appendParticleVertex=function(e,t,i,r){var n=e*this._vertexBufferSize;if(this._vertexData[n++]=t.position.x+this.worldOffset.x,this._vertexData[n++]=t.position.y+this.worldOffset.y,this._vertexData[n++]=t.position.z+this.worldOffset.z,this._vertexData[n++]=t.color.r,this._vertexData[n++]=t.color.g,this._vertexData[n++]=t.color.b,this._vertexData[n++]=t.color.a,this._vertexData[n++]=t.angle,this._vertexData[n++]=t.scale.x*t.size,this._vertexData[n++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[n++]=t.cellIndex),this._isBillboardBased)this.billboardMode!==u.PARTICLES_BILLBOARDMODE_STRETCHED&&this.billboardMode!==u.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL||(this._vertexData[n++]=t.direction.x,this._vertexData[n++]=t.direction.y,this._vertexData[n++]=t.direction.z);else if(t._initialDirection){var o=t._initialDirection;this.isLocal&&(V.TransformNormalToRef(o,this._emitterWorldMatrix,H.Vector3[0]),o=H.Vector3[0]),0===o.x&&0===o.z&&(o.x=.001),this._vertexData[n++]=o.x,this._vertexData[n++]=o.y,this._vertexData[n++]=o.z}else{var a=t.direction;this.isLocal&&(V.TransformNormalToRef(a,this._emitterWorldMatrix,H.Vector3[0]),a=H.Vector3[0]),0===a.x&&0===a.z&&(a.x=.001),this._vertexData[n++]=a.x,this._vertexData[n++]=a.y,this._vertexData[n++]=a.z}this._useRampGradients&&t.remapData&&(this._vertexData[n++]=t.remapData.x,this._vertexData[n++]=t.remapData.y,this._vertexData[n++]=t.remapData.z,this._vertexData[n++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===r?r=this._epsilon:1===r&&(r=1-this._epsilon)),this._vertexData[n++]=i,this._vertexData[n++]=r)},t.prototype._prepareParticle=function(e){},t.prototype._update=function(e){var t,i=this;if(this._alive=this._particles.length>0,this.emitter.position){var r=this.emitter;this._emitterWorldMatrix=r.getWorldMatrix()}else{var n=this.emitter;this._emitterWorldMatrix=z.Translation(n.x,n.y,n.z)}this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);for(var o=function(e){if(a._particles.length===a._capacity)return"break";if(t=a._createParticle(),a._particles.push(t),a.targetStopDuration&&a._lifeTimeGradients&&a._lifeTimeGradients.length>0){var r=F(a._actualFrame/a.targetStopDuration);Kx.GetCurrentGradient(r,a._lifeTimeGradients,(function(e,i){var n=e,o=i,a=n.getFactor(),s=o.getFactor(),l=(r-n.gradient)/(o.gradient-n.gradient);t.lifeTime=N(a,s,l)}))}else t.lifeTime=D(a.minLifeTime,a.maxLifeTime);var n=D(a.minEmitPower,a.maxEmitPower);if(a.startPositionFunction?a.startPositionFunction(a._emitterWorldMatrix,t.position,t,a.isLocal):a.particleEmitterType.startPositionFunction(a._emitterWorldMatrix,t.position,t,a.isLocal),a.isLocal&&(t._localPosition?t._localPosition.copyFrom(t.position):t._localPosition=t.position.clone(),V.TransformCoordinatesToRef(t._localPosition,a._emitterWorldMatrix,t.position)),a.startDirectionFunction?a.startDirectionFunction(a._emitterWorldMatrix,t.direction,t,a.isLocal):a.particleEmitterType.startDirectionFunction(a._emitterWorldMatrix,t.direction,t,a.isLocal,a._emitterInverseWorldMatrix),0===n?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(n),a._sizeGradients&&0!==a._sizeGradients.length?(t._currentSizeGradient=a._sizeGradients[0],t._currentSize1=t._currentSizeGradient.getFactor(),t.size=t._currentSize1,a._sizeGradients.length>1?t._currentSize2=a._sizeGradients[1].getFactor():t._currentSize2=t._currentSize1):t.size=D(a.minSize,a.maxSize),t.scale.copyFromFloats(D(a.minScaleX,a.maxScaleX),D(a.minScaleY,a.maxScaleY)),a._startSizeGradients&&a._startSizeGradients[0]&&a.targetStopDuration){var o=a._actualFrame/a.targetStopDuration;Kx.GetCurrentGradient(o,a._startSizeGradients,(function(e,r,n){e!==i._currentStartSizeGradient&&(i._currentStartSize1=i._currentStartSize2,i._currentStartSize2=r.getFactor(),i._currentStartSizeGradient=e);var o=N(i._currentStartSize1,i._currentStartSize2,n);t.scale.scaleInPlace(o)}))}if(a._angularSpeedGradients&&0!==a._angularSpeedGradients.length?(t._currentAngularSpeedGradient=a._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,a._angularSpeedGradients.length>1?t._currentAngularSpeed2=a._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1):t.angularSpeed=D(a.minAngularSpeed,a.maxAngularSpeed),t.angle=D(a.minInitialRotation,a.maxInitialRotation),a._velocityGradients&&a._velocityGradients.length>0&&(t._currentVelocityGradient=a._velocityGradients[0],t._currentVelocity1=t._currentVelocityGradient.getFactor(),a._velocityGradients.length>1?t._currentVelocity2=a._velocityGradients[1].getFactor():t._currentVelocity2=t._currentVelocity1),a._limitVelocityGradients&&a._limitVelocityGradients.length>0&&(t._currentLimitVelocityGradient=a._limitVelocityGradients[0],t._currentLimitVelocity1=t._currentLimitVelocityGradient.getFactor(),a._limitVelocityGradients.length>1?t._currentLimitVelocity2=a._limitVelocityGradients[1].getFactor():t._currentLimitVelocity2=t._currentLimitVelocity1),a._dragGradients&&a._dragGradients.length>0&&(t._currentDragGradient=a._dragGradients[0],t._currentDrag1=t._currentDragGradient.getFactor(),a._dragGradients.length>1?t._currentDrag2=a._dragGradients[1].getFactor():t._currentDrag2=t._currentDrag1),a._colorGradients&&0!==a._colorGradients.length)t._currentColorGradient=a._colorGradients[0],t._currentColorGradient.getColorToRef(t.color),t._currentColor1.copyFrom(t.color),a._colorGradients.length>1?a._colorGradients[1].getColorToRef(t._currentColor2):t._currentColor2.copyFrom(t.color);else{var s=D(0,1);J.LerpToRef(a.color1,a.color2,s,t.color),a.colorDead.subtractToRef(t.color,a._colorDiff),a._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)}a._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=a.startSpriteCellID,t._initialEndSpriteCellID=a.endSpriteCellID,t._initialSpriteCellLoop=a.spriteCellLoop),t.direction.addInPlace(a._inheritedVelocityOffset),a._useRampGradients&&(t.remapData=new k(0,1,0,1)),a.noiseTexture&&(t._randomNoiseCoordinates1?(t._randomNoiseCoordinates1.copyFromFloats(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2.copyFromFloats(Math.random(),Math.random(),Math.random())):(t._randomNoiseCoordinates1=new V(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new V(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()},a=this,s=0;s<e&&"break"!==o();s++);},t._GetAttributeNamesOrOptions=function(e,t,i){void 0===e&&(e=!1),void 0===t&&(t=!1),void 0===i&&(i=!1);var r=[Nr.PositionKind,Nr.ColorKind,"angle","offset","size"];return e&&r.push("cellIndex"),t||r.push("direction"),i&&r.push("remapData"),r},t._GetEffectCreationOptions=function(e,t,i){void 0===e&&(e=!1),void 0===t&&(t=!1),void 0===i&&(i=!1);var r=["invView","view","projection","textureMask","translationPivot","eyePosition"];return Go(r),e&&r.push("particlesInfos"),t&&r.push("logarithmicDepthConstant"),i&&(r.push("vFogInfos"),r.push("vFogColor")),r},t.prototype.fillDefines=function(e,t){if(this._scene&&(zo(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&this._scene.fogMode!==u.FOGMODE_NONE&&e.push("#define FOG")),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===vl.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case u.PARTICLES_BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case u.PARTICLES_BILLBOARDMODE_STRETCHED:case u.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL:e.push("#define BILLBOARDSTRETCHED"),this.billboardMode===u.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case u.PARTICLES_BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))},t.prototype.fillUniformsAttributesAndSamplerNames=function(e,i,r){i.push.apply(i,t._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==u.PARTICLES_BILLBOARDMODE_STRETCHED&&this.billboardMode!==u.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL,this._useRampGradients)),e.push.apply(e,t._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),r.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(hr(e,this._imageProcessingConfigurationDefines),dr(r,this._imageProcessingConfigurationDefines))},t.prototype._getWrapper=function(e){var t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;var i=[];this.fillDefines(i,e);var r=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:u.RENDERPASS_MAIN,n=this._drawWrappers[r];n||(n=this._drawWrappers[r]=[]);var o=n[e];o||((o=new ho(this._engine)).drawContext&&(o.drawContext.useInstancing=this._useInstancing),n[e]=o);var a=i.join("\n");if(o.defines!==a){var s=[],l=[],c=[];this.fillUniformsAttributesAndSamplerNames(l,s,c),o.setEffect(this._engine.createEffect("particles",s,l,c,a),a)}return o},t.prototype.animate=function(e){var t,i=this;if(void 0===e&&(e=!1),this._started){if(!e&&this._scene){if(!this.isReady())return;if(this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}var r;if(this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:(null===(t=this._scene)||void 0===t?void 0:t.getAnimationRatio())||1),this.manualEmitCount>-1)r=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{var n=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){var o=this._actualFrame/this.targetStopDuration;Kx.GetCurrentGradient(o,this._emitRateGradients,(function(e,t,r){e!==i._currentEmitRateGradient&&(i._currentEmitRate1=i._currentEmitRate2,i._currentEmitRate2=t.getFactor(),i._currentEmitRateGradient=e),n=N(i._currentEmitRate1,i._currentEmitRate2,r)}))}r=n*this._scaledUpdateSpeed|0,this._newPartsExcess+=n*this._scaledUpdateSpeed-r}if(this._newPartsExcess>1&&(r+=0|this._newPartsExcess,this._newPartsExcess-=0|this._newPartsExcess),this._alive=!1,this._stopped?r=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(r),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene&&this._scene._toBeDisposed.push(this))),!e){for(var a=0,s=0;s<this._particles.length;s++){var l=this._particles[s];this._appendParticleVertices(a,l),a+=this._useInstancing?1:4}this._vertexBuffer&&this._vertexBuffer.updateDirectly(this._vertexData,0,this._particles.length)}0===this.manualEmitCount&&this.disposeOnStop&&this.stop()}},t.prototype._appendParticleVertices=function(e,t){this._appendParticleVertex(e++,t,0,0),this._useInstancing||(this._appendParticleVertex(e++,t,1,0),this._appendParticleVertex(e++,t,1,1),this._appendParticleVertex(e++,t,0,1))},t.prototype.rebuild=function(){var e;this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._createIndexBuffer(),null===(e=this._spriteBuffer)||void 0===e||e._rebuild(),this._createVertexBuffers(),this.resetDrawCache()},t.prototype.isReady=function(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==vl.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else{if(!this._getWrapper(vl.BLENDMODE_MULTIPLY).effect.isReady())return!1;if(!this._getWrapper(vl.BLENDMODE_ADD).effect.isReady())return!1}return!0},t.prototype._render=function(e){var t,i,r,n,o,a,s,l,c=this._getWrapper(e),h=c.effect,d=this._engine;d.enableEffect(c);var p=null!==(t=this.defaultViewMatrix)&&void 0!==t?t:this._scene.getViewMatrix();if(h.setTexture("diffuseSampler",this.particleTexture),h.setMatrix("view",p),h.setMatrix("projection",null!==(i=this.defaultProjectionMatrix)&&void 0!==i?i:this._scene.getProjectionMatrix()),this._isAnimationSheetEnabled&&this.particleTexture){var f=this.particleTexture.getBaseSize();h.setFloat3("particlesInfos",this.spriteCellWidth/f.width,this.spriteCellHeight/f.height,this.spriteCellWidth/f.width)}if(h.setVector2("translationPivot",this.translationPivot),h.setFloat4("textureMask",this.textureMask.r,this.textureMask.g,this.textureMask.b,this.textureMask.a),this._isBillboardBased&&this._scene){var _=this._scene.activeCamera;h.setVector3("eyePosition",_.globalPosition)}this._rampGradientsTexture&&(this._rampGradients&&this._rampGradients.length||(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),h.setTexture("rampSampler",this._rampGradientsTexture));var m=h.defines;switch(this._scene&&(Ho(h,this,this._scene),this.applyFog&&Qo(this._scene,void 0,h)),m.indexOf("#define BILLBOARDMODE_ALL")>=0&&(p.invertToRef(H.Matrix[0]),h.setMatrix("invView",H.Matrix[0])),void 0!==this._vertexArrayObject?(null===(r=this._scene)||void 0===r?void 0:r.forceWireframe)?d.bindBuffers(this._vertexBuffers,this._linesIndexBufferUseInstancing,h):(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,null,h)),this._engine.bindVertexArrayObject(this._vertexArrayObject,(null===(n=this._scene)||void 0===n?void 0:n.forceWireframe)?this._linesIndexBufferUseInstancing:this._indexBuffer)):this._indexBuffer?d.bindBuffers(this._vertexBuffers,(null===(a=this._scene)||void 0===a?void 0:a.forceWireframe)?this._linesIndexBuffer:this._indexBuffer,h):d.bindBuffers(this._vertexBuffers,(null===(o=this._scene)||void 0===o?void 0:o.forceWireframe)?this._linesIndexBufferUseInstancing:null,h),this.useLogarithmicDepth&&this._scene&&Ko(m,h,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(h),e){case vl.BLENDMODE_ADD:d.setAlphaMode(u.ALPHA_ADD);break;case vl.BLENDMODE_ONEONE:d.setAlphaMode(u.ALPHA_ONEONE);break;case vl.BLENDMODE_STANDARD:d.setAlphaMode(u.ALPHA_COMBINE);break;case vl.BLENDMODE_MULTIPLY:d.setAlphaMode(u.ALPHA_MULTIPLY)}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(h),this._useInstancing?(null===(s=this._scene)||void 0===s?void 0:s.forceWireframe)?d.drawElementsType(u.MATERIAL_LineStripDrawMode,0,10,this._particles.length):d.drawArraysType(u.MATERIAL_TriangleStripDrawMode,0,4,this._particles.length):(null===(l=this._scene)||void 0===l?void 0:l.forceWireframe)?d.drawElementsType(u.MATERIAL_WireFrameFillMode,0,10*this._particles.length):d.drawElementsType(u.MATERIAL_TriangleFillMode,0,6*this._particles.length),this._particles.length},t.prototype.render=function(){if(!this.isReady()||!this._particles.length)return 0;var e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));var t;return t=this.blendMode===vl.BLENDMODE_MULTIPLYADD?this._render(vl.BLENDMODE_MULTIPLY)+this._render(vl.BLENDMODE_ADD):this._render(this.blendMode),this._engine.unbindInstanceAttributes(),this._engine.setAlphaMode(u.ALPHA_DISABLE),t},t.prototype._onDispose=function(e,t){void 0===e&&(e=!1),void 0===t&&(t=!1)},t.prototype.dispose=function(e,t,i){if(void 0===e&&(e=!0),void 0===t&&(t=!1),void 0===i&&(i=!1),this.resetDrawCache(),this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._linesIndexBuffer&&(this._engine._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null),this._linesIndexBufferUseInstancing&&(this._engine._releaseBuffer(this._linesIndexBufferUseInstancing),this._linesIndexBufferUseInstancing=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._onDispose(t,i),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.clear(),this._scene){var r=this._scene.particleSystems.indexOf(this);r>-1&&this._scene.particleSystems.splice(r,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()},t}(vl);!function(e){e[e.ATTACHED=0]="ATTACHED",e[e.END=1]="END"}(qx||(qx={}));var Jx=function(){function e(e){if(this.particleSystem=e,this.type=qx.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){var t=s("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}return e.prototype.clone=function(){var t=this.particleSystem.emitter;t?t instanceof V?t=t.clone():-1!==t.getClassName().indexOf("Mesh")&&((t=new(s("BABYLON.Mesh"))("",t.getScene())).isVisible=!1):t=new V;var i=new e(this.particleSystem.clone(this.particleSystem.name,t));return i.particleSystem.name+="Clone",i.type=this.type,i.inheritDirection=this.inheritDirection,i.inheritedVelocityAmount=this.inheritedVelocityAmount,i.particleSystem._disposeEmitterOnDispose=!0,i.particleSystem.disposeOnStop=!0,i},e.prototype.serialize=function(e){void 0===e&&(e=!1);var t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t},e._ParseParticleSystem=function(e,t,i,r){throw void 0===r&&(r=!1),He("ParseParticle")},e.Parse=function(t,i,r){var n=t.particleSystem,o=new e(e._ParseParticleSystem(n,i,r,!0));return o.type=t.type,o.inheritDirection=t.inheritDirection,o.inheritedVelocityAmount=t.inheritedVelocityAmount,o.particleSystem._isSubEmitter=!0,o},e.prototype.dispose=function(){this.particleSystem.dispose()},e}();function $x(e,t){var i=new Bx;return i.direction1=e,i.direction2=t,i}function eA(e,t){return void 0===e&&(e=1),void 0===t&&(t=1),new wx(e,t)}function tA(e,t){return void 0===e&&(e=1),void 0===t&&(t=1),new Ux(e,t)}function iA(e,t,i){return void 0===e&&(e=1),void 0===t&&(t=new V(0,1,0)),void 0===i&&(i=new V(0,1,0)),new Vx(e,t,i)}function rA(e,t,i,r){return void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=1),void 0===r&&(r=0),new Fx(e,t,i,r)}function nA(e,t,i,r,n){return void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=1),void 0===r&&(r=new V(0,1,0)),void 0===n&&(n=new V(0,1,0)),new Lx(e,t,i,r,n)}function oA(e,t){return void 0===e&&(e=1),void 0===t&&(t=Math.PI/4),new Nx(e,t)}var aA=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._disposeEmitterOnDispose=!1,t._emitFromParticle=function(e){if(t._subEmitters&&0!==t._subEmitters.length){var i=Math.floor(Math.random()*t._subEmitters.length);t._subEmitters[i].forEach((function(i){if(i.type===qx.END){var r=i.clone();e._inheritParticleInfoToSubEmitter(r),r.particleSystem._rootParticleSystem=t,t.activeSubSystems.push(r.particleSystem),r.particleSystem.start()}}))}},t}return m(t,e),t.prototype.createPointEmitter=function(e,t){var i=$x(e,t);return this.particleEmitterType=i,i},t.prototype.createHemisphericEmitter=function(e,t){void 0===e&&(e=1),void 0===t&&(t=1);var i=eA(e,t);return this.particleEmitterType=i,i},t.prototype.createSphereEmitter=function(e,t){void 0===e&&(e=1),void 0===t&&(t=1);var i=tA(e,t);return this.particleEmitterType=i,i},t.prototype.createDirectedSphereEmitter=function(e,t,i){void 0===e&&(e=1),void 0===t&&(t=new V(0,1,0)),void 0===i&&(i=new V(0,1,0));var r=iA(e,t,i);return this.particleEmitterType=r,r},t.prototype.createCylinderEmitter=function(e,t,i,r){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=1),void 0===r&&(r=0);var n=rA(e,t,i,r);return this.particleEmitterType=n,n},t.prototype.createDirectedCylinderEmitter=function(e,t,i,r,n){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=1),void 0===r&&(r=new V(0,1,0)),void 0===n&&(n=new V(0,1,0));var o=nA(e,t,i,r,n);return this.particleEmitterType=o,o},t.prototype.createConeEmitter=function(e,t){void 0===e&&(e=1),void 0===t&&(t=Math.PI/4);var i=oA(e,t);return this.particleEmitterType=i,i},t.prototype.createBoxEmitter=function(e,t,i,r){var n=new Dx;return this.particleEmitterType=n,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=r,n},t.prototype._prepareSubEmitterInternalArray=function(){var e=this;this._subEmitters=new Array,this.subEmitters&&this.subEmitters.forEach((function(i){i instanceof t?e._subEmitters.push([new Jx(i)]):i instanceof Jx?e._subEmitters.push([i]):i instanceof Array&&e._subEmitters.push(i)}))},t.prototype._stopSubEmitters=function(){this.activeSubSystems&&(this.activeSubSystems.forEach((function(e){e.stop(!0)})),this.activeSubSystems=[])},t.prototype._removeFromRoot=function(){if(this._rootParticleSystem){var e=this._rootParticleSystem.activeSubSystems.indexOf(this);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}},t.prototype._preStart=function(){this._prepareSubEmitterInternalArray(),this._subEmitters&&0!=this._subEmitters.length&&(this.activeSubSystems=[])},t.prototype._postStop=function(e){e&&this._stopSubEmitters()},t.prototype._prepareParticle=function(e){if(this._subEmitters&&this._subEmitters.length>0){var t=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];e._attachedSubEmitters=[],t.forEach((function(t){if(t.type===qx.ATTACHED){var i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}}))}},t.prototype._onDispose=function(e,t){var i;if(void 0===e&&(e=!1),void 0===t&&(t=!1),this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),e&&(null===(i=this.particles)||void 0===i||i.forEach((function(e){if(e._attachedSubEmitters)for(var t=e._attachedSubEmitters.length-1;t>=0;t-=1)e._attachedSubEmitters[t].dispose()}))),t&&this.activeSubSystems)for(var r=this.activeSubSystems.length-1;r>=0;r-=1)this.activeSubSystems[r].dispose();if(this._subEmitters&&this._subEmitters.length){for(var n=0;n<this._subEmitters.length;n++)for(var o=0,a=this._subEmitters[n];o<a.length;o++)a[o].dispose();this._subEmitters=[],this.subEmitters=[]}this._disposeEmitterOnDispose&&this.emitter&&this.emitter.dispose&&this.emitter.dispose(!0)},t._Parse=function(e,t,i,r){var n,o,a,l;l=i instanceof Mi?null:i;var c,u=s("BABYLON.Texture");if(u&&l&&(e.texture?t.particleTexture=u.Parse(e.texture,l,r):e.textureName&&(t.particleTexture=new u(r+e.textureName,l,!1,void 0===e.invertY||e.invertY),t.particleTexture.name=e.textureName)),e.emitterId||0===e.emitterId||void 0!==e.emitter?e.emitterId&&l?t.emitter=l.getLastMeshById(e.emitterId):t.emitter=V.FromArray(e.emitter):t.emitter=V.Zero(),t.isLocal=!!e.isLocal,void 0!==e.renderingGroupId&&(t.renderingGroupId=e.renderingGroupId),void 0!==e.isBillboardBased&&(t.isBillboardBased=e.isBillboardBased),void 0!==e.billboardMode&&(t.billboardMode=e.billboardMode),void 0!==e.useLogarithmicDepth&&(t.useLogarithmicDepth=e.useLogarithmicDepth),e.animations){for(var h=0;h<e.animations.length;h++){var d=e.animations[h],p=s("BABYLON.Animation");p&&t.animations.push(p.Parse(d))}t.beginAnimationOnStart=e.beginAnimationOnStart,t.beginAnimationFrom=e.beginAnimationFrom,t.beginAnimationTo=e.beginAnimationTo,t.beginAnimationLoop=e.beginAnimationLoop}if(e.autoAnimate&&l&&l.beginAnimation(t,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),t.startDelay=0|e.startDelay,t.minAngularSpeed=e.minAngularSpeed,t.maxAngularSpeed=e.maxAngularSpeed,t.minSize=e.minSize,t.maxSize=e.maxSize,e.minScaleX&&(t.minScaleX=e.minScaleX,t.maxScaleX=e.maxScaleX,t.minScaleY=e.minScaleY,t.maxScaleY=e.maxScaleY),void 0!==e.preWarmCycles&&(t.preWarmCycles=e.preWarmCycles,t.preWarmStepOffset=e.preWarmStepOffset),void 0!==e.minInitialRotation&&(t.minInitialRotation=e.minInitialRotation,t.maxInitialRotation=e.maxInitialRotation),t.minLifeTime=e.minLifeTime,t.maxLifeTime=e.maxLifeTime,t.minEmitPower=e.minEmitPower,t.maxEmitPower=e.maxEmitPower,t.emitRate=e.emitRate,t.gravity=V.FromArray(e.gravity),e.noiseStrength&&(t.noiseStrength=V.FromArray(e.noiseStrength)),t.color1=J.FromArray(e.color1),t.color2=J.FromArray(e.color2),t.colorDead=J.FromArray(e.colorDead),t.updateSpeed=e.updateSpeed,t.targetStopDuration=e.targetStopDuration,t.blendMode=e.blendMode,e.colorGradients)for(var f=0,_=e.colorGradients;f<_.length;f++){var m=_[f];t.addColorGradient(m.gradient,J.FromArray(m.color1),m.color2?J.FromArray(m.color2):void 0)}if(e.rampGradients){for(var g=0,v=e.rampGradients;g<v.length;g++){var y=v[g];t.addRampGradient(y.gradient,Z.FromArray(y.color))}t.useRampGradients=e.useRampGradients}if(e.colorRemapGradients)for(var b=0,T=e.colorRemapGradients;b<T.length;b++){var E=T[b];t.addColorRemapGradient(E.gradient,void 0!==E.factor1?E.factor1:E.factor,E.factor2)}if(e.alphaRemapGradients)for(var S=0,x=e.alphaRemapGradients;S<x.length;S++){var A=x[S];t.addAlphaRemapGradient(A.gradient,void 0!==A.factor1?A.factor1:A.factor,A.factor2)}if(e.sizeGradients)for(var C=0,R=e.sizeGradients;C<R.length;C++){var P=R[C];t.addSizeGradient(P.gradient,void 0!==P.factor1?P.factor1:P.factor,P.factor2)}if(e.angularSpeedGradients)for(var I=0,M=e.angularSpeedGradients;I<M.length;I++){var O=M[I];t.addAngularSpeedGradient(O.gradient,void 0!==O.factor1?O.factor1:O.factor,O.factor2)}if(e.velocityGradients)for(var D=0,N=e.velocityGradients;D<N.length;D++){var F=N[D];t.addVelocityGradient(F.gradient,void 0!==F.factor1?F.factor1:F.factor,F.factor2)}if(e.dragGradients)for(var L=0,w=e.dragGradients;L<w.length;L++){var B=w[L];t.addDragGradient(B.gradient,void 0!==B.factor1?B.factor1:B.factor,B.factor2)}if(e.emitRateGradients)for(var U=0,k=e.emitRateGradients;U<k.length;U++){var G=k[U];t.addEmitRateGradient(G.gradient,void 0!==G.factor1?G.factor1:G.factor,G.factor2)}if(e.startSizeGradients)for(var z=0,W=e.startSizeGradients;z<W.length;z++){var H=W[z];t.addStartSizeGradient(H.gradient,void 0!==H.factor1?H.factor1:H.factor,H.factor2)}if(e.lifeTimeGradients)for(var X=0,j=e.lifeTimeGradients;X<j.length;X++){var Y=j[X];t.addLifeTimeGradient(Y.gradient,void 0!==Y.factor1?Y.factor1:Y.factor,Y.factor2)}if(e.limitVelocityGradients){for(var K=0,Q=e.limitVelocityGradients;K<Q.length;K++){var q=Q[K];t.addLimitVelocityGradient(q.gradient,void 0!==q.factor1?q.factor1:q.factor,q.factor2)}t.limitVelocityDamping=e.limitVelocityDamping}if(e.noiseTexture&&l){var $=s("BABYLON.ProceduralTexture");t.noiseTexture=$.Parse(e.noiseTexture,l,r)}if(e.particleEmitterType){switch(e.particleEmitterType.type){case"SphereParticleEmitter":c=new Ux;break;case"SphereDirectedParticleEmitter":c=new Vx;break;case"ConeEmitter":case"ConeParticleEmitter":c=new Nx;break;case"CylinderParticleEmitter":c=new Fx;break;case"CylinderDirectedParticleEmitter":c=new Lx;break;case"HemisphericParticleEmitter":c=new wx;break;case"PointParticleEmitter":c=new Bx;break;case"MeshParticleEmitter":c=new Gx;break;case"CustomParticleEmitter":c=new kx;break;default:c=new Dx}c.parse(e.particleEmitterType,l)}else(c=new Dx).parse(e,l);t.particleEmitterType=c,t.startSpriteCellID=e.startSpriteCellID,t.endSpriteCellID=e.endSpriteCellID,t.spriteCellLoop=null===(n=e.spriteCellLoop)||void 0===n||n,t.spriteCellWidth=e.spriteCellWidth,t.spriteCellHeight=e.spriteCellHeight,t.spriteCellChangeSpeed=e.spriteCellChangeSpeed,t.spriteRandomStartCell=e.spriteRandomStartCell,t.disposeOnStop=null!==(o=e.disposeOnStop)&&void 0!==o&&o,t.manualEmitCount=null!==(a=e.manualEmitCount)&&void 0!==a?a:-1},t.Parse=function(e,i,r,n,o){void 0===n&&(n=!1);var a,s=e.name,l=null,c=null;if(a=i instanceof Mi?i:i.getEngine(),e.customShader&&a.createEffectForParticles){var u=(c=e.customShader).shaderOptions.defines.length>0?c.shaderOptions.defines.join("\n"):"";l=a.createEffectForParticles(c.shaderPath.fragmentElement,c.shaderOptions.uniforms,c.shaderOptions.samplers,u)}var h=new t(s,o||e.capacity,i,l,e.isAnimationSheetEnabled);if(h.customShader=c,h._rootUrl=r,e.id&&(h.id=e.id),e.subEmitters){h.subEmitters=[];for(var d=0,p=e.subEmitters;d<p.length;d++){for(var f=[],_=0,m=p[d];_<m.length;_++){var g=m[_];f.push(Jx.Parse(g,i,r))}h.subEmitters.push(f)}}return t._Parse(e,h,i,r),e.textureMask&&(h.textureMask=J.FromArray(e.textureMask)),e.worldOffset&&(h.worldOffset=V.FromArray(e.worldOffset)),e.preventAutoStart&&(h.preventAutoStart=e.preventAutoStart),n||h.preventAutoStart||h.start(),h},t.prototype.serialize=function(e){void 0===e&&(e=!1);var i={};if(t._Serialize(i,this,e),i.textureMask=this.textureMask.asArray(),i.customShader=this.customShader,i.preventAutoStart=this.preventAutoStart,i.worldOffset=this.worldOffset.asArray(),this.subEmitters){i.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(var r=0,n=this._subEmitters;r<n.length;r++){for(var o=[],a=0,s=n[r];a<s.length;a++){var l=s[a];o.push(l.serialize(e))}i.subEmitters.push(o)}}return i},t._Serialize=function(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){var r=t.emitter;e.emitterId=r.id}else{var n=t.emitter;e.emitter=n.asArray()}t.particleEmitterType&&(e.particleEmitterType=t.particleEmitterType.serialize()),t.particleTexture&&(i?e.texture=t.particleTexture.serialize():(e.textureName=t.particleTexture.name,e.invertY=!!t.particleTexture._invertY)),e.isLocal=t.isLocal,Ke.AppendSerializedAnimations(t,e),e.beginAnimationOnStart=t.beginAnimationOnStart,e.beginAnimationFrom=t.beginAnimationFrom,e.beginAnimationTo=t.beginAnimationTo,e.beginAnimationLoop=t.beginAnimationLoop,e.startDelay=t.startDelay,e.renderingGroupId=t.renderingGroupId,e.isBillboardBased=t.isBillboardBased,e.billboardMode=t.billboardMode,e.minAngularSpeed=t.minAngularSpeed,e.maxAngularSpeed=t.maxAngularSpeed,e.minSize=t.minSize,e.maxSize=t.maxSize,e.minScaleX=t.minScaleX,e.maxScaleX=t.maxScaleX,e.minScaleY=t.minScaleY,e.maxScaleY=t.maxScaleY,e.minEmitPower=t.minEmitPower,e.maxEmitPower=t.maxEmitPower,e.minLifeTime=t.minLifeTime,e.maxLifeTime=t.maxLifeTime,e.emitRate=t.emitRate,e.gravity=t.gravity.asArray(),e.noiseStrength=t.noiseStrength.asArray(),e.color1=t.color1.asArray(),e.color2=t.color2.asArray(),e.colorDead=t.colorDead.asArray(),e.updateSpeed=t.updateSpeed,e.targetStopDuration=t.targetStopDuration,e.blendMode=t.blendMode,e.preWarmCycles=t.preWarmCycles,e.preWarmStepOffset=t.preWarmStepOffset,e.minInitialRotation=t.minInitialRotation,e.maxInitialRotation=t.maxInitialRotation,e.startSpriteCellID=t.startSpriteCellID,e.spriteCellLoop=t.spriteCellLoop,e.endSpriteCellID=t.endSpriteCellID,e.spriteCellChangeSpeed=t.spriteCellChangeSpeed,e.spriteCellWidth=t.spriteCellWidth,e.spriteCellHeight=t.spriteCellHeight,e.spriteRandomStartCell=t.spriteRandomStartCell,e.isAnimationSheetEnabled=t.isAnimationSheetEnabled,e.useLogarithmicDepth=t.useLogarithmicDepth;var o=t.getColorGradients();if(o){e.colorGradients=[];for(var a=0,s=o;a<s.length;a++){var l=s[a],c={gradient:l.gradient,color1:l.color1.asArray()};l.color2?c.color2=l.color2.asArray():c.color2=l.color1.asArray(),e.colorGradients.push(c)}}var u=t.getRampGradients();if(u){e.rampGradients=[];for(var h=0,d=u;h<d.length;h++){var p=d[h];c={gradient:p.gradient,color:p.color.asArray()},e.rampGradients.push(c)}e.useRampGradients=t.useRampGradients}var f=t.getColorRemapGradients();if(f){e.colorRemapGradients=[];for(var _=0,m=f;_<m.length;_++){var g=m[_];c={gradient:g.gradient,factor1:g.factor1},void 0!==g.factor2?c.factor2=g.factor2:c.factor2=g.factor1,e.colorRemapGradients.push(c)}}var v=t.getAlphaRemapGradients();if(v){e.alphaRemapGradients=[];for(var y=0,b=v;y<b.length;y++){var T=b[y];c={gradient:T.gradient,factor1:T.factor1},void 0!==T.factor2?c.factor2=T.factor2:c.factor2=T.factor1,e.alphaRemapGradients.push(c)}}var E=t.getSizeGradients();if(E){e.sizeGradients=[];for(var S=0,x=E;S<x.length;S++){var A=x[S];c={gradient:A.gradient,factor1:A.factor1},void 0!==A.factor2?c.factor2=A.factor2:c.factor2=A.factor1,e.sizeGradients.push(c)}}var C=t.getAngularSpeedGradients();if(C){e.angularSpeedGradients=[];for(var R=0,P=C;R<P.length;R++){var I=P[R];c={gradient:I.gradient,factor1:I.factor1},void 0!==I.factor2?c.factor2=I.factor2:c.factor2=I.factor1,e.angularSpeedGradients.push(c)}}var M=t.getVelocityGradients();if(M){e.velocityGradients=[];for(var O=0,D=M;O<D.length;O++){var N=D[O];c={gradient:N.gradient,factor1:N.factor1},void 0!==N.factor2?c.factor2=N.factor2:c.factor2=N.factor1,e.velocityGradients.push(c)}}var F=t.getDragGradients();if(F){e.dragGradients=[];for(var L=0,w=F;L<w.length;L++){var B=w[L];c={gradient:B.gradient,factor1:B.factor1},void 0!==B.factor2?c.factor2=B.factor2:c.factor2=B.factor1,e.dragGradients.push(c)}}var U=t.getEmitRateGradients();if(U){e.emitRateGradients=[];for(var V=0,k=U;V<k.length;V++){var G=k[V];c={gradient:G.gradient,factor1:G.factor1},void 0!==G.factor2?c.factor2=G.factor2:c.factor2=G.factor1,e.emitRateGradients.push(c)}}var z=t.getStartSizeGradients();if(z){e.startSizeGradients=[];for(var W=0,H=z;W<H.length;W++){var X=H[W];c={gradient:X.gradient,factor1:X.factor1},void 0!==X.factor2?c.factor2=X.factor2:c.factor2=X.factor1,e.startSizeGradients.push(c)}}var j=t.getLifeTimeGradients();if(j){e.lifeTimeGradients=[];for(var Y=0,K=j;Y<K.length;Y++){var Q=K[Y];c={gradient:Q.gradient,factor1:Q.factor1},void 0!==Q.factor2?c.factor2=Q.factor2:c.factor2=Q.factor1,e.lifeTimeGradients.push(c)}}var q=t.getLimitVelocityGradients();if(q){e.limitVelocityGradients=[];for(var Z=0,J=q;Z<J.length;Z++){var $=J[Z];c={gradient:$.gradient,factor1:$.factor1},void 0!==$.factor2?c.factor2=$.factor2:c.factor2=$.factor1,e.limitVelocityGradients.push(c)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())},t.prototype.clone=function(e,i,r){void 0===r&&(r=!1);var n=g({},this._customWrappers),o=null,a=this._engine;if(a.createEffectForParticles&&null!=this.customShader){var s=(o=this.customShader).shaderOptions.defines.length>0?o.shaderOptions.defines.join("\n"):"",l=a.createEffectForParticles(o.shaderPath.fragmentElement,o.shaderOptions.uniforms,o.shaderOptions.samplers,s);n[0]?n[0].effect=l:this.setCustomEffect(l,0)}var c=this.serialize(r),u=t.Parse(c,this._scene||this._engine,this._rootUrl);return u.name=e,u.customShader=o,u._customWrappers=n,void 0===i&&(i=this.emitter),this.noiseTexture&&(u.noiseTexture=this.noiseTexture.clone()),u.emitter=i,this.preventAutoStart||u.start(),u},t.BILLBOARDMODE_Y=u.PARTICLES_BILLBOARDMODE_Y,t.BILLBOARDMODE_ALL=u.PARTICLES_BILLBOARDMODE_ALL,t.BILLBOARDMODE_STRETCHED=u.PARTICLES_BILLBOARDMODE_STRETCHED,t.BILLBOARDMODE_STRETCHED_LOCAL=u.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL,t}(Zx);Jx._ParseParticleSystem=aA.Parse;li.IncludesShadersStore.clipPlaneFragmentDeclaration2="#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nin float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nin float fClipDistance6;\n#endif\n";li.ShadersStore.gpuRenderParticlesPixelShader="precision highp float;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform sampler2D diffuseSampler;varying vec2 vUV;varying vec4 vColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<logDepthDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#include<fogFragmentDeclaration>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture2D(diffuseSampler,vUV);gl_FragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha);\n#endif \n#include<logDepthFragment>\n#include<fogFragment>(color,gl_FragColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\ngl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessing(gl_FragColor);\n#endif\n#endif\n}\n";li.IncludesShadersStore.clipPlaneVertexDeclaration2="#ifdef CLIPPLANE\nuniform vec4 vClipPlane;out float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;out float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;out float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;out float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nuniform vec4 vClipPlane5;out float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nuniform vec4 vClipPlane6;out float fClipDistance6;\n#endif\n";li.ShadersStore.gpuRenderParticlesVertexShader="precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset;\n#ifdef LOCAL\nuniform mat4 emitterWM;\n#endif\nattribute vec3 position;attribute float age;attribute float life;attribute vec3 size;\n#ifndef BILLBOARD\nattribute vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\nattribute float angle;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\nattribute vec2 offset;attribute vec2 uv;varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW;\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#include<fogVertexDeclaration>\n#include<logDepthDeclaration>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;attribute vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;\n#ifdef LOCAL\nreturn ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;\n#else\nreturn (position+worldOffset)+alignedCorner;\n#endif\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;\n#ifdef LOCAL\nreturn ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;\n#else\nreturn (position+worldOffset)+alignedCorner;\n#endif\n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);float columnOffset=cellIndex-rowOffset*sheetInfos.z;vec2 uvScale=sheetInfos.xy;vec2 uvOffset=vec2(uv.x ,1.0-uv.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture2D(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x;\n#ifdef BILLBOARD\nvec4 rotatedCorner;rotatedCorner.w=0.;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=(position+worldOffset)-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0));\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=(position+worldOffset)-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0));\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;\n#ifdef LOCAL\nvec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner;\n#else\nvec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner;\n#endif\nvPositionW=(invView*viewPosition).xyz;\n#endif\n#else\nvec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=0.;rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(initialDirection);vPositionW=rotate(yaxis,rotatedCorner);vec4 viewPosition=view*vec4(vPositionW,1.0);\n#endif\ngl_Position=projection*viewPosition;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<logDepthVertex>\n}";var sA=function(e){function t(t,i,r,n,o){void 0===n&&(n=null),void 0===o&&(o=!1);var a=e.call(this,t)||this;if(a.layerMask=268435455,a._accumulatedCount=0,a._renderVertexBuffers=[],a._targetIndex=0,a._currentRenderId=-1,a._currentRenderingCameraUniqueId=-1,a._started=!1,a._stopped=!1,a._timeDelta=0,a.updateInAnimate=!1,a._actualFrame=0,a._rawTextureWidth=256,a._rebuildingAfterContextLost=!1,a.onDisposeObservable=new f,a.onStoppedObservable=new f,a.forceDepthWrite=!1,a._preWarmDone=!1,a.isLocal=!1,a.isGPU=!0,a._onBeforeDrawParticlesObservable=null,r&&"Scene"!==r.getClassName()?(a._engine=r,a.defaultProjectionMatrix=z.PerspectiveFovLH(.8,1,.1,100,a._engine.isNDCHalfZRange)):(a._scene=r||M.LastCreatedScene,a._engine=a._scene.getEngine(),a.uniqueId=a._scene.getUniqueId(),a._scene.particleSystems.push(a)),a._engine.getCaps().supportComputeShaders){if(!s("BABYLON.ComputeShaderParticleSystem"))throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");a._platform=new(s("BABYLON.ComputeShaderParticleSystem"))(a,a._engine)}else{if(!s("BABYLON.WebGL2ParticleSystem"))throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");a._platform=new(s("BABYLON.WebGL2ParticleSystem"))(a,a._engine)}a._customWrappers={0:new ho(a._engine)},a._customWrappers[0].effect=n,a._drawWrappers={0:new ho(a._engine)},a._drawWrappers[0].drawContext&&(a._drawWrappers[0].drawContext.useInstancing=!0),a._createIndexBuffer(),a._attachImageProcessingConfiguration(null),(i=null!=i?i:{}).randomTextureSize||delete i.randomTextureSize;var l=g({capacity:5e4,randomTextureSize:a._engine.getCaps().maxTextureSize},i),c=i;isFinite(c)&&(l.capacity=c),a._capacity=l.capacity,a._maxActiveParticleCount=l.capacity,a._currentActiveCount=0,a._isAnimationSheetEnabled=o,a.particleEmitterType=new Dx;for(var h=Math.min(a._engine.getCaps().maxTextureSize,l.randomTextureSize),d=[],p=0;p<h;++p)d.push(Math.random()),d.push(Math.random()),d.push(Math.random()),d.push(Math.random());for(a._randomTexture=new is(new Float32Array(d),h,1,u.TEXTUREFORMAT_RGBA,r,!1,!1,u.TEXTURE_NEAREST_SAMPLINGMODE,u.TEXTURETYPE_FLOAT),a._randomTexture.name="GPUParticleSystem_random1",a._randomTexture.wrapU=u.TEXTURE_WRAP_ADDRESSMODE,a._randomTexture.wrapV=u.TEXTURE_WRAP_ADDRESSMODE,d=[],p=0;p<h;++p)d.push(Math.random()),d.push(Math.random()),d.push(Math.random()),d.push(Math.random());return a._randomTexture2=new is(new Float32Array(d),h,1,u.TEXTUREFORMAT_RGBA,r,!1,!1,u.TEXTURE_NEAREST_SAMPLINGMODE,u.TEXTURETYPE_FLOAT),a._randomTexture2.name="GPUParticleSystem_random2",a._randomTexture2.wrapU=u.TEXTURE_WRAP_ADDRESSMODE,a._randomTexture2.wrapV=u.TEXTURE_WRAP_ADDRESSMODE,a._randomTextureSize=h,a}return m(t,e),Object.defineProperty(t,"IsSupported",{get:function(){if(!M.LastCreatedEngine)return!1;var e=M.LastCreatedEngine.getCaps();return e.supportTransformFeedbacks||e.supportComputeShaders},enumerable:!1,configurable:!0}),t.prototype._createIndexBuffer=function(){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]),void 0,"GPUParticleSystemLinesIndexBuffer")},t.prototype.getCapacity=function(){return this._capacity},Object.defineProperty(t.prototype,"maxActiveParticleCount",{get:function(){return this._maxActiveParticleCount},set:function(e){this._maxActiveParticleCount=Math.min(e,this._capacity)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"activeParticleCount",{get:function(){return this.maxActiveParticleCount},set:function(e){this.maxActiveParticleCount=e},enumerable:!1,configurable:!0}),t.prototype.createPointEmitter=function(e,t){var i=$x(e,t);return this.particleEmitterType=i,i},t.prototype.createHemisphericEmitter=function(e,t){void 0===e&&(e=1),void 0===t&&(t=1);var i=eA(e,t);return this.particleEmitterType=i,i},t.prototype.createSphereEmitter=function(e,t){void 0===e&&(e=1),void 0===t&&(t=1);var i=tA(e,t);return this.particleEmitterType=i,i},t.prototype.createDirectedSphereEmitter=function(e,t,i){void 0===e&&(e=1),void 0===t&&(t=new V(0,1,0)),void 0===i&&(i=new V(0,1,0));var r=iA(e,t,i);return this.particleEmitterType=r,r},t.prototype.createCylinderEmitter=function(e,t,i,r){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=1),void 0===r&&(r=0);var n=rA(e,t,i,r);return this.particleEmitterType=n,n},t.prototype.createDirectedCylinderEmitter=function(e,t,i,r,n){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=1),void 0===r&&(r=new V(0,1,0)),void 0===n&&(n=new V(0,1,0));var o=nA(e,t,i,r,n);return this.particleEmitterType=o,o},t.prototype.createConeEmitter=function(e,t){void 0===e&&(e=1),void 0===t&&(t=Math.PI/4);var i=oA(e,t);return this.particleEmitterType=i,i},t.prototype.createBoxEmitter=function(e,t,i,r){var n=new Dx;return this.particleEmitterType=n,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=r,n},t.prototype.isReady=function(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady()||this._rebuildingAfterContextLost)return!1;if(this.blendMode!==aA.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else{if(!this._getWrapper(aA.BLENDMODE_MULTIPLY).effect.isReady())return!1;if(!this._getWrapper(aA.BLENDMODE_ADD).effect.isReady())return!1}return this._platform.isUpdateBufferCreated()?this._platform.isUpdateBufferReady():(this._recreateUpdateEffect(),!1)},t.prototype.isStarted=function(){return this._started},t.prototype.isStopped=function(){return this._stopped},t.prototype.isStopping=function(){return!1},t.prototype.getActiveCount=function(){return this._currentActiveCount},t.prototype.start=function(e){var t=this;if(void 0===e&&(e=this.startDelay),!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";e?setTimeout((function(){t.start(0)}),e):(this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop))},t.prototype.stop=function(){this._stopped||(this._stopped=!0)},t.prototype.reset=function(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0},t.prototype.getClassName=function(){return"GPUParticleSystem"},t.prototype.getCustomEffect=function(e){var t,i;return void 0===e&&(e=0),null!==(i=null===(t=this._customWrappers[e])||void 0===t?void 0:t.effect)&&void 0!==i?i:this._customWrappers[0].effect},t.prototype._getCustomDrawWrapper=function(e){var t;return void 0===e&&(e=0),null!==(t=this._customWrappers[e])&&void 0!==t?t:this._customWrappers[0]},t.prototype.setCustomEffect=function(e,t){void 0===t&&(t=0),this._customWrappers[t]=new ho(this._engine),this._customWrappers[t].effect=e},Object.defineProperty(t.prototype,"onBeforeDrawParticlesObservable",{get:function(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new f),this._onBeforeDrawParticlesObservable},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vertexShaderName",{get:function(){return"gpuRenderParticles"},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vertexBuffers",{get:function(){return this._renderVertexBuffers[1^this._targetIndex]},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"indexBuffer",{get:function(){return null},enumerable:!1,configurable:!0}),t.prototype._removeGradientAndTexture=function(t,i,r){return e.prototype._removeGradientAndTexture.call(this,t,i,r),this._releaseBuffers(),this},t.prototype.addColorGradient=function(e,t){this._colorGradients||(this._colorGradients=[]);var i=new Xx(e,t);return this._colorGradients.push(i),this._refreshColorGradient(!0),this._releaseBuffers(),this},t.prototype._refreshColorGradient=function(e){void 0===e&&(e=!1),this._colorGradients&&(e&&this._colorGradients.sort((function(e,t){return e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0})),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null))},t.prototype.forceRefreshGradients=function(){this._refreshColorGradient(),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture"),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture"),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture"),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture"),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture"),this.reset()},t.prototype.removeColorGradient=function(e){return this._removeGradientAndTexture(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this},t.prototype.resetDrawCache=function(){var e;for(var t in this._drawWrappers)null===(e=this._drawWrappers[t].drawContext)||void 0===e||e.reset()},t.prototype._addFactorGradient=function(e,t,i){var r=new Yx(t,i);e.push(r),this._releaseBuffers()},t.prototype.addSizeGradient=function(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this},t.prototype.removeSizeGradient=function(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this},t.prototype._refreshFactorGradient=function(e,t,i){if(void 0===i&&(i=!1),e){i&&e.sort((function(e,t){return e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0}));var r=this;r[t]&&(r[t].dispose(),r[t]=null)}},t.prototype.addAngularSpeedGradient=function(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this},t.prototype.removeAngularSpeedGradient=function(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this},t.prototype.addVelocityGradient=function(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this},t.prototype.removeVelocityGradient=function(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this},t.prototype.addLimitVelocityGradient=function(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this},t.prototype.removeLimitVelocityGradient=function(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this},t.prototype.addDragGradient=function(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this},t.prototype.removeDragGradient=function(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this},t.prototype.addEmitRateGradient=function(){return this},t.prototype.removeEmitRateGradient=function(){return this},t.prototype.addStartSizeGradient=function(){return this},t.prototype.removeStartSizeGradient=function(){return this},t.prototype.addColorRemapGradient=function(){return this},t.prototype.removeColorRemapGradient=function(){return this},t.prototype.addAlphaRemapGradient=function(){return this},t.prototype.removeAlphaRemapGradient=function(){return this},t.prototype.addRampGradient=function(){return this},t.prototype.removeRampGradient=function(){return this},t.prototype.getRampGradients=function(){return null},Object.defineProperty(t.prototype,"useRampGradients",{get:function(){return!1},set:function(e){},enumerable:!1,configurable:!0}),t.prototype.addLifeTimeGradient=function(){return this},t.prototype.removeLifeTimeGradient=function(){return this},t.prototype._reset=function(){this._releaseBuffers()},t.prototype._createVertexBuffers=function(e,t,i){var r={};r.position=t.createVertexBuffer("position",0,3,this._attributesStrideSize,!0);var n=3;r.age=t.createVertexBuffer("age",n,1,this._attributesStrideSize,!0),n+=1,r.size=t.createVertexBuffer("size",n,3,this._attributesStrideSize,!0),n+=3,r.life=t.createVertexBuffer("life",n,1,this._attributesStrideSize,!0),n+=1,n+=4,this.billboardMode===aA.BILLBOARDMODE_STRETCHED&&(r.direction=t.createVertexBuffer("direction",n,3,this._attributesStrideSize,!0)),n+=3,this._platform.alignDataInBuffer&&(n+=1),this.particleEmitterType instanceof kx&&(n+=3,this._platform.alignDataInBuffer&&(n+=1)),this._colorGradientsTexture||(r.color=t.createVertexBuffer("color",n,4,this._attributesStrideSize,!0),n+=4),this._isBillboardBased||(r.initialDirection=t.createVertexBuffer("initialDirection",n,3,this._attributesStrideSize,!0),n+=3,this._platform.alignDataInBuffer&&(n+=1)),this.noiseTexture&&(r.noiseCoordinates1=t.createVertexBuffer("noiseCoordinates1",n,3,this._attributesStrideSize,!0),n+=3,this._platform.alignDataInBuffer&&(n+=1),r.noiseCoordinates2=t.createVertexBuffer("noiseCoordinates2",n,3,this._attributesStrideSize,!0),n+=3,this._platform.alignDataInBuffer&&(n+=1)),r.angle=t.createVertexBuffer("angle",n,1,this._attributesStrideSize,!0),this._angularSpeedGradientsTexture?n++:n+=2,this._isAnimationSheetEnabled&&(r.cellIndex=t.createVertexBuffer("cellIndex",n,1,this._attributesStrideSize,!0),n+=1,this.spriteRandomStartCell&&(r.cellStartOffset=t.createVertexBuffer("cellStartOffset",n,1,this._attributesStrideSize,!0),n+=1)),r.offset=i.createVertexBuffer("offset",0,2),r.uv=i.createVertexBuffer("uv",2,2),this._renderVertexBuffers.push(r),this._platform.createVertexBuffers(e,r),this.resetDrawCache()},t.prototype._initialize=function(e){if(void 0===e&&(e=!1),!this._buffer0||e){var t=this._engine,i=[];this._attributesStrideSize=21,this._targetIndex=0,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=1),this.particleEmitterType instanceof kx&&(this._attributesStrideSize+=3,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=1)),this.isBillboardBased||(this._attributesStrideSize+=3,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=1)),this._colorGradientsTexture&&(this._attributesStrideSize-=4),this._angularSpeedGradientsTexture&&(this._attributesStrideSize-=1),this._isAnimationSheetEnabled&&(this._attributesStrideSize+=1,this.spriteRandomStartCell&&(this._attributesStrideSize+=1)),this.noiseTexture&&(this._attributesStrideSize+=6,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=2)),this._platform.alignDataInBuffer&&(this._attributesStrideSize+=3-(this._attributesStrideSize+3&3));for(var r=this.particleEmitterType instanceof kx,n=H.Vector3[0],o=0,a=0;a<this._capacity;a++)if(i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),r?(this.particleEmitterType.particleDestinationGenerator(a,null,n),i.push(n.x),i.push(n.y),i.push(n.z)):(i.push(0),i.push(0),i.push(0)),this._platform.alignDataInBuffer&&i.push(0),o+=16,r&&(this.particleEmitterType.particlePositionGenerator(a,null,n),i.push(n.x),i.push(n.y),i.push(n.z),this._platform.alignDataInBuffer&&i.push(0),o+=4),this._colorGradientsTexture||(i.push(0),i.push(0),i.push(0),i.push(0),o+=4),this.isBillboardBased||(i.push(0),i.push(0),i.push(0),this._platform.alignDataInBuffer&&i.push(0),o+=4),this.noiseTexture&&(i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),this._platform.alignDataInBuffer&&i.push(0),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),this._platform.alignDataInBuffer&&i.push(0),o+=8),i.push(0),o+=1,this._angularSpeedGradientsTexture||(i.push(0),o+=1),this._isAnimationSheetEnabled&&(i.push(0),o+=1,this.spriteRandomStartCell&&(i.push(0),o+=1)),this._platform.alignDataInBuffer){var s=3-(o+3&3);for(o+=s;s-- >0;)i.push(0)}var l=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),c=this._platform.createParticleBuffer(i),u=this._platform.createParticleBuffer(i);this._buffer0=new Dr(t,c,!1,this._attributesStrideSize),this._buffer1=new Dr(t,u,!1,this._attributesStrideSize),this._spriteBuffer=new Dr(t,l,!1,4),this._renderVertexBuffers=[],this._createVertexBuffers(this._buffer0,this._buffer1,this._spriteBuffer),this._createVertexBuffers(this._buffer1,this._buffer0,this._spriteBuffer),this._sourceBuffer=this._buffer0,this._targetBuffer=this._buffer1}},t.prototype._recreateUpdateEffect=function(){this._createColorGradientTexture(),this._createSizeGradientTexture(),this._createAngularSpeedGradientTexture(),this._createVelocityGradientTexture(),this._createLimitVelocityGradientTexture(),this._createDragGradientTexture();var e=this.particleEmitterType?this.particleEmitterType.getEffectDefines():"";return this._isBillboardBased&&(e+="\n#define BILLBOARD"),this._colorGradientsTexture&&(e+="\n#define COLORGRADIENTS"),this._sizeGradientsTexture&&(e+="\n#define SIZEGRADIENTS"),this._angularSpeedGradientsTexture&&(e+="\n#define ANGULARSPEEDGRADIENTS"),this._velocityGradientsTexture&&(e+="\n#define VELOCITYGRADIENTS"),this._limitVelocityGradientsTexture&&(e+="\n#define LIMITVELOCITYGRADIENTS"),this._dragGradientsTexture&&(e+="\n#define DRAGGRADIENTS"),this.isAnimationSheetEnabled&&(e+="\n#define ANIMATESHEET",this.spriteRandomStartCell&&(e+="\n#define ANIMATESHEETRANDOMSTART")),this.noiseTexture&&(e+="\n#define NOISE"),this.isLocal&&(e+="\n#define LOCAL"),this._platform.isUpdateBufferCreated()&&this._cachedUpdateDefines===e||(this._cachedUpdateDefines=e,this._updateBuffer=this._platform.createUpdateBuffer(e)),this._platform.isUpdateBufferReady()},t.prototype._getWrapper=function(e){var t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;var i=[];this.fillDefines(i,e);var r=this._drawWrappers[e];r||((r=new ho(this._engine)).drawContext&&(r.drawContext.useInstancing=!0),this._drawWrappers[e]=r);var n=i.join("\n");if(r.defines!==n){var o=[],a=[],s=[];this.fillUniformsAttributesAndSamplerNames(a,o,s),r.setEffect(this._engine.createEffect("gpuRenderParticles",o,a,s,n),n)}return r},t._GetAttributeNamesOrOptions=function(e,t,i,r){void 0===e&&(e=!1),void 0===t&&(t=!1),void 0===i&&(i=!1),void 0===r&&(r=!1);var n=[Nr.PositionKind,"age","life","size","angle"];return e||n.push(Nr.ColorKind),t&&n.push("cellIndex"),i||n.push("initialDirection"),r&&n.push("direction"),n.push("offset",Nr.UVKind),n},t._GetEffectCreationOptions=function(e,t,i){void 0===e&&(e=!1),void 0===t&&(t=!1),void 0===i&&(i=!1);var r=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return Go(r),e&&r.push("sheetInfos"),t&&r.push("logarithmicDepthConstant"),i&&(r.push("vFogInfos"),r.push("vFogColor")),r},t.prototype.fillDefines=function(e,t){if(void 0===t&&(t=0),this._scene&&(zo(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&this._scene.fogMode!==pn.FOGMODE_NONE&&e.push("#define FOG")),t===aA.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this.isLocal&&e.push("#define LOCAL"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case aA.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case aA.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case aA.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._colorGradientsTexture&&e.push("#define COLORGRADIENTS"),this.isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(""+this._imageProcessingConfigurationDefines.toString()))},t.prototype.fillUniformsAttributesAndSamplerNames=function(e,i,r){i.push.apply(i,t._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===aA.BILLBOARDMODE_STRETCHED)),e.push.apply(e,t._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),r.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(pr.PrepareUniforms(e,this._imageProcessingConfigurationDefines),pr.PrepareSamplers(r,this._imageProcessingConfigurationDefines))},t.prototype.animate=function(e){var t;void 0===e&&(e=!1),this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:(null===(t=this._scene)||void 0===t?void 0:t.getAnimationRatio())||1),this._actualFrame+=this._timeDelta,this._stopped||this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop(),this.updateInAnimate&&this._update()},t.prototype._createFactorGradientTexture=function(e,t){var i=this[t];if(e&&e.length&&!i){for(var r=new Float32Array(this._rawTextureWidth),n=function(t){var i=t/o._rawTextureWidth;Kx.GetCurrentGradient(i,e,(function(e,i,n){r[t]=j.Lerp(e.factor1,i.factor1,n)}))},o=this,a=0;a<this._rawTextureWidth;a++)n(a);this[t]=is.CreateRTexture(r,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,u.TEXTURE_NEAREST_SAMPLINGMODE),this[t].name=t.substring(1)}},t.prototype._createSizeGradientTexture=function(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")},t.prototype._createAngularSpeedGradientTexture=function(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")},t.prototype._createVelocityGradientTexture=function(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")},t.prototype._createLimitVelocityGradientTexture=function(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")},t.prototype._createDragGradientTexture=function(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")},t.prototype._createColorGradientTexture=function(){if(this._colorGradients&&this._colorGradients.length&&!this._colorGradientsTexture){for(var e=new Uint8Array(4*this._rawTextureWidth),t=$.Color4[0],i=function(i){var n=i/r._rawTextureWidth;Kx.GetCurrentGradient(n,r._colorGradients,(function(r,n,o){J.LerpToRef(r.color1,n.color1,o,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255*t.a}))},r=this,n=0;n<this._rawTextureWidth;n++)i(n);this._colorGradientsTexture=is.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,u.TEXTURE_NEAREST_SAMPLINGMODE),this._colorGradientsTexture.name="colorGradients"}},t.prototype._render=function(e,t){var i,r,n,o,a,s=this._getWrapper(e),l=s.effect;this._engine.enableEffect(s);var c=(null===(i=this._scene)||void 0===i?void 0:i.getViewMatrix())||z.IdentityReadOnly;if(l.setMatrix("view",c),l.setMatrix("projection",null!==(r=this.defaultProjectionMatrix)&&void 0!==r?r:this._scene.getProjectionMatrix()),l.setTexture("diffuseSampler",this.particleTexture),l.setVector2("translationPivot",this.translationPivot),l.setVector3("worldOffset",this.worldOffset),this.isLocal&&l.setMatrix("emitterWM",t),this._colorGradientsTexture?l.setTexture("colorGradientSampler",this._colorGradientsTexture):l.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){var h=this.particleTexture.getBaseSize();l.setFloat3("sheetInfos",this.spriteCellWidth/h.width,this.spriteCellHeight/h.height,h.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){var d=this._scene.activeCamera;l.setVector3("eyePosition",d.globalPosition)}var p=l.defines;if(this._scene&&(Ho(l,this,this._scene),this.applyFog&&Qo(this._scene,void 0,l)),p.indexOf("#define BILLBOARDMODE_ALL")>=0){var f=c.clone();f.invert(),l.setMatrix("invView",f)}switch(this.useLogarithmicDepth&&this._scene&&Ko(p,l,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(l),e){case aA.BLENDMODE_ADD:this._engine.setAlphaMode(u.ALPHA_ADD);break;case aA.BLENDMODE_ONEONE:this._engine.setAlphaMode(u.ALPHA_ONEONE);break;case aA.BLENDMODE_STANDARD:this._engine.setAlphaMode(u.ALPHA_COMBINE);break;case aA.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(u.ALPHA_MULTIPLY)}return this._platform.bindDrawBuffers(this._targetIndex,l,(null===(n=this._scene)||void 0===n?void 0:n.forceWireframe)?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(l),(null===(o=this._scene)||void 0===o?void 0:o.forceWireframe)?this._engine.drawElementsType(u.MATERIAL_LineStripDrawMode,0,10,this._currentActiveCount):this._engine.drawArraysType(u.MATERIAL_TriangleStripDrawMode,0,4,this._currentActiveCount),this._engine.setAlphaMode(u.ALPHA_DISABLE),(null===(a=this._scene)||void 0===a?void 0:a.forceWireframe)&&this._engine.unbindInstanceAttributes(),this._currentActiveCount},t.prototype._update=function(e){if(this.emitter&&this._targetBuffer&&this._recreateUpdateEffect()&&!this._rebuildingAfterContextLost){if(!e)if(this.emitter.position)e=this.emitter.getWorldMatrix();else{var t=this.emitter;e=H.Matrix[0],z.TranslationToRef(t.x,t.y,t.z,e)}this._platform.preUpdateParticleBuffer(),this._updateBuffer.setFloat("currentCount",this._currentActiveCount),this._updateBuffer.setFloat("timeDelta",this._timeDelta),this._updateBuffer.setFloat("stopFactor",this._stopped?0:1),this._updateBuffer.setInt("randomTextureSize",this._randomTextureSize),this._updateBuffer.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateBuffer.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateBuffer.setDirectColor4("color1",this.color1),this._updateBuffer.setDirectColor4("color2",this.color2)),this._updateBuffer.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateBuffer.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateBuffer.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateBuffer.setVector3("gravity",this.gravity),this._limitVelocityGradientsTexture&&this._updateBuffer.setFloat("limitVelocityDamping",this.limitVelocityDamping),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateBuffer),this._isAnimationSheetEnabled&&this._updateBuffer.setFloat4("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed,this.spriteCellLoop?1:0),this.noiseTexture&&this._updateBuffer.setVector3("noiseStrength",this.noiseStrength),this.isLocal||this._updateBuffer.setMatrix("emitterWM",e),this._platform.updateParticleBuffer(this._targetIndex,this._targetBuffer,this._currentActiveCount),this._targetIndex++,2===this._targetIndex&&(this._targetIndex=0);var i=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=i}},t.prototype.render=function(e,t){if(void 0===e&&(e=!1),void 0===t&&(t=!1),!this._started)return 0;if(!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(var i=0;i<this.preWarmCycles;i++)this.animate(!0),this.render(!0,!0);this._preWarmDone=!0}if(this._currentRenderId===this._scene.getRenderId()&&(!this._scene.activeCamera||this._scene.activeCamera&&this._currentRenderingCameraUniqueId===this._scene.activeCamera.uniqueId))return 0;this._currentRenderId=this._scene.getRenderId(),this._scene.activeCamera&&(this._currentRenderingCameraUniqueId=this._scene.activeCamera.uniqueId)}if(this._initialize(),this._accumulatedCount+=this.emitRate*this._timeDelta,this._accumulatedCount>1){var r=0|this._accumulatedCount;this._accumulatedCount-=r,this._currentActiveCount+=r}if(this._currentActiveCount=Math.min(this._maxActiveParticleCount,this._currentActiveCount),!this._currentActiveCount)return 0;var n;if(this.emitter.position)n=this.emitter.getWorldMatrix();else{var o=this.emitter;n=H.Matrix[0],z.TranslationToRef(o.x,o.y,o.z,n)}var a=this._engine;this.updateInAnimate||this._update(n);var s=0;return e||t||(a.setState(!1),this.forceDepthWrite&&a.setDepthWrite(!0),s=this.blendMode===aA.BLENDMODE_MULTIPLYADD?this._render(aA.BLENDMODE_MULTIPLY,n)+this._render(aA.BLENDMODE_ADD,n):this._render(this.blendMode,n),this._engine.setAlphaMode(u.ALPHA_DISABLE)),s},t.prototype.rebuild=function(){var e=this,t=function(){e._recreateUpdateEffect()&&e._platform.isUpdateBufferReady()?(e._initialize(!0),e._rebuildingAfterContextLost=!1):setTimeout(t,10)};this._createIndexBuffer(),this._cachedUpdateDefines="",this._platform.contextLost(),this._rebuildingAfterContextLost=!0,t()},t.prototype._releaseBuffers=function(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._platform.releaseBuffers()},t.prototype.dispose=function(e){for(var t in void 0===e&&(e=!0),this._drawWrappers)this._drawWrappers[t].dispose();if(this._drawWrappers={},this._scene){var i=this._scene.particleSystems.indexOf(this);i>-1&&this._scene.particleSystems.splice(i,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(var r=0;r<this._renderVertexBuffers.length;++r){var n=this._renderVertexBuffers[r];for(var o in n)n[o].dispose()}this._renderVertexBuffers=[],this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null),this._sizeGradientsTexture&&(this._sizeGradientsTexture.dispose(),this._sizeGradientsTexture=null),this._angularSpeedGradientsTexture&&(this._angularSpeedGradientsTexture.dispose(),this._angularSpeedGradientsTexture=null),this._velocityGradientsTexture&&(this._velocityGradientsTexture.dispose(),this._velocityGradientsTexture=null),this._limitVelocityGradientsTexture&&(this._limitVelocityGradientsTexture.dispose(),this._limitVelocityGradientsTexture=null),this._dragGradientsTexture&&(this._dragGradientsTexture.dispose(),this._dragGradientsTexture=null),this._randomTexture&&(this._randomTexture.dispose(),this._randomTexture=null),this._randomTexture2&&(this._randomTexture2.dispose(),this._randomTexture2=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this.onStoppedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},t.prototype.clone=function(e,i,r){void 0===r&&(r=!1);var n=g({},this._customWrappers),o=null,a=this._engine;if(a.createEffectForParticles&&null!=this.customShader){var s=(o=this.customShader).shaderOptions.defines.length>0?o.shaderOptions.defines.join("\n"):"";n[0]=a.createEffectForParticles(o.shaderPath.fragmentElement,o.shaderOptions.uniforms,o.shaderOptions.samplers,s,void 0,void 0,void 0,this)}var l=this.serialize(r),c=t.Parse(l,this._scene||this._engine,this._rootUrl);return c.name=e,c.customShader=o,c._customWrappers=n,void 0===i&&(i=this.emitter),this.noiseTexture&&(c.noiseTexture=this.noiseTexture.clone()),c.emitter=i,c},t.prototype.serialize=function(e){void 0===e&&(e=!1);var t={};return aA._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t},t.Parse=function(e,i,r,n,o){void 0===n&&(n=!1);var a,s=e.name;a=i instanceof Mi?i:i.getEngine();var l=new t(s,{capacity:o||e.capacity,randomTextureSize:e.randomTextureSize},i,null,e.isAnimationSheetEnabled);if(l._rootUrl=r,e.customShader&&a.createEffectForParticles){var c=e.customShader,u=c.shaderOptions.defines.length>0?c.shaderOptions.defines.join("\n"):"",h=a.createEffectForParticles(c.shaderPath.fragmentElement,c.shaderOptions.uniforms,c.shaderOptions.samplers,u,void 0,void 0,void 0,l);l.setCustomEffect(h,0),l.customShader=c}return e.id&&(l.id=e.id),e.activeParticleCount&&(l.activeParticleCount=e.activeParticleCount),aA._Parse(e,l,i,r),e.preventAutoStart&&(l.preventAutoStart=e.preventAutoStart),n||l.preventAutoStart||l.start(),l},t}(vl),lA=function(){function e(){this._emitterNodeIsOwned=!0,this.systems=[]}return Object.defineProperty(e.prototype,"emitterNode",{get:function(){return this._emitterNode},set:function(e){this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1);for(var t=0,i=this.systems;t<i.length;t++)i[t].emitter=e;this._emitterNode=e},enumerable:!1,configurable:!0}),e.prototype.setEmitterAsSphere=function(e,t,i){this._emitterNodeIsOwned&&this._emitterNode&&this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!0,this._emitterCreationOptions={kind:"Sphere",options:e,renderingGroupId:t};var r=Gh("emitterSphere",{diameter:e.diameter,segments:e.segments},i);r.renderingGroupId=t;var n=new Uu("emitterSphereMaterial",i);n.emissiveColor=e.color,r.material=n;for(var o=0,a=this.systems;o<a.length;o++)a[o].emitter=r;this._emitterNode=r},e.prototype.start=function(e){for(var t=0,i=this.systems;t<i.length;t++){var r=i[t];e&&(r.emitter=e),r.start()}},e.prototype.dispose=function(){for(var e=0,t=this.systems;e<t.length;e++)t[e].dispose();this.systems.length=0,this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)},e.prototype.serialize=function(e){void 0===e&&(e=!1);for(var t={systems:[]},i=0,r=this.systems;i<r.length;i++){var n=r[i];t.systems.push(n.serialize(e))}return this._emitterNode&&(t.emitter=this._emitterCreationOptions),t},e.Parse=function(t,i,r,n){void 0===r&&(r=!1);var o=new e,a=this.BaseAssetsUrl+"/textures/";i=i||M.LastCreatedScene;for(var s=0,l=t.systems;s<l.length;s++){var c=l[s];o.systems.push(r?sA.Parse(c,i,a,!0,n):aA.Parse(c,i,a,!0,n))}if(t.emitter){var u=t.emitter.options;"Sphere"===t.emitter.kind&&o.setEmitterAsSphere({diameter:u.diameter,segments:u.segments,color:Z.FromArray(u.color)},t.emitter.renderingGroupId,i)}return o},e.BaseAssetsUrl="https://assets.babylonjs.com/particles",e}(),cA=function(){function e(){}return e.CreateDefault=function(e,t,i,r){var n;return void 0===t&&(t=500),void 0===r&&(r=!1),(n=r?new sA("default system",{capacity:t},i):new aA("default system",t,i)).emitter=e,n.particleTexture=new Ja("https://assets.babylonjs.com/textures/flare.png",n.getScene()),n.createConeEmitter(.1,Math.PI/4),n.color1=new J(1,1,1,1),n.color2=new J(1,1,1,1),n.colorDead=new J(1,1,1,0),n.minSize=.1,n.maxSize=.1,n.minEmitPower=2,n.maxEmitPower=2,n.updateSpeed=1/60,n.emitRate=30,n},e.CreateAsync=function(t,i,r,n){void 0===r&&(r=!1),i||(i=M.LastCreatedScene);var o={};return i.addPendingData(o),new Promise((function(a,s){if(r&&!sA.IsSupported)return i.removePendingData(o),s("Particle system with GPU is not supported.");rr.LoadFile("".concat(e.BaseAssetsUrl,"/systems/").concat(t,".json"),(function(e){i.removePendingData(o);var t=JSON.parse(e.toString());return a(lA.Parse(t,i,r,n))}),void 0,void 0,void 0,(function(){return i.removePendingData(o),s("An error occurred with the creation of your particle system. Check if your type '".concat(t,"' exists."))}))}))},e.ExportSet=function(e){for(var t=new lA,i=0,r=e;i<r.length;i++){var n=r[i];t.systems.push(n)}return t},e.ParseFromFileAsync=function(e,t,i,r,n,o){return void 0===r&&(r=!1),void 0===n&&(n=""),new Promise((function(a,s){var l=new Je;l.addEventListener("readystatechange",(function(){if(4==l.readyState)if(200==l.status){var t=JSON.parse(l.responseText),c=void 0;c=r?sA.Parse(t,i,n,!1,o):aA.Parse(t,i,n,!1,o),e&&(c.name=e),a(c)}else s("Unable to load the particle system")})),l.open("GET",t),l.send()}))},e.ParseFromSnippetAsync=function(e,t,i,r,n){var o=this;if(void 0===i&&(i=!1),void 0===r&&(r=""),"_BLANK"===e){var a=this.CreateDefault(null);return a.start(),Promise.resolve(a)}return new Promise((function(a,s){var l=new Je;l.addEventListener("readystatechange",(function(){if(4==l.readyState)if(200==l.status){var o=JSON.parse(JSON.parse(l.responseText).jsonPayload),c=JSON.parse(o.particleSystem),u=void 0;(u=i?sA.Parse(c,t,r,!1,n):aA.Parse(c,t,r,!1,n)).snippetId=e,a(u)}else s("Unable to load the snippet "+e)})),l.open("GET",o.SnippetUrl+"/"+e.replace(/#/g,"/")),l.send()}))},e.BaseAssetsUrl=lA.BaseAssetsUrl,e.SnippetUrl=u.SnippetUrl,e.CreateFromSnippetAsync=e.ParseFromSnippetAsync,e}();c.AddParser(Vr.NAME_PARTICLESYSTEM,(function(e,t,i,r){var n=c.GetIndividualParser(Vr.NAME_PARTICLESYSTEM);if(n&&void 0!==e.particleSystems&&null!==e.particleSystems)for(var o=0,a=e.particleSystems.length;o<a;o++){var s=e.particleSystems[o];i.particleSystems.push(n(s,t,r))}})),c.AddIndividualParser(Vr.NAME_PARTICLESYSTEM,(function(e,t,i){return e.activeParticleCount?sA.Parse(e,t,i):aA.Parse(e,t,i)})),Mi.prototype.createEffectForParticles=function(e,t,i,r,n,o,a,s){var l;void 0===t&&(t=[]),void 0===i&&(i=[]),void 0===r&&(r="");var c=[],u=[],h=[];return s?s.fillUniformsAttributesAndSamplerNames(u,c,h):(c=aA._GetAttributeNamesOrOptions(),u=aA._GetEffectCreationOptions()),-1===r.indexOf(" BILLBOARD")&&(r+="\n#define BILLBOARD\n"),(null==s?void 0:s.isAnimationSheetEnabled)&&-1===r.indexOf(" ANIMATESHEET")&&(r+="\n#define ANIMATESHEET\n"),-1===i.indexOf("diffuseSampler")&&i.push("diffuseSampler"),this.createEffect({vertex:null!==(l=null==s?void 0:s.vertexShaderName)&&void 0!==l?l:"particles",fragmentElement:e},c,u.concat(t),h.concat(i),r,n,o,a)},Fa.prototype.getEmittedParticleSystems=function(){for(var e=[],t=0;t<this.getScene().particleSystems.length;t++){var i=this.getScene().particleSystems[t];i.emitter===this&&e.push(i)}return e},Fa.prototype.getHierarchyEmittedParticleSystems=function(){var e=[],t=this.getDescendants();t.push(this);for(var i=0;i<this.getScene().particleSystems.length;i++){var r=this.getScene().particleSystems[i],n=r.emitter;n.position&&-1!==t.indexOf(n)&&e.push(r)}return e};var uA,hA=function(){function e(e,t,i,r,n,o,a,s,l,c){void 0===l&&(l=null),void 0===c&&(c=null),this.idx=0,this.id=0,this.color=new J(1,1,1,1),this.position=V.Zero(),this.rotation=V.Zero(),this.scaling=V.One(),this.uvs=new k(0,0,1,1),this.velocity=V.Zero(),this.pivot=V.Zero(),this.translateFromPivot=!1,this.alive=!0,this.isVisible=!0,this._pos=0,this._ind=0,this.shapeId=0,this.idxInShape=0,this._stillInvisible=!1,this._rotationMatrix=[1,0,0,0,1,0,0,0,1],this.parentId=null,this.materialIndex=null,this.props=null,this.cullingStrategy=Uo.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this._globalPosition=V.Zero(),this.idx=e,this.id=t,this._pos=i,this._ind=r,this._model=n,this.shapeId=o,this.idxInShape=a,this._sps=s,l&&(this._modelBoundingInfo=l,this._boundingInfo=new so(l.minimum,l.maximum)),null!==c&&(this.materialIndex=c)}return e.prototype.getBoundingInfo=function(){return this._boundingInfo},Object.defineProperty(e.prototype,"hasBoundingInfo",{get:function(){return null!==this._boundingInfo},enumerable:!1,configurable:!0}),e.prototype.copyToRef=function(e){return e.position.copyFrom(this.position),e.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(e.rotationQuaternion?e.rotationQuaternion.copyFrom(this.rotationQuaternion):e.rotationQuaternion=this.rotationQuaternion.clone()),e.scaling.copyFrom(this.scaling),this.color&&(e.color?e.color.copyFrom(this.color):e.color=this.color.clone()),e.uvs.copyFrom(this.uvs),e.velocity.copyFrom(this.velocity),e.pivot.copyFrom(this.pivot),e.translateFromPivot=this.translateFromPivot,e.alive=this.alive,e.isVisible=this.isVisible,e.parentId=this.parentId,e.cullingStrategy=this.cullingStrategy,null!==this.materialIndex&&(e.materialIndex=this.materialIndex),this},Object.defineProperty(e.prototype,"scale",{get:function(){return this.scaling},set:function(e){this.scaling=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"quaternion",{get:function(){return this.rotationQuaternion},set:function(e){this.rotationQuaternion=e},enumerable:!1,configurable:!0}),e.prototype.intersectsMesh=function(e){return!(!this._boundingInfo||!e.hasBoundingInfo)&&(this._sps._bSphereOnly?io.Intersects(this._boundingInfo.boundingSphere,e.getBoundingInfo().boundingSphere):this._boundingInfo.intersects(e.getBoundingInfo(),!1))},e.prototype.isInFrustum=function(e){return null!==this._boundingInfo&&this._boundingInfo.isInFrustum(e,this.cullingStrategy)},e.prototype.getRotationMatrix=function(e){var t;if(this.rotationQuaternion)t=this.rotationQuaternion;else{t=H.Quaternion[0];var i=this.rotation;G.RotationYawPitchRollToRef(i.y,i.x,i.z,t)}t.toRotationMatrix(e)},e}(),dA=function(){function e(e,t,i,r,n,o,a,s,l){this._indicesLength=0,this.shapeId=e,this._shape=t,this._indices=i,this._indicesLength=i.length,this._shapeUV=o,this._shapeColors=n,this._normals=r,this._positionFunction=a,this._vertexFunction=s,this._material=l}return Object.defineProperty(e.prototype,"shapeID",{get:function(){return this.shapeId},set:function(e){this.shapeId=e},enumerable:!1,configurable:!0}),e}(),pA=function(e,t,i,r){this.idx=0,this.ind=0,this.indicesLength=0,this.sqDistance=0,this.materialIndex=0,this.idx=e,this.ind=t,this.indicesLength=i,this.materialIndex=r},fA=function(){function e(){this.position=V.Zero(),this.color=new J(1,1,1,1),this.uv=U.Zero()}return Object.defineProperty(e.prototype,"x",{get:function(){return this.position.x},set:function(e){this.position.x=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"y",{get:function(){return this.position.y},set:function(e){this.position.y=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"z",{get:function(){return this.position.z},set:function(e){this.position.z=e},enumerable:!1,configurable:!0}),e}(),_A=function(){function e(e,t,i){this.particles=new Array,this.nbParticles=0,this.billboard=!1,this.recomputeNormals=!1,this.counter=0,this.vars={},this._bSphereOnly=!1,this._bSphereRadiusFactor=1,this._positions=new Array,this._indices=new Array,this._normals=new Array,this._colors=new Array,this._uvs=new Array,this._index=0,this._updatable=!0,this._pickable=!1,this._isVisibilityBoxLocked=!1,this._alwaysVisible=!1,this._depthSort=!1,this._expandable=!1,this._shapeCounter=0,this._copy=new hA(0,0,0,0,null,0,0,this),this._color=new J(0,0,0,0),this._computeParticleColor=!0,this._computeParticleTexture=!0,this._computeParticleRotation=!0,this._computeParticleVertex=!1,this._computeBoundingBox=!1,this._autoFixFaceOrientation=!1,this._depthSortParticles=!0,this._mustUnrotateFixedNormals=!1,this._particlesIntersect=!1,this._needs32Bits=!1,this._isNotBuilt=!0,this._lastParticleId=0,this._idxOfId=[],this._multimaterialEnabled=!1,this._useModelMaterial=!1,this._depthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},this._materialSortFunction=function(e,t){return e.materialIndex-t.materialIndex},this._autoUpdateSubMeshes=!1,this._recomputeInvisibles=!1,this.name=e,this._scene=t||M.LastCreatedScene,this._camera=t.activeCamera,this._pickable=!!i&&i.isPickable,this._depthSort=!!i&&i.enableDepthSort,this._multimaterialEnabled=!!i&&i.enableMultiMaterial,this._useModelMaterial=!!i&&i.useModelMaterial,this._multimaterialEnabled=!!this._useModelMaterial||this._multimaterialEnabled,this._expandable=!!i&&i.expandable,this._particlesIntersect=!!i&&i.particleIntersection,this._bSphereOnly=!!i&&i.boundingSphereOnly,this._bSphereRadiusFactor=i&&i.bSphereRadiusFactor?i.bSphereRadiusFactor:1,this._computeBoundingBox=!!(null==i?void 0:i.computeBoundingBox)&&i.computeBoundingBox,this._autoFixFaceOrientation=!!(null==i?void 0:i.autoFixFaceOrientation)&&i.autoFixFaceOrientation,i&&void 0!==i.updatable?this._updatable=i.updatable:this._updatable=!0,this._pickable&&(this.pickedBySubMesh=[[]],this.pickedParticles=this.pickedBySubMesh[0]),(this._depthSort||this._multimaterialEnabled)&&(this.depthSortedParticles=[]),this._multimaterialEnabled&&(this._multimaterial=new Ra(this.name+"MultiMaterial",this._scene),this._materials=[],this._materialIndexesById={}),this._tmpVertex=new fA}return e.prototype.buildMesh=function(){if(!this._isNotBuilt&&this.mesh)return this.mesh;if(0===this.nbParticles&&!this.mesh){var e=qh("",{radius:1,tessellation:3},this._scene);this.addShape(e,1),e.dispose()}if(this._indices32=this._needs32Bits?new Uint32Array(this._indices):new Uint16Array(this._indices),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors),!this.mesh){var t=new Fa(this.name,this._scene);this.mesh=t}!this._updatable&&this._multimaterialEnabled&&this._sortParticlesByMaterial(),this.recomputeNormals&&_o.ComputeNormals(this._positions32,this._indices32,this._normals),this._normals32=new Float32Array(this._normals),this._fixedNormal32=new Float32Array(this._normals),this._mustUnrotateFixedNormals&&this._unrotateFixedNormals();var i=new _o;if(i.indices=this._depthSort?this._indices:this._indices32,i.set(this._positions32,Nr.PositionKind),i.set(this._normals32,Nr.NormalKind),this._uvs32.length>0&&i.set(this._uvs32,Nr.UVKind),this._colors32.length>0&&i.set(this._colors32,Nr.ColorKind),i.applyToMesh(this.mesh,this._updatable),this.mesh.isPickable=this._pickable,this._pickable)for(var r=0,n=0;n<this.nbParticles;n++)for(var o=this.particles[n],a=o._model._indicesLength,s=0;s<a;s++)if(0==s%3){var l={idx:o.idx,faceId:r};this.pickedParticles[r]=l,r++}return this._multimaterialEnabled&&this.setMultiMaterial(this._materials),this._expandable||(this._depthSort||this._multimaterialEnabled||this._autoFixFaceOrientation||(this._indices=null),this._positions=null,this._normals=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0)),this._isNotBuilt=!1,this.recomputeNormals=!1,this._recomputeInvisibles=!0,this.mesh},e.prototype._getUVKind=function(e,t){var i,r;return-1===t&&((null===(i=e.material)||void 0===i?void 0:i.diffuseTexture)?t=e.material.diffuseTexture.coordinatesIndex:(null===(r=e.material)||void 0===r?void 0:r.albedoTexture)&&(t=e.material.albedoTexture.coordinatesIndex)),"uv"+(t?t+1:"")},e.prototype.digest=function(e,t){var i,r=t&&t.facetNb||1,n=t&&t.number||0,o=t&&t.delta||0,a=e.getVerticesData(Nr.PositionKind),s=e.getIndices(),l=e.getVerticesData(this._getUVKind(e,null!==(i=null==t?void 0:t.uvKind)&&void 0!==i?i:0)),c=e.getVerticesData(Nr.ColorKind),u=e.getVerticesData(Nr.NormalKind),h=t&&t.storage?t.storage:null,d=0,p=s.length/3;n?(n=n>p?p:n,r=Math.round(p/n),o=0):r=r>p?p:r;for(var f=[],_=[],m=[],g=[],v=[],y=V.Zero(),b=r;d<p;){d>p-(r=b+Math.floor((1+o)*Math.random()))&&(r=p-d),f.length=0,_.length=0,m.length=0,g.length=0,v.length=0;for(var T=0,E=3*d;E<3*(d+r);E++){m.push(T);var S=s[E],x=3*S;if(f.push(a[x],a[x+1],a[x+2]),_.push(u[x],u[x+1],u[x+2]),l){var A=2*S;g.push(l[A],l[A+1])}if(c){var C=4*S;v.push(c[C],c[C+1],c[C+2],c[C+3])}T++}var R=this.nbParticles,P=this._posToShape(f),I=this._uvsToShapeUV(g),M=m.slice(),O=v.slice(),D=_.slice();y.copyFromFloats(0,0,0);var N=void 0;for(N=0;N<P.length;N++)y.addInPlace(P[N]);y.scaleInPlace(1/P.length);var F=new V(1/0,1/0,1/0),L=new V(-1/0,-1/0,-1/0);for(N=0;N<P.length;N++)P[N].subtractInPlace(y),F.minimizeInPlaceFromFloats(P[N].x,P[N].y,P[N].z),L.maximizeInPlaceFromFloats(P[N].x,P[N].y,P[N].z);var w=void 0;this._particlesIntersect&&(w=new so(F,L));var B=null;this._useModelMaterial&&(B=e.material?e.material:this._setDefaultMaterial());var U=new dA(this._shapeCounter,P,M,D,O,I,null,null,B),k=this._positions.length,G=this._indices.length;this._meshBuilder(this._index,G,P,this._positions,M,this._indices,g,this._uvs,O,this._colors,D,this._normals,R,0,null,U),this._addParticle(R,this._lastParticleId,k,G,U,this._shapeCounter,0,w,h),this.particles[this.nbParticles].position.addInPlace(y),h||(this._index+=P.length,R++,this.nbParticles++,this._lastParticleId++),this._shapeCounter++,d+=r}return this._isNotBuilt=!0,this},e.prototype._unrotateFixedNormals=function(){for(var e=0,t=0,i=H.Vector3[0],r=H.Quaternion[0],n=H.Matrix[0],o=0;o<this.particles.length;o++){var a=this.particles[o],s=a._model._shape;if(a.rotationQuaternion)a.rotationQuaternion.conjugateToRef(r);else{var l=a.rotation;G.RotationYawPitchRollToRef(l.y,l.x,l.z,r),r.conjugateInPlace()}r.toRotationMatrix(n);for(var c=0;c<s.length;c++)t=e+3*c,V.TransformNormalFromFloatsToRef(this._normals32[t],this._normals32[t+1],this._normals32[t+2],n,i),i.toArray(this._fixedNormal32,t);e=t+3}},e.prototype._resetCopy=function(){var e=this._copy;e.position.setAll(0),e.rotation.setAll(0),e.rotationQuaternion=null,e.scaling.setAll(1),e.uvs.copyFromFloats(0,0,1,1),e.color=null,e.translateFromPivot=!1,e.shapeId=0,e.materialIndex=null},e.prototype._meshBuilder=function(e,t,i,r,n,o,a,s,l,c,u,h,d,p,f,_){var m,g=0,v=0,y=0;this._resetCopy();var b=this._copy,T=!(!f||!f.storage);if(b.idx=d,b.idxInShape=p,b.shapeId=_.shapeId,this._useModelMaterial){var E=_._material.uniqueId,S=this._materialIndexesById;Object.prototype.hasOwnProperty.call(S,E)||(S[E]=this._materials.length,this._materials.push(_._material));var x=S[E];b.materialIndex=x}if(f&&f.positionFunction&&(f.positionFunction(b,d,p),this._mustUnrotateFixedNormals=!0),T)return b;var A=H.Matrix[0],C=this._tmpVertex,R=C.position,P=C.color,I=C.uv,M=H.Vector3[1],O=H.Vector3[2],D=H.Vector3[3];z.IdentityToRef(A),b.getRotationMatrix(A),b.pivot.multiplyToRef(b.scaling,D),b.translateFromPivot?O.setAll(0):O.copyFrom(D);var N=f&&f.vertexFunction;for(m=0;m<i.length;m++){if(R.copyFrom(i[m]),b.color&&P.copyFrom(b.color),a&&I.copyFromFloats(a[g],a[g+1]),N&&f.vertexFunction(b,C,m),R.multiplyInPlace(b.scaling).subtractInPlace(D),V.TransformCoordinatesToRef(R,A,M),M.addInPlace(O).addInPlace(b.position),r.push(M.x,M.y,M.z),a){var F=b.uvs;s.push((F.z-F.x)*I.x+F.x,(F.w-F.y)*I.y+F.y),g+=2}if(b.color)this._color.copyFrom(P);else{var L=this._color;l&&void 0!==l[v]?(L.r=l[v],L.g=l[v+1],L.b=l[v+2],L.a=l[v+3]):(L.r=1,L.g=1,L.b=1,L.a=1)}c.push(this._color.r,this._color.g,this._color.b,this._color.a),v+=4,!this.recomputeNormals&&u&&(V.TransformNormalFromFloatsToRef(u[y],u[y+1],u[y+2],A,R),h.push(R.x,R.y,R.z),y+=3)}for(m=0;m<n.length;m++){var w=e+n[m];o.push(w),w>65535&&(this._needs32Bits=!0)}if(this._depthSort||this._multimaterialEnabled){var B=null!==b.materialIndex?b.materialIndex:0;this.depthSortedParticles.push(new pA(d,t,n.length,B))}return b},e.prototype._posToShape=function(e){for(var t=[],i=0;i<e.length;i+=3)t.push(V.FromArray(e,i));return t},e.prototype._uvsToShapeUV=function(e){var t=[];if(e)for(var i=0;i<e.length;i++)t.push(e[i]);return t},e.prototype._addParticle=function(e,t,i,r,n,o,a,s,l){void 0===s&&(s=null),void 0===l&&(l=null);var c=new hA(e,t,i,r,n,o,a,this,s);return(l||this.particles).push(c),c},e.prototype.addShape=function(e,t,i){var r=e.getVerticesData(Nr.PositionKind),n=e.getIndices(),o=e.getVerticesData(Nr.UVKind),a=e.getVerticesData(Nr.ColorKind),s=e.getVerticesData(Nr.NormalKind);this.recomputeNormals=!s;var l=Array.from(n),c=s?Array.from(s):[],u=a?Array.from(a):[],h=i&&i.storage?i.storage:null,d=null;this._particlesIntersect&&(d=e.getBoundingInfo());var p=this._posToShape(r),f=this._uvsToShapeUV(o),_=i?i.positionFunction:null,m=i?i.vertexFunction:null,g=null;this._useModelMaterial&&(g=e.material?e.material:this._setDefaultMaterial());for(var v=new dA(this._shapeCounter,p,l,c,u,f,_,m,g),y=0;y<t;y++)this._insertNewParticle(this.nbParticles,y,v,p,n,o,a,s,d,h,i);return this._shapeCounter++,this._isNotBuilt=!0,this._shapeCounter-1},e.prototype._rebuildParticle=function(e,t){void 0===t&&(t=!1),this._resetCopy();var i=this._copy;e._model._positionFunction&&e._model._positionFunction(i,e.idx,e.idxInShape);var r=H.Matrix[0],n=H.Vector3[0],o=H.Vector3[1],a=H.Vector3[2],s=H.Vector3[3];i.getRotationMatrix(r),e.pivot.multiplyToRef(e.scaling,s),i.translateFromPivot?a.copyFromFloats(0,0,0):a.copyFrom(s);for(var l=e._model._shape,c=0;c<l.length;c++)n.copyFrom(l[c]),e._model._vertexFunction&&e._model._vertexFunction(i,n,c),n.multiplyInPlace(i.scaling).subtractInPlace(s),V.TransformCoordinatesToRef(n,r,o),o.addInPlace(a).addInPlace(i.position).toArray(this._positions32,e._pos+3*c);t&&(e.position.setAll(0),e.rotation.setAll(0),e.rotationQuaternion=null,e.scaling.setAll(1),e.uvs.setAll(0),e.pivot.setAll(0),e.translateFromPivot=!1,e.parentId=null)},e.prototype.rebuildMesh=function(e){void 0===e&&(e=!1);for(var t=0;t<this.particles.length;t++)this._rebuildParticle(this.particles[t],e);return this.mesh.updateVerticesData(Nr.PositionKind,this._positions32,!1,!1),this},e.prototype.removeParticles=function(e,t){var i=t-e+1;if(!this._expandable||i<=0||i>=this.nbParticles||!this._updatable)return[];var r=this.particles,n=this.nbParticles;if(t<n-1)for(var o=t+1,a=r[o]._pos-r[e]._pos,s=r[o]._ind-r[e]._ind,l=o;l<n;l++){var c=r[l];c._pos-=a,c._ind-=s}var u=r.splice(e,i);this._positions.length=0,this._indices.length=0,this._colors.length=0,this._uvs.length=0,this._normals.length=0,this._index=0,this._idxOfId.length=0,(this._depthSort||this._multimaterialEnabled)&&(this.depthSortedParticles=[]);for(var h=0,d=r.length,p=0;p<d;p++){var f=r[p],_=f._model,m=_._shape,g=_._indices,v=_._normals,y=_._shapeColors,b=_._shapeUV;f.idx=p,this._idxOfId[f.id]=p,this._meshBuilder(this._index,h,m,this._positions,g,this._indices,b,this._uvs,y,this._colors,v,this._normals,f.idx,f.idxInShape,null,_),this._index+=m.length,h+=g.length}return this.nbParticles-=i,this._isNotBuilt=!0,u},e.prototype.insertParticlesFromArray=function(e){if(!this._expandable)return this;for(var t=0,i=e[0].shapeId,r=e.length,n=0;n<r;n++){var o=e[n],a=o._model,s=a._shape,l=a._indices,c=a._shapeUV,u=a._shapeColors,h=a._normals,d=!h;this.recomputeNormals=d||this.recomputeNormals;var p=o.getBoundingInfo(),f=this._insertNewParticle(this.nbParticles,t,a,s,l,c,u,h,p,null,null);o.copyToRef(f),t++,i!=o.shapeId&&(i=o.shapeId,t=0)}return this._isNotBuilt=!0,this},e.prototype._insertNewParticle=function(e,t,i,r,n,o,a,s,l,c,u){var h=this._positions.length,d=this._indices.length,p=this._meshBuilder(this._index,d,r,this._positions,n,this._indices,o,this._uvs,a,this._colors,s,this._normals,e,t,u,i),f=null;return this._updatable&&((f=this._addParticle(this.nbParticles,this._lastParticleId,h,d,i,this._shapeCounter,t,l,c)).position.copyFrom(p.position),f.rotation.copyFrom(p.rotation),p.rotationQuaternion&&(f.rotationQuaternion?f.rotationQuaternion.copyFrom(p.rotationQuaternion):f.rotationQuaternion=p.rotationQuaternion.clone()),p.color&&(f.color?f.color.copyFrom(p.color):f.color=p.color.clone()),f.scaling.copyFrom(p.scaling),f.uvs.copyFrom(p.uvs),null!==p.materialIndex&&(f.materialIndex=p.materialIndex),this.expandable&&(this._idxOfId[f.id]=f.idx)),c||(this._index+=r.length,this.nbParticles++,this._lastParticleId++),f},e.prototype.setParticles=function(e,t,i){if(void 0===e&&(e=0),void 0===t&&(t=this.nbParticles-1),void 0===i&&(i=!0),!this._updatable||this._isNotBuilt)return this;this.beforeUpdateParticles(e,t,i);var r=H.Matrix[0],n=H.Matrix[1],o=this.mesh,a=this._colors32,s=this._positions32,l=this._normals32,c=this._uvs32,u=this._indices32,h=this._indices,d=this._fixedNormal32,p=this._depthSort&&this._depthSortParticles,f=H.Vector3,_=f[5].copyFromFloats(1,0,0),m=f[6].copyFromFloats(0,1,0),g=f[7].copyFromFloats(0,0,1),v=f[8].setAll(Number.MAX_VALUE),y=f[9].setAll(-Number.MAX_VALUE),b=f[10].setAll(0),T=this._tmpVertex,E=T.position,S=T.color,x=T.uv;if((this.billboard||this._depthSort)&&(this.mesh.computeWorldMatrix(!0),this.mesh._worldMatrix.invertToRef(n)),this.billboard){var A=f[0];this._camera.getDirectionToRef(_n.Z,A),V.TransformNormalToRef(A,n,g),g.normalize();var C=this._camera.getViewMatrix(!0);V.TransformNormalFromFloatsToRef(C.m[1],C.m[5],C.m[9],n,m),V.CrossToRef(m,g,_),m.normalize(),_.normalize()}this._depthSort&&V.TransformCoordinatesToRef(this._camera.globalPosition,n,b),z.IdentityToRef(r);var R=0,P=0,I=0,M=0,O=0,D=0,N=0;if(this.mesh.isFacetDataEnabled&&(this._computeBoundingBox=!0),t=t>=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(0!=e||t!=this.nbParticles-1)){var F=this.mesh.getBoundingInfo();F&&(v.copyFrom(F.minimum),y.copyFrom(F.maximum))}var L=(P=this.particles[e]._pos)/3|0;M=4*L,D=2*L;for(var w=e;w<=t;w++){var B=this.particles[w];this.updateParticle(B);var U=B._model._shape,k=B._model._shapeUV,G=B._rotationMatrix,W=B.position,X=B.rotation,j=B.scaling,Y=B._globalPosition;if(p){var K=this.depthSortedParticles[w];K.idx=B.idx,K.ind=B._ind,K.indicesLength=B._model._indicesLength,K.sqDistance=V.DistanceSquared(B.position,b)}if(B.alive&&(!B._stillInvisible||B.isVisible||this._recomputeInvisibles)){if(B.isVisible){B._stillInvisible=!1;var Q=f[12];if(B.pivot.multiplyToRef(j,Q),this.billboard&&(X.x=0,X.y=0),(this._computeParticleRotation||this.billboard)&&B.getRotationMatrix(r),null!==B.parentId){var q=this.getParticleById(B.parentId);if(q){var Z=q._rotationMatrix,J=q._globalPosition,$=W.x*Z[1]+W.y*Z[4]+W.z*Z[7],ee=W.x*Z[0]+W.y*Z[3]+W.z*Z[6],te=W.x*Z[2]+W.y*Z[5]+W.z*Z[8];if(Y.x=J.x+ee,Y.y=J.y+$,Y.z=J.z+te,this._computeParticleRotation||this.billboard){var ie=r.m;G[0]=ie[0]*Z[0]+ie[1]*Z[3]+ie[2]*Z[6],G[1]=ie[0]*Z[1]+ie[1]*Z[4]+ie[2]*Z[7],G[2]=ie[0]*Z[2]+ie[1]*Z[5]+ie[2]*Z[8],G[3]=ie[4]*Z[0]+ie[5]*Z[3]+ie[6]*Z[6],G[4]=ie[4]*Z[1]+ie[5]*Z[4]+ie[6]*Z[7],G[5]=ie[4]*Z[2]+ie[5]*Z[5]+ie[6]*Z[8],G[6]=ie[8]*Z[0]+ie[9]*Z[3]+ie[10]*Z[6],G[7]=ie[8]*Z[1]+ie[9]*Z[4]+ie[10]*Z[7],G[8]=ie[8]*Z[2]+ie[9]*Z[5]+ie[10]*Z[8]}}else B.parentId=null}else Y.x=W.x,Y.y=W.y,Y.z=W.z,(this._computeParticleRotation||this.billboard)&&(ie=r.m,G[0]=ie[0],G[1]=ie[1],G[2]=ie[2],G[3]=ie[4],G[4]=ie[5],G[5]=ie[6],G[6]=ie[8],G[7]=ie[9],G[8]=ie[10]);var re=f[11];for(B.translateFromPivot?re.setAll(0):re.copyFrom(Q),N=0;N<U.length;N++){R=P+3*N,I=M+4*N,O=D+2*N;var ne=2*N,oe=ne+1;E.copyFrom(U[N]),this._computeParticleColor&&B.color&&S.copyFrom(B.color),this._computeParticleTexture&&x.copyFromFloats(k[ne],k[oe]),this._computeParticleVertex&&this.updateParticleVertex(B,T,N);var ae=E.x*j.x-Q.x,se=E.y*j.y-Q.y,le=E.z*j.z-Q.z;ee=ae*G[0]+se*G[3]+le*G[6],$=ae*G[1]+se*G[4]+le*G[7],te=ae*G[2]+se*G[5]+le*G[8],ee+=re.x,$+=re.y,te+=re.z;var ce=s[R]=Y.x+_.x*ee+m.x*$+g.x*te,ue=s[R+1]=Y.y+_.y*ee+m.y*$+g.y*te,he=s[R+2]=Y.z+_.z*ee+m.z*$+g.z*te;if(this._computeBoundingBox&&(v.minimizeInPlaceFromFloats(ce,ue,he),y.maximizeInPlaceFromFloats(ce,ue,he)),!this._computeParticleVertex){var de=d[R],pe=d[R+1],fe=d[R+2],_e=de*G[0]+pe*G[3]+fe*G[6],me=de*G[1]+pe*G[4]+fe*G[7],ge=de*G[2]+pe*G[5]+fe*G[8];l[R]=_.x*_e+m.x*me+g.x*ge,l[R+1]=_.y*_e+m.y*me+g.y*ge,l[R+2]=_.z*_e+m.z*me+g.z*ge}if(this._computeParticleColor&&B.color){var ve=this._colors32;ve[I]=S.r,ve[I+1]=S.g,ve[I+2]=S.b,ve[I+3]=S.a}if(this._computeParticleTexture){var ye=B.uvs;c[O]=x.x*(ye.z-ye.x)+ye.x,c[O+1]=x.y*(ye.w-ye.y)+ye.y}}}else for(B._stillInvisible=!0,N=0;N<U.length;N++){if(I=M+4*N,O=D+2*N,s[R=P+3*N]=s[R+1]=s[R+2]=0,l[R]=l[R+1]=l[R+2]=0,this._computeParticleColor&&B.color){var be=B.color;a[I]=be.r,a[I+1]=be.g,a[I+2]=be.b,a[I+3]=be.a}this._computeParticleTexture&&(ye=B.uvs,c[O]=k[2*N]*(ye.z-ye.x)+ye.x,c[O+1]=k[2*N+1]*(ye.w-ye.y)+ye.y)}if(this._particlesIntersect){var Te=B.getBoundingInfo(),Ee=Te.boundingBox,Se=Te.boundingSphere,xe=B._modelBoundingInfo;if(!this._bSphereOnly){var Ae=xe.boundingBox.vectors,Ce=f[1],Re=f[2];Ce.setAll(Number.MAX_VALUE),Re.setAll(-Number.MAX_VALUE);for(var Pe=0;Pe<8;Pe++){var Ie=Ae[Pe].x*j.x,Me=Ae[Pe].y*j.y,Oe=Ae[Pe].z*j.z,De=(ee=Ie*G[0]+Me*G[3]+Oe*G[6],$=Ie*G[1]+Me*G[4]+Oe*G[7],te=Ie*G[2]+Me*G[5]+Oe*G[8],W.x+_.x*ee+m.x*$+g.x*te),Ne=W.y+_.y*ee+m.y*$+g.y*te,Fe=W.z+_.z*ee+m.z*$+g.z*te;Ce.minimizeInPlaceFromFloats(De,Ne,Fe),Re.maximizeInPlaceFromFloats(De,Ne,Fe)}Ee.reConstruct(Ce,Re,o._worldMatrix)}var Le=xe.minimum.multiplyToRef(j,f[1]),we=xe.maximum.multiplyToRef(j,f[2]),Be=we.addToRef(Le,f[3]).scaleInPlace(.5).addInPlace(Y),Ue=we.subtractToRef(Le,f[4]).scaleInPlace(.5*this._bSphereRadiusFactor),Ve=Be.subtractToRef(Ue,f[1]),ke=Be.addToRef(Ue,f[2]);Se.reConstruct(Ve,ke,o._worldMatrix)}P=R+3,M=I+4,D=O+2}else P+=3*(N=U.length),M+=4*N,D+=2*N}if(i){this._computeParticleColor&&((He=o.getVertexBuffer(Nr.ColorKind))&&!o.isPickable?He.updateDirectly(a,0):o.updateVerticesData(Nr.ColorKind,a,!1,!1)),this._computeParticleTexture&&((He=o.getVertexBuffer(Nr.UVKind))&&!o.isPickable?He.updateDirectly(c,0):o.updateVerticesData(Nr.UVKind,c,!1,!1));var Ge=o.getVertexBuffer(Nr.PositionKind);if(Ge&&!o.isPickable?Ge.updateDirectly(s,0):o.updateVerticesData(Nr.PositionKind,s,!1,!1),!o.areNormalsFrozen||o.isFacetDataEnabled){if(this._computeParticleVertex||o.isFacetDataEnabled){var ze=o.isFacetDataEnabled?o.getFacetDataParameters():null;_o.ComputeNormals(s,u,l,ze);for(var We=0;We<l.length;We++)d[We]=l[We]}var He;o.areNormalsFrozen||((He=o.getVertexBuffer(Nr.NormalKind))&&!o.isPickable?He.updateDirectly(l,0):o.updateVerticesData(Nr.NormalKind,l,!1,!1))}if(p){var Xe=this.depthSortedParticles;Xe.sort(this._depthSortFunction);for(var je=Xe.length,Ye=0,Ke=0,Qe=0;Qe<je;Qe++){var qe=Xe[Qe],Ze=qe.indicesLength,Je=qe.ind;for(We=0;We<Ze;We++)if(u[Ye]=h[Je+We],Ye++,this._pickable&&0==We%3){var $e=this.pickedParticles[Ke];$e.idx=qe.idx,$e.faceId=Ke,Ke++}}}if(this._autoFixFaceOrientation)for(var et=0,tt=0;tt<this.particles.length;tt++){if((B=p?this.particles[this.depthSortedParticles[tt].idx]:this.particles[tt]).scale.x*B.scale.y*B.scale.z<0)for(var it=0;it<B._model._indicesLength;it+=3){var rt=h[B._ind+it];u[et+it]=h[B._ind+it+1],u[et+it+1]=rt}et+=B._model._indicesLength}(p||this._autoFixFaceOrientation)&&o.updateIndices(u)}return this._computeBoundingBox&&(o.hasBoundingInfo?o.getBoundingInfo().reConstruct(v,y,o._worldMatrix):o.buildBoundingInfo(v,y,o._worldMatrix)),this._autoUpdateSubMeshes&&this.computeSubMeshes(),this._recomputeInvisibles=!1,this.afterUpdateParticles(e,t,i),this},e.prototype.dispose=function(){this.mesh.dispose(),this.vars=null,this._positions=null,this._indices=null,this._normals=null,this._uvs=null,this._colors=null,this._indices32=null,this._positions32=null,this._normals32=null,this._fixedNormal32=null,this._uvs32=null,this._colors32=null,this.pickedParticles=null,this.pickedBySubMesh=null,this._materials=null,this._materialIndexes=null,this._indicesByMaterial=null,this._idxOfId=null},e.prototype.pickedParticle=function(e){if(e.hit){var t=e.subMeshId,i=e.faceId-this.mesh.subMeshes[t].indexStart/3,r=this.pickedBySubMesh;if(r[t]&&r[t][i])return r[t][i]}return null},e.prototype.getParticleById=function(e){var t=this.particles[e];if(t&&t.id==e)return t;var i=this.particles,r=this._idxOfId[e];if(void 0!==r)return i[r];for(var n=0,o=this.nbParticles;n<o;){var a=i[n];if(a.id==e)return a;n++}return null},e.prototype.getParticlesByShapeId=function(e){var t=[];return this.getParticlesByShapeIdToRef(e,t),t},e.prototype.getParticlesByShapeIdToRef=function(e,t){t.length=0;for(var i=0;i<this.nbParticles;i++){var r=this.particles[i];r.shapeId==e&&t.push(r)}return this},e.prototype.computeSubMeshes=function(){if(!this.mesh||!this._multimaterialEnabled)return this;var e=this.depthSortedParticles;if(this.particles.length>0)for(var t=0;t<this.particles.length;t++){var i=this.particles[t];i.materialIndex||(i.materialIndex=0);var r=e[t];r.materialIndex=i.materialIndex,r.ind=i._ind,r.indicesLength=i._model._indicesLength,r.idx=i.idx}this._sortParticlesByMaterial();var n=this._indicesByMaterial,o=this._materialIndexes,a=this.mesh;a.subMeshes=[];for(var s=a.getTotalVertices(),l=0;l<o.length;l++){var c=n[l],u=n[l+1]-c,h=o[l];new po(h,0,s,c,u,a)}return this},e.prototype._sortParticlesByMaterial=function(){var e=[0];this._indicesByMaterial=e;var t=[];this._materialIndexes=t;var i=this.depthSortedParticles;i.sort(this._materialSortFunction);var r=i.length,n=this._indices32,o=this._indices,a=0,s=0,l=0,c=i[0].materialIndex;t.push(c),this._pickable&&(this.pickedBySubMesh=[[]],this.pickedParticles=this.pickedBySubMesh[0]);for(var u=0;u<r;u++){var h=i[u],d=h.indicesLength,p=h.ind;h.materialIndex!==c&&(c=h.materialIndex,e.push(l),t.push(c),this._pickable&&(a++,this.pickedBySubMesh[a]=[],s=0));for(var f=0,_=0;_<d;_++){if(n[l]=o[p+_],this._pickable&&0==_%3){var m=this.pickedBySubMesh[a][s];m?(m.idx=h.idx,m.faceId=f):this.pickedBySubMesh[a][s]={idx:h.idx,faceId:f},s++,f++}l++}}return e.push(n.length),this._updatable&&this.mesh.updateIndices(n),this},e.prototype._setMaterialIndexesById=function(){this._materialIndexesById={};for(var e=0;e<this._materials.length;e++){var t=this._materials[e].uniqueId;this._materialIndexesById[t]=e}},e.prototype._filterUniqueMaterialId=function(e){return e.filter((function(e,t,i){return i.indexOf(e)===t}))},e.prototype._setDefaultMaterial=function(){return this._defaultMaterial||(this._defaultMaterial=new Uu(this.name+"DefaultMaterial",this._scene)),this._defaultMaterial},e.prototype.refreshVisibleSize=function(){return this._isVisibilityBoxLocked||this.mesh.refreshBoundingInfo(),this},e.prototype.setVisibilityBox=function(e){var t=e/2;this.mesh.buildBoundingInfo(new V(-t,-t,-t),new V(t,t,t))},Object.defineProperty(e.prototype,"isAlwaysVisible",{get:function(){return this._alwaysVisible},set:function(e){this._alwaysVisible=e,this.mesh.alwaysSelectAsActiveMesh=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isVisibilityBoxLocked",{get:function(){return this._isVisibilityBoxLocked},set:function(e){this._isVisibilityBoxLocked=e,this.mesh.getBoundingInfo().isLocked=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"computeParticleRotation",{get:function(){return this._computeParticleRotation},set:function(e){this._computeParticleRotation=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"computeParticleColor",{get:function(){return this._computeParticleColor},set:function(e){this._computeParticleColor=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"computeParticleTexture",{get:function(){return this._computeParticleTexture},set:function(e){this._computeParticleTexture=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"computeParticleVertex",{get:function(){return this._computeParticleVertex},set:function(e){this._computeParticleVertex=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"computeBoundingBox",{get:function(){return this._computeBoundingBox},set:function(e){this._computeBoundingBox=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"depthSortParticles",{get:function(){return this._depthSortParticles},set:function(e){this._depthSortParticles=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"expandable",{get:function(){return this._expandable},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"multimaterialEnabled",{get:function(){return this._multimaterialEnabled},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useModelMaterial",{get:function(){return this._useModelMaterial},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"materials",{get:function(){return this._materials},enumerable:!1,configurable:!0}),e.prototype.setMultiMaterial=function(e){this._materials=this._filterUniqueMaterialId(e),this._setMaterialIndexesById(),this._multimaterial&&this._multimaterial.dispose(),this._multimaterial=new Ra(this.name+"MultiMaterial",this._scene);for(var t=0;t<this._materials.length;t++)this._multimaterial.subMaterials.push(this._materials[t]);this.computeSubMeshes(),this.mesh.material=this._multimaterial},Object.defineProperty(e.prototype,"multimaterial",{get:function(){return this._multimaterial},set:function(e){this._multimaterial=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"autoUpdateSubMeshes",{get:function(){return this._autoUpdateSubMeshes},set:function(e){this._autoUpdateSubMeshes=e},enumerable:!1,configurable:!0}),e.prototype.initParticles=function(){},e.prototype.recycleParticle=function(e){return e},e.prototype.updateParticle=function(e){return e},e.prototype.updateParticleVertex=function(e,t,i){return this},e.prototype.beforeUpdateParticles=function(e,t,i){},e.prototype.afterUpdateParticles=function(e,t,i){},e}(),mA=function(){function e(e,t,i,r,n){this.idx=0,this.color=new J(1,1,1,1),this.position=V.Zero(),this.rotation=V.Zero(),this.uv=new U(0,0),this.velocity=V.Zero(),this.pivot=V.Zero(),this.translateFromPivot=!1,this._pos=0,this._ind=0,this.groupId=0,this.idxInGroup=0,this._stillInvisible=!1,this._rotationMatrix=[1,0,0,0,1,0,0,0,1],this.parentId=null,this._globalPosition=V.Zero(),this.idx=e,this._group=t,this.groupId=i,this.idxInGroup=r,this._pcs=n}return Object.defineProperty(e.prototype,"size",{get:function(){return this.size},set:function(e){this.size=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"quaternion",{get:function(){return this.rotationQuaternion},set:function(e){this.rotationQuaternion=e},enumerable:!1,configurable:!0}),e.prototype.intersectsMesh=function(e,t){if(!e.hasBoundingInfo)return!1;if(!this._pcs.mesh)throw new Error("Point Cloud System doesnt contain the Mesh");if(t)return e.getBoundingInfo().boundingSphere.intersectsPoint(this.position.add(this._pcs.mesh.position));var i=e.getBoundingInfo().boundingBox,r=i.maximumWorld.x,n=i.minimumWorld.x,o=i.maximumWorld.y,a=i.minimumWorld.y,s=i.maximumWorld.z,l=i.minimumWorld.z,c=this.position.x+this._pcs.mesh.position.x,u=this.position.y+this._pcs.mesh.position.y,h=this.position.z+this._pcs.mesh.position.z;return n<=c&&c<=r&&a<=u&&u<=o&&l<=h&&h<=s},e.prototype.getRotationMatrix=function(e){var t;if(this.rotationQuaternion)t=this.rotationQuaternion;else{t=H.Quaternion[0];var i=this.rotation;G.RotationYawPitchRollToRef(i.y,i.x,i.z,t)}t.toRotationMatrix(e)},e}(),gA=function(){function e(e,t){this.groupId=e,this._positionFunction=t}return Object.defineProperty(e.prototype,"groupID",{get:function(){return this.groupId},set:function(e){this.groupId=e},enumerable:!1,configurable:!0}),e}();!function(e){e[e.Color=2]="Color",e[e.UV=1]="UV",e[e.Random=0]="Random",e[e.Stated=3]="Stated"}(uA||(uA={}));var vA=function(){function e(e,t,i,r){this.particles=new Array,this.nbParticles=0,this.counter=0,this.vars={},this._promises=[],this._positions=new Array,this._indices=new Array,this._normals=new Array,this._colors=new Array,this._uvs=new Array,this._updatable=!0,this._isVisibilityBoxLocked=!1,this._alwaysVisible=!1,this._groups=new Array,this._groupCounter=0,this._computeParticleColor=!0,this._computeParticleTexture=!0,this._computeParticleRotation=!0,this._computeBoundingBox=!1,this._isReady=!1,this.name=e,this._size=t,this._scene=i||M.LastCreatedScene,r&&void 0!==r.updatable?this._updatable=r.updatable:this._updatable=!0}return Object.defineProperty(e.prototype,"positions",{get:function(){return this._positions32},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"colors",{get:function(){return this._colors32},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"uvs",{get:function(){return this._uvs32},enumerable:!1,configurable:!0}),e.prototype.buildMeshAsync=function(e){var t=this;return Promise.all(this._promises).then((function(){return t._isReady=!0,t._buildMesh(e)}))},e.prototype._buildMesh=function(e){0===this.nbParticles&&this.addPoints(1),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors);var t=new _o;t.set(this._positions32,Nr.PositionKind),this._uvs32.length>0&&t.set(this._uvs32,Nr.UVKind);var i=0;this._colors32.length>0&&(i=1,t.set(this._colors32,Nr.ColorKind));var r=new Fa(this.name,this._scene);t.applyToMesh(r,this._updatable),this.mesh=r,this._positions=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0);var n=e;return n||((n=new Uu("point cloud material",this._scene)).emissiveColor=new Z(i,i,i),n.disableLighting=!0,n.pointsCloud=!0,n.pointSize=this._size),r.material=n,new Promise((function(e){return e(r)}))},e.prototype._addParticle=function(e,t,i,r){var n=new mA(e,t,i,r,this);return this.particles.push(n),n},e.prototype._randomUnitVector=function(e){e.position=new V(Math.random(),Math.random(),Math.random()),e.color=new J(1,1,1,1)},e.prototype._getColorIndicesForCoord=function(e,t,i,r){var n=e._groupImageData,o=i*(4*r)+4*t,a=[o,o+1,o+2,o+3],s=a[1],l=a[2],c=a[3],u=n[a[0]],h=n[s],d=n[l],p=n[c];return new J(u/255,h/255,d/255,p)},e.prototype._setPointsColorOrUV=function(e,t,i,r,n,o,a,s){s=null!=s?s:0,i&&e.updateFacetData();var l=2*e.getBoundingInfo().boundingSphere.radius,c=e.getVerticesData(Nr.PositionKind),u=e.getIndices(),h=e.getVerticesData(Nr.UVKind+(s?s+1:"")),d=e.getVerticesData(Nr.ColorKind),p=V.Zero();e.computeWorldMatrix();var f=e.getWorldMatrix();if(!f.isIdentity()){c=c.slice(0);for(var _=0;_<c.length/3;_++)V.TransformCoordinatesFromFloatsToRef(c[3*_],c[3*_+1],c[3*_+2],f,p),c[3*_]=p.x,c[3*_+1]=p.y,c[3*_+2]=p.z}var m,g,v=0,y=0,b=0,T=0,E=0,S=0,x=0,A=0,C=0,R=0,P=0,I=0,M=0,O=V.Zero(),D=V.Zero(),N=V.Zero(),F=V.Zero(),L=V.Zero(),w=0,B=0,G=0,z=0,W=0,H=0,X=U.Zero(),Y=U.Zero(),K=U.Zero(),Q=U.Zero(),q=U.Zero(),$=0,ee=0,te=0,ie=0,re=0,ne=0,oe=0,ae=0,se=0,le=0,ce=0,ue=0,he=k.Zero(),de=k.Zero(),pe=k.Zero(),fe=k.Zero(),_e=k.Zero(),me=0,ge=0;a=a||0;for(var ve,ye=new k(0,0,0,0),be=V.Zero(),Te=V.Zero(),Ee=V.Zero(),Se=0,xe=V.Zero(),Ae=0,Ce=0,Re=new hs(V.Zero(),new V(1,0,0)),Pe=V.Zero(),Ie=0;Ie<u.length/3;Ie++){y=u[3*Ie],b=u[3*Ie+1],T=u[3*Ie+2],E=c[3*y],S=c[3*y+1],x=c[3*y+2],A=c[3*b],C=c[3*b+1],R=c[3*b+2],P=c[3*T],I=c[3*T+1],M=c[3*T+2],O.set(E,S,x),D.set(A,C,R),N.set(P,I,M),D.subtractToRef(O,F),N.subtractToRef(D,L),h&&(w=h[2*y],B=h[2*y+1],G=h[2*b],z=h[2*b+1],W=h[2*T],H=h[2*T+1],X.set(w,B),Y.set(G,z),K.set(W,H),Y.subtractToRef(X,Q),K.subtractToRef(Y,q)),d&&r&&($=d[4*y],ee=d[4*y+1],te=d[4*y+2],ie=d[4*y+3],re=d[4*b],ne=d[4*b+1],oe=d[4*b+2],ae=d[4*b+3],se=d[4*T],le=d[4*T+1],ce=d[4*T+2],ue=d[4*T+3],he.set($,ee,te,ie),de.set(re,ne,oe,ae),pe.set(se,le,ce,ue),de.subtractToRef(he,fe),pe.subtractToRef(de,_e));for(var Me=void 0,Oe=void 0,De=void 0,Ne=void 0,Fe=void 0,Le=void 0,we=void 0,Be=void 0,Ue=new Z(0,0,0),Ve=new Z(0,0,0),ke=void 0,Ge=void 0,ze=0;ze<t._groupDensity[Ie];ze++)v=this.particles.length,this._addParticle(v,t,this._groupCounter,Ie+ze),Ge=this.particles[v],me=Math.sqrt(j.RandomRange(0,1)),ge=j.RandomRange(0,1),m=O.add(F.scale(me)).add(L.scale(me*ge)),i&&(be=e.getFacetNormal(Ie).normalize().scale(-1),Te=F.clone().normalize(),Ee=V.Cross(be,Te),Se=j.RandomRange(0,2*Math.PI),xe=Te.scale(Math.cos(Se)).add(Ee.scale(Math.sin(Se))),Se=j.RandomRange(.1,Math.PI/2),Pe=xe.scale(Math.cos(Se)).add(be.scale(Math.sin(Se))),Re.origin=m.add(Pe.scale(1e-5)),Re.direction=Pe,Re.length=l,(ve=Re.intersectsMesh(e)).hit&&(Ce=ve.pickedPoint.subtract(m).length(),Ae=j.RandomRange(0,1)*Ce,m.addInPlace(Pe.scale(Ae)))),Ge.position=m.clone(),this._positions.push(Ge.position.x,Ge.position.y,Ge.position.z),void 0!==r?h&&(g=X.add(Q.scale(me)).add(q.scale(me*ge)),r?n&&null!==t._groupImageData?(Me=t._groupImgWidth,Oe=t._groupImgHeight,ke=this._getColorIndicesForCoord(t,Math.round(g.x*Me),Math.round(g.y*Oe),Me),Ge.color=ke,this._colors.push(ke.r,ke.g,ke.b,ke.a)):d?(ye=he.add(fe.scale(me)).add(_e.scale(me*ge)),Ge.color=new J(ye.x,ye.y,ye.z,ye.w),this._colors.push(ye.x,ye.y,ye.z,ye.w)):(ye=he.set(Math.random(),Math.random(),Math.random(),1),Ge.color=new J(ye.x,ye.y,ye.z,ye.w),this._colors.push(ye.x,ye.y,ye.z,ye.w)):(Ge.uv=g.clone(),this._uvs.push(Ge.uv.x,Ge.uv.y))):(o?(Ue.set(o.r,o.g,o.b),De=j.RandomRange(-a,a),Ne=j.RandomRange(-a,a),Fe=(Be=Ue.toHSV()).r,(Le=Be.g+De)<0&&(Le=0),Le>1&&(Le=1),(we=Be.b+Ne)<0&&(we=0),we>1&&(we=1),Z.HSVtoRGBToRef(Fe,Le,we,Ve),ye.set(Ve.r,Ve.g,Ve.b,1)):ye=he.set(Math.random(),Math.random(),Math.random(),1),Ge.color=new J(ye.x,ye.y,ye.z,ye.w),this._colors.push(ye.x,ye.y,ye.z,ye.w))}},e.prototype._colorFromTexture=function(e,t,i){var r=this;if(null===e.material)return ae.Warn(e.name+"has no material."),t._groupImageData=null,void this._setPointsColorOrUV(e,t,i,!0,!1);var n=e.material.getActiveTextures();if(0===n.length)return ae.Warn(e.name+"has no usable texture."),t._groupImageData=null,void this._setPointsColorOrUV(e,t,i,!0,!1);var o=e.clone();o.setEnabled(!1),this._promises.push(new Promise((function(e){Ya.WhenAllReady(n,(function(){var a=t._textureNb;a<0&&(a=0),a>n.length-1&&(a=n.length-1);var s=function(){t._groupImgWidth=n[a].getSize().width,t._groupImgHeight=n[a].getSize().height,r._setPointsColorOrUV(o,t,i,!0,!0,void 0,void 0,n[a].coordinatesIndex),o.dispose(),e()};t._groupImageData=null;var l=n[a].readPixels();l?l.then((function(e){t._groupImageData=e,s()})):s()}))})))},e.prototype._calculateDensity=function(e,t,i){for(var r,n,o,a,s,l,c,u,h,d,p,f,_=V.Zero(),m=V.Zero(),g=V.Zero(),v=V.Zero(),y=V.Zero(),b=V.Zero(),T=[],E=0,S=i.length/3,x=0;x<S;x++)r=i[3*x],n=i[3*x+1],o=i[3*x+2],a=t[3*r],s=t[3*r+1],l=t[3*r+2],c=t[3*n],u=t[3*n+1],h=t[3*n+2],d=t[3*o],p=t[3*o+1],f=t[3*o+2],_.set(a,s,l),m.set(c,u,h),g.set(d,p,f),m.subtractToRef(_,v),g.subtractToRef(m,y),V.CrossToRef(v,y,b),E+=.5*b.length(),T[x]=E;var A=new Array(S),C=e;for(x=S-1;x>0;x--){var R=T[x];if(0===R)A[x]=0;else{var P=(R-T[x-1])/R*C,I=Math.floor(P),M=P-I,O=I+Number(Math.random()<M);A[x]=O,C-=O}}return A[0]=C,A},e.prototype.addPoints=function(e,t){void 0===t&&(t=this._randomUnitVector);for(var i,r=new gA(this._groupCounter,t),n=this.nbParticles,o=0;o<e;o++)i=this._addParticle(n,r,this._groupCounter,o),r&&r._positionFunction&&r._positionFunction(i,n,o),this._positions.push(i.position.x,i.position.y,i.position.z),i.color&&this._colors.push(i.color.r,i.color.g,i.color.b,i.color.a),i.uv&&this._uvs.push(i.uv.x,i.uv.y),n++;return this.nbParticles+=e,this._groupCounter++,this._groupCounter},e.prototype.addSurfacePoints=function(e,t,i,r,n){var o=i||uA.Random;(isNaN(o)||o<0||o>3)&&(o=uA.Random);var a=e.getVerticesData(Nr.PositionKind),s=e.getIndices();this._groups.push(this._groupCounter);var l=new gA(this._groupCounter,null);switch(l._groupDensity=this._calculateDensity(t,a,s),o===uA.Color?l._textureNb=r||0:r=r||new J(1,1,1,1),o){case uA.Color:this._colorFromTexture(e,l,!1);break;case uA.UV:this._setPointsColorOrUV(e,l,!1,!1,!1);break;case uA.Random:this._setPointsColorOrUV(e,l,!1);break;case uA.Stated:this._setPointsColorOrUV(e,l,!1,void 0,void 0,r,n)}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1},e.prototype.addVolumePoints=function(e,t,i,r,n){var o=i||uA.Random;(isNaN(o)||o<0||o>3)&&(o=uA.Random);var a=e.getVerticesData(Nr.PositionKind),s=e.getIndices();this._groups.push(this._groupCounter);var l=new gA(this._groupCounter,null);switch(l._groupDensity=this._calculateDensity(t,a,s),o===uA.Color?l._textureNb=r||0:r=r||new J(1,1,1,1),o){case uA.Color:this._colorFromTexture(e,l,!0);break;case uA.UV:this._setPointsColorOrUV(e,l,!0,!1,!1);break;case uA.Random:this._setPointsColorOrUV(e,l,!0);break;case uA.Stated:this._setPointsColorOrUV(e,l,!0,void 0,void 0,r,n)}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1},e.prototype.setParticles=function(e,t,i){var r,n;if(void 0===e&&(e=0),void 0===t&&(t=this.nbParticles-1),void 0===i&&(i=!0),!this._updatable||!this._isReady)return this;this.beforeUpdateParticles(e,t,i);var o=H.Matrix[0],a=this.mesh,s=this._colors32,l=this._positions32,c=this._uvs32,u=H.Vector3,h=u[5].copyFromFloats(1,0,0),d=u[6].copyFromFloats(0,1,0),p=u[7].copyFromFloats(0,0,1),f=u[8].setAll(Number.MAX_VALUE),_=u[9].setAll(-Number.MAX_VALUE);z.IdentityToRef(o);var m=0;if((null===(r=this.mesh)||void 0===r?void 0:r.isFacetDataEnabled)&&(this._computeBoundingBox=!0),t=t>=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(0!=e||t!=this.nbParticles-1)){var g=null===(n=this.mesh)||void 0===n?void 0:n.getBoundingInfo();g&&(f.copyFrom(g.minimum),_.copyFrom(g.maximum))}m=0;for(var v=0,y=0,b=0,T=e;T<=t;T++){var E=this.particles[T];v=3*(m=E.idx),y=4*m,b=2*m,this.updateParticle(E);var S=E._rotationMatrix,x=E.position,A=E._globalPosition;if(this._computeParticleRotation&&E.getRotationMatrix(o),null!==E.parentId){var C=this.particles[E.parentId],R=C._rotationMatrix,P=C._globalPosition,I=x.x*R[1]+x.y*R[4]+x.z*R[7],M=x.x*R[0]+x.y*R[3]+x.z*R[6],O=x.x*R[2]+x.y*R[5]+x.z*R[8];if(A.x=P.x+M,A.y=P.y+I,A.z=P.z+O,this._computeParticleRotation){var D=o.m;S[0]=D[0]*R[0]+D[1]*R[3]+D[2]*R[6],S[1]=D[0]*R[1]+D[1]*R[4]+D[2]*R[7],S[2]=D[0]*R[2]+D[1]*R[5]+D[2]*R[8],S[3]=D[4]*R[0]+D[5]*R[3]+D[6]*R[6],S[4]=D[4]*R[1]+D[5]*R[4]+D[6]*R[7],S[5]=D[4]*R[2]+D[5]*R[5]+D[6]*R[8],S[6]=D[8]*R[0]+D[9]*R[3]+D[10]*R[6],S[7]=D[8]*R[1]+D[9]*R[4]+D[10]*R[7],S[8]=D[8]*R[2]+D[9]*R[5]+D[10]*R[8]}}else A.x=0,A.y=0,A.z=0,this._computeParticleRotation&&(D=o.m,S[0]=D[0],S[1]=D[1],S[2]=D[2],S[3]=D[4],S[4]=D[5],S[5]=D[6],S[6]=D[8],S[7]=D[9],S[8]=D[10]);var N=u[11];E.translateFromPivot?N.setAll(0):N.copyFrom(E.pivot);var F=u[0];F.copyFrom(E.position);var L=F.x-E.pivot.x,w=F.y-E.pivot.y,B=F.z-E.pivot.z,U=L*S[0]+w*S[3]+B*S[6],V=L*S[1]+w*S[4]+B*S[7],k=L*S[2]+w*S[5]+B*S[8];U+=N.x,V+=N.y,k+=N.z;var G=l[v]=A.x+h.x*U+d.x*V+p.x*k,W=l[v+1]=A.y+h.y*U+d.y*V+p.y*k,X=l[v+2]=A.z+h.z*U+d.z*V+p.z*k;if(this._computeBoundingBox&&(f.minimizeInPlaceFromFloats(G,W,X),_.maximizeInPlaceFromFloats(G,W,X)),this._computeParticleColor&&E.color){var j=E.color,Y=this._colors32;Y[y]=j.r,Y[y+1]=j.g,Y[y+2]=j.b,Y[y+3]=j.a}if(this._computeParticleTexture&&E.uv){var K=E.uv,Q=this._uvs32;Q[b]=K.x,Q[b+1]=K.y}}return a&&(i&&(this._computeParticleColor&&a.updateVerticesData(Nr.ColorKind,s,!1,!1),this._computeParticleTexture&&a.updateVerticesData(Nr.UVKind,c,!1,!1),a.updateVerticesData(Nr.PositionKind,l,!1,!1)),this._computeBoundingBox&&(a.hasBoundingInfo?a.getBoundingInfo().reConstruct(f,_,a._worldMatrix):a.buildBoundingInfo(f,_,a._worldMatrix))),this.afterUpdateParticles(e,t,i),this},e.prototype.dispose=function(){var e;null===(e=this.mesh)||void 0===e||e.dispose(),this.vars=null,this._positions=null,this._indices=null,this._normals=null,this._uvs=null,this._colors=null,this._indices32=null,this._positions32=null,this._uvs32=null,this._colors32=null},e.prototype.refreshVisibleSize=function(){var e;return this._isVisibilityBoxLocked||null===(e=this.mesh)||void 0===e||e.refreshBoundingInfo(),this},e.prototype.setVisibilityBox=function(e){if(this.mesh){var t=e/2;this.mesh.buildBoundingInfo(new V(-t,-t,-t),new V(t,t,t))}},Object.defineProperty(e.prototype,"isAlwaysVisible",{get:function(){return this._alwaysVisible},set:function(e){this.mesh&&(this._alwaysVisible=e,this.mesh.alwaysSelectAsActiveMesh=e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"computeParticleRotation",{set:function(e){this._computeParticleRotation=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"computeParticleColor",{get:function(){return this._computeParticleColor},set:function(e){this._computeParticleColor=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"computeParticleTexture",{get:function(){return this._computeParticleTexture},set:function(e){this._computeParticleTexture=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"computeBoundingBox",{get:function(){return this._computeBoundingBox},set:function(e){this._computeBoundingBox=e},enumerable:!1,configurable:!0}),e.prototype.initParticles=function(){},e.prototype.recycleParticle=function(e){return e},e.prototype.updateParticle=function(e){return e},e.prototype.beforeUpdateParticles=function(e,t,i){},e.prototype.afterUpdateParticles=function(e,t,i){},e}();Object.defineProperty(Uo.prototype,"physicsImpostor",{get:function(){return this._physicsImpostor},set:function(e){var t=this;this._physicsImpostor!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsImpostor=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add((function(){t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)}))))},enumerable:!0,configurable:!0}),Uo.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},Uo.prototype.applyImpulse=function(e,t){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(e,t),this):this},Uo.prototype.setPhysicsLinkWith=function(e,t,i,r){return this.physicsImpostor&&e.physicsImpostor?(this.physicsImpostor.createJoint(e.physicsImpostor,Cs.HingeJoint,{mainPivot:t,connectedPivot:i,nativeParams:r}),this):this};var yA,bA,TA,EA,SA,xA,AA,CA,RA=function(){function e(t,i){void 0===i&&(i=e.DefaultPluginFactory()),this._physicsPlugin=i,this._physicsBodies=[],this._subTimeStep=0,t=t||new V(0,-9.807,0),this.setGravity(t),this.setTimeStep()}return e.prototype.getPluginVersion=function(){return this._physicsPlugin.getPluginVersion()},e.DefaultPluginFactory=function(){throw He("")},e.prototype.setGravity=function(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)},e.prototype.setTimeStep=function(e){void 0===e&&(e=1/60),this._physicsPlugin.setTimeStep(e)},e.prototype.getTimeStep=function(){return this._physicsPlugin.getTimeStep()},e.prototype.setSubTimeStep=function(e){void 0===e&&(e=0),this._subTimeStep=e},e.prototype.getSubTimeStep=function(){return this._subTimeStep},e.prototype.dispose=function(){this._physicsPlugin.dispose()},e.prototype.getPhysicsPluginName=function(){return this._physicsPlugin.name},e.prototype._step=function(e){e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._physicsBodies)},e.prototype.addBody=function(e){this._physicsBodies.push(e)},e.prototype.removeBody=function(e){var t=this._physicsBodies.indexOf(e);t>-1&&this._physicsBodies.splice(t,1)},e.prototype.getBodies=function(){return this._physicsBodies},e.prototype.getPhysicsPlugin=function(){return this._physicsPlugin},e.prototype.raycastToRef=function(e,t,i,r){this._physicsPlugin.raycast(e,t,i,r)},e.prototype.raycast=function(e,t,i){var r=new Nv;return this._physicsPlugin.raycast(e,t,r,i),r},e}();!function(e){e[e.FREE=0]="FREE",e[e.LIMITED=1]="LIMITED",e[e.LOCKED=2]="LOCKED"}(yA||(yA={})),function(e){e[e.LINEAR_X=0]="LINEAR_X",e[e.LINEAR_Y=1]="LINEAR_Y",e[e.LINEAR_Z=2]="LINEAR_Z",e[e.ANGULAR_X=3]="ANGULAR_X",e[e.ANGULAR_Y=4]="ANGULAR_Y",e[e.ANGULAR_Z=5]="ANGULAR_Z",e[e.LINEAR_DISTANCE=6]="LINEAR_DISTANCE"}(bA||(bA={})),function(e){e[e.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",e[e.DISTANCE=2]="DISTANCE",e[e.HINGE=3]="HINGE",e[e.SLIDER=4]="SLIDER",e[e.LOCK=5]="LOCK",e[e.PRISMATIC=6]="PRISMATIC",e[e.SIX_DOF=7]="SIX_DOF"}(TA||(TA={})),function(e){e[e.SPHERE=0]="SPHERE",e[e.CAPSULE=1]="CAPSULE",e[e.CYLINDER=2]="CYLINDER",e[e.BOX=3]="BOX",e[e.CONVEX_HULL=4]="CONVEX_HULL",e[e.CONTAINER=5]="CONTAINER",e[e.MESH=6]="MESH",e[e.HEIGHTFIELD=7]="HEIGHTFIELD"}(EA||(EA={})),function(e){e[e.NONE=0]="NONE",e[e.VELOCITY=1]="VELOCITY",e[e.POSITION=2]="POSITION"}(SA||(SA={})),function(e){e.COLLISION_STARTED="COLLISION_STARTED",e.COLLISION_CONTINUED="COLLISION_CONTINUED",e.COLLISION_FINISHED="COLLISION_FINISHED",e.TRIGGER_ENTERED="TRIGGER_ENTERED",e.TRIGGER_EXITED="TRIGGER_EXITED"}(xA||(xA={})),function(e){e[e.STATIC=0]="STATIC",e[e.ANIMATED=1]="ANIMATED",e[e.DYNAMIC=2]="DYNAMIC"}(AA||(AA={})),function(e){e[e.SIMULATION_CONTROLLED=0]="SIMULATION_CONTROLLED",e[e.ALWAYS_ACTIVE=1]="ALWAYS_ACTIVE",e[e.ALWAYS_INACTIVE=2]="ALWAYS_INACTIVE"}(CA||(CA={}));var PA,IA=function(){function e(e,t,i,r){var n=this;if(this._pluginData=void 0,this._pluginDataInstances=[],this._collisionCBEnabled=!1,this._collisionEndedCBEnabled=!1,this.disablePreStep=!0,this.disableSync=!1,this._isDisposed=!1,this._shape=null,r){var o=r.getPhysicsEngine();if(!o)throw new Error("No Physics Engine available.");if(this._physicsEngine=o,2!=o.getPluginVersion())throw new Error("Plugin version is incorrect. Expected version 2.");var a=o.getPhysicsPlugin();if(!a)throw new Error("No Physics Plugin available.");this._physicsPlugin=a,e.rotationQuaternion||(e.rotationQuaternion=G.FromEulerAngles(e.rotation.x,e.rotation.y,e.rotation.z)),this.startAsleep=i,this._motionType=t,this.disableSync=t==AA.STATIC;var s=e;s.hasThinInstances?this._physicsPlugin.initBodyInstances(this,t,s):(e.parent&&e.computeWorldMatrix(!0),this._physicsPlugin.initBody(this,t,e.absolutePosition,e.absoluteRotationQuaternion)),this.transformNode=e,e.physicsBody=this,o.addBody(this),this._nodeDisposeObserver=e.onDisposeObservable.add((function(){n.dispose()}))}}return e.prototype.getClassName=function(){return"PhysicsBody"},e.prototype.clone=function(t){var i=new e(t,this.getMotionType(),this.startAsleep,this.transformNode.getScene());return i.shape=this.shape,i.setMassProperties(this.getMassProperties()),i.setLinearDamping(this.getLinearDamping()),i.setAngularDamping(this.getAngularDamping()),i},e.prototype.updateBodyInstances=function(){var e=this.transformNode;e.hasThinInstances&&this._physicsPlugin.updateBodyInstances(this,e)},Object.defineProperty(e.prototype,"numInstances",{get:function(){return this._pluginDataInstances.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"motionType",{get:function(){return this._motionType},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"shape",{get:function(){return this._shape},set:function(e){this._shape=e,e&&this._physicsPlugin.setShape(this,e)},enumerable:!1,configurable:!0}),e.prototype.setEventMask=function(e,t){this._physicsPlugin.setEventMask(this,e,t)},e.prototype.getEventMask=function(e){return this._physicsPlugin.getEventMask(this,e)},e.prototype.setMotionType=function(e,t){this.disableSync=e==AA.STATIC,this._physicsPlugin.setMotionType(this,e,t)},e.prototype.getMotionType=function(e){return this._physicsPlugin.getMotionType(this,e)},e.prototype.computeMassProperties=function(e){return this._physicsPlugin.computeMassProperties(this,e)},e.prototype.setMassProperties=function(e,t){this._physicsPlugin.setMassProperties(this,e,t)},e.prototype.getMassProperties=function(e){return this._physicsPlugin.getMassProperties(this,e)},e.prototype.setLinearDamping=function(e,t){this._physicsPlugin.setLinearDamping(this,e,t)},e.prototype.getLinearDamping=function(e){return this._physicsPlugin.getLinearDamping(this,e)},e.prototype.setAngularDamping=function(e,t){this._physicsPlugin.setAngularDamping(this,e,t)},e.prototype.getAngularDamping=function(e){return this._physicsPlugin.getAngularDamping(this,e)},e.prototype.setLinearVelocity=function(e,t){this._physicsPlugin.setLinearVelocity(this,e,t)},e.prototype.getLinearVelocityToRef=function(e,t){this._physicsPlugin.getLinearVelocityToRef(this,e,t)},e.prototype.getLinearVelocity=function(e){var t=new V;return this.getLinearVelocityToRef(t,e),t},e.prototype.setAngularVelocity=function(e,t){this._physicsPlugin.setAngularVelocity(this,e,t)},e.prototype.getAngularVelocityToRef=function(e,t){this._physicsPlugin.getAngularVelocityToRef(this,e,t)},e.prototype.getAngularVelocity=function(e){var t=new V;return this.getAngularVelocityToRef(t,e),t},e.prototype.applyImpulse=function(e,t,i){this._physicsPlugin.applyImpulse(this,e,t,i)},e.prototype.applyAngularImpulse=function(e,t){this._physicsPlugin.applyAngularImpulse(this,e,t)},e.prototype.applyForce=function(e,t,i){this._physicsPlugin.applyForce(this,e,t,i)},e.prototype.getGeometry=function(){return this._physicsPlugin.getBodyGeometry(this)},e.prototype.getCollisionObservable=function(){return this._physicsPlugin.getCollisionObservable(this)},e.prototype.getCollisionEndedObservable=function(){return this._physicsPlugin.getCollisionEndedObservable(this)},e.prototype.setCollisionCallbackEnabled=function(e){this._collisionCBEnabled=e,this._physicsPlugin.setCollisionCallbackEnabled(this,e)},e.prototype.setCollisionEndedCallbackEnabled=function(e){this._collisionEndedCBEnabled=e,this._physicsPlugin.setCollisionEndedCallbackEnabled(this,e)},e.prototype.getObjectCenterWorld=function(e){var t=new V;return this.getObjectCenterWorldToRef(t,e)},e.prototype.getObjectCenterWorldToRef=function(e,t){var i;if((null===(i=this._pluginDataInstances)||void 0===i?void 0:i.length)>0){var r=t||0,n=this.transformNode._thinInstanceDataStorage.matrixData;n&&e.set(n[16*r+12],n[16*r+13],n[16*r+14])}else e.copyFrom(this.transformNode.position);return e},e.prototype.addConstraint=function(e,t,i,r){this._physicsPlugin.addConstraint(this,e,t,i,r)},e.prototype.syncWithBone=function(e,t,i,r,n,o){var a=this.transformNode;if(a.rotationQuaternion)if(n){var s=H.Quaternion[0];e.getRotationQuaternionToRef(dn.WORLD,t,s),s.multiplyToRef(n,a.rotationQuaternion)}else e.getRotationQuaternionToRef(dn.WORLD,t,a.rotationQuaternion);var l=H.Vector3[0],c=H.Vector3[1];o||((o=H.Vector3[2]).x=0,o.y=1,o.z=0),e.getDirectionToRef(o,t,c),e.getAbsolutePositionToRef(t,l),null==r&&i&&(r=i.length()),null!=r&&(l.x+=c.x*r,l.y+=c.y*r,l.z+=c.z*r),a.setAbsolutePosition(l)},e.prototype.iterateOverAllInstances=function(e){var t;if((null===(t=this._pluginDataInstances)||void 0===t?void 0:t.length)>0)for(var i=0;i<this._pluginDataInstances.length;i++)e(this,i);else e(this,void 0)},e.prototype.setGravityFactor=function(e,t){this._physicsPlugin.setGravityFactor(this,e,t)},e.prototype.getGravityFactor=function(e){return this._physicsPlugin.getGravityFactor(this,e)},e.prototype.setTargetTransform=function(e,t,i){this._physicsPlugin.setTargetTransform(this,e,t,i)},Object.defineProperty(e.prototype,"isDisposed",{get:function(){return this._isDisposed},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){this._isDisposed||(this._collisionCBEnabled&&this.setCollisionCallbackEnabled(!1),this._collisionEndedCBEnabled&&this.setCollisionEndedCallbackEnabled(!1),this._nodeDisposeObserver&&(this.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver),this._nodeDisposeObserver=null),this._physicsEngine.removeBody(this),this._physicsPlugin.removeBody(this),this._physicsPlugin.disposeBody(this),this.transformNode.physicsBody=null,this._pluginData=null,this._pluginDataInstances.length=0,this._isDisposed=!0,this.shape=null)},e}(),MA=function(){function e(e,t){var i;if(this._pluginData=void 0,this._isTrigger=!1,this._isDisposed=!1,t){var r=t.getPhysicsEngine();if(!r)throw new Error("No Physics Engine available.");if(2!=r.getPluginVersion())throw new Error("Plugin version is incorrect. Expected version 2.");var n=r.getPhysicsPlugin();if(!n)throw new Error("No Physics Plugin available.");if(this._physicsPlugin=n,void 0!==e.pluginData&&null!==e.pluginData)this._pluginData=e.pluginData,this._type=this._physicsPlugin.getShapeType(this);else if(void 0!==e.type&&null!==e.type){this._type=e.type;var o=null!==(i=e.parameters)&&void 0!==i?i:{};this._physicsPlugin.initShape(this,e.type,o)}}}return e.prototype.getClassName=function(){return"PhysicsShape"},Object.defineProperty(e.prototype,"type",{get:function(){return this._type},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"filterMembershipMask",{get:function(){return this._physicsPlugin.getShapeFilterMembershipMask(this)},set:function(e){this._physicsPlugin.setShapeFilterMembershipMask(this,e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"filterCollideMask",{get:function(){return this._physicsPlugin.getShapeFilterCollideMask(this)},set:function(e){this._physicsPlugin.setShapeFilterCollideMask(this,e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"material",{get:function(){return this._material||(this._material=this._physicsPlugin.getMaterial(this)),this._material},set:function(e){this._physicsPlugin.setMaterial(this,e),this._material=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"density",{get:function(){return this._physicsPlugin.getDensity(this)},set:function(e){this._physicsPlugin.setDensity(this,e)},enumerable:!1,configurable:!0}),e.prototype.addChildFromParent=function(e,t,i){var r=i.computeWorldMatrix(!0),n=e.computeWorldMatrix(!0),o=H.Matrix[0];r.multiplyToRef(z.Invert(n),o);var a=H.Vector3[0],s=H.Quaternion[0],l=H.Vector3[1];o.decompose(l,s,a),this._physicsPlugin.addChild(this,t,a,s,l)},e.prototype.addChild=function(e,t,i,r){this._physicsPlugin.addChild(this,e,t,i,r)},e.prototype.removeChild=function(e){this._physicsPlugin.removeChild(this,e)},e.prototype.getNumChildren=function(){return this._physicsPlugin.getNumChildren(this)},e.prototype.getBoundingBox=function(){return this._physicsPlugin.getBoundingBox(this)},Object.defineProperty(e.prototype,"isTrigger",{get:function(){return this._isTrigger},set:function(e){this._isTrigger!==e&&(this._isTrigger=e,this._physicsPlugin.setTrigger(this,e))},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){this._isDisposed||(this._physicsPlugin.disposeShape(this),this._isDisposed=!0)},e}(),OA=function(e){function t(t,i,r){return e.call(this,{type:EA.SPHERE,parameters:{center:t,radius:i}},r)||this}return m(t,e),t.FromMesh=function(e){var i=e.getBoundingInfo(),r=i.boundingSphere.center,n=i.boundingBox.extendSize;return new t(r,Math.max(n.x,n.y,n.z),e.getScene())},t}(MA),DA=function(e){function t(t,i,r,n){return e.call(this,{type:EA.CAPSULE,parameters:{pointA:t,pointB:i,radius:r}},n)||this}return m(t,e),t.FromMesh=function(e){var i=e.getBoundingInfo(),r=i.boundingBox.extendSize.x,n=new V(0,i.boundingBox.extendSize.y-r,0);return new t(i.boundingBox.center.add(n),i.boundingBox.center.subtract(n),r,e.getScene())},t}(MA),NA=function(e){function t(t,i,r,n){return e.call(this,{type:EA.CYLINDER,parameters:{pointA:t,pointB:i,radius:r}},n)||this}return m(t,e),t.FromMesh=function(e){var i=e.getBoundingInfo(),r=i.boundingBox.extendSize.x,n=new V(0,i.boundingBox.extendSize.y,0);return new t(i.boundingBox.center.add(n),i.boundingBox.center.subtract(n),r,e.getScene())},t}(MA),FA=function(e){function t(t,i,r,n){return e.call(this,{type:EA.BOX,parameters:{center:t,rotation:i,extents:r}},n)||this}return m(t,e),t.FromMesh=function(e){var i=e.getBoundingInfo(),r=i.boundingBox.center,n=i.boundingBox.extendSize.scale(2);return new t(r,G.Identity(),n,e.getScene())},t}(MA),LA=function(e){function t(t,i){return e.call(this,{type:EA.CONVEX_HULL,parameters:{mesh:t}},i)||this}return m(t,e),t}(MA),wA=function(e){function t(t,i){return e.call(this,{type:EA.MESH,parameters:{mesh:t}},i)||this}return m(t,e),t}(MA),BA=function(e){function t(t){return e.call(this,{type:EA.CONTAINER,parameters:{}},t)||this}return m(t,e),t}(MA),UA=function(){function e(e,t,i){if(this._pluginData=void 0,!i)throw new Error("Missing scene parameter for constraint constructor.");var r=i.getPhysicsEngine();if(!r)throw new Error("No Physics Engine available.");if(2!=r.getPluginVersion())throw new Error("Plugin version is incorrect. Expected version 2.");var n=r.getPhysicsPlugin();if(!n)throw new Error("No Physics Plugin available.");this._physicsPlugin=n,this._options=t,this._type=e}return Object.defineProperty(e.prototype,"type",{get:function(){return this._type},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isEnabled",{get:function(){return this._physicsPlugin.getEnabled(this)},set:function(e){this._physicsPlugin.setEnabled(this,e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isCollisionsEnabled",{get:function(){return this._physicsPlugin.getCollisionsEnabled(this)},set:function(e){this._physicsPlugin.setCollisionsEnabled(this,e)},enumerable:!1,configurable:!0}),e.prototype.getBodiesUsingConstraint=function(){return this._physicsPlugin.getBodiesUsingConstraint(this)},e.prototype.dispose=function(){this._physicsPlugin.disposeConstraint(this)},e}(),VA=function(){},kA=function(e){function t(t,i,r){var n=e.call(this,TA.SIX_DOF,t,r)||this;return n.limits=i,n}return m(t,e),t.prototype.setAxisFriction=function(e,t){this._physicsPlugin.setAxisFriction(this,e,t)},t.prototype.getAxisFriction=function(e){return this._physicsPlugin.getAxisFriction(this,e)},t.prototype.setAxisMode=function(e,t){this._physicsPlugin.setAxisMode(this,e,t)},t.prototype.getAxisMode=function(e){return this._physicsPlugin.getAxisMode(this,e)},t.prototype.setAxisMinLimit=function(e,t){this._physicsPlugin.setAxisMinLimit(this,e,t)},t.prototype.getAxisMinLimit=function(e){return this._physicsPlugin.getAxisMinLimit(this,e)},t.prototype.setAxisMaxLimit=function(e,t){this._physicsPlugin.setAxisMaxLimit(this,e,t)},t.prototype.getAxisMaxLimit=function(e){return this._physicsPlugin.getAxisMaxLimit(this,e)},t.prototype.setAxisMotorType=function(e,t){this._physicsPlugin.setAxisMotorType(this,e,t)},t.prototype.getAxisMotorType=function(e){return this._physicsPlugin.getAxisMotorType(this,e)},t.prototype.setAxisMotorTarget=function(e,t){this._physicsPlugin.setAxisMotorTarget(this,e,t)},t.prototype.getAxisMotorTarget=function(e){return this._physicsPlugin.getAxisMotorTarget(this,e)},t.prototype.setAxisMotorMaxForce=function(e,t){this._physicsPlugin.setAxisMotorMaxForce(this,e,t)},t.prototype.getAxisMotorMaxForce=function(e){return this._physicsPlugin.getAxisMotorMaxForce(this,e)},t}(UA),GA=function(e){function t(t,i,r,n,o){return e.call(this,TA.BALL_AND_SOCKET,{pivotA:t,pivotB:i,axisA:r,axisB:n},o)||this}return m(t,e),t}(UA),zA=function(e){function t(t,i){return e.call(this,TA.DISTANCE,{maxDistance:t},i)||this}return m(t,e),t}(UA),WA=function(e){function t(t,i,r,n,o){return e.call(this,TA.HINGE,{pivotA:t,pivotB:i,axisA:r,axisB:n},o)||this}return m(t,e),t}(UA),HA=function(e){function t(t,i,r,n,o){return e.call(this,TA.SLIDER,{pivotA:t,pivotB:i,axisA:r,axisB:n},o)||this}return m(t,e),t}(UA),XA=function(e){function t(t,i,r,n,o){return e.call(this,TA.LOCK,{pivotA:t,pivotB:i,axisA:r,axisB:n},o)||this}return m(t,e),t}(UA),jA=function(e){function t(t,i,r,n,o){return e.call(this,TA.PRISMATIC,{pivotA:t,pivotB:i,axisA:r,axisB:n},o)||this}return m(t,e),t}(UA),YA=function(e){function t(t,i,r,n,o,a,s,l,c){return e.call(this,{pivotA:t,pivotB:i,axisA:r,axisB:n},[{axis:bA.LINEAR_DISTANCE,minLimit:o,maxLimit:a,stiffness:s,damping:l}],c)||this}return m(t,e),t}(kA);!function(e){e[e.GEOMETRIC_MEAN=0]="GEOMETRIC_MEAN",e[e.MINIMUM=1]="MINIMUM",e[e.MAXIMUM=2]="MAXIMUM",e[e.ARITHMETIC_MEAN=3]="ARITHMETIC_MEAN",e[e.MULTIPLY=4]="MULTIPLY"}(PA||(PA={}));var KA=function(){function e(e,t,i,r){void 0===i&&(i={mass:0});var n,o=this;if(this.transformNode=e,this.type=t,this._options=i,this._scene=r,this._disposeShapeWhenDisposed=!0,this.transformNode){var a=e;if(this.transformNode.parent&&0!==this._options.mass&&a.hasThinInstances&&ae.Warn("A physics body has been created for an object which has a parent and thin instances. Babylon physics currently works in local space so unexpected issues may occur."),!this._scene&&e.getScene&&(this._scene=e.getScene()),this._scene){this._options.mass=void 0===i.mass?0:i.mass,this._options.friction=void 0===i.friction?.2:i.friction,this._options.restitution=void 0===i.restitution?.2:i.restitution;var s=0===this._options.mass?AA.STATIC:AA.DYNAMIC,l=null!==(n=this._options.startAsleep)&&void 0!==n&&n;this.body=new IA(e,s,l,this._scene),this._addSizeOptions(),t.getClassName&&"PhysicsShape"===t.getClassName()?(this.shape=t,this._disposeShapeWhenDisposed=!1):this.shape=new MA({type:t,parameters:this._options},this._scene),this._options.isTriggerShape&&(this.shape.isTrigger=!0),this.material={friction:this._options.friction,restitution:this._options.restitution},this.body.shape=this.shape,this.shape.material=this.material,this.body.setMassProperties({mass:this._options.mass}),this._nodeDisposeObserver=this.transformNode.onDisposeObservable.add((function(){o.dispose()}))}}else ae.Error("No object was provided. A physics object is obligatory")}return e.prototype._getObjectBoundingBox=function(){return this.transformNode.getRawBoundingInfo?this.transformNode.getRawBoundingInfo().boundingBox:new to(new V(-.5,-.5,-.5),new V(.5,.5,.5))},e.prototype._hasVertices=function(e){return(null==e?void 0:e.getTotalVertices())>0},e.prototype._addSizeOptions=function(){var e,t,i,r,n,o,a,s;this.transformNode.computeWorldMatrix(!0);var l=this._getObjectBoundingBox(),c=H.Vector3[0];c.copyFrom(l.extendSize),c.scaleInPlace(2),c.multiplyInPlace(this.transformNode.scaling),c.x=Math.abs(c.x),c.y=Math.abs(c.y),c.z=Math.abs(c.z);var u=H.Vector3[1];if(u.copyFrom(l.minimum),u.multiplyInPlace(this.transformNode.scaling),!this._options.center){var h=new V;h.copyFrom(l.center),h.multiplyInPlace(this.transformNode.scaling),this._options.center=h}switch(this.type){case EA.SPHERE:!this._options.radius&&j.WithinEpsilon(c.x,c.y,1e-4)&&j.WithinEpsilon(c.x,c.z,1e-4)?this._options.radius=c.x/2:this._options.radius||(ae.Warn("Non uniform scaling is unsupported for sphere shapes. Setting the radius to the biggest bounding box extent."),this._options.radius=Math.max(c.x,c.y,c.z)/2);break;case EA.CAPSULE:var d=c.x/2;this._options.radius=null!==(e=this._options.radius)&&void 0!==e?e:d,this._options.pointA=null!==(t=this._options.pointA)&&void 0!==t?t:new V(0,u.y+d,0),this._options.pointB=null!==(i=this._options.pointB)&&void 0!==i?i:new V(0,u.y+c.y-d,0);break;case EA.CYLINDER:d=c.x/2,this._options.radius=null!==(r=this._options.radius)&&void 0!==r?r:d,this._options.pointA=null!==(n=this._options.pointA)&&void 0!==n?n:new V(0,u.y,0),this._options.pointB=null!==(o=this._options.pointB)&&void 0!==o?o:new V(0,u.y+c.y,0);break;case EA.MESH:case EA.CONVEX_HULL:if(!this._options.mesh&&this._hasVertices(this.transformNode))this._options.mesh=this.transformNode;else if(!this._options.mesh||!this._hasVertices(this._options.mesh))throw new Error("No valid mesh was provided for mesh or convex hull shape parameter. Please provide a mesh with valid geometry (number of vertices greater than 0).");break;case EA.BOX:this._options.extents=null!==(a=this._options.extents)&&void 0!==a?a:new V(c.x,c.y,c.z),this._options.rotation=null!==(s=this._options.rotation)&&void 0!==s?s:G.Identity()}},e.prototype.dispose=function(){this._nodeDisposeObserver&&(this.body.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver),this._nodeDisposeObserver=null),this.body.dispose(),this._disposeShapeWhenDisposed&&this.shape.dispose()},e}(),QA=function(){},qA=function(){function e(e,t,i){this._boxConfigs=new Array,this._joints=new Array,this._bones=new Array,this._initialRotation=new Array,this._initialRotation2=new Array,this._boneNames=[],this._transforms=new Array,this._aggregates=new Array,this._ragdollMode=!1,this._rootBoneName="",this._rootBoneIndex=-1,this._mass=10,this._restitution=0,this.pauseSync=!1,this._defaultJoint=TA.HINGE,this._defaultJointMin=-90,this._defaultJointMax=90,this._skeleton=e,this._scene=e.getScene(),this._rootTransformNode=t,this._config=i,this._boxConfigs=[],this._putBoxesInBoneCenter=!1,this._defaultJoint=TA.HINGE,this._init()}return e.prototype.getAggregate=function(e){return e<0||e>=this._aggregates.length?this._aggregates[this._rootBoneIndex]:this._aggregates[e]},e.prototype._createColliders=function(){var e,t,i;this._rootTransformNode.computeWorldMatrix(),this._skeleton.computeAbsoluteMatrices(!0),this._skeleton.prepare(!0);for(var r=this._config,n=0;n<r.length;n++)for(var o=void 0!==r[n].bone?[r[n].bone]:r[n].bones,a=0;a<o.length;a++){var s=this._skeleton.bones[this._skeleton.getBoneIndexByName(o[a])];if(null==s)return;var l={width:this._config[n].width,depth:this._config[n].depth,height:this._config[n].height,size:this._config[n].size};l.width=null!==(e=l.width)&&void 0!==e?e:l.size,l.depth=null!==(t=l.depth)&&void 0!==t?t:l.size,l.height=null!==(i=l.height)&&void 0!==i?i:l.size;var c=new Fo(o[a]+"_transform",this._scene);l.joint=void 0!==r[n].joint?r[n].joint:this._defaultJoint,l.rotationAxis=void 0!==r[n].rotationAxis?r[n].rotationAxis:_n.X,l.min=void 0!==r[n].min?r[n].min:this._defaultJointMin,l.max=void 0!==r[n].max?r[n].max:this._defaultJointMax;var u=0;void 0!==r[n].putBoxInBoneCenter&&r[n].putBoxInBoneCenter||this._putBoxesInBoneCenter?(void 0===s.length&&ae.Log("The length property is not defined for bone "+s.name),u=s.length/2):void 0!==r[n].boxOffset&&(u=r[n].boxOffset),l.boxOffset=u;var h=void 0!==r[n].boneOffsetAxis?r[n].boneOffsetAxis:_n.Y,d=s.getDirection(h,this._rootTransformNode);l.boneOffsetAxis=h,c.position=s.getAbsolutePosition(this._rootTransformNode).add(d.scale(u));var p=void 0!==r[n].mass?r[n].mass:this._mass,f=void 0!==r[n].restitution?r[n].restitution:this._restitution,_=new KA(c,EA.BOX,{mass:p,restitution:f,friction:.6,extents:new V(l.width,l.height,l.depth)},this._scene);_.body.setCollisionCallbackEnabled(!0),_.body.disablePreStep=!1,_.body.setMotionType(AA.ANIMATED),this._aggregates.push(_),this._bones.push(s),this._boneNames.push(s.name),this._transforms.push(c),this._boxConfigs.push(l),this._initialRotation.push(s.getRotationQuaternion(dn.WORLD,this._rootTransformNode)),this._initialRotation2.push(s.getRotationQuaternion(dn.WORLD))}},e.prototype._initJoints=function(){this._rootTransformNode.computeWorldMatrix();for(var e=0;e<this._bones.length;e++)if(e!=this._rootBoneIndex){var t=this._findNearestParent(e);if(null==t)return void ae.Warn("Couldn't find a nearest parent bone in the configs for bone called "+this._boneNames[e]);var i=this._boneNames.indexOf(t.name),r=this._bones[e].getAbsolutePosition(this._rootTransformNode).subtract(this._transforms[i].position),n=this._transforms[i].computeWorldMatrix(),o=z.Invert(n);r=V.TransformCoordinates(this._bones[e].getAbsolutePosition(this._rootTransformNode),o);var a=this._bones[e].getAbsolutePosition(this._rootTransformNode),s=this._transforms[e].position.clone(),l=a.subtract(s),c=new UA(TA.BALL_AND_SOCKET,{pivotA:r,pivotB:l,axisA:this._boxConfigs[e].rotationAxis,axisB:this._boxConfigs[e].rotationAxis,collision:!1},this._scene);this._aggregates[i].body.addConstraint(this._aggregates[e].body,c),c.isEnabled=!1,this._joints.push(c)}},e.prototype._syncBonesToPhysics=function(){for(var e,t=this._rootTransformNode.getWorldMatrix(),i=0;i<this._bones.length;i++){var r=this._aggregates[i].transformNode,n=this._bones[i].getAbsolutePosition();V.TransformCoordinatesToRef(n,t,r.position),this._bones[i].getDirectionToRef(this._boxConfigs[i].boneOffsetAxis,this._rootTransformNode,H.Vector3[0]),H.Vector3[0].scaleInPlace(null!==(e=this._boxConfigs[i].boxOffset)&&void 0!==e?e:0),r.position.addInPlace(H.Vector3[0]),this._setBoneOrientationToBody(i)}},e.prototype._setBoneOrientationToBody=function(e){var t=this._aggregates[e].transformNode,i=this._bones[e];this._initialRotation[e].conjugateToRef(H.Quaternion[0]),i.getRotationQuaternionToRef(dn.WORLD,this._rootTransformNode,H.Quaternion[1]),H.Quaternion[1].multiplyToRef(H.Quaternion[0],t.rotationQuaternion),t.rotationQuaternion.normalize()},e.prototype._syncBonesAndBoxes=function(){if(!this.pauseSync)if(this._ragdollMode){this._setBodyOrientationToBone(this._rootBoneIndex);var e=this._aggregates[this._rootBoneIndex].body.transformNode.position;this._rootTransformNode.getWorldMatrix().invertToRef(H.Matrix[0]),V.TransformCoordinatesToRef(e,H.Matrix[0],H.Vector3[0]),this._bones[this._rootBoneIndex].setAbsolutePosition(H.Vector3[0]);for(var t=0;t<this._bones.length;t++)t!=this._rootBoneIndex&&this._setBodyOrientationToBone(t)}else this._syncBonesToPhysics()},e.prototype._setBodyOrientationToBone=function(e){var t,i,r,n=null!==(t=this._rootTransformNode.rotationQuaternion)&&void 0!==t?t:G.FromEulerAngles(this._rootTransformNode.rotation.x,this._rootTransformNode.rotation.y,this._rootTransformNode.rotation.z),o=this._initialRotation2[e],a=null===(r=null===(i=this._aggregates[e].body)||void 0===i?void 0:i.transformNode)||void 0===r?void 0:r.rotationQuaternion;n.multiplyToRef(o,H.Quaternion[1]),a.multiplyToRef(H.Quaternion[1],H.Quaternion[0]),this._bones[e].setRotationQuaternion(H.Quaternion[0],dn.WORLD,this._rootTransformNode)},e.prototype._defineRootBone=function(){var e=this._skeleton.getChildren();return 1!=e.length?(ae.Log("Ragdoll creation failed: there can only be one root in the skeleton."),!1):(this._rootBoneName=e[0].name,this._rootBoneIndex=this._boneNames.indexOf(this._rootBoneName),-1!=this._rootBoneIndex||(ae.Log("Ragdoll creation failed: the array boneNames doesn't have the root bone. The root bone is "+this._skeleton.getChildren()),!1))},e.prototype._findNearestParent=function(e){var t=this._bones[e].getParent();do{if(null!=t&&this._boneNames.includes(t.name))break;t=null==t?void 0:t.getParent()}while(null!=t);return t},e.prototype._init=function(){var e=this;this._createColliders(),this._defineRootBone()&&(this._initJoints(),this._scene.registerBeforeRender((function(){e._syncBonesAndBoxes()})),this._syncBonesToPhysics())},e.prototype.ragdoll=function(){this._ragdollMode=!0,this._skeleton.bones.forEach((function(e){e.linkTransformNode(null)}));for(var e=0;e<this._joints.length;e++)this._joints[e].isEnabled=!0;for(e=0;e<this._aggregates.length;e++)this._aggregates[e].body.setMotionType(AA.DYNAMIC)},e.prototype.dispose=function(){this._aggregates.forEach((function(e){e.dispose()}))},e}(),ZA=function(){function e(e,t,i){this._vertices=[],this._indices=[],this._isRightHanded=i.useRightHandedSystem,this._collectIndices=t}return e.prototype.addNodeMeshes=function(e,t){var i=this;e.computeWorldMatrix(!0);var r=H.Matrix[0];if(z.ScalingToRef(e.absoluteScaling.x,e.absoluteScaling.y,e.absoluteScaling.z,r),e instanceof Fa?this._addMesh(e,r):e instanceof La&&this._addMesh(e.sourceMesh,r),t){var n=H.Matrix[1];e.computeWorldMatrix().invertToRef(n);var o=H.Matrix[2];n.multiplyToRef(r,o),e.getChildMeshes(!1).filter((function(e){return!e.physicsBody})).forEach((function(e){var t=e.computeWorldMatrix(),r=H.Matrix[3];t.multiplyToRef(o,r),e instanceof Fa?i._addMesh(e,r):e instanceof La&&i._addMesh(e.sourceMesh,r)}))}},e.prototype._addMesh=function(e,t){for(var i=e.getVerticesData(Nr.PositionKind)||[],r=i.length/3,n=this._vertices.length,o=0;o<r;o++){var a=new V(i[3*o+0],i[3*o+1],i[3*o+2]);this._vertices.push(V.TransformCoordinates(a,t))}if(this._collectIndices){var s=e.getIndices();if(s)for(var l=0;l<s.length;l+=3)this._isRightHanded?(this._indices.push(s[l+0]+n),this._indices.push(s[l+1]+n),this._indices.push(s[l+2]+n)):(this._indices.push(s[l+2]+n),this._indices.push(s[l+1]+n),this._indices.push(s[l+0]+n))}},e.prototype.getVertices=function(e){for(var t=3*this._vertices.length,i=4*t,r=e._malloc(i),n=new Float32Array(e.HEAPU8.buffer,r,t),o=0;o<this._vertices.length;o++)n[3*o+0]=this._vertices[o].x,n[3*o+1]=this._vertices[o].y,n[3*o+2]=this._vertices[o].z;return{offset:r,numObjects:t}},e.prototype.freeBuffer=function(e,t){e._free(t.offset)},e.prototype.getTriangles=function(e){for(var t=4*this._indices.length,i=e._malloc(t),r=new Int32Array(e.HEAPU8.buffer,i,this._indices.length),n=0;n<this._indices.length;n++)r[n]=this._indices[n];return{offset:i,numObjects:this._indices.length}},e}(),JA=function(e){this.hpBodyId=e,this.userMassProps={centerOfMass:void 0,mass:void 0,inertia:void 0,inertiaOrientation:void 0}},$A=function(){this.bodyId=BigInt(0),this.position=new V,this.normal=new V},eC=function(){function e(){this.contactOnA=new $A,this.contactOnB=new $A,this.impulseApplied=0,this.type=0}return e.readToRef=function(e,t,i){var r=new Int32Array(e,t),n=new Float32Array(e,t);i.contactOnA.bodyId=BigInt(r[2]),i.contactOnA.position.set(n[10],n[11],n[12]),i.contactOnA.normal.set(n[13],n[14],n[15]),i.contactOnB.bodyId=BigInt(r[18]),i.contactOnB.position.set(n[26],n[27],n[28]),i.contactOnB.normal.set(n[29],n[30],n[31]),i.impulseApplied=n[34],i.type=r[0]},e}(),tC=function(){function e(){this.bodyIdA=BigInt(0),this.bodyIdB=BigInt(0),this.type=0}return e.readToRef=function(e,t,i){var r=new Int32Array(e,t);i.type=r[0],i.bodyIdA=BigInt(r[2]),i.bodyIdB=BigInt(r[6])},e}(),iC=function(){function e(e,t){void 0===e&&(e=!0),void 0===t&&(t=HK),this._useDeltaForWorldStep=e,this._hknp={},this.name="HavokPlugin",this._fixedTimeStep=1/60,this._tmpVec3=C.BuildArray(3,V.Zero),this._bodies=new Map,this._shapes=new Map,this._bodyCollisionObservable=new Map,this._constraintToBodyIdPair=new Map,this._bodyCollisionEndedObservable=new Map,this.onCollisionObservable=new f,this.onCollisionEndedObservable=new f,this.onTriggerCollisionObservable=new f,"function"!=typeof t?(this._hknp=t,this.isSupported()?(this.world=this._hknp.HP_World_Create()[1],this._queryCollector=this._hknp.HP_QueryCollector_Create(1)[1]):ae.Error("Havok is not available. Please make sure you included the js file.")):ae.Error("Havok is not ready. Please make sure you await HK() before using the plugin.")}return e.prototype.isSupported=function(){return void 0!==this._hknp},e.prototype.setGravity=function(e){this._hknp.HP_World_SetGravity(this.world,this._bVecToV3(e))},e.prototype.setTimeStep=function(e){this._fixedTimeStep=e},e.prototype.getTimeStep=function(){return this._fixedTimeStep},e.prototype.executeStep=function(e,t){for(var i=0,r=t;i<r.length;i++)(s=r[i]).disablePreStep||this.setPhysicsBodyTransformation(s,s.transformNode);var n=this._useDeltaForWorldStep?e:this._fixedTimeStep;this._hknp.HP_World_SetIdealStepTime(this.world,n),this._hknp.HP_World_Step(this.world,n),this._bodyBuffer=this._hknp.HP_World_GetBodyBuffer(this.world)[1];for(var o=0,a=t;o<a.length;o++){var s;(s=a[o]).disableSync||this.sync(s)}this._notifyCollisions(),this._notifyTriggers()},e.prototype.getPluginVersion=function(){return 2},e.prototype.initBody=function(e,t,i,r){e._pluginData=new JA(this._hknp.HP_Body_Create()[1]),this._internalSetMotionType(e._pluginData,t);var n=[this._bVecToV3(i),this._bQuatToV4(r)];this._hknp.HP_Body_SetQTransform(e._pluginData.hpBodyId,n),this._hknp.HP_World_AddBody(this.world,e._pluginData.hpBodyId,e.startAsleep),this._bodies.set(e._pluginData.hpBodyId[0],{body:e,index:0})},e.prototype.removeBody=function(e){if(e._pluginDataInstances&&e._pluginDataInstances.length>0)for(var t=0,i=e._pluginDataInstances;t<i.length;t++){var r=i[t];this._bodyCollisionObservable.delete(r.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,r.hpBodyId),this._bodies.delete(r.hpBodyId[0])}e._pluginData&&(this._bodyCollisionObservable.delete(e._pluginData.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,e._pluginData.hpBodyId),this._bodies.delete(e._pluginData.hpBodyId[0]))},e.prototype.initBodyInstances=function(e,t,i){var r,n,o=this,a=null!==(n=null===(r=i._thinInstanceDataStorage)||void 0===r?void 0:r.instancesCount)&&void 0!==n?n:0,s=i._thinInstanceDataStorage.matrixData;s&&(this._createOrUpdateBodyInstances(e,t,s,0,a,!1),e._pluginDataInstances.forEach((function(t,i){o._bodies.set(t.hpBodyId[0],{body:e,index:i})})))},e.prototype._createOrUpdateBodyInstances=function(e,t,i,r,n,o){for(var a=H.Quaternion[0],s=z.Identity(),l=r;l<n;l++){var c,u=[i[16*l+12],i[16*l+13],i[16*l+14]];c=o?e._pluginDataInstances[l].hpBodyId:this._hknp.HP_Body_Create()[1],s.setRowFromFloats(0,i[16*l+0],i[16*l+1],i[16*l+2],0),s.setRowFromFloats(1,i[16*l+4],i[16*l+5],i[16*l+6],0),s.setRowFromFloats(2,i[16*l+8],i[16*l+9],i[16*l+10],0),G.FromRotationMatrixToRef(s,a);var h=[u,[a.x,a.y,a.z,a.w]];if(this._hknp.HP_Body_SetQTransform(c,h),!o){var d=new JA(c);e._pluginDataInstances.length&&(d.userMassProps=e._pluginDataInstances[0].userMassProps),this._internalSetMotionType(d,t),this._internalUpdateMassProperties(d),e._pluginDataInstances.push(d),this._hknp.HP_World_AddBody(this.world,c,e.startAsleep),d.worldTransformOffset=this._hknp.HP_Body_GetWorldTransformOffset(c)[1]}}},e.prototype.updateBodyInstances=function(e,t){var i,r,n,o=null!==(r=null===(i=t._thinInstanceDataStorage)||void 0===i?void 0:i.instancesCount)&&void 0!==r?r:0,a=t._thinInstanceDataStorage.matrixData;if(a){var s=e._pluginDataInstances.length,l=this.getMotionType(e);if(o>s){this._createOrUpdateBodyInstances(e,l,a,s,o,!1);var c=this._hknp.HP_Body_GetShape(e._pluginDataInstances[0].hpBodyId)[1];c[0]||(c[0]=null===(n=e.shape)||void 0===n?void 0:n._pluginData[0]);for(var u=s;u<o;u++)this._hknp.HP_Body_SetShape(e._pluginDataInstances[u].hpBodyId,c),this._internalUpdateMassProperties(e._pluginDataInstances[u]),this._bodies.set(e._pluginDataInstances[u].hpBodyId[0],{body:e,index:u})}else if(o<s){var h=s-o;for(u=0;u<h;u++){var d=e._pluginDataInstances.pop();this._bodies.delete(d.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,d.hpBodyId),this._hknp.HP_Body_Release(d.hpBodyId)}this._createOrUpdateBodyInstances(e,l,a,0,o,!0)}}},e.prototype.sync=function(e){this.syncTransform(e,e.transformNode)},e.prototype.syncTransform=function(e,t){var i;if(e._pluginDataInstances.length){var r=t,n=r._thinInstanceDataStorage.matrixData;if(!n)return;for(var o=e._pluginDataInstances.length,a=0;a<o;a++){for(var s=e._pluginDataInstances[a].worldTransformOffset,l=new Float32Array(this._hknp.HEAPU8.buffer,this._bodyBuffer+s,16),c=16*a,u=0;u<15;u++)3&~u&&(n[c+u]=l[u]);n[c+15]=1}r.thinInstanceBufferUpdated("matrix")}else try{var h=this._hknp.HP_Body_GetQTransform(e._pluginData.hpBodyId)[1],d=h[0],p=h[1],f=H.Quaternion[0];f.set(p[0],p[1],p[2],p[3]);var _=t.parent;if(_&&!_.getWorldMatrix().isIdentity()){_.computeWorldMatrix(!0),f.normalize();var m=H.Matrix[0],g=H.Vector3[0];g.copyFromFloats(d[0],d[1],d[2]),z.ComposeToRef(t.absoluteScaling,f,g,m);var v=H.Matrix[1];_.getWorldMatrix().invertToRef(v);var y=H.Matrix[2];m.multiplyToRef(v,y),y.decomposeToTransformNode(t),null===(i=t.rotationQuaternion)||void 0===i||i.normalize()}else t.position.set(d[0],d[1],d[2]),t.rotationQuaternion?t.rotationQuaternion.copyFrom(f):f.toEulerAnglesToRef(t.rotation)}catch(e){ae.Error("Syncing transform failed for node ".concat(t.name,": ").concat(e.message,"..."))}},e.prototype.setShape=function(e,t){var i,r,n,o=t&&t._pluginData?t._pluginData:BigInt(0);if(!(e.transformNode instanceof Fa&&(null===(i=e.transformNode._thinInstanceDataStorage)||void 0===i?void 0:i.matrixData)))return this._hknp.HP_Body_SetShape(e._pluginData.hpBodyId,o),void this._internalUpdateMassProperties(e._pluginData);for(var a=null!==(n=null===(r=e.transformNode._thinInstanceDataStorage)||void 0===r?void 0:r.instancesCount)&&void 0!==n?n:0,s=0;s<a;s++)this._hknp.HP_Body_SetShape(e._pluginDataInstances[s].hpBodyId,o),this._internalUpdateMassProperties(e._pluginDataInstances[s])},e.prototype._getPluginReference=function(e,t){var i;return(null===(i=e._pluginDataInstances)||void 0===i?void 0:i.length)?e._pluginDataInstances[null!=t?t:0]:e._pluginData},e.prototype.getShape=function(e){var t=this._getPluginReference(e),i=this._hknp.HP_Body_GetShape(t.hpBodyId)[1];if(0!=i){var r=e.transformNode.getScene();return new MA({pluginData:i},r)}return null},e.prototype.getShapeType=function(e){return e.type?e.type:this._hknp.HP_Shape_GetType(e._pluginData)},e.prototype.setEventMask=function(e,t,i){var r=this;this._applyToBodyOrInstances(e,(function(e){r._hknp.HP_Body_SetEventMask(e.hpBodyId,t)}),i)},e.prototype.getEventMask=function(e,t){var i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetEventMask(i.hpBodyId)[1]},e.prototype._fromMassPropertiesTuple=function(e){return{centerOfMass:V.FromArray(e[0]),mass:e[1],inertia:V.FromArray(e[2]),inertiaOrientation:G.FromArray(e[3])}},e.prototype._internalUpdateMassProperties=function(e){var t=this._internalComputeMassProperties(e),i=e.userMassProps;i.centerOfMass&&(t[0]=i.centerOfMass.asArray()),null!=i.mass&&(t[1]=i.mass),i.inertia&&(t[2]=i.inertia.asArray()),i.inertiaOrientation&&(t[3]=i.inertiaOrientation.asArray()),this._hknp.HP_Body_SetMassProperties(e.hpBodyId,t)},e.prototype._internalSetMotionType=function(e,t){switch(t){case AA.STATIC:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.STATIC);break;case AA.ANIMATED:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.KINEMATIC);break;case AA.DYNAMIC:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.DYNAMIC)}},e.prototype.setMotionType=function(e,t,i){var r=this;this._applyToBodyOrInstances(e,(function(e){r._internalSetMotionType(e,t)}),i)},e.prototype.getMotionType=function(e,t){var i=this._getPluginReference(e,t),r=this._hknp.HP_Body_GetMotionType(i.hpBodyId)[1];switch(r){case this._hknp.MotionType.STATIC:return AA.STATIC;case this._hknp.MotionType.KINEMATIC:return AA.ANIMATED;case this._hknp.MotionType.DYNAMIC:return AA.DYNAMIC}throw new Error("Unknown motion type: "+r)},e.prototype.setActivationControl=function(e,t){switch(t){case CA.ALWAYS_ACTIVE:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.ALWAYS_ACTIVE);break;case CA.ALWAYS_INACTIVE:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.ALWAYS_INACTIVE);break;case CA.SIMULATION_CONTROLLED:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.SIMULATION_CONTROLLED)}},e.prototype._internalComputeMassProperties=function(e){var t=this._hknp.HP_Body_GetShape(e.hpBodyId);if(t[0]==this._hknp.Result.RESULT_OK){var i=this._hknp.HP_Shape_BuildMassProperties(t[1]);if(i[0]==this._hknp.Result.RESULT_OK)return i[1]}return[[0,0,0],1,[1,1,1],[0,0,0,1]]},e.prototype.computeMassProperties=function(e,t){var i=this._getPluginReference(e,t),r=this._internalComputeMassProperties(i);return this._fromMassPropertiesTuple(r)},e.prototype.setMassProperties=function(e,t,i){var r=this;this._applyToBodyOrInstances(e,(function(e){e.userMassProps=t,r._internalUpdateMassProperties(e)}),i)},e.prototype.getMassProperties=function(e,t){var i=this._getPluginReference(e,t),r=this._hknp.HP_Body_GetMassProperties(i.hpBodyId)[1];return this._fromMassPropertiesTuple(r)},e.prototype.setLinearDamping=function(e,t,i){var r=this;this._applyToBodyOrInstances(e,(function(e){r._hknp.HP_Body_SetLinearDamping(e.hpBodyId,t)}),i)},e.prototype.getLinearDamping=function(e,t){var i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetLinearDamping(i.hpBodyId)[1]},e.prototype.setAngularDamping=function(e,t,i){var r=this;this._applyToBodyOrInstances(e,(function(e){r._hknp.HP_Body_SetAngularDamping(e.hpBodyId,t)}),i)},e.prototype.getAngularDamping=function(e,t){var i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetAngularDamping(i.hpBodyId)[1]},e.prototype.setLinearVelocity=function(e,t,i){var r=this;this._applyToBodyOrInstances(e,(function(e){r._hknp.HP_Body_SetLinearVelocity(e.hpBodyId,r._bVecToV3(t))}),i)},e.prototype.getLinearVelocityToRef=function(e,t,i){var r=this._getPluginReference(e,i),n=this._hknp.HP_Body_GetLinearVelocity(r.hpBodyId)[1];this._v3ToBvecRef(n,t)},e.prototype._applyToBodyOrInstances=function(e,t,i){var r;if((null===(r=e._pluginDataInstances)||void 0===r?void 0:r.length)>0&&void 0===i)for(var n=0;n<e._pluginDataInstances.length;n++)t(e._pluginDataInstances[n]);else t(this._getPluginReference(e,i))},e.prototype.applyImpulse=function(e,t,i,r){var n=this;this._applyToBodyOrInstances(e,(function(e){n._hknp.HP_Body_ApplyImpulse(e.hpBodyId,n._bVecToV3(i),n._bVecToV3(t))}),r)},e.prototype.applyAngularImpulse=function(e,t,i){var r=this;this._applyToBodyOrInstances(e,(function(e){r._hknp.HP_Body_ApplyAngularImpulse(e.hpBodyId,r._bVecToV3(t))}),i)},e.prototype.applyForce=function(e,t,i,r){t.scaleToRef(this.getTimeStep(),this._tmpVec3[0]),this.applyImpulse(e,this._tmpVec3[0],i,r)},e.prototype.setAngularVelocity=function(e,t,i){var r=this;this._applyToBodyOrInstances(e,(function(e){r._hknp.HP_Body_SetAngularVelocity(e.hpBodyId,r._bVecToV3(t))}),i)},e.prototype.getAngularVelocityToRef=function(e,t,i){var r=this._getPluginReference(e,i),n=this._hknp.HP_Body_GetAngularVelocity(r.hpBodyId)[1];this._v3ToBvecRef(n,t)},e.prototype.setPhysicsBodyTransformation=function(e,t){var i=e.transformNode;if(e.numInstances>0){var r=i._thinInstanceDataStorage.matrixData;if(!r)return;var n=e.numInstances;this._createOrUpdateBodyInstances(e,e.getMotionType(),r,0,n,!0)}else this._hknp.HP_Body_SetQTransform(e._pluginData.hpBodyId,this._getTransformInfos(t))},e.prototype.setTargetTransform=function(e,t,i,r){var n=this;this._applyToBodyOrInstances(e,(function(e){n._hknp.HP_Body_SetTargetQTransform(e.hpBodyId,[n._bVecToV3(t),n._bQuatToV4(i)])}),r)},e.prototype.setGravityFactor=function(e,t,i){var r=this;this._applyToBodyOrInstances(e,(function(e){r._hknp.HP_Body_SetGravityFactor(e.hpBodyId,t)}),i)},e.prototype.getGravityFactor=function(e,t){var i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetGravityFactor(i.hpBodyId)[1]},e.prototype.disposeBody=function(e){if(e._pluginDataInstances&&e._pluginDataInstances.length>0)for(var t=0,i=e._pluginDataInstances;t<i.length;t++){var r=i[t];this._hknp.HP_Body_Release(r.hpBodyId),r.hpBodyId=void 0}e._pluginData&&(this._hknp.HP_Body_Release(e._pluginData.hpBodyId),e._pluginData.hpBodyId=void 0)},e.prototype.initShape=function(e,t,i){switch(t){case EA.SPHERE:var r=i.radius||1,n=i.center?this._bVecToV3(i.center):[0,0,0];e._pluginData=this._hknp.HP_Shape_CreateSphere(n,r)[1];break;case EA.BOX:var o=i.rotation?this._bQuatToV4(i.rotation):[0,0,0,1],a=i.extents?this._bVecToV3(i.extents):[1,1,1];n=i.center?this._bVecToV3(i.center):[0,0,0],e._pluginData=this._hknp.HP_Shape_CreateBox(n,o,a)[1];break;case EA.CAPSULE:var s=i.pointA?this._bVecToV3(i.pointA):[0,0,0],l=i.pointB?this._bVecToV3(i.pointB):[0,1,0];r=i.radius||0,e._pluginData=this._hknp.HP_Shape_CreateCapsule(s,l,r)[1];break;case EA.CONTAINER:e._pluginData=this._hknp.HP_Shape_CreateContainer()[1];break;case EA.CYLINDER:s=i.pointA?this._bVecToV3(i.pointA):[0,0,0],l=i.pointB?this._bVecToV3(i.pointB):[0,1,0],r=i.radius||0,e._pluginData=this._hknp.HP_Shape_CreateCylinder(s,l,r)[1];break;case EA.CONVEX_HULL:case EA.MESH:var c=i.mesh;if(!c)throw new Error("No mesh provided to create physics shape.");var u=!!i.includeChildMeshes,h=t!=EA.CONVEX_HULL,d=new ZA(c,h,null==c?void 0:c.getScene());d.addNodeMeshes(c,u);var p=d.getVertices(this._hknp),f=p.numObjects/3;if(t==EA.CONVEX_HULL)e._pluginData=this._hknp.HP_Shape_CreateConvexHull(p.offset,f)[1];else{var _=d.getTriangles(this._hknp),m=_.numObjects/3;e._pluginData=this._hknp.HP_Shape_CreateMesh(p.offset,f,_.offset,m)[1],d.freeBuffer(this._hknp,_)}d.freeBuffer(this._hknp,p);break;case EA.HEIGHTFIELD:if(!(i.numHeightFieldSamplesX&&i.numHeightFieldSamplesZ&&i.heightFieldSizeX&&i.heightFieldSizeZ&&i.heightFieldData))throw new Error("Missing required heightfield parameters");for(var g=i.numHeightFieldSamplesX*i.numHeightFieldSamplesZ,v=4*g,y=this._hknp._malloc(v),b=new Float32Array(this._hknp.HEAPU8.buffer,y,g),T=0;T<i.numHeightFieldSamplesX;T++)for(var E=0;E<i.numHeightFieldSamplesZ;E++){var S=E*i.numHeightFieldSamplesX+T,x=(i.numHeightFieldSamplesX-1-T)*i.numHeightFieldSamplesZ+E;b[S]=i.heightFieldData[x]}var A=i.heightFieldSizeX/(i.numHeightFieldSamplesX-1),C=i.heightFieldSizeZ/(i.numHeightFieldSamplesZ-1);e._pluginData=this._hknp.HP_Shape_CreateHeightField(i.numHeightFieldSamplesX,i.numHeightFieldSamplesZ,[A,1,C],y)[1],this._hknp._free(y);break;default:throw new Error("Unsupported Shape Type.")}this._shapes.set(e._pluginData[0],e)},e.prototype.setShapeFilterMembershipMask=function(e,t){var i=this._hknp.HP_Shape_GetFilterInfo(e._pluginData)[1][1];this._hknp.HP_Shape_SetFilterInfo(e._pluginData,[t,i])},e.prototype.getShapeFilterMembershipMask=function(e){return this._hknp.HP_Shape_GetFilterInfo(e._pluginData)[1][0]},e.prototype.setShapeFilterCollideMask=function(e,t){var i=this._hknp.HP_Shape_GetFilterInfo(e._pluginData)[1][0];this._hknp.HP_Shape_SetFilterInfo(e._pluginData,[i,t])},e.prototype.getShapeFilterCollideMask=function(e){return this._hknp.HP_Shape_GetFilterInfo(e._pluginData)[1][1]},e.prototype.setMaterial=function(e,t){var i,r,n,o,a,s=null!==(i=t.friction)&&void 0!==i?i:.5,l=null!==(r=t.staticFriction)&&void 0!==r?r:s,c=null!==(n=t.restitution)&&void 0!==n?n:0,u=null!==(o=t.frictionCombine)&&void 0!==o?o:PA.MINIMUM,h=null!==(a=t.restitutionCombine)&&void 0!==a?a:PA.MAXIMUM,d=[l,s,c,this._materialCombineToNative(u),this._materialCombineToNative(h)];this._hknp.HP_Shape_SetMaterial(e._pluginData,d)},e.prototype.getMaterial=function(e){var t=this._hknp.HP_Shape_GetMaterial(e._pluginData)[1];return{staticFriction:t[0],friction:t[1],restitution:t[2],frictionCombine:this._nativeToMaterialCombine(t[3]),restitutionCombine:this._nativeToMaterialCombine(t[4])}},e.prototype.setDensity=function(e,t){this._hknp.HP_Shape_SetDensity(e._pluginData,t)},e.prototype.getDensity=function(e){return this._hknp.HP_Shape_GetDensity(e._pluginData)[1]},e.prototype._getTransformInfos=function(e){if(e.parent)return e.computeWorldMatrix(!0),[this._bVecToV3(e.absolutePosition),this._bQuatToV4(e.absoluteRotationQuaternion)];var t=H.Quaternion[0];if(e.rotationQuaternion)t=e.rotationQuaternion;else{var i=e.rotation;G.FromEulerAnglesToRef(i.x,i.y,i.z,t)}return[this._bVecToV3(e.position),this._bQuatToV4(t)]},e.prototype.addChild=function(e,t,i,r,n){var o=[i?this._bVecToV3(i):[0,0,0],r?this._bQuatToV4(r):[0,0,0,1],n?this._bVecToV3(n):[1,1,1]];this._hknp.HP_Shape_AddChild(e._pluginData,t._pluginData,o)},e.prototype.removeChild=function(e,t){this._hknp.HP_Shape_RemoveChild(e._pluginData,t)},e.prototype.getNumChildren=function(e){return this._hknp.HP_Shape_GetNumChildren(e._pluginData)[1]},e.prototype.setTrigger=function(e,t){this._hknp.HP_Shape_SetTrigger(e._pluginData,t)},e.prototype.getBoundingBox=function(e){return{}},e.prototype.getBodyGeometry=function(e){var t,i=(null===(t=e._pluginDataInstances)||void 0===t?void 0:t.length)>0?e._pluginDataInstances[0]:e._pluginData,r=this._hknp.HP_Body_GetShape(i.hpBodyId)[1],n=this._hknp.HP_Shape_CreateDebugDisplayGeometry(r);if(n[0]!=this._hknp.Result.RESULT_OK)return{positions:[],indices:[]};var o=this._hknp.HP_DebugGeometry_GetInfo(n[1])[1],a=new Float32Array(this._hknp.HEAPU8.buffer,o[0],3*o[1]),s=new Uint32Array(this._hknp.HEAPU8.buffer,o[2],3*o[3]),l=a.slice(0),c=s.slice(0);return this._hknp.HP_DebugGeometry_Release(n[1]),{positions:l,indices:c}},e.prototype.disposeShape=function(e){this._hknp.HP_Shape_Release(e._pluginData),e._pluginData=void 0},e.prototype.initConstraint=function(e,t,i,r,n){var o,a,s,l,c,u=e.type,h=e.options;if(u&&h)if(t._pluginDataInstances.length>0&&void 0===r||i._pluginDataInstances.length>0&&void 0===n)ae.Warn("Body is instanced but no instance index was specified. Constraint will not be applied.");else{e._pluginData=null!==(o=e._pluginData)&&void 0!==o?o:[];var d=this._hknp.HP_Constraint_Create()[1];e._pluginData.push(d);var p=this._getPluginReference(t,r).hpBodyId,f=this._getPluginReference(i,n).hpBodyId;this._hknp.HP_Constraint_SetParentBody(d,p),this._hknp.HP_Constraint_SetChildBody(d,f),this._constraintToBodyIdPair.set(d[0],[p[0],f[0]]);var _=h.pivotA?this._bVecToV3(h.pivotA):this._bVecToV3(V.Zero()),m=null!==(a=h.axisA)&&void 0!==a?a:new V(1,0,0),g=this._tmpVec3[0];h.perpAxisA?g.copyFrom(h.perpAxisA):m.getNormalToRef(g),this._hknp.HP_Constraint_SetAnchorInParent(d,_,this._bVecToV3(m),this._bVecToV3(g));var v=h.pivotB?this._bVecToV3(h.pivotB):this._bVecToV3(V.Zero()),y=null!==(s=h.axisB)&&void 0!==s?s:new V(1,0,0),b=this._tmpVec3[0];if(h.perpAxisB?b.copyFrom(h.perpAxisB):y.getNormalToRef(b),this._hknp.HP_Constraint_SetAnchorInChild(d,v,this._bVecToV3(y),this._bVecToV3(b)),e._initOptions||(e._initOptions={axisA:m.clone(),axisB:y.clone(),perpAxisA:g.clone(),perpAxisB:b.clone(),pivotA:new V(_[0],_[1],_[2]),pivotB:new V(v[0],v[1],v[2])}),u==TA.LOCK)this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(u==TA.DISTANCE){var T=h.maxDistance||0,E=this._hknp.ConstraintAxis.LINEAR_DISTANCE;this._hknp.HP_Constraint_SetAxisMode(d,E,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(d,E,T),this._hknp.HP_Constraint_SetAxisMaxLimit(d,E,T)}else if(u==TA.HINGE)this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(u==TA.PRISMATIC)this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(u==TA.SLIDER)this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(u==TA.BALL_AND_SOCKET)this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(d,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else{if(u!=TA.SIX_DOF)throw new Error("Unsupported Constraint Type.");for(var S=0,x=e.limits;S<x.length;S++){var A=x[S],C=this._constraintAxisToNative(A.axis);0==(null!==(l=A.minLimit)&&void 0!==l?l:-1)&&0==(null!==(c=A.maxLimit)&&void 0!==c?c:-1)?this._hknp.HP_Constraint_SetAxisMode(d,C,this._hknp.ConstraintAxisLimitMode.LOCKED):(null!=A.minLimit&&(this._hknp.HP_Constraint_SetAxisMode(d,C,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(d,C,A.minLimit)),null!=A.maxLimit&&(this._hknp.HP_Constraint_SetAxisMode(d,C,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMaxLimit(d,C,A.maxLimit))),A.stiffness&&this._hknp.HP_Constraint_SetAxisStiffness(d,C,A.stiffness),A.damping&&this._hknp.HP_Constraint_SetAxisDamping(d,C,A.damping)}}var R=!!h.collision;this._hknp.HP_Constraint_SetCollisionsEnabled(d,R),this._hknp.HP_Constraint_SetEnabled(d,!0)}else ae.Warn("No constraint type or options. Constraint is invalid.")},e.prototype.getBodiesUsingConstraint=function(e){for(var t=[],i=0,r=e._pluginData;i<r.length;i++){var n=r[i],o=this._constraintToBodyIdPair.get(n[0]);if(o){var a=this._bodies.get(o[0]),s=this._bodies.get(o[1]);a&&s&&t.push({parentBody:a.body,parentBodyIndex:a.index,childBody:s.body,childBodyIndex:s.index})}}return t},e.prototype.addConstraint=function(e,t,i,r,n){this.initConstraint(i,e,t,r,n)},e.prototype.setEnabled=function(e,t){for(var i=0,r=e._pluginData;i<r.length;i++){var n=r[i];this._hknp.HP_Constraint_SetEnabled(n,t)}},e.prototype.getEnabled=function(e){var t=e._pluginData&&e._pluginData[0];return!!t&&this._hknp.HP_Constraint_GetEnabled(t)[1]},e.prototype.setCollisionsEnabled=function(e,t){for(var i=0,r=e._pluginData;i<r.length;i++){var n=r[i];this._hknp.HP_Constraint_SetCollisionsEnabled(n,t)}},e.prototype.getCollisionsEnabled=function(e){var t=e._pluginData&&e._pluginData[0];return!!t&&this._hknp.HP_Constraint_GetCollisionsEnabled(t)[1]},e.prototype.setAxisFriction=function(e,t,i){for(var r=0,n=e._pluginData;r<n.length;r++){var o=n[r];this._hknp.HP_Constraint_SetAxisFriction(o,this._constraintAxisToNative(t),i)}},e.prototype.getAxisFriction=function(e,t){var i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisFriction(i,this._constraintAxisToNative(t))[1]:null},e.prototype.setAxisMode=function(e,t,i){for(var r=0,n=e._pluginData;r<n.length;r++){var o=n[r];this._hknp.HP_Constraint_SetAxisMode(o,this._constraintAxisToNative(t),this._limitModeToNative(i))}},e.prototype.getAxisMode=function(e,t){var i=e._pluginData&&e._pluginData[0];if(i){var r=this._hknp.HP_Constraint_GetAxisMode(i,this._constraintAxisToNative(t))[1];return this._nativeToLimitMode(r)}return null},e.prototype.setAxisMinLimit=function(e,t,i){for(var r=0,n=e._pluginData;r<n.length;r++){var o=n[r];this._hknp.HP_Constraint_SetAxisMinLimit(o,this._constraintAxisToNative(t),i)}},e.prototype.getAxisMinLimit=function(e,t){var i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMinLimit(i,this._constraintAxisToNative(t))[1]:null},e.prototype.setAxisMaxLimit=function(e,t,i){for(var r=0,n=e._pluginData;r<n.length;r++){var o=n[r];this._hknp.HP_Constraint_SetAxisMaxLimit(o,this._constraintAxisToNative(t),i)}},e.prototype.getAxisMaxLimit=function(e,t){var i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMaxLimit(i,this._constraintAxisToNative(t))[1]:null},e.prototype.setAxisMotorType=function(e,t,i){for(var r=0,n=e._pluginData;r<n.length;r++){var o=n[r];this._hknp.HP_Constraint_SetAxisMotorType(o,this._constraintAxisToNative(t),this._constraintMotorTypeToNative(i))}},e.prototype.getAxisMotorType=function(e,t){var i=e._pluginData&&e._pluginData[0];return i?this._nativeToMotorType(this._hknp.HP_Constraint_GetAxisMotorType(i,this._constraintAxisToNative(t))[1]):null},e.prototype.setAxisMotorTarget=function(e,t,i){for(var r=0,n=e._pluginData;r<n.length;r++){var o=n[r];this._hknp.HP_Constraint_SetAxisMotorTarget(o,this._constraintAxisToNative(t),i)}},e.prototype.getAxisMotorTarget=function(e,t){return e._pluginData&&e._pluginData[0]?this._hknp.HP_Constraint_GetAxisMotorTarget(e._pluginData,this._constraintAxisToNative(t))[1]:null},e.prototype.setAxisMotorMaxForce=function(e,t,i){for(var r=0,n=e._pluginData;r<n.length;r++){var o=n[r];this._hknp.HP_Constraint_SetAxisMotorMaxForce(o,this._constraintAxisToNative(t),i)}},e.prototype.getAxisMotorMaxForce=function(e,t){var i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMotorMaxForce(i,this._constraintAxisToNative(t))[1]:null},e.prototype.disposeConstraint=function(e){for(var t=0,i=e._pluginData;t<i.length;t++){var r=i[t];this._hknp.HP_Constraint_SetEnabled(r,!1),this._hknp.HP_Constraint_Release(r)}e._pluginData.length=0},e.prototype._populateHitData=function(e,t){var i=this._bodies.get(e[0][0]);t.body=null==i?void 0:i.body,t.bodyIndex=null==i?void 0:i.index;var r=this._shapes.get(e[1][0]);t.shape=r;var n=e[3],o=e[4],a=e[5];t.setHitData({x:o[0],y:o[1],z:o[2]},{x:n[0],y:n[1],z:n[2]},a)},e.prototype.raycast=function(e,t,i,r){var n,o,a=null!==(n=null==r?void 0:r.membership)&&void 0!==n?n:-1,s=null!==(o=null==r?void 0:r.collideWith)&&void 0!==o?o:-1;i.reset(e,t);var l=[BigInt(0)],c=[this._bVecToV3(e),this._bVecToV3(t),[a,s],!1,l];if(this._hknp.HP_World_CastRayWithCollector(this.world,this._queryCollector,c),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){var u=this._hknp.HP_QueryCollector_GetCastRayResult(this._queryCollector,0)[1][1];this._populateHitData(u,i),i.calculateHitDistance()}},e.prototype.pointProximity=function(e,t){var i,r,n,o,a=null!==(r=null===(i=null==e?void 0:e.collisionFilter)||void 0===i?void 0:i.membership)&&void 0!==r?r:-1,s=null!==(o=null===(n=null==e?void 0:e.collisionFilter)||void 0===n?void 0:n.collideWith)&&void 0!==o?o:-1;t.reset();var l=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],c=[this._bVecToV3(e.position),e.maxDistance,[a,s],e.shouldHitTriggers,l];if(this._hknp.HP_World_PointProximityWithCollector(this.world,this._queryCollector,c),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){var u=this._hknp.HP_QueryCollector_GetPointProximityResult(this._queryCollector,0)[1],h=u[0],d=u[1];this._populateHitData(d,t),t.setHitDistance(h)}},e.prototype.shapeProximity=function(e,t,i){t.reset(),i.reset();var r=e.shape._pluginData,n=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],o=[r,this._bVecToV3(e.position),this._bQuatToV4(e.rotation),e.maxDistance,e.shouldHitTriggers,n];if(this._hknp.HP_World_ShapeProximityWithCollector(this.world,this._queryCollector,o),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){var a=this._hknp.HP_QueryCollector_GetShapeProximityResult(this._queryCollector,0)[1],s=a[0],l=a[1],c=a[2];this._populateHitData(l,t),this._populateHitData(c,i),t.setHitDistance(s),i.setHitDistance(s)}},e.prototype.shapeCast=function(e,t,i){t.reset(),i.reset();var r=e.shape._pluginData,n=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],o=[r,this._bQuatToV4(e.rotation),this._bVecToV3(e.startPosition),this._bVecToV3(e.endPosition),e.shouldHitTriggers,n];if(this._hknp.HP_World_ShapeCastWithCollector(this.world,this._queryCollector,o),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){var a=this._hknp.HP_QueryCollector_GetShapeCastResult(this._queryCollector,0)[1],s=a[0],l=a[1],c=a[2];this._populateHitData(l,t),this._populateHitData(c,i),t.setHitFraction(s),i.setHitFraction(s)}},e.prototype.getCollisionObservable=function(e){var t=e._pluginData.hpBodyId[0],i=this._bodyCollisionObservable.get(t);return i||(i=new f,this._bodyCollisionObservable.set(t,i)),i},e.prototype.getCollisionEndedObservable=function(e){var t=e._pluginData.hpBodyId[0],i=this._bodyCollisionEndedObservable.get(t);return i||(i=new f,this._bodyCollisionEndedObservable.set(t,i)),i},e.prototype.setCollisionCallbackEnabled=function(e,t){var i=this,r=this._hknp.EventType.COLLISION_STARTED.value|this._hknp.EventType.COLLISION_CONTINUED.value|this._hknp.EventType.COLLISION_FINISHED.value;e._pluginDataInstances&&e._pluginDataInstances.length?e._pluginDataInstances.forEach((function(e){i._hknp.HP_Body_SetEventMask(e.hpBodyId,t?r:0)})):e._pluginData&&this._hknp.HP_Body_SetEventMask(e._pluginData.hpBodyId,t?r:0)},e.prototype.setCollisionEndedCallbackEnabled=function(e,t){var i=this,r=this._getPluginReference(e),n=this._hknp.HP_Body_GetEventMask(r.hpBodyId)[1];n=t?n|this._hknp.EventType.COLLISION_FINISHED.value:n&~this._hknp.EventType.COLLISION_FINISHED.value,e._pluginDataInstances&&e._pluginDataInstances.length?e._pluginDataInstances.forEach((function(e){i._hknp.HP_Body_SetEventMask(e.hpBodyId,n)})):e._pluginData&&this._hknp.HP_Body_SetEventMask(e._pluginData.hpBodyId,n)},e.prototype._notifyTriggers=function(){for(var e=this._hknp.HP_World_GetTriggerEvents(this.world)[1],t=new tC;e;){tC.readToRef(this._hknp.HEAPU8.buffer,e,t);var i=this._bodies.get(t.bodyIdA),r=this._bodies.get(t.bodyIdB);if(i&&r){var n={collider:i.body,colliderIndex:i.index,collidedAgainst:r.body,collidedAgainstIndex:r.index,type:this._nativeTriggerCollisionValueToCollisionType(t.type)};this.onTriggerCollisionObservable.notifyObservers(n)}e=this._hknp.HP_World_GetNextTriggerEvent(this.world,e)}},e.prototype._notifyCollisions=function(){for(var e=this._hknp.HP_World_GetCollisionEvents(this.world)[1],t=new eC,i=Number(this.world);e;){eC.readToRef(this._hknp.HEAPU8.buffer,e,t);var r=this._bodies.get(t.contactOnA.bodyId),n=this._bodies.get(t.contactOnB.bodyId);if(r&&n){var o={collider:r.body,colliderIndex:r.index,collidedAgainst:n.body,collidedAgainstIndex:n.index,type:this._nativeCollisionValueToCollisionType(t.type)};if(o.type===xA.COLLISION_FINISHED)this.onCollisionEndedObservable.notifyObservers(o);else{t.contactOnB.position.subtractToRef(t.contactOnA.position,this._tmpVec3[0]);var a=V.Dot(this._tmpVec3[0],t.contactOnA.normal);o.point=t.contactOnA.position,o.distance=a,o.impulse=t.impulseApplied,o.normal=t.contactOnA.normal,this.onCollisionObservable.notifyObservers(o)}if(this._bodyCollisionObservable.size&&o.type!==xA.COLLISION_FINISHED){var s=this._bodyCollisionObservable.get(t.contactOnA.bodyId),l=this._bodyCollisionObservable.get(t.contactOnB.bodyId);s?s.notifyObservers(o):l&&(o.collider=n.body,o.colliderIndex=n.index,o.collidedAgainst=r.body,o.collidedAgainstIndex=r.index,o.normal=t.contactOnB.normal,l.notifyObservers(o))}else this._bodyCollisionEndedObservable.size&&(s=this._bodyCollisionEndedObservable.get(t.contactOnA.bodyId),l=this._bodyCollisionEndedObservable.get(t.contactOnB.bodyId),s?s.notifyObservers(o):l&&(o.collider=n.body,o.colliderIndex=n.index,o.collidedAgainst=r.body,o.collidedAgainstIndex=r.index,o.normal=t.contactOnB.normal,l.notifyObservers(o)))}e=this._hknp.HP_World_GetNextCollisionEvent(i,e)}},Object.defineProperty(e.prototype,"numBodies",{get:function(){return this._hknp.HP_World_GetNumBodies(this.world)[1]},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){this._hknp.HP_QueryCollector_Release(this._queryCollector),this._queryCollector=BigInt(0),this._hknp.HP_World_Release(this.world),this.world=void 0},e.prototype._v3ToBvecRef=function(e,t){t.set(e[0],e[1],e[2])},e.prototype._bVecToV3=function(e){return[e._x,e._y,e._z]},e.prototype._bQuatToV4=function(e){return[e._x,e._y,e._z,e._w]},e.prototype._constraintMotorTypeToNative=function(e){switch(e){case SA.POSITION:return this._hknp.ConstraintMotorType.POSITION;case SA.VELOCITY:return this._hknp.ConstraintMotorType.VELOCITY}return this._hknp.ConstraintMotorType.NONE},e.prototype._nativeToMotorType=function(e){switch(e){case this._hknp.ConstraintMotorType.POSITION:return SA.POSITION;case this._hknp.ConstraintMotorType.VELOCITY:return SA.VELOCITY}return SA.NONE},e.prototype._materialCombineToNative=function(e){switch(e){case PA.GEOMETRIC_MEAN:return this._hknp.MaterialCombine.GEOMETRIC_MEAN;case PA.MINIMUM:return this._hknp.MaterialCombine.MINIMUM;case PA.MAXIMUM:return this._hknp.MaterialCombine.MAXIMUM;case PA.ARITHMETIC_MEAN:return this._hknp.MaterialCombine.ARITHMETIC_MEAN;case PA.MULTIPLY:return this._hknp.MaterialCombine.MULTIPLY}},e.prototype._nativeToMaterialCombine=function(e){switch(e){case this._hknp.MaterialCombine.GEOMETRIC_MEAN:return PA.GEOMETRIC_MEAN;case this._hknp.MaterialCombine.MINIMUM:return PA.MINIMUM;case this._hknp.MaterialCombine.MAXIMUM:return PA.MAXIMUM;case this._hknp.MaterialCombine.ARITHMETIC_MEAN:return PA.ARITHMETIC_MEAN;case this._hknp.MaterialCombine.MULTIPLY:return PA.MULTIPLY;default:return}},e.prototype._constraintAxisToNative=function(e){switch(e){case bA.LINEAR_X:return this._hknp.ConstraintAxis.LINEAR_X;case bA.LINEAR_Y:return this._hknp.ConstraintAxis.LINEAR_Y;case bA.LINEAR_Z:return this._hknp.ConstraintAxis.LINEAR_Z;case bA.ANGULAR_X:return this._hknp.ConstraintAxis.ANGULAR_X;case bA.ANGULAR_Y:return this._hknp.ConstraintAxis.ANGULAR_Y;case bA.ANGULAR_Z:return this._hknp.ConstraintAxis.ANGULAR_Z;case bA.LINEAR_DISTANCE:return this._hknp.ConstraintAxis.LINEAR_DISTANCE}},e.prototype._nativeToLimitMode=function(e){switch(e){case this._hknp.ConstraintAxisLimitMode.FREE:return yA.FREE;case this._hknp.ConstraintAxisLimitMode.LIMITED:return yA.LIMITED;case this._hknp.ConstraintAxisLimitMode.LOCKED:return yA.LOCKED}return yA.FREE},e.prototype._limitModeToNative=function(e){switch(e){case yA.FREE:return this._hknp.ConstraintAxisLimitMode.FREE;case yA.LIMITED:return this._hknp.ConstraintAxisLimitMode.LIMITED;case yA.LOCKED:return this._hknp.ConstraintAxisLimitMode.LOCKED}},e.prototype._nativeCollisionValueToCollisionType=function(e){switch(e){case this._hknp.EventType.COLLISION_STARTED.value:return xA.COLLISION_STARTED;case this._hknp.EventType.COLLISION_FINISHED.value:return xA.COLLISION_FINISHED;case this._hknp.EventType.COLLISION_CONTINUED.value:return xA.COLLISION_CONTINUED}return xA.COLLISION_STARTED},e.prototype._nativeTriggerCollisionValueToCollisionType=function(e){switch(e){case 8:return xA.TRIGGER_ENTERED;case 16:return xA.TRIGGER_EXITED}return xA.TRIGGER_ENTERED},e}();pn.prototype.getPhysicsEngine=function(){return this._physicsEngine},pn.prototype.enablePhysics=function(e,t){if(void 0===e&&(e=null),this._physicsEngine)return!0;var i=this._getComponent(Vr.NAME_PHYSICSENGINE);i||(i=new rC(this),this._addComponent(i));try{if(t&&1!==(null==t?void 0:t.getPluginVersion())){if(2!==(null==t?void 0:t.getPluginVersion()))throw new Error("Unsupported Physics plugin version.");this._physicsEngine=new RA(e,t)}else this._physicsEngine=new Fv(e,t);return this._physicsTimeAccumulator=0,!0}catch(e){return ae.Error(e.message),!1}},pn.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},pn.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},pn.prototype.deleteCompoundImpostor=function(e){var t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},pn.prototype._advancePhysicsEngineStep=function(e){if(this._physicsEngine){var t=this._physicsEngine.getSubTimeStep();if(t>0)for(this._physicsTimeAccumulator+=e;this._physicsTimeAccumulator>t;)this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(t/1e3),this.onAfterPhysicsObservable.notifyObservers(this),this._physicsTimeAccumulator-=t;else this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(e/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};var rC=function(){function e(e){var t=this;this.name=Vr.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new f,this.scene.onAfterPhysicsObservable=new f,this.scene.getDeterministicFrameTime=function(){return t.scene._physicsEngine?1e3*t.scene._physicsEngine.getTimeStep():1e3/60}}return e.prototype.register=function(){},e.prototype.rebuild=function(){},e.prototype.dispose=function(){this.scene.onBeforePhysicsObservable.clear(),this.scene.onAfterPhysicsObservable.clear(),this.scene._physicsEngine&&this.scene.disablePhysicsEngine()},e}();Object.defineProperty(Fo.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(e){var t=this;this._physicsBody!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add((function(){t.physicsBody&&(t.physicsBody.dispose(),t.physicsBody=null)}))))},enumerable:!0,configurable:!0}),Fo.prototype.getPhysicsBody=function(){return this.physicsBody},Fo.prototype.applyImpulse=function(e,t){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(e,t),this},Fo.prototype.applyAngularImpulse=function(e){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyAngularImpulse(e),this};var nC,oC,aC=function(){function e(){}return e.GetContactPointToRef=function(e,t,i,r,n){var o=e.getScene().getPhysicsEngine(),a=null==o?void 0:o.getPluginVersion();if(1===a){var s=new hs(t,i).intersectsMesh(e);if(s.hit&&s.pickedPoint)return r.copyFrom(s.pickedPoint),!0}else if(2===a)return e.physicsBody.getObjectCenterWorldToRef(r,n),!0;return!1},e.HasAppliedForces=function(e,t){var i,r,n;return e.getMotionType(t)===AA.STATIC||0===(null!==(r=null===(i=e.getMassProperties(t))||void 0===i?void 0:i.mass)&&void 0!==r?r:0)||0===(null===(n=e.transformNode)||void 0===n?void 0:n.getTotalVertices())},e.IsInsideCylinder=function(e,t,i,r){var n=H.Vector3[0];return e.subtractToRef(t,n),Math.abs(n.x)<=i&&Math.abs(n.z)<=i&&n.y>=0&&n.y<=r},e}(),sC=function(){function e(e){this._hitData={force:new V,contactPoint:new V,distanceFromOrigin:0},this._scene=e,this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine||ae.Warn("Physics engine not enabled. Please enable the physics before you can use the methods.")}return e.prototype.applyRadialExplosionImpulse=function(e,t,i,r){var n=this;if(!this._physicsEngine)return ae.Warn("Physics engine not enabled. Please enable the physics before you call this method."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;var o=!1;if("number"==typeof t){var a=t;(t=new dC).radius=a,t.strength=null!=i?i:t.strength,t.falloff=null!=r?r:t.falloff}else o=!(!t.affectedImpostorsCallback&&!t.affectedBodiesCallback);var s=new lC(this._scene,t),l=this._hitData;if(1===this._physicsEngine.getPluginVersion()){var c=Array();this._physicsEngine.getImpostors().forEach((function(t){s.getImpostorHitData(t,e,l)&&(t.applyImpulse(l.force,l.contactPoint),o&&c.push({impostor:t,hitData:n._copyPhysicsHitData(l)}))})),s.triggerAffectedImpostorsCallback(c)}else this._applicationForBodies(s,e,l,o,(function(e,t){e.applyImpulse(t.force,t.contactPoint,t.instanceIndex)}));return s.dispose(!1),s},e.prototype.applyRadialExplosionForce=function(e,t,i,r){var n=this;if(!this._physicsEngine)return ae.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;var o=!1;if("number"==typeof t){var a=t;(t=new dC).radius=a,t.strength=null!=i?i:t.strength,t.falloff=null!=r?r:t.falloff}else o=!(!t.affectedImpostorsCallback&&!t.affectedBodiesCallback);var s=new lC(this._scene,t),l=this._hitData;if(1===this._physicsEngine.getPluginVersion()){var c=Array();this._physicsEngine.getImpostors().forEach((function(t){s.getImpostorHitData(t,e,l)&&(t.applyForce(l.force,l.contactPoint),o&&c.push({impostor:t,hitData:n._copyPhysicsHitData(l)}))})),s.triggerAffectedImpostorsCallback(c)}else this._applicationForBodies(s,e,l,o,(function(e,t){e.applyForce(t.force,t.contactPoint,t.instanceIndex)}));return s.dispose(!1),s},e.prototype._applicationForBodies=function(e,t,i,r,n){for(var o=this,a=Array(),s=0,l=this._physicsEngine.getBodies();s<l.length;s++)l[s].iterateOverAllInstances((function(s,l){e.getBodyHitData(s,t,i,l)&&(n(s,i),r&&a.push({body:s,hitData:o._copyPhysicsHitData(i)}))}));e.triggerAffectedBodiesCallback(a)},e.prototype.gravitationalField=function(e,t,i,r){if(!this._physicsEngine)return ae.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){var n=t;(t=new dC).radius=n,t.strength=null!=i?i:t.strength,t.falloff=null!=r?r:t.falloff}var o=new cC(this,this._scene,e,t);return o.dispose(!1),o},e.prototype.updraft=function(e,t,i,r,n){if(!this._physicsEngine)return ae.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){var o=t;(t=new pC).radius=o,t.strength=null!=i?i:t.strength,t.height=null!=r?r:t.height,t.updraftMode=null!=n?n:t.updraftMode}var a=new uC(this._scene,e,t);return a.dispose(!1),a},e.prototype.vortex=function(e,t,i,r){if(!this._physicsEngine)return ae.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){var n=t;(t=new fC).radius=n,t.strength=null!=i?i:t.strength,t.height=null!=r?r:t.height}var o=new hC(this._scene,e,t);return o.dispose(!1),o},e.prototype._copyPhysicsHitData=function(e){return{force:e.force.clone(),contactPoint:e.contactPoint.clone(),distanceFromOrigin:e.distanceFromOrigin,instanceIndex:e.instanceIndex}},e}(),lC=function(){function e(e,t){this._scene=e,this._options=t,this._dataFetched=!1,this._options=g(g({},new dC),this._options)}return e.prototype.getData=function(){return this._dataFetched=!0,{sphere:this._sphere}},e.prototype._getHitData=function(e,t,i,r){var n=H.Vector3[0];n.copyFrom(t).subtractInPlace(i);var o=H.Vector3[1];if(!aC.GetContactPointToRef(e,i,n,o,r.instanceIndex))return!1;var a=V.Distance(i,o);if(a>this._options.radius)return!1;var s=this._options.falloff===nC.Constant?this._options.strength:this._options.strength*(1-a/this._options.radius);return n.scaleInPlace(s),r.force.copyFrom(n),r.contactPoint.copyFrom(o),r.distanceFromOrigin=a,!0},e.prototype.getBodyHitData=function(e,t,i,r){if(aC.HasAppliedForces(e,r))return!1;var n=e.transformNode,o=e.getObjectCenterWorld(r);return i.instanceIndex=r,this._getHitData(n,o,t,i)},e.prototype.getImpostorHitData=function(e,t,i){if(0===e.mass)return!1;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;var r=e.object;if(!this._intersectsWithSphere(r,t,this._options.radius))return!1;var n=e.getObjectCenter();return this._getHitData(r,n,t,i),!0},e.prototype.triggerAffectedImpostorsCallback=function(e){this._options.affectedImpostorsCallback&&this._options.affectedImpostorsCallback(e)},e.prototype.triggerAffectedBodiesCallback=function(e){this._options.affectedBodiesCallback&&this._options.affectedBodiesCallback(e)},e.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),this._sphere&&(e?this._sphere.dispose():setTimeout((function(){t._dataFetched||t._sphere.dispose()}),0))},e.prototype._prepareSphere=function(){this._sphere||(this._sphere=Gh("radialExplosionEventSphere",this._options.sphere,this._scene),this._sphere.isVisible=!1)},e.prototype._intersectsWithSphere=function(e,t,i){return this._prepareSphere(),this._sphere.position=t,this._sphere.scaling.setAll(2*i),this._sphere._updateBoundingInfo(),this._sphere.computeWorldMatrix(!0),this._sphere.intersectsMesh(e,!0)},e}(),cC=function(){function e(e,t,i,r){var n=this;this._physicsHelper=e,this._scene=t,this._origin=i,this._options=r,this._dataFetched=!1,this._options=g(g({},new dC),this._options),this._tickCallback=function(){return n._tick()},this._options.strength=-1*this._options.strength}return e.prototype.getData=function(){return this._dataFetched=!0,{sphere:this._sphere}},e.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},e.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},e.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),this._sphere&&(e?this._sphere.dispose():setTimeout((function(){t._dataFetched||t._sphere.dispose()}),0))},e.prototype._tick=function(){var e;if(this._sphere)this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);else{var t=this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);t&&(this._sphere=null===(e=t.getData().sphere)||void 0===e?void 0:e.clone("radialExplosionEventSphereClone"))}},e}(),uC=function(){function e(e,t,i){var r=this;this._scene=e,this._origin=t,this._options=i,this._originTop=V.Zero(),this._originDirection=V.Zero(),this._cylinderPosition=V.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=g(g({},new pC),this._options),this._origin.addToRef(new V(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new V(0,this._options.height,0),this._originTop),this._options.updraftMode===oC.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=function(){return r._tick()},1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}return e.prototype.getData=function(){return this._dataFetched=!0,{cylinder:this._cylinder}},e.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},e.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},e.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),this._cylinder&&(e?(this._cylinder.dispose(),this._cylinder=void 0):setTimeout((function(){!t._dataFetched&&t._cylinder&&(t._cylinder.dispose(),t._cylinder=void 0)}),0))},e.prototype._getHitData=function(e,t){var i;i=this._options.updraftMode===oC.Perpendicular?this._originDirection:e.subtract(this._originTop);var r=V.Distance(this._origin,e),n=-1*this._options.strength,o=i.multiplyByFloats(n,n,n);t.force.copyFrom(o),t.contactPoint.copyFrom(e),t.distanceFromOrigin=r},e.prototype._getBodyHitData=function(e,t,i){if(aC.HasAppliedForces(e))return!1;var r=e.getObjectCenterWorld(i);return!!aC.IsInsideCylinder(r,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(r,t),!0)},e.prototype._getImpostorHitData=function(e,t){if(0===e.mass)return!1;var i=e.object;if(!this._intersectsWithCylinder(i))return!1;var r=e.getObjectCenter();return this._getHitData(r,t),!0},e.prototype._tick=function(){var t=this,i=e._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((function(e){t._getImpostorHitData(e,i)&&e.applyForce(i.force,i.contactPoint)})):this._physicsEngine.getBodies().forEach((function(e){e.iterateOverAllInstances((function(e,r){t._getBodyHitData(e,i,r)&&e.applyForce(i.force,i.contactPoint,i.instanceIndex)}))}))},e.prototype._prepareCylinder=function(){this._cylinder||(this._cylinder=xh("updraftEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)},e.prototype._intersectsWithCylinder=function(e){return!!this._cylinder&&(this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0))},e._HitData={force:new V,contactPoint:new V,distanceFromOrigin:0},e}(),hC=function(){function e(e,t,i){var r=this;this._scene=e,this._origin=t,this._options=i,this._originTop=V.Zero(),this._cylinderPosition=V.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=g(g({},new fC),this._options),this._origin.addToRef(new V(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new V(0,this._options.height,0),this._originTop),this._tickCallback=function(){return r._tick()},1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}return e.prototype.getData=function(){return this._dataFetched=!0,{cylinder:this._cylinder}},e.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},e.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},e.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),this._cylinder&&(e?this._cylinder.dispose():setTimeout((function(){t._dataFetched||t._cylinder.dispose()}),0))},e.prototype._getHitData=function(t,i,r){var n=e._OriginOnPlane;n.set(this._origin.x,i.y,this._origin.z);var o=H.Vector3[0];i.subtractToRef(n,o);var a=H.Vector3[1];if(!aC.GetContactPointToRef(t,n,o,a,r.instanceIndex))return!1;var s,l,c,u=V.Distance(a,n)/this._options.radius,h=H.Vector3[2];if(a.normalizeToRef(h),u>this._options.centripetalForceThreshold&&h.negateInPlace(),u>this._options.centripetalForceThreshold)s=h.x*this._options.centripetalForceMultiplier,l=h.y*this._options.updraftForceMultiplier,c=h.z*this._options.centripetalForceMultiplier;else{var d=V.Cross(n,i).normalize();s=(d.x+h.x)*this._options.centrifugalForceMultiplier,l=this._originTop.y*this._options.updraftForceMultiplier,c=(d.z+h.z)*this._options.centrifugalForceMultiplier}var p=H.Vector3[3];return p.set(s,l,c),p.scaleInPlace(this._options.strength),r.force.copyFrom(p),r.contactPoint.copyFrom(i),r.distanceFromOrigin=u,!0},e.prototype._getBodyHitData=function(e,t,i){if(aC.HasAppliedForces(e,i))return!1;var r=e.transformNode,n=e.getObjectCenterWorld(i);return!!aC.IsInsideCylinder(n,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(r,n,t))},e.prototype._getImpostorHitData=function(e,t){if(0===e.mass)return!1;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;var i=e.object;if(!this._intersectsWithCylinder(i))return!1;var r=e.getObjectCenter();return this._getHitData(i,r,t),!0},e.prototype._tick=function(){var t=this,i=e._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((function(e){t._getImpostorHitData(e,i)&&e.applyForce(i.force,i.contactPoint)})):this._physicsEngine.getBodies().forEach((function(e){e.iterateOverAllInstances((function(e,r){t._getBodyHitData(e,i,r)&&e.applyForce(i.force,i.contactPoint,i.instanceIndex)}))}))},e.prototype._prepareCylinder=function(){this._cylinder||(this._cylinder=xh("vortexEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)},e.prototype._intersectsWithCylinder=function(e){return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)},e._OriginOnPlane=V.Zero(),e._HitData={force:new V,contactPoint:new V,distanceFromOrigin:0},e}(),dC=function(){this.radius=5,this.strength=10,this.falloff=nC.Constant,this.sphere={segments:32,diameter:1}},pC=function(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=oC.Center},fC=function(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02};!function(e){e[e.Constant=0]="Constant",e[e.Linear=1]="Linear"}(nC||(nC={})),function(e){e[e.Center=0]="Center",e[e.Perpendicular=1]="Perpendicular"}(oC||(oC={}));var _C=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._hitDistance=0,t}return m(t,e),Object.defineProperty(t.prototype,"hitDistance",{get:function(){return this._hitDistance},enumerable:!1,configurable:!0}),t.prototype.setHitDistance=function(e){this._hitDistance=e},t.prototype.reset=function(){e.prototype.reset.call(this),this._hitDistance=0},t}(Dv),mC=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._hitFraction=0,t}return m(t,e),Object.defineProperty(t.prototype,"hitFraction",{get:function(){return this._hitFraction},enumerable:!1,configurable:!0}),t.prototype.setHitFraction=function(e){this._hitFraction=e},t}(Dv);li.ShadersStore.blackAndWhitePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}";var gC=function(e){function t(t,i,r,n,o,a){var s=e.call(this,t,"blackAndWhite",["degree"],null,i,r,n,o,a)||this;return s.degree=1,s.onApplyObservable.add((function(e){e.setFloat("degree",s.degree)})),s}return m(t,e),t.prototype.getClassName=function(){return"BlackAndWhitePostProcess"},t._Parse=function(e,i,r,n){return Ke.Parse((function(){return new t(e.name,e.options,i,e.renderTargetSamplingMode,r.getEngine(),e.reusable)}),e,r,n)},v([Ie()],t.prototype,"degree",void 0),t}(hl);a("BABYLON.BlackAndWhitePostProcess",gC);var vC=function(){function e(e,t,i,r){this._name=t,this._singleInstance=r||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}return Object.defineProperty(e.prototype,"isSupported",{get:function(){for(var e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e))for(var t=this._postProcesses[e],i=0;i<t.length;i++)if(!t[i].isSupported)return!1;return!0},enumerable:!1,configurable:!0}),e.prototype._update=function(){},e.prototype._attachCameras=function(e){var t,i=this,r=rr.MakeArray(e||this._cameras);if(r)for(var n=function(e){var n=r[e];if(!n)return"continue";var a=n.name;if(t=o._singleInstance?0:a,!o._postProcesses[t]){var s=o._getPostProcesses();s&&(o._postProcesses[t]=Array.isArray(s)?s:[s])}o._indicesForCamera[a]||(o._indicesForCamera[a]=[]),o._postProcesses[t].forEach((function(e){var t=n.attachPostProcess(e);i._indicesForCamera[a].push(t)})),o._cameras[a]||(o._cameras[a]=n)},o=this,a=0;a<r.length;a++)n(a)},e.prototype._detachCameras=function(e){var t=rr.MakeArray(e||this._cameras);if(t)for(var i=function(e){var i=t[e],n=i.name,o=r._postProcesses[r._singleInstance?0:n];o&&o.forEach((function(e){i.detachPostProcess(e)})),r._cameras[n]&&(r._cameras[n]=null),delete r._indicesForCamera[n]},r=this,n=0;n<t.length;n++)i(n)},e.prototype._enable=function(e){var t=rr.MakeArray(e||this._cameras);if(t)for(var i=0;i<t.length;i++)for(var r=t[i],n=r.name,o=this._singleInstance?0:n,a=0;a<this._indicesForCamera[n].length;a++){var s=this._indicesForCamera[n][a];null==r._postProcesses[s]&&t[i].attachPostProcess(this._postProcesses[o][a],s)}},e.prototype._disable=function(e){var t=rr.MakeArray(e||this._cameras);if(t)for(var i=function(e){var i=t[e],n=i.name;r._postProcesses[r._singleInstance?0:n].forEach((function(e){i.detachPostProcess(e)}))},r=this,n=0;n<t.length;n++)i(n)},e.prototype.getPostProcesses=function(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null},e}();li.ShadersStore.extractHighlightsPixelShader="#include<helperFunctions>\nvarying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}";var yC=function(e){function t(t,i,r,n,o,a,s,l){void 0===s&&(s=u.TEXTURETYPE_UNSIGNED_INT),void 0===l&&(l=!1);var c=e.call(this,t,"extractHighlights",["threshold","exposure"],null,i,r,n,o,a,null,s,void 0,null,l)||this;return c.threshold=.9,c._exposure=1,c._inputPostProcess=null,c.onApplyObservable.add((function(e){c.externalTextureSamplerBinding=!!c._inputPostProcess,c._inputPostProcess&&e.setTextureFromPostProcess("textureSampler",c._inputPostProcess),e.setFloat("threshold",Math.pow(c.threshold,E)),e.setFloat("exposure",c._exposure)})),c}return m(t,e),t.prototype.getClassName=function(){return"ExtractHighlightsPostProcess"},v([Ie()],t.prototype,"threshold",void 0),t}(hl);a("BABYLON.ExtractHighlightsPostProcess",yC);li.ShadersStore.bloomMergePixelShader="uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); }\n";var bC=function(e){function t(t,i,r,n,o,a,s,l,c,h,d){void 0===h&&(h=u.TEXTURETYPE_UNSIGNED_INT),void 0===d&&(d=!1);var p=e.call(this,t,"bloomMerge",["bloomWeight"],["bloomBlur"],o,a,s,l,c,null,h,void 0,null,!0)||this;return p.weight=1,p.weight=n,p.externalTextureSamplerBinding=!0,p.onApplyObservable.add((function(e){e.setTextureFromPostProcess("textureSampler",i),e.setTextureFromPostProcessOutput("bloomBlur",r),e.setFloat("bloomWeight",p.weight)})),d||p.updateEffect(),p}return m(t,e),t.prototype.getClassName=function(){return"BloomMergePostProcess"},v([Ie()],t.prototype,"weight",void 0),t}(hl);a("BABYLON.BloomMergePostProcess",bC);var TC=function(e){function t(t,i,r,n,o,a){void 0===o&&(o=0),void 0===a&&(a=!1);var s=e.call(this,t.getEngine(),"bloom",(function(){return s._effects}),!0)||this;return s._bloomScale=i,s._effects=[],s._downscale=new yC("highlights",1,null,Ja.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,o,a),s._blurX=new Om("horizontal blur",new U(1,0),10,i,null,Ja.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,o,void 0,a),s._blurX.alwaysForcePOT=!0,s._blurX.autoClear=!1,s._blurY=new Om("vertical blur",new U(0,1),10,i,null,Ja.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,o,void 0,a),s._blurY.alwaysForcePOT=!0,s._blurY.autoClear=!1,s.kernel=n,s._effects=[s._downscale,s._blurX,s._blurY],s._merge=new bC("bloomMerge",s._downscale,s._blurY,r,i,null,Ja.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,o,a),s._merge.autoClear=!1,s._effects.push(s._merge),s}return m(t,e),Object.defineProperty(t.prototype,"threshold",{get:function(){return this._downscale.threshold},set:function(e){this._downscale.threshold=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"weight",{get:function(){return this._merge.weight},set:function(e){this._merge.weight=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"kernel",{get:function(){return this._blurX.kernel/this._bloomScale},set:function(e){this._blurX.kernel=e*this._bloomScale,this._blurY.kernel=e*this._bloomScale},enumerable:!1,configurable:!0}),t.prototype.disposeEffects=function(e){for(var t=0;t<this._effects.length;t++)this._effects[t].dispose(e)},t.prototype._updateEffects=function(){for(var e=0;e<this._effects.length;e++)this._effects[e].updateEffect()},t.prototype._isReady=function(){for(var e=0;e<this._effects.length;e++)if(!this._effects[e].isReady())return!1;return!0},t}(vC);li.ShadersStore.chromaticAberrationPixelShader="uniform sampler2D textureSampler; \nuniform float chromatic_aberration;uniform float radialIntensity;uniform vec2 direction;uniform vec2 centerPosition;uniform float screen_width;uniform float screen_height;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);vec2 directionOfEffect=direction;if(directionOfEffect.x==0. && directionOfEffect.y==0.){directionOfEffect=normalize(centered_screen_pos);}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+ centered_screen_pos.y*centered_screen_pos.y;float radius=sqrt(radius2);vec4 original=texture2D(textureSampler,vUV);vec3 ref_indices=vec3(-0.3,0.0,0.3);float ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;float ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;vec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);vec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);vec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);original.r=texture2D(textureSampler,ref_coords_r).r;original.g=texture2D(textureSampler,ref_coords_g).g;original.b=texture2D(textureSampler,ref_coords_b).b;original.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);gl_FragColor=original;}";var EC=function(e){function t(t,i,r,n,o,a,s,l,c,h){void 0===c&&(c=u.TEXTURETYPE_UNSIGNED_INT),void 0===h&&(h=!1);var d=e.call(this,t,"chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],n,o,a,s,l,null,c,void 0,null,h)||this;return d.aberrationAmount=30,d.radialIntensity=0,d.direction=new U(.707,.707),d.centerPosition=new U(.5,.5),d.screenWidth=i,d.screenHeight=r,d.onApplyObservable.add((function(e){e.setFloat("chromatic_aberration",d.aberrationAmount),e.setFloat("screen_width",i),e.setFloat("screen_height",r),e.setFloat("radialIntensity",d.radialIntensity),e.setFloat2("direction",d.direction.x,d.direction.y),e.setFloat2("centerPosition",d.centerPosition.x,d.centerPosition.y)})),d}return m(t,e),t.prototype.getClassName=function(){return"ChromaticAberrationPostProcess"},t._Parse=function(e,i,r,n){return Ke.Parse((function(){return new t(e.name,e.screenWidth,e.screenHeight,e.options,i,e.renderTargetSamplingMode,r.getEngine(),e.reusable,e.textureType,!1)}),e,r,n)},v([Ie()],t.prototype,"aberrationAmount",void 0),v([Ie()],t.prototype,"radialIntensity",void 0),v([Ie()],t.prototype,"direction",void 0),v([Ie()],t.prototype,"centerPosition",void 0),v([Ie()],t.prototype,"screenWidth",void 0),v([Ie()],t.prototype,"screenHeight",void 0),t}(hl);a("BABYLON.ChromaticAberrationPostProcess",EC);li.ShadersStore.circleOfConfusionPixelShader="uniform sampler2D depthSampler;varying vec2 vUV;uniform vec2 cameraMinMaxZ;uniform float focusDistance;uniform float cocPrecalculation;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float depth=texture2D(depthSampler,vUV).r;\n#define CUSTOM_COC_DEPTH\nfloat pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; \n#define CUSTOM_COC_PIXELDISTANCE\nfloat coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);}\n";var SC=function(e){function t(t,i,r,n,o,a,s,l,c){void 0===l&&(l=u.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=!1);var h=e.call(this,t,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],r,n,o,a,s,null,l,void 0,null,c)||this;return h.lensSize=50,h.fStop=1.4,h.focusDistance=2e3,h.focalLength=50,h._depthTexture=null,h._depthTexture=i,h.onApplyObservable.add((function(e){if(h._depthTexture){e.setTexture("depthSampler",h._depthTexture);var t=h.lensSize/h.fStop*h.focalLength/(h.focusDistance-h.focalLength);e.setFloat("focusDistance",h.focusDistance),e.setFloat("cocPrecalculation",t);var i=h._depthTexture.activeCamera;e.setFloat2("cameraMinMaxZ",i.minZ,i.maxZ-i.minZ)}else ae.Warn("No depth texture set on CircleOfConfusionPostProcess")})),h}return m(t,e),t.prototype.getClassName=function(){return"CircleOfConfusionPostProcess"},Object.defineProperty(t.prototype,"depthTexture",{set:function(e){this._depthTexture=e},enumerable:!1,configurable:!0}),v([Ie()],t.prototype,"lensSize",void 0),v([Ie()],t.prototype,"fStop",void 0),v([Ie()],t.prototype,"focusDistance",void 0),v([Ie()],t.prototype,"focalLength",void 0),t}(hl);a("BABYLON.CircleOfConfusionPostProcess",SC);li.ShadersStore.colorCorrectionPixelShader="uniform sampler2D textureSampler; \nuniform sampler2D colorTable; \nvarying vec2 vUV;const float SLICE_COUNT=16.0; \nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);float zSlice1=min(zSlice0+1.0,width-1.0);float xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;float s0=xOffset+(zSlice0*sliceSize);float s1=xOffset+(zSlice1*sliceSize);vec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));vec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));float zOffset=mod(uv.z*width,1.0);vec4 result=mix(slice0Color,slice1Color,zOffset);return result;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}";var xC=function(e){function t(t,i,r,n,o,a,s){var l=e.call(this,t,"colorCorrection",null,["colorTable"],r,n,o,a,s)||this,c=(null==n?void 0:n.getScene())||null;return l._colorTableTexture=new Ja(i,c,!0,!1,Ja.TRILINEAR_SAMPLINGMODE),l._colorTableTexture.anisotropicFilteringLevel=1,l._colorTableTexture.wrapU=Ja.CLAMP_ADDRESSMODE,l._colorTableTexture.wrapV=Ja.CLAMP_ADDRESSMODE,l.colorTableUrl=i,l.onApply=function(e){e.setTexture("colorTable",l._colorTableTexture)},l}return m(t,e),t.prototype.getClassName=function(){return"ColorCorrectionPostProcess"},t._Parse=function(e,i,r,n){return Ke.Parse((function(){return new t(e.name,e.colorTableUrl,e.options,i,e.renderTargetSamplingMode,r.getEngine(),e.reusable)}),e,r,n)},v([Ie()],t.prototype,"colorTableUrl",void 0),t}(hl);a("BABYLON.ColorCorrectionPostProcess",xC);li.ShadersStore.convolutionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9];\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}";var AC=function(e){function t(t,i,r,n,o,a,s,l){void 0===l&&(l=u.TEXTURETYPE_UNSIGNED_INT);var c=e.call(this,t,"convolution",["kernel","screenSize"],null,r,n,o,a,s,null,l)||this;return c.kernel=i,c.onApply=function(e){e.setFloat2("screenSize",c.width,c.height),e.setArray("kernel",c.kernel)},c}return m(t,e),t.prototype.getClassName=function(){return"ConvolutionPostProcess"},t._Parse=function(e,i,r,n){return Ke.Parse((function(){return new t(e.name,e.kernel,e.options,i,e.renderTargetSamplingMode,r.getEngine(),e.reusable,e.textureType)}),e,r,n)},t.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],t.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],t.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],t.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],t.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],t.GaussianKernel=[0,1,0,1,1,1,0,1,0],v([Ie()],t.prototype,"kernel",void 0),t}(hl);a("BABYLON.ConvolutionPostProcess",AC);var CC=function(e){function t(t,i,r,n,o,a,s,l,c,h,d,p,f,_){void 0===l&&(l=null),void 0===c&&(c=Ja.BILINEAR_SAMPLINGMODE),void 0===p&&(p=u.TEXTURETYPE_UNSIGNED_INT),void 0===f&&(f=!1),void 0===_&&(_=u.TEXTUREFORMAT_RGBA);var m=e.call(this,t,r,n,o,a,c=u.TEXTURE_BILINEAR_SAMPLINGMODE,h,d,p,"#define DOF 1\n",f,_)||this;return m.direction=r,m.externalTextureSamplerBinding=!!l,m.onApplyObservable.add((function(e){null!=l&&e.setTextureFromPostProcess("textureSampler",l),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",s)})),m}return m(t,e),t.prototype.getClassName=function(){return"DepthOfFieldBlurPostProcess"},v([Ie()],t.prototype,"direction",void 0),t}(Om);a("BABYLON.DepthOfFieldBlurPostProcess",CC);li.ShadersStore.depthOfFieldMergePixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r;\n#if BLUR_LEVEL==0\nvec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL==1\nif(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);}\n#endif\n#if BLUR_LEVEL==2\nif(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);}\n#endif\n}\n";var RC,PC=function(e){function t(t,i,r,n,o,a,s,l,c,h,d){void 0===h&&(h=u.TEXTURETYPE_UNSIGNED_INT),void 0===d&&(d=!1);var p=e.call(this,t,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],o,a,s,l,c,null,h,void 0,null,!0)||this;return p._blurSteps=n,p.externalTextureSamplerBinding=!0,p.onApplyObservable.add((function(e){e.setTextureFromPostProcess("textureSampler",i),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",r),n.forEach((function(t,i){e.setTextureFromPostProcessOutput("blurStep"+(n.length-i-1),t)}))})),d||p.updateEffect(),p}return m(t,e),t.prototype.getClassName=function(){return"DepthOfFieldMergePostProcess"},t.prototype.updateEffect=function(t,i,r,n,o,a){void 0===t&&(t=null),void 0===i&&(i=null),void 0===r&&(r=null),t||(t="",t+="#define BLUR_LEVEL "+(this._blurSteps.length-1)+"\n"),e.prototype.updateEffect.call(this,t,i,r,n,o,a)},t}(hl);!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(RC||(RC={}));var IC=function(e){function t(t,i,r,n,o){void 0===r&&(r=RC.Low),void 0===n&&(n=0),void 0===o&&(o=!1);var a=e.call(this,t.getEngine(),"depth of field",(function(){return a._effects}),!0)||this;a._effects=[];var s=t.getEngine(),l=s.isWebGPU||s.version>1?u.TEXTUREFORMAT_RED:u.TEXTUREFORMAT_RGBA;a._circleOfConfusion=new SC("circleOfConfusion",i,1,null,Ja.BILINEAR_SAMPLINGMODE,s,!1,n,o),a._depthOfFieldBlurY=[],a._depthOfFieldBlurX=[];var c=1,h=15;switch(r){case RC.High:c=3,h=51;break;case RC.Medium:c=2,h=31;break;default:h=15,c=1}for(var d=h/Math.pow(2,c-1),p=1,f=0;f<c;f++){var _=new CC("vertical blur",t,new U(0,1),d,p,null,a._circleOfConfusion,0==f?a._circleOfConfusion:null,Ja.BILINEAR_SAMPLINGMODE,s,!1,n,o,0==f?l:u.TEXTUREFORMAT_RGBA);_.autoClear=!1,p=.75/Math.pow(2,f);var m=new CC("horizontal blur",t,new U(1,0),d,p,null,a._circleOfConfusion,null,Ja.BILINEAR_SAMPLINGMODE,s,!1,n,o);m.autoClear=!1,a._depthOfFieldBlurY.push(_),a._depthOfFieldBlurX.push(m)}for(a._effects=[a._circleOfConfusion],f=0;f<a._depthOfFieldBlurX.length;f++)a._effects.push(a._depthOfFieldBlurY[f]),a._effects.push(a._depthOfFieldBlurX[f]);return a._dofMerge=new PC("dofMerge",a._circleOfConfusion,a._circleOfConfusion,a._depthOfFieldBlurX,p,null,Ja.BILINEAR_SAMPLINGMODE,s,!1,n,o),a._dofMerge.autoClear=!1,a._effects.push(a._dofMerge),a}return m(t,e),Object.defineProperty(t.prototype,"focalLength",{get:function(){return this._circleOfConfusion.focalLength},set:function(e){this._circleOfConfusion.focalLength=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"fStop",{get:function(){return this._circleOfConfusion.fStop},set:function(e){this._circleOfConfusion.fStop=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"focusDistance",{get:function(){return this._circleOfConfusion.focusDistance},set:function(e){this._circleOfConfusion.focusDistance=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"lensSize",{get:function(){return this._circleOfConfusion.lensSize},set:function(e){this._circleOfConfusion.lensSize=e},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"DepthOfFieldEffect"},Object.defineProperty(t.prototype,"depthTexture",{set:function(e){this._circleOfConfusion.depthTexture=e},enumerable:!1,configurable:!0}),t.prototype.disposeEffects=function(e){for(var t=0;t<this._effects.length;t++)this._effects[t].dispose(e)},t.prototype._updateEffects=function(){for(var e=0;e<this._effects.length;e++)this._effects[e].updateEffect()},t.prototype._isReady=function(){for(var e=0;e<this._effects.length;e++)if(!this._effects[e].isReady())return!1;return!0},t}(vC);li.ShadersStore.displayPassPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D passSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(passSampler,vUV);}";var MC=function(e){function t(t,i,r,n,o,a){return e.call(this,t,"displayPass",["passSampler"],["passSampler"],i,r,n,o,a)||this}return m(t,e),t.prototype.getClassName=function(){return"DisplayPassPostProcess"},t._Parse=function(e,i,r,n){return Ke.Parse((function(){return new t(e.name,e.options,i,e.renderTargetSamplingMode,r.getEngine(),e.reusable)}),e,r,n)},t}(hl);a("BABYLON.DisplayPassPostProcess",MC);li.ShadersStore.filterPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}";var OC=function(e){function t(t,i,r,n,o,a,s){var l=e.call(this,t,"filter",["kernelMatrix"],null,r,n,o,a,s)||this;return l.kernelMatrix=i,l.onApply=function(e){e.setMatrix("kernelMatrix",l.kernelMatrix)},l}return m(t,e),t.prototype.getClassName=function(){return"FilterPostProcess"},t._Parse=function(e,i,r,n){return Ke.Parse((function(){return new t(e.name,e.kernelMatrix,e.options,i,e.renderTargetSamplingMode,r.getEngine(),e.reusable)}),e,r,n)},v([ke()],t.prototype,"kernelMatrix",void 0),t}(hl);a("BABYLON.FilterPostProcess",OC);li.ShadersStore.fxaaPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nuniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{gl_FragColor=rgbyM;return;}\n#endif\nfloat lumaNW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordNW,0.0));float lumaSE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordSE,0.0));float lumaNE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordNE,0.0));float lumaSW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordSW,0.0));float lumaNS=lumaN+lumaS;float lumaWE=lumaW+lumaE;float subpixRcpRange=1.0/range;float subpixNSWE=lumaNS+lumaWE;float edgeHorz1=(-2.0*lumaM)+lumaNS;float edgeVert1=(-2.0*lumaM)+lumaWE;float lumaNESE=lumaNE+lumaSE;float lumaNWNE=lumaNW+lumaNE;float edgeHorz2=(-2.0*lumaE)+lumaNESE;float edgeVert2=(-2.0*lumaN)+lumaNWNE;float lumaNWSW=lumaNW+lumaSW;float lumaSWSE=lumaSW+lumaSE;float edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);float edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);float edgeHorz3=(-2.0*lumaW)+lumaNWSW;float edgeVert3=(-2.0*lumaS)+lumaSWSE;float edgeHorz=abs(edgeHorz3)+edgeHorz4;float edgeVert=abs(edgeVert3)+edgeVert4;float subpixNWSWNESE=lumaNWSW+lumaNESE;float lengthSign=texelSize.x;bool horzSpan=edgeHorz>=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan)\n{lumaN=lumaW;}\nif (!horzSpan) \n{lumaS=lumaE;}\nif (horzSpan) \n{lengthSign=texelSize.y;}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN)\n{lengthSign=-lengthSign;}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) \n{posB.x+=lengthSign*0.5;}\nif (horzSpan)\n{posB.y+=lengthSign*0.5;}\nvec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) \n{lumaNN=lumaSS;}\nfloat gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) \n{posN.x-=offNP.x*3.0;}\nif (!doneN) \n{posN.y-=offNP.y*3.0;}\nbool doneNP=(!doneN) || (!doneP);if (!doneP) \n{posP.x+=offNP.x*3.0;}\nif (!doneP)\n{posP.y+=offNP.y*3.0;}\nif (doneNP)\n{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;}\nfloat dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan)\n{dstN=posM.y-posN.y;}\nif (!horzSpan) \n{dstP=posP.y-posM.y;}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN<dstP;float dst=min(dstN,dstP);bool goodSpan=directionN ? goodSpanN : goodSpanP;float subpixG=subpixF*subpixF;float pixelOffset=(dst*(-spanLengthRcp))+0.5;float subpixH=subpixG*fxaaQualitySubpix;float pixelOffsetGood=goodSpan ? pixelOffset : 0.0;float pixelOffsetSubpix=max(pixelOffsetGood,subpixH);if (!horzSpan)\n{posM.x+=pixelOffsetSubpix*lengthSign;}\nif (horzSpan)\n{posM.y+=pixelOffsetSubpix*lengthSign;}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{gl_FragColor=rgbyM;}\nelse\n{gl_FragColor=TEXTUREFUNC(textureSampler,posM,0.0);}\n#else\ngl_FragColor=TEXTUREFUNC(textureSampler,posM,0.0);\n#endif\n}";li.ShadersStore.fxaaVertexShader="attribute vec2 position;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=(position*madd+madd);sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";var DC=function(e){function t(t,i,r,n,o,a,s){void 0===r&&(r=null),void 0===s&&(s=u.TEXTURETYPE_UNSIGNED_INT);var l=e.call(this,t,"fxaa",["texelSize"],null,i,r,n||Ja.BILINEAR_SAMPLINGMODE,o,a,null,s,"fxaa",void 0,!0)||this,c=l._getDefines();return l.updateEffect(c),l.onApplyObservable.add((function(e){var t=l.texelSize;e.setFloat2("texelSize",t.x,t.y)})),l}return m(t,e),t.prototype.getClassName=function(){return"FxaaPostProcess"},t.prototype._getDefines=function(){var e=this.getEngine();return e&&e.extractDriverInfo().toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null},t._Parse=function(e,i,r,n){return Ke.Parse((function(){return new t(e.name,e.options,i,e.renderTargetSamplingMode,r.getEngine(),e.reusable)}),e,r,n)},t}(hl);a("BABYLON.FxaaPostProcess",DC);li.ShadersStore.grainPixelShader="#include<helperFunctions>\nuniform sampler2D textureSampler; \nuniform float intensity;uniform float animatedSeed;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}";var NC=function(e){function t(t,i,r,n,o,a,s,l){void 0===s&&(s=u.TEXTURETYPE_UNSIGNED_INT),void 0===l&&(l=!1);var c=e.call(this,t,"grain",["intensity","animatedSeed"],[],i,r,n,o,a,null,s,void 0,null,l)||this;return c.intensity=30,c.animated=!1,c.onApplyObservable.add((function(e){e.setFloat("intensity",c.intensity),e.setFloat("animatedSeed",c.animated?Math.random()+1:1)})),c}return m(t,e),t.prototype.getClassName=function(){return"GrainPostProcess"},t._Parse=function(e,i,r,n){return Ke.Parse((function(){return new t(e.name,e.options,i,e.renderTargetSamplingMode,r.getEngine(),e.reusable)}),e,r,n)},v([Ie()],t.prototype,"intensity",void 0),v([Ie()],t.prototype,"animated",void 0),t}(hl);a("BABYLON.GrainPostProcess",NC);li.ShadersStore.highlightsPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec4 tex=texture2D(textureSampler,vUV);vec3 c=tex.rgb;float luma=dot(c.rgb,RGBLuminanceCoefficients);gl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); }";var FC=function(e){function t(t,i,r,n,o,a,s){return void 0===s&&(s=u.TEXTURETYPE_UNSIGNED_INT),e.call(this,t,"highlights",null,null,i,r,n,o,a,null,s)||this}return m(t,e),t.prototype.getClassName=function(){return"HighlightsPostProcess"},t}(hl);li.ShadersStore.imageProcessingPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;}";var LC=function(e){function t(t,i,r,n,o,a,s,l){void 0===r&&(r=null),void 0===s&&(s=u.TEXTURETYPE_UNSIGNED_INT);var c=e.call(this,t,"imageProcessing",[],[],i,r,n,o,a,null,s,"postprocess",null,!0)||this;return c._fromLinearSpace=!0,c._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:0,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},l?(l.applyByPostProcess=!0,c._attachImageProcessingConfiguration(l,!0),c._updateParameters()):(c._attachImageProcessingConfiguration(null,!0),c.imageProcessingConfiguration.applyByPostProcess=!0),c.onApply=function(e){c.imageProcessingConfiguration.bind(e,c.aspectRatio)},c}return m(t,e),Object.defineProperty(t.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)},enumerable:!1,configurable:!0}),t.prototype._attachImageProcessingConfiguration=function(e,t){var i=this;if(void 0===t&&(t=!1),e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{var r=null,n=this.getEngine(),o=this.getCamera();if(o)r=o.getScene();else if(n&&n.scenes){var a=n.scenes;r=a[a.length-1]}else r=M.LastCreatedScene;this._imageProcessingConfiguration=r?r.imageProcessingConfiguration:new pr}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((function(){i._updateParameters()}))),t||this._updateParameters()}},Object.defineProperty(t.prototype,"isSupported",{get:function(){var e=this.getEffect();return!e||e.isSupported},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"colorCurves",{get:function(){return this.imageProcessingConfiguration.colorCurves},set:function(e){this.imageProcessingConfiguration.colorCurves=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"colorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"colorGradingTexture",{get:function(){return this.imageProcessingConfiguration.colorGradingTexture},set:function(e){this.imageProcessingConfiguration.colorGradingTexture=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"colorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"exposure",{get:function(){return this.imageProcessingConfiguration.exposure},set:function(e){this.imageProcessingConfiguration.exposure=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"toneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"toneMappingType",{get:function(){return this._imageProcessingConfiguration.toneMappingType},set:function(e){this._imageProcessingConfiguration.toneMappingType=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"contrast",{get:function(){return this.imageProcessingConfiguration.contrast},set:function(e){this.imageProcessingConfiguration.contrast=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vignetteStretch",{get:function(){return this.imageProcessingConfiguration.vignetteStretch},set:function(e){this.imageProcessingConfiguration.vignetteStretch=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vignetteCentreX",{get:function(){return this.imageProcessingConfiguration.vignetteCenterX},set:function(e){this.imageProcessingConfiguration.vignetteCenterX=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vignetteCentreY",{get:function(){return this.imageProcessingConfiguration.vignetteCenterY},set:function(e){this.imageProcessingConfiguration.vignetteCenterY=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vignetteCenterY",{get:function(){return this.imageProcessingConfiguration.vignetteCenterY},set:function(e){this.imageProcessingConfiguration.vignetteCenterY=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vignetteCenterX",{get:function(){return this.imageProcessingConfiguration.vignetteCenterX},set:function(e){this.imageProcessingConfiguration.vignetteCenterX=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vignetteWeight",{get:function(){return this.imageProcessingConfiguration.vignetteWeight},set:function(e){this.imageProcessingConfiguration.vignetteWeight=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vignetteColor",{get:function(){return this.imageProcessingConfiguration.vignetteColor},set:function(e){this.imageProcessingConfiguration.vignetteColor=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vignetteCameraFov",{get:function(){return this.imageProcessingConfiguration.vignetteCameraFov},set:function(e){this.imageProcessingConfiguration.vignetteCameraFov=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vignetteBlendMode",{get:function(){return this.imageProcessingConfiguration.vignetteBlendMode},set:function(e){this.imageProcessingConfiguration.vignetteBlendMode=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vignetteEnabled",{get:function(){return this.imageProcessingConfiguration.vignetteEnabled},set:function(e){this.imageProcessingConfiguration.vignetteEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"ditheringIntensity",{get:function(){return this.imageProcessingConfiguration.ditheringIntensity},set:function(e){this.imageProcessingConfiguration.ditheringIntensity=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"ditheringEnabled",{get:function(){return this.imageProcessingConfiguration.ditheringEnabled},set:function(e){this.imageProcessingConfiguration.ditheringEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"fromLinearSpace",{get:function(){return this._fromLinearSpace},set:function(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"ImageProcessingPostProcess"},t.prototype._updateParameters=function(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);var e="";for(var t in this._defines){var i=this._defines[t];switch(typeof i){case"number":case"string":e+="#define ".concat(t," ").concat(i,";\n");break;default:i&&(e+="#define ".concat(t,";\n"))}}var r=["textureSampler"],n=["scale"];pr&&(pr.PrepareSamplers(r,this._defines),pr.PrepareUniforms(n,this._defines)),this.updateEffect(e,n,r)},t.prototype.dispose=function(t){e.prototype.dispose.call(this,t),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)},v([Ie()],t.prototype,"_fromLinearSpace",void 0),t}(hl);li.IncludesShadersStore.mrtFragmentDeclaration="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n";li.ShadersStore.geometryPixelShader="#extension GL_EXT_draw_buffers : require\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\nprecision highp float;\n#ifdef BUMP\nvarying mat4 vWorldView;varying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nvarying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#ifdef NEED_UV\nvarying vec2 vUV;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIVITY)\n#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nuniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV;\n#endif\n#ifdef ALBEDOTEXTURE\nvarying vec2 vAlbedoUV;uniform sampler2D albedoSampler;\n#endif\n#ifdef REFLECTIVITYCOLOR\nuniform vec3 reflectivityColor;\n#endif\n#ifdef ALBEDOCOLOR\nuniform vec3 albedoColor;\n#endif\n#ifdef METALLIC\nuniform float metallic;\n#endif\n#if defined(ROUGHNESS) || defined(GLOSSINESS)\nuniform float glossiness;\n#endif\n#endif\n#if defined(ALPHATEST) && defined(NEED_UV)\nuniform sampler2D diffuseSampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<mrtFragmentDeclaration>[RENDER_TARGET_COUNT]\n#include<bumpFragmentMainFunctions>\n#include<bumpFragmentFunctions>\n#include<helperFunctions>\nvoid main() {\n#include<clipPlaneFragment>\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nvec3 normalOutput;\n#ifdef BUMP\nvec3 normalW=normalize(vNormalW);\n#include<bumpFragment>\n#ifdef NORMAL_WORLDSPACE\nnormalOutput=normalW;\n#else\nnormalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0)));\n#endif\n#else\nnormalOutput=normalize(vNormalV);\n#endif\n#ifdef ENCODE_NORMAL\nnormalOutput=normalOutput*0.5+0.5;\n#endif\n#ifdef PREPASS\n#ifdef PREPASS_DEPTH\ngl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n#endif\n#ifdef PREPASS_NORMAL\ngl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0);\n#endif\n#else\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);gl_FragData[1]=vec4(normalOutput,1.0);\n#endif\n#ifdef POSITION\ngl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0);\n#endif\n#ifdef VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0);\n#endif\n#ifdef REFLECTIVITY\nvec4 reflectivity=vec4(0.0,0.0,0.0,1.0);\n#ifdef METALLICWORKFLOW\nfloat metal=1.0;float roughness=1.0;\n#ifdef ORMTEXTURE\nmetal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g;\n#endif\n#ifdef METALLIC\nmetal*=metallic;\n#endif\n#ifdef ROUGHNESS\nroughness*=(1.0-glossiness); \n#endif\nreflectivity.a-=roughness;vec3 color=vec3(1.0);\n#ifdef ALBEDOTEXTURE\ncolor=texture2D(albedoSampler,vAlbedoUV).rgb;\n#ifdef GAMMAALBEDO\ncolor=toLinearSpace(color);\n#endif\n#endif\n#ifdef ALBEDOCOLOR\ncolor*=albedoColor.xyz;\n#endif\nreflectivity.rgb=mix(vec3(0.04),color,metal);\n#else\n#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nreflectivity=texture2D(reflectivitySampler,vReflectivityUV);\n#ifdef GAMMAREFLECTIVITYTEXTURE\nreflectivity.rgb=toLinearSpace(reflectivity.rgb);\n#endif\n#else \n#ifdef REFLECTIVITYCOLOR\nreflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0;\n#endif\n#endif\n#ifdef GLOSSINESSS\nreflectivity.a*=glossiness; \n#endif\n#endif\ngl_FragData[REFLECTIVITY_INDEX]=reflectivity;\n#endif\n}\n";li.IncludesShadersStore.geometryVertexDeclaration="uniform mat4 viewProjection;uniform mat4 view;";li.IncludesShadersStore.geometryUboDeclaration="#include<sceneUboDeclaration>\n";li.ShadersStore.geometryVertexShader="precision highp float;\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#include<instancesDeclaration>\n#include<__decl__geometryVertex>\n#include<clipPlaneVertexDeclaration>\nattribute vec3 position;attribute vec3 normal;\n#ifdef NEED_UV\nvarying vec2 vUV;\n#ifdef ALPHATEST\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef BUMP\nuniform mat4 bumpMatrix;varying vec2 vBumpUV;\n#endif\n#ifdef REFLECTIVITY\nuniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef BUMP\nvarying mat4 vWorldView;\n#endif\n#ifdef BUMP\nvarying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nuniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertexGlobal>\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0));\n#ifdef BUMP\nvWorldView=view*finalWorld;vNormalW=normalUpdated;\n#else\n#ifdef NORMAL_WORLDSPACE\nvNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#else\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0)));\n#endif\n#endif\nvViewPos=view*worldPos;\n#if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);\n#else\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#endif\n#if defined(POSITION) || defined(BUMP)\nvPositionW=worldPos.xyz/worldPos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#include<clipPlaneVertex>\n#ifdef NEED_UV\n#ifdef UV1\n#if defined(ALPHATEST) && defined(ALPHATEST_UV1)\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#else\nvUV=uv;\n#endif\n#ifdef BUMP_UV1\nvBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV1\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV1\nvAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#endif\n#ifdef UV2\n#if defined(ALPHATEST) && defined(ALPHATEST_UV2)\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#else\nvUV=uv2;\n#endif\n#ifdef BUMP_UV2\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV2\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV2\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#endif\n#include<bumpVertex>\n}\n";var wC=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","boneTextureWidth"];Go(wC);var BC=function(){function e(t,i,r,n){void 0===i&&(i=1),void 0===r&&(r=u.TEXTUREFORMAT_DEPTH16),this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._normalsAreUnsigned=!1,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new J(0,0,0,0),this._clearDepthColor=new J(1e8,0,0,1),this._positionIndex=-1,this._velocityIndex=-1,this._reflectivityIndex=-1,this._depthIndex=-1,this._normalIndex=-1,this._linkedWithPrePass=!1,this.useSpecificClearForDepthTexture=!1,this._scene=t,this._ratioOrDimensions=i,this._useUbo=t.getEngine().supportsUniformBuffers,this._depthFormat=r,this._textureTypesAndFormats=n||{},e._SceneComponentInitialization(this._scene),this._createRenderTargets()}return Object.defineProperty(e.prototype,"normalsAreUnsigned",{get:function(){return this._normalsAreUnsigned},enumerable:!1,configurable:!0}),e.prototype._linkPrePassRenderer=function(e){this._linkedWithPrePass=!0,this._prePassRenderer=e,this._multiRenderTarget&&(this._multiRenderTarget.onClearObservable.clear(),this._multiRenderTarget.onClearObservable.add((function(){})))},e.prototype._unlinkPrePassRenderer=function(){this._linkedWithPrePass=!1,this._createRenderTargets()},e.prototype._resetLayout=function(){this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._attachmentsFromPrePass=[]},e.prototype._forceTextureType=function(t,i){t===e.POSITION_TEXTURE_TYPE?(this._positionIndex=i,this._enablePosition=!0):t===e.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=i,this._enableVelocity=!0):t===e.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=i,this._enableReflectivity=!0):t===e.DEPTH_TEXTURE_TYPE?this._depthIndex=i:t===e.NORMAL_TEXTURE_TYPE&&(this._normalIndex=i)},e.prototype._setAttachments=function(e){this._attachmentsFromPrePass=e},e.prototype._linkInternalTexture=function(e){this._multiRenderTarget.setInternalTexture(e,0,!1)},Object.defineProperty(e.prototype,"renderList",{get:function(){return this._multiRenderTarget.renderList},set:function(e){this._multiRenderTarget.renderList=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isSupported",{get:function(){return this._multiRenderTarget.isSupported},enumerable:!1,configurable:!0}),e.prototype.getTextureIndex=function(t){switch(t){case e.POSITION_TEXTURE_TYPE:return this._positionIndex;case e.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case e.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case e.DEPTH_TEXTURE_TYPE:return this._linkedWithPrePass?this._depthIndex:0;case e.NORMAL_TEXTURE_TYPE:return this._linkedWithPrePass?this._normalIndex:1;default:return-1}},Object.defineProperty(e.prototype,"enablePosition",{get:function(){return this._enablePosition},set:function(e){this._enablePosition=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"enableVelocity",{get:function(){return this._enableVelocity},set:function(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets()),this._scene.needsPreviousWorldMatrices=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"enableReflectivity",{get:function(){return this._enableReflectivity},set:function(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"scene",{get:function(){return this._scene},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"ratio",{get:function(){return"object"==typeof this._ratioOrDimensions?1:this._ratioOrDimensions},enumerable:!1,configurable:!0}),e.prototype.isReady=function(e,t){var i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;var r=[],n=[Nr.PositionKind,Nr.NormalKind],o=e.getMesh();if(i){var a=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(r.push("#define ALPHATEST"),r.push("#define ALPHATEST_UV".concat(i.getAlphaTestTexture().coordinatesIndex+1)),a=!0),i.bumpTexture&&xu.BumpTextureEnabled&&(r.push("#define BUMP"),r.push("#define BUMP_UV".concat(i.bumpTexture.coordinatesIndex+1)),a=!0),this._enableReflectivity){var s=!1;"PBRMetallicRoughnessMaterial"===i.getClassName()?(i.metallicRoughnessTexture&&(r.push("#define ORMTEXTURE"),r.push("#define REFLECTIVITY_UV".concat(i.metallicRoughnessTexture.coordinatesIndex+1)),r.push("#define METALLICWORKFLOW"),a=!0,s=!0),null!=i.metallic&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),s=!0),null!=i.roughness&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),s=!0),s&&(i.baseTexture&&(r.push("#define ALBEDOTEXTURE"),r.push("#define ALBEDO_UV".concat(i.baseTexture.coordinatesIndex+1)),i.baseTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),a=!0),i.baseColor&&r.push("#define ALBEDOCOLOR"))):"PBRSpecularGlossinessMaterial"===i.getClassName()?(i.specularGlossinessTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push("#define REFLECTIVITY_UV".concat(i.specularGlossinessTexture.coordinatesIndex+1)),a=!0,i.specularGlossinessTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE")):i.specularColor&&r.push("#define REFLECTIVITYCOLOR"),null!=i.glossiness&&r.push("#define GLOSSINESS")):"PBRMaterial"===i.getClassName()?(i.metallicTexture&&(r.push("#define ORMTEXTURE"),r.push("#define REFLECTIVITY_UV".concat(i.metallicTexture.coordinatesIndex+1)),r.push("#define METALLICWORKFLOW"),a=!0,s=!0),null!=i.metallic&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),s=!0),null!=i.roughness&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),s=!0),s?(i.albedoTexture&&(r.push("#define ALBEDOTEXTURE"),r.push("#define ALBEDO_UV".concat(i.albedoTexture.coordinatesIndex+1)),i.albedoTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),a=!0),i.albedoColor&&r.push("#define ALBEDOCOLOR")):(i.reflectivityTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push("#define REFLECTIVITY_UV".concat(i.reflectivityTexture.coordinatesIndex+1)),i.reflectivityTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),a=!0):i.reflectivityColor&&r.push("#define REFLECTIVITYCOLOR"),null!=i.microSurface&&r.push("#define GLOSSINESS"))):"StandardMaterial"===i.getClassName()&&(i.specularTexture&&(r.push("#define REFLECTIVITYTEXTURE"),r.push("#define REFLECTIVITY_UV".concat(i.specularTexture.coordinatesIndex+1)),i.specularTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),a=!0),i.specularColor&&r.push("#define REFLECTIVITYCOLOR"))}a&&(r.push("#define NEED_UV"),o.isVerticesDataPresent(Nr.UVKind)&&(n.push(Nr.UVKind),r.push("#define UV1")),o.isVerticesDataPresent(Nr.UV2Kind)&&(n.push(Nr.UV2Kind),r.push("#define UV2")))}this._linkedWithPrePass&&(r.push("#define PREPASS"),-1!==this._depthIndex&&(r.push("#define DEPTH_INDEX "+this._depthIndex),r.push("#define PREPASS_DEPTH")),-1!==this._normalIndex&&(r.push("#define NORMAL_INDEX "+this._normalIndex),r.push("#define PREPASS_NORMAL"))),this._enablePosition&&(r.push("#define POSITION"),r.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(r.push("#define VELOCITY"),r.push("#define VELOCITY_INDEX "+this._velocityIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(o)&&r.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(r.push("#define REFLECTIVITY"),r.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this.generateNormalsInWorldSpace&&r.push("#define NORMAL_WORLDSPACE"),this._normalsAreUnsigned&&r.push("#define ENCODE_NORMAL"),o.useBones&&o.computeBonesUsingShaders&&o.skeleton?(n.push(Nr.MatricesIndicesKind),n.push(Nr.MatricesWeightsKind),o.numBoneInfluencers>4&&(n.push(Nr.MatricesIndicesExtraKind),n.push(Nr.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+o.numBoneInfluencers),r.push("#define BONETEXTURE "+o.skeleton.isUsingTextureForMatrices),r.push("#define BonesPerMesh "+(o.skeleton.bones.length+1))):(r.push("#define NUM_BONE_INFLUENCERS 0"),r.push("#define BONETEXTURE false"),r.push("#define BonesPerMesh 0"));var l=o.morphTargetManager,c=0;l&&(c=l.numMaxInfluencers||l.numInfluencers)>0&&(r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+c),l.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),qo(n,o,c)),t&&(r.push("#define INSTANCES"),Jo(n,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES")),this._linkedWithPrePass?r.push("#define RENDER_TARGET_COUNT "+this._attachmentsFromPrePass.length):r.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length),zo(i,this._scene,r);var u=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),d=h.defines,p=r.join("\n");return d!==p&&h.setEffect(u.createEffect("geometry",{attributes:n,uniformsNames:wC,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets","boneSampler"],defines:p,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:c}},u),p),h.effect.isReady()},e.prototype.getGBuffer=function(){return this._multiRenderTarget},Object.defineProperty(e.prototype,"samples",{get:function(){return this._multiRenderTarget.samples},set:function(e){this._multiRenderTarget.samples=e},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.getGBuffer().dispose()},e.prototype._assignRenderTargetIndices=function(){var t=[],i=[],r=2;return t.push("gBuffer_Depth","gBuffer_Normal"),i.push(this._textureTypesAndFormats[e.DEPTH_TEXTURE_TYPE]),i.push(this._textureTypesAndFormats[e.NORMAL_TEXTURE_TYPE]),this._enablePosition&&(this._positionIndex=r,r++,t.push("gBuffer_Position"),i.push(this._textureTypesAndFormats[e.POSITION_TEXTURE_TYPE])),this._enableVelocity&&(this._velocityIndex=r,r++,t.push("gBuffer_Velocity"),i.push(this._textureTypesAndFormats[e.VELOCITY_TEXTURE_TYPE])),this._enableReflectivity&&(this._reflectivityIndex=r,r++,t.push("gBuffer_Reflectivity"),i.push(this._textureTypesAndFormats[e.REFLECTIVITY_TEXTURE_TYPE])),[r,t,i]},e.prototype._createRenderTargets=function(){var t,i=this,r=this._scene.getEngine(),n=(t=this._assignRenderTargetIndices())[0],o=t[1],a=t[2],s=u.TEXTURETYPE_UNSIGNED_BYTE;r._caps.textureFloat&&r._caps.textureFloatLinearFiltering?s=u.TEXTURETYPE_FLOAT:r._caps.textureHalfFloat&&r._caps.textureHalfFloatLinearFiltering&&(s=u.TEXTURETYPE_HALF_FLOAT);for(var l=void 0!==this._ratioOrDimensions.width?this._ratioOrDimensions:{width:r.getRenderWidth()*this._ratioOrDimensions,height:r.getRenderHeight()*this._ratioOrDimensions},c=[],h=[],d=0,p=a;d<p.length;d++){var f=p[d];f?(c.push(f.textureType),h.push(f.textureFormat)):(c.push(s),h.push(u.TEXTUREFORMAT_RGBA))}if(this._normalsAreUnsigned=c[e.NORMAL_TEXTURE_TYPE]===u.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV||c[e.NORMAL_TEXTURE_TYPE]===u.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV,this._multiRenderTarget=new ky("gBuffer",l,n,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,types:c,formats:h,depthTextureFormat:this._depthFormat},o.concat("gBuffer_DepthBuffer")),this.isSupported){this._multiRenderTarget.wrapU=Ja.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=Ja.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;for(var _=[!0],m=[!1],g=[!0],v=1;v<n;++v)_.push(!0),g.push(!1),m.push(!0);var y=r.buildTextureLayout(_),b=r.buildTextureLayout(m),T=r.buildTextureLayout(g);this._multiRenderTarget.onClearObservable.add((function(e){e.bindAttachments(i.useSpecificClearForDepthTexture?b:y),e.clear(i._clearColor,!0,!0,!0),i.useSpecificClearForDepthTexture&&(e.bindAttachments(T),e.clear(i._clearDepthColor,!0,!0,!0)),e.bindAttachments(y)})),this._resizeObserver=r.onResizeObservable.add((function(){if(i._multiRenderTarget){var e=void 0!==i._ratioOrDimensions.width?i._ratioOrDimensions:{width:r.getRenderWidth()*i._ratioOrDimensions,height:r.getRenderHeight()*i._ratioOrDimensions};i._multiRenderTarget.resize(e)}}));var E=function(e){var t=e.getRenderingMesh(),r=e.getEffectiveMesh(),n=i._scene,o=n.getEngine(),a=e.getMaterial();if(a){if(r._internalAbstractMeshDataInfo._isActiveIntermediate=!1,i._enableVelocity&&!i._previousTransformationMatrices[r.uniqueId]&&(i._previousTransformationMatrices[r.uniqueId]={world:z.Identity(),viewProjection:n.getTransformMatrix()},t.skeleton)){var s=t.skeleton.getTransformMatrices(t);i._previousBonesTransformationMatrices[t.uniqueId]=i._copyBonesTransformationMatrices(s,new Float32Array(s.length))}var l=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(!l.mustReturn){var c=o.getCaps().instancedArrays&&(null!==l.visibleInstances[e._id]||t.hasThinInstances),u=r.getWorldMatrix();if(i.isReady(e,c)){var h=e._getDrawWrapper();if(!h)return;var d=h.effect;o.enableEffect(h),c||t._bind(e,d,a.fillMode),i._useUbo?(ea(d,i._scene.getSceneUniformBuffer()),i._scene.finalizeSceneUbo()):(d.setMatrix("viewProjection",n.getTransformMatrix()),d.setMatrix("view",n.getViewMatrix()));var p=void 0,f=t._instanceDataStorage;if(f.isFrozen||!a.backFaceCulling&&null===t.overrideMaterialSideOrientation)p=f.sideOrientation;else{var _=r._getWorldMatrixDeterminant();null===(p=t.overrideMaterialSideOrientation)&&(p=a.sideOrientation),_<0&&(p=p===Ca.ClockWiseSideOrientation?Ca.CounterClockWiseSideOrientation:Ca.ClockWiseSideOrientation)}if(a._preBind(h,p),a.needAlphaTesting()){var m=a.getAlphaTestTexture();m&&(d.setTexture("diffuseSampler",m),d.setMatrix("diffuseMatrix",m.getTextureMatrix()))}if(a.bumpTexture&&n.getEngine().getCaps().standardDerivatives&&xu.BumpTextureEnabled&&(d.setFloat3("vBumpInfos",a.bumpTexture.coordinatesIndex,1/a.bumpTexture.level,a.parallaxScaleBias),d.setMatrix("bumpMatrix",a.bumpTexture.getTextureMatrix()),d.setTexture("bumpSampler",a.bumpTexture),d.setFloat2("vTangentSpaceParams",a.invertNormalMapX?-1:1,a.invertNormalMapY?-1:1)),i._enableReflectivity&&("PBRMetallicRoughnessMaterial"===a.getClassName()?(null!==a.metallicRoughnessTexture&&(d.setTexture("reflectivitySampler",a.metallicRoughnessTexture),d.setMatrix("reflectivityMatrix",a.metallicRoughnessTexture.getTextureMatrix())),null!==a.metallic&&d.setFloat("metallic",a.metallic),null!==a.roughness&&d.setFloat("glossiness",1-a.roughness),null!==a.baseTexture&&(d.setTexture("albedoSampler",a.baseTexture),d.setMatrix("albedoMatrix",a.baseTexture.getTextureMatrix())),null!==a.baseColor&&d.setColor3("albedoColor",a.baseColor)):"PBRSpecularGlossinessMaterial"===a.getClassName()?(null!==a.specularGlossinessTexture?(d.setTexture("reflectivitySampler",a.specularGlossinessTexture),d.setMatrix("reflectivityMatrix",a.specularGlossinessTexture.getTextureMatrix())):null!==a.specularColor&&d.setColor3("reflectivityColor",a.specularColor),null!==a.glossiness&&d.setFloat("glossiness",a.glossiness)):"PBRMaterial"===a.getClassName()?(null!==a.metallicTexture&&(d.setTexture("reflectivitySampler",a.metallicTexture),d.setMatrix("reflectivityMatrix",a.metallicTexture.getTextureMatrix())),null!==a.metallic&&d.setFloat("metallic",a.metallic),null!==a.roughness&&d.setFloat("glossiness",1-a.roughness),null!==a.roughness||null!==a.metallic||null!==a.metallicTexture?(null!==a.albedoTexture&&(d.setTexture("albedoSampler",a.albedoTexture),d.setMatrix("albedoMatrix",a.albedoTexture.getTextureMatrix())),null!==a.albedoColor&&d.setColor3("albedoColor",a.albedoColor)):(null!==a.reflectivityTexture?(d.setTexture("reflectivitySampler",a.reflectivityTexture),d.setMatrix("reflectivityMatrix",a.reflectivityTexture.getTextureMatrix())):null!==a.reflectivityColor&&d.setColor3("reflectivityColor",a.reflectivityColor),null!==a.microSurface&&d.setFloat("glossiness",a.microSurface))):"StandardMaterial"===a.getClassName()&&(null!==a.specularTexture&&(d.setTexture("reflectivitySampler",a.specularTexture),d.setMatrix("reflectivityMatrix",a.specularTexture.getTextureMatrix())),null!==a.specularColor&&d.setColor3("reflectivityColor",a.specularColor))),Ho(d,a,i._scene),t.useBones&&t.computeBonesUsingShaders&&t.skeleton){var g=t.skeleton;if(g.isUsingTextureForMatrices&&d.getUniformIndex("boneTextureWidth")>-1){var v=g.getTransformMatrixTexture(t);d.setTexture("boneSampler",v),d.setFloat("boneTextureWidth",4*(g.bones.length+1))}else d.setMatrices("mBones",t.skeleton.getTransformMatrices(t));i._enableVelocity&&d.setMatrices("mPreviousBones",i._previousBonesTransformationMatrices[t.uniqueId])}$o(t,d),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(d),i._enableVelocity&&(d.setMatrix("previousWorld",i._previousTransformationMatrices[r.uniqueId].world),d.setMatrix("previousViewProjection",i._previousTransformationMatrices[r.uniqueId].viewProjection)),c&&t.hasThinInstances&&d.setMatrix("world",u),t._processRendering(r,e,d,a.fillMode,l,c,(function(e,t){e||d.setMatrix("world",t)}))}i._enableVelocity&&(i._previousTransformationMatrices[r.uniqueId].world=u.clone(),i._previousTransformationMatrices[r.uniqueId].viewProjection=i._scene.getTransformMatrix().clone(),t.skeleton&&i._copyBonesTransformationMatrices(t.skeleton.getTransformMatrices(t),i._previousBonesTransformationMatrices[r.uniqueId]))}}};this._multiRenderTarget.customIsReadyFunction=function(e,t,n){if((n||0===t)&&e.subMeshes)for(var o=0;o<e.subMeshes.length;++o){var a=e.subMeshes[o],s=a.getMaterial(),l=a.getRenderingMesh();if(s){var c=l._getInstancesRenderList(a._id,!!a.getReplacementMesh()),u=r.getCaps().instancedArrays&&(null!==c.visibleInstances[a._id]||l.hasThinInstances);if(!i.isReady(a,u))return!1}}return!0},this._multiRenderTarget.customRenderFunction=function(e,t,n,o){var a;if(i._linkedWithPrePass){if(!i._prePassRenderer.enabled)return;i._scene.getEngine().bindAttachments(i._attachmentsFromPrePass)}if(o.length){for(r.setColorWrite(!1),a=0;a<o.length;a++)E(o.data[a]);r.setColorWrite(!0)}for(a=0;a<e.length;a++)E(e.data[a]);for(r.setDepthWrite(!1),a=0;a<t.length;a++)E(t.data[a]);if(i.renderTransparentMeshes)for(a=0;a<n.length;a++)E(n.data[a]);r.setDepthWrite(!0)}}},e.prototype._copyBonesTransformationMatrices=function(e,t){for(var i=0;i<e.length;i++)t[i]=e[i];return t},e.DEPTH_TEXTURE_TYPE=0,e.NORMAL_TEXTURE_TYPE=1,e.POSITION_TEXTURE_TYPE=2,e.VELOCITY_TEXTURE_TYPE=3,e.REFLECTIVITY_TEXTURE_TYPE=4,e._SceneComponentInitialization=function(e){throw He("GeometryBufferRendererSceneComponent")},e}(),UC=function(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[u.PREPASS_VELOCITY_TEXTURE_TYPE]};Object.defineProperty(pn.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(e){e&&e.isSupported&&(this._geometryBufferRenderer=e)},enumerable:!0,configurable:!0}),pn.prototype.enableGeometryBufferRenderer=function(e,t,i){return void 0===e&&(e=1),void 0===t&&(t=u.TEXTUREFORMAT_DEPTH16),this._geometryBufferRenderer||(this._geometryBufferRenderer=new BC(this,e,t,i),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null)),this._geometryBufferRenderer},pn.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};var VC=function(){function e(e){this.name=Vr.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}return e.prototype.register=function(){this.scene._gatherRenderTargetsStage.registerStep(Vr.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)},e.prototype.rebuild=function(){},e.prototype.dispose=function(){},e.prototype._gatherRenderTargets=function(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())},e}();BC._SceneComponentInitialization=function(e){var t=e._getComponent(Vr.NAME_GEOMETRYBUFFERRENDERER);t||(t=new VC(e),e._addComponent(t))};li.ShadersStore.motionBlurPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize;\n#ifdef OBJECT_BASED\nuniform sampler2D velocitySampler;\n#else\nuniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#ifdef GEOMETRY_SUPPORTED\n#ifdef OBJECT_BASED\nvec2 texelSize=1.0/screenSize;vec4 velocityColor=texture2D(velocitySampler,vUV);velocityColor.rg=velocityColor.rg*2.0-vec2(1.0);vec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;velocity*=motionScale*motionStrength;float speed=length(velocity/texelSize);int samplesCount=int(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;float hlim=float(-samplesCount)*0.5+0.5;vec4 result=texture2D(textureSampler,vUV);for (int i=1; i<int(SAMPLES); ++i)\n{if (i>=samplesCount)\nbreak;vec2 offset=vUV+velocity*(hlim+float(i));\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset,0.0);\n#else\nresult+=texture2D(textureSampler,offset);\n#endif\n}\ngl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0;\n#else\nvec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; \nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=inverseViewProjection*cpos;cpos/=cpos.w;vec4 ppos=prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i<int(SAMPLES); ++i) {if (i>=nSamples)\nbreak;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset1,0.0);\n#else\nresult+=texture2D(textureSampler,offset1);\n#endif\n}\ngl_FragColor=result/float(nSamples);\n#endif\n#else\ngl_FragColor=texture2D(textureSampler,vUV);\n#endif\n}\n";var kC=function(e){function t(t,i,r,n,o,a,s,l,c,h){void 0===l&&(l=u.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=!1),void 0===h&&(h=!1);var d=e.call(this,t,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],r,n,o,a,s,"#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0\n#define OBJECT_BASED",l,void 0,null,c)||this;return d.motionStrength=1,d._motionBlurSamples=32,d._isObjectBased=!0,d._forceGeometryBuffer=!1,d._invViewProjection=null,d._previousViewProjection=null,d._forceGeometryBuffer=h,d._forceGeometryBuffer?(i.enableGeometryBufferRenderer(),d._geometryBufferRenderer&&(d._geometryBufferRenderer.enableVelocity=d._isObjectBased)):(i.enablePrePassRenderer(),d._prePassRenderer&&(d._prePassRenderer.markAsDirty(),d._prePassEffectConfiguration=new UC)),d._applyMode(),d}return m(t,e),Object.defineProperty(t.prototype,"motionBlurSamples",{get:function(){return this._motionBlurSamples},set:function(e){this._motionBlurSamples=e,this._updateEffect()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isObjectBased",{get:function(){return this._isObjectBased},set:function(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_geometryBufferRenderer",{get:function(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_prePassRenderer",{get:function(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"MotionBlurPostProcess"},t.prototype.excludeSkinnedMesh=function(e){if(e.skeleton){var t=void 0;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}t.push(e)}},t.prototype.removeExcludedSkinnedMesh=function(e){if(e.skeleton){var t=void 0;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}var i=t.indexOf(e);-1!==i&&t.splice(i,1)}},t.prototype.dispose=function(t){this._geometryBufferRenderer&&(this._geometryBufferRenderer._previousTransformationMatrices={},this._geometryBufferRenderer._previousBonesTransformationMatrices={},this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity=[]),e.prototype.dispose.call(this,t)},t.prototype._applyMode=function(){var e=this;if(!this._geometryBufferRenderer&&!this._prePassRenderer)return ae.Warn("Multiple Render Target support needed to compute object based motion blur"),this.updateEffect();this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased),this._updateEffect(),this._invViewProjection=null,this._previousViewProjection=null,this.isObjectBased?(this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=u.PREPASS_VELOCITY_TEXTURE_TYPE),this.onApply=function(t){return e._onApplyObjectBased(t)}):(this._invViewProjection=z.Identity(),this._previousViewProjection=this._scene.getTransformMatrix().clone(),this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=u.PREPASS_DEPTH_TEXTURE_TYPE),this.onApply=function(t){return e._onApplyScreenBased(t)})},t.prototype._onApplyObjectBased=function(e){if(e.setVector2("screenSize",new U(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){var t=this._geometryBufferRenderer.getTextureIndex(BC.VELOCITY_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else this._prePassRenderer&&(t=this._prePassRenderer.getIndex(u.PREPASS_VELOCITY_TEXTURE_TYPE),e.setTexture("velocitySampler",this._prePassRenderer.getRenderTarget().textures[t]))},t.prototype._onApplyScreenBased=function(e){var t=H.Matrix[0];if(t.copyFrom(this._scene.getTransformMatrix()),t.invertToRef(this._invViewProjection),e.setMatrix("inverseViewProjection",this._invViewProjection),e.setMatrix("prevViewProjection",this._previousViewProjection),this._previousViewProjection.copyFrom(t),e.setMatrix("projection",this._scene.getProjectionMatrix()),e.setVector2("screenSize",new U(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){var i=this._geometryBufferRenderer.getTextureIndex(BC.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[i])}else this._prePassRenderer&&(i=this._prePassRenderer.getIndex(u.PREPASS_DEPTH_TEXTURE_TYPE),e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[i]))},t.prototype._updateEffect=function(){if(this._geometryBufferRenderer||this._prePassRenderer){var e=["#define GEOMETRY_SUPPORTED","#define SAMPLES "+this._motionBlurSamples.toFixed(1),this._isObjectBased?"#define OBJECT_BASED":"#define SCREEN_BASED"];this.updateEffect(e.join("\n"))}},t._Parse=function(e,i,r,n){return Ke.Parse((function(){return new t(e.name,r,e.options,i,e.renderTargetSamplingMode,r.getEngine(),e.reusable,e.textureType,!1)}),e,r,n)},v([Ie()],t.prototype,"motionStrength",void 0),v([Ie()],t.prototype,"motionBlurSamples",null),v([Ie()],t.prototype,"isObjectBased",null),t}(hl);a("BABYLON.MotionBlurPostProcess",kC);li.ShadersStore.refractionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D refractionSampler;uniform vec3 baseColor;uniform float depth;uniform float colorLevel;void main() {float ref=1.0-texture2D(refractionSampler,vUV).r;vec2 uv=vUV-vec2(0.5);vec2 offset=uv*depth*ref;vec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;gl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);}";var GC=function(e){function t(t,i,r,n,o,a,s,l,c,u){var h=e.call(this,t,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],a,s,l,c,u)||this;return h._ownRefractionTexture=!0,h.color=r,h.depth=n,h.colorLevel=o,h.refractionTextureUrl=i,h.onActivateObservable.add((function(e){h._refTexture=h._refTexture||new Ja(i,e.getScene())})),h.onApplyObservable.add((function(e){e.setColor3("baseColor",h.color),e.setFloat("depth",h.depth),e.setFloat("colorLevel",h.colorLevel),e.setTexture("refractionSampler",h._refTexture)})),h}return m(t,e),Object.defineProperty(t.prototype,"refractionTexture",{get:function(){return this._refTexture},set:function(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"RefractionPostProcess"},t.prototype.dispose=function(t){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),e.prototype.dispose.call(this,t)},t._Parse=function(e,i,r,n){return Ke.Parse((function(){return new t(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,i,e.renderTargetSamplingMode,r.getEngine(),e.reusable)}),e,r,n)},v([Ie()],t.prototype,"color",void 0),v([Ie()],t.prototype,"depth",void 0),v([Ie()],t.prototype,"colorLevel",void 0),v([Ie()],t.prototype,"refractionTextureUrl",void 0),t}(hl);a("BABYLON.RefractionPostProcess",GC);li.ShadersStore.sharpenPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}";var zC=function(e){function t(t,i,r,n,o,a,s,l){void 0===s&&(s=u.TEXTURETYPE_UNSIGNED_INT),void 0===l&&(l=!1);var c=e.call(this,t,"sharpen",["sharpnessAmounts","screenSize"],null,i,r,n,o,a,null,s,void 0,null,l)||this;return c.colorAmount=1,c.edgeAmount=.3,c.onApply=function(e){e.setFloat2("screenSize",c.width,c.height),e.setFloat2("sharpnessAmounts",c.edgeAmount,c.colorAmount)},c}return m(t,e),t.prototype.getClassName=function(){return"SharpenPostProcess"},t._Parse=function(e,i,r,n){return Ke.Parse((function(){return new t(e.name,e.options,i,e.renderTargetSamplingMode,r.getEngine(),e.textureType,e.reusable)}),e,r,n)},v([Ie()],t.prototype,"colorAmount",void 0),v([Ie()],t.prototype,"edgeAmount",void 0),t}(hl);a("BABYLON.SharpenPostProcess",zC);var WC=function(){function e(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=new Array,this._cameras=[]}return Object.defineProperty(e.prototype,"name",{get:function(){return this._name},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"cameras",{get:function(){return this._cameras},enumerable:!1,configurable:!0}),e.prototype.getClassName=function(){return"PostProcessRenderPipeline"},Object.defineProperty(e.prototype,"isSupported",{get:function(){for(var e in this._renderEffects)if(Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&!this._renderEffects[e].isSupported)return!1;return!0},enumerable:!1,configurable:!0}),e.prototype.addEffect=function(e){this._renderEffects[e._name]=e},e.prototype._rebuild=function(){},e.prototype._enableEffect=function(e,t){var i=this._renderEffects[e];i&&i._enable(rr.MakeArray(t||this._cameras))},e.prototype._disableEffect=function(e,t){var i=this._renderEffects[e];i&&i._disable(rr.MakeArray(t||this._cameras))},e.prototype._attachCameras=function(e,t){var i=rr.MakeArray(e||this._cameras);if(i){var r,n=[];for(r=0;r<i.length;r++){var o=i[r];o&&(-1===this._cameras.indexOf(o)?this._cameras.push(o):t&&n.push(r))}for(r=0;r<n.length;r++)i.splice(n[r],1);for(var a in this._renderEffects)Object.prototype.hasOwnProperty.call(this._renderEffects,a)&&this._renderEffects[a]._attachCameras(i)}},e.prototype._detachCameras=function(e){var t=rr.MakeArray(e||this._cameras);if(t){for(var i in this._renderEffects)Object.prototype.hasOwnProperty.call(this._renderEffects,i)&&this._renderEffects[i]._detachCameras(t);for(var r=0;r<t.length;r++)this._cameras.splice(this._cameras.indexOf(t[r]),1)}},e.prototype._update=function(){for(var e in this._renderEffects)Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&this._renderEffects[e]._update();for(var t=0;t<this._cameras.length;t++)if(this._cameras[t]){var i=this._cameras[t].name;this._renderEffectsForIsolatedPass[i]&&this._renderEffectsForIsolatedPass[i]._update()}},e.prototype._reset=function(){this._renderEffects={},this._renderEffectsForIsolatedPass=new Array},e.prototype._enableMSAAOnFirstPostProcess=function(e){if(!this._engine._features.supportMSAA)return!1;var t=Object.keys(this._renderEffects);if(t.length>0){var i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0},e.prototype._adaptPostProcessesToViewPort=function(){for(var e=0,t=Object.keys(this._renderEffects);e<t.length;e++){var i=t[e],r=this._renderEffects[i].getPostProcesses();if(r)for(var n=0,o=r;n<o.length;n++)o[n].adaptScaleToCurrentViewport=!0}},e.prototype.setPrePassRenderer=function(e){return!1},e.prototype.dispose=function(){},v([Ie()],e.prototype,"_name",void 0),e}(),HC=function(){function e(){this._renderPipelines={}}return Object.defineProperty(e.prototype,"supportedPipelines",{get:function(){var e=[];for(var t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){var i=this._renderPipelines[t];i.isSupported&&e.push(i)}return e},enumerable:!1,configurable:!0}),e.prototype.addPipeline=function(e){this._renderPipelines[e._name]=e},e.prototype.removePipeline=function(e){delete this._renderPipelines[e]},e.prototype.attachCamerasToRenderPipeline=function(e,t,i){void 0===i&&(i=!1);var r=this._renderPipelines[e];r&&r._attachCameras(t,i)},e.prototype.detachCamerasFromRenderPipeline=function(e,t){var i=this._renderPipelines[e];i&&i._detachCameras(t)},e.prototype.enableEffectInPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._enableEffect(t,i)},e.prototype.disableEffectInPipeline=function(e,t,i){var r=this._renderPipelines[e];r&&r._disableEffect(t,i)},e.prototype.update=function(){for(var e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){var t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}},e.prototype._rebuild=function(){for(var e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e]._rebuild()},e.prototype.dispose=function(){for(var e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e].dispose()},e}();Object.defineProperty(pn.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){var e=this._getComponent(Vr.NAME_POSTPROCESSRENDERPIPELINEMANAGER);e||(e=new XC(this),this._addComponent(e)),this._postProcessRenderPipelineManager=new HC}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});var XC=function(){function e(e){this.name=Vr.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}return e.prototype.register=function(){this.scene._gatherRenderTargetsStage.registerStep(Vr.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER,this,this._gatherRenderTargets)},e.prototype.rebuild=function(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager._rebuild()},e.prototype.dispose=function(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.dispose()},e.prototype._gatherRenderTargets=function(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.update()},e}(),jC=function(e){function t(t,i,r,n,o){void 0===t&&(t=""),void 0===i&&(i=!0),void 0===r&&(r=M.LastCreatedScene),void 0===o&&(o=!0);var a=e.call(this,r.getEngine(),t)||this;a._camerasToBeAttached=[],a.SharpenPostProcessId="SharpenPostProcessEffect",a.ImageProcessingPostProcessId="ImageProcessingPostProcessEffect",a.FxaaPostProcessId="FxaaPostProcessEffect",a.ChromaticAberrationPostProcessId="ChromaticAberrationPostProcessEffect",a.GrainPostProcessId="GrainPostProcessEffect",a._glowLayer=null,a.animations=[],a._imageProcessingConfigurationObserver=null,a._sharpenEnabled=!1,a._bloomEnabled=!1,a._depthOfFieldEnabled=!1,a._depthOfFieldBlurLevel=RC.Low,a._fxaaEnabled=!1,a._imageProcessingEnabled=!0,a._bloomScale=.5,a._chromaticAberrationEnabled=!1,a._grainEnabled=!1,a._buildAllowed=!0,a.onBuildObservable=new f,a._resizeObserver=null,a._hardwareScaleLevel=1,a._bloomKernel=64,a._bloomWeight=.15,a._bloomThreshold=.9,a._samples=1,a._hasCleared=!1,a._prevPostProcess=null,a._prevPrevPostProcess=null,a._depthOfFieldSceneObserver=null,a._activeCameraChangedObserver=null,a._activeCamerasChangedObserver=null,a._cameras=n||r.cameras,a._cameras=a._cameras.slice(),a._camerasToBeAttached=a._cameras.slice(),a._buildAllowed=o,a._scene=r;var s=a._scene.getEngine().getCaps();a._hdr=i&&(s.textureHalfFloatRender||s.textureFloatRender),a._hdr?s.textureHalfFloatRender?a._defaultPipelineTextureType=u.TEXTURETYPE_HALF_FLOAT:s.textureFloatRender&&(a._defaultPipelineTextureType=u.TEXTURETYPE_FLOAT):a._defaultPipelineTextureType=u.TEXTURETYPE_UNSIGNED_INT,r.postProcessRenderPipelineManager.addPipeline(a);var l=a._scene.getEngine();a.sharpen=new zC("sharpen",1,null,Ja.BILINEAR_SAMPLINGMODE,l,!1,a._defaultPipelineTextureType,!0),a._sharpenEffect=new vC(l,a.SharpenPostProcessId,(function(){return a.sharpen}),!0),a.depthOfField=new IC(a._scene,null,a._depthOfFieldBlurLevel,a._defaultPipelineTextureType,!0),a._hardwareScaleLevel=l.getHardwareScalingLevel(),a._resizeObserver=l.onResizeObservable.add((function(){a._hardwareScaleLevel=l.getHardwareScalingLevel(),a.bloomKernel=a._bloomKernel})),a.bloom=new TC(a._scene,a._bloomScale,a._bloomWeight,a.bloomKernel/a._hardwareScaleLevel,a._defaultPipelineTextureType,!0),a.chromaticAberration=new EC("ChromaticAberration",l.getRenderWidth(),l.getRenderHeight(),1,null,Ja.BILINEAR_SAMPLINGMODE,l,!1,a._defaultPipelineTextureType,!0),a._chromaticAberrationEffect=new vC(l,a.ChromaticAberrationPostProcessId,(function(){return a.chromaticAberration}),!0),a.grain=new NC("Grain",1,null,Ja.BILINEAR_SAMPLINGMODE,l,!1,a._defaultPipelineTextureType,!0),a._grainEffect=new vC(l,a.GrainPostProcessId,(function(){return a.grain}),!0);var c=!0;return a._imageProcessingConfigurationObserver=a._scene.imageProcessingConfiguration.onUpdateParameters.add((function(){a.bloom._downscale._exposure=a._scene.imageProcessingConfiguration.exposure,a.imageProcessingEnabled!==a._scene.imageProcessingConfiguration.isEnabled&&(a._imageProcessingEnabled=a._scene.imageProcessingConfiguration.isEnabled,c?rr.SetImmediate((function(){a._buildPipeline()})):a._buildPipeline())})),a._buildPipeline(),c=!1,a}return m(t,e),Object.defineProperty(t.prototype,"automaticBuild",{get:function(){return this._buildAllowed},set:function(e){this._buildAllowed=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scene",{get:function(){return this._scene},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"sharpenEnabled",{get:function(){return this._sharpenEnabled},set:function(e){this._sharpenEnabled!==e&&(this._sharpenEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"bloomKernel",{get:function(){return this._bloomKernel},set:function(e){this._bloomKernel=e,this.bloom.kernel=e/this._hardwareScaleLevel},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"bloomWeight",{get:function(){return this._bloomWeight},set:function(e){this._bloomWeight!==e&&(this.bloom.weight=e,this._bloomWeight=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"bloomThreshold",{get:function(){return this._bloomThreshold},set:function(e){this._bloomThreshold!==e&&(this.bloom.threshold=e,this._bloomThreshold=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"bloomScale",{get:function(){return this._bloomScale},set:function(e){this._bloomScale!==e&&(this._bloomScale=e,this._rebuildBloom(),this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"bloomEnabled",{get:function(){return this._bloomEnabled},set:function(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),t.prototype._rebuildBloom=function(){var e=this.bloom;this.bloom=new TC(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(var t=0;t<this._cameras.length;t++)e.disposeEffects(this._cameras[t])},Object.defineProperty(t.prototype,"depthOfFieldEnabled",{get:function(){return this._depthOfFieldEnabled},set:function(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"depthOfFieldBlurLevel",{get:function(){return this._depthOfFieldBlurLevel},set:function(e){if(this._depthOfFieldBlurLevel!==e){this._depthOfFieldBlurLevel=e;var t=this.depthOfField;this.depthOfField=new IC(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!1),this.depthOfField.focalLength=t.focalLength,this.depthOfField.focusDistance=t.focusDistance,this.depthOfField.fStop=t.fStop,this.depthOfField.lensSize=t.lensSize;for(var i=0;i<this._cameras.length;i++)t.disposeEffects(this._cameras[i]);this._buildPipeline()}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"fxaaEnabled",{get:function(){return this._fxaaEnabled},set:function(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"samples",{get:function(){return this._samples},set:function(e){this._samples!==e&&(this._samples=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"imageProcessingEnabled",{get:function(){return this._imageProcessingEnabled},set:function(e){this._imageProcessingEnabled!==e&&(this._scene.imageProcessingConfiguration.isEnabled=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"glowLayerEnabled",{get:function(){return null!=this._glowLayer},set:function(e){e&&!this._glowLayer?this._glowLayer=new nv("",this._scene):!e&&this._glowLayer&&(this._glowLayer.dispose(),this._glowLayer=null)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"glowLayer",{get:function(){return this._glowLayer},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"chromaticAberrationEnabled",{get:function(){return this._chromaticAberrationEnabled},set:function(e){this._chromaticAberrationEnabled!==e&&(this._chromaticAberrationEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"grainEnabled",{get:function(){return this._grainEnabled},set:function(e){this._grainEnabled!==e&&(this._grainEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"DefaultRenderingPipeline"},t.prototype.prepare=function(){var e=this._buildAllowed;this._buildAllowed=!0,this._buildPipeline(),this._buildAllowed=e},t.prototype._setAutoClearAndTextureSharing=function(e,t){void 0===t&&(t=!1),this._hasCleared?e.autoClear=!1:(e.autoClear=!0,this._scene.autoClear=!1,this._hasCleared=!0),t||(this._prevPrevPostProcess?e.shareOutputWith(this._prevPrevPostProcess):e.useOwnOutput(),this._prevPostProcess&&(this._prevPrevPostProcess=this._prevPostProcess),this._prevPostProcess=e)},t.prototype._buildPipeline=function(){var e=this;if(this._buildAllowed){this._scene.autoClear=!0;var t=this._scene.getEngine();if(this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._prevPostProcess=null,this._prevPrevPostProcess=null,this._hasCleared=!1,this.depthOfFieldEnabled){if(this._cameras.length>1){for(var i=0,r=this._cameras;i<r.length;i++){var n=r[i];(o=this._scene.enableDepthRenderer(n)).useOnlyInActiveCamera=!0}this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add((function(t){e._cameras.indexOf(t.activeCamera)>-1&&(e.depthOfField.depthTexture=t.enableDepthRenderer(t.activeCamera).getDepthMap())}))}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);var o=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=o.getDepthMap()}this.depthOfField._isReady()||this.depthOfField._updateEffects(),this.addEffect(this.depthOfField),this._setAutoClearAndTextureSharing(this.depthOfField._effects[0],!0)}else this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);this.bloomEnabled&&(this.bloom._isReady()||this.bloom._updateEffects(),this.addEffect(this.bloom),this._setAutoClearAndTextureSharing(this.bloom._effects[0],!0)),this._imageProcessingEnabled&&(this.imageProcessing=new LC("imageProcessing",1,null,Ja.BILINEAR_SAMPLINGMODE,t,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new vC(t,this.ImageProcessingPostProcessId,(function(){return e.imageProcessing}),!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._cameras&&0!==this._cameras.length||(this._scene.imageProcessingConfiguration.applyByPostProcess=!1),this.imageProcessing.getEffect()||this.imageProcessing._updateParameters()),this.sharpenEnabled&&(this.sharpen.isReady()||this.sharpen.updateEffect(),this.addEffect(this._sharpenEffect),this._setAutoClearAndTextureSharing(this.sharpen)),this.grainEnabled&&(this.grain.isReady()||this.grain.updateEffect(),this.addEffect(this._grainEffect),this._setAutoClearAndTextureSharing(this.grain)),this.chromaticAberrationEnabled&&(this.chromaticAberration.isReady()||this.chromaticAberration.updateEffect(),this.addEffect(this._chromaticAberrationEffect),this._setAutoClearAndTextureSharing(this.chromaticAberration)),this.fxaaEnabled&&(this.fxaa=new DC("fxaa",1,null,Ja.BILINEAR_SAMPLINGMODE,t,!1,this._defaultPipelineTextureType),this.addEffect(new vC(t,this.FxaaPostProcessId,(function(){return e.fxaa}),!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera))&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add((function(){e._scene.activeCamera&&-1===e._cameras.indexOf(e._scene.activeCamera)&&(e._scene.autoClear=!0)}))),this._activeCamerasChangedObserver||(this._activeCamerasChangedObserver=this._scene.onActiveCamerasChanged.add((function(){e._scene.activeCameras&&e._scene.activeCameras.length>1&&(e._scene.autoClear=!0)}))),this._adaptPostProcessesToViewPort(),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&ae.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}},t.prototype._disposePostProcesses=function(e){void 0===e&&(e=!1);for(var t=0;t<this._cameras.length;t++){var i=this._cameras[t];this.imageProcessing&&this.imageProcessing.dispose(i),this.fxaa&&this.fxaa.dispose(i),e&&(this.sharpen&&this.sharpen.dispose(i),this.depthOfField&&(this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver),this.depthOfField.disposeEffects(i)),this.bloom&&this.bloom.disposeEffects(i),this.chromaticAberration&&this.chromaticAberration.dispose(i),this.grain&&this.grain.dispose(i),this._glowLayer&&this._glowLayer.dispose())}this.imageProcessing=null,this.fxaa=null,e&&(this.sharpen=null,this._sharpenEffect=null,this.depthOfField=null,this.bloom=null,this.chromaticAberration=null,this._chromaticAberrationEffect=null,this.grain=null,this._grainEffect=null,this._glowLayer=null)},t.prototype.addCamera=function(e){this._camerasToBeAttached.push(e),this._buildPipeline()},t.prototype.removeCamera=function(e){var t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()},t.prototype.dispose=function(){this._buildAllowed=!1,this.onBuildObservable.clear(),this._disposePostProcesses(!0),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._scene._postProcessRenderPipelineManager.removePipeline(this.name),this._scene.autoClear=!0,this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this._scene.onActiveCameraChanged.remove(this._activeCameraChangedObserver),this._scene.onActiveCamerasChanged.remove(this._activeCamerasChangedObserver),this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver),e.prototype.dispose.call(this)},t.prototype.serialize=function(){var e=Ke.Serialize(this);return e.customType="DefaultRenderingPipeline",e},t.Parse=function(e,i,r){return Ke.Parse((function(){return new t(e._name,e._name._hdr,i)}),e,i,r)},v([Ie()],t.prototype,"sharpenEnabled",null),v([Ie()],t.prototype,"bloomKernel",null),v([Ie()],t.prototype,"_bloomWeight",void 0),v([Ie()],t.prototype,"_bloomThreshold",void 0),v([Ie()],t.prototype,"_hdr",void 0),v([Ie()],t.prototype,"bloomWeight",null),v([Ie()],t.prototype,"bloomThreshold",null),v([Ie()],t.prototype,"bloomScale",null),v([Ie()],t.prototype,"bloomEnabled",null),v([Ie()],t.prototype,"depthOfFieldEnabled",null),v([Ie()],t.prototype,"depthOfFieldBlurLevel",null),v([Ie()],t.prototype,"fxaaEnabled",null),v([Ie()],t.prototype,"samples",null),v([Ie()],t.prototype,"imageProcessingEnabled",null),v([Ie()],t.prototype,"glowLayerEnabled",null),v([Ie()],t.prototype,"chromaticAberrationEnabled",null),v([Ie()],t.prototype,"grainEnabled",null),t}(WC);a("BABYLON.DefaultRenderingPipeline",jC);li.ShadersStore.lensHighlightsPixelShader="uniform sampler2D textureSampler; \nuniform float gain;uniform float threshold;uniform float screen_width;uniform float screen_height;varying vec2 vUV;vec4 highlightColor(vec4 color) {vec4 highlight=color;float luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));float lum_threshold;if (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;}\nfloat w=2.0/screen_width;float h=2.0/screen_height;float weight=1.0;vec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;gl_FragColor=blurred;}";li.ShadersStore.depthOfFieldPixelShader="uniform sampler2D textureSampler;uniform sampler2D highlightsSampler;uniform sampler2D depthSampler;uniform sampler2D grainSampler;uniform float grain_amount;uniform bool blur_noise;uniform float screen_width;uniform float screen_height;uniform float distortion;uniform bool dof_enabled;uniform float screen_distance; \nuniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV;\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \nvec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co)\n{float noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));float noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));return clamp(vec2(noise1,noise2),0.0,1.0);}\nvec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);vec2 dist_coords=vec2(0.5,0.5);dist_coords.x=0.5+direction.x*radius2*1.0;dist_coords.y=0.5+direction.y*radius2*1.0;float dist_amount=clamp(distortion*0.23,0.0,1.0);dist_coords=mix(coords,dist_coords,dist_amount);return dist_coords;}\nfloat sampleScreen(inout vec4 color,in vec2 offset,in float weight) {vec2 coords=distorted_coords;float angle=rand(coords*100.0).x*TWOPI;coords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));color+=texture2D(textureSampler,coords)*weight;return weight;}\nfloat getBlurLevel(float size) {return min(3.0,ceil(size/1.0));}\nvec4 getBlurColor(float size) {vec4 col=texture2D(textureSampler,distorted_coords);float blur_level=getBlurLevel(size);float w=(size/screen_width);float h=(size/screen_height);float total_weight=1.0;vec2 sample_coords;total_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);total_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);total_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);total_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);total_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);total_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);total_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);total_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);total_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);total_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);if (blur_level>1.0) {total_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);total_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);total_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);total_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);total_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);total_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);total_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);total_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);total_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);total_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);}\nif (blur_level>2.0) {total_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);total_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);total_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);total_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);total_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);total_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);total_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);total_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);total_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);}\ncol/=total_weight; \nif (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);}\nreturn col;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);radius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;radius=sqrt(radius2);distorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; }\nfloat edge_blur_amount=0.0;if (edge_blur>0.0) {edge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;}\nfloat blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);}\nelse {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;}\nif (blur_noise) {vec2 noise=rand(distorted_coords)*0.01*blur_amount;vec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);gl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;}}\nif (grain_amount>0.0) {vec4 grain_color=texture2D(grainSampler,texels_coords*0.003);gl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;}}\n";var YC=function(e){function t(t,i,r,n,o){void 0===n&&(n=1);var a=e.call(this,r.getEngine(),t)||this;return a.LensChromaticAberrationEffect="LensChromaticAberrationEffect",a.HighlightsEnhancingEffect="HighlightsEnhancingEffect",a.LensDepthOfFieldEffect="LensDepthOfFieldEffect",a._pentagonBokehIsEnabled=!1,a._scene=r,a._depthTexture=r.enableDepthRenderer().getDepthMap(),i.grain_texture?a._grainTexture=i.grain_texture:a._createGrainTexture(),a._edgeBlur=i.edge_blur?i.edge_blur:0,a._grainAmount=i.grain_amount?i.grain_amount:0,a._chromaticAberration=i.chromatic_aberration?i.chromatic_aberration:0,a._distortion=i.distortion?i.distortion:0,a._highlightsGain=void 0!==i.dof_gain?i.dof_gain:-1,a._highlightsThreshold=i.dof_threshold?i.dof_threshold:1,a._dofDistance=void 0!==i.dof_focus_distance?i.dof_focus_distance:-1,a._dofAperture=i.dof_aperture?i.dof_aperture:1,a._dofDarken=i.dof_darken?i.dof_darken:0,a._dofPentagon=void 0===i.dof_pentagon||i.dof_pentagon,a._blurNoise=void 0===i.blur_noise||i.blur_noise,a._createChromaticAberrationPostProcess(n),a._createHighlightsPostProcess(n),a._createDepthOfFieldPostProcess(n/4),a.addEffect(new vC(r.getEngine(),a.LensChromaticAberrationEffect,(function(){return a._chromaticAberrationPostProcess}),!0)),a.addEffect(new vC(r.getEngine(),a.HighlightsEnhancingEffect,(function(){return a._highlightsPostProcess}),!0)),a.addEffect(new vC(r.getEngine(),a.LensDepthOfFieldEffect,(function(){return a._depthOfFieldPostProcess}),!0)),-1===a._highlightsGain&&a._disableEffect(a.HighlightsEnhancingEffect,null),r.postProcessRenderPipelineManager.addPipeline(a),o&&r.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(t,o),a}return m(t,e),t.prototype.getClassName=function(){return"LensRenderingPipeline"},Object.defineProperty(t.prototype,"scene",{get:function(){return this._scene},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"edgeBlur",{get:function(){return this._edgeBlur},set:function(e){this.setEdgeBlur(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"grainAmount",{get:function(){return this._grainAmount},set:function(e){this.setGrainAmount(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"chromaticAberration",{get:function(){return this._chromaticAberration},set:function(e){this.setChromaticAberration(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dofAperture",{get:function(){return this._dofAperture},set:function(e){this.setAperture(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"edgeDistortion",{get:function(){return this._distortion},set:function(e){this.setEdgeDistortion(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dofDistortion",{get:function(){return this._dofDistance},set:function(e){this.setFocusDistance(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"darkenOutOfFocus",{get:function(){return this._dofDarken},set:function(e){this.setDarkenOutOfFocus(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"blurNoise",{get:function(){return this._blurNoise},set:function(e){this._blurNoise=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"pentagonBokeh",{get:function(){return this._pentagonBokehIsEnabled},set:function(e){e?this.enablePentagonBokeh():this.disablePentagonBokeh()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"highlightsGain",{get:function(){return this._highlightsGain},set:function(e){this.setHighlightsGain(e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"highlightsThreshold",{get:function(){return this._highlightsThreshold},set:function(e){this.setHighlightsThreshold(e)},enumerable:!1,configurable:!0}),t.prototype.setEdgeBlur=function(e){this._edgeBlur=e},t.prototype.disableEdgeBlur=function(){this._edgeBlur=0},t.prototype.setGrainAmount=function(e){this._grainAmount=e},t.prototype.disableGrain=function(){this._grainAmount=0},t.prototype.setChromaticAberration=function(e){this._chromaticAberration=e},t.prototype.disableChromaticAberration=function(){this._chromaticAberration=0},t.prototype.setEdgeDistortion=function(e){this._distortion=e},t.prototype.disableEdgeDistortion=function(){this._distortion=0},t.prototype.setFocusDistance=function(e){this._dofDistance=e},t.prototype.disableDepthOfField=function(){this._dofDistance=-1},t.prototype.setAperture=function(e){this._dofAperture=e},t.prototype.setDarkenOutOfFocus=function(e){this._dofDarken=e},t.prototype.enablePentagonBokeh=function(){this._highlightsPostProcess.updateEffect("#define PENTAGON\n"),this._pentagonBokehIsEnabled=!0},t.prototype.disablePentagonBokeh=function(){this._pentagonBokehIsEnabled=!1,this._highlightsPostProcess.updateEffect()},t.prototype.enableNoiseBlur=function(){this._blurNoise=!0},t.prototype.disableNoiseBlur=function(){this._blurNoise=!1},t.prototype.setHighlightsGain=function(e){this._highlightsGain=e},t.prototype.setHighlightsThreshold=function(e){-1===this._highlightsGain&&(this._highlightsGain=1),this._highlightsThreshold=e},t.prototype.disableHighlights=function(){this._highlightsGain=-1},t.prototype.dispose=function(e){void 0===e&&(e=!1),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),this._chromaticAberrationPostProcess=null,this._highlightsPostProcess=null,this._depthOfFieldPostProcess=null,this._grainTexture.dispose(),e&&this._scene.disableDepthRenderer()},t.prototype._createChromaticAberrationPostProcess=function(e){var t=this;this._chromaticAberrationPostProcess=new hl("LensChromaticAberration","chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],e,null,Ja.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._chromaticAberrationPostProcess.onApply=function(e){e.setFloat("chromatic_aberration",t._chromaticAberration),e.setFloat("screen_width",t._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",t._scene.getEngine().getRenderHeight()),e.setFloat("radialIntensity",1),e.setFloat2("direction",17,17),e.setFloat2("centerPosition",.5,.5)}},t.prototype._createHighlightsPostProcess=function(e){var t=this;this._highlightsPostProcess=new hl("LensHighlights","lensHighlights",["gain","threshold","screen_width","screen_height"],[],e,null,Ja.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,this._dofPentagon?"#define PENTAGON\n":""),this._highlightsPostProcess.externalTextureSamplerBinding=!0,this._highlightsPostProcess.onApply=function(e){e.setFloat("gain",t._highlightsGain),e.setFloat("threshold",t._highlightsThreshold),e.setTextureFromPostProcess("textureSampler",t._chromaticAberrationPostProcess),e.setFloat("screen_width",t._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",t._scene.getEngine().getRenderHeight())}},t.prototype._createDepthOfFieldPostProcess=function(e){var t=this;this._depthOfFieldPostProcess=new hl("LensDepthOfField","depthOfField",["grain_amount","blur_noise","screen_width","screen_height","distortion","dof_enabled","screen_distance","aperture","darken","edge_blur","highlights","near","far"],["depthSampler","grainSampler","highlightsSampler"],e,null,Ja.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._depthOfFieldPostProcess.externalTextureSamplerBinding=!0,this._depthOfFieldPostProcess.onApply=function(e){e.setTexture("depthSampler",t._depthTexture),e.setTexture("grainSampler",t._grainTexture),e.setTextureFromPostProcess("textureSampler",t._highlightsPostProcess),e.setTextureFromPostProcess("highlightsSampler",t._depthOfFieldPostProcess),e.setFloat("grain_amount",t._grainAmount),e.setBool("blur_noise",t._blurNoise),e.setFloat("screen_width",t._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",t._scene.getEngine().getRenderHeight()),e.setFloat("distortion",t._distortion),e.setBool("dof_enabled",-1!==t._dofDistance),e.setFloat("screen_distance",1/(.1-1/t._dofDistance)),e.setFloat("aperture",t._dofAperture),e.setFloat("darken",t._dofDarken),e.setFloat("edge_blur",t._edgeBlur),e.setBool("highlights",-1!==t._highlightsGain),t._scene.activeCamera&&(e.setFloat("near",t._scene.activeCamera.minZ),e.setFloat("far",t._scene.activeCamera.maxZ))}},t.prototype._createGrainTexture=function(){for(var e=new Uint8Array(1048576),t=0;t<e.length;){var i=Math.floor(255*j.RandomRange(.42,.58));e[t++]=i,e[t++]=i,e[t++]=i,e[t++]=255}var r=is.CreateRGBATexture(e,512,512,this._scene,!1,!1,u.TEXTURE_BILINEAR_SAMPLINGMODE);r.name="LensNoiseTexture",r.wrapU=Ja.WRAP_ADDRESSMODE,r.wrapV=Ja.WRAP_ADDRESSMODE,this._grainTexture=r},t}(WC),KC=function(){this.enabled=!1,this.name="ssao2",this.texturesRequired=[u.PREPASS_NORMAL_TEXTURE_TYPE,u.PREPASS_DEPTH_TEXTURE_TYPE]};li.ShadersStore.ssao2PixelShader="precision highp float;uniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSAO\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);uniform float near;uniform float radius;uniform sampler2D depthSampler;uniform sampler2D randomSampler;uniform sampler2D normalSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float base;uniform float xViewport;uniform float yViewport;uniform mat3 depthProjection;uniform float maxZ;uniform float minZAspect;uniform vec2 texelSize;uniform mat4 projection;void main()\n{vec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;float depth=textureLod(depthSampler,vUV,0.0).r;float depthSign=sign(depth);depth=depth*depthSign;vec3 normal=textureLod(normalSampler,vUV,0.0).rgb;float occlusion=0.0;float correctedRadius=min(radius,minZAspect*depth/near);vec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);vec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);vec3 origin=vViewRay*vDepthFactor;vec3 rvec=random*2.0-1.0;rvec.z=0.0;float dotProduct=dot(rvec,normal);rvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i<SAMPLES; ++i) {vec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];samplePosition=samplePosition*correctedRadius+origin;vec4 offset=vec4(samplePosition,1.0);offset=projection*offset;offset.xyz/=offset.w;offset.xy=offset.xy*0.5+0.5;if (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {continue;}\nfloat sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor=vec4(vec3(result),1.0);}\n#endif\n#ifdef BLUR\nuniform float outSize;uniform float soften;uniform float tolerance;uniform int samples;\n#ifndef BLUR_BYPASS\nuniform sampler2D depthSampler;\n#ifdef BLUR_LEGACY\n#define inline\nfloat blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {float result=0.0;vec2 off1=vec2(1.411764705882353)*step;vec2 off2=vec2(3.2941176470588234)*step;vec2 off3=vec2(5.176470588235294)*step;float compareDepth=abs(textureLod(depthSampler,uv,0.0).r);float sampleDepth;float weight;float weightSum=30.0;result+=textureLod(image,uv,0.0).r*30.0;sampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv+off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv-off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off3,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off3,0.0).r*weight;return result/weightSum;}\n#endif\n#endif\nvoid main()\n{float result=0.0;\n#ifdef BLUR_BYPASS\nresult=textureLod(textureSampler,vUV,0.0).r;\n#else\n#ifdef BLUR_H\nvec2 step=vec2(1.0/outSize,0.0);\n#else\nvec2 step=vec2(0.0,1.0/outSize);\n#endif\n#ifdef BLUR_LEGACY\nresult=blur13Bilateral(textureSampler,vUV,step);\n#else\nfloat compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; i<samples; i+=2)\n{vec2 samplePos=vUV+step*(float(i)+0.5);float sampleDepth=abs(textureLod(depthSampler,samplePos,0.0).r);float falloff=smoothstep(0.0,\nfloat(samples),\nfloat(samples)-abs(float(i))*soften);float minDivider=tolerance*0.5+0.003;float weight=falloff/( minDivider+abs(compareDepth-sampleDepth));result+=textureLod(textureSampler,samplePos,0.0).r*weight;weightSum+=weight;}\nresult/=weightSum;\n#endif\n#endif\ngl_FragColor.rgb=vec3(result);gl_FragColor.a=1.0;}\n#endif\n";li.ShadersStore.ssaoCombinePixelShader="uniform sampler2D textureSampler;uniform sampler2D originalColor;uniform vec4 viewport;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);vec4 sceneColor=texture2D(originalColor,vUV);gl_FragColor=sceneColor*ssaoColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";var QC=function(e){function t(t,i,r,n,o,a){void 0===o&&(o=!1),void 0===a&&(a=u.TEXTURETYPE_UNSIGNED_INT);var s,l,c=this;if((c=e.call(this,i.getEngine(),t)||this).SSAOOriginalSceneColorEffect="SSAOOriginalSceneColorEffect",c.SSAORenderEffect="SSAORenderEffect",c.SSAOBlurHRenderEffect="SSAOBlurHRenderEffect",c.SSAOBlurVRenderEffect="SSAOBlurVRenderEffect",c.SSAOCombineRenderEffect="SSAOCombineRenderEffect",c.totalStrength=1,c.maxZ=100,c.minZAspect=.2,c._epsilon=.02,c._samples=8,c._textureSamples=1,c._forceGeometryBuffer=!1,c.radius=2,c.base=0,c._bypassBlur=!1,c._expensiveBlur=!0,c.bilateralSamples=16,c.bilateralSoften=0,c.bilateralTolerance=0,c._bits=new Uint32Array(1),c._scene=i,c._ratio=r,c._textureType=a,c._forceGeometryBuffer=o,!c.isSupported)return ae.Error("The current engine does not support SSAO 2."),c;var h=c._ratio.ssaoRatio||r,d=c._ratio.blurRatio||r;return c._forceGeometryBuffer?(i.enableGeometryBufferRenderer(),(null===(s=i.geometryBufferRenderer)||void 0===s?void 0:s.generateNormalsInWorldSpace)&&ae.Error("SSAO2RenderingPipeline does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!")):(i.enablePrePassRenderer(),(null===(l=i.prePassRenderer)||void 0===l?void 0:l.generateNormalsInWorldSpace)&&ae.Error("SSAO2RenderingPipeline does not support generateNormalsInWorldSpace=true for the prepass renderer!")),c._createRandomTexture(),c._originalColorPostProcess=new qc("SSAOOriginalSceneColor",1,null,Ja.BILINEAR_SAMPLINGMODE,i.getEngine(),void 0,c._textureType),c._originalColorPostProcess.samples=c.textureSamples,c._createSSAOPostProcess(1,a),c._createBlurPostProcess(h,d,c._textureType),c._createSSAOCombinePostProcess(d,c._textureType),c.addEffect(new vC(i.getEngine(),c.SSAOOriginalSceneColorEffect,(function(){return c._originalColorPostProcess}),!0)),c.addEffect(new vC(i.getEngine(),c.SSAORenderEffect,(function(){return c._ssaoPostProcess}),!0)),c.addEffect(new vC(i.getEngine(),c.SSAOBlurHRenderEffect,(function(){return c._blurHPostProcess}),!0)),c.addEffect(new vC(i.getEngine(),c.SSAOBlurVRenderEffect,(function(){return c._blurVPostProcess}),!0)),c.addEffect(new vC(i.getEngine(),c.SSAOCombineRenderEffect,(function(){return c._ssaoCombinePostProcess}),!0)),i.postProcessRenderPipelineManager.addPipeline(c),n&&i.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(t,n),c}return m(t,e),Object.defineProperty(t.prototype,"epsilon",{get:function(){return this._epsilon},set:function(e){this._epsilon=e,this._ssaoPostProcess.updateEffect(this._getDefinesForSSAO())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"samples",{get:function(){return this._samples},set:function(e){this._samples=e,this._ssaoPostProcess.updateEffect(this._getDefinesForSSAO()),this._sampleSphere=this._generateHemisphere()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"textureSamples",{get:function(){return this._textureSamples},set:function(e){this._textureSamples=e,this._prePassRenderer?this._prePassRenderer.samples=e:this._originalColorPostProcess.samples=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_geometryBufferRenderer",{get:function(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_prePassRenderer",{get:function(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"bypassBlur",{get:function(){return this._bypassBlur},set:function(e){var t=this._getDefinesForBlur(this.expensiveBlur,e),i=this._getSamplersForBlur(e);this._blurHPostProcess.updateEffect(t.h,null,i),this._blurVPostProcess.updateEffect(t.v,null,i),this._bypassBlur=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"expensiveBlur",{get:function(){return this._expensiveBlur},set:function(e){var t=this._getDefinesForBlur(e,this._bypassBlur);this._blurHPostProcess.updateEffect(t.h),this._blurVPostProcess.updateEffect(t.v),this._expensiveBlur=e},enumerable:!1,configurable:!0}),Object.defineProperty(t,"IsSupported",{get:function(){var e=M.LastCreatedEngine;return!!e&&e._features.supportSSAO2},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scene",{get:function(){return this._scene},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"SSAO2RenderingPipeline"},t.prototype.dispose=function(t){void 0===t&&(t=!1);for(var i=0;i<this._scene.cameras.length;i++){var r=this._scene.cameras[i];this._originalColorPostProcess.dispose(r),this._ssaoPostProcess.dispose(r),this._blurHPostProcess.dispose(r),this._blurVPostProcess.dispose(r),this._ssaoCombinePostProcess.dispose(r)}this._randomTexture.dispose(),t&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),e.prototype.dispose.call(this)},t.prototype._rebuild=function(){e.prototype._rebuild.call(this)},t.prototype._getSamplersForBlur=function(e){return e?["textureSampler"]:["textureSampler","depthSampler"]},t.prototype._getDefinesForBlur=function(e,t){var i="#define BLUR\n";return t&&(i+="#define BLUR_BYPASS\n"),e||(i+="#define BLUR_LEGACY\n"),{h:i+"#define BLUR_H\n",v:i}},t.prototype._createBlurPostProcess=function(e,t,i){var r=this._getDefinesForBlur(this.expensiveBlur,this.bypassBlur),n=this._getSamplersForBlur(this.bypassBlur);this._blurHPostProcess=this._createBlurFilter("BlurH",n,e,r.h,i,!0),this._blurVPostProcess=this._createBlurFilter("BlurV",n,t,r.v,i,!1)},t.prototype._createBlurFilter=function(e,t,i,r,n,o){var a=this,s=new hl(e,"ssao2",["outSize","samples","soften","tolerance"],t,i,null,Ja.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,r,n);return s.onApply=function(e){if(a._scene.activeCamera){var t=o?a._ssaoCombinePostProcess.width:a._ssaoCombinePostProcess.height,i=o?a._originalColorPostProcess.width:a._originalColorPostProcess.height;e.setFloat("outSize",t>0?t:i),e.setInt("samples",a.bilateralSamples),e.setFloat("soften",a.bilateralSoften),e.setFloat("tolerance",a.bilateralTolerance),a._geometryBufferRenderer?e.setTexture("depthSampler",a._geometryBufferRenderer.getGBuffer().textures[0]):a._prePassRenderer&&e.setTexture("depthSampler",a._prePassRenderer.getRenderTarget().textures[a._prePassRenderer.getIndex(u.PREPASS_DEPTH_TEXTURE_TYPE)])}},s.samples=this.textureSamples,s.autoClear=!1,s},t.prototype._radicalInverse_VdC=function(e){return this._bits[0]=e,this._bits[0]=(this._bits[0]<<16|this._bits[0]>>16)>>>0,this._bits[0]=(1431655765&this._bits[0])<<1|(2863311530&this._bits[0])>>>1>>>0,this._bits[0]=(858993459&this._bits[0])<<2|(3435973836&this._bits[0])>>>2>>>0,this._bits[0]=(252645135&this._bits[0])<<4|(4042322160&this._bits[0])>>>4>>>0,this._bits[0]=(16711935&this._bits[0])<<8|(4278255360&this._bits[0])>>>8>>>0,2.3283064365386963e-10*this._bits[0]},t.prototype._hammersley=function(e,t){return[e/t,this._radicalInverse_VdC(e)]},t.prototype._hemisphereSample_uniform=function(e,t){var i=2*t*Math.PI,r=1-.85*e,n=Math.sqrt(1-r*r);return new V(Math.cos(i)*n,Math.sin(i)*n,r)},t.prototype._generateHemisphere=function(){for(var e,t=this.samples,i=[],r=0;r<t;){if(t<16)e=this._hemisphereSample_uniform(Math.random(),Math.random());else{var n=this._hammersley(r,t);e=this._hemisphereSample_uniform(n[0],n[1])}i.push(e.x,e.y,e.z),r++}return i},t.prototype._getDefinesForSSAO=function(){return"#define SSAO\n#define SAMPLES ".concat(this.samples,"\n#define EPSILON ").concat(this.epsilon.toFixed(4))},t.prototype._createSSAOPostProcess=function(e,i){var r=this;this._sampleSphere=this._generateHemisphere();var n=this._getDefinesForSSAO();this._ssaoPostProcess=new hl("ssao2","ssao2",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","base","range","projection","near","texelSize","xViewport","yViewport","maxZ","minZAspect","depthProjection"],["randomSampler","depthSampler","normalSampler"],e,null,Ja.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,n,i),this._ssaoPostProcess.autoClear=!1,this._ssaoPostProcess.onApply=function(e){var i,n,o,a;if(r._scene.activeCamera){if(e.setArray3("sampleSphere",r._sampleSphere),e.setFloat("randTextureTiles",32),e.setFloat("samplesFactor",1/r.samples),e.setFloat("totalStrength",r.totalStrength),e.setFloat2("texelSize",1/r._ssaoPostProcess.width,1/r._ssaoPostProcess.height),e.setFloat("radius",r.radius),e.setFloat("maxZ",r.maxZ),e.setFloat("minZAspect",r.minZAspect),e.setFloat("base",r.base),e.setFloat("near",r._scene.activeCamera.minZ),r._scene.activeCamera.mode===$n.PERSPECTIVE_CAMERA)e.setMatrix3x3("depthProjection",t.PERSPECTIVE_DEPTH_PROJECTION),e.setFloat("xViewport",Math.tan(r._scene.activeCamera.fov/2)*r._scene.getEngine().getAspectRatio(r._scene.activeCamera,!0)),e.setFloat("yViewport",Math.tan(r._scene.activeCamera.fov/2));else{var s=r._scene.getEngine().getRenderWidth()/2,l=r._scene.getEngine().getRenderHeight()/2,c=null!==(i=r._scene.activeCamera.orthoLeft)&&void 0!==i?i:-s,h=null!==(n=r._scene.activeCamera.orthoRight)&&void 0!==n?n:s,d=null!==(o=r._scene.activeCamera.orthoBottom)&&void 0!==o?o:-l,p=null!==(a=r._scene.activeCamera.orthoTop)&&void 0!==a?a:l;e.setMatrix3x3("depthProjection",t.ORTHO_DEPTH_PROJECTION),e.setFloat("xViewport",.5*(h-c)),e.setFloat("yViewport",.5*(p-d))}e.setMatrix("projection",r._scene.getProjectionMatrix()),r._geometryBufferRenderer?(e.setTexture("depthSampler",r._geometryBufferRenderer.getGBuffer().textures[0]),e.setTexture("normalSampler",r._geometryBufferRenderer.getGBuffer().textures[1])):r._prePassRenderer&&(e.setTexture("depthSampler",r._prePassRenderer.getRenderTarget().textures[r._prePassRenderer.getIndex(u.PREPASS_DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",r._prePassRenderer.getRenderTarget().textures[r._prePassRenderer.getIndex(u.PREPASS_NORMAL_TEXTURE_TYPE)])),e.setTexture("randomSampler",r._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new KC)},t.prototype._createSSAOCombinePostProcess=function(e,t){var i=this;this._ssaoCombinePostProcess=new hl("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Ja.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=function(e){var t=i._scene.activeCamera.viewport;e.setVector4("viewport",H.Vector4[0].copyFromFloats(t.x,t.y,t.width,t.height)),e.setTextureFromPostProcessOutput("originalColor",i._originalColorPostProcess)},this._ssaoCombinePostProcess.autoClear=!1,this._ssaoCombinePostProcess.samples=this.textureSamples},t.prototype._createRandomTexture=function(){for(var e=new Uint8Array(65536),t=U.Zero(),i=0;i<e.length;)t.set(j.RandomRange(0,1),j.RandomRange(0,1)).normalize().scaleInPlace(255),e[i++]=Math.floor(t.x),e[i++]=Math.floor(t.y),e[i++]=0,e[i++]=255;var r=is.CreateRGBATexture(e,128,128,this._scene,!1,!1,u.TEXTURE_BILINEAR_SAMPLINGMODE);r.name="SSAORandomTexture",r.wrapU=Ja.WRAP_ADDRESSMODE,r.wrapV=Ja.WRAP_ADDRESSMODE,this._randomTexture=r},t.prototype.serialize=function(){var e=Ke.Serialize(this);return e.customType="SSAO2RenderingPipeline",e},t.Parse=function(e,i,r){return Ke.Parse((function(){return new t(e._name,i,e._ratio,void 0,e._forceGeometryBuffer,e._textureType)}),e,i,r)},t.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1],t.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1],v([Ie()],t.prototype,"totalStrength",void 0),v([Ie()],t.prototype,"maxZ",void 0),v([Ie()],t.prototype,"minZAspect",void 0),v([Ie("epsilon")],t.prototype,"_epsilon",void 0),v([Ie("samples")],t.prototype,"_samples",void 0),v([Ie("textureSamples")],t.prototype,"_textureSamples",void 0),v([Ie()],t.prototype,"_forceGeometryBuffer",void 0),v([Ie()],t.prototype,"_ratio",void 0),v([Ie()],t.prototype,"_textureType",void 0),v([Ie()],t.prototype,"radius",void 0),v([Ie()],t.prototype,"base",void 0),v([Ie("bypassBlur")],t.prototype,"_bypassBlur",void 0),v([Ie("expensiveBlur")],t.prototype,"_expensiveBlur",void 0),v([Ie()],t.prototype,"bilateralSamples",void 0),v([Ie()],t.prototype,"bilateralSoften",void 0),v([Ie()],t.prototype,"bilateralTolerance",void 0),t}(WC);a("BABYLON.SSAO2RenderingPipeline",QC);li.ShadersStore.ssaoPixelShader="uniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float radius;uniform float area;uniform float fallOff;uniform float base;vec3 normalFromDepth(float depth,vec2 coords)\n{vec2 offset1=vec2(0.0,radius);vec2 offset2=vec2(radius,0.0);float depth1=texture2D(textureSampler,coords+offset1).r;float depth2=texture2D(textureSampler,coords+offset2).r;vec3 p1=vec3(offset1,depth1-depth);vec3 p2=vec3(offset2,depth2-depth);vec3 normal=cross(p1,p2);normal.z=-normal.z;return normalize(normal);}\nvoid main()\n{vec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);float depth=texture2D(textureSampler,vUV).r;vec3 position=vec3(vUV,depth);vec3 normal=normalFromDepth(depth,vUV);float radiusDepth=radius/depth;float occlusion=0.0;vec3 ray;vec3 hemiRay;float occlusionDepth;float difference;for (int i=0; i<SAMPLES; i++)\n{ray=radiusDepth*reflect(sampleSphere[i],random);hemiRay=position+sign(dot(ray,normal))*ray;occlusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;difference=depth-occlusionDepth;occlusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor.r=result;gl_FragColor.g=result;gl_FragColor.b=result;gl_FragColor.a=1.0;}\n#endif\n";var qC=function(e){function t(t,i,r,n){var o=e.call(this,i.getEngine(),t)||this;o.SSAOOriginalSceneColorEffect="SSAOOriginalSceneColorEffect",o.SSAORenderEffect="SSAORenderEffect",o.SSAOBlurHRenderEffect="SSAOBlurHRenderEffect",o.SSAOBlurVRenderEffect="SSAOBlurVRenderEffect",o.SSAOCombineRenderEffect="SSAOCombineRenderEffect",o.totalStrength=1,o.radius=1e-4,o.area=.0075,o.fallOff=1e-6,o.base=.5,o._firstUpdate=!0,o._scene=i,o._createRandomTexture();var a=r.ssaoRatio||r,s=r.combineRatio||r;return o._originalColorPostProcess=new qc("SSAOOriginalSceneColor",s,null,Ja.BILINEAR_SAMPLINGMODE,i.getEngine(),!1),o._createSSAOPostProcess(a),o._createBlurPostProcess(a),o._createSSAOCombinePostProcess(s),o.addEffect(new vC(i.getEngine(),o.SSAOOriginalSceneColorEffect,(function(){return o._originalColorPostProcess}),!0)),o.addEffect(new vC(i.getEngine(),o.SSAORenderEffect,(function(){return o._ssaoPostProcess}),!0)),o.addEffect(new vC(i.getEngine(),o.SSAOBlurHRenderEffect,(function(){return o._blurHPostProcess}),!0)),o.addEffect(new vC(i.getEngine(),o.SSAOBlurVRenderEffect,(function(){return o._blurVPostProcess}),!0)),o.addEffect(new vC(i.getEngine(),o.SSAOCombineRenderEffect,(function(){return o._ssaoCombinePostProcess}),!0)),i.postProcessRenderPipelineManager.addPipeline(o),n&&i.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(t,n),o}return m(t,e),Object.defineProperty(t.prototype,"scene",{get:function(){return this._scene},enumerable:!1,configurable:!0}),t.prototype._attachCameras=function(t,i){e.prototype._attachCameras.call(this,t,i);for(var r=0,n=this._cameras;r<n.length;r++){var o=n[r];this._scene.enableDepthRenderer(o).getDepthMap()}},t.prototype.getClassName=function(){return"SSAORenderingPipeline"},t.prototype.dispose=function(t){void 0===t&&(t=!1);for(var i=0;i<this._scene.cameras.length;i++){var r=this._scene.cameras[i];this._originalColorPostProcess.dispose(r),this._ssaoPostProcess.dispose(r),this._blurHPostProcess.dispose(r),this._blurVPostProcess.dispose(r),this._ssaoCombinePostProcess.dispose(r)}this._randomTexture.dispose(),t&&this._scene.disableDepthRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),e.prototype.dispose.call(this)},t.prototype._createBlurPostProcess=function(e){var t=this;this._blurHPostProcess=new Om("BlurH",new U(1,0),16,e,null,Ja.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,u.TEXTURETYPE_UNSIGNED_INT),this._blurVPostProcess=new Om("BlurV",new U(0,1),16,e,null,Ja.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,u.TEXTURETYPE_UNSIGNED_INT),this._blurHPostProcess.onActivateObservable.add((function(){var e=t._blurHPostProcess.width/t._scene.getEngine().getRenderWidth();t._blurHPostProcess.kernel=16*e})),this._blurVPostProcess.onActivateObservable.add((function(){var e=t._blurVPostProcess.height/t._scene.getEngine().getRenderHeight();t._blurVPostProcess.kernel=16*e}))},t.prototype._rebuild=function(){this._firstUpdate=!0,e.prototype._rebuild.call(this)},t.prototype._createSSAOPostProcess=function(e){var t=this,i=[.5381,.1856,-.4319,.1379,.2486,.443,.3371,.5679,-.0057,-.6999,-.0451,-.0019,.0689,-.1598,-.8547,.056,.0069,-.1843,-.0146,.1402,.0762,.01,-.1924,-.0344,-.3577,-.5301,-.4358,-.3169,.1063,.0158,.0103,-.5869,.0046,-.0897,-.494,.3287,.7119,-.0154,-.0918,-.0533,.0596,-.5411,.0352,-.0631,.546,-.4776,.2847,-.0271];this._ssaoPostProcess=new hl("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,Ja.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define SAMPLES 16\n#define SSAO"),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=function(e){t._firstUpdate&&(e.setArray3("sampleSphere",i),e.setFloat("samplesFactor",.0625),e.setFloat("randTextureTiles",4)),e.setFloat("totalStrength",t.totalStrength),e.setFloat("radius",t.radius),e.setFloat("area",t.area),e.setFloat("fallOff",t.fallOff),e.setFloat("base",t.base),e.setTexture("textureSampler",t._scene.enableDepthRenderer(t._scene.activeCamera).getDepthMap()),e.setTexture("randomSampler",t._randomTexture)}},t.prototype._createSSAOCombinePostProcess=function(e){var t=this;this._ssaoCombinePostProcess=new hl("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Ja.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=function(e){e.setVector4("viewport",H.Vector4[0].copyFromFloats(0,0,1,1)),e.setTextureFromPostProcess("originalColor",t._originalColorPostProcess)}},t.prototype._createRandomTexture=function(){for(var e=new Uint8Array(1048576),t=0;t<e.length;)e[t++]=Math.floor(255*Math.max(0,j.RandomRange(-1,1))),e[t++]=Math.floor(255*Math.max(0,j.RandomRange(-1,1))),e[t++]=Math.floor(255*Math.max(0,j.RandomRange(-1,1))),e[t++]=255;var i=is.CreateRGBATexture(e,512,512,this._scene,!1,!1,u.TEXTURE_BILINEAR_SAMPLINGMODE);i.name="SSAORandomTexture",i.wrapU=Ja.WRAP_ADDRESSMODE,i.wrapV=Ja.WRAP_ADDRESSMODE,this._randomTexture=i},v([Ie()],t.prototype,"totalStrength",void 0),v([Ie()],t.prototype,"radius",void 0),v([Ie()],t.prototype,"area",void 0),v([Ie()],t.prototype,"fallOff",void 0),v([Ie()],t.prototype,"base",void 0),t}(WC),ZC=function(){this.enabled=!1,this.name="screenSpaceReflections",this.texturesRequired=[u.PREPASS_NORMAL_TEXTURE_TYPE,u.PREPASS_REFLECTIVITY_TEXTURE_TYPE,u.PREPASS_POSITION_TEXTURE_TYPE]};li.ShadersStore.screenSpaceReflectionPixelShader="uniform sampler2D textureSampler;\n#ifdef SSR_SUPPORTED\nuniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D positionSampler;\n#endif\nuniform mat4 view;uniform mat4 projection;uniform float stepSize;uniform float strength;uniform float threshold;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;varying vec2 vUV;\n#ifdef SSR_SUPPORTED\nstruct ReflectionInfo {vec3 color;vec4 coords;};/**\n* According to specular,see https:\n*/\nvec3 fresnelSchlick(float cosTheta,vec3 F0)\n{return F0+(1.0-F0)*pow(1.0-cosTheta,5.0);}\n/**\n* Once the pixel's coordinates has been found,let's adjust (smooth) a little bit\n* by sampling multiple reflection pixels.\n*/\nReflectionInfo smoothReflectionInfo(vec3 dir,vec3 hitCoord)\n{ReflectionInfo info;info.color=vec3(0.0);vec4 projectedCoord;float sampledDepth;for(int i=0; i<SMOOTH_STEPS; i++)\n{projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);sampledDepth=(view*texture2D(positionSampler,projectedCoord.xy)).z;float depth=sampledDepth-hitCoord.z;dir*=0.5;if(depth>0.0)\nhitCoord-=dir;else\nhitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;}\nprojectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);info.coords=vec4(projectedCoord.xy,sampledDepth,1.0);info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;info.color/=float(SMOOTH_STEPS+1);return info;}\n/**\n* Tests the given world position (hitCoord) according to the given reflection vector (dir)\n* until it finds a collision (means that depth is enough close to say \"it's the pixel to sample!\").\n*/\nReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord)\n{ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i<REFLECTION_SAMPLES; i++)\n{hitCoord+=dir;projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);sampledDepth=(view*texture2D(positionSampler,projectedCoord.xy)).z;float depth=sampledDepth-hitCoord.z;\n#ifdef RIGHT_HANDED_SCENE\ndepth*=-1.0;\n#endif\nif(((depth-dir.z)<threshold) && depth<=0.0)\n{\n#ifdef ENABLE_SMOOTH_REFLECTIONS\nreturn smoothReflectionInfo(dir,hitCoord);\n#else\ninfo.color=texture2D(textureSampler,projectedCoord.xy).rgb;info.coords=vec4(projectedCoord.xy,sampledDepth,0.0);return info;\n#endif\n}}\ninfo.color=texture2D(textureSampler,projectedCoord.xy).rgb;info.coords=vec4(projectedCoord.xy,sampledDepth,0.0);return info;}\nvec3 hash(vec3 a)\n{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);}\n#endif\nvoid main()\n{\n#ifdef SSR_SUPPORTED\nvec4 albedoFull=texture2D(textureSampler,vUV);vec3 albedo=albedoFull.rgb;float spec=texture2D(reflectivitySampler,vUV).r;if (spec==0.0) {gl_FragColor=albedoFull;return;}\nvec3 normal=(texture2D(normalSampler,vUV)).xyz;vec3 position=(view*texture2D(positionSampler,vUV)).xyz;vec3 reflected=normalize(reflect(normalize(position),normalize(normal)));float roughness=1.0-texture2D(reflectivitySampler,vUV).a;vec3 jitt=mix(vec3(0.0),hash(position),roughness)*roughnessFactor;ReflectionInfo info=getReflectionInfo(jitt+reflected,position);vec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-info.coords.xy));float screenEdgefactor=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);vec3 F0=vec3(0.04);F0 =mix(F0,albedo,spec);vec3 fresnel=fresnelSchlick(max(dot(normalize(normal),normalize(position)),0.0),F0);\n#ifdef RIGHT_HANDED_SCENE\nreflected.z*=-1.0;\n#endif\nfloat reflectionMultiplier=clamp(pow(spec*strength,reflectionSpecularFalloffExponent)*screenEdgefactor*reflected.z,0.0,0.9);float albedoMultiplier=1.0-reflectionMultiplier;vec3 SSR=info.color*fresnel;gl_FragColor=vec4((albedo*albedoMultiplier)+(SSR*reflectionMultiplier),albedoFull.a);\n#else\ngl_FragColor=texture2D(textureSampler,vUV);\n#endif\n}\n";var JC=function(e){function t(t,i,r,n,o,a,s,l,c,h){void 0===l&&(l=u.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=!1),void 0===h&&(h=!1);var d=e.call(this,t,"screenSpaceReflection",["projection","view","threshold","reflectionSpecularFalloffExponent","strength","stepSize","roughnessFactor"],["textureSampler","normalSampler","positionSampler","reflectivitySampler"],r,n,o,a,s,"#define SSR_SUPPORTED\n#define REFLECTION_SAMPLES 64\n#define SMOOTH_STEPS 5\n",l,void 0,null,c)||this;if(d.threshold=1.2,d.strength=1,d.reflectionSpecularFalloffExponent=3,d.step=1,d.roughnessFactor=.2,d._forceGeometryBuffer=!1,d._enableSmoothReflections=!1,d._reflectionSamples=64,d._smoothSteps=5,d._forceGeometryBuffer=h,d._forceGeometryBuffer){var p=i.enableGeometryBufferRenderer();p&&p.isSupported&&(p.enablePosition=!0,p.enableReflectivity=!0,p.generateNormalsInWorldSpace&&ae.Error("ScreenSpaceReflectionPostProcess does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!"))}else{var f=i.enablePrePassRenderer();null==f||f.markAsDirty(),(null==f?void 0:f.generateNormalsInWorldSpace)&&ae.Error("ScreenSpaceReflectionPostProcess does not support generateNormalsInWorldSpace=true for the prepass renderer!"),d._prePassEffectConfiguration=new ZC}return d._updateEffectDefines(),d.onApply=function(e){var t=d._geometryBufferRenderer,r=d._prePassRenderer;if(r||t){if(t){var n=t.getTextureIndex(BC.POSITION_TEXTURE_TYPE),o=t.getTextureIndex(BC.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("positionSampler",t.getGBuffer().textures[n]),e.setTexture("reflectivitySampler",t.getGBuffer().textures[o])}else if(r){n=r.getIndex(u.PREPASS_POSITION_TEXTURE_TYPE),o=r.getIndex(u.PREPASS_REFLECTIVITY_TEXTURE_TYPE);var a=r.getIndex(u.PREPASS_NORMAL_TEXTURE_TYPE);e.setTexture("normalSampler",r.getRenderTarget().textures[a]),e.setTexture("positionSampler",r.getRenderTarget().textures[n]),e.setTexture("reflectivitySampler",r.getRenderTarget().textures[o])}var s=i.activeCamera;if(s){var l=s.getViewMatrix(!0),c=s.getProjectionMatrix(!0);e.setMatrix("projection",c),e.setMatrix("view",l),e.setFloat("threshold",d.threshold),e.setFloat("reflectionSpecularFalloffExponent",d.reflectionSpecularFalloffExponent),e.setFloat("strength",d.strength),e.setFloat("stepSize",d.step),e.setFloat("roughnessFactor",d.roughnessFactor)}}},d._isSceneRightHanded=i.useRightHandedSystem,d}return m(t,e),Object.defineProperty(t.prototype,"_geometryBufferRenderer",{get:function(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_prePassRenderer",{get:function(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"ScreenSpaceReflectionPostProcess"},Object.defineProperty(t.prototype,"enableSmoothReflections",{get:function(){return this._enableSmoothReflections},set:function(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"reflectionSamples",{get:function(){return this._reflectionSamples},set:function(e){e!==this._reflectionSamples&&(this._reflectionSamples=e,this._updateEffectDefines())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"smoothSteps",{get:function(){return this._smoothSteps},set:function(e){e!==this._smoothSteps&&(this._smoothSteps=e,this._updateEffectDefines())},enumerable:!1,configurable:!0}),t.prototype._updateEffectDefines=function(){var e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define ENABLE_SMOOTH_REFLECTIONS"),this._isSceneRightHanded&&e.push("#define RIGHT_HANDED_SCENE"),e.push("#define REFLECTION_SAMPLES "+(0|this._reflectionSamples)),e.push("#define SMOOTH_STEPS "+(0|this._smoothSteps)),this.updateEffect(e.join("\n"))},t._Parse=function(e,i,r,n){return Ke.Parse((function(){return new t(e.name,r,e.options,i,e.renderTargetSamplingMode,r.getEngine(),e.textureType,e.reusable)}),e,r,n)},v([Ie()],t.prototype,"threshold",void 0),v([Ie()],t.prototype,"strength",void 0),v([Ie()],t.prototype,"reflectionSpecularFalloffExponent",void 0),v([Ie()],t.prototype,"step",void 0),v([Ie()],t.prototype,"roughnessFactor",void 0),v([Ie()],t.prototype,"enableSmoothReflections",null),v([Ie()],t.prototype,"reflectionSamples",null),v([Ie()],t.prototype,"smoothSteps",null),t}(hl);a("BABYLON.ScreenSpaceReflectionPostProcess",JC);li.ShadersStore.standardPixelShader="uniform sampler2D textureSampler;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];void main(void)\n{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+dsOffsets[0]);average+=texture2D(textureSampler,vUV+dsOffsets[1]);average+=texture2D(textureSampler,vUV+dsOffsets[2]);average+=texture2D(textureSampler,vUV+dsOffsets[3]);average+=texture2D(textureSampler,vUV+dsOffsets[4]);average+=texture2D(textureSampler,vUV+dsOffsets[5]);average+=texture2D(textureSampler,vUV+dsOffsets[6]);average+=texture2D(textureSampler,vUV+dsOffsets[7]);average+=texture2D(textureSampler,vUV+dsOffsets[8]);average+=texture2D(textureSampler,vUV+dsOffsets[9]);average+=texture2D(textureSampler,vUV+dsOffsets[10]);average+=texture2D(textureSampler,vUV+dsOffsets[11]);average+=texture2D(textureSampler,vUV+dsOffsets[12]);average+=texture2D(textureSampler,vUV+dsOffsets[13]);average+=texture2D(textureSampler,vUV+dsOffsets[14]);average+=texture2D(textureSampler,vUV+dsOffsets[15]);average/=16.0;gl_FragColor=average;}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void)\n{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));average*=0.25;float luminance=length(average.rgb);if (luminance<brightThreshold) {average=vec4(0.0,0.0,0.0,1.0);}\ngl_FragColor=average;}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;uniform sampler2D lensSampler;uniform float exposure;void main(void)\n{vec3 colour=texture2D(textureSampler,vUV).rgb;colour*=exposure;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor;colour+=colour*texture2D(lensSampler,vUV).rgb;vec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);gl_FragColor=finalColor;}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;uniform mat4 lightWorld;uniform vec3 cameraPosition;uniform vec3 sunDirection;uniform vec3 sunColor;uniform vec2 depthValues;uniform float scatteringCoefficient;uniform float scatteringPower;uniform sampler2D shadowMapSampler;uniform sampler2D positionSampler;float computeScattering(float lightDotView)\n{float result=1.0-scatteringCoefficient*scatteringCoefficient;result/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));return result;}\nvoid main(void)\n{vec3 worldPos=texture2D(positionSampler,vUV).rgb;vec3 startPosition=cameraPosition;vec3 rayVector=worldPos-startPosition;float rayLength=length(rayVector);vec3 rayDirection=rayVector/rayLength;float stepLength=rayLength/NB_STEPS;vec3 stepL=rayDirection*stepLength;vec3 currentPosition=startPosition;vec3 accumFog=vec3(0.0);for (int i=0; i<int(NB_STEPS); i++)\n{vec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);float depthMetric= (worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depthMetric,0.0,1.0);worldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;worldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);float shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;if (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;}\naccumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;void main(void)\n{gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];void main()\n{float average=0.0;vec4 color=vec4(0.0);float maximum=-1e20;vec3 weight=vec3(0.299,0.587,0.114);for (int i=0; i<4; i++)\n{color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));}\naverage=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];uniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\n#include<packingFunctions>\n#endif\nvoid main()\n{vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++)\n{color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;uniform float averageLuminance;void main()\n{vec4 color=texture2D(textureAdderSampler,vUV);\n#ifndef AUTO_EXPOSURE\nvec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0;\n#endif\ngl_FragColor=color;}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p)\n{float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);}\nfloat noise(in vec2 p)\n{vec2 i=floor(p);vec2 f=fract(p);vec2 u=f*f*(3.0-2.0*f);return mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);}\nfloat fbm(vec2 p)\n{float f=0.0;f+=0.5000*noise(p); p*=2.02;f+=0.2500*noise(p); p*=2.03;f+=0.1250*noise(p); p*=2.01;f+=0.0625*noise(p); p*=2.04;f/=0.9375;return f;}\nvec3 pattern(vec2 uv)\n{vec2 p=-1.0+2.0*uv;float p2=dot(p,p);float f=fbm(vec2(15.0*p2))/2.0;float r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));float g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));float b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));return (1.0-f)*vec3(r,g,b);}\nfloat luminance(vec3 color)\n{return dot(color.rgb,vec3(0.2126,0.7152,0.0722));}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{return vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);}\nvoid main(void)\n{vec2 uv=-vUV+vec2(1.0);vec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;vec2 texelSize=1.0/resolution;vec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);vec4 result=vec4(0.0);float ghostIndice=1.0;for (int i=0; i<GHOSTS; ++i)\n{vec2 offset=fract(uv+ghostDir*ghostIndice);float weight=length(vec2(0.5)-offset)/length(vec2(0.5));weight=pow(1.0-weight,10.0);result+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;ghostIndice+=1.0;}\nvec2 haloVec=normalize(ghostDir)*haloWidth;float weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));weight=pow(1.0-weight,10.0);result+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;result*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));gl_FragColor=result;}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;uniform sampler2D lensDirtSampler;uniform sampler2D lensStarSampler;uniform mat4 lensStarMatrix;void main(void)\n{vec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;vec4 lensMod=texture2D(lensDirtSampler,vUV);lensMod+=texture2D(lensStarSampler,vUV/*lensFlareCoords*/);vec4 result=texture2D(textureSampler,vUV)*lensMod;gl_FragColor=texture2D(otherSampler,vUV)+result;}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;uniform sampler2D depthSampler;uniform float distance;void main(void)\n{vec4 sharp=texture2D(otherSampler,vUV);vec4 blur=texture2D(textureSampler,vUV);float dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);float factor=0.0;if (dist<0.05)\nfactor=1.0;else if (dist<0.1)\nfactor=20.0*(0.1-dist);else if (dist<0.5)\nfactor=0.0;else\nfactor=2.0*(dist-0.5);factor=clamp(factor,0.0,0.90);gl_FragColor=mix(sharp,blur,factor);}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform vec2 screenSize;uniform float motionScale;uniform float motionStrength;uniform sampler2D depthSampler;void main(void)\n{vec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;vec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=cpos*inverseViewProjection;vec4 ppos=cpos*prevViewProjection;ppos.xyz/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {if (i>=nSamples)\nbreak;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);}\ngl_FragColor=result/float(nSamples);}\n#endif\n";var $C=function(e){function t(t,i,r,n,o){void 0===n&&(n=null);var a=e.call(this,i.getEngine(),t)||this;return a.downSampleX4PostProcess=null,a.brightPassPostProcess=null,a.blurHPostProcesses=[],a.blurVPostProcesses=[],a.textureAdderPostProcess=null,a.volumetricLightPostProcess=null,a.volumetricLightSmoothXPostProcess=null,a.volumetricLightSmoothYPostProcess=null,a.volumetricLightMergePostProces=null,a.volumetricLightFinalPostProcess=null,a.luminancePostProcess=null,a.luminanceDownSamplePostProcesses=[],a.hdrPostProcess=null,a.textureAdderFinalPostProcess=null,a.lensFlareFinalPostProcess=null,a.hdrFinalPostProcess=null,a.lensFlarePostProcess=null,a.lensFlareComposePostProcess=null,a.motionBlurPostProcess=null,a.depthOfFieldPostProcess=null,a.fxaaPostProcess=null,a.screenSpaceReflectionPostProcess=null,a.brightThreshold=1,a.blurWidth=512,a.horizontalBlur=!1,a.lensTexture=null,a.volumetricLightCoefficient=.2,a.volumetricLightPower=4,a.volumetricLightBlurScale=64,a.sourceLight=null,a.hdrMinimumLuminance=1,a.hdrDecreaseRate=.5,a.hdrIncreaseRate=.5,a.lensColorTexture=null,a.lensFlareStrength=20,a.lensFlareGhostDispersal=1.4,a.lensFlareHaloWidth=.7,a.lensFlareDistortionStrength=16,a.lensFlareBlurWidth=512,a.lensStarTexture=null,a.lensFlareDirtTexture=null,a.depthOfFieldDistance=10,a.depthOfFieldBlurWidth=64,a.animations=[],a._currentDepthOfFieldSource=null,a._fixedExposure=1,a._currentExposure=1,a._hdrAutoExposure=!1,a._hdrCurrentLuminance=1,a._motionStrength=1,a._isObjectBasedMotionBlur=!1,a._camerasToBeAttached=[],a._bloomEnabled=!1,a._depthOfFieldEnabled=!1,a._vlsEnabled=!1,a._lensFlareEnabled=!1,a._hdrEnabled=!1,a._motionBlurEnabled=!1,a._fxaaEnabled=!1,a._screenSpaceReflectionsEnabled=!1,a._motionBlurSamples=64,a._volumetricLightStepsCount=50,a._samples=1,a._cameras=o||i.cameras,a._cameras=a._cameras.slice(),a._camerasToBeAttached=a._cameras.slice(),a._scene=i,a._basePostProcess=n,a._ratio=r,a._floatTextureType=i.getEngine().getCaps().textureFloatRender?u.TEXTURETYPE_FLOAT:u.TEXTURETYPE_HALF_FLOAT,i.postProcessRenderPipelineManager.addPipeline(a),a._buildPipeline(),a}return m(t,e),Object.defineProperty(t.prototype,"exposure",{get:function(){return this._fixedExposure},set:function(e){this._fixedExposure=e,this._currentExposure=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"hdrAutoExposure",{get:function(){return this._hdrAutoExposure},set:function(e){if(this._hdrAutoExposure=e,this.hdrPostProcess){var t=["#define HDR"];e&&t.push("#define AUTO_EXPOSURE"),this.hdrPostProcess.updateEffect(t.join("\n"))}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"motionStrength",{get:function(){return this._motionStrength},set:function(e){this._motionStrength=e,this._isObjectBasedMotionBlur&&this.motionBlurPostProcess&&(this.motionBlurPostProcess.motionStrength=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"objectBasedMotionBlur",{get:function(){return this._isObjectBasedMotionBlur},set:function(e){var t=this._isObjectBasedMotionBlur!==e;this._isObjectBasedMotionBlur=e,t&&this._buildPipeline()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"BloomEnabled",{get:function(){return this._bloomEnabled},set:function(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"DepthOfFieldEnabled",{get:function(){return this._depthOfFieldEnabled},set:function(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"LensFlareEnabled",{get:function(){return this._lensFlareEnabled},set:function(e){this._lensFlareEnabled!==e&&(this._lensFlareEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"HDREnabled",{get:function(){return this._hdrEnabled},set:function(e){this._hdrEnabled!==e&&(this._hdrEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"VLSEnabled",{get:function(){return this._vlsEnabled},set:function(e){if(this._vlsEnabled!==e){if(e&&!this._scene.enableGeometryBufferRenderer())return void ae.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");this._vlsEnabled=e,this._buildPipeline()}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"MotionBlurEnabled",{get:function(){return this._motionBlurEnabled},set:function(e){this._motionBlurEnabled!==e&&(this._motionBlurEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"fxaaEnabled",{get:function(){return this._fxaaEnabled},set:function(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"screenSpaceReflectionsEnabled",{get:function(){return this._screenSpaceReflectionsEnabled},set:function(e){this._screenSpaceReflectionsEnabled!==e&&(this._screenSpaceReflectionsEnabled=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"volumetricLightStepsCount",{get:function(){return this._volumetricLightStepsCount},set:function(e){this.volumetricLightPostProcess&&this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS "+e.toFixed(1)),this._volumetricLightStepsCount=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"motionBlurSamples",{get:function(){return this._motionBlurSamples},set:function(e){this.motionBlurPostProcess&&(this._isObjectBasedMotionBlur?this.motionBlurPostProcess.motionBlurSamples=e:this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+e.toFixed(1))),this._motionBlurSamples=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"samples",{get:function(){return this._samples},set:function(e){this._samples!==e&&(this._samples=e,this._buildPipeline())},enumerable:!1,configurable:!0}),t.prototype._buildPipeline=function(){var e=this,t=this._ratio,i=this._scene;this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._screenSpaceReflectionsEnabled&&(this.screenSpaceReflectionPostProcess=new JC("HDRPass",i,t,null,Ja.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add((function(){e._currentDepthOfFieldSource=e.screenSpaceReflectionPostProcess})),this.addEffect(new vC(i.getEngine(),"HDRScreenSpaceReflections",(function(){return e.screenSpaceReflectionPostProcess}),!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new hl("HDRPass","standard",[],[],t,null,Ja.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,"#define PASS_POST_PROCESS",this._floatTextureType),this.originalPostProcess.autoClear=!this.screenSpaceReflectionPostProcess,this.originalPostProcess.onApplyObservable.add((function(){e._currentDepthOfFieldSource=e.originalPostProcess})),this.addEffect(new vC(i.getEngine(),"HDRPassPostProcess",(function(){return e.originalPostProcess}),!0)),this._bloomEnabled&&(this._createDownSampleX4PostProcess(i,t/4),this._createBrightPassPostProcess(i,t/4),this._createBlurPostProcesses(i,t/4,1),this._createTextureAdderPostProcess(i,t),this.textureAdderFinalPostProcess=new hl("HDRDepthOfFieldSource","standard",[],[],t,null,Ja.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,"#define PASS_POST_PROCESS",u.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new vC(i.getEngine(),"HDRBaseDepthOfFieldSource",(function(){return e.textureAdderFinalPostProcess}),!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(i,t),this.volumetricLightFinalPostProcess=new hl("HDRVLSFinal","standard",[],[],t,null,Ja.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,"#define PASS_POST_PROCESS",u.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new vC(i.getEngine(),"HDRVLSFinal",(function(){return e.volumetricLightFinalPostProcess}),!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(i,t),this.lensFlareFinalPostProcess=new hl("HDRPostLensFlareDepthOfFieldSource","standard",[],[],t,null,Ja.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,"#define PASS_POST_PROCESS",u.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new vC(i.getEngine(),"HDRPostLensFlareDepthOfFieldSource",(function(){return e.lensFlareFinalPostProcess}),!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(i,this._floatTextureType),this._createHdrPostProcess(i,t),this.hdrFinalPostProcess=new hl("HDRPostHDReDepthOfFieldSource","standard",[],[],t,null,Ja.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,"#define PASS_POST_PROCESS",u.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new vC(i.getEngine(),"HDRPostHDReDepthOfFieldSource",(function(){return e.hdrFinalPostProcess}),!0))),this._depthOfFieldEnabled&&(this._createBlurPostProcesses(i,t/2,3,"depthOfFieldBlurWidth"),this._createDepthOfFieldPostProcess(i,t)),this._motionBlurEnabled&&this._createMotionBlurPostProcess(i,t),this._fxaaEnabled&&(this.fxaaPostProcess=new DC("fxaa",1,null,Ja.BILINEAR_SAMPLINGMODE,i.getEngine(),!1,u.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new vC(i.getEngine(),"HDRFxaa",(function(){return e.fxaaPostProcess}),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&ae.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")},t.prototype._createDownSampleX4PostProcess=function(e,t){var i=this,r=new Array(32);this.downSampleX4PostProcess=new hl("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,Ja.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=function(e){for(var t=0,n=i.downSampleX4PostProcess.width,o=i.downSampleX4PostProcess.height,a=-2;a<2;a++)for(var s=-2;s<2;s++)r[t]=(a+.5)*(1/n),r[t+1]=(s+.5)*(1/o),t+=2;e.setArray2("dsOffsets",r)},this.addEffect(new vC(e.getEngine(),"HDRDownSampleX4",(function(){return i.downSampleX4PostProcess}),!0))},t.prototype._createBrightPassPostProcess=function(e,t){var i=this,r=new Array(8);this.brightPassPostProcess=new hl("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,Ja.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=function(e){var t=1/i.brightPassPostProcess.width,n=1/i.brightPassPostProcess.height;r[0]=-.5*t,r[1]=.5*n,r[2]=.5*t,r[3]=.5*n,r[4]=-.5*t,r[5]=-.5*n,r[6]=.5*t,r[7]=-.5*n,e.setArray2("dsOffsets",r),e.setFloat("brightThreshold",i.brightThreshold)},this.addEffect(new vC(e.getEngine(),"HDRBrightPass",(function(){return i.brightPassPostProcess}),!0))},t.prototype._createBlurPostProcesses=function(e,t,i,r){var n=this;void 0===r&&(r="blurWidth");var o=e.getEngine(),a=new Om("HDRBlurH_"+i,new U(1,0),this[r],t,null,Ja.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),s=new Om("HDRBlurV_"+i,new U(0,1),this[r],t,null,Ja.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);a.onActivateObservable.add((function(){var e=a.width/o.getRenderWidth();a.kernel=n[r]*e})),s.onActivateObservable.add((function(){var e=s.height/o.getRenderHeight();s.kernel=n.horizontalBlur?64*e:n[r]*e})),this.addEffect(new vC(e.getEngine(),"HDRBlurH"+i,(function(){return a}),!0)),this.addEffect(new vC(e.getEngine(),"HDRBlurV"+i,(function(){return s}),!0)),this.blurHPostProcesses.push(a),this.blurVPostProcesses.push(s)},t.prototype._createTextureAdderPostProcess=function(e,t){var i=this;this.textureAdderPostProcess=new hl("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,Ja.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",this._floatTextureType),this.textureAdderPostProcess.onApply=function(e){e.setTextureFromPostProcess("otherSampler",i._vlsEnabled?i._currentDepthOfFieldSource:i.originalPostProcess),e.setTexture("lensSampler",i.lensTexture),e.setFloat("exposure",i._currentExposure),i._currentDepthOfFieldSource=i.textureAdderFinalPostProcess},this.addEffect(new vC(e.getEngine(),"HDRTextureAdder",(function(){return i.textureAdderPostProcess}),!0))},t.prototype._createVolumetricLightPostProcess=function(e,t){var i=this,r=e.enableGeometryBufferRenderer();r.enablePosition=!0;var n=r.getGBuffer();this.volumetricLightPostProcess=new hl("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,Ja.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLS\n#define NB_STEPS "+this._volumetricLightStepsCount.toFixed(1));var o=U.Zero();this.volumetricLightPostProcess.onApply=function(e){if(i.sourceLight&&i.sourceLight.getShadowGenerator()&&i._scene.activeCamera){var t=i.sourceLight.getShadowGenerator();e.setTexture("shadowMapSampler",t.getShadowMap()),e.setTexture("positionSampler",n.textures[2]),e.setColor3("sunColor",i.sourceLight.diffuse),e.setVector3("sunDirection",i.sourceLight.getShadowDirection()),e.setVector3("cameraPosition",i._scene.activeCamera.globalPosition),e.setMatrix("shadowViewProjection",t.getTransformMatrix()),e.setFloat("scatteringCoefficient",i.volumetricLightCoefficient),e.setFloat("scatteringPower",i.volumetricLightPower),o.x=i.sourceLight.getDepthMinZ(i._scene.activeCamera),o.y=i.sourceLight.getDepthMaxZ(i._scene.activeCamera),e.setVector2("depthValues",o)}},this.addEffect(new vC(e.getEngine(),"HDRVLS",(function(){return i.volumetricLightPostProcess}),!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new hl("HDRVLSMerge","standard",[],["originalSampler"],t,null,Ja.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=function(e){e.setTextureFromPostProcess("originalSampler",i._bloomEnabled?i.textureAdderFinalPostProcess:i.originalPostProcess),i._currentDepthOfFieldSource=i.volumetricLightFinalPostProcess},this.addEffect(new vC(e.getEngine(),"HDRVLSMerge",(function(){return i.volumetricLightMergePostProces}),!0))},t.prototype._createLuminancePostProcesses=function(e,i){var r=this,n=Math.pow(3,t.LuminanceSteps);this.luminancePostProcess=new hl("HDRLuminance","standard",["lumOffsets"],[],{width:n,height:n},null,Ja.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",i);var o=[];this.luminancePostProcess.onApply=function(e){var t=1/r.luminancePostProcess.width,i=1/r.luminancePostProcess.height;o[0]=-.5*t,o[1]=.5*i,o[2]=.5*t,o[3]=.5*i,o[4]=-.5*t,o[5]=-.5*i,o[6]=.5*t,o[7]=-.5*i,e.setArray2("lumOffsets",o)},this.addEffect(new vC(e.getEngine(),"HDRLuminance",(function(){return r.luminancePostProcess}),!0));for(var a=t.LuminanceSteps-1;a>=0;a--){n=Math.pow(3,a);var s="#define LUMINANCE_DOWN_SAMPLE\n";0===a&&(s+="#define FINAL_DOWN_SAMPLER");var l=new hl("HDRLuminanceDownSample"+a,"standard",["dsOffsets","halfDestPixelSize"],[],{width:n,height:n},null,Ja.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,i);this.luminanceDownSamplePostProcesses.push(l)}var c=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach((function(t,i){var n=new Array(18);t.onApply=function(e){if(c){for(var o=0,a=-1;a<2;a++)for(var s=-1;s<2;s++)n[o]=a/c.width,n[o+1]=s/c.height,o+=2;e.setArray2("dsOffsets",n),e.setFloat("halfDestPixelSize",.5/c.width),c=i===r.luminanceDownSamplePostProcesses.length-1?r.luminancePostProcess:t}},i===r.luminanceDownSamplePostProcesses.length-1&&(t.onAfterRender=function(){var t=e.getEngine().readPixels(0,0,1,1),i=new k(1/16581375,1/65025,1/255,1);t.then((function(e){var t=new Uint8Array(e.buffer);r._hdrCurrentLuminance=(t[0]*i.x+t[1]*i.y+t[2]*i.z+t[3]*i.w)/100}))}),r.addEffect(new vC(e.getEngine(),"HDRLuminanceDownSample"+i,(function(){return t}),!0))}))},t.prototype._createHdrPostProcess=function(e,t){var i=this,r=["#define HDR"];this._hdrAutoExposure&&r.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new hl("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,Ja.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r.join("\n"),u.TEXTURETYPE_UNSIGNED_INT);var n=1,o=0,a=0;this.hdrPostProcess.onApply=function(t){if(t.setTextureFromPostProcess("textureAdderSampler",i._currentDepthOfFieldSource),o+=e.getEngine().getDeltaTime(),n<0)n=i._hdrCurrentLuminance;else{var r=(a-o)/1e3;i._hdrCurrentLuminance<n+i.hdrDecreaseRate*r?n+=i.hdrDecreaseRate*r:i._hdrCurrentLuminance>n-i.hdrIncreaseRate*r?n-=i.hdrIncreaseRate*r:n=i._hdrCurrentLuminance}i.hdrAutoExposure?i._currentExposure=i._fixedExposure/n:(n=j.Clamp(n,i.hdrMinimumLuminance,1e20),t.setFloat("averageLuminance",n)),a=o,i._currentDepthOfFieldSource=i.hdrFinalPostProcess},this.addEffect(new vC(e.getEngine(),"HDR",(function(){return i.hdrPostProcess}),!0))},t.prototype._createLensFlarePostProcess=function(e,t){var i=this;this.lensFlarePostProcess=new hl("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,Ja.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",u.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new vC(e.getEngine(),"HDRLensFlare",(function(){return i.lensFlarePostProcess}),!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new hl("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,Ja.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",u.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new vC(e.getEngine(),"HDRLensFlareCompose",(function(){return i.lensFlareComposePostProcess}),!0));var r=new U(0,0);this.lensFlarePostProcess.externalTextureSamplerBinding=!0,this.lensFlarePostProcess.onApply=function(e){e.setTextureFromPostProcess("textureSampler",i._bloomEnabled?i.blurHPostProcesses[0]:i.originalPostProcess),e.setTexture("lensColorSampler",i.lensColorTexture),e.setFloat("strength",i.lensFlareStrength),e.setFloat("ghostDispersal",i.lensFlareGhostDispersal),e.setFloat("haloWidth",i.lensFlareHaloWidth),r.x=i.lensFlarePostProcess.width,r.y=i.lensFlarePostProcess.height,e.setVector2("resolution",r),e.setFloat("distortionStrength",i.lensFlareDistortionStrength)};var n=z.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),o=z.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=function(e){if(i._scene.activeCamera){e.setTextureFromPostProcess("otherSampler",i.lensFlarePostProcess),e.setTexture("lensDirtSampler",i.lensFlareDirtTexture),e.setTexture("lensStarSampler",i.lensStarTexture);var t=i._scene.activeCamera.getViewMatrix().getRow(0),r=i._scene.activeCamera.getViewMatrix().getRow(2),a=V.Dot(t.toVector3(),new V(1,0,0))+V.Dot(r.toVector3(),new V(0,0,1));a*=4;var s=z.FromValues(.5*Math.cos(a),-Math.sin(a),0,0,Math.sin(a),.5*Math.cos(a),0,0,0,0,1,0,0,0,0,1),l=o.multiply(s).multiply(n);e.setMatrix("lensStarMatrix",l),i._currentDepthOfFieldSource=i.lensFlareFinalPostProcess}}},t.prototype._createDepthOfFieldPostProcess=function(e,t){var i=this;this.depthOfFieldPostProcess=new hl("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,Ja.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",u.TEXTURETYPE_UNSIGNED_INT),this.depthOfFieldPostProcess.onApply=function(e){e.setTextureFromPostProcess("otherSampler",i._currentDepthOfFieldSource),e.setTexture("depthSampler",i._getDepthTexture()),e.setFloat("distance",i.depthOfFieldDistance)},this.addEffect(new vC(e.getEngine(),"HDRDepthOfField",(function(){return i.depthOfFieldPostProcess}),!0))},t.prototype._createMotionBlurPostProcess=function(e,t){var i=this;if(this._isObjectBasedMotionBlur){var r=new kC("HDRMotionBlur",e,t,null,Ja.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,u.TEXTURETYPE_UNSIGNED_INT);r.motionStrength=this.motionStrength,r.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=r}else{this.motionBlurPostProcess=new hl("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,Ja.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),u.TEXTURETYPE_UNSIGNED_INT);var n=0,o=z.Identity(),a=z.Identity(),s=z.Identity(),l=U.Zero();this.motionBlurPostProcess.onApply=function(t){(s=e.getProjectionMatrix().multiply(e.getViewMatrix())).invertToRef(a),t.setMatrix("inverseViewProjection",a),t.setMatrix("prevViewProjection",o),o=s,l.x=i.motionBlurPostProcess.width,l.y=i.motionBlurPostProcess.height,t.setVector2("screenSize",l),n=e.getEngine().getFps()/60,t.setFloat("motionScale",n),t.setFloat("motionStrength",i.motionStrength),t.setTexture("depthSampler",i._getDepthTexture())}}this.addEffect(new vC(e.getEngine(),"HDRMotionBlur",(function(){return i.motionBlurPostProcess}),!0))},t.prototype._getDepthTexture=function(){return this._scene.getEngine().getCaps().drawBuffersExtension?this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]:this._scene.enableDepthRenderer().getDepthMap()},t.prototype._disposePostProcesses=function(){for(var e=0;e<this._cameras.length;e++){var t=this._cameras[e];this.originalPostProcess&&this.originalPostProcess.dispose(t),this.screenSpaceReflectionPostProcess&&this.screenSpaceReflectionPostProcess.dispose(t),this.downSampleX4PostProcess&&this.downSampleX4PostProcess.dispose(t),this.brightPassPostProcess&&this.brightPassPostProcess.dispose(t),this.textureAdderPostProcess&&this.textureAdderPostProcess.dispose(t),this.volumetricLightPostProcess&&this.volumetricLightPostProcess.dispose(t),this.volumetricLightSmoothXPostProcess&&this.volumetricLightSmoothXPostProcess.dispose(t),this.volumetricLightSmoothYPostProcess&&this.volumetricLightSmoothYPostProcess.dispose(t),this.volumetricLightMergePostProces&&this.volumetricLightMergePostProces.dispose(t),this.volumetricLightFinalPostProcess&&this.volumetricLightFinalPostProcess.dispose(t),this.lensFlarePostProcess&&this.lensFlarePostProcess.dispose(t),this.lensFlareComposePostProcess&&this.lensFlareComposePostProcess.dispose(t);for(var i=0;i<this.luminanceDownSamplePostProcesses.length;i++)this.luminanceDownSamplePostProcesses[i].dispose(t);for(this.luminancePostProcess&&this.luminancePostProcess.dispose(t),this.hdrPostProcess&&this.hdrPostProcess.dispose(t),this.hdrFinalPostProcess&&this.hdrFinalPostProcess.dispose(t),this.depthOfFieldPostProcess&&this.depthOfFieldPostProcess.dispose(t),this.motionBlurPostProcess&&this.motionBlurPostProcess.dispose(t),this.fxaaPostProcess&&this.fxaaPostProcess.dispose(t),i=0;i<this.blurHPostProcesses.length;i++)this.blurHPostProcesses[i].dispose(t);for(i=0;i<this.blurVPostProcesses.length;i++)this.blurVPostProcesses[i].dispose(t)}this.originalPostProcess=null,this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.textureAdderPostProcess=null,this.textureAdderFinalPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.luminancePostProcess=null,this.hdrPostProcess=null,this.hdrFinalPostProcess=null,this.depthOfFieldPostProcess=null,this.motionBlurPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.luminanceDownSamplePostProcesses.length=0,this.blurHPostProcesses.length=0,this.blurVPostProcesses.length=0},t.prototype.dispose=function(){this._disposePostProcesses(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),e.prototype.dispose.call(this)},t.prototype.serialize=function(){var e=Ke.Serialize(this);return this.sourceLight&&(e.sourceLightId=this.sourceLight.id),this.screenSpaceReflectionPostProcess&&(e.screenSpaceReflectionPostProcess=Ke.Serialize(this.screenSpaceReflectionPostProcess)),e.customType="StandardRenderingPipeline",e},t.Parse=function(e,i,r){var n=Ke.Parse((function(){return new t(e._name,i,e._ratio)}),e,i,r);return e.sourceLightId&&(n.sourceLight=i.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&Ke.Parse((function(){return n.screenSpaceReflectionPostProcess}),e.screenSpaceReflectionPostProcess,i,r),n},t.LuminanceSteps=6,v([Ie()],t.prototype,"brightThreshold",void 0),v([Ie()],t.prototype,"blurWidth",void 0),v([Ie()],t.prototype,"horizontalBlur",void 0),v([Ie()],t.prototype,"exposure",null),v([Me("lensTexture")],t.prototype,"lensTexture",void 0),v([Ie()],t.prototype,"volumetricLightCoefficient",void 0),v([Ie()],t.prototype,"volumetricLightPower",void 0),v([Ie()],t.prototype,"volumetricLightBlurScale",void 0),v([Ie()],t.prototype,"hdrMinimumLuminance",void 0),v([Ie()],t.prototype,"hdrDecreaseRate",void 0),v([Ie()],t.prototype,"hdrIncreaseRate",void 0),v([Ie()],t.prototype,"hdrAutoExposure",null),v([Me("lensColorTexture")],t.prototype,"lensColorTexture",void 0),v([Ie()],t.prototype,"lensFlareStrength",void 0),v([Ie()],t.prototype,"lensFlareGhostDispersal",void 0),v([Ie()],t.prototype,"lensFlareHaloWidth",void 0),v([Ie()],t.prototype,"lensFlareDistortionStrength",void 0),v([Ie()],t.prototype,"lensFlareBlurWidth",void 0),v([Me("lensStarTexture")],t.prototype,"lensStarTexture",void 0),v([Me("lensFlareDirtTexture")],t.prototype,"lensFlareDirtTexture",void 0),v([Ie()],t.prototype,"depthOfFieldDistance",void 0),v([Ie()],t.prototype,"depthOfFieldBlurWidth",void 0),v([Ie()],t.prototype,"motionStrength",null),v([Ie()],t.prototype,"objectBasedMotionBlur",null),v([Ie()],t.prototype,"_ratio",void 0),v([Ie()],t.prototype,"BloomEnabled",null),v([Ie()],t.prototype,"DepthOfFieldEnabled",null),v([Ie()],t.prototype,"LensFlareEnabled",null),v([Ie()],t.prototype,"HDREnabled",null),v([Ie()],t.prototype,"VLSEnabled",null),v([Ie()],t.prototype,"MotionBlurEnabled",null),v([Ie()],t.prototype,"fxaaEnabled",null),v([Ie()],t.prototype,"screenSpaceReflectionsEnabled",null),v([Ie()],t.prototype,"volumetricLightStepsCount",null),v([Ie()],t.prototype,"motionBlurSamples",null),v([Ie()],t.prototype,"samples",null),t}(WC);a("BABYLON.StandardRenderingPipeline",$C);var eR=function(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[u.PREPASS_NORMAL_TEXTURE_TYPE,u.PREPASS_REFLECTIVITY_TEXTURE_TYPE,u.PREPASS_DEPTH_TEXTURE_TYPE]};li.IncludesShadersStore.screenSpaceRayTrace="float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); }\n/**\nparam csOrigin Camera-space ray origin,which must be \nwithin the view volume and must have z>0.01 and project within the valid screen rectangle\nparam csDirection Unit length camera-space ray direction\nparam projectToPixelMatrix A projection matrix that maps to **pixel** coordinates \n(**not** [-1,+1] normalized device coordinates).\nparam csZBuffer The camera-space Z buffer\nparam csZBufferSize Dimensions of csZBuffer\nparam csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer\nparam nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value\nfor clipping rays headed towards the camera\nparam stride Step in horizontal or vertical pixels between samples. This is a float\nbecause integer math is slow on GPUs,but should be set to an integer>=1\nparam jitterFraction Number between 0 and 1 for how far to bump the ray in stride units\nto conceal banding artifacts,plus the stride ray offset.\nparam maxSteps Maximum number of iterations. Higher gives better images but may be slow\nparam maxRayTraceDistance Maximum camera-space distance to trace before returning a miss\nparam selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions.\n1 is a reasonable value,depending on the scene you may need to set this value to 2\nparam hitPixel Pixel coordinates of the first intersection with the scene\nparam numIterations number of iterations performed\nparam csHitPoint Camera space location of the ray hit\n*/\n#define inline\nbool traceScreenSpaceRay1(\nvec3 csOrigin,\nvec3 csDirection,\nmat4 projectToPixelMatrix,\nsampler2D csZBuffer,\nvec2 csZBufferSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nsampler2D csZBackBuffer,\nfloat csZBackSizeFactor,\n#endif\nfloat csZThickness,\nfloat nearPlaneZ,\nfloat stride,\nfloat jitterFraction,\nfloat maxSteps,\nfloat maxRayTraceDistance,\nfloat selfCollisionNumSkip,\nout vec2 startPixel,\nout vec2 hitPixel,\nout vec3 csHitPoint,\nout float numIterations\n#ifdef SSRAYTRACE_DEBUG\n,out vec3 debugColor\n#endif\n)\n{\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance;\n#else\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)<nearPlaneZ ? (nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance;\n#endif\nvec3 csEndPoint=csOrigin+csDirection*rayLength;hitPixel=vec2(-1.0,-1.0);vec4 H0=projectToPixelMatrix*vec4(csOrigin,1.0);vec4 H1=projectToPixelMatrix*vec4(csEndPoint,1.0);float k0=1.0/H0.w;float k1=1.0/H1.w;vec3 Q0=csOrigin*k0;vec3 Q1=csEndPoint*k1;vec2 P0=H0.xy*k0;vec2 P1=H1.xy*k1;\n#ifdef SSRAYTRACE_CLIP_TO_FRUSTUM\nfloat xMax=csZBufferSize.x-0.5,xMin=0.5,yMax=csZBufferSize.y-0.5,yMin=0.5;float alpha=0.0;if ((P1.y>yMax) || (P1.y<yMin)) {alpha=(P1.y-((P1.y>yMax) ? yMax : yMin))/(P1.y-P0.y);}\nif ((P1.x>xMax) || (P1.x<xMin)) {alpha=max(alpha,(P1.x-((P1.x>xMax) ? xMax : xMin))/(P1.x-P0.x));}\nP1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha);\n#endif\nP1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)<abs(delta.y)) { \npermute=true;delta=delta.yx;P0=P0.yx;P1=P1.yx; }\nfloat stepDirection=sign(delta.x);float invdx=stepDirection/delta.x;vec2 dP=vec2(stepDirection,delta.y*invdx);vec3 dQ=(Q1-Q0)*invdx;float dk=(k1-k0)*invdx;float zMin=min(csEndPoint.z,csOrigin.z);float zMax=max(csEndPoint.z,csOrigin.z);dP*=stride; dQ*=stride; dk*=stride;P0+=dP*jitterFraction; Q0+=dQ*jitterFraction; k0+=dk*jitterFraction;vec4 pqk=vec4(P0,Q0.z,k0);vec4 dPQK=vec4(dP,dQ.z,dk);startPixel=permute ? P0.yx : P0.xy;float prevZMaxEstimate=csOrigin.z;float rayZMin=prevZMaxEstimate,rayZMax=prevZMaxEstimate;float sceneZMax=rayZMax+1e4;float end=P1.x*stepDirection;bool hit=false;float stepCount;for (stepCount=0.0;stepCount<=selfCollisionNumSkip ||\n(pqk.x*stepDirection)<=end &&\nstepCount<maxSteps &&\n!hit &&\nsceneZMax != 0.0; \npqk+=dPQK,++stepCount)\n{hitPixel=permute ? pqk.yx : pqk.xy;rayZMin=prevZMaxEstimate;rayZMax=(dPQK.z*0.5+pqk.z)/(dPQK.w*0.5+pqk.w);rayZMax=clamp(rayZMax,zMin,zMax);prevZMaxEstimate=rayZMax;if (rayZMin>rayZMax) { \nfloat t=rayZMin; rayZMin=rayZMax; rayZMax=t;}\nsceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax);\n#else\nhit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax);\n#endif\n#else\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0);\n#else\nhit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax);\n#endif\n#endif\n}\npqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;}\n#ifdef SSRAYTRACE_ENABLE_REFINEMENT\nif (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;float invStride=1.0/stride;dPQK*=invStride;float refinementStepCount=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 ||\n(refinementStepCount<=stride*1.4) &&\n(rayZMax<sceneZMax) && (sceneZMax != 0.0);pqk+=dPQK,refinementStepCount+=1.0)\n{rayZMin=prevZMaxEstimate;rayZMax=(dPQK.z*0.5+pqk.z)/(dPQK.w*0.5+pqk.w);rayZMax=clamp(rayZMax,zMin,zMax);prevZMaxEstimate=rayZMax;rayZMax=max(rayZMax,rayZMin);hitPixel=permute ? pqk.yx : pqk.xy;sceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;}\npqk-=dPQK;refinementStepCount-=1.0;stepCount+=refinementStepCount/stride;}\n#endif\nQ0.xy+=dQ.xy*stepCount;Q0.z=pqk.z;csHitPoint=Q0/pqk.w;numIterations=stepCount+1.0;\n#ifdef SSRAYTRACE_DEBUG\nif (((pqk.x+dPQK.x)*stepDirection)>end) {debugColor=vec3(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {debugColor=vec3(1,0,0);} else if (sceneZMax==0.0) {debugColor=vec3(1,1,0);} else {debugColor=vec3(0,stepCount/maxSteps,0);}\n#endif\nreturn hit;}\n/**\ntexCoord: in the [0,1] range\ndepth: depth in view space (range [znear,zfar]])\n*/\nvec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef ORTHOGRAPHIC_CAMERA\nndc.z=-projection[2].z*depth+projection[3].z;\n#else\nndc.z=-projection[2].z-projection[3].z/depth;\n#endif\n#else\n#ifdef ORTHOGRAPHIC_CAMERA\nndc.z=projection[2].z*depth+projection[3].z;\n#else\nndc.z=projection[2].z+projection[3].z/depth;\n#endif\n#endif\nndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}\n";li.ShadersStore.screenSpaceReflection2PixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSR_SUPPORTED\nuniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler;\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nuniform sampler2D backDepthSampler;uniform float backSizeFactor;\n#endif\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nuniform samplerCube envCubeSampler;\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize;\n#endif\n#endif\nuniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float stepSize;uniform float maxSteps;uniform float strength;uniform float thickness;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;uniform float maxDistance;uniform float selfCollisionNumSkip;uniform float reflectivityThreshold;\n#include<helperFunctions>\n#include<pbrBRDFFunctions>\n#include<screenSpaceRayTrace>\nvec3 hash(vec3 a)\n{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);}\nfloat computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0;\n#ifdef SSR_ATTENUATE_SCREEN_BORDERS\nvec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE\nattenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS\nattenuation*=1.0-(numIterations/maxSteps);\n#endif\n#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION\nvec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation;\n#endif\nreturn attenuation;}\n#endif\nvoid main()\n{\n#ifdef SSR_SUPPORTED\nvec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {\n#ifdef SSR_USE_BLUR\ngl_FragColor=vec4(0.);\n#else\ngl_FragColor=colorFull;\n#endif\nreturn;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\nvec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; \n#ifdef SSR_DECODE_NORMAL\ncsNormal=csNormal*2.0-1.0;\n#endif\n#ifdef SSR_NORMAL_IS_IN_WORLDSPACE\ncsNormal=(view*vec4(csNormal,0.0)).xyz;\n#endif\nfloat depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);\n#ifdef ORTHOGRAPHIC_CAMERA\nvec3 csViewDirection=vec3(0.,0.,1.);\n#else\nvec3 csViewDirection=normalize(csPosition);\n#endif\nvec3 csReflectedVector=reflect(csViewDirection,csNormal);\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nvec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0));\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nvec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition);\n#endif\n#ifdef SSR_INVERTCUBICMAP\nwReflectedVector.y*=-1.0;\n#endif\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nwReflectedVector.z*=-1.0;\n#endif\nvec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz;\n#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE\nenvColor=toLinearSpace(envColor);\n#endif\n#else\nvec3 envColor=color;\n#endif\nfloat reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations;\n#ifdef SSRAYTRACE_DEBUG\nvec3 debugColor;\n#endif\n#ifdef SSR_ATTENUATE_FACING_CAMERA\nreflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector));\n#endif\nif (reflectionAttenuation>0.0) {\n#ifdef SSR_USE_BLUR\nvec3 jitt=vec3(0.);\n#else\nfloat roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; \n#endif\nvec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); \nrayHasHit=traceScreenSpaceRay1(\ncsPosition,\nnormalize(csReflectedVector+jitt),\nprojectionPixel,\ndepthSampler,\ntexSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nbackDepthSampler,\nbackSizeFactor,\n#endif\nthickness,\nnearPlaneZ,\nstepSize,\njitter,\nmaxSteps,\nmaxDistance,\nselfCollisionNumSkip,\nstartPixel,\nhitPixel,\nhitPoint,\nnumIterations\n#ifdef SSRAYTRACE_DEBUG\n,debugColor\n#endif\n);}\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=vec4(debugColor,1.);return;\n#endif\nvec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 SSR=envColor;if (rayHasHit) {vec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb;\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\nreflectedColor=toLinearSpace(reflectedColor);\n#endif\nreflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;}\n#ifndef SSR_BLEND_WITH_FRESNEL\nSSR*=fresnel;\n#endif\n#ifdef SSR_USE_BLUR\nfloat blur_radius=0.0;float roughness=1.0-reflectivity.a*(1.0-roughnessFactor);if (roughness>0.001) {float cone_angle=min(roughness,0.999)*3.14159265*0.5;float cone_len=distance(startPixel,hitPixel);float op_len=2.0*tan(cone_angle)*cone_len; \nfloat a=op_len;float h=cone_len;float a2=a*a;float fh2=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);}\ngl_FragColor=vec4(SSR,blur_radius/255.0); \n#else\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,colorFull.a);\n#endif\n#else\ngl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0);\n#endif\n}\n";li.ShadersStore.screenSpaceReflection2BlurPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;uniform vec2 texelOffsetScale;const float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);void processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator)\n{vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;}\nvoid main()\n{vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;}\nfloat blurRadius=colorFull.a*255.0; \nvec2 stepSize=texelOffsetScale.xy*blurRadius;vec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;float denominator=0.214607;processSample(vUV,1.0,stepSize,accumulator,denominator);processSample(vUV,1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,1.0*2.0,stepSize,accumulator,denominator);processSample(vUV,-1.0,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);gl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);}\n";li.ShadersStore.screenSpaceReflection2BlurCombinerPixelShader="uniform sampler2D textureSampler; \nuniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV;\n#include<helperFunctions>\n#ifdef SSR_BLEND_WITH_FRESNEL\n#include<pbrBRDFFunctions>\n#include<screenSpaceRayTrace>\nuniform mat4 projection;uniform mat4 invProjectionMatrix;uniform sampler2D normalSampler;uniform sampler2D depthSampler;\n#endif\nvoid main()\n{\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=texture2D(textureSampler,vUV);\n#else\nvec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,color.a);\n#endif\n}\n";var tR=z.Compose(new V(.5,.5,.5),G.Identity(),new V(.5,.5,.5)),iR=z.Compose(new V(.5,.5,1),G.Identity(),new V(.5,.5,0)),rR=function(e){function t(t,i,r,n,o){void 0===n&&(n=!1),void 0===o&&(o=u.TEXTURETYPE_UNSIGNED_BYTE);var a=e.call(this,i.getEngine(),t)||this;if(a.SSRRenderEffect="SSRRenderEffect",a.SSRBlurRenderEffect="SSRBlurRenderEffect",a.SSRCombineRenderEffect="SSRCombineRenderEffect",a._samples=1,a.maxDistance=1e3,a.step=1,a.thickness=.5,a.strength=1,a.reflectionSpecularFalloffExponent=1,a.maxSteps=1e3,a.roughnessFactor=.2,a.selfCollisionNumSkip=1,a._reflectivityThreshold=.04,a._ssrDownsample=0,a._blurDispersionStrength=.03,a._blurDownsample=0,a._enableSmoothReflections=!1,a._environmentTextureIsProbe=!1,a._attenuateScreenBorders=!0,a._attenuateIntersectionDistance=!0,a._attenuateIntersectionIterations=!0,a._attenuateFacingCamera=!1,a._attenuateBackfaceReflection=!1,a._clipToFrustum=!0,a._useFresnel=!1,a._enableAutomaticThicknessComputation=!1,a._backfaceDepthTextureDownsample=0,a._backfaceForceDepthWriteTransparentMeshes=!0,a._isEnabled=!0,a._inputTextureColorIsInGammaSpace=!0,a._generateOutputInGammaSpace=!0,a._debug=!1,a._forceGeometryBuffer=!1,a._isDirty=!1,a._camerasToBeAttached=[],a._cameras=r||i.cameras,a._cameras=a._cameras.slice(),a._camerasToBeAttached=a._cameras.slice(),a._scene=i,a._textureType=o,a._forceGeometryBuffer=n,a.isSupported){if(i.postProcessRenderPipelineManager.addPipeline(a),a._forceGeometryBuffer){var s=i.enableGeometryBufferRenderer();s&&(s.enableReflectivity=!0,s.useSpecificClearForDepthTexture=!0)}else{var l=i.enablePrePassRenderer();l&&(l.useSpecificClearForDepthTexture=!0,l.markAsDirty())}a._buildPipeline()}return a}return m(t,e),Object.defineProperty(t.prototype,"samples",{get:function(){return this._samples},set:function(e){this._samples!==e&&(this._samples=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"reflectivityThreshold",{get:function(){return this._reflectivityThreshold},set:function(e){e!==this._reflectivityThreshold&&(0===e&&0!==this._reflectivityThreshold||0!==e&&0===this._reflectivityThreshold?(this._reflectivityThreshold=e,this._buildPipeline()):this._reflectivityThreshold=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"ssrDownsample",{get:function(){return this._ssrDownsample},set:function(e){e!==this._ssrDownsample&&(this._ssrDownsample=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"blurDispersionStrength",{get:function(){return this._blurDispersionStrength},set:function(e){if(e!==this._blurDispersionStrength){var t=0===e&&0!==this._blurDispersionStrength||0!==e&&0===this._blurDispersionStrength;this._blurDispersionStrength=e,t&&this._buildPipeline()}},enumerable:!1,configurable:!0}),t.prototype._useBlur=function(){return this._blurDispersionStrength>0},Object.defineProperty(t.prototype,"blurDownsample",{get:function(){return this._blurDownsample},set:function(e){e!==this._blurDownsample&&(this._blurDownsample=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"enableSmoothReflections",{get:function(){return this._enableSmoothReflections},set:function(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"environmentTexture",{get:function(){return this._environmentTexture},set:function(e){this._environmentTexture=e,this._updateEffectDefines()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"environmentTextureIsProbe",{get:function(){return this._environmentTextureIsProbe},set:function(e){this._environmentTextureIsProbe=e,this._updateEffectDefines()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"attenuateScreenBorders",{get:function(){return this._attenuateScreenBorders},set:function(e){this._attenuateScreenBorders!==e&&(this._attenuateScreenBorders=e,this._updateEffectDefines())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"attenuateIntersectionDistance",{get:function(){return this._attenuateIntersectionDistance},set:function(e){this._attenuateIntersectionDistance!==e&&(this._attenuateIntersectionDistance=e,this._updateEffectDefines())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"attenuateIntersectionIterations",{get:function(){return this._attenuateIntersectionIterations},set:function(e){this._attenuateIntersectionIterations!==e&&(this._attenuateIntersectionIterations=e,this._updateEffectDefines())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"attenuateFacingCamera",{get:function(){return this._attenuateFacingCamera},set:function(e){this._attenuateFacingCamera!==e&&(this._attenuateFacingCamera=e,this._updateEffectDefines())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"attenuateBackfaceReflection",{get:function(){return this._attenuateBackfaceReflection},set:function(e){this._attenuateBackfaceReflection!==e&&(this._attenuateBackfaceReflection=e,this._updateEffectDefines())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"clipToFrustum",{get:function(){return this._clipToFrustum},set:function(e){this._clipToFrustum!==e&&(this._clipToFrustum=e,this._updateEffectDefines())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"useFresnel",{get:function(){return this._useFresnel},set:function(e){this._useFresnel!==e&&(this._useFresnel=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"enableAutomaticThicknessComputation",{get:function(){return this._enableAutomaticThicknessComputation},set:function(e){this._enableAutomaticThicknessComputation!==e&&(this._enableAutomaticThicknessComputation=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"backfaceDepthRenderer",{get:function(){return this._depthRenderer},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"backfaceDepthTextureDownsample",{get:function(){return this._backfaceDepthTextureDownsample},set:function(e){this._backfaceDepthTextureDownsample!==e&&(this._backfaceDepthTextureDownsample=e,this._resizeDepthRenderer())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"backfaceForceDepthWriteTransparentMeshes",{get:function(){return this._backfaceForceDepthWriteTransparentMeshes},set:function(e){this._backfaceForceDepthWriteTransparentMeshes!==e&&(this._backfaceForceDepthWriteTransparentMeshes=e,this._depthRenderer&&(this._depthRenderer.forceDepthWriteTransparentMeshes=e))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"inputTextureColorIsInGammaSpace",{get:function(){return this._inputTextureColorIsInGammaSpace},set:function(e){this._inputTextureColorIsInGammaSpace!==e&&(this._inputTextureColorIsInGammaSpace=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"generateOutputInGammaSpace",{get:function(){return this._generateOutputInGammaSpace},set:function(e){this._generateOutputInGammaSpace!==e&&(this._generateOutputInGammaSpace=e,this._buildPipeline())},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"debug",{get:function(){return this._debug},set:function(e){this._debug!==e&&(this._debug=e,this._buildPipeline())},enumerable:!1,configurable:!0}),t.prototype.getScene=function(){return this._scene},Object.defineProperty(t.prototype,"_geometryBufferRenderer",{get:function(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_prePassRenderer",{get:function(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scene",{get:function(){return this._scene},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isSupported",{get:function(){var e=this._scene.getEngine().getCaps();return e.drawBuffersExtension&&e.texelFetch},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"SSRRenderingPipeline"},t.prototype.addCamera=function(e){this._camerasToBeAttached.push(e),this._buildPipeline()},t.prototype.removeCamera=function(e){var t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()},t.prototype.dispose=function(t){void 0===t&&(t=!1),this._disposeDepthRenderer(),this._disposePostProcesses(),t&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),e.prototype.dispose.call(this)},t.prototype._getTextureSize=function(){var e,t,i=this._scene.getEngine(),r=this._prePassRenderer,n={width:i.getRenderWidth(),height:i.getRenderHeight()};if(r&&(null===(e=this._scene.activeCamera)||void 0===e?void 0:e._getFirstPostProcess())===this._ssrPostProcess){var o=r.getRenderTarget();o&&o.textures&&(n=o.textures[r.getIndex(u.PREPASS_COLOR_TEXTURE_TYPE)].getSize())}else(null===(t=this._ssrPostProcess)||void 0===t?void 0:t.inputTexture)&&(n.width=this._ssrPostProcess.inputTexture.width,n.height=this._ssrPostProcess.inputTexture.height);return n},t.prototype._updateEffectDefines=function(){var e,t,i,r,n,o,a=[];(this._geometryBufferRenderer||this._prePassRenderer)&&a.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&a.push("#define SSRAYTRACE_ENABLE_REFINEMENT"),this._scene.useRightHandedSystem&&a.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"),this._environmentTexture&&(a.push("#define SSR_USE_ENVIRONMENT_CUBE"),this._environmentTexture.boundingBoxSize&&a.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"),this._environmentTexture.gammaSpace&&a.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE")),this._environmentTextureIsProbe&&a.push("#define SSR_INVERTCUBICMAP"),this._enableAutomaticThicknessComputation&&a.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"),this._attenuateScreenBorders&&a.push("#define SSR_ATTENUATE_SCREEN_BORDERS"),this._attenuateIntersectionDistance&&a.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"),this._attenuateIntersectionIterations&&a.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"),this._attenuateFacingCamera&&a.push("#define SSR_ATTENUATE_FACING_CAMERA"),this._attenuateBackfaceReflection&&a.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"),this._clipToFrustum&&a.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"),this._useBlur()&&a.push("#define SSR_USE_BLUR"),this._debug&&a.push("#define SSRAYTRACE_DEBUG"),this._inputTextureColorIsInGammaSpace&&a.push("#define SSR_INPUT_IS_GAMMA_SPACE"),this._generateOutputInGammaSpace&&a.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"),this._useFresnel&&a.push("#define SSR_BLEND_WITH_FRESNEL"),0===this._reflectivityThreshold&&a.push("#define SSR_DISABLE_REFLECTIVITY_TEST"),(null!==(t=null===(e=this._geometryBufferRenderer)||void 0===e?void 0:e.generateNormalsInWorldSpace)&&void 0!==t?t:null===(i=this._prePassRenderer)||void 0===i?void 0:i.generateNormalsInWorldSpace)&&a.push("#define SSR_NORMAL_IS_IN_WORLDSPACE"),(null===(r=this._geometryBufferRenderer)||void 0===r?void 0:r.normalsAreUnsigned)&&a.push("#define SSR_DECODE_NORMAL");var s=null===(n=this._cameras)||void 0===n?void 0:n[0];s&&s.mode===u.ORTHOGRAPHIC_CAMERA&&a.push("#define ORTHOGRAPHIC_CAMERA"),null===(o=this._ssrPostProcess)||void 0===o||o.updateEffect(a.join("\n"))},t.prototype._buildPipeline=function(){var e,t=this;if(this.isSupported)if(this._isEnabled){this._isDirty=!1;var i=this._scene.getEngine();if(this._disposeDepthRenderer(),this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._enableAutomaticThicknessComputation){var r=null===(e=this._cameras)||void 0===e?void 0:e[0];r&&(this._depthRendererCamera=r,this._depthRenderer=new pv(this._scene,void 0,void 0,void 0,u.TEXTURE_NEAREST_SAMPLINGMODE,!0,"SSRBackDepth"),this._depthRenderer.clearColor.r=1e8,this._depthRenderer.reverseCulling=!0,this._depthRenderer.forceDepthWriteTransparentMeshes=this._backfaceForceDepthWriteTransparentMeshes,this._resizeDepthRenderer(),r.customRenderTargets.push(this._depthRenderer.getDepthMap()))}this._createSSRPostProcess(),this.addEffect(new vC(i,this.SSRRenderEffect,(function(){return t._ssrPostProcess}),!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new vC(i,this.SSRBlurRenderEffect,(function(){return[t._blurPostProcessX,t._blurPostProcessY]}),!0)),this.addEffect(new vC(i,this.SSRCombineRenderEffect,(function(){return t._blurCombinerPostProcess}),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}else this._isDirty=!0},t.prototype._resizeDepthRenderer=function(){if(this._depthRenderer){var e=this._getTextureSize(),t=this._depthRenderer.getDepthMap().getSize(),i=Math.floor(e.width/(this._backfaceDepthTextureDownsample+1)),r=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));t.width===i&&t.height===r||this._depthRenderer.getDepthMap().resize({width:i,height:r})}},t.prototype._disposeDepthRenderer=function(){var e;if(this._depthRenderer){if(this._depthRendererCamera){var t=null!==(e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap()))&&void 0!==e?e:-1;-1!==t&&this._depthRendererCamera.customRenderTargets.splice(t,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null},t.prototype._disposePostProcesses=function(){for(var e,t,i,r,n=0;n<this._cameras.length;n++){var o=this._cameras[n];null===(e=this._ssrPostProcess)||void 0===e||e.dispose(o),null===(t=this._blurPostProcessX)||void 0===t||t.dispose(o),null===(i=this._blurPostProcessY)||void 0===i||i.dispose(o),null===(r=this._blurCombinerPostProcess)||void 0===r||r.dispose(o)}this._ssrPostProcess=null,this._blurPostProcessX=null,this._blurPostProcessY=null,this._blurCombinerPostProcess=null},t.prototype._createSSRPostProcess=function(){var e=this;this._ssrPostProcess=new hl("ssr","screenSpaceReflection2",["projection","invProjectionMatrix","view","invView","thickness","reflectionSpecularFalloffExponent","strength","stepSize","maxSteps","roughnessFactor","projectionPixel","nearPlaneZ","maxDistance","selfCollisionNumSkip","vReflectionPosition","vReflectionSize","backSizeFactor","reflectivityThreshold"],["textureSampler","normalSampler","reflectivitySampler","depthSampler","envCubeSampler","backDepthSampler"],1,null,this._textureType,this._scene.getEngine(),!1,"",this._textureType),this._updateEffectDefines(),this._ssrPostProcess.onApply=function(t){e._resizeDepthRenderer();var i=e._geometryBufferRenderer,r=e._prePassRenderer;if(r||i){if(i){var n=i.getTextureIndex(BC.REFLECTIVITY_TEXTURE_TYPE);t.setTexture("normalSampler",i.getGBuffer().textures[1]),t.setTexture("reflectivitySampler",i.getGBuffer().textures[n]),t.setTexture("depthSampler",i.getGBuffer().textures[0])}else if(r){var o=r.getIndex(u.PREPASS_DEPTH_TEXTURE_TYPE),a=(n=r.getIndex(u.PREPASS_REFLECTIVITY_TEXTURE_TYPE),r.getIndex(u.PREPASS_NORMAL_TEXTURE_TYPE));t.setTexture("normalSampler",r.getRenderTarget().textures[a]),t.setTexture("depthSampler",r.getRenderTarget().textures[o]),t.setTexture("reflectivitySampler",r.getRenderTarget().textures[n])}e._enableAutomaticThicknessComputation&&e._depthRenderer&&(t.setTexture("backDepthSampler",e._depthRenderer.getDepthMap()),t.setFloat("backSizeFactor",e._backfaceDepthTextureDownsample+1));var s=e._scene.activeCamera;if(s){var l=s.getViewMatrix(),c=s.getProjectionMatrix();c.invertToRef(H.Matrix[0]),l.invertToRef(H.Matrix[1]),t.setMatrix("projection",c),t.setMatrix("view",l),t.setMatrix("invView",H.Matrix[1]),t.setMatrix("invProjectionMatrix",H.Matrix[0]),t.setFloat("thickness",e.thickness),t.setFloat("reflectionSpecularFalloffExponent",e.reflectionSpecularFalloffExponent),t.setFloat("strength",e.strength),t.setFloat("stepSize",e.step),t.setFloat("maxSteps",e.maxSteps),t.setFloat("roughnessFactor",e.roughnessFactor),t.setFloat("nearPlaneZ",s.minZ),t.setFloat("maxDistance",e.maxDistance),t.setFloat("selfCollisionNumSkip",e.selfCollisionNumSkip),t.setFloat("reflectivityThreshold",e._reflectivityThreshold);var h=e._getTextureSize();z.ScalingToRef(h.width,h.height,1,H.Matrix[2]),c.multiplyToRef(e._scene.getEngine().isWebGPU?iR:tR,H.Matrix[3]),H.Matrix[3].multiplyToRef(H.Matrix[2],H.Matrix[4]),t.setMatrix("projectionPixel",H.Matrix[4]),e._environmentTexture&&(t.setTexture("envCubeSampler",e._environmentTexture),e._environmentTexture.boundingBoxSize&&(t.setVector3("vReflectionPosition",e._environmentTexture.boundingBoxPosition),t.setVector3("vReflectionSize",e._environmentTexture.boundingBoxSize)))}}},this._ssrPostProcess.samples=this.samples,this._forceGeometryBuffer||(this._ssrPostProcess._prePassEffectConfiguration=new eR)},t.prototype._createBlurAndCombinerPostProcesses=function(){var e=this,t=this._scene.getEngine();this._blurPostProcessX=new hl("SSRblurX","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._ssrDownsample+1):1,null,u.TEXTURE_BILINEAR_SAMPLINGMODE,t,!1,"",this._textureType),this._blurPostProcessX.autoClear=!1,this._blurPostProcessX.onApplyObservable.add((function(t){var i,r,n=null!==(r=null===(i=e._blurPostProcessX)||void 0===i?void 0:i.inputTexture.width)&&void 0!==r?r:e._scene.getEngine().getRenderWidth();t.setFloat2("texelOffsetScale",e._blurDispersionStrength/n,0)})),this._blurPostProcessY=new hl("SSRblurY","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._blurDownsample+1):1,null,u.TEXTURE_BILINEAR_SAMPLINGMODE,t,!1,"",this._textureType),this._blurPostProcessY.autoClear=!1,this._blurPostProcessY.onApplyObservable.add((function(t){var i,r,n=null!==(r=null===(i=e._blurPostProcessY)||void 0===i?void 0:i.inputTexture.height)&&void 0!==r?r:e._scene.getEngine().getRenderHeight();t.setFloat2("texelOffsetScale",0,e._blurDispersionStrength/n)}));var i=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],r=["textureSampler","mainSampler","reflectivitySampler"],n="";this._debug&&(n+="#define SSRAYTRACE_DEBUG\n"),this._inputTextureColorIsInGammaSpace&&(n+="#define SSR_INPUT_IS_GAMMA_SPACE\n"),this._generateOutputInGammaSpace&&(n+="#define SSR_OUTPUT_IS_GAMMA_SPACE\n"),this.useFresnel&&(n+="#define SSR_BLEND_WITH_FRESNEL\n",i.push("projection","invProjectionMatrix"),r.push("depthSampler","normalSampler")),0===this._reflectivityThreshold&&(n+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new hl("SSRblurCombiner","screenSpaceReflection2BlurCombiner",i,r,this._useBlur()?1/(this._blurDownsample+1):1,null,u.TEXTURE_NEAREST_SAMPLINGMODE,t,!1,n,this._textureType),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add((function(t){var i,r=e._geometryBufferRenderer,n=e._prePassRenderer;if(n||r){if(n&&(null===(i=e._scene.activeCamera)||void 0===i?void 0:i._getFirstPostProcess())===e._ssrPostProcess){var o=n.getRenderTarget();o&&o.textures&&t.setTexture("mainSampler",o.textures[n.getIndex(u.PREPASS_COLOR_TEXTURE_TYPE)])}else t.setTextureFromPostProcess("mainSampler",e._ssrPostProcess);if(r){var a=r.getTextureIndex(BC.REFLECTIVITY_TEXTURE_TYPE);t.setTexture("reflectivitySampler",r.getGBuffer().textures[a]),e.useFresnel&&(t.setTexture("normalSampler",r.getGBuffer().textures[1]),t.setTexture("depthSampler",r.getGBuffer().textures[0]))}else if(n&&(a=n.getIndex(u.PREPASS_REFLECTIVITY_TEXTURE_TYPE),t.setTexture("reflectivitySampler",n.getRenderTarget().textures[a]),e.useFresnel)){var s=n.getIndex(u.PREPASS_DEPTH_TEXTURE_TYPE),l=n.getIndex(u.PREPASS_NORMAL_TEXTURE_TYPE);t.setTexture("normalSampler",n.getRenderTarget().textures[l]),t.setTexture("depthSampler",n.getRenderTarget().textures[s])}if(t.setFloat("strength",e.strength),t.setFloat("reflectionSpecularFalloffExponent",e.reflectionSpecularFalloffExponent),t.setFloat("reflectivityThreshold",e._reflectivityThreshold),e.useFresnel){var c=e._scene.activeCamera;if(c){var h=c.getProjectionMatrix();h.invertToRef(H.Matrix[0]),t.setMatrix("projection",h),t.setMatrix("invProjectionMatrix",H.Matrix[0])}}}}))},t.prototype.serialize=function(){var e=Ke.Serialize(this);return e.customType="SSRRenderingPipeline",e},t.Parse=function(e,i,r){return Ke.Parse((function(){return new t(e._name,i,e._ratio)}),e,i,r)},v([Ie()],t.prototype,"samples",null),v([Ie()],t.prototype,"maxDistance",void 0),v([Ie()],t.prototype,"step",void 0),v([Ie()],t.prototype,"thickness",void 0),v([Ie()],t.prototype,"strength",void 0),v([Ie()],t.prototype,"reflectionSpecularFalloffExponent",void 0),v([Ie()],t.prototype,"maxSteps",void 0),v([Ie()],t.prototype,"roughnessFactor",void 0),v([Ie()],t.prototype,"selfCollisionNumSkip",void 0),v([Ie()],t.prototype,"_reflectivityThreshold",void 0),v([Ie("_ssrDownsample")],t.prototype,"_ssrDownsample",void 0),v([Ie()],t.prototype,"ssrDownsample",null),v([Ie("blurDispersionStrength")],t.prototype,"_blurDispersionStrength",void 0),v([Ie("blurDownsample")],t.prototype,"_blurDownsample",void 0),v([Ie("enableSmoothReflections")],t.prototype,"_enableSmoothReflections",void 0),v([Ie("environmentTexture")],t.prototype,"_environmentTexture",void 0),v([Ie("environmentTextureIsProbe")],t.prototype,"_environmentTextureIsProbe",void 0),v([Ie("attenuateScreenBorders")],t.prototype,"_attenuateScreenBorders",void 0),v([Ie("attenuateIntersectionDistance")],t.prototype,"_attenuateIntersectionDistance",void 0),v([Ie("attenuateIntersectionIterations")],t.prototype,"_attenuateIntersectionIterations",void 0),v([Ie("attenuateFacingCamera")],t.prototype,"_attenuateFacingCamera",void 0),v([Ie("attenuateBackfaceReflection")],t.prototype,"_attenuateBackfaceReflection",void 0),v([Ie("clipToFrustum")],t.prototype,"_clipToFrustum",void 0),v([Ie("useFresnel")],t.prototype,"_useFresnel",void 0),v([Ie("enableAutomaticThicknessComputation")],t.prototype,"_enableAutomaticThicknessComputation",void 0),v([Ie("backfaceDepthTextureDownsample")],t.prototype,"_backfaceDepthTextureDownsample",void 0),v([Ie("backfaceForceDepthWriteTransparentMeshes")],t.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0),v([Ie("isEnabled")],t.prototype,"_isEnabled",void 0),v([Ie("inputTextureColorIsInGammaSpace")],t.prototype,"_inputTextureColorIsInGammaSpace",void 0),v([Ie("generateOutputInGammaSpace")],t.prototype,"_generateOutputInGammaSpace",void 0),v([Ie("debug")],t.prototype,"_debug",void 0),t}(WC);a("BABYLON.SSRRenderingPipeline",rR);li.ShadersStore.taaPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D historySampler;uniform float factor;void main() {vec4 c=texelFetch(textureSampler,ivec2(gl_FragCoord.xy),0);vec4 h=texelFetch(historySampler,ivec2(gl_FragCoord.xy),0);gl_FragColor=mix(h,c,factor);}\n";var nR=function(e){function t(t,i,r,n){void 0===n&&(n=u.TEXTURETYPE_UNSIGNED_BYTE);var o=this,a=i.getEngine();return(o=e.call(this,a,t)||this).TAARenderEffect="TAARenderEffect",o.TAAPassEffect="TAAPassEffect",o._samples=8,o._msaaSamples=1,o.factor=.05,o.disableOnCameraMove=!0,o._isEnabled=!0,o._isDirty=!1,o._camerasToBeAttached=[],o._pingpong=0,o._firstUpdate=!0,o._cameras=r||i.cameras,o._cameras=o._cameras.slice(),o._camerasToBeAttached=o._cameras.slice(),o._scene=i,o._textureType=n,o._hs=new cE(o.samples),o.isSupported&&(o._createPingPongTextures(a.getRenderWidth(),a.getRenderHeight()),i.postProcessRenderPipelineManager.addPipeline(o),o._buildPipeline()),o}return m(t,e),Object.defineProperty(t.prototype,"samples",{get:function(){return this._samples},set:function(e){this._samples!==e&&(this._samples=e,this._hs.regenerate(e))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"msaaSamples",{get:function(){return this._msaaSamples},set:function(e){this._msaaSamples!==e&&(this._msaaSamples=e,this._taaPostProcess&&(this._taaPostProcess.samples=e))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&(this._firstUpdate=!0,this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras))):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"scene",{get:function(){return this._scene},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isSupported",{get:function(){return this._scene.getEngine().getCaps().texelFetch},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"TAARenderingPipeline"},t.prototype.addCamera=function(e){this._camerasToBeAttached.push(e),this._buildPipeline()},t.prototype.removeCamera=function(e){var t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()},t.prototype.dispose=function(){this._disposePostProcesses(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._ping.dispose(),this._pong.dispose(),e.prototype.dispose.call(this)},t.prototype._createPingPongTextures=function(e,t){var i,r,n=this._scene.getEngine();null===(i=this._ping)||void 0===i||i.dispose(),null===(r=this._pong)||void 0===r||r.dispose(),this._ping=n.createRenderTargetTexture({width:e,height:t},{generateMipMaps:!1,generateDepthBuffer:!1,type:u.TEXTURETYPE_HALF_FLOAT,samplingMode:u.TEXTURE_NEAREST_NEAREST}),this._pong=n.createRenderTargetTexture({width:e,height:t},{generateMipMaps:!1,generateDepthBuffer:!1,type:u.TEXTURETYPE_HALF_FLOAT,samplingMode:u.TEXTURE_NEAREST_NEAREST}),this._hs.setDimensions(e/2,t/2),this._firstUpdate=!0},t.prototype._updateEffectDefines=function(){var e;null===(e=this._taaPostProcess)||void 0===e||e.updateEffect([].join("\n"))},t.prototype._buildPipeline=function(){var e=this;if(this.isSupported)if(this._isEnabled){this._isDirty=!1;var t=this._scene.getEngine();this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._createTAAPostProcess(),this.addEffect(new vC(t,this.TAARenderEffect,(function(){return e._taaPostProcess}),!0)),this._createPassPostProcess(),this.addEffect(new vC(t,this.TAAPassEffect,(function(){return e._passPostProcess}),!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}else this._isDirty=!0},t.prototype._disposePostProcesses=function(){for(var e,t,i=0;i<this._cameras.length;i++){var r=this._cameras[i];null===(e=this._taaPostProcess)||void 0===e||e.dispose(r),null===(t=this._passPostProcess)||void 0===t||t.dispose(r),r.getProjectionMatrix(!0)}this._taaPostProcess=null,this._passPostProcess=null},t.prototype._createTAAPostProcess=function(){var e=this;this._taaPostProcess=new hl("TAA","taa",{uniforms:["factor"],samplers:["historySampler"],size:1,engine:this._scene.getEngine(),textureType:this._textureType}),this._taaPostProcess.samples=this._msaaSamples,this._updateEffectDefines(),this._taaPostProcess.onActivateObservable.add((function(){var t,i,r,n=e._scene.activeCamera;if((null===(t=e._taaPostProcess)||void 0===t?void 0:t.width)!==e._ping.width||(null===(i=e._taaPostProcess)||void 0===i?void 0:i.height)!==e._ping.height){var o=e._scene.getEngine();e._createPingPongTextures(o.getRenderWidth(),o.getRenderHeight())}n&&!n.hasMoved&&(n.mode===$n.PERSPECTIVE_CAMERA?(r=n.getProjectionMatrix()).setRowFromFloats(2,e._hs.x,e._hs.y,r.m[10],r.m[11]):(r=n.getProjectionMatrix(!0)).setRowFromFloats(3,e._hs.x+r.m[12],e._hs.y+r.m[13],r.m[14],r.m[15])),e._passPostProcess&&(e._passPostProcess.inputTexture=e._pingpong?e._ping:e._pong),e._pingpong=1^e._pingpong,e._hs.next()})),this._taaPostProcess.onApplyObservable.add((function(t){var i=e._scene.activeCamera;t._bindTexture("historySampler",e._pingpong?e._ping.texture:e._pong.texture),t.setFloat("factor",(null==i?void 0:i.hasMoved)&&e.disableOnCameraMove||e._firstUpdate?1:e.factor),e._firstUpdate=!1}))},t.prototype._createPassPostProcess=function(){var e=this._scene.getEngine();this._passPostProcess=new qc("TAAPass",1,null,u.TEXTURE_NEAREST_NEAREST,e),this._passPostProcess.inputTexture=this._ping,this._passPostProcess.autoClear=!1},t.prototype.serialize=function(){var e=Ke.Serialize(this);return e.customType="TAARenderingPipeline",e},t.Parse=function(e,i,r){return Ke.Parse((function(){return new t(e._name,i,e._ratio)}),e,i,r)},v([Ie("samples")],t.prototype,"_samples",void 0),v([Ie("msaaSamples")],t.prototype,"_msaaSamples",void 0),v([Ie()],t.prototype,"factor",void 0),v([Ie()],t.prototype,"disableOnCameraMove",void 0),v([Ie("isEnabled")],t.prototype,"_isEnabled",void 0),t}(WC);a("BABYLON.TAARenderingPipeline",nR);var oR;li.ShadersStore.tonemapPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst 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;\n#endif\nfloat Luminance(vec3 c)\n{return dot(c,vec3(0.22,0.707,0.071));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;const float ExposureBias=2.0;vec3 x=ExposureBias*colour;vec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x=vec3(W,W,W);vec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);}",function(e){e[e.Hable=0]="Hable",e[e.Reinhard=1]="Reinhard",e[e.HejiDawson=2]="HejiDawson",e[e.Photographic=3]="Photographic"}(oR||(oR={}));var aR=function(e){function t(t,i,r,n,o,a,s,l){void 0===o&&(o=u.TEXTURE_BILINEAR_SAMPLINGMODE),void 0===s&&(s=u.TEXTURETYPE_UNSIGNED_INT);var c=e.call(this,t,"tonemap",["_ExposureAdjustment"],null,1,n,o,a,l,null,s)||this;c._operator=i,c.exposureAdjustment=r;var h="#define ";return c._operator===oR.Hable?h+="HABLE_TONEMAPPING":c._operator===oR.Reinhard?h+="REINHARD_TONEMAPPING":c._operator===oR.HejiDawson?h+="OPTIMIZED_HEJIDAWSON_TONEMAPPING":c._operator===oR.Photographic&&(h+="PHOTOGRAPHIC_TONEMAPPING"),c.updateEffect(h),c.onApply=function(e){e.setFloat("_ExposureAdjustment",c.exposureAdjustment)},c}return m(t,e),t.prototype.getClassName=function(){return"TonemapPostProcess"},t}(hl);li.ShadersStore.volumetricLightScatteringPixelShader="uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i<NUM_SAMPLES; i++) {tc-=deltaTexCoord;vec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;dataSample*=illuminationDecay*weight;color+=dataSample;illuminationDecay*=decay;}\nvec4 realColor=texture2D(textureSampler,vUV);gl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";li.ShadersStore.volumetricLightScatteringPassVertexShader="attribute vec3 position;\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#include<instancesDeclaration>\nuniform mat4 viewProjection;uniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV1)\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertexGlobal>\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n";li.ShadersStore.volumetricLightScatteringPassPixelShader="#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);if (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);}\n";var sR=function(e){function t(i,r,n,o,a,s,l,c,u){void 0===a&&(a=100),void 0===s&&(s=Ja.BILINEAR_SAMPLINGMODE);var h,d,p=this;return(p=e.call(this,i,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],r.postProcessRatio||r,n,s,l,c,"#define NUM_SAMPLES "+a)||this)._screenCoordinates=U.Zero(),p.customMeshPosition=V.Zero(),p.useCustomMeshPosition=!1,p.invert=!0,p.excludedMeshes=[],p.includedMeshes=[],p.exposure=.3,p.decay=.96815,p.weight=.58767,p.density=.926,l=(u=null!==(d=null!==(h=null==n?void 0:n.getScene())&&void 0!==h?h:u)&&void 0!==d?d:p._scene).getEngine(),p._viewPort=new Jn(0,0,1,1).toGlobal(l.getRenderWidth(),l.getRenderHeight()),p.mesh=null!=o?o:t.CreateDefaultMesh("VolumetricLightScatteringMesh",u),p._createPass(u,r.passRatio||r),p.onActivate=function(e){p.isSupported||p.dispose(e),p.onActivate=null},p.onApplyObservable.add((function(e){p._updateMeshScreenCoordinates(u),e.setTexture("lightScatteringSampler",p._volumetricLightScatteringRTT),e.setFloat("exposure",p.exposure),e.setFloat("decay",p.decay),e.setFloat("weight",p.weight),e.setFloat("density",p.density),e.setVector2("meshPositionOnScreen",p._screenCoordinates)})),p}return m(t,e),Object.defineProperty(t.prototype,"useDiffuseColor",{get:function(){return ae.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1},set:function(e){ae.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"VolumetricLightScatteringPostProcess"},t.prototype._isReady=function(e,t){var i,r=e.getMesh();if(r===this.mesh&&r.material)return r.material.isReady(r);var n=null===(i=r._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[this._scene.getEngine().currentRenderPassId];if(n)return n.isReadyForSubMesh(r,e,t);var o=[],a=[Nr.PositionKind],s=e.getMaterial();s&&(s.needAlphaTesting()&&o.push("#define ALPHATEST"),r.isVerticesDataPresent(Nr.UVKind)&&(a.push(Nr.UVKind),o.push("#define UV1")),r.isVerticesDataPresent(Nr.UV2Kind)&&(a.push(Nr.UV2Kind),o.push("#define UV2"))),r.useBones&&r.computeBonesUsingShaders?(a.push(Nr.MatricesIndicesKind),a.push(Nr.MatricesWeightsKind),o.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),o.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0))):o.push("#define NUM_BONE_INFLUENCERS 0"),t&&(o.push("#define INSTANCES"),Jo(a),e.getRenderingMesh().hasThinInstances&&o.push("#define THIN_INSTANCES"));var l=e._getDrawWrapper(void 0,!0),c=l.defines,u=o.join("\n");return c!==u&&l.setEffect(r.getScene().getEngine().createEffect("volumetricLightScatteringPass",a,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],u,void 0,void 0,void 0,{maxSimultaneousMorphTargets:r.numBoneInfluencers}),u),l.effect.isReady()},t.prototype.setCustomMeshPosition=function(e){this.customMeshPosition=e},t.prototype.getCustomMeshPosition=function(){return this.customMeshPosition},t.prototype.dispose=function(t){var i=t.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);-1!==i&&t.getScene().customRenderTargets.splice(i,1),this._volumetricLightScatteringRTT.dispose(),e.prototype.dispose.call(this,t)},t.prototype.getPass=function(){return this._volumetricLightScatteringRTT},t.prototype._meshExcluded=function(e){return this.includedMeshes.length>0&&-1===this.includedMeshes.indexOf(e)||this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)},t.prototype._createPass=function(e,t){var i=this,r=e.getEngine();this._volumetricLightScatteringRTT=new Pl("volumetricLightScatteringMap",{width:r.getRenderWidth()*t,height:r.getRenderHeight()*t},e,!1,!0,u.TEXTURETYPE_UNSIGNED_INT),this._volumetricLightScatteringRTT.wrapU=Ja.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=Ja.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;var n=this.getCamera();n?n.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);var o,a=function(e){var t,r=e.getRenderingMesh(),n=e.getEffectiveMesh();if(!i._meshExcluded(r)){n._internalAbstractMeshDataInfo._isActiveIntermediate=!1;var o=e.getMaterial();if(o){var a=r.getScene(),s=a.getEngine();s.setState(o.backFaceCulling,void 0,void 0,void 0,o.cullBackFaces);var l=r._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(!l.mustReturn){var c=s.getCaps().instancedArrays&&(null!==l.visibleInstances[e._id]||r.hasThinInstances);if(i._isReady(e,c)){var u=null===(t=n._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===t?void 0:t[s.currentRenderPassId],h=e._getDrawWrapper();if(r!==i.mesh||h||(h=o._getDrawWrapper()),!h)return;var d=h.effect;if(s.enableEffect(h),c||r._bind(e,d,o.fillMode),r===i.mesh)o.bind(n.getWorldMatrix(),r);else if(u)u.bindForSubMesh(n.getWorldMatrix(),n,e);else{if(d.setMatrix("viewProjection",a.getTransformMatrix()),o&&o.needAlphaTesting()){var p=o.getAlphaTestTexture();d.setTexture("diffuseSampler",p),p&&d.setMatrix("diffuseMatrix",p.getTextureMatrix())}r.useBones&&r.computeBonesUsingShaders&&r.skeleton&&d.setMatrices("mBones",r.skeleton.getTransformMatrices(r))}c&&r.hasThinInstances&&d.setMatrix("world",n.getWorldMatrix()),r._processRendering(n,e,d,Ca.TriangleFillMode,l,c,(function(e,t){e||d.setMatrix("world",t)}))}}}}},s=new J(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add((function(){o=e.clearColor,e.clearColor=s})),this._volumetricLightScatteringRTT.onAfterRenderObservable.add((function(){e.clearColor=o})),this._volumetricLightScatteringRTT.customIsReadyFunction=function(e,t,n){if((n||0===t)&&e.subMeshes)for(var o=0;o<e.subMeshes.length;++o){var a=e.subMeshes[o],s=a.getMaterial(),l=a.getRenderingMesh();if(s){var c=l._getInstancesRenderList(a._id,!!a.getReplacementMesh()),u=r.getCaps().instancedArrays&&(null!==c.visibleInstances[a._id]||l.hasThinInstances);if(!i._isReady(a,u))return!1}}return!0},this._volumetricLightScatteringRTT.customRenderFunction=function(t,i,r,n){var o,s=e.getEngine();if(n.length){for(s.setColorWrite(!1),o=0;o<n.length;o++)a(n.data[o]);s.setColorWrite(!0)}for(o=0;o<t.length;o++)a(t.data[o]);for(o=0;o<i.length;o++)a(i.data[o]);if(r.length){for(o=0;o<r.length;o++){var l=r.data[o],c=l.getBoundingInfo();c&&e.activeCamera&&(l._alphaIndex=l.getMesh().alphaIndex,l._distanceToCamera=c.boundingSphere.centerWorld.subtract(e.activeCamera.position).length())}var h=r.data.slice(0,r.length);for(h.sort((function(e,t){return e._alphaIndex>t._alphaIndex?1:e._alphaIndex<t._alphaIndex?-1:e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0})),s.setAlphaMode(u.ALPHA_COMBINE),o=0;o<h.length;o++)a(h[o]);s.setAlphaMode(u.ALPHA_DISABLE)}}},t.prototype._updateMeshScreenCoordinates=function(e){var t,i=e.getTransformMatrix();t=this.useCustomMeshPosition?this.customMeshPosition:this.attachedNode?this.attachedNode.position:this.mesh.parent?this.mesh.getAbsolutePosition():this.mesh.position;var r=V.Project(t,z.Identity(),i,this._viewPort);this._screenCoordinates.x=r.x/this._viewPort.width,this._screenCoordinates.y=r.y/this._viewPort.height,this.invert&&(this._screenCoordinates.y=1-this._screenCoordinates.y)},t.CreateDefaultMesh=function(e,t){var i=fs(e,{size:1},t);i.billboardMode=Uo.BILLBOARDMODE_ALL;var r=new Uu(e+"Material",t);return r.emissiveColor=new Z(1,1,1),i.material=r,i},v([Fe()],t.prototype,"customMeshPosition",void 0),v([Ie()],t.prototype,"useCustomMeshPosition",void 0),v([Ie()],t.prototype,"invert",void 0),v([Le()],t.prototype,"mesh",void 0),v([Ie()],t.prototype,"excludedMeshes",void 0),v([Ie()],t.prototype,"includedMeshes",void 0),v([Ie()],t.prototype,"exposure",void 0),v([Ie()],t.prototype,"decay",void 0),v([Ie()],t.prototype,"weight",void 0),v([Ie()],t.prototype,"density",void 0),t}(hl);a("BABYLON.VolumetricLightScatteringPostProcess",sR);li.ShadersStore.screenSpaceCurvaturePixelShader="precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform float curvature_ridge;uniform float curvature_valley;\n#ifndef CURVATURE_OFFSET\n#define CURVATURE_OFFSET 1\n#endif\nfloat curvature_soft_clamp(float curvature,float control)\n{if (curvature<0.5/control)\nreturn curvature*(1.0-curvature*control);return 0.25/control;}\nfloat calculate_curvature(ivec2 texel,float ridge,float valley)\n{vec2 normal_up =texelFetch(normalSampler,texel+ivec2(0, CURVATURE_OFFSET),0).rb;vec2 normal_down =texelFetch(normalSampler,texel+ivec2(0,-CURVATURE_OFFSET),0).rb;vec2 normal_left =texelFetch(normalSampler,texel+ivec2(-CURVATURE_OFFSET,0),0).rb;vec2 normal_right=texelFetch(normalSampler,texel+ivec2( CURVATURE_OFFSET,0),0).rb;float normal_diff=((normal_up.g-normal_down.g)+(normal_right.r-normal_left.r));if (normal_diff<0.0)\nreturn -2.0*curvature_soft_clamp(-normal_diff,valley);return 2.0*curvature_soft_clamp(normal_diff,ridge);}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{ivec2 texel=ivec2(gl_FragCoord.xy);vec4 baseColor=texture2D(textureSampler,vUV);float curvature=calculate_curvature(texel,curvature_ridge,curvature_valley);baseColor.rgb*=curvature+1.0;gl_FragColor=baseColor;}";var lR=function(e){function t(t,i,r,n,o,a,s,l,c){void 0===l&&(l=u.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=!1);var h=e.call(this,t,"screenSpaceCurvature",["curvature_ridge","curvature_valley"],["textureSampler","normalSampler"],r,n,o,a,s,void 0,l,void 0,null,c)||this;return h.ridge=1,h.valley=1,h._geometryBufferRenderer=i.enableGeometryBufferRenderer(),h._geometryBufferRenderer?(h._geometryBufferRenderer.generateNormalsInWorldSpace&&ae.Error("ScreenSpaceCurvaturePostProcess does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!"),h.onApply=function(e){e.setFloat("curvature_ridge",.5/Math.max(h.ridge*h.ridge,1e-4)),e.setFloat("curvature_valley",.7/Math.max(h.valley*h.valley,1e-4));var t=h._geometryBufferRenderer.getGBuffer().textures[1];e.setTexture("normalSampler",t)}):ae.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first."),h}return m(t,e),t.prototype.getClassName=function(){return"ScreenSpaceCurvaturePostProcess"},Object.defineProperty(t,"IsSupported",{get:function(){var e=M.LastCreatedEngine;return!!e&&e.getCaps().drawBuffersExtension},enumerable:!1,configurable:!0}),t._Parse=function(e,i,r,n){return Ke.Parse((function(){return new t(e.name,r,e.options,i,e.renderTargetSamplingMode,r.getEngine(),e.textureType,e.reusable)}),e,r,n)},v([Ie()],t.prototype,"ridge",void 0),v([Ie()],t.prototype,"valley",void 0),t}(hl);a("BABYLON.ScreenSpaceCurvaturePostProcess",lR);li.IncludesShadersStore.boundingBoxRendererFragmentDeclaration="uniform vec4 color;\n";li.IncludesShadersStore.boundingBoxRendererUboDeclaration="#ifdef WEBGL2\nuniform vec4 color;uniform mat4 world;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#else\nlayout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;};\n#endif\n";li.ShadersStore.boundingBoxRendererPixelShader="#include<__decl__boundingBoxRendererFragment>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";li.IncludesShadersStore.boundingBoxRendererVertexDeclaration="uniform mat4 world;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n";li.ShadersStore.boundingBoxRendererVertexShader="attribute vec3 position;\n#include<__decl__boundingBoxRendererVertex>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec4 worldPos=world*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n",Object.defineProperty(pn.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(e){this._forceShowBoundingBoxes=e,e&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0}),pn.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new cR(this)),this._boundingBoxRenderer},Object.defineProperty(Uo.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(e){this._showBoundingBox=e,e&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});var cR=function(){function e(e){this.name=Vr.NAME_BOUNDINGBOXRENDERER,this.frontColor=new Z(1,1,1),this.backColor=new Z(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new f,this.onAfterBoxRenderingObservable=new f,this.onResourcesReadyObservable=new f,this.enabled=!0,this.renderList=new ar(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new Or(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new Or(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferBack)}return e.prototype._buildUniformLayout=function(e){e.addUniform("color",4),e.addUniform("world",16),e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.create()},e.prototype.register=function(){this.scene._beforeEvaluateActiveMeshStage.registerStep(Vr.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(Vr.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(Vr.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(Vr.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)},e.prototype._evaluateSubMesh=function(e,t){if(e.showSubMeshesBoundingBox){var i=t.getBoundingInfo();null!=i&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}},e.prototype._preActiveMesh=function(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){var t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}},e.prototype._prepareResources=function(){if(!this._colorShader){this._colorShader=new ld("colorShader",this.scene,"boundingBoxRenderer",{attributes:[Nr.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new ld("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[Nr.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};var e=this.scene.getEngine(),t=wh({size:1});this._vertexBuffers[Nr.PositionKind]=new Nr(e,t.positions,Nr.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}},e.prototype._createIndexBuffer=function(){var e=this.scene.getEngine();this._indexBuffer=e.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])},e.prototype.rebuild=function(){var e=this._vertexBuffers[Nr.PositionKind];e&&e._rebuild(),this._createIndexBuffer()},e.prototype.reset=function(){this.renderList.reset()},e.prototype.render=function(e){var t,i;if(0!==this.renderList.length&&this.enabled&&(this._prepareResources(),this._colorShader.isReady())){var r=this.scene.getEngine();r.setDepthWrite(!1);for(var n=this.scene.getTransformMatrix(),o=0;o<this.renderList.length;o++){var a=this.renderList.data[o];if(a._tag===e){this._createWrappersForBoundingBox(a),this.onBeforeBoxRenderingObservable.notifyObservers(a);var s=a.minimum,l=a.maximum.subtract(s),c=s.add(l.scale(.5)),u=z.Scaling(l.x,l.y,l.z).multiply(z.Translation(c.x,c.y,c.z)).multiply(a.getWorldMatrix()),h=r.useReverseDepthBuffer;if(this.showBackLines){var d=null!==(t=a._drawWrapperBack)&&void 0!==t?t:this._colorShader._getDrawWrapper();this._colorShader._preBind(d),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._colorShader.getEffect()),h?r.setDepthFunctionToLessOrEqual():r.setDepthFunctionToGreaterOrEqual(),this._uniformBufferBack.bindToEffect(d.effect,"BoundingBoxRenderer"),this._uniformBufferBack.updateColor4("color",this.backColor,1),this._uniformBufferBack.updateMatrix("world",u),this._uniformBufferBack.updateMatrix("viewProjection",n),this._uniformBufferBack.update(),r.drawElementsType(Ca.LineListDrawMode,0,24)}var p=null!==(i=a._drawWrapperFront)&&void 0!==i?i:this._colorShader._getDrawWrapper();this._colorShader._preBind(p),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._colorShader.getEffect()),h?r.setDepthFunctionToGreater():r.setDepthFunctionToLess(),this._uniformBufferFront.bindToEffect(p.effect,"BoundingBoxRenderer"),this._uniformBufferFront.updateColor4("color",this.frontColor,1),this._uniformBufferFront.updateMatrix("world",u),this._uniformBufferFront.updateMatrix("viewProjection",n),this._uniformBufferFront.update(),r.drawElementsType(Ca.LineListDrawMode,0,24),this.onAfterBoxRenderingObservable.notifyObservers(a)}}this._colorShader.unbind(),r.setDepthFunctionToLessOrEqual(),r.setDepthWrite(!0)}},e.prototype._createWrappersForBoundingBox=function(e){if(!e._drawWrapperFront){var t=this.scene.getEngine();e._drawWrapperFront=new ho(t),e._drawWrapperBack=new ho(t),e._drawWrapperFront.setEffect(this._colorShader.getEffect()),e._drawWrapperBack.setEffect(this._colorShader.getEffect())}},e.prototype.renderOcclusionBoundingBox=function(e){var t=this.scene.getEngine();void 0===this._renderPassIdForOcclusionQuery&&(this._renderPassIdForOcclusionQuery=t.createRenderPassId("Render pass for occlusion query"));var i=t.currentRenderPassId;t.currentRenderPassId=this._renderPassIdForOcclusionQuery,this._prepareResources();var r=e.subMeshes[0];if(this._colorShaderForOcclusionQuery.isReady(e,void 0,r)&&e.hasBoundingInfo){this._fillIndexBuffer||(this._fillIndexBuffer=t.createIndexBuffer(this._fillIndexData));var n=t.useReverseDepthBuffer;t.setDepthWrite(!1),t.setColorWrite(!1);var o=e.getBoundingInfo().boundingBox,a=o.minimum,s=o.maximum.subtract(a),l=a.add(s.scale(.5)),c=z.Scaling(s.x,s.y,s.z).multiply(z.Translation(l.x,l.y,l.z)).multiply(o.getWorldMatrix()),u=r._drawWrapper;this._colorShaderForOcclusionQuery._preBind(u),t.bindBuffers(this._vertexBuffers,this._fillIndexBuffer,u.effect),n?t.setDepthFunctionToGreater():t.setDepthFunctionToLess(),this.scene.resetCachedMaterial(),this._uniformBufferFront.bindToEffect(u.effect,"BoundingBoxRenderer"),this._uniformBufferFront.updateMatrix("world",c),this._uniformBufferFront.updateMatrix("viewProjection",this.scene.getTransformMatrix()),this._uniformBufferFront.update(),t.drawElementsType(Ca.TriangleFillMode,0,36),this._colorShaderForOcclusionQuery.unbind(),t.setDepthFunctionToLessOrEqual(),t.setDepthWrite(!0),t.setColorWrite(!0),t.currentRenderPassId=i}else t.currentRenderPassId=i},e.prototype.dispose=function(){if(void 0!==this._renderPassIdForOcclusionQuery&&(this.scene.getEngine().releaseRenderPassId(this._renderPassIdForOcclusionQuery),this._renderPassIdForOcclusionQuery=void 0),this._colorShader){this.onBeforeBoxRenderingObservable.clear(),this.onAfterBoxRenderingObservable.clear(),this.onResourcesReadyObservable.clear(),this.renderList.dispose(),this._colorShader.dispose(),this._colorShaderForOcclusionQuery.dispose(),this._uniformBufferFront.dispose(),this._uniformBufferBack.dispose();var e=this._vertexBuffers[Nr.PositionKind];e&&(e.dispose(),this._vertexBuffers[Nr.PositionKind]=null),this.scene.getEngine()._releaseBuffer(this._indexBuffer),this._fillIndexBuffer&&(this.scene.getEngine()._releaseBuffer(this._fillIndexBuffer),this._fillIndexBuffer=null)}},e}();pn.prototype.enableDepthRenderer=function(e,t,i,r,n){if(void 0===t&&(t=!1),void 0===i&&(i=!1),void 0===r&&(r=u.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===n&&(n=!1),!(e=e||this.activeCamera))throw"No camera available to enable depth renderer";if(this._depthRenderer||(this._depthRenderer={}),!this._depthRenderer[e.id]){var o,a=!!this.getEngine().getCaps().textureFloatRender;o=!this.getEngine().getCaps().textureHalfFloatRender||i&&a?a?u.TEXTURETYPE_FLOAT:u.TEXTURETYPE_UNSIGNED_BYTE:u.TEXTURETYPE_HALF_FLOAT,this._depthRenderer[e.id]=new pv(this,o,e,t,r,n)}return this._depthRenderer[e.id]},pn.prototype.disableDepthRenderer=function(e){(e=e||this.activeCamera)&&this._depthRenderer&&this._depthRenderer[e.id]&&this._depthRenderer[e.id].dispose()};var uR=function(){function e(e){this.name=Vr.NAME_DEPTHRENDERER,this.scene=e}return e.prototype.register=function(){this.scene._gatherRenderTargetsStage.registerStep(Vr.STEP_GATHERRENDERTARGETS_DEPTHRENDERER,this,this._gatherRenderTargets),this.scene._gatherActiveCameraRenderTargetsStage.registerStep(Vr.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER,this,this._gatherActiveCameraRenderTargets)},e.prototype.rebuild=function(){},e.prototype.dispose=function(){for(var e in this.scene._depthRenderer)this.scene._depthRenderer[e].dispose()},e.prototype._gatherRenderTargets=function(e){if(this.scene._depthRenderer)for(var t in this.scene._depthRenderer){var i=this.scene._depthRenderer[t];i.enabled&&!i.useOnlyInActiveCamera&&e.push(i.getDepthMap())}},e.prototype._gatherActiveCameraRenderTargets=function(e){if(this.scene._depthRenderer)for(var t in this.scene._depthRenderer){var i=this.scene._depthRenderer[t];i.enabled&&i.useOnlyInActiveCamera&&this.scene.activeCamera.id===t&&e.push(i.getDepthMap())}},e}();pv._SceneComponentInitialization=function(e){var t=e._getComponent(Vr.NAME_DEPTHRENDERER);t||(t=new uR(e),e._addComponent(t))};li.ShadersStore.oitFinalPixelShader="precision highp float;uniform sampler2D uFrontColor;uniform sampler2D uBackColor;void main() {ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec4 frontColor=texelFetch(uFrontColor,fragCoord,0);vec4 backColor=texelFetch(uBackColor,fragCoord,0);float alphaMultiplier=1.0-frontColor.a;glFragColor=vec4(\nfrontColor.rgb+alphaMultiplier*backColor.rgb,\nfrontColor.a+backColor.a\n);}";li.ShadersStore.oitBackBlendPixelShader="precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { \ndiscard;}}";var hR=function(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[u.PREPASS_COLOR_TEXTURE_TYPE]},dR=function(){function e(t,i){if(void 0===i&&(i=5),this._thinTextures=[],this._currentPingPongState=0,this._layoutCacheFormat=[[!0],[!0,!0],[!0,!0,!0]],this._layoutCache=[],this._candidateSubMeshes=new ar(10),this._excludedSubMeshes=new ar(10),this._excludedMeshes=[],this._colorCache=[new J(e._DEPTH_CLEAR_VALUE,e._DEPTH_CLEAR_VALUE,0,0),new J(-e._MIN_DEPTH,e._MAX_DEPTH,0,0),new J(0,0,0,0)],this._scene=t,this._engine=t.getEngine(),this._passCount=i,t.enablePrePassRenderer()){for(var r=0;r<this._layoutCacheFormat.length;++r)this._layoutCache[r]=this._engine.buildTextureLayout(this._layoutCacheFormat[r]);this._renderPassIds=[],this.useRenderPasses=!1,this._prePassEffectConfiguration=new hR,this._createTextures(),this._createEffects()}else ae.Warn("Depth peeling for order independant transparency could not enable PrePass, aborting.")}return Object.defineProperty(e.prototype,"passCount",{get:function(){return this._passCount},set:function(e){this._passCount!==e&&(this._passCount=e,this._createRenderPassIds())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useRenderPasses",{get:function(){return this._useRenderPasses},set:function(e){this._useRenderPasses!==e&&(this._useRenderPasses=e,this._createRenderPassIds())},enumerable:!1,configurable:!0}),e.prototype.addExcludedMesh=function(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)},e.prototype.removeExcludedMesh=function(e){var t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)},e.prototype._createRenderPassIds=function(){if(this._releaseRenderPassIds(),this._useRenderPasses)for(var e=0;e<this._passCount+1;++e)this._renderPassIds[e]||(this._renderPassIds[e]=this._engine.createRenderPassId("DepthPeelingRenderer - pass #".concat(e)))},e.prototype._releaseRenderPassIds=function(){for(var e=0;e<this._renderPassIds.length;++e)this._engine.releaseRenderPassId(this._renderPassIds[e]);this._renderPassIds=[]},e.prototype._createTextures=function(){var e={width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()};this._depthMrts=[new ky("depthPeelingDepth0MRT",e,3,this._scene,void 0,["depthPeelingDepth0MRT_depth","depthPeelingDepth0MRT_frontColor","depthPeelingDepth0MRT_backColor"]),new ky("depthPeelingDepth1MRT",e,3,this._scene,void 0,["depthPeelingDepth1MRT_depth","depthPeelingDepth1MRT_frontColor","depthPeelingDepth1MRT_backColor"])],this._colorMrts=[new ky("depthPeelingColor0MRT",e,2,this._scene,{generateDepthBuffer:!1},["depthPeelingColor0MRT_frontColor","depthPeelingColor0MRT_backColor"]),new ky("depthPeelingColor1MRT",e,2,this._scene,{generateDepthBuffer:!1},["depthPeelingColor1MRT_frontColor","depthPeelingColor1MRT_backColor"])],this._blendBackMrt=new ky("depthPeelingBackMRT",e,1,this._scene,{generateDepthBuffer:!1},["depthPeelingBackMRT_blendBack"]),this._outputRT=new Pl("depthPeelingOutputRTT",e,this._scene,!1);for(var t=[{format:u.TEXTUREFORMAT_RG,samplingMode:u.TEXTURE_NEAREST_SAMPLINGMODE,type:this._engine.getCaps().textureFloatLinearFiltering?u.TEXTURETYPE_FLOAT:u.TEXTURETYPE_HALF_FLOAT,label:"DepthPeelingRenderer-DepthTexture"},{format:u.TEXTUREFORMAT_RGBA,samplingMode:u.TEXTURE_NEAREST_SAMPLINGMODE,type:u.TEXTURETYPE_HALF_FLOAT,label:"DepthPeelingRenderer-ColorTexture"}],i=0;i<2;i++){var r=this._engine._createInternalTexture(e,t[0],!1),n=this._engine._createInternalTexture(e,t[1],!1),o=this._engine._createInternalTexture(e,t[1],!1);this._depthMrts[i].setInternalTexture(r,0),this._depthMrts[i].setInternalTexture(n,1),this._depthMrts[i].setInternalTexture(o,2),this._colorMrts[i].setInternalTexture(n,0),this._colorMrts[i].setInternalTexture(o,1),this._thinTextures.push(new ja(r),new ja(n),new ja(o))}},e.prototype._disposeTextures=function(){for(var e=0;e<this._thinTextures.length;e++)6!==e&&this._thinTextures[e].dispose();for(e=0;e<2;e++)this._depthMrts[e].dispose(!0),this._colorMrts[e].dispose(!0),this._blendBackMrt.dispose(!0);this._outputRT.dispose(),this._thinTextures=[],this._colorMrts=[],this._depthMrts=[]},e.prototype._updateTextures=function(){return this._depthMrts[0].getSize().width===this._engine.getRenderWidth()&&this._depthMrts[0].getSize().height===this._engine.getRenderHeight()||(this._disposeTextures(),this._createTextures()),this._updateTextureReferences()},e.prototype._updateTextureReferences=function(){var e,t=this._scene.prePassRenderer;if(!t)return!1;var i=t.getIndex(u.PREPASS_COLOR_TEXTURE_TYPE),r=(null===(e=t.defaultRT.textures)||void 0===e?void 0:e.length)?t.defaultRT.textures[i].getInternalTexture():null;return!!r&&(this._blendBackTexture!==r&&(this._blendBackTexture=r,this._blendBackMrt.setInternalTexture(this._blendBackTexture,0),this._thinTextures[6]&&this._thinTextures[6].dispose(),this._thinTextures[6]=new ja(this._blendBackTexture),t.defaultRT.renderTarget.shareDepth(this._depthMrts[0].renderTarget)),!0)},e.prototype._createEffects=function(){this._blendBackEffectWrapper=new El({fragmentShader:"oitBackBlend",useShaderStore:!0,engine:this._engine,samplerNames:["uBackColor"],uniformNames:[]}),this._blendBackEffectWrapperPingPong=new El({fragmentShader:"oitBackBlend",useShaderStore:!0,engine:this._engine,samplerNames:["uBackColor"],uniformNames:[]}),this._finalEffectWrapper=new El({fragmentShader:"oitFinal",useShaderStore:!0,engine:this._engine,samplerNames:["uFrontColor","uBackColor"],uniformNames:[]}),this._effectRenderer=new Tl(this._engine)},e.prototype.setPrePassRenderer=function(e){e.addEffectConfiguration(this._prePassEffectConfiguration)},e.prototype.bind=function(e){e.setTexture("oitDepthSampler",this._thinTextures[3*this._currentPingPongState]),e.setTexture("oitFrontColorSampler",this._thinTextures[3*this._currentPingPongState+1])},e.prototype._renderSubMeshes=function(e){var t;this._useRenderPasses&&(t={});for(var i=0;i<e.length;i++){var r=e.data[i].getMaterial(),n=!0,o=!1,a=e.data[i],s=void 0,l=!1;if(this._useRenderPasses&&(l=!(s=a._getDrawWrapper())),r&&(n=r.allowShaderHotSwapping,o=r.backFaceCulling,r.allowShaderHotSwapping=!1,r.backFaceCulling=!1),a.render(!1),l&&(s=a._getDrawWrapper()).materialContext){var c=t[s.materialContext.uniqueId];c||(c=t[s.materialContext.uniqueId]=this._engine.createMaterialContext()),a._getDrawWrapper().materialContext=c}r&&(r.allowShaderHotSwapping=n,r.backFaceCulling=o)}},e.prototype._finalCompose=function(e){var t;(null===(t=this._scene.prePassRenderer)||void 0===t?void 0:t.setCustomOutput(this._outputRT))?this._engine.bindFramebuffer(this._outputRT.renderTarget):this._engine.restoreDefaultFramebuffer(),this._engine.setAlphaMode(u.ALPHA_DISABLE),this._engine.applyStates(),this._engine.enableEffect(this._finalEffectWrapper._drawWrapper),this._finalEffectWrapper.effect.setTexture("uFrontColor",this._thinTextures[3*e+1]),this._finalEffectWrapper.effect.setTexture("uBackColor",this._thinTextures[6]),this._effectRenderer.render(this._finalEffectWrapper)},e.prototype.isReady=function(){return this._blendBackEffectWrapper.effect.isReady()&&this._blendBackEffectWrapperPingPong.effect.isReady()&&this._finalEffectWrapper.effect.isReady()&&this._updateTextures()},e.prototype.render=function(e){if(this._candidateSubMeshes.length=0,this._excludedSubMeshes.length=0,!this.isReady())return this._excludedSubMeshes;this._scene.activeCamera&&this._engine.setViewport(this._scene.activeCamera.viewport);for(var t=0;t<e.length;t++){var i=e.data[t],r=i.getMaterial(),n=r&&i.getRenderingMesh()._getRenderingFillMode(r.fillMode);!r||n!==Ca.TriangleFanDrawMode&&n!==Ca.TriangleFillMode&&n!==Ca.TriangleStripDrawMode||-1!==this._excludedMeshes.indexOf(i.getMesh().uniqueId)?this._excludedSubMeshes.push(i):this._candidateSubMeshes.push(i)}if(!this._candidateSubMeshes.length)return this._engine.bindFramebuffer(this._colorMrts[1].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget),this._finalCompose(1),this._excludedSubMeshes;var o=this._engine.currentRenderPassId;this._scene.prePassRenderer._enabled=!1,this._useRenderPasses&&(this._engine.currentRenderPassId=this._renderPassIds[0]),this._engine.bindFramebuffer(this._depthMrts[0].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.clear(this._colorCache[0],!0,!1,!1),this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget),this._engine.bindFramebuffer(this._depthMrts[1].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.clear(this._colorCache[1],!0,!1,!1),this._engine.unBindFramebuffer(this._depthMrts[1].renderTarget),this._engine.bindFramebuffer(this._colorMrts[0].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[0].renderTarget),this._engine.bindFramebuffer(this._colorMrts[1].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget),this._engine.bindFramebuffer(this._depthMrts[0].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.setAlphaMode(u.ALPHA_ONEONE_ONEONE),this._engine.setAlphaEquation(u.ALPHA_EQUATION_MAX),this._engine.depthCullingState.depthMask=!1,this._engine.depthCullingState.depthTest=!0,this._engine.applyStates(),this._currentPingPongState=1,this._renderSubMeshes(this._candidateSubMeshes),this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget),this._scene.resetCachedMaterial();var a=0,s=0;for(t=0;t<this._passCount;t++){s=1-(a=t%2),this._currentPingPongState=a,this._useRenderPasses&&(this._engine.currentRenderPassId=this._renderPassIds[t+1]),this._scene.activeCamera&&this._engine.setViewport(this._scene.activeCamera.viewport),this._engine.bindFramebuffer(this._depthMrts[s].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.clear(this._colorCache[0],!0,!1,!1),this._engine.unBindFramebuffer(this._depthMrts[s].renderTarget),this._engine.bindFramebuffer(this._colorMrts[s].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[s].renderTarget),this._engine.bindFramebuffer(this._depthMrts[s].renderTarget),this._engine.bindAttachments(this._layoutCache[2]),this._engine.setAlphaMode(u.ALPHA_ONEONE_ONEONE),this._engine.setAlphaEquation(u.ALPHA_EQUATION_MAX),this._engine.depthCullingState.depthTest=!1,this._engine.applyStates(),this._renderSubMeshes(this._candidateSubMeshes),this._engine.unBindFramebuffer(this._depthMrts[s].renderTarget),this._scene.resetCachedMaterial(),this._engine.bindFramebuffer(this._blendBackMrt.renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.setAlphaEquation(u.ALPHA_EQUATION_ADD),this._engine.setAlphaMode(u.ALPHA_LAYER_ACCUMULATE),this._engine.applyStates();var l=0!==s&&this._useRenderPasses?this._blendBackEffectWrapperPingPong:this._blendBackEffectWrapper;this._engine.enableEffect(l._drawWrapper),l.effect.setTexture("uBackColor",this._thinTextures[3*s+2]),this._effectRenderer.render(l),this._engine.unBindFramebuffer(this._blendBackMrt.renderTarget)}return this._engine.currentRenderPassId=o,this._finalCompose(s),this._scene.prePassRenderer._enabled=!0,this._engine.depthCullingState.depthMask=!0,this._engine.depthCullingState.depthTest=!0,this._excludedSubMeshes},e.prototype.dispose=function(){this._disposeTextures(),this._blendBackEffectWrapper.dispose(),this._finalEffectWrapper.dispose(),this._effectRenderer.dispose(),this._releaseRenderPassIds()},e._DEPTH_CLEAR_VALUE=-99999,e._MIN_DEPTH=0,e._MAX_DEPTH=1,e}();Object.defineProperty(pn.prototype,"depthPeelingRenderer",{get:function(){if(!this._depthPeelingRenderer){var e=this._getComponent(Vr.NAME_DEPTHPEELINGRENDERER);e||(e=new pR(this),this._addComponent(e))}return this._depthPeelingRenderer},set:function(e){this._depthPeelingRenderer=e},enumerable:!0,configurable:!0}),Object.defineProperty(pn.prototype,"useOrderIndependentTransparency",{get:function(){return this._useOrderIndependentTransparency},set:function(e){var t;this._useOrderIndependentTransparency!==e&&(this._useOrderIndependentTransparency=e,this.markAllMaterialsAsDirty(u.MATERIAL_AllDirtyFlag),null===(t=this.prePassRenderer)||void 0===t||t.markAsDirty())},enumerable:!0,configurable:!0});var pR=function(){function e(e){this.name=Vr.NAME_DEPTHPEELINGRENDERER,this.scene=e,e.depthPeelingRenderer=new dR(e)}return e.prototype.register=function(){},e.prototype.rebuild=function(){},e.prototype.dispose=function(){var e;null===(e=this.scene.depthPeelingRenderer)||void 0===e||e.dispose(),this.scene.depthPeelingRenderer=null},e}();li.ShadersStore.linePixelShader="#include<clipPlaneFragmentDeclaration>\nuniform vec4 color;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<logDepthFragment>\n#include<clipPlaneFragment>\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";li.ShadersStore.lineVertexShader="#include<instancesDeclaration>\n#include<clipPlaneVertexDeclaration>\nattribute vec3 position;attribute vec4 normal;uniform mat4 viewProjection;uniform float width;uniform float aspectRatio;\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include<instancesVertex>\nmat4 worldViewProjection=viewProjection*finalWorld;vec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#include<clipPlaneVertex>\n#endif\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}",Uo.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this},Uo.prototype.enableEdgesRendering=function(e,t,i){return void 0===e&&(e=.95),void 0===t&&(t=!1),this.disableEdgesRendering(),this._edgesRenderer=new _R(this,e,t,!0,i),this},Object.defineProperty(Uo.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0}),cd.prototype.enableEdgesRendering=function(e,t){return void 0===e&&(e=.95),void 0===t&&(t=!1),this.disableEdgesRendering(),this._edgesRenderer=new mR(this,e,t),this},ud.prototype.enableEdgesRendering=function(e,t){return void 0===e&&(e=.95),void 0===t&&(t=!1),cd.prototype.enableEdgesRendering.apply(this,arguments),this};var fR=function(){this.edges=[],this.edgesConnectedCount=0},_R=function(){function e(e,t,i,r,n){void 0===t&&(t=.95),void 0===i&&(i=!1),void 0===r&&(r=!0);var o,a=this;this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new ar(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=null!=n?n:null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new ho(e.getEngine())),this._prepareRessources(),r&&(null===(o=null==n?void 0:n.useAlternateEdgeFinder)||void 0===o||o?this._generateEdgesLinesAlternate():this._generateEdgesLines()),this._meshRebuildObserver=this._source.onRebuildObservable.add((function(){a._rebuild()})),this._meshDisposeObserver=this._source.onDisposeObservable.add((function(){a.dispose()}))}return Object.defineProperty(e.prototype,"linesPositions",{get:function(){return this._linesPositions},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"linesNormals",{get:function(){return this._linesNormals},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"linesIndices",{get:function(){return this._linesIndices},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"lineShader",{get:function(){return this._lineShader},set:function(e){this._lineShader=e},enumerable:!1,configurable:!0}),e._GetShader=function(e){if(!e._edgeRenderLineShader){var t=new ld("lineShader",e,"line",{attributes:["position","normal"],uniforms:["world","viewProjection","color","width","aspectRatio"]},!1);t.disableDepthWrite=!0,t.backFaceCulling=!1,t.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=t}return e._edgeRenderLineShader},e.prototype._prepareRessources=function(){this._lineShader||(this._lineShader=e._GetShader(this._source.getScene()))},e.prototype._rebuild=function(){var e=this._buffers[Nr.PositionKind];e&&e._rebuild(),(e=this._buffers[Nr.NormalKind])&&e._rebuild();var t=this._source.getScene().getEngine();this._ib=t.createIndexBuffer(this._linesIndices)},e.prototype.dispose=function(){var e;this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);var t=this._buffers[Nr.PositionKind];t&&(t.dispose(),this._buffers[Nr.PositionKind]=null),(t=this._buffers[Nr.NormalKind])&&(t.dispose(),this._buffers[Nr.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),null===(e=this._drawWrapper)||void 0===e||e.dispose()},e.prototype._processEdgeForAdjacencies=function(e,t,i,r,n){return e===i&&t===r||e===r&&t===i?0:e===r&&t===n||e===n&&t===r?1:e===n&&t===i||e===i&&t===n?2:-1},e.prototype._processEdgeForAdjacenciesWithVertices=function(e,t,i,r,n){var o=1e-10;return e.equalsWithEpsilon(i,o)&&t.equalsWithEpsilon(r,o)||e.equalsWithEpsilon(r,o)&&t.equalsWithEpsilon(i,o)?0:e.equalsWithEpsilon(r,o)&&t.equalsWithEpsilon(n,o)||e.equalsWithEpsilon(n,o)&&t.equalsWithEpsilon(r,o)?1:e.equalsWithEpsilon(n,o)&&t.equalsWithEpsilon(i,o)||e.equalsWithEpsilon(i,o)&&t.equalsWithEpsilon(n,o)?2:-1},e.prototype._checkEdge=function(e,t,i,r,n){(void 0===t||V.Dot(i[e],i[t])<this._epsilon)&&this.createLine(r,n,this._linesPositions.length/3)},e.prototype.createLine=function(e,t,i){this._linesPositions.push(e.x,e.y,e.z,e.x,e.y,e.z,t.x,t.y,t.z,t.x,t.y,t.z),this._linesNormals.push(t.x,t.y,t.z,-1,t.x,t.y,t.z,1,e.x,e.y,e.z,-1,e.x,e.y,e.z,1),this._linesIndices.push(i,i+1,i+2,i,i+2,i+3)},e.prototype._tessellateTriangle=function(e,t,i,r){var n=function(e,t,i){i>=0&&t.push(i);for(var r=0;r<e.length;++r)t.push(e[r][0])},o=0;e[1].length>=e[0].length&&e[1].length>=e[2].length?o=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(o=2);for(var a=0;a<3;++a)a===o?e[a].sort((function(e,t){return e[1]<t[1]?-1:e[1]>t[1]?1:0})):e[a].sort((function(e,t){return e[1]>t[1]?-1:e[1]<t[1]?1:0}));var s=[],l=[];n(e[o],s,-1);for(var c=s.length,u=o+2;u>=o+1;--u)n(e[u%3],l,u!==o+2?r[i[t+(u+1)%3]]:-1);var h=l.length;i.push(r[i[t+o]],s[0],l[0]),i.push(r[i[t+(o+1)%3]],l[h-1],s[c-1]);for(var d=c<=h,p=d?c:h,f=d?h:c,_=d?c-1:h-1,m=d?0:1,g=c+h-2,v=0,y=0,b=d?s:l,T=d?l:s,E=0;g-- >0;){m?i.push(b[v],T[y]):i.push(T[y],b[v]);var S=void 0;(E+=p)>=f&&v<_?(S=b[++v],E-=f):S=T[++y],i.push(S)}i[t+0]=i[i.length-3],i[t+1]=i[i.length-2],i[t+2]=i[i.length-1],i.length=i.length-3},e.prototype._generateEdgesLinesAlternate=function(){var e,t,i,r,n,o,a,s,l,c,u=this._source.getVerticesData(Nr.PositionKind),h=this._source.getIndices();if(h&&u){Array.isArray(h)||(h=Array.from(h));var d=null===(t=null===(e=this._options)||void 0===e?void 0:e.useFastVertexMerger)||void 0===t||t,p=d?Math.round(-Math.log(null!==(r=null===(i=this._options)||void 0===i?void 0:i.epsilonVertexMerge)&&void 0!==r?r:1e-6)/Math.log(10)):null!==(o=null===(n=this._options)||void 0===n?void 0:n.epsilonVertexMerge)&&void 0!==o?o:1e-6,f=[],_=[];if(d)for(var m={},g=0;g<u.length;g+=3){var v=u[g+0],y=u[g+1],b=u[g+2];if(void 0!==m[ie=v.toFixed(p)+"|"+y.toFixed(p)+"|"+b.toFixed(p)])f.push(m[ie]);else{var T=g/3;m[ie]=T,f.push(T),_.push(T)}}else for(g=0;g<u.length;g+=3){v=u[g+0],y=u[g+1],b=u[g+2];for(var E=!1,S=0;S<g&&!E;S+=3){var x=u[S+0],A=u[S+1],C=u[S+2];if(Math.abs(v-x)<p&&Math.abs(y-A)<p&&Math.abs(b-C)<p){f.push(S/3),E=!0;break}}E||(f.push(g/3),_.push(g/3))}if(null===(a=this._options)||void 0===a?void 0:a.applyTessellation){for(var R=null!==(l=null===(s=this._options)||void 0===s?void 0:s.epsilonVertexAligned)&&void 0!==l?l:1e-6,P=[],I=0;I<h.length;I+=3)for(var M=void 0,O=0;O<3;++O){var D=f[h[I+O]],N=f[h[I+(O+1)%3]],F=f[h[I+(O+2)%3]];if(D!==N)for(var L=u[3*D+0],w=u[3*D+1],B=u[3*D+2],U=u[3*N+0],k=u[3*N+1],G=u[3*N+2],z=Math.sqrt((U-L)*(U-L)+(k-w)*(k-w)+(G-B)*(G-B)),W=0;W<_.length-1;W++){var X=_[W];if(X!==D&&X!==N&&X!==F){var j=u[3*X+0],Y=u[3*X+1],K=u[3*X+2],Q=Math.sqrt((j-L)*(j-L)+(Y-w)*(Y-w)+(K-B)*(K-B)),q=Math.sqrt((j-U)*(j-U)+(Y-k)*(Y-k)+(K-G)*(K-G));Math.abs(Q+q-z)<R&&(M||(M={index:I,edgesPoints:[[],[],[]]},P.push(M)),M.edgesPoints[O].push([X,Q]))}}}for(var Z=0;Z<P.length;++Z){var J=P[Z];this._tessellateTriangle(J.edgesPoints,J.index,h,f)}P.length=0}var $={};for(I=0;I<h.length;I+=3){var ee=void 0;for(O=0;O<3;++O)if(D=f[h[I+O]],N=f[h[I+(O+1)%3]],F=f[h[I+(O+2)%3]],D!==N&&(D!==F&&N!==F||!(null===(c=this._options)||void 0===c?void 0:c.removeDegeneratedTriangles))){if(H.Vector3[0].copyFromFloats(u[3*D+0],u[3*D+1],u[3*D+2]),H.Vector3[1].copyFromFloats(u[3*N+0],u[3*N+1],u[3*N+2]),H.Vector3[2].copyFromFloats(u[3*F+0],u[3*F+1],u[3*F+2]),ee||(H.Vector3[1].subtractToRef(H.Vector3[0],H.Vector3[3]),H.Vector3[2].subtractToRef(H.Vector3[1],H.Vector3[4]),(ee=V.Cross(H.Vector3[3],H.Vector3[4])).normalize()),D>N){var te=D;D=N,N=te}(re=$[ie=D+"_"+N])?re.done||(V.Dot(ee,re.normal)<this._epsilon&&this.createLine(H.Vector3[0],H.Vector3[1],this._linesPositions.length/3),re.done=!0):$[ie]={normal:ee,done:!1,index:I,i:O}}}for(var ie in $){var re;(re=$[ie]).done||(D=f[h[re.index+re.i]],N=f[h[re.index+(re.i+1)%3]],H.Vector3[0].copyFromFloats(u[3*D+0],u[3*D+1],u[3*D+2]),H.Vector3[1].copyFromFloats(u[3*N+0],u[3*N+1],u[3*N+2]),this.createLine(H.Vector3[0],H.Vector3[1],this._linesPositions.length/3))}var ne=this._source.getScene().getEngine();this._buffers[Nr.PositionKind]=new Nr(ne,this._linesPositions,Nr.PositionKind,!1),this._buffers[Nr.NormalKind]=new Nr(ne,this._linesNormals,Nr.NormalKind,!1,!1,4),this._buffersForInstances[Nr.PositionKind]=this._buffers[Nr.PositionKind],this._buffersForInstances[Nr.NormalKind]=this._buffers[Nr.NormalKind],this._ib=ne.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length}},e.prototype._generateEdgesLines=function(){var e=this._source.getVerticesData(Nr.PositionKind),t=this._source.getIndices();if(t&&e){var i,r,n=[],o=[];for(i=0;i<t.length;i+=3){r=new fR;var a=t[i],s=t[i+1],l=t[i+2];r.p0=new V(e[3*a],e[3*a+1],e[3*a+2]),r.p1=new V(e[3*s],e[3*s+1],e[3*s+2]),r.p2=new V(e[3*l],e[3*l+1],e[3*l+2]);var c=V.Cross(r.p1.subtract(r.p0),r.p2.subtract(r.p1));c.normalize(),o.push(c),n.push(r)}for(i=0;i<n.length;i++){r=n[i];for(var u=i+1;u<n.length;u++){var h=n[u];if(3===r.edgesConnectedCount)break;if(3!==h.edgesConnectedCount)for(var d=t[3*u],p=t[3*u+1],f=t[3*u+2],_=0;_<3;_++){var m=0;if(void 0===r.edges[_]){switch(_){case 0:m=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(r.p0,r.p1,h.p0,h.p1,h.p2):this._processEdgeForAdjacencies(t[3*i],t[3*i+1],d,p,f);break;case 1:m=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(r.p1,r.p2,h.p0,h.p1,h.p2):this._processEdgeForAdjacencies(t[3*i+1],t[3*i+2],d,p,f);break;case 2:m=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(r.p2,r.p0,h.p0,h.p1,h.p2):this._processEdgeForAdjacencies(t[3*i+2],t[3*i],d,p,f)}if(-1!==m&&(r.edges[_]=u,h.edges[m]=i,r.edgesConnectedCount++,h.edgesConnectedCount++,3===r.edgesConnectedCount))break}}}}for(i=0;i<n.length;i++){var g=n[i];this._checkEdge(i,g.edges[0],o,g.p0,g.p1),this._checkEdge(i,g.edges[1],o,g.p1,g.p2),this._checkEdge(i,g.edges[2],o,g.p2,g.p0)}var v=this._source.getScene().getEngine();this._buffers[Nr.PositionKind]=new Nr(v,this._linesPositions,Nr.PositionKind,!1),this._buffers[Nr.NormalKind]=new Nr(v,this._linesNormals,Nr.NormalKind,!1,!1,4),this._buffersForInstances[Nr.PositionKind]=this._buffers[Nr.PositionKind],this._buffersForInstances[Nr.NormalKind]=this._buffers[Nr.NormalKind],this._ib=v.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length}},e.prototype.isReady=function(){return this._lineShader.isReady(this._source,this._source.hasInstances&&this.customInstances.length>0||this._source.hasThinInstances)},e.prototype.render=function(){var e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),this.isReady()&&e.activeCamera){var i=this._source.hasInstances&&this.customInstances.length>0,r=i||this._source.hasThinInstances,n=0;if(r)if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){var o=this._source._instanceDataStorage;if(n=this.customInstances.length,!o.instancesData)return void(this._source.getScene()._activeMeshesFrozen||this.customInstances.reset());if(!o.isFrozen){for(var a=0,s=0;s<n;++s)this.customInstances.data[s].copyToArray(o.instancesData,a),a+=16;o.instancesBuffer.updateDirectly(o.instancesData,0,n)}}else n=this._source.thinInstanceCount;var l=e.getEngine();this._lineShader._preBind(),1!==this._source.edgesColor.a?l.setAlphaMode(u.ALPHA_COMBINE):l.setAlphaMode(u.ALPHA_DISABLE),l.bindBuffers(r?this._buffersForInstances:this._buffers,this._ib,this._lineShader.getEffect()),e.resetCachedMaterial(),this._lineShader.setColor4("color",this._source.edgesColor),e.activeCamera.mode===$n.ORTHOGRAPHIC_CAMERA?this._lineShader.setFloat("width",this._source.edgesWidth/this.edgesWidthScalerForOrthographic):this._lineShader.setFloat("width",this._source.edgesWidth/this.edgesWidthScalerForPerspective),this._lineShader.setFloat("aspectRatio",l.getAspectRatio(e.activeCamera)),this._lineShader.bind(this._source.getWorldMatrix()),l.drawElementsType(Ca.TriangleFillMode,0,this._indicesCount,n),this._lineShader.unbind(),r&&l.unbindInstanceAttributes(),this._source.getScene()._activeMeshesFrozen||this.customInstances.reset(),this._lineShader._setDrawWrapper(t)}else this._lineShader._setDrawWrapper(t)},e}(),mR=function(e){function t(t,i,r){void 0===i&&(i=.95),void 0===r&&(r=!1);var n=e.call(this,t,i,r,!1)||this;return n._generateEdgesLines(),n}return m(t,e),t.prototype._generateEdgesLines=function(){var e=this._source.getVerticesData(Nr.PositionKind),t=this._source.getIndices();if(t&&e){for(var i=H.Vector3[0],r=H.Vector3[1],n=t.length-1,o=0,a=0;o<n;o+=2,a+=4)V.FromArrayToRef(e,3*t[o],i),V.FromArrayToRef(e,3*t[o+1],r),this.createLine(i,r,a);var s=this._source.getScene().getEngine();this._buffers[Nr.PositionKind]=new Nr(s,this._linesPositions,Nr.PositionKind,!1),this._buffers[Nr.NormalKind]=new Nr(s,this._linesNormals,Nr.NormalKind,!1,!1,4),this._ib=s.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length}},t}(_R),gR=function(e){function t(t,i,r,n,o,a){var s=e.call(this,t,r,n,o,a)||this;return s._beforeCompositionPostProcesses=[],s._internalTextureDirty=!1,s.enabled=!1,s.renderTargetTexture=null,s.renderTargetTexture=i,s}return m(t,e),t.prototype._createCompositionEffect=function(){this.imageProcessingPostProcess=new LC("prePassComposition",1,null,void 0,this._engine),this.imageProcessingPostProcess._updateParameters()},t.prototype._checkSize=function(){var e=this._engine.getRenderWidth(!0),t=this._engine.getRenderHeight(!0),i=this.getRenderWidth(),r=this.getRenderHeight();i===e&&r===t||(this.resize({width:e,height:t}),this._internalTextureDirty=!0)},t.prototype.updateCount=function(t,i,r){e.prototype.updateCount.call(this,t,i,r),this._internalTextureDirty=!0},t.prototype._resetPostProcessChain=function(){this._beforeCompositionPostProcesses.length=0},t.prototype.dispose=function(){var t=this._scene;if(e.prototype.dispose.call(this),t&&t.prePassRenderer){var i=t.prePassRenderer.renderTargets.indexOf(this);-1!==i&&t.prePassRenderer.renderTargets.splice(i,1)}this.imageProcessingPostProcess&&this.imageProcessingPostProcess.dispose(),this.renderTargetTexture&&(this.renderTargetTexture._prePassRenderTarget=null),this._outputPostProcess&&(this._outputPostProcess.autoClear=!0,this._outputPostProcess.restoreDefaultInputTexture())},t}(ky),vR=function(){function e(t){this.excludedSkinnedMesh=[],this.excludedMaterials=[],this.mrtCount=0,this._mrtTypes=[],this._mrtFormats=[],this._mrtLayout=[],this._mrtNames=[],this._textureIndices=[],this._generateNormalsInWorldSpace=!1,this._useSpecificClearForDepthTexture=!1,this._isDirty=!0,this._effectConfigurations=[],this.doNotUseGeometryRendererFallback=!0,this.renderTargets=[],this._clearColor=new J(0,0,0,0),this._clearDepthColor=new J(1e8,0,0,1),this._enabled=!1,this._needsCompositionForThisPass=!1,this.disableGammaTransform=!1,this._scene=t,this._engine=t.getEngine();var i=u.TEXTURETYPE_UNSIGNED_BYTE;this._engine._caps.textureFloat&&this._engine._caps.textureFloatLinearFiltering?i=u.TEXTURETYPE_FLOAT:this._engine._caps.textureHalfFloat&&this._engine._caps.textureHalfFloatLinearFiltering&&(i=u.TEXTURETYPE_HALF_FLOAT);for(var r=0;r<e.TextureFormats.length;++r){var n=e.TextureFormats[r].format;e.TextureFormats[r].type===u.TEXTURETYPE_FLOAT&&(e.TextureFormats[u.PREPASS_DEPTH_TEXTURE_TYPE].type=i,n!==u.TEXTUREFORMAT_R&&n!==u.TEXTUREFORMAT_RG&&n!==u.TEXTUREFORMAT_RGBA||this._engine._caps.supportFloatTexturesResolve||(e.TextureFormats[u.PREPASS_DEPTH_TEXTURE_TYPE].type=u.TEXTURETYPE_HALF_FLOAT))}e._SceneComponentInitialization(this._scene),this.defaultRT=this._createRenderTarget("sceneprePassRT",null),this._currentTarget=this.defaultRT}return Object.defineProperty(e.prototype,"generateNormalsInWorldSpace",{get:function(){return this._generateNormalsInWorldSpace},set:function(e){this._generateNormalsInWorldSpace!==e&&(this._generateNormalsInWorldSpace=e,this._markAllMaterialsAsPrePassDirty())},enumerable:!1,configurable:!0}),e.prototype.getIndex=function(e){return this._textureIndices[e]},Object.defineProperty(e.prototype,"samples",{get:function(){return this.defaultRT.samples},set:function(e){this.defaultRT.samples=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useSpecificClearForDepthTexture",{get:function(){return this._useSpecificClearForDepthTexture},set:function(e){this._useSpecificClearForDepthTexture!==e&&(this._useSpecificClearForDepthTexture=e,this._isDirty=!0)},enumerable:!1,configurable:!0}),e.prototype.getRenderTarget=function(){return this._currentTarget},e.prototype._setRenderTarget=function(e){var t,i;e?this._currentTarget=e:(this._currentTarget=this.defaultRT,this._engine.currentRenderPassId=null!==(i=null===(t=this._scene.activeCamera)||void 0===t?void 0:t.renderPassId)&&void 0!==i?i:this._currentTarget.renderPassId)},Object.defineProperty(e.prototype,"currentRTisSceneRT",{get:function(){return this._currentTarget===this.defaultRT},enumerable:!1,configurable:!0}),e.prototype._refreshGeometryBufferRendererLink=function(){if(this.doNotUseGeometryRendererFallback)this._geometryBuffer&&this._geometryBuffer._unlinkPrePassRenderer(),this._geometryBuffer=null,this._scene.disableGeometryBufferRenderer();else{if(this._geometryBuffer=this._scene.enableGeometryBufferRenderer(),!this._geometryBuffer)return void(this.doNotUseGeometryRendererFallback=!0);this._geometryBuffer._linkPrePassRenderer(this)}},Object.defineProperty(e.prototype,"enabled",{get:function(){return this._enabled},enumerable:!1,configurable:!0}),e.prototype._createRenderTarget=function(e,t){var i=new gR(e,t,{width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()},0,this._scene,{generateMipMaps:!1,generateStencilBuffer:this._engine.isStencilEnable,defaultType:u.TEXTURETYPE_UNSIGNED_INT,types:[],drawOnlyOnFirstAttachmentByDefault:!0});return this.renderTargets.push(i),this._enabled&&this._update(),i},Object.defineProperty(e.prototype,"isSupported",{get:function(){return this._scene.getEngine().getCaps().drawBuffersExtension},enumerable:!1,configurable:!0}),e.prototype.bindAttachmentsForEffect=function(e,t){var i=t.getMaterial(),r=i&&i.isPrePassCapable,n=i&&-1!==this.excludedMaterials.indexOf(i);this.enabled&&this._currentTarget.enabled&&(e._multiTarget&&r&&!n?this._engine.bindAttachments(this._multiRenderAttachments):(this._engine._currentRenderTarget?this._engine.bindAttachments(this._defaultAttachments):this._engine.restoreSingleAttachment(),this._geometryBuffer&&this.currentRTisSceneRT&&!n&&this._geometryBuffer.renderList.push(t.getRenderingMesh())))},e.prototype._reinitializeAttachments=function(){for(var e=[],t=[!1],i=[!1],r=[!0],n=0;n<this.mrtCount;n++)e.push(!0),n>0&&(this._useSpecificClearForDepthTexture&&this._mrtLayout[n]===u.PREPASS_DEPTH_TEXTURE_TYPE?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),r.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(e),this._clearAttachments=this._engine.buildTextureLayout(t),this._clearDepthAttachments=this._engine.buildTextureLayout(i),this._defaultAttachments=this._engine.buildTextureLayout(r)},e.prototype._resetLayout=function(){for(var t=0;t<e.TextureFormats.length;t++)this._textureIndices[e.TextureFormats[t].purpose]=-1;this._textureIndices[u.PREPASS_COLOR_TEXTURE_TYPE]=0,this._mrtLayout=[u.PREPASS_COLOR_TEXTURE_TYPE],this._mrtTypes=[e.TextureFormats[u.PREPASS_COLOR_TEXTURE_TYPE].type],this._mrtFormats=[e.TextureFormats[u.PREPASS_COLOR_TEXTURE_TYPE].format],this._mrtNames=[e.TextureFormats[u.PREPASS_COLOR_TEXTURE_TYPE].name],this.mrtCount=1},e.prototype._updateGeometryBufferLayout=function(){if(this._refreshGeometryBufferRendererLink(),this._geometryBuffer){this._geometryBuffer._resetLayout();for(var e=[],t=0;t<this._mrtLayout.length;t++)e.push(!1);this._geometryBuffer._linkInternalTexture(this.defaultRT.getInternalTexture());var i=[{prePassConstant:u.PREPASS_DEPTH_TEXTURE_TYPE,geometryBufferConstant:BC.DEPTH_TEXTURE_TYPE},{prePassConstant:u.PREPASS_NORMAL_TEXTURE_TYPE,geometryBufferConstant:BC.NORMAL_TEXTURE_TYPE},{prePassConstant:u.PREPASS_POSITION_TEXTURE_TYPE,geometryBufferConstant:BC.POSITION_TEXTURE_TYPE},{prePassConstant:u.PREPASS_REFLECTIVITY_TEXTURE_TYPE,geometryBufferConstant:BC.REFLECTIVITY_TEXTURE_TYPE},{prePassConstant:u.PREPASS_VELOCITY_TEXTURE_TYPE,geometryBufferConstant:BC.VELOCITY_TEXTURE_TYPE}];for(t=0;t<i.length;t++){var r=this._mrtLayout.indexOf(i[t].prePassConstant);-1!==r&&(this._geometryBuffer._forceTextureType(i[t].geometryBufferConstant,r),e[r]=!0)}this._geometryBuffer._setAttachments(this._engine.buildTextureLayout(e))}},e.prototype.restoreAttachments=function(){this.enabled&&this._currentTarget.enabled&&this._defaultAttachments&&(this._engine._currentRenderTarget?this._engine.bindAttachments(this._defaultAttachments):this._engine.restoreSingleAttachment())},e.prototype._beforeDraw=function(e,t,i){this._isDirty&&this._update(),this._enabled&&this._currentTarget.enabled&&(this._geometryBuffer&&(this._geometryBuffer.renderList=[]),this._setupOutputForThisPass(this._currentTarget,e))},e.prototype._prepareFrame=function(e,t,i){e.renderTargetTexture?e.renderTargetTexture._prepareFrame(this._scene,t,i,e.renderTargetTexture.useCameraPostProcesses):this._postProcessesSourceForThisPass.length?this._scene.postProcessManager._prepareFrame():this._engine.restoreDefaultFramebuffer()},e.prototype.setCustomOutput=function(e){var t=this._postProcessesSourceForThisPass[0];return!!t&&(t.inputTexture=e.renderTarget,!0)},e.prototype._renderPostProcesses=function(e,t){var i,r=this._postProcessesSourceForThisPass[0],n=r?r.inputTexture:e.renderTargetTexture?e.renderTargetTexture.renderTarget:null,o=this._currentTarget._beforeCompositionPostProcesses;this._needsCompositionForThisPass&&(o=o.concat([this._currentTarget.imageProcessingPostProcess])),o.length&&(this._scene.postProcessManager._prepareFrame(null===(i=this._currentTarget.renderTarget)||void 0===i?void 0:i.texture,o),this._scene.postProcessManager.directRender(o,n,!1,t))},e.prototype._afterDraw=function(e,t){this._enabled&&this._currentTarget.enabled&&(this._prepareFrame(this._currentTarget,e,t),this._renderPostProcesses(this._currentTarget,e))},e.prototype._clear=function(){this._isDirty&&this._update(),this._enabled&&this._currentTarget.enabled&&(this._bindFrameBuffer(),this._engine.bindAttachments(this._clearAttachments),this._engine.clear(this._clearColor,!0,!1,!1),this._useSpecificClearForDepthTexture&&(this._engine.bindAttachments(this._clearDepthAttachments),this._engine.clear(this._clearDepthColor,!0,!1,!1)),this._engine.bindAttachments(this._defaultAttachments))},e.prototype._bindFrameBuffer=function(){if(this._enabled&&this._currentTarget.enabled){this._currentTarget._checkSize();var e=this._currentTarget.renderTarget;e&&this._engine.bindFramebuffer(e)}},e.prototype._setEnabled=function(e){this._enabled=e},e.prototype._setRenderTargetEnabled=function(e,t){e.enabled=t,t||this._unlinkInternalTexture(e)},e.prototype.addEffectConfiguration=function(e){for(var t=0;t<this._effectConfigurations.length;t++)if(this._effectConfigurations[t].name===e.name)return this._effectConfigurations[t];return this._effectConfigurations.push(e),e},e.prototype.getEffectConfiguration=function(e){for(var t=0;t<this._effectConfigurations.length;t++)if(this._effectConfigurations[t].name===e)return this._effectConfigurations[t];return null},e.prototype._enable=function(){for(var e=this.mrtCount,t=0;t<this._effectConfigurations.length;t++)this._effectConfigurations[t].enabled&&this._enableTextures(this._effectConfigurations[t].texturesRequired);for(t=0;t<this.renderTargets.length;t++){this.mrtCount===e&&this.renderTargets[t].count===this.mrtCount||this.renderTargets[t].updateCount(this.mrtCount,{types:this._mrtTypes,formats:this._mrtFormats},this._mrtNames.concat("prePass_DepthBuffer")),this.renderTargets[t]._resetPostProcessChain();for(var i=0;i<this._effectConfigurations.length;i++)this._effectConfigurations[i].enabled&&(!this._effectConfigurations[i].postProcess&&this._effectConfigurations[i].createPostProcess&&this._effectConfigurations[i].createPostProcess(),this._effectConfigurations[i].postProcess&&this.renderTargets[t]._beforeCompositionPostProcesses.push(this._effectConfigurations[i].postProcess))}this._reinitializeAttachments(),this._setEnabled(!0),this._updateGeometryBufferLayout()},e.prototype._disable=function(){this._setEnabled(!1);for(var e=0;e<this.renderTargets.length;e++)this._setRenderTargetEnabled(this.renderTargets[e],!1);for(this._resetLayout(),e=0;e<this._effectConfigurations.length;e++)this._effectConfigurations[e].enabled=!1},e.prototype._getPostProcessesSource=function(e,t){if(t)return t._postProcesses;if(e.renderTargetTexture){if(e.renderTargetTexture.useCameraPostProcesses){var i=e.renderTargetTexture.activeCamera?e.renderTargetTexture.activeCamera:this._scene.activeCamera;return i?i._postProcesses:[]}return e.renderTargetTexture.postProcesses?e.renderTargetTexture.postProcesses:[]}return this._scene.activeCamera?this._scene.activeCamera._postProcesses:[]},e.prototype._setupOutputForThisPass=function(e,t){var i=t&&this._scene.activeCameras&&!!this._scene.activeCameras.length&&0!==this._scene.activeCameras.indexOf(t);this._postProcessesSourceForThisPass=this._getPostProcessesSource(e,t),this._postProcessesSourceForThisPass=this._postProcessesSourceForThisPass.filter((function(e){return null!=e})),this._scene.autoClear=!0;var r=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!r&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;var n=this._getFirstPostProcess(this._postProcessesSourceForThisPass),o=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0],a=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||r,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),o?a=o:this._needsCompositionForThisPass?a=e.imageProcessingPostProcess:n&&(a=n),this._bindFrameBuffer(),this._linkInternalTexture(e,a)},e.prototype._linkInternalTexture=function(e,t){t&&(t.autoClear=!1,t.inputTexture=e.renderTarget),e._outputPostProcess!==t&&(e._outputPostProcess&&this._unlinkInternalTexture(e),e._outputPostProcess=t),e._internalTextureDirty&&(this._updateGeometryBufferLayout(),e._internalTextureDirty=!1)},e.prototype._unlinkInternalTexture=function(e){e._outputPostProcess&&(e._outputPostProcess.autoClear=!0,e._outputPostProcess.restoreDefaultInputTexture(),e._outputPostProcess=null)},e.prototype._needsImageProcessing=function(){for(var e=0;e<this._effectConfigurations.length;e++)if(this._effectConfigurations[e].enabled&&this._effectConfigurations[e].needsImageProcessing)return!0;return!1},e.prototype._hasImageProcessing=function(e){var t,i=!1;if(e)for(var r=0;r<e.length;r++)if("ImageProcessingPostProcess"===(null===(t=e[r])||void 0===t?void 0:t.getClassName())){i=!0;break}return i},e.prototype._getFirstPostProcess=function(e){for(var t=0;t<e.length;t++)if(null!==e[t])return e[t];return null},e.prototype.markAsDirty=function(){this._isDirty=!0},e.prototype._enableTextures=function(t){this._scene.needsPreviousWorldMatrices=!1;for(var i=0;i<t.length;i++){var r=t[i];-1===this._textureIndices[r]&&(this._textureIndices[r]=this._mrtLayout.length,this._mrtLayout.push(r),this._mrtTypes.push(e.TextureFormats[r].type),this._mrtFormats.push(e.TextureFormats[r].format),this._mrtNames.push(e.TextureFormats[r].name),this.mrtCount++),r===u.PREPASS_VELOCITY_TEXTURE_TYPE&&(this._scene.needsPreviousWorldMatrices=!0)}},e.prototype.update=function(){this._isDirty&&this._update()},e.prototype._update=function(){this._disable();var e,t=!1;this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._scene._depthPeelingRenderer&&this._scene.useOrderIndependentTransparency&&(this._scene._depthPeelingRenderer.setPrePassRenderer(this),t=!0);for(var i=0;i<this._scene.materials.length;i++)this._scene.materials[i].setPrePassRenderer(this)&&(t=!0);for(t&&this._setRenderTargetEnabled(this.defaultRT,!0),i=0;i<this.renderTargets.length;i++){if(this.renderTargets[i].renderTargetTexture)e=this._getPostProcessesSource(this.renderTargets[i]);else{var r=this._scene.activeCamera;if(!r)continue;e=r._postProcesses}if(e&&(e=e.filter((function(e){return null!=e})))){for(var n=0;n<e.length;n++)e[n].setPrePassRenderer(this)&&(this._setRenderTargetEnabled(this.renderTargets[i],!0),t=!0);this._hasImageProcessing(e)&&(this._scene.imageProcessingConfiguration.applyByPostProcess=!0)}}this._markAllMaterialsAsPrePassDirty(),this._isDirty=!1,t&&this._enable()},e.prototype._markAllMaterialsAsPrePassDirty=function(){for(var e=this._scene.materials,t=0;t<e.length;t++)e[t].markAsDirty(Ca.PrePassDirtyFlag)},e.prototype.dispose=function(){for(var e=this.renderTargets.length-1;e>=0;e--)this.renderTargets[e].dispose();for(e=0;e<this._effectConfigurations.length;e++)this._effectConfigurations[e].dispose&&this._effectConfigurations[e].dispose()},e._SceneComponentInitialization=function(e){throw He("PrePassRendererSceneComponent")},e.TextureFormats=[{purpose:u.PREPASS_IRRADIANCE_TEXTURE_TYPE,type:u.TEXTURETYPE_HALF_FLOAT,format:u.TEXTUREFORMAT_RGBA,name:"prePass_Irradiance"},{purpose:u.PREPASS_POSITION_TEXTURE_TYPE,type:u.TEXTURETYPE_HALF_FLOAT,format:u.TEXTUREFORMAT_RGBA,name:"prePass_Position"},{purpose:u.PREPASS_VELOCITY_TEXTURE_TYPE,type:u.TEXTURETYPE_UNSIGNED_INT,format:u.TEXTUREFORMAT_RGBA,name:"prePass_Velocity"},{purpose:u.PREPASS_REFLECTIVITY_TEXTURE_TYPE,type:u.TEXTURETYPE_UNSIGNED_INT,format:u.TEXTUREFORMAT_RGBA,name:"prePass_Reflectivity"},{purpose:u.PREPASS_COLOR_TEXTURE_TYPE,type:u.TEXTURETYPE_HALF_FLOAT,format:u.TEXTUREFORMAT_RGBA,name:"prePass_Color"},{purpose:u.PREPASS_DEPTH_TEXTURE_TYPE,type:u.TEXTURETYPE_FLOAT,format:u.TEXTUREFORMAT_R,name:"prePass_Depth"},{purpose:u.PREPASS_NORMAL_TEXTURE_TYPE,type:u.TEXTURETYPE_HALF_FLOAT,format:u.TEXTUREFORMAT_RGBA,name:"prePass_Normal"},{purpose:u.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE,type:u.TEXTURETYPE_UNSIGNED_INT,format:u.TEXTUREFORMAT_RGBA,name:"prePass_Albedo"}],e}();Object.defineProperty(pn.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(e){e&&e.isSupported&&(this._prePassRenderer=e)},enumerable:!0,configurable:!0}),pn.prototype.enablePrePassRenderer=function(){return this._prePassRenderer||(this._prePassRenderer=new vR(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,ae.Error("PrePassRenderer needs WebGL 2 support.\nMaybe you tried to use the following features that need the PrePassRenderer :\n + Subsurface Scattering"))),this._prePassRenderer},pn.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};var yR=function(){function e(e){this.name=Vr.NAME_PREPASSRENDERER,this.scene=e}return e.prototype.register=function(){this.scene._beforeCameraDrawStage.registerStep(Vr.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(Vr.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(Vr.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(Vr.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(Vr.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(Vr.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(Vr.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(Vr.STEP_AFTERRENDERINGMESH_PREPASS,this,this._afterRenderingMeshStage)},e.prototype._beforeRenderTargetDraw=function(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._beforeDraw(void 0,t,i))},e.prototype._afterRenderTargetDraw=function(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&this.scene.prePassRenderer._afterDraw(t,i)},e.prototype._beforeRenderTargetClearStage=function(e){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(e._prePassRenderTarget||(e._prePassRenderTarget=this.scene.prePassRenderer._createRenderTarget(e.name+"_prePassRTT",e)),this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._clear())},e.prototype._beforeCameraDraw=function(e){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._beforeDraw(e))},e.prototype._afterCameraDraw=function(){this.scene.prePassRenderer&&this.scene.prePassRenderer._afterDraw()},e.prototype._beforeClearStage=function(){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._clear())},e.prototype._beforeRenderingMeshStage=function(e,t,i,r){if(r){var n=e.getScene();n.prePassRenderer&&n.prePassRenderer.bindAttachmentsForEffect(r,t)}},e.prototype._afterRenderingMeshStage=function(e){var t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()},e.prototype.rebuild=function(){},e.prototype.dispose=function(){this.scene.disablePrePassRenderer()},e}();vR._SceneComponentInitialization=function(e){var t=e._getComponent(Vr.NAME_PREPASSRENDERER);t||(t=new yR(e),e._addComponent(t))};li.IncludesShadersStore.fibonacci="#define rcp(x) 1./x\n#define GOLDEN_RATIO 1.618033988749895\n#define TWO_PI 6.2831855\nvec2 Golden2dSeq(int i,float n)\n{return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));}\nvec2 SampleDiskGolden(int i,int sampleCount)\n{vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}";li.IncludesShadersStore.diffusionProfile="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";li.ShadersStore.subSurfaceScatteringPixelShader="#include<fibonacci>\n#include<helperFunctions>\n#include<subSurfaceScatteringFunctions>\n#include<diffusionProfile>\nvarying vec2 vUV;uniform vec2 texelSize;uniform sampler2D textureSampler;uniform sampler2D irradianceSampler;uniform sampler2D depthSampler;uniform sampler2D albedoSampler;uniform vec2 viewportSize;uniform float metersPerUnit;const float LOG2_E=1.4426950408889634;const float SSS_PIXELS_PER_SAMPLE=4.;const int _SssSampleBudget=40;\n#define rcp(x) 1./x\n#define Sq(x) x*x\n#define SSS_BILATERAL_FILTER true\nvec3 EvalBurleyDiffusionProfile(float r,vec3 S)\n{vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); \nvec3 expSum=exp_13*(1.+exp_13*exp_13); \nreturn (S*rcp(8.*PI))*expSum; }\nvec2 SampleBurleyDiffusionProfile(float u,float rcpS)\n{u=1.-u; \nfloat g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); \nfloat p=(g*n)*n; \nfloat c=1.+p+n; \nfloat d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); \nfloat x=(3./LOG2_E)*log2(c)-d; \nfloat rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; \nreturn vec2(r,rcpPdf);}\nvec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf)\n{\n#ifndef SSS_BILATERAL_FILTER\nz=0.;\n#endif\nfloat r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf;\n#if SSS_CLAMP_ARTIFACT\nreturn clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0);\n#else\nreturn EvalBurleyDiffusionProfile(r,S)*area;\n#endif\n}\nvoid EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm,\nfloat phase,inout vec3 totalIrradiance,inout vec3 totalWeight)\n{float scale =rcp(float(n));float offset=rcp(float(n))*0.5;float sinPhase,cosPhase;sinPhase=sin(phase);cosPhase=cos(phase);vec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);float r=bdp.x;float rcpPdf=bdp.y;float phi=SampleDiskGolden(i,n).y;float sinPhi,cosPhi;sinPhi=sin(phi);cosPhi=cos(phi);float sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; \nfloat cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; \nvec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; \nfloat xy2;position=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;xy2 =r*r;vec4 textureSample=texture2D(irradianceSampler,position);float viewZ=texture2D(depthSampler,position).r;vec3 irradiance =textureSample.rgb;if (testLightingForSSS(textureSample.a))\n{float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;}\nelse\n{}}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);vec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;int diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));float centerDepth =0.;vec4 inputColor=texture2D(textureSampler,vUV);bool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest)\n{centerDepth=texture2D(depthSampler,vUV).r;}\nif (!passedStencilTest) { \ngl_FragColor=inputColor;return;}\nfloat distScale =1.;vec3 S =diffusionS[diffusionProfileIndex];float d =diffusionD[diffusionProfileIndex];float filterRadius=filterRadii[diffusionProfileIndex];vec2 centerPosNDC=vUV;vec2 cornerPosNDC=vUV+0.5*texelSize;vec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; \nvec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; \nfloat mmPerUnit =1000.*(metersPerUnit*rcp(distScale));float unitsPerMm=rcp(mmPerUnit);float unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);float pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;float filterArea =PI*Sq(filterRadius*pixelsPerMm);int sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));int sampleBudget=_SssSampleBudget;int texturingMode=0;vec3 albedo =texture2D(albedoSampler,vUV).rgb;if (distScale==0. || sampleCount<1)\n{\n#ifdef DEBUG_SSS_SAMPLES\nvec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return;\n#endif\ngl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;}\n#ifdef DEBUG_SSS_SAMPLES\nvec3 red =vec3(1.,0.,0.);vec3 blue=vec3(0.,0.,1.);gl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);return;\n#endif\nfloat phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); \nvec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; i<n; i++)\n{EvaluateSample(i,n,S,d,centerPosVS,mmPerUnit,pixelsPerMm,\nphase,totalIrradiance,totalWeight);}\ntotalWeight=max(totalWeight,HALF_MIN);gl_FragColor=vec4(inputColor.rgb+albedo*max(totalIrradiance/totalWeight,vec3(0.0)),1.);}";var bR=function(e){function t(t,i,r,n,o,a,s,l){void 0===n&&(n=null),void 0===l&&(l=u.TEXTURETYPE_UNSIGNED_INT);var c=e.call(this,t,"subSurfaceScattering",["texelSize","viewportSize","metersPerUnit"],["diffusionS","diffusionD","filterRadii","irradianceSampler","depthSampler","albedoSampler"],r,n,o||Ja.BILINEAR_SAMPLINGMODE,a,s,null,l,"postprocess",void 0,!0)||this;return c._scene=i,c.updateEffect(),c.onApplyObservable.add((function(e){if(i.prePassRenderer&&i.subSurfaceConfiguration){var t=c.texelSize;e.setFloat("metersPerUnit",i.subSurfaceConfiguration.metersPerUnit),e.setFloat2("texelSize",t.x,t.y),e.setTexture("irradianceSampler",i.prePassRenderer.getRenderTarget().textures[i.prePassRenderer.getIndex(u.PREPASS_IRRADIANCE_TEXTURE_TYPE)]),e.setTexture("depthSampler",i.prePassRenderer.getRenderTarget().textures[i.prePassRenderer.getIndex(u.PREPASS_DEPTH_TEXTURE_TYPE)]),e.setTexture("albedoSampler",i.prePassRenderer.getRenderTarget().textures[i.prePassRenderer.getIndex(u.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE)]),e.setFloat2("viewportSize",Math.tan(i.activeCamera.fov/2)*i.getEngine().getAspectRatio(i.activeCamera,!0),Math.tan(i.activeCamera.fov/2)),e.setArray3("diffusionS",i.subSurfaceConfiguration.ssDiffusionS),e.setArray("diffusionD",i.subSurfaceConfiguration.ssDiffusionD),e.setArray("filterRadii",i.subSurfaceConfiguration.ssFilterRadii)}else ae.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.")})),c}return m(t,e),t.prototype.getClassName=function(){return"SubSurfaceScatteringPostProcess"},t}(hl),TR=function(){function e(t){this._ssDiffusionS=[],this._ssFilterRadii=[],this._ssDiffusionD=[],this.enabled=!1,this.needsImageProcessing=!0,this.name=Vr.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[u.PREPASS_DEPTH_TEXTURE_TYPE,u.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE,u.PREPASS_COLOR_TEXTURE_TYPE,u.PREPASS_IRRADIANCE_TEXTURE_TYPE],this.addDiffusionProfile(new Z(1,1,1)),this._scene=t,e._SceneComponentInitialization(this._scene)}return Object.defineProperty(e.prototype,"ssDiffusionS",{get:function(){return this._ssDiffusionS},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"ssDiffusionD",{get:function(){return this._ssDiffusionD},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"ssFilterRadii",{get:function(){return this._ssFilterRadii},enumerable:!1,configurable:!0}),e.prototype.addDiffusionProfile=function(e){if(this.ssDiffusionD.length>=5)return ae.Error("You already reached the maximum number of diffusion profiles."),0;for(var t=0;t<this._ssDiffusionS.length/3;t++)if(this._ssDiffusionS[3*t]===e.r&&this._ssDiffusionS[3*t+1]===e.g&&this._ssDiffusionS[3*t+2]===e.b)return t;return this._ssDiffusionS.push(e.r,e.b,e.g),this._ssDiffusionD.push(Math.max(Math.max(e.r,e.b),e.g)),this._ssFilterRadii.push(this.getDiffusionProfileParameters(e)),this.ssDiffusionProfileColors.push(e),this._ssDiffusionD.length-1},e.prototype.createPostProcess=function(){return this.postProcess=new bR("subSurfaceScattering",this._scene,1,null,void 0,this._scene.getEngine()),this.postProcess.autoClear=!1,this.postProcess},e.prototype.clearAllDiffusionProfiles=function(){this._ssDiffusionD=[],this._ssDiffusionS=[],this._ssFilterRadii=[],this.ssDiffusionProfileColors=[]},e.prototype.dispose=function(){this.clearAllDiffusionProfiles(),this.postProcess&&this.postProcess.dispose()},e.prototype.getDiffusionProfileParameters=function(e){var t=Math.max(e.r,e.g,e.b);return this._sampleBurleyDiffusionProfile(.997,t)},e.prototype._sampleBurleyDiffusionProfile=function(e,t){var i=1+4*(e=1-e)*(2*e+Math.sqrt(1+4*e*e)),r=Math.pow(i,-1/3),n=1+i*r*r+r;return 3*Math.log(n/(4*e))*t},e._SceneComponentInitialization=function(e){throw He("SubSurfaceSceneComponent")},e}();c.AddParser(Vr.NAME_SUBSURFACE,(function(e,t){if(void 0!==e.ssDiffusionProfileColors&&null!==e.ssDiffusionProfileColors&&(t.enableSubSurfaceForPrePass(),t.subSurfaceConfiguration))for(var i=0,r=e.ssDiffusionProfileColors.length;i<r;i++){var n=e.ssDiffusionProfileColors[i];t.subSurfaceConfiguration.addDiffusionProfile(new Z(n.r,n.g,n.b))}})),Object.defineProperty(pn.prototype,"subSurfaceConfiguration",{get:function(){return this._subSurfaceConfiguration},set:function(e){e&&this.enablePrePassRenderer()&&(this._subSurfaceConfiguration=e)},enumerable:!0,configurable:!0}),pn.prototype.enableSubSurfaceForPrePass=function(){if(this._subSurfaceConfiguration)return this._subSurfaceConfiguration;var e=this.enablePrePassRenderer();return e?(this._subSurfaceConfiguration=new TR(this),e.addEffectConfiguration(this._subSurfaceConfiguration),this._subSurfaceConfiguration):null},pn.prototype.disableSubSurfaceForPrePass=function(){this._subSurfaceConfiguration&&(this._subSurfaceConfiguration.dispose(),this._subSurfaceConfiguration=null)};var ER=function(){function e(e){this.name=Vr.NAME_PREPASSRENDERER,this.scene=e}return e.prototype.register=function(){},e.prototype.serialize=function(e){if(this.scene.subSurfaceConfiguration){var t=this.scene.subSurfaceConfiguration.ssDiffusionProfileColors;e.ssDiffusionProfileColors=[];for(var i=0;i<t.length;i++)e.ssDiffusionProfileColors.push({r:t[i].r,g:t[i].g,b:t[i].b})}},e.prototype.addFromContainer=function(){},e.prototype.removeFromContainer=function(){this.scene.prePassRenderer&&this.scene.subSurfaceConfiguration&&this.scene.subSurfaceConfiguration.clearAllDiffusionProfiles()},e.prototype.rebuild=function(){},e.prototype.dispose=function(){},e}();TR._SceneComponentInitialization=function(e){var t=e._getComponent(Vr.NAME_SUBSURFACE);t||(t=new ER(e),e._addComponent(t))};li.ShadersStore.outlinePixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";li.ShadersStore.outlineVertexShader="attribute vec3 position;attribute vec3 normal;\n#include<bonesDeclaration>\n#include<bakedVertexAnimationDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#include<clipPlaneVertexDeclaration>\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include<morphTargetsVertexGlobal>\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\nvec3 offsetPosition=positionUpdated+(normalUpdated*offset);\n#include<instancesVertex>\n#include<bonesVertex>\n#include<bakedVertexAnimation>\nvec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<clipPlaneVertex>\n#include<logDepthVertex>\n}\n",pn.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new xR(this)),this._outlineRenderer},Object.defineProperty(Fa.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOutline=e},enumerable:!0,configurable:!0}),Object.defineProperty(Fa.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOverlay=e},enumerable:!0,configurable:!0});var SR,xR=function(){function e(e){this.name=Vr.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(var t=0;t<4;++t)this._passIdForDrawWrapper[t]=this._engine.createRenderPassId("Outline Renderer (".concat(t,")"))}return e.prototype.register=function(){this.scene._beforeRenderingMeshStage.registerStep(Vr.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(Vr.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)},e.prototype.rebuild=function(){},e.prototype.dispose=function(){for(var e=0;e<this._passIdForDrawWrapper.length;++e)this._engine.releaseRenderPassId(this._passIdForDrawWrapper[e])},e.prototype.render=function(e,t,i,r){void 0===i&&(i=!1),r=null!=r?r:this._passIdForDrawWrapper[0];var n=this.scene,o=n.getEngine(),a=o.getCaps().instancedArrays&&(null!==t.visibleInstances[e._id]&&void 0!==t.visibleInstances[e._id]||e.getRenderingMesh().hasThinInstances);if(this.isReady(e,a,r)){var s=e.getMesh(),l=s._internalAbstractMeshDataInfo._actAsRegularMesh?s:null,c=e.getRenderingMesh(),u=l||c,h=e.getMaterial();if(h&&n.activeCamera){var d=e._getDrawWrapper(r),p=ho.GetEffect(d);if(o.enableEffect(d),h.useLogarithmicDepth&&p.setFloat("logarithmicDepthConstant",2/(Math.log(n.activeCamera.maxZ+1)/Math.LN2)),p.setFloat("offset",i?0:c.outlineWidth),p.setColor4("color",i?c.overlayColor:c.outlineColor,i?c.overlayAlpha:h.alpha),p.setMatrix("viewProjection",n.getTransformMatrix()),p.setMatrix("world",u.getWorldMatrix()),c.useBones&&c.computeBonesUsingShaders&&c.skeleton&&p.setMatrices("mBones",c.skeleton.getTransformMatrices(c)),c.morphTargetManager&&c.morphTargetManager.isUsingTextureForTargets&&c.morphTargetManager._bind(p),$o(c,p),a||c._bind(e,p,h.fillMode),h&&h.needAlphaTesting()){var f=h.getAlphaTestTexture();f&&(p.setTexture("diffuseSampler",f),p.setMatrix("diffuseMatrix",f.getTextureMatrix()))}Ho(p,h,n),o.setZOffset(-this.zOffset),o.setZOffsetUnits(-this.zOffsetUnits),c._processRendering(u,e,p,h.fillMode,t,a,(function(e,t){p.setMatrix("world",t)})),o.setZOffset(0),o.setZOffsetUnits(0)}}},e.prototype.isReady=function(e,t,i){i=null!=i?i:this._passIdForDrawWrapper[0];var r=[],n=[Nr.PositionKind,Nr.NormalKind],o=e.getMesh(),a=e.getMaterial();if(!a)return!1;var s=o.getScene();a.needAlphaTesting()&&(r.push("#define ALPHATEST"),o.isVerticesDataPresent(Nr.UVKind)&&(n.push(Nr.UVKind),r.push("#define UV1")),o.isVerticesDataPresent(Nr.UV2Kind)&&(n.push(Nr.UV2Kind),r.push("#define UV2"))),a.useLogarithmicDepth&&r.push("#define LOGARITHMICDEPTH"),zo(a,s,r),o.useBones&&o.computeBonesUsingShaders?(n.push(Nr.MatricesIndicesKind),n.push(Nr.MatricesWeightsKind),o.numBoneInfluencers>4&&(n.push(Nr.MatricesIndicesExtraKind),n.push(Nr.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+o.numBoneInfluencers),r.push("#define BonesPerMesh "+(o.skeleton?o.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0");var l=o.morphTargetManager,c=0;l&&(c=l.numMaxInfluencers||l.numInfluencers)>0&&(r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+c),l.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),qo(n,o,c)),t&&(r.push("#define INSTANCES"),Jo(n),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES"));var u=e._getDrawWrapper(i,!0),h=u.defines,d=r.join("\n");if(h!==d){var p=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];Go(p),u.setEffect(this.scene.getEngine().createEffect("outline",n,p,["diffuseSampler","morphTargets"],d,void 0,void 0,void 0,{maxSimultaneousMorphTargets:c}),d)}return u.effect.isReady()},e.prototype._beforeRenderingMesh=function(t,i,r){if(this._savedDepthWrite=this._engine.getDepthWrite(),t.renderOutline){var n=i.getMaterial();n&&n.needAlphaBlendingForMesh(t)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(u.REPLACE),this._engine.setStencilFunction(u.ALWAYS),this._engine.setStencilMask(e._StencilReference),this._engine.setStencilFunctionReference(e._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(i,r,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(u.NOTEQUAL)),this._engine.setDepthWrite(!1),this.render(i,r,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),n&&n.needAlphaBlendingForMesh(t)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}},e.prototype._afterRenderingMesh=function(e,t,i){if(e.renderOverlay){var r=this._engine.getAlphaMode(),n=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(u.ALPHA_COMBINE),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(r),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=n}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))},e._StencilReference=4,e}(),AR=function(){function e(e){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new f,this.particleThicknessAlpha=.05,this._useVelocity=!1,this._scene=e,this._engine=e.getEngine(),this._effectsAreDirty=!0,this._depthEffectWrapper=null,this._thicknessEffectWrapper=null}return Object.defineProperty(e.prototype,"particleSize",{get:function(){return this._particleSize},set:function(e){e!==this._particleSize&&(this._particleSize=e,this.onParticleSizeChanged.notifyObservers(this))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useInstancing",{get:function(){return!this.indexBuffer},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useVelocity",{get:function(){return this._useVelocity},set:function(e){this._useVelocity!==e&&this._hasVelocity()&&(this._useVelocity=e,this._effectsAreDirty=!0)},enumerable:!1,configurable:!0}),e.prototype._hasVelocity=function(){var e;return!!(null===(e=this.vertexBuffers)||void 0===e?void 0:e.velocity)},Object.defineProperty(e.prototype,"indexBuffer",{get:function(){return null},enumerable:!1,configurable:!0}),e.prototype.getClassName=function(){return"FluidRenderingObject"},e.prototype._createEffects=function(){var e=["view","projection","particleRadius","size"],t=["position","offset"],i=[];this._effectsAreDirty=!1,this.useVelocity&&(t.push("velocity"),i.push("#define FLUIDRENDERING_VELOCITY")),this._scene.useRightHandedSystem&&i.push("#define FLUIDRENDERING_RHS"),this._depthEffectWrapper=new El({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new El({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleThickness",fragmentShader:"fluidRenderingParticleThickness",attributeNames:["position","offset"],uniformNames:e,samplerNames:[]})},e.prototype.isReady=function(){if(this._effectsAreDirty&&this._createEffects(),!this._depthEffectWrapper||!this._thicknessEffectWrapper)return!1;var e=this._depthEffectWrapper._drawWrapper.effect,t=this._thicknessEffectWrapper._drawWrapper.effect;return e.isReady()&&t.isReady()},e.prototype.renderDepthTexture=function(){var e=this.numParticles;if(this._depthEffectWrapper&&0!==e){var t=this._depthEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat2("size",this._particleSize,this._particleSize),i.setFloat("particleRadius",this._particleSize/2),this.useInstancing?this._engine.drawArraysType(u.MATERIAL_TriangleStripDrawMode,0,4,e):this._engine.drawElementsType(u.MATERIAL_TriangleFillMode,0,e)}},e.prototype.renderThicknessTexture=function(){var e=this.numParticles;if(this._thicknessEffectWrapper&&0!==e){var t=this._thicknessEffectWrapper._drawWrapper,i=t.effect;this._engine.setAlphaMode(u.ALPHA_ONEONE),this._engine.setDepthWrite(!1),this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat("particleAlpha",this.particleThicknessAlpha),i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(u.MATERIAL_TriangleStripDrawMode,0,4,e):this._engine.drawElementsType(u.MATERIAL_TriangleFillMode,0,e),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(u.ALPHA_DISABLE)}},e.prototype.renderDiffuseTexture=function(){},e.prototype.dispose=function(){var e,t;null===(e=this._depthEffectWrapper)||void 0===e||e.dispose(),null===(t=this._thicknessEffectWrapper)||void 0===t||t.dispose()},e}(),CR=function(e){function t(t,i){var r=e.call(this,t)||this;return r._useTrueRenderingForDiffuseTexture=!0,r._particleSystem=i,r._originalRender=i.render.bind(i),r._blendMode=i.blendMode,r._onBeforeDrawParticleObserver=null,r._updateInAnimate=r._particleSystem.updateInAnimate,r._particleSystem.updateInAnimate=!0,r._particleSystem.render=function(){return 0},r.particleSize=(i.minSize+i.maxSize)/2,r.useTrueRenderingForDiffuseTexture=!1,r}return m(t,e),Object.defineProperty(t.prototype,"particleSystem",{get:function(){return this._particleSystem},enumerable:!1,configurable:!0}),t.prototype.getClassName=function(){return"FluidRenderingObjectParticleSystem"},Object.defineProperty(t.prototype,"useTrueRenderingForDiffuseTexture",{get:function(){return this._useTrueRenderingForDiffuseTexture},set:function(e){var t=this;this._useTrueRenderingForDiffuseTexture!==e&&(this._useTrueRenderingForDiffuseTexture=e,e?(this._particleSystem.blendMode=this._blendMode,this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null):(this._particleSystem.blendMode=-1,this._onBeforeDrawParticleObserver=this._particleSystem.onBeforeDrawParticlesObservable.add((function(){t._engine.setAlphaMode(u.ALPHA_COMBINE)}))))},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"vertexBuffers",{get:function(){return this._particleSystem.vertexBuffers},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"indexBuffer",{get:function(){return this._particleSystem.indexBuffer},enumerable:!1,configurable:!0}),t.prototype.isReady=function(){return e.prototype.isReady.call(this)&&this._particleSystem.isReady()},Object.defineProperty(t.prototype,"numParticles",{get:function(){return this._particleSystem.getActiveCount()},enumerable:!1,configurable:!0}),t.prototype.renderDiffuseTexture=function(){this._originalRender()},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null,this._particleSystem.render=this._originalRender,this._particleSystem.blendMode=this._blendMode,this._particleSystem.updateInAnimate=this._updateInAnimate},t}(AR),RR=function(){function e(e,t,i,r,n,o,a,s,l,c,h,d,p,_){void 0===a&&(a=u.TEXTURETYPE_FLOAT),void 0===s&&(s=u.TEXTUREFORMAT_R),void 0===l&&(l=u.TEXTURETYPE_FLOAT),void 0===c&&(c=u.TEXTUREFORMAT_R),void 0===h&&(h=!1),void 0===d&&(d=null),void 0===p&&(p=!0),void 0===_&&(_=1),this.enableBlur=!0,this.blurSizeDivisor=1,this.blurFilterSize=7,this._blurNumIterations=3,this.blurMaxFilterSize=100,this.blurDepthScale=10,this.particleSize=.02,this.onDisposeObservable=new f,this._name=e,this._scene=t,this._camera=d,this._engine=t.getEngine(),this._width=i,this._height=r,this._blurTextureSizeX=n,this._blurTextureSizeY=o,this._textureType=a,this._textureFormat=s,this._blurTextureType=l,this._blurTextureFormat=c,this._useStandardBlur=h,this._generateDepthBuffer=p,this._samples=_,this._postProcessRunningIndex=0,this.enableBlur=0!==n&&0!==o,this._rt=null,this._texture=null,this._rtBlur=null,this._textureBlurred=null,this._blurPostProcesses=null}return Object.defineProperty(e.prototype,"blurNumIterations",{get:function(){return this._blurNumIterations},set:function(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,null!==this._blurPostProcesses)){var t=this._blurPostProcesses[0],i=this._blurPostProcesses[1];this._blurPostProcesses=[];for(var r=0;r<2*this._blurNumIterations;++r)this._blurPostProcesses[r]=1&r?i:t}},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"renderTarget",{get:function(){return this._rt},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"renderTargetBlur",{get:function(){return this._rtBlur},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"texture",{get:function(){return this._texture},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"textureBlur",{get:function(){return this._textureBlurred},enumerable:!1,configurable:!0}),e.prototype.initialize=function(){if(this.dispose(),this._createRenderTarget(),this.enableBlur&&this._texture){var e=this._createBlurPostProcesses(this._texture,this._blurTextureType,this._blurTextureFormat,this.blurSizeDivisor,this._name,this._useStandardBlur),t=e[0],i=e[1],r=e[2];this._rtBlur=t,this._textureBlurred=i,this._blurPostProcesses=r}},e.prototype.applyBlurPostProcesses=function(){this.enableBlur&&this._blurPostProcesses&&(this._postProcessRunningIndex=0,this._scene.postProcessManager.directRender(this._blurPostProcesses,this._rtBlur,!0),this._engine.unBindFramebuffer(this._rtBlur))},e.prototype._createRenderTarget=function(){this._rt=this._engine.createRenderTargetTexture({width:this._width,height:this._height},{generateMipMaps:!1,type:this._textureType,format:this._textureFormat,samplingMode:u.TEXTURE_NEAREST_SAMPLINGMODE,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:!1,samples:this._samples,label:"FluidRenderingRTT-".concat(this._name)});var e=this._rt.texture;e.incrementReferences(),this._texture=new Ja(null,this._scene),this._texture.name="rtt"+this._name,this._texture._texture=e,this._texture.wrapU=Ja.CLAMP_ADDRESSMODE,this._texture.wrapV=Ja.CLAMP_ADDRESSMODE,this._texture.anisotropicFilteringLevel=1},e.prototype._createBlurPostProcesses=function(e,t,i,r,n,o){var a=this;void 0===o&&(o=!1);var s=this._scene.getEngine(),l=new U(Math.floor(this._blurTextureSizeX/r),Math.floor(this._blurTextureSizeY/r)),c=t===u.TEXTURETYPE_FLOAT&&s.getCaps().textureFloatLinearFiltering||t===u.TEXTURETYPE_HALF_FLOAT&&s.getCaps().textureHalfFloatLinearFiltering,h=this._engine.createRenderTargetTexture({width:l.x,height:l.y},{generateMipMaps:!1,type:t,format:i,samplingMode:c?u.TEXTURE_BILINEAR_SAMPLINGMODE:u.TEXTURE_NEAREST_SAMPLINGMODE,generateDepthBuffer:!1,generateStencilBuffer:!1,samples:this._samples,label:"FluidRenderingRTTBlur-".concat(n)}),d=h.texture;d.incrementReferences();var p=new Ja(null,this._scene);if(p.name="rttBlurred"+n,p._texture=d,p.wrapU=Ja.CLAMP_ADDRESSMODE,p.wrapV=Ja.CLAMP_ADDRESSMODE,p.anisotropicFilteringLevel=1,o){var f=new hl("BilateralBlurX","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,u.TEXTURE_NEAREST_SAMPLINGMODE,s,!0,null,t,void 0,void 0,void 0,i);f.samples=this._samples,f.externalTextureSamplerBinding=!0,f.onApplyObservable.add((function(t){0===a._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",f.inputTexture.texture),t.setInt("filterSize",a.blurFilterSize),t.setFloat2("blurDir",1/a._blurTextureSizeX,0),a._postProcessRunningIndex++})),f.onSizeChangedObservable.add((function(){f._textures.forEach((function(e){e.texture.wrapU=Ja.CLAMP_ADDRESSMODE,e.texture.wrapV=Ja.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(f);var _=new hl("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,u.TEXTURE_NEAREST_SAMPLINGMODE,s,!0,null,t,void 0,void 0,void 0,i);_.samples=this._samples,_.onApplyObservable.add((function(e){e.setInt("filterSize",a.blurFilterSize),e.setFloat2("blurDir",0,1/a._blurTextureSizeY),a._postProcessRunningIndex++})),_.onSizeChangedObservable.add((function(){_._textures.forEach((function(e){e.texture.wrapU=Ja.CLAMP_ADDRESSMODE,e.texture.wrapV=Ja.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(_),f.autoClear=!1,_.autoClear=!1;for(var m=[],g=0;g<2*this._blurNumIterations;++g)m[g]=1&g?_:f;return[h,p,m]}var v=["maxFilterSize","blurDir","projectedParticleConstant","depthThreshold"],y=new hl("BilateralBlurX","fluidRenderingBilateralBlur",v,null,1,null,u.TEXTURE_NEAREST_SAMPLINGMODE,s,!0,null,t,void 0,void 0,void 0,i);y.samples=this._samples,y.externalTextureSamplerBinding=!0,y.onApplyObservable.add((function(t){0===a._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",y.inputTexture.texture),t.setInt("maxFilterSize",a.blurMaxFilterSize),t.setFloat2("blurDir",1/a._blurTextureSizeX,0),t.setFloat("projectedParticleConstant",a._getProjectedParticleConstant()),t.setFloat("depthThreshold",a._getDepthThreshold()),a._postProcessRunningIndex++})),y.onSizeChangedObservable.add((function(){y._textures.forEach((function(e){e.texture.wrapU=Ja.CLAMP_ADDRESSMODE,e.texture.wrapV=Ja.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(y);var b=new hl("BilateralBlurY","fluidRenderingBilateralBlur",v,null,1,null,u.TEXTURE_NEAREST_SAMPLINGMODE,s,!0,null,t,void 0,void 0,void 0,i);for(b.samples=this._samples,b.onApplyObservable.add((function(e){e.setInt("maxFilterSize",a.blurMaxFilterSize),e.setFloat2("blurDir",0,1/a._blurTextureSizeY),e.setFloat("projectedParticleConstant",a._getProjectedParticleConstant()),e.setFloat("depthThreshold",a._getDepthThreshold()),a._postProcessRunningIndex++})),b.onSizeChangedObservable.add((function(){b._textures.forEach((function(e){e.texture.wrapU=Ja.CLAMP_ADDRESSMODE,e.texture.wrapV=Ja.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(b),y.autoClear=!1,b.autoClear=!1,m=[],g=0;g<2*this._blurNumIterations;++g)m[g]=1&g?b:y;return[h,p,m]},e.prototype._fixReusablePostProcess=function(e){e.isReusable()&&(e.onActivateObservable.add((function(){e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})),e.onApplyObservable.add((function(){e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})))},e.prototype._getProjectedParticleConstant=function(){var e,t;return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan((null!==(t=null===(e=this._camera)||void 0===e?void 0:e.fov)&&void 0!==t?t:45*Math.PI/180)/2)},e.prototype._getDepthThreshold=function(){return this.particleSize/2*this.blurDepthScale},e.prototype.dispose=function(){var e,t,i,r;this.onDisposeObservable.hasObservers()&&this.onDisposeObservable.notifyObservers(this),null===(e=this._rt)||void 0===e||e.dispose(),this._rt=null,null===(t=this._texture)||void 0===t||t.dispose(),this._texture=null,null===(i=this._rtBlur)||void 0===i||i.dispose(),this._rtBlur=null,null===(r=this._textureBlurred)||void 0===r||r.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null},e}();!function(e){e[e.DepthTexture=0]="DepthTexture",e[e.DepthBlurredTexture=1]="DepthBlurredTexture",e[e.ThicknessTexture=2]="ThicknessTexture",e[e.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",e[e.DiffuseTexture=4]="DiffuseTexture",e[e.Normals=5]="Normals",e[e.DiffuseRendering=6]="DiffuseRendering"}(SR||(SR={}));var PR,IR=function(){function e(e,t){this._generateDiffuseTexture=!1,this.fluidColor=new Z(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new V(-2,-1,1).normalize(),this._debugFeature=SR.DepthBlurredTexture,this._debug=!1,this._enableBlurDepth=!0,this._blurDepthSizeDivisor=1,this._blurDepthFilterSize=7,this._blurDepthNumIterations=3,this._blurDepthMaxFilterSize=100,this._blurDepthDepthScale=10,this._enableBlurThickness=!0,this._blurThicknessSizeDivisor=1,this._blurThicknessFilterSize=5,this._blurThicknessNumIterations=1,this._useFixedThickness=!1,this._onUseVelocityChanged=new f,this._useVelocity=!1,this._depthMapSize=null,this._thicknessMapSize=null,this._diffuseMapSize=null,this._samples=1,this._compositeMode=!1,this._scene=e,this._engine=e.getEngine(),this._camera=null!=t?t:e.activeCamera,this._needInitialization=!0,this._bgDepthTexture=null,this._invProjectionMatrix=new z,this._depthClearColor=new J(1e6,1e6,1e6,1),this._thicknessClearColor=new J(0,0,0,1),this._depthRenderTarget=null,this._diffuseRenderTarget=null,this._thicknessRenderTarget=null,this._renderPostProcess=null}return Object.defineProperty(e.prototype,"needInitialization",{get:function(){return this._needInitialization},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"generateDiffuseTexture",{get:function(){return this._generateDiffuseTexture},set:function(e){this._generateDiffuseTexture!==e&&(this._generateDiffuseTexture=e,this._needInitialization=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"debugFeature",{get:function(){return this._debugFeature},set:function(e){this._debugFeature!==e&&(this._needInitialization=!0,this._debugFeature=e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"debug",{get:function(){return this._debug},set:function(e){this._debug!==e&&(this._debug=e,this._needInitialization=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"environmentMap",{get:function(){return this._environmentMap},set:function(e){this._environmentMap!==e&&(this._needInitialization=!0,this._environmentMap=e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"enableBlurDepth",{get:function(){return this._enableBlurDepth},set:function(e){this._enableBlurDepth!==e&&(this._enableBlurDepth=e,this._needInitialization=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"blurDepthSizeDivisor",{get:function(){return this._blurDepthSizeDivisor},set:function(e){this._blurDepthSizeDivisor!==e&&(this._blurDepthSizeDivisor=e,this._needInitialization=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"blurDepthFilterSize",{get:function(){return this._blurDepthFilterSize},set:function(e){this._blurDepthFilterSize!==e&&(this._blurDepthFilterSize=e,this._setBlurParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"blurDepthNumIterations",{get:function(){return this._blurDepthNumIterations},set:function(e){this._blurDepthNumIterations!==e&&(this._blurDepthNumIterations=e,this._setBlurParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"blurDepthMaxFilterSize",{get:function(){return this._blurDepthMaxFilterSize},set:function(e){this._blurDepthMaxFilterSize!==e&&(this._blurDepthMaxFilterSize=e,this._setBlurParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"blurDepthDepthScale",{get:function(){return this._blurDepthDepthScale},set:function(e){this._blurDepthDepthScale!==e&&(this._blurDepthDepthScale=e,this._setBlurParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"enableBlurThickness",{get:function(){return this._enableBlurThickness},set:function(e){this._enableBlurThickness!==e&&(this._enableBlurThickness=e,this._needInitialization=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"blurThicknessSizeDivisor",{get:function(){return this._blurThicknessSizeDivisor},set:function(e){this._blurThicknessSizeDivisor!==e&&(this._blurThicknessSizeDivisor=e,this._needInitialization=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"blurThicknessFilterSize",{get:function(){return this._blurThicknessFilterSize},set:function(e){this._blurThicknessFilterSize!==e&&(this._blurThicknessFilterSize=e,this._setBlurParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"blurThicknessNumIterations",{get:function(){return this._blurThicknessNumIterations},set:function(e){this._blurThicknessNumIterations!==e&&(this._blurThicknessNumIterations=e,this._setBlurParameters())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useFixedThickness",{get:function(){return this._useFixedThickness},set:function(e){this._useFixedThickness!==e&&(this._useFixedThickness=e,this._needInitialization=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useVelocity",{get:function(){return this._useVelocity},set:function(e){this._useVelocity!==e&&(this._useVelocity=e,this._needInitialization=!0,this._onUseVelocityChanged.notifyObservers(this))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"depthMapSize",{get:function(){return this._depthMapSize},set:function(e){this._depthMapSize!==e&&(this._depthMapSize=e,this._needInitialization=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"thicknessMapSize",{get:function(){return this._thicknessMapSize},set:function(e){this._thicknessMapSize!==e&&(this._thicknessMapSize=e,this._needInitialization=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"diffuseMapSize",{get:function(){return this._diffuseMapSize},set:function(e){this._diffuseMapSize!==e&&(this._diffuseMapSize=e,this._needInitialization=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"samples",{get:function(){return this._samples},set:function(e){this._samples!==e&&(this._samples=e,this._needInitialization=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"compositeMode",{get:function(){return this._compositeMode},set:function(e){this._compositeMode!==e&&(this._compositeMode=e,this._needInitialization=!0)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"camera",{get:function(){return this._camera},enumerable:!1,configurable:!0}),e.prototype._initialize=function(){var e,t,i;this.dispose(),this._needInitialization=!1;var r=null!==(e=this._depthMapSize)&&void 0!==e?e:this._engine.getRenderWidth(),n=null!==this._depthMapSize?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new RR("Depth",this._scene,r,n,r,n,u.TEXTURETYPE_FLOAT,u.TEXTUREFORMAT_RG,u.TEXTURETYPE_FLOAT,u.TEXTUREFORMAT_RG,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){var o=null!==(t=this._diffuseMapSize)&&void 0!==t?t:this._engine.getRenderWidth(),a=null!==this._diffuseMapSize?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new RR("Diffuse",this._scene,o,a,0,0,u.TEXTURETYPE_UNSIGNED_BYTE,u.TEXTUREFORMAT_RGBA,u.TEXTURETYPE_UNSIGNED_BYTE,u.TEXTUREFORMAT_RGBA,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}var s=null!==(i=this._thicknessMapSize)&&void 0!==i?i:this._engine.getRenderWidth(),l=null!==this._thicknessMapSize?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new RR("Thickness",this._scene,s,l,s,l,u.TEXTURETYPE_HALF_FLOAT,u.TEXTUREFORMAT_R,u.TEXTURETYPE_HALF_FLOAT,u.TEXTUREFORMAT_R,!0,this._camera,!1,this._samples),this._initializeRenderTarget(this._thicknessRenderTarget)),this._createLiquidRenderingPostProcess()},e.prototype._setBlurParameters=function(e){void 0===e&&(e=null),null!==e&&e!==this._depthRenderTarget||this._setBlurDepthParameters(),null!==e&&e!==this._thicknessRenderTarget||this._setBlurThicknessParameters()},e.prototype._setBlurDepthParameters=function(){this._depthRenderTarget&&(this._depthRenderTarget.blurFilterSize=this.blurDepthFilterSize,this._depthRenderTarget.blurMaxFilterSize=this.blurDepthMaxFilterSize,this._depthRenderTarget.blurNumIterations=this.blurDepthNumIterations,this._depthRenderTarget.blurDepthScale=this.blurDepthDepthScale)},e.prototype._setBlurThicknessParameters=function(){this._thicknessRenderTarget&&(this._thicknessRenderTarget.blurFilterSize=this.blurThicknessFilterSize,this._thicknessRenderTarget.blurNumIterations=this.blurThicknessNumIterations)},e.prototype._initializeRenderTarget=function(e){e!==this._diffuseRenderTarget&&(e.enableBlur=e===this._depthRenderTarget?this.enableBlurDepth:this.enableBlurThickness,e.blurSizeDivisor=e===this._depthRenderTarget?this.blurDepthSizeDivisor:this.blurThicknessSizeDivisor),this._setBlurParameters(e),e.initialize()},e.prototype._createLiquidRenderingPostProcess=function(){var e,t=this,i=this._scene.getEngine(),r=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],n=["depthSampler"],o=[];if(this.dispose(!0),this._camera){var a=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,s=new U(1/a.getSize().width,1/a.getSize().height);this._scene.useRightHandedSystem&&o.push("#define FLUIDRENDERING_RHS"),null!==this._environmentMap&&(null!==(e=this._environmentMap)&&void 0!==e?e:this._scene.environmentTexture)&&(n.push("reflectionSampler"),o.push("#define FLUIDRENDERING_ENVIRONMENT")),this._diffuseRenderTarget?(n.push("diffuseSampler"),o.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):r.push("diffuseColor"),this._useVelocity&&(n.push("velocitySampler"),o.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(r.push("thickness"),n.push("bgDepthSampler"),o.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(r.push("minimumThickness"),n.push("thicknessSampler")),this._compositeMode&&o.push("#define FLUIDRENDERING_COMPOSITE_MODE"),this._debug&&(o.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===SR.Normals?o.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===SR.DiffuseRendering?o.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(o.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),n.push("debugSampler"),this._debugFeature!==SR.DepthTexture&&this._debugFeature!==SR.DepthBlurredTexture||o.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new hl("FluidRendering","fluidRenderingRender",r,n,1,null,u.TEXTURE_BILINEAR_SAMPLINGMODE,i,!1,null,u.TEXTURETYPE_UNSIGNED_BYTE,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(o.join("\n")),this._renderPostProcess.samples=this._samples;var l=i,c=l.setTextureSampler;this._renderPostProcess.onApplyObservable.add((function(e){var i,r,n,o,a,u,h,d,p,f,_,m,g,v,y,b,T,E,S,x,A,C,R;if(t._invProjectionMatrix.copyFrom(t._scene.getProjectionMatrix()),t._invProjectionMatrix.invert(),c&&c.call(l,"textureSamplerSampler",t._renderPostProcess.inputTexture.texture),t._depthRenderTarget.enableBlur?(e.setTexture("depthSampler",t._depthRenderTarget.textureBlur),c&&c.call(l,"depthSamplerSampler",null!==(o=null===(n=t._depthRenderTarget.textureBlur)||void 0===n?void 0:n.getInternalTexture())&&void 0!==o?o:null)):(e.setTexture("depthSampler",t._depthRenderTarget.texture),c&&c.call(l,"depthSamplerSampler",null!==(r=null===(i=t._depthRenderTarget.texture)||void 0===i?void 0:i.getInternalTexture())&&void 0!==r?r:null)),t._diffuseRenderTarget?t._diffuseRenderTarget.enableBlur?(e.setTexture("diffuseSampler",t._diffuseRenderTarget.textureBlur),c&&c.call(l,"diffuseSamplerSampler",null!==(d=null===(h=t._diffuseRenderTarget.textureBlur)||void 0===h?void 0:h.getInternalTexture())&&void 0!==d?d:null)):(e.setTexture("diffuseSampler",t._diffuseRenderTarget.texture),c&&c.call(l,"diffuseSamplerSampler",null!==(u=null===(a=t._diffuseRenderTarget.texture)||void 0===a?void 0:a.getInternalTexture())&&void 0!==u?u:null)):e.setColor3("diffuseColor",t.fluidColor),t._useFixedThickness?(e.setFloat("thickness",t.minimumThickness),e._bindTexture("bgDepthSampler",t._bgDepthTexture),c&&c.call(l,"bgDepthSamplerSampler",null!==(p=t._bgDepthTexture)&&void 0!==p?p:null)):(t._thicknessRenderTarget.enableBlur?(e.setTexture("thicknessSampler",t._thicknessRenderTarget.textureBlur),c&&c.call(l,"thicknessSamplerSampler",null!==(g=null===(m=t._thicknessRenderTarget.textureBlur)||void 0===m?void 0:m.getInternalTexture())&&void 0!==g?g:null)):(e.setTexture("thicknessSampler",t._thicknessRenderTarget.texture),c&&c.call(l,"thicknessSamplerSampler",null!==(_=null===(f=t._thicknessRenderTarget.texture)||void 0===f?void 0:f.getInternalTexture())&&void 0!==_?_:null)),e.setFloat("minimumThickness",t.minimumThickness)),null!==t._environmentMap){var P=null!==(v=t._environmentMap)&&void 0!==v?v:t._scene.environmentTexture;P&&(e.setTexture("reflectionSampler",P),c&&c.call(l,"reflectionSamplerSampler",null!==(y=null==P?void 0:P.getInternalTexture())&&void 0!==y?y:null))}if(e.setMatrix("viewMatrix",t._scene.getViewMatrix()),e.setMatrix("invProjectionMatrix",t._invProjectionMatrix),e.setMatrix("projectionMatrix",t._scene.getProjectionMatrix()),e.setVector2("texelSize",s),e.setFloat("density",t.density),e.setFloat("refractionStrength",t.refractionStrength),e.setFloat("fresnelClamp",t.fresnelClamp),e.setFloat("specularPower",t.specularPower),e.setVector3("dirLight",t.dirLight),e.setFloat("cameraFar",t._camera.maxZ),t._debug){var I=null;switch(t._debugFeature){case SR.DepthTexture:I=t._depthRenderTarget.texture;break;case SR.DepthBlurredTexture:I=t._depthRenderTarget.enableBlur?t._depthRenderTarget.textureBlur:t._depthRenderTarget.texture;break;case SR.ThicknessTexture:I=null!==(T=null===(b=t._thicknessRenderTarget)||void 0===b?void 0:b.texture)&&void 0!==T?T:null;break;case SR.ThicknessBlurredTexture:I=(null===(E=t._thicknessRenderTarget)||void 0===E?void 0:E.enableBlur)?null!==(x=null===(S=t._thicknessRenderTarget)||void 0===S?void 0:S.textureBlur)&&void 0!==x?x:null:null!==(C=null===(A=t._thicknessRenderTarget)||void 0===A?void 0:A.texture)&&void 0!==C?C:null;break;case SR.DiffuseTexture:t._diffuseRenderTarget&&(I=t._diffuseRenderTarget.texture)}t._debugFeature!==SR.Normals&&(e.setTexture("debugSampler",I),c&&c.call(l,"debugSamplerSampler",null!==(R=null==I?void 0:I.getInternalTexture())&&void 0!==R?R:null))}}))}},e.prototype._clearTargets=function(){var e,t,i;(null===(e=this._depthRenderTarget)||void 0===e?void 0:e.renderTarget)&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),this._engine.clear(this._depthClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),(null===(t=this._diffuseRenderTarget)||void 0===t?void 0:t.renderTarget)&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(null===(i=this._thicknessRenderTarget)||void 0===i?void 0:i.renderTarget)&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!1,!1),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget))},e.prototype._render=function(e){var t,i,r,n,o,a;if(!this._needInitialization&&e.isReady()){var s=this._engine._currentRenderTarget;this._engine.setState(!1,void 0,void 0,void 0,!0),this._engine.setDepthBuffer(!0),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(u.ALPHA_DISABLE),(null===(t=this._depthRenderTarget)||void 0===t?void 0:t.renderTarget)&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),(null===(i=this._diffuseRenderTarget)||void 0===i?void 0:i.renderTarget)&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(null===(r=this._thicknessRenderTarget)||void 0===r?void 0:r.renderTarget)&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),null===(n=this._depthRenderTarget)||void 0===n||n.applyBlurPostProcesses(),null===(o=this._diffuseRenderTarget)||void 0===o||o.applyBlurPostProcesses(),null===(a=this._thicknessRenderTarget)||void 0===a||a.applyBlurPostProcesses(),s&&this._engine.bindFramebuffer(s)}},e.prototype.dispose=function(e){var t,i,r,n;void 0===e&&(e=!1),e||(null===(t=this._depthRenderTarget)||void 0===t||t.dispose(),this._depthRenderTarget=null,null===(i=this._diffuseRenderTarget)||void 0===i||i.dispose(),this._diffuseRenderTarget=null,null===(r=this._thicknessRenderTarget)||void 0===r||r.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),null===(n=this._renderPostProcess)||void 0===n||n.dispose(),this._renderPostProcess=null,this._needInitialization=!1},e}(),MR=function(e){function t(t,i,r){var n=e.call(this,t)||this;return n._numParticles=r,n._diffuseEffectWrapper=null,n._vertexBuffers={},n.addBuffers(i),n}return m(t,e),t.prototype.getClassName=function(){return"FluidRenderingObjectCustomParticles"},Object.defineProperty(t.prototype,"vertexBuffers",{get:function(){return this._vertexBuffers},enumerable:!1,configurable:!0}),t.prototype.addBuffers=function(e){for(var t in e){var i=void 0,r=!0;switch(t){case"velocity":i=3;break;case"offset":r=!1}this._vertexBuffers[t]=new Nr(this._engine,e[t],t,!0,!1,i,r)}},t.prototype._createEffects=function(){e.prototype._createEffects.call(this),this._diffuseEffectWrapper=new El({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:["position","offset","color"],uniformNames:["view","projection","size"],samplerNames:[]})},t.prototype.isReady=function(){var t,i;return this._vertexBuffers.offset||(this._vertexBuffers.offset=new Nr(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),e.prototype.isReady.call(this)&&null!==(i=null===(t=this._diffuseEffectWrapper)||void 0===t?void 0:t.effect.isReady())&&void 0!==i&&i},Object.defineProperty(t.prototype,"numParticles",{get:function(){return this._numParticles},enumerable:!1,configurable:!0}),t.prototype.setNumParticles=function(e){this._numParticles=e},t.prototype.renderDiffuseTexture=function(){var e=this.numParticles;if(this._diffuseEffectWrapper&&0!==e){var t=this._diffuseEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),null!==this._particleSize&&i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(u.MATERIAL_TriangleStripDrawMode,0,4,e):this._engine.drawElementsType(u.MATERIAL_TriangleFillMode,0,e)}},t.prototype.dispose=function(){var t;for(var i in e.prototype.dispose.call(this),null===(t=this._diffuseEffectWrapper)||void 0===t||t.dispose(),this._vertexBuffers)this._vertexBuffers[i].dispose();this._vertexBuffers={}},t}(AR);li.ShadersStore.copyTextureToTexturePixelShader="uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV;\n#include<helperFunctions>\nvoid main(void) \n{vec4 color=texture2D(textureSampler,vUV);\n#ifdef DEPTH_TEXTURE\ngl_FragDepth=color.r;\n#else\nif (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);}\ngl_FragColor=color;\n#endif\n}\n",function(e){e[e.None=0]="None",e[e.ToLinearSpace=1]="ToLinearSpace",e[e.ToGammaSpace=2]="ToGammaSpace"}(PR||(PR={}));var OR=function(){function e(e,t){void 0===t&&(t=!1);var i=this;this._engine=e,this._isDepthTexture=t,this._renderer=new Tl(e),this._effectWrapper=new El({engine:e,name:"CopyTextureToTexture",fragmentShader:"copyTextureToTexture",useShaderStore:!0,uniformNames:["conversion"],samplerNames:["textureSampler"],defines:t?["#define DEPTH_TEXTURE"]:[]}),this._effectWrapper.onApplyObservable.add((function(){t&&(e.setState(!1),e.setDepthBuffer(!0),e.depthCullingState.depthMask=!0,e.depthCullingState.depthFunc=u.ALWAYS),i._textureIsInternal(i._source)?i._effectWrapper.effect._bindTexture("textureSampler",i._source):i._effectWrapper.effect.setTexture("textureSampler",i._source),i._effectWrapper.effect.setFloat("conversion",i._conversion)}))}return e.prototype._textureIsInternal=function(e){return void 0===e.getInternalTexture},e.prototype.isReady=function(){return this._effectWrapper.effect.isReady()},e.prototype.copy=function(e,t,i){if(void 0===i&&(i=PR.None),!this.isReady())return!1;this._source=e,this._conversion=i;var r=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&r&&(this._engine.depthCullingState.depthFunc=r),!0},e.prototype.dispose=function(){this._effectWrapper.dispose(),this._renderer.dispose()},e}(),DR=function(){function e(e,t,i,r){void 0===r&&(r=1),this._engine=e,this._copyTextureToTexture=new OR(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:u.TEXTURETYPE_UNSIGNED_BYTE,format:u.TEXTUREFORMAT_R,samplingMode:u.TEXTURE_NEAREST_SAMPLINGMODE,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:r,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"}),this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil").label="FluidDepthTextureCopy".concat(t,"x").concat(i,"x").concat(r)}return Object.defineProperty(e.prototype,"depthRTWrapper",{get:function(){return this._depthRTWrapper},enumerable:!1,configurable:!0}),e.prototype.copy=function(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)},e.prototype.dispose=function(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()},e}();li.ShadersStore.fluidRenderingParticleDepthVertexShader="attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nattribute vec3 velocity;varying float velocityNorm;\n#endif\nvoid main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;viewPos=(view*vec4(position,1.0)).xyz;gl_Position=projection*vec4(viewPos+cornerPos,1.0);uv=offset;sphereRadius=size.x/2.0;\n#ifdef FLUIDRENDERING_VELOCITY\nvelocityNorm=length(velocity);\n#endif\n}\n";li.ShadersStore.fluidRenderingParticleDepthPixelShader="uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nvarying float velocityNorm;\n#endif\nvoid main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;normal.z=sqrt(1.0-r2);\n#ifndef FLUIDRENDERING_RHS\nnormal.z=-normal.z;\n#endif\nvec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos;\n#ifdef WEBGPU\ngl_FragDepth=clipSpacePos.z/clipSpacePos.w;\n#else\ngl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5;\n#endif\n#ifdef FLUIDRENDERING_RHS\nrealViewPos.z=-realViewPos.z;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nglFragColor=vec4(realViewPos.z,velocityNorm,0.,1.);\n#else\nglFragColor=vec4(realViewPos.z,0.,0.,1.);\n#endif\n}\n";li.ShadersStore.fluidRenderingParticleThicknessVertexShader="attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;}\n";li.ShadersStore.fluidRenderingParticleThicknessPixelShader="uniform float particleAlpha;varying vec2 uv;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;float thickness=sqrt(1.0-r2);glFragColor=vec4(vec3(particleAlpha*thickness),1.0);}\n";li.ShadersStore.fluidRenderingParticleDiffuseVertexShader="attribute vec3 position;attribute vec2 offset;attribute vec4 color;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;diffuseColor=color.rgb;}\n";li.ShadersStore.fluidRenderingParticleDiffusePixelShader="uniform float particleAlpha;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;glFragColor=vec4(diffuseColor,1.0);}\n";li.ShadersStore.fluidRenderingBilateralBlurPixelShader="uniform sampler2D textureSampler;uniform int maxFilterSize;uniform vec2 blurDir;uniform float projectedParticleConstant;uniform float depthThreshold;varying vec2 vUV;void main(void) {float depth=textureLod(textureSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(vec3(depth),1.);return;}\nint filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));float sigma=float(filterSize)/3.0;float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold/3.0;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sum=0.;float wsum=0.;float sumVel=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepthVel.r-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;}\nglFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);}\n";li.ShadersStore.fluidRenderingStandardBlurPixelShader="uniform sampler2D textureSampler;uniform int filterSize;uniform vec2 blurDir;varying vec2 vUV;void main(void) {vec4 s=textureLod(textureSampler,vUV,0.);if (s.r==0.) {glFragColor=vec4(0.,0.,0.,1.);return;}\nfloat sigma=float(filterSize)/3.0;float twoSigma2=2.0*sigma*sigma;vec4 sum=vec4(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);float w=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;}\nsum/=wsum;glFragColor=vec4(sum.rgb,1.);}\n";function NR(e){return!!e.particleSystem}function FR(e){return!!e.addBuffers}li.ShadersStore.fluidRenderingRenderPixelShader="/* disable_uniformity_analysis */\n#define IOR 1.333\n#define ETA 1.0/IOR\n#define F0 0.02\nuniform sampler2D textureSampler;uniform sampler2D depthSampler;\n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nuniform sampler2D diffuseSampler;\n#else\nuniform vec3 diffuseColor;\n#endif\n#ifdef FLUIDRENDERING_FIXED_THICKNESS\nuniform float thickness;uniform sampler2D bgDepthSampler;\n#else\nuniform float minimumThickness;uniform sampler2D thicknessSampler;\n#endif\n#ifdef FLUIDRENDERING_ENVIRONMENT\nuniform samplerCube reflectionSampler;\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nuniform sampler2D debugSampler;\n#endif\nuniform mat4 viewMatrix;uniform mat4 projectionMatrix;uniform mat4 invProjectionMatrix;uniform vec2 texelSize;uniform vec3 dirLight;uniform float cameraFar;uniform float density;uniform float refractionStrength;uniform float fresnelClamp;uniform float specularPower;varying vec2 vUV;vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {vec4 ndc;ndc.xy=texCoord*2.0-1.0;\n#ifdef FLUIDRENDERING_RHS\nndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#else\nndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#endif\nndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}\nvec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);}\nvoid main(void) {vec2 texCoord=vUV;\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nvec4 color=texture2D(debugSampler,texCoord);\n#ifdef FLUIDRENDERING_DEBUG_DEPTH\nglFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);}\n#else\nglFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);}\n#endif\nreturn;\n#endif\nvec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r;\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nfloat thickness=texture2D(thicknessSampler,texCoord).x;\n#else\nfloat bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5;\n#endif\nvec4 backColor=texture2D(textureSampler,texCoord);\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nif (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) {\n#else\nif (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) {\n#endif\n#ifdef FLUIDRENDERING_COMPOSITE_MODE\nglFragColor.rgb=backColor.rgb*backColor.a;glFragColor.a=backColor.a;\n#else\nglFragColor=backColor;\n#endif\nreturn;}\nvec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);vec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;vec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;vec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;}\nvec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;}\nvec3 normal=normalize(cross(ddy,ddx));\n#ifdef FLUIDRENDERING_RHS\nnormal=-normal;\n#endif\n#ifndef WEBGPU\nif(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);}\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL)\nglFragColor=vec4(normal*0.5+0.5,1.0);return;\n#endif\nvec3 rayDir=normalize(viewPos); \n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nvec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb;\n#endif\nvec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower);\n#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING\nfloat diffuse =max(0.0,dot(lightDir,normal))*1.0;glFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);return;\n#endif\nvec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);\n#ifdef FLUIDRENDERING_COMPOSITE_MODE\nif (transmitted.a==0.) transmitted.a=thickness;\n#endif\nvec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); \nvec3 refractionColor=transmitted.rgb*transmittance;\n#ifdef FLUIDRENDERING_ENVIRONMENT\nvec3 reflectionDir=reflect(rayDir,normal);vec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);float fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);vec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular;\n#else\nvec3 finalColor=refractionColor+specular;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nfloat velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0));\n#endif\nglFragColor=vec4(finalColor,transmitted.a);}\n",Object.defineProperty(pn.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(e){this._fluidRenderer=e},enumerable:!0,configurable:!0}),pn.prototype.enableFluidRenderer=function(){return this._fluidRenderer||(this._fluidRenderer=new wR(this)),this._fluidRenderer},pn.prototype.disableFluidRenderer=function(){var e;null===(e=this._fluidRenderer)||void 0===e||e.dispose(),this._fluidRenderer=null};var LR=function(){function e(e){this.name=Vr.NAME_FLUIDRENDERER,this.scene=e}return e.prototype.register=function(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(Vr.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(Vr.STEP_AFTERCAMERADRAW_FLUIDRENDERER,this,this._afterCameraDraw)},e.prototype._gatherActiveCameraRenderTargets=function(e){var t;null===(t=this.scene.fluidRenderer)||void 0===t||t._prepareRendering()},e.prototype._afterCameraDraw=function(e){var t;null===(t=this.scene.fluidRenderer)||void 0===t||t._render(e)},e.prototype.rebuild=function(){var e=this.scene.fluidRenderer;if(e){for(var t=new Set,i=0;i<e.renderObjects.length;++i){var r=e.renderObjects[i].object;if(FR(r)){var n=r.vertexBuffers;for(var o in n)t.add(n[o].getWrapperBuffer())}}t.forEach((function(e){e._rebuild()}))}},e.prototype.dispose=function(){this.scene.disableFluidRenderer()},e}(),wR=function(){function e(t){var i=this;this._scene=t,this._engine=t.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,e._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add((function(){i._initialize()}))}return e._SceneComponentInitialization=function(e){var t=e._getComponent(Vr.NAME_FLUIDRENDERER);t||(t=new LR(e),e._addComponent(t))},e.prototype.recreate=function(){this._sortRenderingObjects(),this._initialize()},e.prototype.getRenderObjectFromParticleSystem=function(e){var t=this._getParticleSystemIndex(e);return-1!==t?this.renderObjects[t]:null},e.prototype.addParticleSystem=function(e,t,i,r){var n=this,o=new CR(this._scene,e);o.onParticleSizeChanged.add((function(){return n._setParticleSizeForRenderTargets()})),i||(i=new IR(this._scene,r),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add((function(){return n._setUseVelocityForRenderObject()})),void 0!==t&&(i.generateDiffuseTexture=t);var a={object:o,targetRenderer:i};return this.renderObjects.push(a),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),a},e.prototype.addCustomParticles=function(e,t,i,r,n){var o=this,a=new MR(this._scene,e,t);a.onParticleSizeChanged.add((function(){return o._setParticleSizeForRenderTargets()})),r||(r=new IR(this._scene,n),this.targetRenderers.push(r)),r._onUseVelocityChanged.hasObservers()||r._onUseVelocityChanged.add((function(){return o._setUseVelocityForRenderObject()})),void 0!==i&&(r.generateDiffuseTexture=i);var s={object:a,targetRenderer:r};return this.renderObjects.push(s),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),s},e.prototype.removeRenderObject=function(e,t){void 0===t&&(t=!0);var i=this.renderObjects.indexOf(e);return-1!==i&&(e.object.dispose(),this.renderObjects.splice(i,1),t&&this._removeUnusedTargetRenderers()?this._initialize():this._setParticleSizeForRenderTargets(),!0)},e.prototype._sortRenderingObjects=function(){this.renderObjects.sort((function(e,t){return e.object.priority<t.object.priority?-1:e.object.priority>t.object.priority?1:0}))},e.prototype._removeUnusedTargetRenderers=function(){for(var e,t={},i=0;i<this.renderObjects.length;++i){var r=this.renderObjects[i].targetRenderer;t[this.targetRenderers.indexOf(r)]=!0}var n=!1,o=[];for(i=0;i<this.targetRenderers.length;++i)t[i]?o.push(this.targetRenderers[i]):(this.targetRenderers[i].dispose(),n=!0);return n&&(this.targetRenderers.length=0,(e=this.targetRenderers).push.apply(e,o)),n},e.prototype._getParticleSystemIndex=function(e){for(var t=0;t<this.renderObjects.length;++t){var i=this.renderObjects[t].object;if(NR(i)&&i.particleSystem===e)return t}return-1},e.prototype._initialize=function(){for(var e=this,t=0;t<this.targetRenderers.length;++t)this.targetRenderers[t].dispose();var i=new Map;for(t=0;t<this.targetRenderers.length;++t){var r=this.targetRenderers[t];r._initialize(),r.camera&&r._renderPostProcess&&((s=i.get(r.camera))||(s=[[],{}],i.set(r.camera,s)),s[0].push(r),r.camera.attachPostProcess(r._renderPostProcess,t))}for(var n=i.keys(),o=function(t){var r=t.value,n=i.get(r),o=r._getFirstPostProcess();if(!o)return"continue";var a=n[0],s=n[1];o.onSizeChangedObservable.add((function(){var t;o.inputTexture.depthStencilTexture||o.inputTexture.createDepthStencilTexture(0,!0,e._engine.isStencilEnable,a[0].samples,e._engine.isStencilEnable?u.TEXTUREFORMAT_DEPTH24_STENCIL8:u.TEXTUREFORMAT_DEPTH32_FLOAT,"PostProcessRTTDepthStencil-".concat(o.name));for(var i=0,r=a;i<r.length;i++){var n=null===(t=r[i]._thicknessRenderTarget)||void 0===t?void 0:t.renderTarget,l=null==n?void 0:n.texture;if(n&&l){var c=l.width+"_"+l.height,h=s[c];h||(h=s[c]=new DR(e._engine,l.width,l.height)),h.depthRTWrapper.shareDepth(n)}}}))},a=n.next();!0!==a.done;a=n.next())o(a);for(a=(n=this._cameras.keys()).next();!0!==a.done;a=n.next()){var s,l=a.value,c=(s=this._cameras.get(l))[1],h=i.get(l);if(h)for(var d in c)h[1][d]||c[d].dispose();else for(var p in c)c[p].dispose()}this._cameras.clear(),this._cameras=i,this._setParticleSizeForRenderTargets()},e.prototype._setParticleSizeForRenderTargets=function(){for(var e=new Map,t=0;t<this.renderObjects.length;++t){var i=this.renderObjects[t],r=e.get(i.targetRenderer);void 0===r&&(r=0),e.set(i.targetRenderer,Math.max(r,i.object.particleSize))}e.forEach((function(e,t){t._depthRenderTarget&&(t._depthRenderTarget.particleSize=e)}))},e.prototype._setUseVelocityForRenderObject=function(){for(var e=0,t=this.renderObjects;e<t.length;e++){var i=t[e];i.object.useVelocity=i.targetRenderer.useVelocity}},e.prototype._prepareRendering=function(){for(var e=0,t=this.targetRenderers;e<t.length;e++)if(t[e].needInitialization)return void this._initialize()},e.prototype._render=function(e){for(var t,i=0;i<this.targetRenderers.length;++i)e&&this.targetRenderers[i].camera!==e||this.targetRenderers[i]._clearTargets();for(var r=this._cameras.keys(),n=r.next();!0!==n.done;n=r.next()){var o=n.value,a=this._cameras.get(o);if(!e||o===e){var s=o._getFirstPostProcess();if(s){var l=null===(t=s.inputTexture)||void 0===t?void 0:t.depthStencilTexture;if(l){for(var c=a[0],u=a[1],h=0,d=c;h<d.length;h++)d[h]._bgDepthTexture=l;for(var p in u)u[p].copy(l)}}}}for(i=0;i<this.renderObjects.length;++i){var f=this.renderObjects[i];e&&f.targetRenderer.camera!==e||f.targetRenderer._render(f.object)}},e.prototype.dispose=function(){this._engine.onResizeObservable.remove(this._onEngineResizeObserver),this._onEngineResizeObserver=null;for(var e=0;e<this.renderObjects.length;++e)this.renderObjects[e].object.dispose();for(e=0;e<this.targetRenderers.length;++e)this.targetRenderers[e].dispose();this._cameras.forEach((function(e){var t=e[1];for(var i in t)t[i].dispose()})),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()},e}(),BR=function(){function e(e,t,i){void 0===i&&(i={width:512,height:512}),this._lightTransformMatrix=z.Identity(),this._enable=!1,this.forceUpdateLightParameters=!1,this._scene=e,this._light=t,this._textureDimensions=i,this._regularMatToMatWithPlugin=new Map,this._counters=[{name:"RSM Generation "+t.name,value:0}],this._createMultiRenderTarget(),this._recomputeLightTransformationMatrix(),this.enable=!0}return Object.defineProperty(e.prototype,"enable",{get:function(){return this._enable},set:function(e){this._enable!==e&&(this._enable=e,this._customRenderTarget(e))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"positionWorldTexture",{get:function(){return this._mrt.textures[0]},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"normalWorldTexture",{get:function(){return this._mrt.textures[1]},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"fluxTexture",{get:function(){return this._mrt.textures[2]},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"renderList",{get:function(){return this._mrt.renderList},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"light",{get:function(){return this._light},enumerable:!1,configurable:!0}),e.prototype.setTextureDimensions=function(e){var t=this,i=this._mrt.renderList;this._textureDimensions=e,this._disposeMultiRenderTarget(),this._createMultiRenderTarget(),null==i||i.forEach((function(e){t._addMeshToMRT(e)}))},e.prototype.addMesh=function(e){var t=this;e?this._addMeshToMRT(e):this._scene.meshes.forEach((function(e){t._addMeshToMRT(e)})),this._recomputeLightTransformationMatrix()},e.prototype.updateLightParameters=function(){this._recomputeLightTransformationMatrix()},Object.defineProperty(e.prototype,"lightTransformationMatrix",{get:function(){return this.forceUpdateLightParameters&&this.updateLightParameters(),this._lightTransformMatrix},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"countersGPU",{get:function(){return this._counters},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){this._disposeMultiRenderTarget()},e.prototype._createMultiRenderTarget=function(){var e,t,i=this,r=this._light.name,n=this._scene.getEngine().getCaps(),o=n.rg11b10ufColorRenderable?u.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:u.TEXTURETYPE_HALF_FLOAT,a=n.rg11b10ufColorRenderable?u.TEXTUREFORMAT_RGB:u.TEXTUREFORMAT_RGBA;this._mrt=new ky("RSMmrt_"+r,this._textureDimensions,3,this._scene,{types:[u.TEXTURETYPE_HALF_FLOAT,u.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV,o],samplingModes:[u.TEXTURE_BILINEAR_SAMPLINGMODE,u.TEXTURE_BILINEAR_SAMPLINGMODE,u.TEXTURE_BILINEAR_SAMPLINGMODE],generateMipMaps:!1,targetTypes:[u.TEXTURE_2D,u.TEXTURE_2D,u.TEXTURE_2D],formats:[u.TEXTUREFORMAT_RGBA,u.TEXTUREFORMAT_RGBA,a]},["RSMPosition_"+r,"RSMNormal_"+r,"RSMFlux_"+r]),this._mrt.renderList=[],this._mrt.clearColor=new J(0,0,0,1),this._mrt.noPrePassRenderer=!0;var s,l=this._scene.getEngine().supportsUniformBuffers;l&&(e=this._scene.createSceneUniformBuffer('Scene for RSM (light "'.concat(r,'")'))),this._mrt.onBeforeBindObservable.add((function(){t=i._scene.getSceneUniformBuffer(),s=i._light.shadowEnabled,i._light.shadowEnabled=!1})),this._mrt.onBeforeRenderObservable.add((function(t){e&&i._scene.setSceneUniformBuffer(e);var r=i._light.getViewMatrix(t),n=i._light.getProjectionMatrix(r||void 0,i._mrt.renderList||void 0);r&&n&&i._scene.setTransformMatrix(r,n),l&&(i._scene.getSceneUniformBuffer().unbindEffect(),i._scene.finalizeSceneUbo())})),this._mrt.onAfterUnbindObservable.add((function(){var r,n;e&&i._scene.setSceneUniformBuffer(t),i._scene.updateTransformMatrix(),i._light.shadowEnabled=s,i._counters[0].value=null!==(n=null===(r=i._mrt.renderTarget.gpuTimeInFrame)||void 0===r?void 0:r.counter.lastSecAverage)&&void 0!==n?n:0})),this._customRenderTarget(!0)},e.prototype._customRenderTarget=function(e){var t=this._scene.customRenderTargets.indexOf(this._mrt);e?-1===t&&this._scene.customRenderTargets.push(this._mrt):-1!==t&&this._scene.customRenderTargets.splice(t,1)},e.prototype._recomputeLightTransformationMatrix=function(){var e=this._light.getViewMatrix(),t=this._light.getProjectionMatrix(e||void 0,this._mrt.renderList||void 0);e&&t&&e.multiplyToRef(t,this._lightTransformMatrix)},e.prototype._addMeshToMRT=function(e){var t;null===(t=this._mrt.renderList)||void 0===t||t.push(e);var i=e.material;if(0!==e.getTotalVertices()&&i){var r=this._regularMatToMatWithPlugin.get(i);if(!r&&(r=i.clone("RSMCreate_"+i.name)||void 0)){Object.defineProperty(r,"canRenderToMRT",{get:function(){return!1},enumerable:!0,configurable:!0}),r.disableLighting=!0;var n=new VR(r);n.isEnabled=!0,n.light=this._light,this._regularMatToMatWithPlugin.set(i,r)}this._mrt.setMaterialForRendering(e,r)}},e.prototype._disposeMultiRenderTarget=function(){this._customRenderTarget(!1),this._mrt.dispose()},e}(),UR=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.RSMCREATE=!1,t.RSMCREATE_PROJTEXTURE=!1,t.RSMCREATE_LIGHT_IS_SPOT=!1,t}return m(t,e),t}(Gs),VR=function(e){function t(i){var r=e.call(this,i,t.Name,300,new UR)||this;return r._lightColor=new Z,r._hasProjectionTexture=!1,r._isEnabled=!1,r.isEnabled=!1,r._internalMarkAllSubMeshesAsTexturesDirty=i._dirtyCallbacks[u.MATERIAL_TextureDirtyFlag],r._varAlbedoName=i instanceof ig?"surfaceAlbedo":"baseColor.rgb",r}return m(t,e),t.prototype._markAllSubMeshesAsTexturesDirty=function(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()},t.prototype.prepareDefines=function(e){e.RSMCREATE=this._isEnabled,this._hasProjectionTexture=!1;var t=this.light.getTypeID()===wa.LIGHTTYPEID_SPOTLIGHT;if(t){var i=this.light;this._hasProjectionTexture=!!i.projectionTexture&&i.projectionTexture.isReady()}e.RSMCREATE_PROJTEXTURE=this._hasProjectionTexture,e.RSMCREATE_LIGHT_IS_SPOT=t},t.prototype.getClassName=function(){return"RSMCreatePluginMaterial"},t.prototype.getUniforms=function(){return{ubo:[{name:"rsmTextureProjectionMatrix",size:16,type:"mat4"},{name:"rsmSpotInfo",size:4,type:"vec4"},{name:"rsmLightColor",size:3,type:"vec3"},{name:"rsmLightPosition",size:3,type:"vec3"}],fragment:"#ifdef RSMCREATE\n uniform mat4 rsmTextureProjectionMatrix;\n uniform vec4 rsmSpotInfo;\n uniform vec3 rsmLightColor;\n uniform vec3 rsmLightPosition;\n #endif"}},t.prototype.getSamplers=function(e){e.push("rsmTextureProjectionSampler")},t.prototype.bindForSubMesh=function(e){if(this._isEnabled&&(this.light.diffuse.scaleToRef(this.light.getScaledIntensity(),this._lightColor),e.updateColor3("rsmLightColor",this._lightColor),this.light.getTypeID()===wa.LIGHTTYPEID_SPOTLIGHT)){var t=this.light;this._hasProjectionTexture&&(e.updateMatrix("rsmTextureProjectionMatrix",t.projectionTextureMatrix),e.setTexture("rsmTextureProjectionSampler",t.projectionTexture));var i=H.Vector3[0];t.computeTransformedInformation()?(e.updateFloat3("rsmLightPosition",this.light.transformedPosition.x,this.light.transformedPosition.y,this.light.transformedPosition.z),t.transformedDirection.normalizeToRef(i)):(e.updateFloat3("rsmLightPosition",this.light.position.x,this.light.position.y,this.light.position.z),t.direction.normalizeToRef(i)),e.updateFloat4("rsmSpotInfo",i.x,i.y,i.z,Math.cos(.5*t.angle))}},t.prototype.getCustomCode=function(e){return"vertex"===e?null:{CUSTOM_FRAGMENT_BEGIN:"\n #ifdef RSMCREATE\n #extension GL_EXT_draw_buffers : require\n #endif\n ",CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RSMCREATE\n #ifdef RSMCREATE_PROJTEXTURE\n uniform highp sampler2D rsmTextureProjectionSampler; \n #endif\n layout(location = 0) out highp vec4 glFragData[3];\n vec4 glFragColor;\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:"\n #ifdef RSMCREATE\n vec3 rsmColor = ".concat(this._varAlbedoName," * rsmLightColor;\n #ifdef RSMCREATE_PROJTEXTURE\n {\n vec4 strq = rsmTextureProjectionMatrix * vec4(vPositionW, 1.0);\n strq /= strq.w;\n rsmColor *= texture2D(rsmTextureProjectionSampler, strq.xy).rgb;\n }\n #endif\n #ifdef RSMCREATE_LIGHT_IS_SPOT\n {\n float cosAngle = max(0., dot(rsmSpotInfo.xyz, normalize(vPositionW - rsmLightPosition)));\n rsmColor = sign(cosAngle - rsmSpotInfo.w) * rsmColor;\n }\n #endif\n glFragData[0] = vec4(vPositionW, 1.);\n glFragData[1] = vec4(normalize(normalW) * 0.5 + 0.5, 1.);\n glFragData[2] = vec4(rsmColor, 1.);\n #endif\n ")}},t.Name="RSMCreate",v([Ie()],t.prototype,"light",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"isEnabled",void 0),t}(Nu);a("BABYLON.RSMCreatePluginMaterial",VR);var kR=function(){function e(e){this.numSamples=400,this.radius=.1,this.intensity=.1,this.edgeArtifactCorrection=.1,this.rotateSample=!0,this.noiseFactor=100,this.useFullTexture=!1,this.rsm=e}return e.prototype.dispose=function(){this.rsm.dispose()},e}();li.ShadersStore.bilateralBlurPixelShader="uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;}\nvec3 normal=textureLod(normalSampler,vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nfloat sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec3 sampleColor=textureLod(textureSampler,vUV+coords*blurDir,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords*blurDir,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords*blurDir,0.).rgb;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nfloat r=dot(coords,coords);float w=exp(-r/two_sigma2);float depthDelta=abs(sampleDepth-depth);float wd=step(depthDelta,depthThreshold);vec3 normalDelta=abs(sampleNormal-normal);float wn=step(normalDelta.x+normalDelta.y+normalDelta.z,normalThreshold);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}\nglFragColor=vec4(sum/wsum,1.);}\n";li.ShadersStore.bilateralBlurQualityPixelShader="uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;}\nvec3 normal=textureLod(normalSampler,vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nfloat sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {for (int y=-filterSize; y<=filterSize; ++y) {vec2 coords=vec2(x,y)*blurDir;vec3 sampleColor=textureLod(textureSampler,vUV+coords,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords,0.).rgb;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nfloat r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepth-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);float rNormal=abs(sampleNormal.x-normal.x)+abs(sampleNormal.y-normal.y)+abs(sampleNormal.z-normal.z);float wn=exp(-rNormal*rNormal/two_sigmaNormal2);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}}\nglFragColor=vec4(sum/wsum,1.);}\n";li.ShadersStore.rsmGlobalIlluminationPixelShader="/**\n* The implementation is an application of the formula found in http:\n* For better results,it also adds a random (noise) rotation to the RSM samples (the noise artifacts are easier to remove than the banding artifacts).\n*/\nprecision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform vec4 rsmInfo2;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux;uniform sampler2D rsmSamples;\n#ifdef TRANSFORM_NORMAL\nuniform mat4 invView;\n#endif\nfloat mod289(float x){return x-floor(x*(1.0/289.0))*289.0;}\nvec4 mod289(vec4 x){return x-floor(x*(1.0/289.0))*289.0;}\nvec4 perm(vec4 x){return mod289(((x*34.0)+1.0)*x);}\nfloat noise(vec3 p){vec3 a=floor(p);vec3 d=p-a;d=d*d*(3.0-2.0*d);vec4 b=a.xxyy+vec4(0.0,1.0,0.0,1.0);vec4 k1=perm(b.xyxy);vec4 k2=perm(k1.xyxy+b.zzww);vec4 c=k2+a.zzzz;vec4 k3=perm(c);vec4 k4=perm(c+1.0);vec4 o1=fract(k3*(1.0/41.0));vec4 o2=fract(k4*(1.0/41.0));vec4 o3=o2*d.z+o1*(1.0-d.z);vec2 o4=o3.yw*d.x+o3.xz*(1.0-d.x);return o4.y*d.y+o4.x*(1.0-d.y);}\nvec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);int numSamples=int(rsmInfo.x);float radius=rsmInfo.y;float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;float angle=noise(p*rsmInfo2.x);float c=cos(angle);float s=sin(angle);for (int i=0; i<numSamples; i++) {vec3 rsmSample=texelFetch(rsmSamples,ivec2(i,0),0).xyz;float weightSquare=rsmSample.z;if (rsmInfo2.y==1.0) rsmSample.xy=vec2(rsmSample.x*c+rsmSample.y*s,-rsmSample.x*s+rsmSample.y*c);vec2 uv=texRSM.xy+rsmSample.xy*radius;if (uv.x<0. || uv.x>1. || uv.y<0. || uv.y>1.) continue;vec3 vplPositionW=textureLod(rsmPositionW,uv,0.).xyz;vec3 vplNormalW=textureLod(rsmNormalW,uv,0.).xyz*2.0-1.0;vec3 vplFlux=textureLod(rsmFlux,uv,0.).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; \nfloat dist2=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*weightSquare*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}\nreturn clamp(indirectDiffuse*intensity,0.0,1.0);}\nvoid main(void) \n{vec3 positionW=texture2D(textureSampler,vUV).xyz;vec3 normalW=texture2D(normalSampler,vUV).xyz;\n#ifdef DECODE_NORMAL\nnormalW=normalW*2.0-1.0;\n#endif\n#ifdef TRANSFORM_NORMAL\nnormalW=(invView*vec4(normalW,0.)).xyz;\n#endif\ngl_FragColor.rgb=computeIndirect(positionW,normalW);gl_FragColor.a=1.0;}\n";li.ShadersStore.rsmFullGlobalIlluminationPixelShader="/**\n* The implementation is a direct application of the formula found in http:\n*/\nprecision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux;\n#ifdef TRANSFORM_NORMAL\nuniform mat4 invView;\n#endif\nvec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;int width=int(rsmInfo.x);int height=int(rsmInfo.y);for (int j=0; j<height; j++) {for (int i=0; i<width; i++) {ivec2 uv=ivec2(i,j);vec3 vplPositionW=texelFetch(rsmPositionW,uv,0).xyz;vec3 vplNormalW=texelFetch(rsmNormalW,uv,0).xyz*2.0-1.0;vec3 vplFlux=texelFetch(rsmFlux,uv,0).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; \nfloat dist2=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}}\nreturn clamp(indirectDiffuse*intensity,0.0,1.0);}\nvoid main(void) \n{vec3 positionW=texture2D(textureSampler,vUV).xyz;vec3 normalW=texture2D(normalSampler,vUV).xyz;\n#ifdef DECODE_NORMAL\nnormalW=normalW*2.0-1.0;\n#endif\n#ifdef TRANSFORM_NORMAL\nnormalW=(invView*vec4(normalW,0.)).xyz;\n#endif\ngl_FragColor.rgb=computeIndirect(positionW,normalW);gl_FragColor.a=1.0;}\n";var GR=function(){function e(e,t,i,r,n){void 0===i&&(i={width:256,height:256}),void 0===r&&(r=2048),void 0===n&&(n=u.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV);var o=this;this._giRSM=[],this._blurRTT=null,this._blurPostProcesses=null,this._blurXPostprocess=null,this._blurYPostprocess=null,this._upsamplingXPostprocess=null,this._upsamplingYPostprocess=null,this._ppGlobalIllumination=[],this._firstActivation=!0,this._geomBufferEnabled=!1,this._geomBufferEnablePosition=!1,this._tempMatrix=new z,this._enable=!1,this.pause=!1,this._enableBlur=!0,this._useQualityBlur=!1,this.blurDepthThreshold=.05,this.blurNormalThreshold=.25,this.blurKernel=12,this._forceFullSizeBlur=!1,this._useQualityUpsampling=!1,this.upsamplerKernel=6,this._showOnlyGI=!1,this._use32BitsDepthBuffer=!1,this._scene=e,this._engine=e.getEngine(),this._outputDimensions=t,this._giTextureDimensions=i,this._giTextureType=n,this._materialsWithRenderPlugin=[],this._maxSamples=r,this._debugLayer=new lv("debug layer",null,this._scene,!1),this._debugLayer.isEnabled=!1,this._counters=[],this._countersRTW=[],this.generateSampleTexture(r),this._drawPhaseObserver=this._scene.onBeforeDrawPhaseObservable.add((function(){var e,t,i,r,n=o._engine._currentRenderTarget,a=!1;if(o._enable){o.pause||(o._scene.postProcessManager.directRender(o._ppGlobalIllumination,o._ppGlobalIllumination[0].inputTexture),o._engine.unBindFramebuffer(o._ppGlobalIllumination[0].inputTexture,!0),o._engine.setAlphaMode(u.ALPHA_DISABLE),a=!0,o.enableBlur&&o._blurPostProcesses&&(o._scene.postProcessManager.directRender(o._blurPostProcesses,o._blurRTT.renderTarget,!0),o._engine.unBindFramebuffer(o._blurRTT.renderTarget,!0)));for(var s=0;s<o._counters.length;++s)for(var l=o._countersRTW[s],c=0;c<l.length;++c)0===c?o._counters[s].value=o.pause?0:null!==(t=null===(e=l[c].gpuTimeInFrame)||void 0===e?void 0:e.counter.lastSecAverage)&&void 0!==t?t:0:o.pause||(o._counters[s].value+=null!==(r=null===(i=l[c].gpuTimeInFrame)||void 0===i?void 0:i.counter.lastSecAverage)&&void 0!==r?r:0);o._scene.activeCamera&&o._engine.setViewport(o._scene.activeCamera.viewport)}a&&n&&o._engine.bindFramebuffer(n)}))}return Object.defineProperty(e.prototype,"enable",{get:function(){return this._enable},set:function(e){0===this._giRSM.length&&(e=!1),e!==this._enable&&(this._enable=e,this._debugLayer.isEnabled=this._showOnlyGI&&e,this._materialsWithRenderPlugin.forEach((function(t){t.pluginManager&&(t.pluginManager.getPlugin(WR.Name).isEnabled=e)})),this.recreateResources(!e))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"enableBlur",{get:function(){return this._enableBlur},set:function(e){e!==this._enableBlur&&(this._enableBlur=e,this.recreateResources())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useQualityBlur",{get:function(){return this._useQualityBlur},set:function(e){e!==this._useQualityBlur&&(this._useQualityBlur=e,this.recreateResources())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"fullSizeBlur",{get:function(){return this._forceFullSizeBlur},set:function(e){this._forceFullSizeBlur!==e&&(this._forceFullSizeBlur=e,this.recreateResources())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"useQualityUpsampling",{get:function(){return this._useQualityUpsampling},set:function(e){e!==this._useQualityUpsampling&&(this._useQualityUpsampling=e,this.recreateResources())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"showOnlyGI",{get:function(){return this._showOnlyGI},set:function(e){this._showOnlyGI!==e&&(this._showOnlyGI=e,this._debugLayer.isEnabled=e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"use32BitsDepthBuffer",{get:function(){return this._use32BitsDepthBuffer},set:function(e){this._use32BitsDepthBuffer!==e&&(this._use32BitsDepthBuffer=e,this.recreateResources())},enumerable:!1,configurable:!0}),e.prototype.setOutputDimensions=function(e){this._outputDimensions=e,this.recreateResources()},e.prototype.setGITextureDimensions=function(e){this._giTextureDimensions=e,this.recreateResources()},Object.defineProperty(e.prototype,"giTextureType",{get:function(){return this._giTextureType},set:function(e){this._giTextureType!==e&&(this._giTextureType=e,this.recreateResources())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"giRSM",{get:function(){return this._giRSM},enumerable:!1,configurable:!0}),e.prototype.addGIRSM=function(e){var t;Array.isArray(e)?(t=this._giRSM).push.apply(t,e):this._giRSM.push(e),this.recreateResources()},e.prototype.removeGIRSM=function(e){if(Array.isArray(e))for(var t=0;t<e.length;++t){var i;-1!==(i=this._giRSM.indexOf(e[t]))&&this._giRSM.splice(i,1)}else-1!==(i=this._giRSM.indexOf(e))&&this._giRSM.splice(i,1);0===this._giRSM.length?this.enable=!1:this.recreateResources()},e.prototype.addMaterial=function(e){var t=this;e?this._addGISupportToMaterial(e):this._scene.meshes.forEach((function(e){e.getTotalVertices()>0&&e.isEnabled()&&e.material&&t._addGISupportToMaterial(e.material)}))},Object.defineProperty(e.prototype,"countersGPU",{get:function(){return this._counters},enumerable:!1,configurable:!0}),e.prototype.recreateResources=function(e){void 0===e&&(e=!1),this._disposePostProcesses(e),this._createPostProcesses(),this._setPluginParameters()},e.prototype.generateSampleTexture=function(e){var t;null===(t=this._sampleTexture)||void 0===t||t.dispose(),this._maxSamples=e;for(var i=new Float32Array(4*this._maxSamples),r=0;r<this._maxSamples;r++){var n=Math.random(),o=Math.random(),a=n*Math.sin(2*Math.PI*o),s=n*Math.cos(2*Math.PI*o);i[4*r+0]=a,i[4*r+1]=s,i[4*r+2]=n*n,i[4*r+3]=1}this._sampleTexture=new is(i,this._maxSamples,1,u.TEXTUREFORMAT_RGBA,this._scene,!1,!1,u.TEXTURE_NEAREST_SAMPLINGMODE,u.TEXTURETYPE_FLOAT),this._sampleTexture.name="GIRSMSamples"},e.prototype.dispose=function(){var e;this._disposePostProcesses(!0),null===(e=this._debugLayer.texture)||void 0===e||e.dispose(),this._debugLayer.dispose(),this._scene.onBeforeDrawPhaseObservable.remove(this._drawPhaseObserver)},e.prototype._disposePostProcesses=function(e){var t,i,r,n,o;void 0===e&&(e=!1),null===(t=this._blurRTT)||void 0===t||t.dispose(),this._blurRTT=null,this._blurPostProcesses=[],null===(i=this._blurXPostprocess)||void 0===i||i.dispose(),this._blurXPostprocess=null,null===(r=this._blurYPostprocess)||void 0===r||r.dispose(),this._blurYPostprocess=null,null===(n=this._upsamplingXPostprocess)||void 0===n||n.dispose(),this._upsamplingXPostprocess=null,null===(o=this._upsamplingYPostprocess)||void 0===o||o.dispose(),this._upsamplingYPostprocess=null;for(var a=0,s=this._ppGlobalIllumination;a<s.length;a++)s[a].dispose();this._ppGlobalIllumination=[],e&&(this._geomBufferEnabled?(this._scene.enableGeometryBufferRenderer(),this._scene.geometryBufferRenderer.enablePosition=this._geomBufferEnablePosition):this._scene.disableGeometryBufferRenderer()),this._counters=[],this._countersRTW=[]},e.prototype._setPluginParameters=function(){var e=this;this._enable&&this._materialsWithRenderPlugin.forEach((function(t){if(t.pluginManager){var i=t.pluginManager.getPlugin(WR.Name);i.textureGIContrib=e.enableBlur?e._blurRTT.renderTarget.texture:e._ppGlobalIllumination[0].inputTexture.texture,i.outputTextureWidth=e._outputDimensions.width,i.outputTextureHeight=e._outputDimensions.height}}))},e.prototype._createPostProcesses=function(){var t,i,r,n=this;if(this._enable){var o=this._giTextureType===u.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV?u.TEXTUREFORMAT_RGB:u.TEXTUREFORMAT_RGBA;this._firstActivation&&(this._firstActivation=!1,this._geomBufferEnabled=!!this._scene.geometryBufferRenderer,this._geomBufferEnablePosition=null!==(i=null===(t=this._scene.geometryBufferRenderer)||void 0===t?void 0:t.enablePosition)&&void 0!==i&&i),this._geomBufferEnabled||this._scene.disableGeometryBufferRenderer();var a=this._scene.enableGeometryBufferRenderer(this._enableBlur?this._outputDimensions:this._giTextureDimensions,this._use32BitsDepthBuffer?u.TEXTUREFORMAT_DEPTH32_FLOAT:u.TEXTUREFORMAT_DEPTH16,e.GeometryBufferTextureTypesAndFormats);if(!a)throw new Error("Geometry buffer renderer is not supported but is required for GIRSMManager.");a.enablePosition=!0,this._geomBufferEnabled||(a.generateNormalsInWorldSpace=!0);var s=a.normalsAreUnsigned,l=a.generateNormalsInWorldSpace;this._counters.push({name:"Geometry buffer renderer",value:0}),this._countersRTW.push([this._scene.geometryBufferRenderer.getGBuffer().renderTarget]);var c="";s&&(c+="#define DECODE_NORMAL\n"),l||(c+="#define TRANSFORM_NORMAL\n");for(var h=function(e){var t=d._giRSM[e],i=t.rsm,r=new hl("RSMGlobalIllumination"+e,t.useFullTexture?"rsmFullGlobalIllumination":"rsmGlobalIllumination",g(g({},d._giTextureDimensions),{uniforms:["rsmLightMatrix","rsmInfo","rsmInfo2","invView"],samplers:["normalSampler","rsmPositionW","rsmNormalW","rsmFlux","rsmSamples"],defines:c,samplingMode:u.TEXTURE_BILINEAR_SAMPLINGMODE,engine:d._engine,textureType:d._giTextureType,textureFormat:o}));d._ppGlobalIllumination.push(r),0!==e&&(r.shareOutputWith(d._ppGlobalIllumination[0]),r.alphaMode=u.ALPHA_ADD),r.autoClear=!1,r.externalTextureSamplerBinding=!0,r.onApplyObservable.add((function(e){e.setTexture("textureSampler",a.getGBuffer().textures[a.getTextureIndex(BC.POSITION_TEXTURE_TYPE)]),e.setTexture("normalSampler",a.getGBuffer().textures[a.getTextureIndex(BC.NORMAL_TEXTURE_TYPE)]),e.setTexture("rsmPositionW",i.positionWorldTexture),e.setTexture("rsmNormalW",i.normalWorldTexture),e.setTexture("rsmFlux",i.fluxTexture),e.setMatrix("rsmLightMatrix",i.lightTransformationMatrix),t.useFullTexture?e.setFloat4("rsmInfo",i.fluxTexture.getInternalTexture().width,i.fluxTexture.getInternalTexture().height,t.intensity,t.edgeArtifactCorrection):(e.setTexture("rsmSamples",n._sampleTexture),e.setFloat4("rsmInfo",t.numSamples,t.radius,t.intensity,t.edgeArtifactCorrection),e.setFloat4("rsmInfo2",t.noiseFactor,t.rotateSample?1:0,i.fluxTexture.getInternalTexture().width,i.fluxTexture.getInternalTexture().height)),l||(n._tempMatrix.copyFrom(n._scene.activeCamera.getViewMatrix()),n._tempMatrix.invert(),e.setMatrix("invView",n._tempMatrix))}))},d=this,p=0;p<this._giRSM.length;++p)h(p);for(var f=0,_=this._ppGlobalIllumination;f<_.length;f++){var m=_[f];m.inputTexture||m.resize(this._giTextureDimensions.width,this._giTextureDimensions.height)}if(this._counters.push({name:"GI generation",value:0}),this._countersRTW.push([this._ppGlobalIllumination[0].inputTexture]),this._enableBlur){var v=this._forceFullSizeBlur?this._outputDimensions:this._giTextureDimensions;this._blurRTT=new Pl("GIRSMContribution",this._outputDimensions,this._scene,{type:this._giTextureType,format:o,generateDepthBuffer:!1}),this._blurRTT.wrapU=u.TEXTURE_CLAMP_ADDRESSMODE,this._blurRTT.wrapV=u.TEXTURE_CLAMP_ADDRESSMODE,this._blurRTT.updateSamplingMode(u.TEXTURE_NEAREST_SAMPLINGMODE),this._blurRTT.skipInitialClear=!0;var y=[];if(this._counters.push({name:"GI blur",value:0}),this._countersRTW.push(y),this._blurXPostprocess=new hl(this._useQualityBlur?"BilateralBlur":"BilateralBlurX",this._useQualityBlur?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:s?"#define DECODE_NORMAL":void 0,size:v,samplingMode:u.TEXTURE_BILINEAR_SAMPLINGMODE,engine:this._engine,textureType:this._giTextureType,textureFormat:o}),this._blurXPostprocess.onApplyObservable.add((function(e){e._bindTexture("textureSampler",n._ppGlobalIllumination[0].inputTexture.texture),e.setTexture("depthSampler",a.getGBuffer().textures[a.getTextureIndex(BC.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",a.getGBuffer().textures[a.getTextureIndex(BC.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",n.blurKernel),e.setFloat2("blurDir",1/n._giTextureDimensions.width,n._useQualityBlur?1/n._giTextureDimensions.height:0),e.setFloat("depthThreshold",n.blurDepthThreshold),e.setFloat("normalThreshold",n.blurNormalThreshold)})),this._blurXPostprocess.externalTextureSamplerBinding=!0,this._blurXPostprocess.autoClear=!1,this._useQualityBlur||(this._blurYPostprocess=new hl("BilateralBlurY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:s?"#define DECODE_NORMAL":void 0,size:v,samplingMode:u.TEXTURE_BILINEAR_SAMPLINGMODE,engine:this._engine,textureType:this._giTextureType,textureFormat:o}),this._blurYPostprocess.autoClear=!1,this._blurYPostprocess.onApplyObservable.add((function(e){e.setTexture("depthSampler",a.getGBuffer().textures[a.getTextureIndex(BC.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",a.getGBuffer().textures[a.getTextureIndex(BC.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",n.blurKernel),e.setFloat2("blurDir",0,1/n._giTextureDimensions.height),e.setFloat("depthThreshold",n.blurDepthThreshold),e.setFloat("normalThreshold",n.blurNormalThreshold)})),this._blurYPostprocess.resize(v.width,v.height),y.push(this._blurYPostprocess.inputTexture)),this._blurPostProcesses=[this._blurXPostprocess],this._blurYPostprocess&&this._blurPostProcesses.push(this._blurYPostprocess),this._giTextureDimensions.width>=this._outputDimensions.width&&this._giTextureDimensions.height>=this._outputDimensions.height||this._forceFullSizeBlur)y.push(this._blurRTT.renderTarget);else{var b=[];this._counters.push({name:"GI upsampling",value:0}),this._countersRTW.push(b),this._upsamplingXPostprocess=new hl(this._useQualityUpsampling?"BilateralUpsampling":"BilateralUpsamplingX",this._useQualityUpsampling?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:s?"#define DECODE_NORMAL":void 0,size:v,samplingMode:u.TEXTURE_BILINEAR_SAMPLINGMODE,engine:this._engine,textureType:this._giTextureType,textureFormat:o}),this._upsamplingXPostprocess.autoClear=!1,this._upsamplingXPostprocess.onApplyObservable.add((function(e){e.setTexture("depthSampler",a.getGBuffer().textures[a.getTextureIndex(BC.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",a.getGBuffer().textures[a.getTextureIndex(BC.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",n.upsamplerKernel),e.setFloat2("blurDir",1/n._outputDimensions.width,n._useQualityUpsampling?1/n._outputDimensions.height:0),e.setFloat("depthThreshold",n.blurDepthThreshold),e.setFloat("normalThreshold",n.blurNormalThreshold)})),this._upsamplingXPostprocess.resize(v.width,v.height),y.push(this._upsamplingXPostprocess.inputTexture),this.useQualityUpsampling||(this._upsamplingYPostprocess=new hl("BilateralUpsamplingY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:s?"#define DECODE_NORMAL":void 0,size:this._outputDimensions,samplingMode:u.TEXTURE_BILINEAR_SAMPLINGMODE,engine:this._engine,textureType:this._giTextureType,textureFormat:o}),this._upsamplingYPostprocess.autoClear=!1,this._upsamplingYPostprocess.onApplyObservable.add((function(e){e.setTexture("depthSampler",a.getGBuffer().textures[a.getTextureIndex(BC.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",a.getGBuffer().textures[a.getTextureIndex(BC.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",n.upsamplerKernel),e.setFloat2("blurDir",0,1/n._outputDimensions.height),e.setFloat("depthThreshold",n.blurDepthThreshold),e.setFloat("normalThreshold",n.blurNormalThreshold)})),this._upsamplingYPostprocess.resize(this._outputDimensions.width,this._outputDimensions.height),b.push(this._upsamplingYPostprocess.inputTexture)),b.push(this._blurRTT.renderTarget),this._blurPostProcesses.push(this._upsamplingXPostprocess),this._upsamplingYPostprocess&&this._blurPostProcesses.push(this._upsamplingYPostprocess)}}null===(r=this._debugLayer.texture)||void 0===r||r.dispose(),this._debugLayer.texture=new Ya(this._scene,this._enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture)}},e.prototype._addGISupportToMaterial=function(e){var t;if(!(null===(t=e.pluginManager)||void 0===t?void 0:t.getPlugin(WR.Name))){var i=new WR(e);this._enable&&this._ppGlobalIllumination.length>0&&(i.textureGIContrib=this._ppGlobalIllumination[0].inputTexture.texture,i.outputTextureWidth=this._outputDimensions.width,i.outputTextureHeight=this._outputDimensions.height),i.isEnabled=this._enable,this._materialsWithRenderPlugin.push(e)}},e.GeometryBufferTextureTypesAndFormats={0:{textureType:u.TEXTURETYPE_HALF_FLOAT,textureFormat:u.TEXTUREFORMAT_R},1:{textureType:u.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV,textureFormat:u.TEXTUREFORMAT_RGBA},2:{textureType:u.TEXTURETYPE_HALF_FLOAT,textureFormat:u.TEXTUREFORMAT_RGBA}},e}(),zR=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.RENDER_WITH_GIRSM=!1,t.RSMCREATE_PROJTEXTURE=!1,t}return m(t,e),t}(Gs),WR=function(e){function t(i){var r=e.call(this,i,t.Name,310,new zR)||this;return r._isEnabled=!1,r.isEnabled=!1,r._internalMarkAllSubMeshesAsTexturesDirty=i._dirtyCallbacks[u.MATERIAL_TextureDirtyFlag],r._isPBR=i instanceof ig,r}return m(t,e),t.prototype._markAllSubMeshesAsTexturesDirty=function(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()},t.prototype.prepareDefines=function(e){e.RENDER_WITH_GIRSM=this._isEnabled},t.prototype.getClassName=function(){return"GIRSMRenderPluginMaterial"},t.prototype.getUniforms=function(){return{ubo:[{name:"girsmTextureOutputSize",size:2,type:"vec2"}],fragment:"#ifdef RENDER_WITH_GIRSM\n uniform vec2 girsmTextureOutputSize;\n #endif"}},t.prototype.getSamplers=function(e){e.push("girsmTextureGIContrib")},t.prototype.bindForSubMesh=function(e){this._isEnabled&&(e.bindTexture("girsmTextureGIContrib",this.textureGIContrib),e.updateFloat2("girsmTextureOutputSize",this.outputTextureWidth,this.outputTextureHeight))},t.prototype.getCustomCode=function(e){var t={CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RENDER_WITH_GIRSM\n uniform sampler2D girsmTextureGIContrib;\n\n vec3 computeIndirect() {\n vec2 uv = gl_FragCoord.xy / girsmTextureOutputSize;\n return texture2D(girsmTextureGIContrib, uv).rgb;\n }\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:"\n #ifdef RENDER_WITH_GIRSM\n finalDiffuse += computeIndirect() * surfaceAlbedo.rgb;\n #endif\n "};return this._isPBR||(t.CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR="\n #ifdef RENDER_WITH_GIRSM\n color.rgb += computeIndirect() * baseColor.rgb;\n #endif\n "),"vertex"===e?null:t},t.Name="GIRSMRender",v([Ie()],t.prototype,"textureGIContrib",void 0),v([Ie()],t.prototype,"outputTextureWidth",void 0),v([Ie()],t.prototype,"outputTextureHeight",void 0),v([Ie(),Pe("_markAllSubMeshesAsTexturesDirty")],t.prototype,"isEnabled",void 0),t}(Nu);a("BABYLON.GIRSMRenderPluginMaterial",WR);li.ShadersStore.spriteMapPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nprecision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul;float mt;const float fdStep=1./4.;const float aFrameSteps=1./MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID){float fX=frameID/spriteCount;return mat4(\ntexture2D(frameMap,vec2(fX,0.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*1.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*2.),0.),\nvec4(0.)\n);}\nvoid main(){vec4 color=vec4(0.);vec2 tileUV=fract(tUV);\n#ifdef FLIPU\ntileUV.y=1.0-tileUV.y;\n#endif\nvec2 tileID=floor(tUV);vec2 sheetUnits=1./spriteMapSize;float spriteUnits=1./spriteCount;vec2 stageUnits=1./stageSize;for(int i=0; i<LAYERS; i++) {float frameID;\n#define LAYER_ID_SWITCH\nvec4 animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,0.),0.);if(animationData.y>0.) {mt=mod(time*animationData.z,1.0);for(float f=0.; f<MAX_ANIMATION_FRAMES; f++){if(animationData.y>mt){frameID=animationData.x;break;}\nanimationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);}}\nmat4 frameData=getFrameData(frameID+0.5);vec2 frameSize=(frameData[0].zw)/spriteMapSize;vec2 offset=frameData[0].xy*sheetUnits;vec2 ratio=frameData[2].xy/frameData[0].zw;if (frameData[2].z==1.){tileUV.xy=tileUV.yx;}\nvec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);if (i==0){color=nc;} else {float alpha=min(color.a+nc.a,1.0);vec3 mixed=mix(color.xyz,nc.xyz,nc.a);color=vec4(mixed,alpha);}}\ncolor.xyz*=colorMul;gl_FragColor=color;}";li.ShadersStore.spriteMapVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;varying vec2 stageUnits;varying vec2 levelUnits;varying vec2 tileID;uniform float time;uniform mat4 worldViewProjection;uniform vec2 outputSize;uniform vec2 stageSize;uniform vec2 spriteMapSize;uniform float stageScale;void main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; \ngl_Position=worldViewProjection*p;}";var HR,XR=function(){function e(e,t,i,r,n){var o=this;this.name=e,this.sprites=[],this.atlasJSON=t,this.sprites=this.atlasJSON.frames,this.spriteSheet=i,this.options=r,r.stageSize=r.stageSize||new U(1,1),r.outputSize=r.outputSize||r.stageSize,r.outputPosition=r.outputPosition||V.Zero(),r.outputRotation=r.outputRotation||V.Zero(),r.layerCount=r.layerCount||1,r.maxAnimationFrames=r.maxAnimationFrames||0,r.baseTile=r.baseTile||0,r.flipU=r.flipU||!1,r.colorMultiply=r.colorMultiply||new V(1,1,1),this._scene=n,this._frameMap=this._createFrameBuffer(),this._tileMaps=new Array;for(var a=0;a<r.layerCount;a++)this._tileMaps.push(this._createTileBuffer(null,a));this._animationMap=this._createTileAnimationBuffer(null);var s=[];s.push("#define LAYERS "+r.layerCount),r.flipU&&s.push("#define FLIPU"),s.push("#define MAX_ANIMATION_FRAMES ".concat(r.maxAnimationFrames,".0"));var l,c=Ei.ShadersStore.spriteMapPixelShader;if(n.getEngine()._features.supportSwitchCaseInShader){for(l="switch(i) {",a=0;a<r.layerCount;a++)l+="case "+a+" : frameID = texture(tileMaps["+a+"], (tileID + 0.5) / stageSize, 0.).x;",l+="break;";l+="}"}else{l="";for(a=0;a<r.layerCount;a++)l+="if (".concat(a," == i) { frameID = texture2D(tileMaps[").concat(a,"], (tileID + 0.5) / stageSize, 0.).x; }")}Ei.ShadersStore["spriteMap"+this.name+"PixelShader"]=c.replace("#define LAYER_ID_SWITCH",l),this._material=new ld("spriteMap:"+this.name,this._scene,{vertex:"spriteMap",fragment:"spriteMap"+this.name},{defines:s,attributes:["position","normal","uv"],uniforms:["worldViewProjection","time","stageSize","outputSize","spriteMapSize","spriteCount","time","colorMul","mousePosition","curTile","flipU"],samplers:["spriteSheet","frameMap","tileMaps","animationMap"],needAlphaBlending:!0}),this._time=0,this._material.setFloat("spriteCount",this.spriteCount),this._material.setVector2("stageSize",r.stageSize),this._material.setVector2("outputSize",r.outputSize),this._material.setTexture("spriteSheet",this.spriteSheet),this._material.setVector2("spriteMapSize",new U(1,1)),this._material.setVector3("colorMul",r.colorMultiply);var u=0,h=function(){o.spriteSheet&&o.spriteSheet.isReady()&&o.spriteSheet._texture?o._material.setVector2("spriteMapSize",new U(o.spriteSheet._texture.baseWidth||1,o.spriteSheet._texture.baseHeight||1)):u<100&&setTimeout((function(){u++,h()}),100)};h(),this._material.setVector3("colorMul",r.colorMultiply),this._material.setTexture("frameMap",this._frameMap),this._material.setTextureArray("tileMaps",this._tileMaps),this._material.setTexture("animationMap",this._animationMap),this._material.setFloat("time",this._time),this._output=fs(e+":output",{size:1,updatable:!0},n),this._output.scaling.x=r.outputSize.x,this._output.scaling.y=r.outputSize.y,this.position=r.outputPosition,this.rotation=r.outputRotation,this._scene.onBeforeRenderObservable.add((function(){o._time+=o._scene.getEngine().getDeltaTime(),o._material.setFloat("time",o._time)})),this._output.material=this._material}return Object.defineProperty(e.prototype,"spriteCount",{get:function(){return this.sprites.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"position",{get:function(){return this._output.position},set:function(e){this._output.position=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"rotation",{get:function(){return this._output.rotation},set:function(e){this._output.rotation=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"animationMap",{get:function(){return this._animationMap},set:function(e){var t=e._texture._bufferView,i=this._createTileAnimationBuffer(t);this._animationMap.dispose(),this._animationMap=i,this._material.setTexture("animationMap",this._animationMap)},enumerable:!1,configurable:!0}),e.prototype.getTileID=function(){var e=this.getMousePosition();return e.multiplyInPlace(this.options.stageSize||U.Zero()),e.x=Math.floor(e.x),e.y=Math.floor(e.y),e},e.prototype.getMousePosition=function(){var e=this._output,t=this._scene.pick(this._scene.pointerX,this._scene.pointerY,(function(t){return t===e}));return t&&t.hit&&t.getTextureCoordinates&&t.getTextureCoordinates()||new U(-1,-1)},e.prototype._createFrameBuffer=function(){for(var e=[],t=0;t<this.spriteCount;t++)e.push(0,0,0,0),e.push(0,0,0,0),e.push(0,0,0,0),e.push(0,0,0,0);for(t=0;t<this.spriteCount;t++){var i=this.sprites[t].frame,r=this.sprites[t].spriteSourceSize,n=this.sprites[t].sourceSize,o=this.sprites[t].rotated?1:0,a=this.sprites[t].trimmed?1:0;e[4*t]=i.x,e[4*t+1]=i.y,e[4*t+2]=i.w,e[4*t+3]=i.h,e[4*t+4*this.spriteCount]=r.x,e[4*t+1+4*this.spriteCount]=r.y,e[4*t+3+4*this.spriteCount]=r.h,e[4*t+8*this.spriteCount]=n.w,e[4*t+1+8*this.spriteCount]=n.h,e[4*t+2+8*this.spriteCount]=o,e[4*t+3+8*this.spriteCount]=a}var s=new Float32Array(e);return is.CreateRGBATexture(s,this.spriteCount,4,this._scene,!1,!1,Ja.NEAREST_NEAREST,Do.TEXTURETYPE_FLOAT)},e.prototype._createTileBuffer=function(e,t){void 0===t&&(t=0);var i=[],r=this.options.stageSize.y||0,n=this.options.stageSize.x||0;if(e)i=e;else{var o=this.options.baseTile;0!=t&&(o=0);for(var a=0;a<r;a++)for(var s=0;s<4*n;s+=4)i.push(o,0,0,0)}var l=new Float32Array(i);return is.CreateRGBATexture(l,n,r,this._scene,!1,!1,Ja.NEAREST_NEAREST,Do.TEXTURETYPE_FLOAT)},e.prototype.changeTiles=function(e,t,i){void 0===e&&(e=0),void 0===i&&(i=0);var r=this._tileMaps[e]._texture._bufferView;if(null!==r){var n=[];t instanceof U?n.push(t):n=t;for(var o=this.options.stageSize.x||0,a=0;a<n.length;a++){var s=n[a];s.x=Math.floor(s.x),s.y=Math.floor(s.y),r[4*s.x+s.y*(4*o)]=i}var l=this._createTileBuffer(r);this._tileMaps[e].dispose(),this._tileMaps[e]=l,this._material.setTextureArray("tileMap",this._tileMaps)}},e.prototype._createTileAnimationBuffer=function(e){var t,i=[];if(e)t=e;else{for(var r=0;r<this.spriteCount;r++){i.push(0,0,0,0);for(var n=1;n<(this.options.maxAnimationFrames||4);)i.push(0,0,0,0),n++}t=new Float32Array(i)}return is.CreateRGBATexture(t,this.spriteCount,this.options.maxAnimationFrames||4,this._scene,!1,!1,Ja.NEAREST_NEAREST,Do.TEXTURETYPE_FLOAT)},e.prototype.addAnimationToTile=function(e,t,i,r,n){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=1);var o=this._animationMap._texture._bufferView,a=4*e+4*this.spriteCount*t;if(o){o[a]=i,o[a+1]=r,o[a+2]=n;var s=this._createTileAnimationBuffer(o);this._animationMap.dispose(),this._animationMap=s,this._material.setTexture("animationMap",this._animationMap)}},e.prototype.saveTileMaps=function(){for(var e="",t=0;t<this._tileMaps.length;t++)t>0&&(e+="\n\r"),e+=this._tileMaps[t]._texture._bufferView.toString();var i=document.createElement("a");i.href="data:octet/stream;charset=utf-8,"+encodeURI(e),i.target="_blank",i.download=this.name+".tilemaps",i.click(),i.remove()},e.prototype.loadTileMaps=function(e){var t=this,i=new XMLHttpRequest;i.open("GET",e);var r=this.options.layerCount||0;i.onload=function(){for(var e=i.response.split("\n\r"),n=0;n<r;n++){var o=e[n].split(",").map(Number),a=t._createTileBuffer(o);t._tileMaps[n].dispose(),t._tileMaps[n]=a}t._material.setTextureArray("tileMap",t._tileMaps)},i.send()},e.prototype.dispose=function(){this._output.dispose(),this._material.dispose(),this._animationMap.dispose(),this._tileMaps.forEach((function(e){e.dispose()})),this._frameMap.dispose()},e}(),jR=function(e){function t(t,i,r,n,o,a,s){void 0===o&&(o=null),void 0===a&&(a=.01),void 0===s&&(s=Ja.TRILINEAR_SAMPLINGMODE);var l=e.call(this,t,i,r,64,n,a,s,!0,o)||this;return l.name=t,l}return m(t,e),t}(zv);!function(e){e[e.INIT=0]="INIT",e[e.RUNNING=1]="RUNNING",e[e.DONE=2]="DONE",e[e.ERROR=3]="ERROR"}(HR||(HR={}));var YR=function(){function e(e){this.name=e,this._isCompleted=!1,this._taskState=HR.INIT}return Object.defineProperty(e.prototype,"isCompleted",{get:function(){return this._isCompleted},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"taskState",{get:function(){return this._taskState},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"errorObject",{get:function(){return this._errorObject},enumerable:!1,configurable:!0}),e.prototype._setErrorObject=function(e,t){this._errorObject||(this._errorObject={message:e,exception:t})},e.prototype.run=function(e,t,i){var r=this;this._taskState=HR.RUNNING,this.runTask(e,(function(){r._onDoneCallback(t,i)}),(function(e,t){r._onErrorCallback(i,e,t)}))},e.prototype.runTask=function(e,t,i){throw new Error("runTask is not implemented")},e.prototype.reset=function(){this._taskState=HR.INIT},e.prototype._onErrorCallback=function(e,t,i){this._taskState=HR.ERROR,this._errorObject={message:t,exception:i},this.onError&&this.onError(this,t,i),e()},e.prototype._onDoneCallback=function(e,t){try{this._taskState=HR.DONE,this._isCompleted=!0,this.onSuccess&&this.onSuccess(this),e()}catch(e){this._onErrorCallback(t,"Task is done, error executing success callback(s)",e)}},e}(),KR=function(e,t,i){this.remainingCount=e,this.totalCount=t,this.task=i},QR=function(e){function t(t,i,r,n,o){var a=e.call(this,t)||this;return a.name=t,a.meshesNames=i,a.rootUrl=r,a.sceneFilename=n,a.extension=o,a}return m(t,e),t.prototype.runTask=function(e,t,i){var r=this;Ls.LoadAssetContainer(this.rootUrl,this.sceneFilename,e,(function(e){r.loadedContainer=e,r.loadedMeshes=e.meshes,r.loadedTransformNodes=e.transformNodes,r.loadedParticleSystems=e.particleSystems,r.loadedSkeletons=e.skeletons,r.loadedAnimationGroups=e.animationGroups,t()}),null,(function(e,t,r){i(t,r)}),this.extension)},t}(YR),qR=function(e){function t(t,i,r,n,o){var a=e.call(this,t)||this;return a.name=t,a.meshesNames=i,a.rootUrl=r,a.sceneFilename=n,a.extension=o,a}return m(t,e),t.prototype.runTask=function(e,t,i){var r=this;Ls.ImportMesh(this.meshesNames,this.rootUrl,this.sceneFilename,e,(function(e,i,n,o,a){r.loadedMeshes=e,r.loadedTransformNodes=a,r.loadedParticleSystems=i,r.loadedSkeletons=n,r.loadedAnimationGroups=o,t()}),null,(function(e,t,r){i(t,r)}),this.extension)},t}(YR),ZR=function(e){function t(t,i,r,n,o){var a=e.call(this,t)||this;return a.name=t,a.rootUrl=i,a.filename=r,a.targetConverter=n,a.extension=o,a}return m(t,e),t.prototype.runTask=function(e,t,i){var r=this,n=e.animatables.length,o=e.animationGroups.length;this.loadedAnimatables=[],this.loadedAnimationGroups=[],Ls.ImportAnimations(this.rootUrl,this.filename,e,!1,Os.NoSync,this.targetConverter,(function(){r.loadedAnimatables=e.animatables.slice(n),r.loadedAnimationGroups=e.animationGroups.slice(o),t()}),null,(function(e,t,r){i(t,r)}),this.extension)},t}(YR),JR=function(e){function t(t,i){var r=e.call(this,t)||this;return r.name=t,r.url=i,r}return m(t,e),t.prototype.runTask=function(e,t,i){var r=this;e._loadFile(this.url,(function(e){r.text=e,t()}),void 0,!1,!1,(function(e,t){e&&i(e.status+" "+e.statusText,t)}))},t}(YR),$R=function(e){function t(t,i){var r=e.call(this,t)||this;return r.name=t,r.url=i,r}return m(t,e),t.prototype.runTask=function(e,t,i){var r=this;e._loadFile(this.url,(function(e){r.data=e,t()}),void 0,!0,!0,(function(e,t){e&&i(e.status+" "+e.statusText,t)}))},t}(YR),eP=function(e){function t(t,i){var r=e.call(this,t)||this;return r.name=t,r.url=i,r}return m(t,e),t.prototype.runTask=function(e,t,i){var r=this,n=new Image;rr.SetCorsBehavior(this.url,n),n.onload=function(){r.image=n,t()},n.onerror=function(e){i("Error loading image",e)},n.src=this.url},t}(YR),tP=function(e){function t(t,i,r,n,o){void 0===n&&(n=!0),void 0===o&&(o=Ja.TRILINEAR_SAMPLINGMODE);var a=e.call(this,t)||this;return a.name=t,a.url=i,a.noMipmap=r,a.invertY=n,a.samplingMode=o,a}return m(t,e),t.prototype.runTask=function(e,t,i){this.texture=new Ja(this.url,e,this.noMipmap,this.invertY,this.samplingMode,(function(){t()}),(function(e,t){i(e,t)}))},t}(YR),iP=function(e){function t(t,i,r,n,o,a){var s=e.call(this,t)||this;return s.name=t,s.url=i,s.extensions=r,s.noMipmap=n,s.files=o,s.prefiltered=a,s}return m(t,e),t.prototype.runTask=function(e,t,i){this.texture=new Nm(this.url,e,this.extensions,this.noMipmap,this.files,(function(){t()}),(function(e,t){i(e,t)}),void 0,this.prefiltered)},t}(YR),rP=function(e){function t(t,i,r,n,o,a,s){void 0===n&&(n=!1),void 0===o&&(o=!0),void 0===a&&(a=!1),void 0===s&&(s=!1);var l=e.call(this,t)||this;return l.name=t,l.url=i,l.size=r,l.noMipmap=n,l.generateHarmonics=o,l.gammaSpace=a,l.reserved=s,l}return m(t,e),t.prototype.runTask=function(e,t,i){this.texture=new Pv(this.url,e,this.size,this.noMipmap,this.generateHarmonics,this.gammaSpace,this.reserved,(function(){t()}),(function(e,t){i(e,t)}))},t}(YR),nP=function(e){function t(t,i,r,n,o){void 0===n&&(n=!1),void 0===o&&(o=!0);var a=e.call(this,t)||this;return a.name=t,a.url=i,a.size=r,a.noMipmap=n,a.gammaSpace=o,a}return m(t,e),t.prototype.runTask=function(e,t,i){this.texture=new ay(this.url,e,this.size,this.noMipmap,this.gammaSpace,(function(){t()}),(function(e,t){i(e,t)}))},t}(YR),oP=function(){function e(e){this._isLoading=!1,this._tasks=new Array,this._waitingTasksCount=0,this._totalTasksCount=0,this.onTaskSuccessObservable=new f,this.onTaskErrorObservable=new f,this.onTasksDoneObservable=new f,this.onProgressObservable=new f,this.useDefaultLoadingScreen=!0,this.autoHideLoadingUI=!0,this._scene=e||M.LastCreatedScene}return e.prototype.addContainerTask=function(e,t,i,r,n){var o=new QR(e,t,i,r,n);return this._tasks.push(o),o},e.prototype.addMeshTask=function(e,t,i,r,n){var o=new qR(e,t,i,r,n);return this._tasks.push(o),o},e.prototype.addTextFileTask=function(e,t){var i=new JR(e,t);return this._tasks.push(i),i},e.prototype.addBinaryFileTask=function(e,t){var i=new $R(e,t);return this._tasks.push(i),i},e.prototype.addImageTask=function(e,t){var i=new eP(e,t);return this._tasks.push(i),i},e.prototype.addTextureTask=function(e,t,i,r,n){void 0===n&&(n=Ja.TRILINEAR_SAMPLINGMODE);var o=new tP(e,t,i,r,n);return this._tasks.push(o),o},e.prototype.addCubeTextureTask=function(e,t,i,r,n,o){var a=new iP(e,t,i,r,n,o);return this._tasks.push(a),a},e.prototype.addHDRCubeTextureTask=function(e,t,i,r,n,o,a){void 0===r&&(r=!1),void 0===n&&(n=!0),void 0===o&&(o=!1),void 0===a&&(a=!1);var s=new rP(e,t,i,r,n,o,a);return this._tasks.push(s),s},e.prototype.addEquiRectangularCubeTextureAssetTask=function(e,t,i,r,n){void 0===r&&(r=!1),void 0===n&&(n=!0);var o=new nP(e,t,i,r,n);return this._tasks.push(o),o},e.prototype.removeTask=function(e){var t=this._tasks.indexOf(e);t>-1&&this._tasks.splice(t,1)},e.prototype._decreaseWaitingTasksCount=function(e){this._waitingTasksCount--;try{this.onProgress&&this.onProgress(this._waitingTasksCount,this._totalTasksCount,e),this.onProgressObservable.notifyObservers(new KR(this._waitingTasksCount,this._totalTasksCount,e))}catch(e){ae.Error("Error running progress callbacks."),ae.Log(e)}if(0===this._waitingTasksCount){try{var t=this._tasks.slice();this.onFinish&&this.onFinish(t);for(var i=0,r=t;i<r.length;i++){var n=r[i];if(n.taskState===HR.DONE){var o=this._tasks.indexOf(n);o>-1&&this._tasks.splice(o,1)}}this.onTasksDoneObservable.notifyObservers(this._tasks)}catch(e){ae.Error("Error running tasks-done callbacks."),ae.Log(e)}this._isLoading=!1,this.autoHideLoadingUI&&this._scene.getEngine().hideLoadingUI()}},e.prototype._runTask=function(e){var t=this,i=function(i,r){e._setErrorObject(i,r),t.onTaskError?t.onTaskError(e):e.onError||ae.Error(t._formatTaskErrorMessage(e)),t.onTaskErrorObservable.notifyObservers(e),t._decreaseWaitingTasksCount(e)};e.run(this._scene,(function(){try{t.onTaskSuccess&&t.onTaskSuccess(e),t.onTaskSuccessObservable.notifyObservers(e),t._decreaseWaitingTasksCount(e)}catch(e){i("Error executing task success callbacks",e)}}),i)},e.prototype._formatTaskErrorMessage=function(e){var t="Unable to complete task "+e.name;return e.errorObject.message&&(t+=": ".concat(e.errorObject.message)),e.errorObject.exception&&(t+=": ".concat(e.errorObject.exception)),t},e.prototype.reset=function(){return this._isLoading=!1,this._tasks=new Array,this},e.prototype.load=function(){if(this._isLoading)return this;if(this._isLoading=!0,this._waitingTasksCount=this._tasks.length,this._totalTasksCount=this._tasks.length,0===this._waitingTasksCount)return this._isLoading=!1,this.onFinish&&this.onFinish(this._tasks),this.onTasksDoneObservable.notifyObservers(this._tasks),this;this.useDefaultLoadingScreen&&this._scene.getEngine().displayLoadingUI();for(var e=0;e<this._tasks.length;e++){var t=this._tasks[e];t.taskState===HR.INIT&&this._runTask(t)}return this},e.prototype.loadAsync=function(){var e=this;return new Promise((function(t,i){e._isLoading?t():(e.onTasksDoneObservable.addOnce((function(e){e&&e.length?i(e):t()})),e.load())}))},e}(),aP=function(){function e(){var e=this;this.promise=new Promise((function(t,i){e._resolve=t,e._reject=i}))}return Object.defineProperty(e.prototype,"resolve",{get:function(){return this._resolve},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"reject",{get:function(){return this._reject},enumerable:!1,configurable:!0}),e}(),sP=function(){function e(e,t){this._meshesOrigins=[],this._toCenterVectors=[],this._scaledDirection=new V(1,1,1),this._newPosition=V.Zero(),this._centerPosition=V.Zero(),this._meshes=e.slice(),t?this._centerMesh=t:this._setCenterMesh(),this._centerMesh.computeWorldMatrix(!0);var i=this._meshes.indexOf(this._centerMesh);i>=0&&this._meshes.splice(i,1),this._centerPosition=this._centerMesh.getAbsolutePosition().clone();for(var r=0;r<this._meshes.length;r++)if(this._meshes[r]){var n=this._meshes[r];this._meshesOrigins[r]=n.getAbsolutePosition().clone(),this._toCenterVectors[r]=V.Zero(),n.hasBoundingInfo&&this._centerMesh.hasBoundingInfo&&(n.computeWorldMatrix(!0),n.getBoundingInfo().boundingBox.centerWorld.subtractToRef(this._centerMesh.getBoundingInfo().boundingBox.centerWorld,this._toCenterVectors[r]))}}return e.prototype._setCenterMesh=function(){for(var e=V.Zero(),t=V.Zero(),i=Number.MAX_VALUE,r=0;r<this._meshes.length;r++)this._meshes[r]&&(o=(n=this._meshes[r]).getBoundingInfo())&&t.addInPlace(o.boundingBox.centerWorld);for(e=t.scale(1/this._meshes.length),r=0;r<this._meshes.length;r++){var n,o;if(this._meshes[r]&&(o=(n=this._meshes[r]).getBoundingInfo())){var a=o.boundingBox.centerWorld.subtract(e).lengthSquared();a<i&&(this._centerMesh=n,i=a)}}},e.prototype.getClassName=function(){return"MeshExploder"},e.prototype.getMeshes=function(){var e=this._meshes.slice();return e.unshift(this._centerMesh),e},e.prototype.explode=function(e){void 0===e&&(e=1);for(var t=0;t<this._meshes.length;t++)this._meshes[t]&&this._meshesOrigins[t]&&this._toCenterVectors[t]&&(this._toCenterVectors[t].scaleToRef(e,this._scaledDirection),this._meshesOrigins[t].addToRef(this._scaledDirection,this._newPosition),this._meshes[t].setAbsolutePosition(this._newPosition));this._centerMesh.setAbsolutePosition(this._centerPosition)},e}(),lP=function(){function e(e,t,i,r,n,o,a,s,l,c){void 0===c&&(c=!1);var u=this;this.useAppend=c,this.onProcessFileCallback=function(){return!0},this.displayLoadingUI=!0,this.loadAsync=function(e,t){return u.useAppend?Ls.AppendAsync("file:",e,u._currentScene,t):Ls.LoadAsync("file:",e,u._engine,t)},this._engine=e,this._currentScene=t,this._sceneLoadedCallback=i,this._progressCallback=r,this._additionalRenderLoopLogicCallback=n,this._textureLoadingCallback=o,this._startingProcessingFilesCallback=a,this._onReloadCallback=s,this._errorCallback=l}return Object.defineProperty(e,"FilesToLoad",{get:function(){return mt.FilesToLoad},enumerable:!1,configurable:!0}),e.prototype.monitorElementForDragNDrop=function(e){var t=this;e&&(this._elementToMonitor=e,this._dragEnterHandler=function(e){t._drag(e)},this._dragOverHandler=function(e){t._drag(e)},this._dropHandler=function(e){t._drop(e)},this._elementToMonitor.addEventListener("dragenter",this._dragEnterHandler,!1),this._elementToMonitor.addEventListener("dragover",this._dragOverHandler,!1),this._elementToMonitor.addEventListener("drop",this._dropHandler,!1))},Object.defineProperty(e.prototype,"filesToLoad",{get:function(){return this._filesToLoad},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){this._elementToMonitor&&(this._elementToMonitor.removeEventListener("dragenter",this._dragEnterHandler),this._elementToMonitor.removeEventListener("dragover",this._dragOverHandler),this._elementToMonitor.removeEventListener("drop",this._dropHandler))},e.prototype._renderFunction=function(){if(this._additionalRenderLoopLogicCallback&&this._additionalRenderLoopLogicCallback(),this._currentScene){if(this._textureLoadingCallback){var e=this._currentScene.getWaitingItemsCount();e>0&&this._textureLoadingCallback(e)}this._currentScene.render()}},e.prototype._drag=function(e){e.stopPropagation(),e.preventDefault()},e.prototype._drop=function(e){e.stopPropagation(),e.preventDefault(),this.loadFiles(e)},e.prototype._traverseFolder=function(e,t,i,r){var n=this,o=e.createReader(),a=e.fullPath.replace(/^\//,"").replace(/(.+?)\/?$/,"$1/");o.readEntries((function(e){i.count+=e.length;for(var o=0,s=e;o<s.length;o++){var l=s[o];l.isFile?l.file((function(e){e.correctName=a+e.name,t.push(e),0==--i.count&&r()})):l.isDirectory&&n._traverseFolder(l,t,i,r)}0==--i.count&&r()}))},e.prototype._processFiles=function(t){for(var i=this,r=0;r<t.length;r++){var n=t[r].correctName.toLowerCase(),o=n.split(".").pop();this.onProcessFileCallback(t[r],n,o,(function(e){return i._sceneFileToLoad=e}))&&(Ls.IsPluginForExtensionAvailable("."+o)&&(this._sceneFileToLoad=t[r]),e.FilesToLoad[n]=t[r])}},e.prototype.loadFiles=function(e){var t=this;if(e&&e.dataTransfer&&e.dataTransfer.files&&(this._filesToLoad=e.dataTransfer.files),e&&e.target&&e.target.files&&(this._filesToLoad=e.target.files),this._filesToLoad&&0!==this._filesToLoad.length&&(this._startingProcessingFilesCallback&&this._startingProcessingFilesCallback(this._filesToLoad),this._filesToLoad&&this._filesToLoad.length>0)){for(var i=[],r=[],n=e.dataTransfer?e.dataTransfer.items:null,o=0;o<this._filesToLoad.length;o++){var a=this._filesToLoad[o],s=a.name.toLowerCase(),l=void 0;if(a.correctName=s,n){var c=n[o];c.getAsEntry?l=c.getAsEntry():c.webkitGetAsEntry&&(l=c.webkitGetAsEntry())}l&&l.isDirectory?r.push(l):i.push(a)}if(0===r.length)this._processFiles(i),this._processReload();else for(var u={count:r.length},h=0,d=r;h<d.length;h++){var p=d[h];this._traverseFolder(p,i,u,(function(){t._processFiles(i),0===u.count&&t._processReload()}))}}},e.prototype._processReload=function(){this._onReloadCallback?this._onReloadCallback(this._sceneFileToLoad):this.reload()},e.prototype.reload=function(){var e=this;this._sceneFileToLoad?(this.useAppend||this._currentScene&&(ae.errorsCount>0&&ae.ClearLogCache(),this._engine.stopRenderLoop()),Ls.ShowLoadingScreen=!1,this.displayLoadingUI&&this._engine.displayLoadingUI(),this.loadAsync(this._sceneFileToLoad,this._progressCallback).then((function(t){e.useAppend?e.displayLoadingUI&&e._engine.hideLoadingUI():(e._currentScene&&e._currentScene.dispose(),e._currentScene=t,e._currentScene.executeWhenReady((function(){e.displayLoadingUI&&e._engine.hideLoadingUI(),e._engine.runRenderLoop((function(){e._renderFunction()}))}))),e._sceneLoadedCallback&&e._currentScene&&e._sceneLoadedCallback(e._sceneFileToLoad,e._currentScene)})).catch((function(t){e.displayLoadingUI&&e._engine.hideLoadingUI(),e._errorCallback&&e._errorCallback(e._sceneFileToLoad,e._currentScene,t.message)}))):ae.Error("Please provide a valid .babylon file.")},e}(),cP=function(){function e(){}return e.prototype.dispose=function(){if(this._observers&&this._observables)for(var e=0;e<this._observers.length;e++)this._observables[e].remove(this._observers[e]);this._observers=null,this._observables=null},e.Watch=function(t,i,r,n){void 0===r&&(r=-1),void 0===n&&(n=null);var o=new e;o._observers=new Array,o._observables=t;for(var a=0,s=t;a<s.length;a++){var l=s[a].add(i,r,!1,n);l&&o._observers.push(l)}return o},e}();f.prototype.notifyObserversWithPromise=function(e,t,i,r,n){return void 0===t&&(t=-1),y(this,void 0,void 0,(function(){var o,a,s=this;return b(this,(function(l){switch(l.label){case 0:return o=Promise.resolve(e),this.observers.length?((a=this._eventState).mask=t,a.target=i,a.currentTarget=r,a.skipNextObservers=!1,a.userInfo=n,this.observers.forEach((function(i){a.skipNextObservers||i._willBeUnregistered||i.mask&t&&(o=i.scope?o.then((function(t){return a.lastReturnValue=t,i.callback.apply(i.scope,[e,a])})):o.then((function(t){return a.lastReturnValue=t,i.callback(e,a)})),i.unregisterOnNextCall&&s._deferUnregister(i))})),[4,o]):[2,o];case 1:return l.sent(),[2,e]}}))}))};var uP=function(){function e(e){void 0===e&&(e=0),this.priority=e}return e.prototype.getDescription=function(){return""},e.prototype.apply=function(e,t){return!0},e}(),hP=function(e){function t(t,i,r){void 0===t&&(t=0),void 0===i&&(i=1024),void 0===r&&(r=.5);var n=e.call(this,t)||this;return n.priority=t,n.maximumSize=i,n.step=r,n}return m(t,e),t.prototype.getDescription=function(){return"Reducing render target texture size to "+this.maximumSize},t.prototype.apply=function(e,t){for(var i=!0,r=0;r<e.textures.length;r++){var n=e.textures[r];if(n.canRescale&&!n.getContext){var o=n.getSize();Math.max(o.width,o.height)>this.maximumSize&&(n.scale(this.step),i=!1)}}return i},t}(uP),dP=function(e){function t(t,i,r){void 0===t&&(t=0),void 0===i&&(i=2),void 0===r&&(r=.25);var n=e.call(this,t)||this;return n.priority=t,n.maximumScale=i,n.step=r,n._currentScale=-1,n._directionOffset=1,n}return m(t,e),t.prototype.getDescription=function(){return"Setting hardware scaling level to "+this._currentScale},t.prototype.apply=function(e,t){return-1===this._currentScale&&(this._currentScale=e.getEngine().getHardwareScalingLevel(),this._currentScale>this.maximumScale&&(this._directionOffset=-1)),this._currentScale+=this._directionOffset*this.step,e.getEngine().setHardwareScalingLevel(this._currentScale),1===this._directionOffset?this._currentScale>=this.maximumScale:this._currentScale<=this.maximumScale},t}(uP),pP=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.prototype.getDescription=function(){return"Turning shadows on/off"},t.prototype.apply=function(e,t){return e.shadowsEnabled=t.isInImprovementMode,!0},t}(uP),fP=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.prototype.getDescription=function(){return"Turning post-processes on/off"},t.prototype.apply=function(e,t){return e.postProcessesEnabled=t.isInImprovementMode,!0},t}(uP),_P=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.prototype.getDescription=function(){return"Turning lens flares on/off"},t.prototype.apply=function(e,t){return e.lensFlaresEnabled=t.isInImprovementMode,!0},t}(uP),mP=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.prototype.getDescription=function(){return this.onGetDescription?this.onGetDescription():"Running user defined callback"},t.prototype.apply=function(e,t){return!this.onApply||this.onApply(e,t)},t}(uP),gP=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.prototype.getDescription=function(){return"Turning particles on/off"},t.prototype.apply=function(e,t){return e.particlesEnabled=t.isInImprovementMode,!0},t}(uP),vP=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.prototype.getDescription=function(){return"Turning render targets off"},t.prototype.apply=function(e,t){return e.renderTargetsEnabled=t.isInImprovementMode,!0},t}(uP),yP=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._canBeMerged=function(e){if(!(e instanceof Fa))return!1;var t=e;return!(t.isDisposed()||!t.isVisible||!t.isEnabled()||t.instances.length>0||t.skeleton||t.hasLODLevels||0===t.getTotalVertices())},t}return m(t,e),Object.defineProperty(t,"UpdateSelectionTree",{get:function(){return t._UpdateSelectionTree},set:function(e){t._UpdateSelectionTree=e},enumerable:!1,configurable:!0}),t.prototype.getDescription=function(){return"Merging similar meshes together"},t.prototype.apply=function(e,i,r){for(var n=e.meshes.slice(0),o=n.length,a=0;a<o;a++){var s=[],l=n[a];if(this._canBeMerged(l)){s.push(l);for(var c=a+1;c<o;c++){var u=n[c];this._canBeMerged(u)&&u.material===l.material&&u.checkCollisions===l.checkCollisions&&(s.push(u),o--,n.splice(c,1),c--)}s.length<2||Fa.MergeMeshes(s,void 0,!0)}}var h=e;return h.createOrUpdateSelectionOctree&&(null!=r?r&&h.createOrUpdateSelectionOctree():t.UpdateSelectionTree&&h.createOrUpdateSelectionOctree()),!0},t._UpdateSelectionTree=!1,t}(uP),bP=function(){function e(e,t){void 0===e&&(e=60),void 0===t&&(t=2e3),this.targetFrameRate=e,this.trackerDuration=t,this.optimizations=[]}return e.prototype.addOptimization=function(e){return this.optimizations.push(e),this},e.prototype.addCustomOptimization=function(e,t,i){void 0===i&&(i=0);var r=new mP(i);return r.onApply=e,r.onGetDescription=t,this.optimizations.push(r),this},e.LowDegradationAllowed=function(t){var i=new e(t),r=0;return i.addOptimization(new yP(r)),i.addOptimization(new pP(r)),i.addOptimization(new _P(r)),r++,i.addOptimization(new fP(r)),i.addOptimization(new gP(r)),r++,i.addOptimization(new hP(r,1024)),i},e.ModerateDegradationAllowed=function(t){var i=new e(t),r=0;return i.addOptimization(new yP(r)),i.addOptimization(new pP(r)),i.addOptimization(new _P(r)),r++,i.addOptimization(new fP(r)),i.addOptimization(new gP(r)),r++,i.addOptimization(new hP(r,512)),r++,i.addOptimization(new vP(r)),r++,i.addOptimization(new dP(r,2)),i},e.HighDegradationAllowed=function(t){var i=new e(t),r=0;return i.addOptimization(new yP(r)),i.addOptimization(new pP(r)),i.addOptimization(new _P(r)),r++,i.addOptimization(new fP(r)),i.addOptimization(new gP(r)),r++,i.addOptimization(new hP(r,256)),r++,i.addOptimization(new vP(r)),r++,i.addOptimization(new dP(r,4)),i},e}(),TP=function(){function e(e,t,i,r){void 0===i&&(i=!0),void 0===r&&(r=!1);var n=this;if(this._isRunning=!1,this._currentPriorityLevel=0,this._targetFrameRate=60,this._trackerDuration=2e3,this._currentFrameRate=0,this._improvementMode=!1,this.onSuccessObservable=new f,this.onNewOptimizationAppliedObservable=new f,this.onFailureObservable=new f,this._options=t||new bP,this._options.targetFrameRate&&(this._targetFrameRate=this._options.targetFrameRate),this._options.trackerDuration&&(this._trackerDuration=this._options.trackerDuration),i)for(var o=0,a=0,s=this._options.optimizations;a<s.length;a++)s[a].priority=o++;this._improvementMode=r,this._scene=e||M.LastCreatedScene,this._sceneDisposeObserver=this._scene.onDisposeObservable.add((function(){n._sceneDisposeObserver=null,n.dispose()}))}return Object.defineProperty(e.prototype,"isInImprovementMode",{get:function(){return this._improvementMode},set:function(e){this._improvementMode=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentPriorityLevel",{get:function(){return this._currentPriorityLevel},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentFrameRate",{get:function(){return this._currentFrameRate},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"targetFrameRate",{get:function(){return this._targetFrameRate},set:function(e){this._targetFrameRate=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"trackerDuration",{get:function(){return this._trackerDuration},set:function(e){this._trackerDuration=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"optimizations",{get:function(){return this._options.optimizations},enumerable:!1,configurable:!0}),e.prototype.stop=function(){this._isRunning=!1},e.prototype.reset=function(){this._currentPriorityLevel=0},e.prototype.start=function(){var e=this;this._isRunning||(this._isRunning=!0,this._scene.executeWhenReady((function(){setTimeout((function(){e._checkCurrentState()}),e._trackerDuration)})))},e.prototype._checkCurrentState=function(){var e=this;if(this._isRunning){var t=this._scene,i=this._options;if(this._currentFrameRate=Math.round(t.getEngine().getFps()),this._improvementMode&&this._currentFrameRate<=this._targetFrameRate||!this._improvementMode&&this._currentFrameRate>=this._targetFrameRate)return this._isRunning=!1,void this.onSuccessObservable.notifyObservers(this);for(var r=!0,n=!0,o=0;o<i.optimizations.length;o++){var a=i.optimizations[o];a.priority===this._currentPriorityLevel&&(n=!1,r=r&&a.apply(t,this),this.onNewOptimizationAppliedObservable.notifyObservers(a))}if(n)return this._isRunning=!1,void this.onFailureObservable.notifyObservers(this);r&&this._currentPriorityLevel++,t.executeWhenReady((function(){setTimeout((function(){e._checkCurrentState()}),e._trackerDuration)}))}},e.prototype.dispose=function(){this.stop(),this.onSuccessObservable.clear(),this.onFailureObservable.clear(),this.onNewOptimizationAppliedObservable.clear(),this._sceneDisposeObserver&&this._scene.onDisposeObservable.remove(this._sceneDisposeObserver)},e.OptimizeAsync=function(t,i,r,n){var o=new e(t,i||bP.ModerateDegradationAllowed(),!1);return r&&o.onSuccessObservable.add((function(){r()})),n&&o.onFailureObservable.add((function(){n()})),o.start(),o},e}(),EP=[],SP=function(e,t){e.doNotSerialize||(t.vertexData.push(e.serializeVerticeData()),EP[e.id]=!0)},xP=function(e,t){var i={},r=e._geometry;return r&&(e.getScene().getGeometryById(r.id)||SP(r,t.geometries)),e.serialize&&e.serialize(i),i},AP=function(){function e(){}return e.ClearCache=function(){EP=[]},e.Serialize=function(t){return e._Serialize(t)},e._Serialize=function(t,i){void 0===i&&(i=!0);var r,n,o,a={};if(i&&!t.getEngine()._features.supportSyncTextureRead&&Ja.ForceSerializeBuffers&&ae.Warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),e.ClearCache(),a.useDelayedTextureLoading=t.useDelayedTextureLoading,a.autoClear=t.autoClear,a.clearColor=t.clearColor.asArray(),a.ambientColor=t.ambientColor.asArray(),a.gravity=t.gravity.asArray(),a.collisionsEnabled=t.collisionsEnabled,a.useRightHandedSystem=t.useRightHandedSystem,void 0!==t.fogMode&&null!==t.fogMode&&(a.fogMode=t.fogMode),void 0!==t.fogColor&&null!==t.fogColor&&(a.fogColor=t.fogColor.asArray()),void 0!==t.fogStart&&null!==t.fogStart&&(a.fogStart=t.fogStart),void 0!==t.fogEnd&&null!==t.fogEnd&&(a.fogEnd=t.fogEnd),void 0!==t.fogDensity&&null!==t.fogDensity&&(a.fogDensity=t.fogDensity),t.isPhysicsEnabled&&t.isPhysicsEnabled()){var s=t.getPhysicsEngine();s&&(a.physicsEnabled=!0,a.physicsGravity=s.gravity.asArray(),a.physicsEngine=s.getPhysicsPluginName())}t.metadata&&(a.metadata=t.metadata),a.morphTargetManagers=[];for(var l=0,c=t.meshes;l<c.length;l++){var h=(b=c[l]).morphTargetManager;h&&a.morphTargetManagers.push(h.serialize())}for(a.lights=[],r=0;r<t.lights.length;r++)(n=t.lights[r]).doNotSerialize||a.lights.push(n.serialize());for(a.cameras=[],r=0;r<t.cameras.length;r++){var d=t.cameras[r];d.doNotSerialize||a.cameras.push(d.serialize())}if(t.activeCamera&&(a.activeCameraID=t.activeCamera.id),Ke.AppendSerializedAnimations(t,a),t.animationGroups&&t.animationGroups.length>0){a.animationGroups=[];for(var p=0;p<t.animationGroups.length;p++){var f=t.animationGroups[p];a.animationGroups.push(f.serialize())}}if(t.reflectionProbes&&t.reflectionProbes.length>0)for(a.reflectionProbes=[],r=0;r<t.reflectionProbes.length;r++){var _=t.reflectionProbes[r];a.reflectionProbes.push(_.serialize())}for(a.materials=[],a.multiMaterials=[],r=0;r<t.materials.length;r++)(o=t.materials[r]).doNotSerialize||a.materials.push(o.serialize());for(a.multiMaterials=[],r=0;r<t.multiMaterials.length;r++){var m=t.multiMaterials[r];a.multiMaterials.push(m.serialize())}for(t.environmentTexture&&(t.environmentTexture._files?a.environmentTexture=t.environmentTexture.serialize():(a.environmentTexture=t.environmentTexture.name,a.environmentTextureRotationY=t.environmentTexture.rotationY)),a.environmentIntensity=t.environmentIntensity,a.skeletons=[],r=0;r<t.skeletons.length;r++){var g=t.skeletons[r];g.doNotSerialize||a.skeletons.push(g.serialize())}for(a.transformNodes=[],r=0;r<t.transformNodes.length;r++)t.transformNodes[r].doNotSerialize||a.transformNodes.push(t.transformNodes[r].serialize());a.geometries={},a.geometries.boxes=[],a.geometries.spheres=[],a.geometries.cylinders=[],a.geometries.toruses=[],a.geometries.grounds=[],a.geometries.planes=[],a.geometries.torusKnots=[],a.geometries.vertexData=[],EP=[];var v=t.getGeometries();for(r=0;r<v.length;r++){var y=v[r];y.isReady()&&SP(y,a.geometries)}for(a.meshes=[],r=0;r<t.meshes.length;r++){var b;if((b=t.meshes[r])instanceof Fa){var T=b;T.doNotSerialize||T.delayLoadState!==u.DELAYLOADSTATE_LOADED&&T.delayLoadState!==u.DELAYLOADSTATE_NONE||a.meshes.push(xP(T,a))}}for(a.particleSystems=[],r=0;r<t.particleSystems.length;r++)a.particleSystems.push(t.particleSystems[r].serialize(!1));for(a.postProcesses=[],r=0;r<t.postProcesses.length;r++)a.postProcesses.push(t.postProcesses[r].serialize());t.actionManager&&(a.actions=t.actionManager.serialize("scene"));for(var E=0,S=t._serializableComponents;E<S.length;E++)S[E].serialize(a);if(t.spriteManagers)for(a.spriteManagers=[],r=0;r<t.spriteManagers.length;r++)a.spriteManagers.push(t.spriteManagers[r].serialize(!0));return a},e.SerializeAsync=function(t){var i=e._Serialize(t,!1),r=[];return this._CollectPromises(i,r),Promise.all(r).then((function(){return i}))},e._CollectPromises=function(e,t){if(Array.isArray(e))for(var i=function(i){var n=e[i];n instanceof Promise?t.push(n.then((function(t){return e[i]=t}))):(n instanceof Object||Array.isArray(n))&&r._CollectPromises(n,t)},r=this,n=0;n<e.length;++n)i(n);else if(e instanceof Object){var o=function(i){if(Object.prototype.hasOwnProperty.call(e,i)){var r=e[i];r instanceof Promise?t.push(r.then((function(t){return e[i]=t}))):(r instanceof Object||Array.isArray(r))&&a._CollectPromises(r,t)}},a=this;for(var s in e)o(s)}},e.SerializeMesh=function(t,i,r){void 0===i&&(i=!1),void 0===r&&(r=!1);var n={meshes:[],transformNodes:[],cameras:[],lights:[]};if(e.ClearCache(),t=t instanceof Array?t:[t],i||r)for(var o=0;o<t.length;++o)r&&t[o].getDescendants().forEach((function(e){t.indexOf(e)<0&&!e.doNotSerialize&&t.push(e)})),i&&t[o].parent&&t.indexOf(t[o].parent)<0&&!t[o].parent.doNotSerialize&&t.push(t[o].parent);return t.forEach((function(e){!function(e,t){if(e._isMesh){var i=e;if(i.delayLoadState===u.DELAYLOADSTATE_LOADED||i.delayLoadState===u.DELAYLOADSTATE_NONE){var r=function(e){t.materials=t.materials||[],i.material&&!t.materials.some((function(e){return e.id===i.material.id}))&&t.materials.push(e.serialize())};if(i.material&&!i.material.doNotSerialize)if(i.material instanceof Ra){if(t.multiMaterials=t.multiMaterials||[],!t.multiMaterials.some((function(e){return e.id===i.material.id}))){t.multiMaterials.push(i.material.serialize());for(var n=0,o=i.material.subMaterials;n<o.length;n++){var a=o[n];a&&r(a)}}}else r(i.material);else i.material||r(i.getScene().defaultMaterial);var s=i._geometry;s&&(t.geometries||(t.geometries={},t.geometries.boxes=[],t.geometries.spheres=[],t.geometries.cylinders=[],t.geometries.toruses=[],t.geometries.grounds=[],t.geometries.planes=[],t.geometries.torusKnots=[],t.geometries.vertexData=[]),SP(s,t.geometries)),i.skeleton&&!i.skeleton.doNotSerialize&&(t.skeletons=t.skeletons||[],t.skeletons.push(i.skeleton.serialize())),t.meshes=t.meshes||[],t.meshes.push(xP(i,t))}}else if("TransformNode"===e.getClassName()){var l=e;t.transformNodes.push(l.serialize())}else if(-1!==e.getClassName().indexOf("Camera")){var c=e;t.cameras.push(c.serialize())}else if(-1!==e.getClassName().indexOf("Light")){var h=e;t.lights.push(h.serialize())}}(e,n)})),n},e}(),CP=function(){function e(t,i){void 0===i&&(i={});var r,n=this;if(!e.IsSupported(t,i.canvas))throw"Your browser does not support recording so far.";var o=null!==(r=i.canvas)&&void 0!==r?r:t.getRenderingCanvas();if(!o)throw"The babylon engine must have a canvas to be recorded";this._canvas=o,this._canvas.isRecording=!1,this._options=g(g({},e._DefaultOptions),i);var a=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(var s=0,l=this._options.audioTracks;s<l.length;s++){var c=l[s];a.addTrack(c)}this._mediaRecorder=new MediaRecorder(a,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=function(e){return n._handleDataAvailable(e)},this._mediaRecorder.onerror=function(e){return n._handleError(e)},this._mediaRecorder.onstop=function(){return n._handleStop()}}return e.IsSupported=function(e,t){var i=null!=t?t:e.getRenderingCanvas();return!!i&&"function"==typeof i.captureStream},Object.defineProperty(e.prototype,"isRecording",{get:function(){return!!this._canvas&&this._canvas.isRecording},enumerable:!1,configurable:!0}),e.prototype.stopRecording=function(){this._canvas&&this._mediaRecorder&&this.isRecording&&(this._canvas.isRecording=!1,this._mediaRecorder.stop())},e.prototype.startRecording=function(e,t){var i=this;if(void 0===e&&(e="babylonjs.webm"),void 0===t&&(t=7),!this._canvas||!this._mediaRecorder)throw"Recorder has already been disposed";if(this.isRecording)throw"Recording already in progress";return t>0&&setTimeout((function(){i.stopRecording()}),1e3*t),this._fileName=e,this._recordedChunks=[],this._resolve=null,this._reject=null,this._canvas.isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise((function(e,t){i._resolve=e,i._reject=t}))},e.prototype.dispose=function(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null},e.prototype._handleDataAvailable=function(e){e.data.size>0&&this._recordedChunks.push(e.data)},e.prototype._handleError=function(e){if(this.stopRecording(),!this._reject)throw new e.error;this._reject(e.error)},e.prototype._handleStop=function(){this.stopRecording();var e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&rr.Download(e,this._fileName)},e._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3},e}(),RP=null;function PP(e,t,i,r,n,o,a){void 0===n&&(n="image/png"),void 0===o&&(o=!1);var s=NP(e,t,i),l=s.height,c=s.width;if(l&&c){RP||(RP=document.createElement("canvas")),RP.width=c,RP.height=l;var u=RP.getContext("2d"),h=e.getRenderWidth()/e.getRenderHeight(),d=c,p=d/h;p>l&&(d=(p=l)*h);var f=Math.max(0,c-d)/2,_=Math.max(0,l-p)/2;t.getScene().activeCamera!==t?OP(e,t,i,(function(e){if(o){var t=new Blob([e]);rr.DownloadBlob(t),r&&r("")}else r&&r(e)}),n,1,e.getCreationOptions().antialias,void 0,void 0,void 0,void 0,a):e.onEndFrameObservable.addOnce((function(){var t=e.getRenderingCanvas();u&&t&&u.drawImage(t,f,_,d,p),RP&&(o?(rr.EncodeScreenshotCanvasData(RP,void 0,n,void 0,a),r&&r("")):rr.EncodeScreenshotCanvasData(RP,r,n,void 0,a))}))}else ae.Error("Invalid 'size' parameter !")}function IP(e,t,i,r,n){return void 0===r&&(r="image/png"),new Promise((function(o,a){PP(e,t,i,(function(e){void 0!==e?o(e):a(new Error("Data is undefined"))}),r,void 0,n)}))}function MP(e,t,i,r,n,o){return void 0===n&&(n="image/png"),new Promise((function(a){PP(e,t,{width:i,height:r},(function(){a()}),n,!0,o)}))}function OP(e,t,i,r,n,o,a,s,l,c,h,d,p){void 0===n&&(n="image/png"),void 0===o&&(o=1),void 0===a&&(a=!1),void 0===l&&(l=!1),void 0===c&&(c=!1),void 0===h&&(h=!0);var f=NP(e,t,i),_=f.height,m=f.width,g=f.finalWidth,v=f.finalHeight,y={width:m,height:_};if(_&&m){var b={width:e.getRenderWidth(),height:e.getRenderHeight()};e.setSize(m,_);var T=t.getScene(),E=new Pl("screenShot",y,T,!1,!1,u.TEXTURETYPE_UNSIGNED_INT,!1,Ja.BILINEAR_SAMPLINGMODE,void 0,c,void 0,void 0,void 0,o);E.renderList=T.meshes.slice(),E.samples=o,E.renderSprites=l,E.activeCamera=t,E.forceLayerMaskCheck=h,null==p||p(E);var S=function(){E.isReadyForRendering()&&t.isReady(!0)?(e.onEndFrameObservable.addOnce((function(){g===m&&v===_?E.readPixels(void 0,void 0,void 0,!1).then((function(e){Rl.DumpData(m,_,e,r,n,s,!0,void 0,d),E.dispose()})):Rp("pass",E.getInternalTexture(),T,void 0,void 0,void 0,g,v).then((function(t){e._readTexturePixels(t,g,v,-1,0,null,!0,!1,0,0).then((function(e){Rl.DumpData(g,v,e,r,n,s,!0,void 0,d),t.dispose()}))}))})),E.render(!0),T.incrementRenderId(),T.resetCachedMaterial(),e.setSize(b.width,b.height),t.getProjectionMatrix(!0),T.render()):setTimeout(S,16)},x=function(){T.incrementRenderId(),T.resetCachedMaterial(),S()};if(a){var A=new DC("antialiasing",1,T.activeCamera);E.addPostProcess(A),A.getEffect().isReady()?x():A.getEffect().onCompiled=function(){x()}}else x()}else ae.Error("Invalid 'size' parameter !")}function DP(e,t,i,r,n,o,a,s,l,c,u){return void 0===r&&(r="image/png"),void 0===n&&(n=1),void 0===o&&(o=!1),void 0===s&&(s=!1),void 0===l&&(l=!1),void 0===c&&(c=!0),new Promise((function(h,d){OP(e,t,i,(function(e){void 0!==e?h(e):d(new Error("Data is undefined"))}),r,n,o,a,s,l,c,u)}))}function NP(e,t,i){var r=0,n=0,o=0,a=0;if("object"==typeof i){var s=i.precision?Math.abs(i.precision):1;i.width&&i.height?(r=i.height*s,n=i.width*s):i.width&&!i.height?(n=i.width*s,r=Math.round(n/e.getAspectRatio(t))):i.height&&!i.width?(r=i.height*s,n=Math.round(r*e.getAspectRatio(t))):(n=Math.round(e.getRenderWidth()*s),r=Math.round(n/e.getAspectRatio(t))),i.finalWidth&&i.finalHeight?(a=i.finalHeight,o=i.finalWidth):i.finalWidth&&!i.finalHeight?(o=i.finalWidth,a=Math.round(o/e.getAspectRatio(t))):i.finalHeight&&!i.finalWidth?(a=i.finalHeight,o=Math.round(a*e.getAspectRatio(t))):(o=n,a=r)}else isNaN(i)||(r=i,n=i,o=i,a=i);return n&&(n=Math.floor(n)),r&&(r=Math.floor(r)),o&&(o=Math.floor(o)),a&&(a=Math.floor(a)),{height:0|r,width:0|n,finalWidth:0|o,finalHeight:0|a}}var FP,LP={CreateScreenshot:PP,CreateScreenshotAsync:IP,CreateScreenshotWithResizeAsync:MP,CreateScreenshotUsingRenderTarget:OP,CreateScreenshotUsingRenderTargetAsync:DP};rr.CreateScreenshot=PP,rr.CreateScreenshotAsync=IP,rr.CreateScreenshotUsingRenderTarget=OP,rr.CreateScreenshotUsingRenderTargetAsync=DP,function(e){e[e.Checkbox=0]="Checkbox",e[e.Slider=1]="Slider",e[e.Vector3=2]="Vector3",e[e.Quaternion=3]="Quaternion",e[e.Color3=4]="Color3",e[e.String=5]="String",e[e.Button=6]="Button",e[e.Options=7]="Options",e[e.Tab=8]="Tab",e[e.FileButton=9]="FileButton",e[e.Vector2=10]="Vector2"}(FP||(FP={}));var wP,BP=function(){function e(e){this.byteOffset=0,this.buffer=e}return e.prototype.loadAsync=function(e){var t=this;return this.buffer.readAsync(this.byteOffset,e).then((function(e){t._dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),t._dataByteOffset=0}))},e.prototype.readUint32=function(){var e=this._dataView.getUint32(this._dataByteOffset,!0);return this._dataByteOffset+=4,this.byteOffset+=4,e},e.prototype.readUint8Array=function(e){var t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._dataByteOffset,e);return this._dataByteOffset+=e,this.byteOffset+=e,t},e.prototype.readString=function(e){return St(this.readUint8Array(e))},e.prototype.skipBytes=function(e){this._dataByteOffset+=e,this.byteOffset+=e},e}(),UP=function(){function e(){}return e._GetStorage=function(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch(t){var e={};return{getItem:function(t){var i=e[t];return void 0===i?null:i},setItem:function(t,i){e[t]=i}}}},e.ReadString=function(e,t){var i=this._Storage.getItem(e);return null!==i?i:t},e.WriteString=function(e,t){this._Storage.setItem(e,t)},e.ReadBoolean=function(e,t){var i=this._Storage.getItem(e);return null!==i?"true"===i:t},e.WriteBoolean=function(e,t){this._Storage.setItem(e,t?"true":"false")},e.ReadNumber=function(e,t){var i=this._Storage.getItem(e);return null!==i?parseFloat(i):t},e.WriteNumber=function(e,t){this._Storage.setItem(e,t.toString())},e._Storage=e._GetStorage(),e}(),VP=function(){function e(){this._trackedScene=null}return e.prototype.track=function(e){this._trackedScene=e,Ke.AllowLoadingUniqueId=!0,this._savedJSON=AP.Serialize(e),Ke.AllowLoadingUniqueId=!1},e.prototype.getDelta=function(){if(!this._trackedScene)return null;var e=Ja.ForceSerializeBuffers;Ja.ForceSerializeBuffers=!1,Ke.AllowLoadingUniqueId=!0;var t=AP.Serialize(this._trackedScene);Ke.AllowLoadingUniqueId=!1;var i={};for(var r in t)this._compareCollections(r,this._savedJSON[r],t[r],i);return Ja.ForceSerializeBuffers=e,i},e.prototype._compareArray=function(e,t,i,r){if(0===t.length&&0===i.length)return!0;if(t.length&&!isNaN(t[0])||i.length&&!isNaN(i[0])){if(t.length!==i.length)return!1;if(0===t.length)return!0;for(var n=0;n<t.length;n++)if(t[n]!==i[n])return r[e]=i,!1;return!0}var o=[],a=function(n){var a=t[n],l=a.uniqueId;o.push(l);var c=i.filter((function(e){return e.uniqueId===l}));if(c.length){var u=c[0],h={};s._compareObjects(a,u,h)||(r[e]||(r[e]=[]),h.__state={id:u.id||u.name},r[e].push(h))}else h={__state:{deleteId:a.id||a.name}},r[e]||(r[e]=[]),r[e].push(h)},s=this;for(n=0;n<t.length;n++)a(n);for(n=0;n<i.length;n++){var l=i[n],c=l.uniqueId;-1===o.indexOf(c)&&(r[e]||(r[e]=[]),r[e].push(l))}return!0},e.prototype._compareObjects=function(e,t,i){var r=!1;for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){var o=e[n],a=t[n],s=!1;if(Array.isArray(o))s=JSON.stringify(o)!==JSON.stringify(a);else if(isNaN(o)&&"[object String]"!=Object.prototype.toString.call(o)){if("object"==typeof o&&"object"==typeof a){var l={};this._compareObjects(o,a,l)||(i[n]=l,r=!0)}}else s=o!==a;s&&(r=!0,i[n]=a)}return!r},e.prototype._compareCollections=function(e,t,i,r){if(t!==i&&t&&i)if(Array.isArray(t)&&Array.isArray(i)){if(this._compareArray(e,t,i,r))return}else if("object"==typeof t&&"object"==typeof i){var n={};return void(this._compareObjects(t,i,n)||(r[e]=n))}},e.GetShadowGeneratorById=function(e,t){for(var i=0,r=e.lights.map((function(e){return e.getShadowGenerators()}));i<r.length;i++){var n=r[i];if(n)for(var o=n.values(),a=o.next();!0!==a.done;a=o.next()){var s=a.value;if(s&&s.id===t)return s}}return null},e.ApplyDelta=function(e,t){var i=this;"string"==typeof e&&(e=JSON.parse(e));var r=t;for(var n in e){var o=e[n],a=r[n];if(Array.isArray(a)||"shadowGenerators"===n)switch(n){case"cameras":this._ApplyDeltaForEntity(o,t,t.getCameraById.bind(t),(function(e){return $n.Parse(e,t)}));break;case"lights":this._ApplyDeltaForEntity(o,t,t.getLightById.bind(t),(function(e){return wa.Parse(e,t)}));break;case"shadowGenerators":this._ApplyDeltaForEntity(o,t,(function(e){return i.GetShadowGeneratorById(t,e)}),(function(e){return dv.Parse(e,t)}));break;case"meshes":this._ApplyDeltaForEntity(o,t,t.getMeshById.bind(t),(function(e){return Fa.Parse(e,t,"")}));break;case"skeletons":this._ApplyDeltaForEntity(o,t,t.getSkeletonById.bind(t),(function(e){return rs.Parse(e,t)}));break;case"materials":this._ApplyDeltaForEntity(o,t,t.getMaterialById.bind(t),(function(e){return Ca.Parse(e,t,"")}));break;case"multiMaterials":this._ApplyDeltaForEntity(o,t,t.getMaterialById.bind(t),(function(e){return Ra.Parse(e,t,"")}));break;case"transformNodes":this._ApplyDeltaForEntity(o,t,t.getTransformNodeById.bind(t),(function(e){return Fo.Parse(e,t,"")}));break;case"particleSystems":this._ApplyDeltaForEntity(o,t,t.getParticleSystemById.bind(t),(function(e){return aA.Parse(e,t,"")}));break;case"morphTargetManagers":this._ApplyDeltaForEntity(o,t,t.getMorphTargetById.bind(t),(function(e){return Ov.Parse(e,t)}));break;case"postProcesses":this._ApplyDeltaForEntity(o,t,t.getPostProcessByName.bind(t),(function(e){return hl.Parse(e,t,"")}))}else isNaN(a)?a.fromArray&&a.fromArray(o):r[n]=o}},e._ApplyPropertiesToEntity=function(e,t){for(var i in e){var r=e[i],n=t[i];void 0!==n&&(!isNaN(n)||Array.isArray(n)?t[i]=r:n.fromArray?n.fromArray(r):"object"==typeof n&&null!==n&&this._ApplyPropertiesToEntity(r,n))}},e._ApplyDeltaForEntity=function(e,t,i,r){for(var n=0,o=e;n<o.length;n++){var a=o[n];if(a.__state&&void 0!==a.__state.id){var s=i(a.__state.id);s&&(this._ApplyPropertiesToEntity(a,s),Ke.ParseProperties(a,s,t,null))}else if(a.__state&&void 0!==a.__state.deleteId){var l=i(a.__state.deleteId);null==l||l.dispose()}else r(a)}},e}();!function(e){var t=function(){function e(e,t,i,r){var n;void 0===t&&(t=null),void 0===i&&(i=null),void 0===r&&(r=null),t=null!=t?t:function(){return 1},i=null!=i?i:function(){return 1},r=null!=r?r:function(e,t){return e===t?0:1},this._characterToIdx=new Map,this._insertionCosts=new Array(e.length),this._deletionCosts=new Array(e.length),this._substitutionCosts=new Array(e.length);for(var o=0;o<e.length;++o){n=e[o],this._characterToIdx.set(n,o),this._insertionCosts[o]=t(n),this._deletionCosts[o]=i(n),this._substitutionCosts[o]=new Array(e.length);for(var a=o;a<e.length;++a)this._substitutionCosts[o][a]=r(n,e[a])}}return e.prototype.serialize=function(){var e={},t=new Array(this._characterToIdx.size);return this._characterToIdx.forEach((function(e,i){t[e]=i})),e.characters=t,e.insertionCosts=this._insertionCosts,e.deletionCosts=this._deletionCosts,e.substitutionCosts=this._substitutionCosts,JSON.stringify(e)},e.Deserialize=function(t){var i=JSON.parse(t),r=new e(i.characters);return r._insertionCosts=i.insertionCosts,r._deletionCosts=i.deletionCosts,r._substitutionCosts=i.substitutionCosts,r},e.prototype.getCharacterIdx=function(e){return this._characterToIdx.get(e)},e.prototype.getInsertionCost=function(e){return this._insertionCosts[e]},e.prototype.getDeletionCost=function(e){return this._deletionCosts[e]},e.prototype.getSubstitutionCost=function(e,t){var i=Math.min(e,t),r=Math.max(e,t);return this._substitutionCosts[i][r]},e}();e.Alphabet=t;var i=function(){function e(t,i){var r=this;if(t.length>e._MAX_SEQUENCE_LENGTH)throw new Error("Sequences longer than "+e._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=i,this._characters=t.map((function(e){return r._alphabet.getCharacterIdx(e)}))}return e.prototype.serialize=function(){return JSON.stringify(this._characters)},e.Deserialize=function(t,i){var r=new e([],i);return r._characters=JSON.parse(t),r},e.prototype.distance=function(t){return e._Distance(this,t)},e._Distance=function(t,i){var r=t._alphabet;if(r!==i._alphabet)throw new Error("Cannot Levenshtein compare Sequences built from different alphabets.");var n=t._characters,o=i._characters,a=n.length,s=o.length,l=e._CostMatrix;l[0][0]=0;for(var c=0;c<a;++c)l[c+1][0]=l[c][0]+r.getInsertionCost(n[c]);for(c=0;c<s;++c)l[0][c+1]=l[0][c]+r.getInsertionCost(o[c]);for(var u=0;u<a;++u)for(var h=0;h<s;++h)e._InsertionCost=l[u+1][h]+r.getInsertionCost(o[h]),e._DeletionCost=l[u][h+1]+r.getDeletionCost(n[u]),e._SubstitutionCost=l[u][h]+r.getSubstitutionCost(n[u],o[h]),l[u+1][h+1]=Math.min(e._InsertionCost,e._DeletionCost,e._SubstitutionCost);return l[a][s]},e._MAX_SEQUENCE_LENGTH=256,e._CostMatrix=T([],Array(e._MAX_SEQUENCE_LENGTH+1),!0).map((function(){return new Array(e._MAX_SEQUENCE_LENGTH+1)})),e}();e.Sequence=i}(wP||(wP={}));var kP=function(){function e(e){void 0===e&&(e=.01),this._points=[],this._segmentLength=e}return e.prototype.serialize=function(){return JSON.stringify(this)},e.Deserialize=function(t){var i=JSON.parse(t),r=new e(i._segmentLength);return r._points=i._points.map((function(e){return new V(e._x,e._y,e._z)})),r},e.prototype.getLength=function(){return this._points.length*this._segmentLength},e.prototype.add=function(e){var t=this,i=this._points.length;if(0===i)this._points.push(e.clone());else for(var r=function(){return t._segmentLength/V.Distance(t._points[i-1],e)},n=r();n<=1;n=r()){var o=this._points[i-1].scale(1-n);e.scaleAndAddToRef(n,o),this._points.push(o),++i}},e.prototype.resampleAtTargetResolution=function(t){var i=new e(this.getLength()/t);return this._points.forEach((function(e){i.add(e)})),i},e.prototype.tokenize=function(t){for(var i=[],r=new V,n=2;n<this._points.length;++n)e._TransformSegmentDirToRef(this._points[n-2],this._points[n-1],this._points[n],r)&&i.push(e._TokenizeSegment(r,t));return i},e._TransformSegmentDirToRef=function(t,i,r,n){return i.subtractToRef(t,e._ForwardDir),e._ForwardDir.normalize(),i.scaleToRef(-1,e._InverseFromVec),e._InverseFromVec.normalize(),!(Math.abs(V.Dot(e._ForwardDir,e._InverseFromVec))>.98||(V.CrossToRef(e._ForwardDir,e._InverseFromVec,e._UpDir),e._UpDir.normalize(),z.LookAtLHToRef(t,i,e._UpDir,e._LookMatrix),r.subtractToRef(i,e._FromToVec),e._FromToVec.normalize(),V.TransformNormalToRef(e._FromToVec,e._LookMatrix,n),0))},e._TokenizeSegment=function(t,i){e._BestMatch=0,e._Score=V.Dot(t,i[0]),e._BestScore=e._Score;for(var r=1;r<i.length;++r)e._Score=V.Dot(t,i[r]),e._Score>e._BestScore&&(e._BestMatch=r,e._BestScore=e._Score);return e._BestMatch},e._ForwardDir=new V,e._InverseFromVec=new V,e._UpDir=new V,e._FromToVec=new V,e._LookMatrix=new z,e}(),GP=function(){function e(e){this.chars=new Array(e)}return e.Generate=function(t,i,r,n,o){void 0===t&&(t=64),void 0===i&&(i=256),void 0===r&&(r=.1),void 0===n&&(n=.001),void 0===o&&(o=[]);for(var a,s,l=new e(t),c=0;c<t;++c)l.chars[c]=new V(Math.random()-.5,Math.random()-.5,Math.random()-.5),l.chars[c].normalize();for(c=0;c<o.length;++c)l.chars[c].copyFrom(o[c]);for(var u,h=new V,d=new V,p=0;p<i;++p){a=(1-(u=p/(i-1)))*r+u*n;var f=function(e){h.copyFromFloats(0,0,0),l.chars.forEach((function(t){l.chars[e].subtractToRef(t,d),(s=d.lengthSquared())>1e-6&&d.scaleAndAddToRef(1/(d.lengthSquared()*s),h)})),h.scaleInPlace(a),l.chars[e].addInPlace(h),l.chars[e].normalize()};for(c=o.length;c<l.chars.length;++c)f(c)}return l},e.prototype.serialize=function(){return JSON.stringify(this.chars)},e.Deserialize=function(t){for(var i=JSON.parse(t),r=new e(i.length),n=0;n<i.length;++n)r.chars[n]=new V(i[n]._x,i[n]._y,i[n]._z);return r},e}(),zP=function(){function e(){this._sequences=[]}return e.prototype.serialize=function(){return JSON.stringify(this._sequences.map((function(e){return e.serialize()})))},e.Deserialize=function(t,i){var r=new e;return r._sequences=JSON.parse(t).map((function(e){return wP.Sequence.Deserialize(e,i)})),r},e.CreateFromTrajectory=function(t,i,r){return e.CreateFromTokenizationPyramid(e._GetTokenizationPyramid(t,i),r)},e.CreateFromTokenizationPyramid=function(t,i){var r=new e;return r._sequences=t.map((function(e){return new wP.Sequence(e,i)})),r},e._GetTokenizationPyramid=function(t,i,r){void 0===r&&(r=e._FINEST_DESCRIPTOR_RESOLUTION);for(var n=[],o=r;o>4;o=Math.floor(o/2))n.push(t.resampleAtTargetResolution(o).tokenize(i.chars));return n},e.prototype.distance=function(e){for(var t=0,i=0;i<this._sequences.length;++i)t+=Math.pow(2,i)*this._sequences[i].distance(e._sequences[i]);return t},e._FINEST_DESCRIPTOR_RESOLUTION=32,e}(),WP=function(){function e(e){void 0===e&&(e=[]),this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}return e.prototype.serialize=function(){var e={};return e.descriptors=this._descriptors.map((function(e){return e.serialize()})),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)},e.Deserialize=function(t,i){var r=JSON.parse(t),n=new e;return n._descriptors=r.descriptors.map((function(e){return zP.Deserialize(e,i)})),n._centroidIdx=r.centroidIdx,n._averageDistance=r.averageDistance,n},e.prototype.add=function(e){this._descriptors.push(e),this._refreshDescription()},e.prototype.getMatchCost=function(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance},e.prototype.getMatchMinimumDistance=function(e){return Math.min.apply(Math,this._descriptors.map((function(t){return t.distance(e)})))},e.prototype._refreshDescription=function(){var t,i=this;this._centroidIdx=-1;for(var r=this._descriptors.map((function(e){return t=0,i._descriptors.forEach((function(i){t+=e.distance(i)})),t})),n=0;n<r.length;++n)(this._centroidIdx<0||r[n]<r[this._centroidIdx])&&(this._centroidIdx=n);this._averageDistance=0,this._descriptors.forEach((function(e){i._averageDistance+=e.distance(i._descriptors[i._centroidIdx])})),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,e._MIN_AVERAGE_DISTANCE))},e._MIN_AVERAGE_DISTANCE=1,e}(),HP=function(){function e(){this._maximumAllowableMatchCost=4,this._nameToDescribedTrajectory=new Map}return e.prototype.serialize=function(){var e={};return e.maximumAllowableMatchCost=this._maximumAllowableMatchCost,e.vector3Alphabet=this._vector3Alphabet.serialize(),e.levenshteinAlphabet=this._levenshteinAlphabet.serialize(),e.nameToDescribedTrajectory=[],this._nameToDescribedTrajectory.forEach((function(t,i){e.nameToDescribedTrajectory.push(i),e.nameToDescribedTrajectory.push(t.serialize())})),JSON.stringify(e)},e.Deserialize=function(t){var i=JSON.parse(t),r=new e;r._maximumAllowableMatchCost=i.maximumAllowableMatchCost,r._vector3Alphabet=GP.Deserialize(i.vector3Alphabet),r._levenshteinAlphabet=wP.Alphabet.Deserialize(i.levenshteinAlphabet);for(var n=0;n<i.nameToDescribedTrajectory.length;n+=2)r._nameToDescribedTrajectory.set(i.nameToDescribedTrajectory[n],WP.Deserialize(i.nameToDescribedTrajectory[n+1],r._levenshteinAlphabet));return r},e.Generate=function(){for(var t=GP.Generate(64,256,.1,.001,[V.Forward()]),i=new Array(t.chars.length),r=0;r<i.length;++r)i[r]=r;var n=new wP.Alphabet(i,(function(e){return 0===e?0:1}),(function(e){return 0===e?0:1}),(function(e,i){return Math.min(1-V.Dot(t.chars[e],t.chars[i]),1)})),o=new e;return o._vector3Alphabet=t,o._levenshteinAlphabet=n,o},e.prototype.addTrajectoryToClassification=function(e,t){this._nameToDescribedTrajectory.has(t)||this._nameToDescribedTrajectory.set(t,new WP),this._nameToDescribedTrajectory.get(t).add(zP.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet))},e.prototype.deleteClassification=function(e){return this._nameToDescribedTrajectory.delete(e)},e.prototype.classifyTrajectory=function(e){var t=this,i=zP.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet),r=[];if(this._nameToDescribedTrajectory.forEach((function(e,n){e.getMatchCost(i)<t._maximumAllowableMatchCost&&r.push(n)})),0===r.length)return null;for(var n,o=0,a=this._nameToDescribedTrajectory.get(r[o]).getMatchMinimumDistance(i),s=0;s<r.length;++s)(n=this._nameToDescribedTrajectory.get(r[s]).getMatchMinimumDistance(i))<a&&(a=n,o=s);return r[o]},e}(),XP=function(){function e(t,i,r){var n=this;this._scene=t,ae.Log("[Reflector] Connecting to ws://".concat(i,":").concat(r)),this._webSocket=new WebSocket("ws://".concat(i,":").concat(r)),this._webSocket.onmessage=function(t){var i=t.data;if(i.startsWith(e._SERVER_PREFIX)){var r=i.substr(e._SERVER_PREFIX.length);return ae.Log("[Reflector] Received server message: ".concat(r.substr(0,64))),void n._handleServerMessage(r)}ae.Log("[Reflector] Received client message: ".concat(i.substr(0,64))),n._handleClientMessage()},this._webSocket.onclose=function(e){ae.Log("[Reflector] Disconnected ".concat(e.code," ").concat(e.reason))}}return e.prototype.close=function(){this._webSocket.close()},e.prototype._handleServerMessage=function(e){var t=this;"connected"===e&&AP.SerializeAsync(this._scene).then((function(e){t._webSocket.send("load|".concat(JSON.stringify(e)))}))},e.prototype._handleClientMessage=function(){},e._SERVER_PREFIX="$$",e}(),jP=function(){function e(t){var i=this;this._observer=null,this._currentState=[],this.onPressureChanged=new f,e.IsAvailable&&(this._observer=new PressureObserver((function(e){i._currentState=e,i.onPressureChanged.notifyObservers(e)}),t))}return Object.defineProperty(e,"IsAvailable",{get:function(){return"undefined"!=typeof PressureObserver&&PressureObserver.supportedSources.includes("cpu")},enumerable:!1,configurable:!0}),e.prototype.observe=function(e){var t;try{null===(t=this._observer)||void 0===t||t.observe(e),this.onPressureChanged.notifyObservers(this._currentState)}catch(e){}},e.prototype.unobserve=function(e){var t;try{null===(t=this._observer)||void 0===t||t.unobserve(e)}catch(e){}},e.prototype.dispose=function(){var e;null===(e=this._observer)||void 0===e||e.disconnect(),this._observer=null,this.onPressureChanged.clear()},e}(),YP=function(){function e(e){this._view=new Float32Array(e),this._itemLength=0}return Object.defineProperty(e.prototype,"itemLength",{get:function(){return this._itemLength},enumerable:!1,configurable:!0}),e.prototype.at=function(e){return e<0||e>=this._itemLength?NaN:this._view[e]},e.prototype.subarray=function(e,t){return e>=t||e<0?new Float32Array(0):(t>this._itemLength&&(t=this._itemLength),this._view.subarray(e,t))},e.prototype.push=function(e){this._view[this._itemLength]=e,this._itemLength++,this._itemLength>=this._view.length&&this._growArray()},e.prototype._growArray=function(){var e=Math.floor(1.5*this._view.length),t=new Float32Array(e);t.set(this._view),this._view=t},e}(),KP=1800,QP="timestamp",qP="numPoints",ZP=/\r/g,JP=function(){function e(t,i){var r=this;this._scene=t,this._collectDataAtFrame=function(){var t=_t.Now-r._startingTimestamp,i=r.datasets.ids.length,n=r.datasets.startingIndices.itemLength,o=0;if(n>0){var a=r.datasets.startingIndices.at(n-1);o=a+r.datasets.data.at(a+e.NumberOfPointsOffset)+e.SliceDataOffset}if(r.datasets.startingIndices.push(o),r.datasets.data.push(t),r.datasets.data.push(i),r.datasets.ids.forEach((function(e){var t=r._strategies.get(e);t&&r.datasets.data.push(t.getData())})),r.datasetObservable.hasObservers()){for(var s=[t,i],l=0;l<i;l++)s.push(r.datasets.data.at(o+e.SliceDataOffset+l));r.datasetObservable.notifyObservers(s)}},this.datasets={ids:[],data:new YP(KP),startingIndices:new YP(KP)},this._strategies=new Map,this._datasetMeta=new Map,this._eventRestoreSet=new Set,this._customEventObservable=new f,this.datasetObservable=new f,this.metadataObservable=new f((function(e){return e.callback(r._datasetMeta,new d(0))})),i&&this.addCollectionStrategies.apply(this,i)}return Object.defineProperty(e,"SliceDataOffset",{get:function(){return 2},enumerable:!1,configurable:!0}),Object.defineProperty(e,"NumberOfPointsOffset",{get:function(){return 1},enumerable:!1,configurable:!0}),e.prototype.registerEvent=function(e,t,i){var r,n=this;if(!this._strategies.has(e)||t){this._strategies.has(e)&&t&&(null===(r=this._strategies.get(e))||void 0===r||r.dispose(),this._strategies.delete(e));var o={name:e};return this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:function(t){var i=0,r=0,o=t.onAfterRenderObservable.add((function(){r=i,i=0})),a=n._customEventObservable.add((function(t){e===t.name&&(void 0!==t.value?i=t.value:i++)}));return{id:e,getData:function(){return r},dispose:function(){t.onAfterRenderObservable.remove(o),n._customEventObservable.remove(a)}}},category:i}),o}},e.prototype.sendEvent=function(e){this._customEventObservable.notifyObservers(e)},e.prototype._restoreStringEvents=function(){var e=this;this._eventRestoreSet.size!==this._customEventObservable.observers.length&&this._eventRestoreSet.forEach((function(t){e.registerEvent(t,!0)}))},e.prototype.addCollectionStrategies=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var i=0,r=e;i<r.length;i++){var n=r[i],o=n.strategyCallback,a=n.category,s=n.hidden,l=o(this._scene);this._strategies.has(l.id)?l.dispose():(this.datasets.ids.push(l.id),a&&(a=a.replace(new RegExp("@","g"),"")),this._datasetMeta.set(l.id,{color:this._getHexColorFromId(l.id),category:a,hidden:s}),this._strategies.set(l.id,l))}this.metadataObservable.notifyObservers(this._datasetMeta)},e.prototype._getHexColorFromId=function(e){for(var t=0,i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);var r="#";for(i=0;i<24;i+=8)r+=("0"+(t>>i&255).toString(16)).substr(-2);return r},e.prototype.getCurrentSlice=function(){var e=this,t=[_t.Now-this._startingTimestamp,this.datasets.ids.length];this.datasets.ids.forEach((function(i){var r=e._strategies.get(i);r&&e.datasetObservable.hasObservers()&&t.push(r.getData())})),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(t)},e.prototype.updateMetadata=function(e,t,i){var r=this._datasetMeta.get(e);r&&(r[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))},e.prototype.clear=function(e){this.datasets.data=new YP(KP),this.datasets.ids.length=0,this.datasets.startingIndices=new YP(KP),this._datasetMeta.clear(),this._strategies.forEach((function(e){return e.dispose()})),this._strategies.clear(),e||this._eventRestoreSet.clear(),this._hasLoadedData=!1},Object.defineProperty(e.prototype,"hasLoadedData",{get:function(){return this._hasLoadedData},enumerable:!1,configurable:!0}),e.prototype.loadFromFileData=function(t,i){var r=t.replace(ZP,"").split("\n").map((function(e){return e.split(",").filter((function(e){return e.length>0}))})).filter((function(e){return e.length>0})),n=e.NumberOfPointsOffset;if(r.length<2)return!1;var o={ids:[],data:new YP(KP),startingIndices:new YP(KP)},a=r[0],s=r.slice(1);if(a.length<2||a[0]!==QP||a[n]!==qP)return!1;for(var l=new Map,c=e.SliceDataOffset;c<a.length;c++){var u=a[c].split("@"),h=u[0],d=u[1];o.ids.push(h),l.set(h,d)}for(var p=0,f=0,_=s;f<_.length;f++){var m=_[f];if(m.length<2)return!1;var g=parseFloat(m[0]),v=parseInt(m[n]);if(isNaN(v)||isNaN(g))return!1;if(o.data.push(g),o.data.push(v),v+e.SliceDataOffset!==m.length)return!1;for(c=e.SliceDataOffset;c<m.length;c++){var y=parseFloat(m[c]);if(isNaN(y))return!1;o.data.push(y)}o.startingIndices.push(p),p+=m.length}if(this.datasets.ids=o.ids,this.datasets.data=o.data,this.datasets.startingIndices=o.startingIndices,i||this._datasetMeta.clear(),this._strategies.forEach((function(e){return e.dispose()})),this._strategies.clear(),!i)for(var b=0,T=this.datasets.ids;b<T.length;b++)h=T[b],d=l.get(h),this._datasetMeta.set(h,{category:d,color:this._getHexColorFromId(h)});return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0},e.prototype.exportDataToCsv=function(){var t="";t+="".concat(QP,",").concat(qP);for(var i=0;i<this.datasets.ids.length;i++)if(t+=",".concat(this.datasets.ids[i]),this._datasetMeta){var r=this._datasetMeta.get(this.datasets.ids[i]);(null==r?void 0:r.category)&&(t+="".concat("@").concat(r.category))}for(t+="\n",i=0;i<this.datasets.startingIndices.itemLength;i++){var n=this.datasets.startingIndices.at(i),o=this.datasets.data.at(n),a=this.datasets.data.at(n+e.NumberOfPointsOffset);t+="".concat(o,",").concat(a);for(var s=0;s<a;s++)t+=",".concat(this.datasets.data.at(n+e.SliceDataOffset+s));for(var l=0;l<this.datasets.ids.length-a;l++)t+=",";t+="\n"}var c="".concat((new Date).toISOString(),"-perfdata.csv");rr.Download(new Blob([t],{type:"text/csv"}),c)},e.prototype.start=function(e){e?void 0===this._startingTimestamp&&(this._startingTimestamp=_t.Now):(this.datasets.data=new YP(KP),this.datasets.startingIndices=new YP(KP),this._startingTimestamp=_t.Now),this._scene.onAfterRenderObservable.add(this._collectDataAtFrame),this._restoreStringEvents(),this._isStarted=!0},e.prototype.stop=function(){this._scene.onAfterRenderObservable.removeCallback(this._collectDataAtFrame),this._isStarted=!1},Object.defineProperty(e.prototype,"isStarted",{get:function(){return this._isStarted},enumerable:!1,configurable:!0}),e.prototype.dispose=function(){this._scene.onAfterRenderObservable.removeCallback(this._collectDataAtFrame),this._datasetMeta.clear(),this._strategies.forEach((function(e){e.dispose()})),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null},e}(),$P=function(){},eI=function(){function e(){}return e.FpsStrategy=function(){return function(e){var t=e.getEngine();return{id:"FPS",getData:function(){return t.getFps()},dispose:$P}}},e.ThermalStrategy=function(){return this._PressureStrategy("Thermal utilization","thermal")},e.PowerSupplyStrategy=function(){return this._PressureStrategy("Power supply utilization","power-supply")},e.PressureStrategy=function(){return this._PressureStrategy("Pressure")},e._PressureStrategy=function(e,t){return void 0===t&&(t=null),function(){var i=0,r=new jP;return r.observe("cpu"),r.onPressureChanged.add((function(e){for(var r,n,o=0,a=e;o<a.length;o++){var s=a[o];if(t&&s.factors.includes(t)||!t&&0===(null!==(n=null===(r=s.factors)||void 0===r?void 0:r.length)&&void 0!==n?n:0))switch(s.state){case"nominal":i=0;break;case"fair":i=.25;break;case"serious":i=.5;break;case"critical":i=1}}})),{id:e,getData:function(){return i},dispose:function(){return r.dispose()}}}},e.TotalMeshesStrategy=function(){return function(e){return{id:"Total meshes",getData:function(){return e.meshes.length},dispose:$P}}},e.ActiveMeshesStrategy=function(){return function(e){return{id:"Active meshes",getData:function(){return e.getActiveMeshes().length},dispose:$P}}},e.ActiveIndicesStrategy=function(){return function(e){return{id:"Active indices",getData:function(){return e.getActiveIndices()},dispose:$P}}},e.ActiveFacesStrategy=function(){return function(e){return{id:"Active faces",getData:function(){return e.getActiveIndices()/3},dispose:$P}}},e.ActiveBonesStrategy=function(){return function(e){return{id:"Active bones",getData:function(){return e.getActiveBones()},dispose:$P}}},e.ActiveParticlesStrategy=function(){return function(e){return{id:"Active particles",getData:function(){return e.getActiveParticles()},dispose:$P}}},e.DrawCallsStrategy=function(){return function(e){var t=0,i=e.onBeforeAnimationsObservable.add((function(){e.getEngine()._drawCalls.fetchNewFrame()})),r=e.onAfterRenderObservable.add((function(){t=e.getEngine()._drawCalls.current}));return{id:"Draw calls",getData:function(){return t},dispose:function(){e.onBeforeAnimationsObservable.remove(i),e.onAfterRenderObservable.remove(r)}}}},e.TotalLightsStrategy=function(){return function(e){return{id:"Total lights",getData:function(){return e.lights.length},dispose:$P}}},e.TotalVerticesStrategy=function(){return function(e){return{id:"Total vertices",getData:function(){return e.getTotalVertices()},dispose:$P}}},e.TotalMaterialsStrategy=function(){return function(e){return{id:"Total materials",getData:function(){return e.materials.length},dispose:$P}}},e.TotalTexturesStrategy=function(){return function(e){return{id:"Total textures",getData:function(){return e.textures.length},dispose:$P}}},e.AbsoluteFpsStrategy=function(){return function(e){var t=new tv(e);return t.captureFrameTime=!0,{id:"Absolute FPS",getData:function(){return 1e3/t.frameTimeCounter.lastSecAverage},dispose:$P}}},e.MeshesSelectionStrategy=function(){return function(e){var t=_t.Now,i=0,r=e.onBeforeActiveMeshesEvaluationObservable.add((function(){t=_t.Now})),n=e.onAfterActiveMeshesEvaluationObservable.add((function(){i=_t.Now-t}));return{id:"Meshes Selection",getData:function(){return i},dispose:function(){e.onBeforeActiveMeshesEvaluationObservable.remove(r),e.onAfterActiveMeshesEvaluationObservable.remove(n)}}}},e.RenderTargetsStrategy=function(){return function(e){var t=_t.Now,i=0,r=e.onBeforeRenderTargetsRenderObservable.add((function(){t=_t.Now})),n=e.onAfterRenderTargetsRenderObservable.add((function(){i=_t.Now-t}));return{id:"Render Targets",getData:function(){return i},dispose:function(){e.onBeforeRenderTargetsRenderObservable.remove(r),e.onAfterRenderTargetsRenderObservable.remove(n)}}}},e.ParticlesStrategy=function(){return function(e){var t=_t.Now,i=0,r=e.onBeforeParticlesRenderingObservable.add((function(){t=_t.Now})),n=e.onAfterParticlesRenderingObservable.add((function(){i=_t.Now-t}));return{id:"Particles",getData:function(){return i},dispose:function(){e.onBeforeParticlesRenderingObservable.remove(r),e.onAfterParticlesRenderingObservable.remove(n)}}}},e.SpritesStrategy=function(){return function(e){var t,i,r=_t.Now,n=0,o=null===(t=e.onBeforeSpritesRenderingObservable)||void 0===t?void 0:t.add((function(){r=_t.Now})),a=null===(i=e.onAfterSpritesRenderingObservable)||void 0===i?void 0:i.add((function(){n=_t.Now-r}));return{id:"Sprites",getData:function(){return n},dispose:function(){var t,i;null===(t=e.onBeforeSpritesRenderingObservable)||void 0===t||t.remove(o),null===(i=e.onAfterSpritesRenderingObservable)||void 0===i||i.remove(a)}}}},e.AnimationsStrategy=function(){return function(e){var t=_t.Now,i=0,r=e.onBeforeAnimationsObservable.add((function(){t=_t.Now})),n=e.onAfterAnimationsObservable.add((function(){i=_t.Now-t}));return{id:"Animations",getData:function(){return i},dispose:function(){e.onBeforeAnimationsObservable.remove(r),e.onAfterAnimationsObservable.remove(n)}}}},e.PhysicsStrategy=function(){return function(e){var t,i,r=_t.Now,n=0,o=null===(t=e.onBeforePhysicsObservable)||void 0===t?void 0:t.add((function(){r=_t.Now})),a=null===(i=e.onAfterPhysicsObservable)||void 0===i?void 0:i.add((function(){n=_t.Now-r}));return{id:"Physics",getData:function(){return n},dispose:function(){var t,i;null===(t=e.onBeforePhysicsObservable)||void 0===t||t.remove(o),null===(i=e.onAfterPhysicsObservable)||void 0===i||i.remove(a)}}}},e.RenderStrategy=function(){return function(e){var t=_t.Now,i=0,r=e.onBeforeDrawPhaseObservable.add((function(){t=_t.Now})),n=e.onAfterDrawPhaseObservable.add((function(){i=_t.Now-t}));return{id:"Render",getData:function(){return i},dispose:function(){e.onBeforeDrawPhaseObservable.remove(r),e.onAfterDrawPhaseObservable.remove(n)}}}},e.FrameTotalStrategy=function(){return function(e){var t=_t.Now,i=0,r=e.onBeforeAnimationsObservable.add((function(){t=_t.Now})),n=e.onAfterRenderObservable.add((function(){i=_t.Now-t}));return{id:"Frame Total",getData:function(){return i},dispose:function(){e.onBeforeAnimationsObservable.remove(r),e.onAfterRenderObservable.remove(n)}}}},e.InterFrameStrategy=function(){return function(e){var t=_t.Now,i=0,r=e.onBeforeAnimationsObservable.add((function(){i=_t.Now-t})),n=e.onAfterRenderObservable.add((function(){t=_t.Now}));return{id:"Inter-frame",getData:function(){return i},dispose:function(){e.onBeforeAnimationsObservable.remove(r),e.onAfterRenderObservable.remove(n)}}}},e.GpuFrameTimeStrategy=function(){return function(e){var t=new ev(e.getEngine());return t.captureGPUFrameTime=!0,{id:"GPU frame time",getData:function(){return Math.max(1e-6*t.gpuFrameTimeCounter.current,0)},dispose:function(){t.dispose()}}}},e}();pn.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new JP(this)),this._perfCollector},f.prototype.runCoroutineAsync=function(e){if(!this._coroutineScheduler){var t=function(e){var t=new Array,i=new Array,r=new Array,n=e.add((function(){for(var e=t.length,n=0;n<e;n++)Xn(t.shift(),i.shift(),r.shift())}));return{scheduler:function(e,n,o){t.push(e),i.push(n),r.push(o)},dispose:function(){e.remove(n)}}}(this);this._coroutineScheduler=t.scheduler,this._coroutineSchedulerDispose=t.dispose}return Qn(e,this._coroutineScheduler)},f.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};function tI(e,t){var i,r;return y(this,void 0,void 0,(function(){var n,o,a,s;return b(this,(function(l){return n=null!==(i=t.probe)&&void 0!==i?i:new Uv("tempProbe",t.size,e),(o=!!t.probe)||(t.position?n.position=t.position.clone():e.activeCamera&&(n.position=e.activeCamera.position.clone())),a=t.meshesFilter?e.meshes.filter(t.meshesFilter):e.meshes,null===(r=n.renderList)||void 0===r||r.push.apply(r,a),n.refreshRate=Pl.REFRESHRATE_RENDER_ONCE,n.cubeTexture.render(),(s=new Wy("tempProceduralTexture","equirectangularPanorama",{width:2*t.size,height:t.size},e)).setTexture("cubeMap",n.cubeTexture),[2,new Promise((function(e,i){s.onGeneratedObservable.addOnce((function(){var r=s.readPixels();if(!r)return i(new Error("No Pixel Data found on procedural texture")),s.dispose(),void(o||n.dispose());r.then((function(i){s.dispose(),o||n.dispose(),t.filename?(Rl.DumpData(2*t.size,t.size,i,void 0,"image/png",t.filename),e(null)):e(i)}))}))}))]}))}))}li.ShadersStore.equirectangularPanoramaPixelShader="#ifdef GL_ES\nprecision highp float;\n#endif\n#define M_PI 3.1415926535897932384626433832795\nvarying vec2 vUV;uniform samplerCube cubeMap;void main(void) {vec2 uv=vUV;float longitude=uv.x*2.*M_PI-M_PI+M_PI/2.;float latitude=(1.-uv.y)*M_PI;vec3 dir=vec3(\n- sin( longitude )*sin( latitude ),\ncos( latitude ),\n- cos( longitude )*sin( latitude )\n);normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}";var iI=function(e){function t(i,r){void 0===r&&(r={});var n=e.call(this,i)||this;return n.options=r,n._direction=new V(0,0,-1),n._mat=new z,n._onSelectEnabled=!1,n._origin=new V(0,0,0),n.lastNativeXRHitResults=[],n.onHitTestResultObservable=new f,n._onHitTestResults=function(e){var t=e.map((function(e){var t=z.FromArray(e.hitMatrix);return n._xrSessionManager.scene.useRightHandedSystem||t.toggleModelMatrixHandInPlace(),n.options.worldParentNode&&t.multiplyToRef(n.options.worldParentNode.getWorldMatrix(),t),{xrHitResult:e,transformationMatrix:t}}));n.lastNativeXRHitResults=e,n.onHitTestResultObservable.notifyObservers(t)},n._onSelect=function(e){n._onSelectEnabled&&t.XRHitTestWithSelectEvent(e,n._xrSessionManager.referenceSpace)},n.xrNativeFeatureName="hit-test",rr.Warn("A newer version of this plugin is available"),n}return m(t,e),t.XRHitTestWithRay=function(e,t,i,r){return e.requestHitTest(t,i).then((function(e){var t=r||function(e){return!!e.hitMatrix};return e.filter(t)}))},t.XRHitTestWithSelectEvent=function(e,t){var i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);var r=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,r,t)},t.prototype.attach=function(){return!!e.prototype.attach.call(this)&&(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0)},t.prototype.detach=function(){return!!e.prototype.detach.call(this)&&(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0)},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onHitTestResultObservable.clear()},t.prototype._onXRFrame=function(e){if(this.attached&&!this.options.testOnPointerDownOnly){var i=e.getViewerPose(this._xrSessionManager.referenceSpace);if(i){z.FromArrayToRef(i.transform.matrix,0,this._mat),V.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),V.TransformCoordinatesFromFloatsToRef(0,0,-1,this._mat,this._direction),this._direction.subtractInPlace(this._origin),this._direction.normalize();var r=new XRRay({x:this._origin.x,y:this._origin.y,z:this._origin.z,w:0},{x:this._direction.x,y:this._direction.y,z:this._direction.z,w:0});t.XRHitTestWithRay(this._xrSessionManager.session,r,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}},t.Name=Ss.HIT_TEST,t.Version=1,t}(As);xs.AddWebXRFeature(iI.Name,(function(e,t){return function(){return new iI(e,t)}}),iI.Version,!1);var rI=0,nI=function(e){function t(t,i){void 0===i&&(i={});var r=e.call(this,t)||this;return r._options=i,r._lastFrameDetected=new Set,r._trackedAnchors=[],r._futureAnchors=[],r.onAnchorAddedObservable=new f,r.onAnchorRemovedObservable=new f,r.onAnchorUpdatedObservable=new f,r._tmpVector=new V,r._tmpQuaternion=new G,r.xrNativeFeatureName="anchors",r}return m(t,e),Object.defineProperty(t.prototype,"referenceSpaceForFrameAnchors",{set:function(e){this._referenceSpaceForFrameAnchors=e},enumerable:!1,configurable:!0}),t.prototype._populateTmpTransformation=function(e,t){return this._tmpVector.copyFrom(e),this._tmpQuaternion.copyFrom(t),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpVector.z*=-1,this._tmpQuaternion.z*=-1,this._tmpQuaternion.w*=-1),{position:this._tmpVector,rotationQuaternion:this._tmpQuaternion}},t.prototype.addAnchorPointUsingHitTestResultAsync=function(e,t,i){return void 0===t&&(t=new V),void 0===i&&(i=new G),y(this,void 0,void 0,(function(){var r,n,o,a=this;return b(this,(function(s){switch(s.label){case 0:if(this._populateTmpTransformation(t,i),r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),e.xrHitResult.createAnchor)return[3,1];throw this.detach(),new Error("Anchors not enabled in this environment/browser");case 1:return s.trys.push([1,3,,4]),[4,e.xrHitResult.createAnchor(r)];case 2:return n=s.sent(),[2,new Promise((function(e,t){a._futureAnchors.push({nativeAnchor:n,resolved:!1,submitted:!0,xrTransformation:r,resolve:e,reject:t})}))];case 3:throw o=s.sent(),new Error(o);case 4:return[2]}}))}))},t.prototype.addAnchorAtPositionAndRotationAsync=function(e,t,i){return void 0===t&&(t=new G),void 0===i&&(i=!1),y(this,void 0,void 0,(function(){var r,n,o,a=this;return b(this,(function(s){switch(s.label){case 0:return this._populateTmpTransformation(e,t),r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),i&&this.attached&&this._xrSessionManager.currentFrame?[4,this._createAnchorAtTransformation(r,this._xrSessionManager.currentFrame)]:[3,2];case 1:return o=s.sent(),[3,3];case 2:o=void 0,s.label=3;case 3:return n=o,[2,new Promise((function(e,t){a._futureAnchors.push({nativeAnchor:n,resolved:!1,submitted:!1,xrTransformation:r,resolve:e,reject:t})}))]}}))}))},Object.defineProperty(t.prototype,"anchors",{get:function(){return this._trackedAnchors},enumerable:!1,configurable:!0}),t.prototype.detach=function(){if(!e.prototype.detach.call(this))return!1;if(!this._options.doNotRemoveAnchorsOnSessionEnded)for(;this._trackedAnchors.length;){var t=this._trackedAnchors.pop();if(t){try{t.remove()}catch(e){}this.onAnchorRemovedObservable.notifyObservers(t)}}return!0},t.prototype.dispose=function(){this._futureAnchors.length=0,e.prototype.dispose.call(this),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()},t.prototype._onXRFrame=function(e){var t=this;if(this.attached&&e){var i=e.trackedAnchors;if(i){var r=this._trackedAnchors.filter((function(e){return!i.has(e.xrAnchor)})).map((function(e){return t._trackedAnchors.indexOf(e)})),n=0;r.forEach((function(e){var i=t._trackedAnchors.splice(e-n,1)[0];t.onAnchorRemovedObservable.notifyObservers(i),n++})),i.forEach((function(i){if(t._lastFrameDetected.has(i)){var r=t._findIndexInAnchorArray(i);o=t._trackedAnchors[r];try{t._updateAnchorWithXRFrame(i,o,e),o.attachedNode&&(o.attachedNode.rotationQuaternion=o.attachedNode.rotationQuaternion||new G,o.transformationMatrix.decompose(o.attachedNode.scaling,o.attachedNode.rotationQuaternion,o.attachedNode.position)),t.onAnchorUpdatedObservable.notifyObservers(o)}catch(e){rr.Warn("Anchor could not be updated")}}else{var n={id:rI++,xrAnchor:i,remove:function(){return i.delete()}},o=t._updateAnchorWithXRFrame(i,n,e);t._trackedAnchors.push(o),t.onAnchorAddedObservable.notifyObservers(o);var a=t._futureAnchors.filter((function(e){return e.nativeAnchor===i}))[0];a&&(a.resolve(o),a.resolved=!0)}})),this._lastFrameDetected=i}this._futureAnchors.forEach((function(i){i.resolved||i.submitted||(t._createAnchorAtTransformation(i.xrTransformation,e).then((function(e){i.nativeAnchor=e}),(function(e){i.resolved=!0,i.reject(e)})),i.submitted=!0)}))}},t.prototype._findIndexInAnchorArray=function(e){for(var t=0;t<this._trackedAnchors.length;++t)if(this._trackedAnchors[t].xrAnchor===e)return t;return-1},t.prototype._updateAnchorWithXRFrame=function(e,t,i){var r=i.getPose(e.anchorSpace,this._xrSessionManager.referenceSpace);if(r){var n=t.transformationMatrix||new z;z.FromArrayToRef(r.transform.matrix,0,n),this._xrSessionManager.scene.useRightHandedSystem||n.toggleModelMatrixHandInPlace(),t.transformationMatrix=n,this._options.worldParentNode&&n.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),n)}return t},t.prototype._createAnchorAtTransformation=function(e,t){var i;return y(this,void 0,void 0,(function(){return b(this,(function(r){if(!t.createAnchor)throw this.detach(),new Error("Anchors are not enabled in your browser");try{return[2,t.createAnchor(e,null!==(i=this._referenceSpaceForFrameAnchors)&&void 0!==i?i:this._xrSessionManager.referenceSpace)]}catch(e){throw new Error(e)}return[2]}))}))},t.Name=Ss.ANCHOR_SYSTEM,t.Version=1,t}(As);xs.AddWebXRFeature(nI.Name,(function(e,t){return function(){return new nI(e,t)}}),nI.Version);var oI=0,aI=function(e){function t(t,i){void 0===i&&(i={});var r=e.call(this,t)||this;return r._options=i,r._detectedPlanes=[],r._enabled=!1,r._lastFrameDetected=new Set,r.onPlaneAddedObservable=new f,r.onPlaneRemovedObservable=new f,r.onPlaneUpdatedObservable=new f,r.xrNativeFeatureName="plane-detection",r._xrSessionManager.session?r._init():r._xrSessionManager.onXRSessionInit.addOnce((function(){r._init()})),r}return m(t,e),t.prototype.detach=function(){if(!e.prototype.detach.call(this))return!1;if(!this._options.doNotRemovePlanesOnSessionEnded)for(;this._detectedPlanes.length;){var t=this._detectedPlanes.pop();t&&this.onPlaneRemovedObservable.notifyObservers(t)}return!0},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onPlaneAddedObservable.clear(),this.onPlaneRemovedObservable.clear(),this.onPlaneUpdatedObservable.clear()},t.prototype.isCompatible=function(){return"undefined"!=typeof XRPlane},t.prototype.initiateRoomCapture=function(){return y(this,void 0,void 0,(function(){return b(this,(function(e){return this._xrSessionManager.session.initiateRoomCapture?[2,this._xrSessionManager.session.initiateRoomCapture()]:[2,Promise.reject("initiateRoomCapture is not supported on this session")]}))}))},t.prototype._onXRFrame=function(e){var t,i=this;if(this.attached&&this._enabled&&e){var r=e.detectedPlanes||(null===(t=e.worldInformation)||void 0===t?void 0:t.detectedPlanes);if(r){for(var n=0;n<this._detectedPlanes.length;n++){var o=this._detectedPlanes[n];r.has(o.xrPlane)||(this._detectedPlanes.splice(n--,1),this.onPlaneRemovedObservable.notifyObservers(o))}r.forEach((function(t){if(i._lastFrameDetected.has(t)){if(t.lastChangedTime===i._xrSessionManager.currentTimestamp){var r=i._findIndexInPlaneArray(t);o=i._detectedPlanes[r],i._updatePlaneWithXRPlane(t,o,e),i.onPlaneUpdatedObservable.notifyObservers(o)}}else{var n={id:oI++,xrPlane:t,polygonDefinition:[]},o=i._updatePlaneWithXRPlane(t,n,e);i._detectedPlanes.push(o),i.onPlaneAddedObservable.notifyObservers(o)}})),this._lastFrameDetected=r}}},t.prototype._init=function(){var e=this,t=function(){e._enabled=!0,e._detectedPlanes.length&&(e._detectedPlanes.length=0)};this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),this._xrSessionManager.session.updateWorldTrackingState?(this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),t()):t()},t.prototype._updatePlaneWithXRPlane=function(e,t,i){var r=this;t.polygonDefinition=e.polygon.map((function(e){var t=r._xrSessionManager.scene.useRightHandedSystem?1:-1;return new V(e.x,e.y,e.z*t)}));var n=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(n){var o=t.transformationMatrix||new z;z.FromArrayToRef(n.transform.matrix,0,o),this._xrSessionManager.scene.useRightHandedSystem||o.toggleModelMatrixHandInPlace(),t.transformationMatrix=o,this._options.worldParentNode&&o.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),o)}return t},t.prototype._findIndexInPlaneArray=function(e){for(var t=0;t<this._detectedPlanes.length;++t)if(this._detectedPlanes[t].xrPlane===e)return t;return-1},t.Name=Ss.PLANE_DETECTION,t.Version=1,t}(As);xs.AddWebXRFeature(aI.Name,(function(e,t){return function(){return new aI(e,t)}}),aI.Version);var sI=function(e){function t(t,i){void 0===i&&(i={});var r=e.call(this,t)||this;return r.options=i,r.onBackgroundStateChangedObservable=new f,r}return m(t,e),t.prototype.attach=function(){return this._setBackgroundState(!1),e.prototype.attach.call(this)},t.prototype.detach=function(){return this._setBackgroundState(!0),e.prototype.detach.call(this)},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onBackgroundStateChangedObservable.clear()},t.prototype._onXRFrame=function(e){},t.prototype._setBackgroundState=function(e){var t=this._xrSessionManager.scene;if(!this.options.ignoreEnvironmentHelper)if(this.options.environmentHelperRemovalFlags){if(this.options.environmentHelperRemovalFlags.skyBox){var i=t.getMeshByName("BackgroundSkybox");i&&i.setEnabled(e)}if(this.options.environmentHelperRemovalFlags.ground){var r=t.getMeshByName("BackgroundPlane");r&&r.setEnabled(e)}}else{var n=t.getMeshByName("BackgroundHelper");n&&n.setEnabled(e)}this.options.backgroundMeshes&&this.options.backgroundMeshes.forEach((function(t){return t.setEnabled(e)})),this.onBackgroundStateChangedObservable.notifyObservers(e)},t.Name=Ss.BACKGROUND_REMOVER,t.Version=1,t}(As);xs.AddWebXRFeature(sI.Name,(function(e,t){return function(){return new sI(e,t)}}),sI.Version,!0);var lI=function(){},cI=function(e){function t(t,i){var r=e.call(this,t)||this;return r._options=i,r._attachController=function(e){r._controllers[e.uniqueId]||(r._xrSessionManager.scene.isPhysicsEnabled()||ae.Warn("physics engine not enabled, skipped. Please add this controller manually."),r._options.physicsProperties.useControllerMesh&&e.inputSource.gamepad?e.onMotionControllerInitObservable.addOnce((function(t){t._doNotLoadControllerMesh?r._createPhysicsImpostor(e):t.onModelLoadedObservable.addOnce((function(){var i=new Ds(t.rootMesh,Ds.MeshImpostor,g({mass:0},r._options.physicsProperties)),n=e.grip||e.pointer;r._controllers[e.uniqueId]={xrController:e,impostor:i,oldPos:n.position.clone(),oldRotation:n.rotationQuaternion.clone()}}))})):r._createPhysicsImpostor(e))},r._controllers={},r._debugMode=!1,r._delta=0,r._lastTimestamp=0,r._tmpQuaternion=new G,r._tmpVector=new V,r._options.physicsProperties||(r._options.physicsProperties={}),r}return m(t,e),t.prototype._createPhysicsImpostor=function(e){var t=this._options.physicsProperties.impostorType||Ds.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,r=Gh("impostor-mesh-"+e.uniqueId,{diameterX:"number"==typeof i?i:i.width,diameterY:"number"==typeof i?i:i.height,diameterZ:"number"==typeof i?i:i.depth});r.isVisible=this._debugMode,r.isPickable=!1,r.rotationQuaternion=new G;var n=e.grip||e.pointer;r.position.copyFrom(n.position),r.rotationQuaternion.copyFrom(n.rotationQuaternion);var o=new Ds(r,t,g({mass:0},this._options.physicsProperties));this._controllers[e.uniqueId]={xrController:e,impostor:o,impostorMesh:r}},t.prototype._enablePhysicsDebug=function(){var e=this;this._debugMode=!0,Object.keys(this._controllers).forEach((function(t){var i=e._controllers[t];i.impostorMesh&&(i.impostorMesh.isVisible=!0)}))},t.prototype.addController=function(e){this._attachController(e)},t.prototype.attach=function(){var t=this;if(!e.prototype.attach.call(this))return!1;if(!this._options.xrInput)return!0;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(function(e){t._detachController(e.uniqueId)})),this._options.enableHeadsetImpostor){var i=this._options.headsetImpostorParams||{impostorType:Ds.SphereImpostor,restitution:.8,impostorSize:.3},r=i.impostorSize||.3;this._headsetMesh=Gh("headset-mesh",{diameterX:"number"==typeof r?r:r.width,diameterY:"number"==typeof r?r:r.height,diameterZ:"number"==typeof r?r:r.depth}),this._headsetMesh.rotationQuaternion=new G,this._headsetMesh.isVisible=!1,this._headsetImpostor=new Ds(this._headsetMesh,i.impostorType,g({mass:0},i))}return!0},t.prototype.detach=function(){var t=this;return!!e.prototype.detach.call(this)&&(Object.keys(this._controllers).forEach((function(e){t._detachController(e)})),this._headsetMesh&&this._headsetMesh.dispose(),!0)},t.prototype.getHeadsetImpostor=function(){return this._headsetImpostor},t.prototype.getImpostorForController=function(e){var t="string"==typeof e?e:e.uniqueId;return this._controllers[t]?this._controllers[t].impostor:null},t.prototype.setPhysicsProperties=function(e){this._options.physicsProperties=g(g({},this._options.physicsProperties),e)},t.prototype._onXRFrame=function(e){var t,i,r=this;if(this._delta=this._xrSessionManager.currentTimestamp-this._lastTimestamp,this._lastTimestamp=this._xrSessionManager.currentTimestamp,this._headsetMesh&&this._headsetImpostor){if(this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition),this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation),null===(t=this._options.xrInput.xrCamera._lastXRViewerPose)||void 0===t?void 0:t.linearVelocity){var n=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(n.x,n.y,n.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if(null===(i=this._options.xrInput.xrCamera._lastXRViewerPose)||void 0===i?void 0:i.angularVelocity){var o=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(o.x,o.y,o.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach((function(e){var t,i,n=r._controllers[e],o=n.xrController.grip||n.xrController.pointer,a=n.oldPos||n.impostorMesh.position;if(null===(t=n.xrController._lastXRPose)||void 0===t?void 0:t.linearVelocity){var s=n.xrController._lastXRPose.linearVelocity;r._tmpVector.set(s.x,s.y,s.z),n.impostor.setLinearVelocity(r._tmpVector)}else o.position.subtractToRef(a,r._tmpVector),r._tmpVector.scaleInPlace(1e3/r._delta),n.impostor.setLinearVelocity(r._tmpVector);a.copyFrom(o.position),r._debugMode&&ae.Log([r._tmpVector,"linear"]);var l=n.oldRotation||n.impostorMesh.rotationQuaternion;if(null===(i=n.xrController._lastXRPose)||void 0===i?void 0:i.angularVelocity){var c=n.xrController._lastXRPose.angularVelocity;r._tmpVector.set(c.x,c.y,c.z),n.impostor.setAngularVelocity(r._tmpVector)}else if(!l.equalsWithEpsilon(o.rotationQuaternion)){l.conjugateInPlace().multiplyToRef(o.rotationQuaternion,r._tmpQuaternion);var u=Math.sqrt(r._tmpQuaternion.x*r._tmpQuaternion.x+r._tmpQuaternion.y*r._tmpQuaternion.y+r._tmpQuaternion.z*r._tmpQuaternion.z);if(r._tmpVector.set(r._tmpQuaternion.x,r._tmpQuaternion.y,r._tmpQuaternion.z),u<.001)r._tmpVector.scaleInPlace(2);else{var h=2*Math.atan2(u,r._tmpQuaternion.w);r._tmpVector.scaleInPlace(h/(u*(r._delta/1e3)))}n.impostor.setAngularVelocity(r._tmpVector)}l.copyFrom(o.rotationQuaternion),r._debugMode&&ae.Log([r._tmpVector,r._tmpQuaternion,"angular"])}))},t.prototype._detachController=function(e){var t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])},t.Name=Ss.PHYSICS_CONTROLLERS,t.Version=1,t}(As);xs.AddWebXRFeature(cI.Name,(function(e,t){return function(){return new cI(e,t)}}),cI.Version,!0);var uI=function(e){function t(t,i){void 0===i&&(i={});var r=e.call(this,t)||this;return r.options=i,r._tmpMat=new z,r._tmpPos=new V,r._tmpQuat=new G,r._initHitTestSource=function(e){if(e){var t=new XRRay(r.options.offsetRay||{}),i={space:r.options.useReferenceSpace?e:r._xrSessionManager.viewerReferenceSpace,offsetRay:t};r.options.entityTypes&&(i.entityTypes=r.options.entityTypes),i.space?r._xrSessionManager.session.requestHitTestSource(i).then((function(e){r._xrHitTestSource&&r._xrHitTestSource.cancel(),r._xrHitTestSource=e})):rr.Warn("waiting for viewer reference space to initialize")}},r.autoCloneTransformation=!1,r.onHitTestResultObservable=new f,r.paused=!1,r.xrNativeFeatureName="hit-test",rr.Warn("Hit test is an experimental and unstable feature."),r}return m(t,e),t.prototype.attach=function(){var t=this;if(!e.prototype.attach.call(this))return!1;if(!this._xrSessionManager.session.requestHitTestSource)return!1;if(this.options.disablePermanentHitTest||(this._xrSessionManager.referenceSpace&&this._initHitTestSource(this._xrSessionManager.referenceSpace),this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource)),this.options.enableTransientHitTest){var i=new XRRay(this.options.transientOffsetRay||{});this._xrSessionManager.session.requestHitTestSourceForTransientInput({profile:this.options.transientHitTestProfile||"generic-touchscreen",offsetRay:i,entityTypes:this.options.entityTypes}).then((function(e){t._transientXrHitTestSource=e}))}return!0},t.prototype.detach=function(){return!!e.prototype.detach.call(this)&&(this._xrHitTestSource&&(this._xrHitTestSource.cancel(),this._xrHitTestSource=null),this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this._initHitTestSource),this._transientXrHitTestSource&&(this._transientXrHitTestSource.cancel(),this._transientXrHitTestSource=null),!0)},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onHitTestResultObservable.clear()},t.prototype._onXRFrame=function(e){var t=this;if(this.attached&&!this.paused){if(this._xrHitTestSource){var i=e.getHitTestResults(this._xrHitTestSource);this._processWebXRHitTestResult(i)}this._transientXrHitTestSource&&e.getHitTestResultsForTransientInput(this._transientXrHitTestSource).forEach((function(e){t._processWebXRHitTestResult(e.results,e.inputSource)}))}},t.prototype._processWebXRHitTestResult=function(e,t){var i=this,r=[];e.forEach((function(e){var n=e.getPose(i._xrSessionManager.referenceSpace);if(n){var o=n.transform.position,a=n.transform.orientation;i._tmpPos.set(o.x,o.y,o.z).scaleInPlace(i._xrSessionManager.worldScalingFactor),i._tmpQuat.set(a.x,a.y,a.z,a.w),z.FromFloat32ArrayToRefScaled(n.transform.matrix,0,1,i._tmpMat),i._xrSessionManager.scene.useRightHandedSystem||(i._tmpPos.z*=-1,i._tmpQuat.z*=-1,i._tmpQuat.w*=-1,i._tmpMat.toggleModelMatrixHandInPlace());var s={position:i.autoCloneTransformation?i._tmpPos.clone():i._tmpPos,rotationQuaternion:i.autoCloneTransformation?i._tmpQuat.clone():i._tmpQuat,transformationMatrix:i.autoCloneTransformation?i._tmpMat.clone():i._tmpMat,inputSource:t,isTransient:!!t,xrHitResult:e};r.push(s)}})),this.onHitTestResultObservable.notifyObservers(r)},t.Name=Ss.HIT_TEST,t.Version=2,t}(As);xs.AddWebXRFeature(uI.Name,(function(e,t){return function(){return new uI(e,t)}}),uI.Version,!1);var hI=function(e){function t(t){var i=e.call(this,t)||this;return i._enabled=!1,i._featurePointCloud=[],i.onFeaturePointsAddedObservable=new f,i.onFeaturePointsUpdatedObservable=new f,i.xrNativeFeatureName="bjsfeature-points",i._xrSessionManager.session?i._init():i._xrSessionManager.onXRSessionInit.addOnce((function(){i._init()})),i}return m(t,e),Object.defineProperty(t.prototype,"featurePointCloud",{get:function(){return this._featurePointCloud},enumerable:!1,configurable:!0}),t.prototype.detach=function(){return!!e.prototype.detach.call(this)&&(this.featurePointCloud.length=0,!0)},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._featurePointCloud.length=0,this.onFeaturePointsUpdatedObservable.clear(),this.onFeaturePointsAddedObservable.clear()},t.prototype._onXRFrame=function(e){if(this.attached&&this._enabled&&e){var t=e.featurePointCloud;if(t&&0!==t.length){if(t.length%5!=0)throw new Error("Received malformed feature point cloud of length: "+t.length);for(var i=t.length/5,r=[],n=[],o=0;o<i;o++){var a=5*o,s=t[a+4];this._featurePointCloud[s]?r.push(s):(this._featurePointCloud[s]={position:new V,confidenceValue:0},n.push(s)),this._featurePointCloud[s].position.x=t[a],this._featurePointCloud[s].position.y=t[a+1],this._featurePointCloud[s].position.z=t[a+2],this._featurePointCloud[s].confidenceValue=t[a+3]}n.length>0&&this.onFeaturePointsAddedObservable.notifyObservers(n),r.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(r)}}},t.prototype._init=function(){this._xrSessionManager.session.trySetFeaturePointCloudEnabled&&this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)&&(this._enabled=!0)},t.Name=Ss.FEATURE_POINTS,t.Version=1,t}(As);xs.AddWebXRFeature(hI.Name,(function(e){return function(){return new hI(e)}}),hI.Version);var dI,pI=0,fI=function(e){function t(t,i){void 0===i&&(i={});var r=e.call(this,t)||this;return r._options=i,r._detectedMeshes=new Map,r.onMeshAddedObservable=new f,r.onMeshRemovedObservable=new f,r.onMeshUpdatedObservable=new f,r.xrNativeFeatureName="mesh-detection",r._options.generateMeshes&&(r._options.convertCoordinateSystems=!0),r._xrSessionManager.session?r._init():r._xrSessionManager.onXRSessionInit.addOnce((function(){r._init()})),r}return m(t,e),t.prototype.detach=function(){var t=this;return!!e.prototype.detach.call(this)&&(this._xrSessionManager.isNative&&this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!1),this._options.doNotRemoveMeshesOnSessionEnded||(this._detectedMeshes.forEach((function(e){t.onMeshRemovedObservable.notifyObservers(e)})),this._detectedMeshes.clear()),!0)},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onMeshUpdatedObservable.clear()},t.prototype._onXRFrame=function(e){var t,i=this;try{if(!this.attached||!e)return;var r=e.detectedMeshes||(null===(t=e.worldInformation)||void 0===t?void 0:t.detectedMeshes);if(r){var n=new Set;this._detectedMeshes.forEach((function(e,t){r.has(t)||n.add(t)})),n.forEach((function(e){var t=i._detectedMeshes.get(e);t&&(i.onMeshRemovedObservable.notifyObservers(t),i._detectedMeshes.delete(e))})),r.forEach((function(t){if(i._detectedMeshes.has(t))t.lastChangedTime===i._xrSessionManager.currentTimestamp&&(n=i._detectedMeshes.get(t))&&(i._updateVertexDataWithXRMesh(t,n,e),i.onMeshUpdatedObservable.notifyObservers(n));else{var r={id:pI++,xrMesh:t},n=i._updateVertexDataWithXRMesh(t,r,e);i._detectedMeshes.set(t,n),i.onMeshAddedObservable.notifyObservers(n)}}))}}catch(e){ae.Log(e.stack)}},t.prototype._init=function(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!0),this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions))},t.prototype._updateVertexDataWithXRMesh=function(e,t,i){var r;t.xrMesh=e,t.worldParentNode=this._options.worldParentNode;var n=e.vertices||e.positions;if(this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=n,t.normals=e.normals;else{t.positions=new Float32Array(n.length);for(var o=0;o<n.length;o+=3)t.positions[o]=n[o],t.positions[o+1]=n[o+1],t.positions[o+2]=-1*n[o+2];if(e.normals)for(t.normals=new Float32Array(e.normals.length),o=0;o<e.normals.length;o+=3)t.normals[o]=e.normals[o],t.normals[o+1]=e.normals[o+1],t.normals[o+2]=-1*e.normals[o+2]}t.indices=e.indices;var a,s=i.getPose(e.meshSpace,this._xrSessionManager.referenceSpace);if(s){var l=t.transformationMatrix||new z;z.FromArrayToRef(s.transform.matrix,0,l),this._xrSessionManager.scene.useRightHandedSystem||l.toggleModelMatrixHandInPlace(),t.transformationMatrix=l,this._options.worldParentNode&&l.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),l)}if(this._options.generateMeshes)t.mesh?((a=t.mesh).updateVerticesData(Nr.PositionKind,t.positions),t.normals?a.updateVerticesData(Nr.NormalKind,t.normals):a.createNormals(!0),a.updateIndices(t.indices)):((a=new Fa("xr mesh "+t.id,this._xrSessionManager.scene)).rotationQuaternion=new G,a.setVerticesData(Nr.PositionKind,t.positions),t.normals?a.setVerticesData(Nr.NormalKind,t.normals):a.createNormals(!0),a.setIndices(t.indices,void 0,!0),t.mesh=a),null===(r=t.transformationMatrix)||void 0===r||r.decompose(t.mesh.scaling,t.mesh.rotationQuaternion,t.mesh.position)}return t},t.Name=Ss.MESH_DETECTION,t.Version=1,t}(As);xs.AddWebXRFeature(fI.Name,(function(e,t){return function(){return new fI(e,t)}}),fI.Version,!1),function(e){e[e.NotReceived=0]="NotReceived",e[e.Waiting=1]="Waiting",e[e.Received=2]="Received"}(dI||(dI={}));var _I=function(e){function t(t,i){var r=e.call(this,t)||this;return r.options=i,r.onUntrackableImageFoundObservable=new f,r.onTrackableImageFoundObservable=new f,r.onTrackedImageUpdatedObservable=new f,r._trackableScoreStatus=dI.NotReceived,r._trackedImages=[],r.xrNativeFeatureName="image-tracking",r}return m(t,e),t.prototype.attach=function(){return e.prototype.attach.call(this)},t.prototype.detach=function(){return e.prototype.detach.call(this)},t.prototype.getTrackedImageById=function(e){return this._trackedImages[e]||null},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._trackedImages.forEach((function(e){e.originalBitmap.close()})),this._trackedImages.length=0,this.onTrackableImageFoundObservable.clear(),this.onUntrackableImageFoundObservable.clear(),this.onTrackedImageUpdatedObservable.clear()},t.prototype.getXRSessionInitExtension=function(){return y(this,void 0,void 0,(function(){var e,t,i=this;return b(this,(function(r){switch(r.label){case 0:if(!this.options.images||!this.options.images.length)return[2,{}];e=this.options.images.map((function(e){return"string"==typeof e.src?i._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(e.src):Promise.resolve(e.src)})),r.label=1;case 1:return r.trys.push([1,3,,4]),[4,Promise.all(e)];case 2:return t=r.sent(),this._originalTrackingRequest=t.map((function(e,t){return{image:e,widthInMeters:i.options.images[t].estimatedRealWorldWidth}})),[2,{trackedImages:this._originalTrackingRequest}];case 3:return r.sent(),rr.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),[2,{}];case 4:return[2]}}))}))},t.prototype._onXRFrame=function(e){if(e.getImageTrackingResults&&this._trackableScoreStatus!==dI.Waiting)if(this._trackableScoreStatus!==dI.NotReceived)for(var t=0,i=e.getImageTrackingResults();t<i.length;t++){var r=i[t],n=!1,o=r.index,a=this._trackedImages[o];if(a){a.xrTrackingResult=r,a.realWorldWidth!==r.measuredWidthInMeters&&(a.realWorldWidth=r.measuredWidthInMeters,n=!0);var s=e.getPose(r.imageSpace,this._xrSessionManager.referenceSpace);if(s){var l=a.transformationMatrix;z.FromArrayToRef(s.transform.matrix,0,l),this._xrSessionManager.scene.useRightHandedSystem||l.toggleModelMatrixHandInPlace(),n=!0}var c="emulated"===r.trackingState;a.emulated!==c&&(a.emulated=c,n=!0),n&&this.onTrackedImageUpdatedObservable.notifyObservers(a)}}else this._checkScoresAsync()},t.prototype._checkScoresAsync=function(){return y(this,void 0,void 0,(function(){var e,t,i,r;return b(this,(function(n){switch(n.label){case 0:return this._xrSessionManager.session.getTrackedImageScores&&this._trackableScoreStatus===dI.NotReceived?(this._trackableScoreStatus=dI.Waiting,[4,this._xrSessionManager.session.getTrackedImageScores()]):[2];case 1:if(!(e=n.sent())||0===e.length)return this._trackableScoreStatus=dI.NotReceived,[2];for(t=0;t<e.length;++t)"untrackable"==e[t]?this.onUntrackableImageFoundObservable.notifyObservers(t):(i=this._originalTrackingRequest[t].image,r={id:t,originalBitmap:i,transformationMatrix:new z,ratio:i.width/i.height},this._trackedImages[t]=r,this.onTrackableImageFoundObservable.notifyObservers(r));return this._trackableScoreStatus=e.length>0?dI.Received:dI.NotReceived,[2]}}))}))},t.Name=Ss.IMAGE_TRACKING,t.Version=1,t}(As);xs.AddWebXRFeature(_I.Name,(function(e,t){return function(){return new _I(e,t)}}),_I.Version,!1);var mI=function(e){function t(t,i){var r=e.call(this,t)||this;return r.options=i,r._domOverlayType=null,r._beforeXRSelectListener=null,r._element=null,r.xrNativeFeatureName="dom-overlay",rr.Warn("dom-overlay is an experimental and unstable feature."),r}return m(t,e),t.prototype.attach=function(){return!(!e.prototype.attach.call(this)||!this._xrSessionManager.session.domOverlayState||null===this._xrSessionManager.session.domOverlayState.type||(this._domOverlayType=this._xrSessionManager.session.domOverlayState.type,null!==this._element&&!0===this.options.supressXRSelectEvents&&(this._beforeXRSelectListener=function(e){e.preventDefault()},this._element.addEventListener("beforexrselect",this._beforeXRSelectListener)),0))},Object.defineProperty(t.prototype,"domOverlayType",{get:function(){return this._domOverlayType},enumerable:!1,configurable:!0}),t.prototype.dispose=function(){e.prototype.dispose.call(this),null!==this._element&&this._beforeXRSelectListener&&this._element.removeEventListener("beforexrselect",this._beforeXRSelectListener)},t.prototype._onXRFrame=function(e){},t.prototype.getXRSessionInitExtension=function(){return y(this,void 0,void 0,(function(){var e;return b(this,(function(t){if(void 0===this.options.element)return rr.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),[2,{}];if("string"==typeof this.options.element){if(null===(e=document.querySelector(this.options.element)))return rr.Warn("element not found '".concat(this.options.element,"' (not requesting xr-dom-overlay)")),[2,{}];this._element=e}else this._element=this.options.element;return[2,{domOverlay:{root:this._element}}]}))}))},t.Name=Ss.DOM_OVERLAY,t.Version=1,t}(As);xs.AddWebXRFeature(mI.Name,(function(e,t){return function(){return new mI(e,t)}}),mI.Version,!1);var gI=function(e){function t(i,r){var n,o,a,s,l,c,u=this;return(u=e.call(this,i)||this)._controllers={},u._currentRegistrationConfigurations=[],u._movementDirection=new G,u._tmpRotationMatrix=z.Identity(),u._tmpTranslationDirection=new V,u._tmpMovementTranslation=new V,u._tempCacheQuaternion=new G,u._attachController=function(e){if(!u._controllers[e.uniqueId]){u._controllers[e.uniqueId]={xrController:e,registeredComponents:[]};var t=u._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){var i=function(){if(e.motionController)for(var i=function(i){var r=null;if(i.allowedComponentTypes)for(var n=0,o=i.allowedComponentTypes;n<o.length;n++){var a=o[n],s=e.motionController.getComponentOfType(a);if(null!==s){r=s;break}}if(i.mainComponentOnly){var l=e.motionController.getMainComponent();if(null===l)return"continue";r=l}if("function"==typeof i.componentSelectionPredicate&&(r=i.componentSelectionPredicate(e)),r&&i.forceHandedness&&e.inputSource.handedness!==i.forceHandedness)return"continue";if(null===r)return"continue";var c={registrationConfiguration:i,component:r};t.registeredComponents.push(c),"axisChangedHandler"in i&&(c.onAxisChangedObserver=r.onAxisValueChangedObservable.add((function(e){i.axisChangedHandler(e,u._movementState,u._featureContext,u._xrInput)}))),"buttonChangedhandler"in i&&(c.onButtonChangedObserver=r.onButtonStateChangedObservable.add((function(){r.changes.pressed&&i.buttonChangedhandler(r.changes.pressed,u._movementState,u._featureContext,u._xrInput)})))},r=0,n=u._currentRegistrationConfigurations;r<n.length;r++)i(n[r])};e.motionController?i():e.onMotionControllerInitObservable.addOnce((function(){i()}))}}},r&&void 0!==r.xrInput?(Array.isArray(r.customRegistrationConfigurations)?u._currentRegistrationConfigurations=r.customRegistrationConfigurations:u._currentRegistrationConfigurations=t.REGISTRATIONS.default,u._featureContext={movementEnabled:r.movementEnabled||!0,movementOrientationFollowsViewerPose:null===(n=r.movementOrientationFollowsViewerPose)||void 0===n||n,movementSpeed:null!==(o=r.movementSpeed)&&void 0!==o?o:1,movementThreshold:null!==(a=r.movementThreshold)&&void 0!==a?a:.25,rotationEnabled:null===(s=r.rotationEnabled)||void 0===s||s,rotationSpeed:null!==(l=r.rotationSpeed)&&void 0!==l?l:1,rotationThreshold:null!==(c=r.rotationThreshold)&&void 0!==c?c:.25},u._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},u._xrInput=r.xrInput,u):(rr.Error('WebXRControllerMovement feature requires "xrInput" option.'),u)}return m(t,e),Object.defineProperty(t.prototype,"movementDirection",{get:function(){return this._movementDirection},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"movementEnabled",{get:function(){return this._featureContext.movementEnabled},set:function(e){this._featureContext.movementEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"movementOrientationFollowsViewerPose",{get:function(){return this._featureContext.movementOrientationFollowsViewerPose},set:function(e){this._featureContext.movementOrientationFollowsViewerPose=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"movementSpeed",{get:function(){return this._featureContext.movementSpeed},set:function(e){this._featureContext.movementSpeed=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"movementThreshold",{get:function(){return this._featureContext.movementThreshold},set:function(e){this._featureContext.movementThreshold=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rotationEnabled",{get:function(){return this._featureContext.rotationEnabled},set:function(e){this._featureContext.rotationEnabled=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rotationSpeed",{get:function(){return this._featureContext.rotationSpeed},set:function(e){this._featureContext.rotationSpeed=e},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rotationThreshold",{get:function(){return this._featureContext.rotationThreshold},set:function(e){this._featureContext.rotationThreshold=e},enumerable:!1,configurable:!0}),t.prototype.attach=function(){var t=this;return!!e.prototype.attach.call(this)&&(this._xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable,(function(e){t._detachController(e.uniqueId)})),!0)},t.prototype.detach=function(){var t=this;return!!e.prototype.detach.call(this)&&(Object.keys(this._controllers).forEach((function(e){t._detachController(e)})),this._controllers={},!0)},t.prototype._onXRFrame=function(e){if(this.attached){if(0!==this._movementState.rotateX&&this._featureContext.rotationEnabled){var t=.001*this._xrSessionManager.scene.getEngine().getDeltaTime()*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this._featureContext.movementOrientationFollowsViewerPose?(this._xrInput.xrCamera.cameraRotation.y+=t,G.RotationYawPitchRollToRef(t,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection)):(G.RotationYawPitchRollToRef(3*t,0,0,this._tempCacheQuaternion),this._movementDirection.multiplyInPlace(this._tempCacheQuaternion))}else this._featureContext.movementOrientationFollowsViewerPose&&this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);(this._movementState.moveX||this._movementState.moveY)&&this._featureContext.movementEnabled&&(z.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),V.TransformCoordinatesToRef(this._tmpTranslationDirection,this._tmpRotationMatrix,this._tmpMovementTranslation),this._tmpMovementTranslation.scaleInPlace(this._xrInput.xrCamera._computeLocalCameraSpeed()*this._featureContext.movementSpeed),this._xrInput.xrCamera.cameraDirection.addInPlace(this._tmpMovementTranslation))}},t.prototype._detachController=function(e){var t=this._controllers[e];if(t){for(var i=0,r=t.registeredComponents;i<r.length;i++){var n=r[i];n.onAxisChangedObserver&&n.component.onAxisValueChangedObservable.remove(n.onAxisChangedObserver),n.onButtonChangedObserver&&n.component.onButtonStateChangedObservable.remove(n.onButtonChangedObserver)}delete this._controllers[e]}},t.Name=Ss.MOVEMENT,t.REGISTRATIONS={default:[{allowedComponentTypes:[Rg.THUMBSTICK_TYPE,Rg.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:function(e,t,i){t.rotateX=Math.abs(e.x)>i.rotationThreshold?e.x:0,t.rotateY=Math.abs(e.y)>i.rotationThreshold?e.y:0}},{allowedComponentTypes:[Rg.THUMBSTICK_TYPE,Rg.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:function(e,t,i){t.moveX=Math.abs(e.x)>i.movementThreshold?e.x:0,t.moveY=Math.abs(e.y)>i.movementThreshold?e.y:0}}]},t.Version=1,t}(As);xs.AddWebXRFeature(gI.Name,(function(e,t){return function(){return new gI(e,t)}}),gI.Version,!0);var vI=function(e){function t(t,i){var r=e.call(this,t)||this;return r.options=i,r._canvasContext=null,r._reflectionCubeMap=null,r._xrLightEstimate=null,r._xrLightProbe=null,r._xrWebGLBinding=null,r._lightDirection=V.Up().negateInPlace(),r._lightColor=Z.White(),r._intensity=1,r._sphericalHarmonics=new Ep,r._cubeMapPollTime=Date.now(),r._lightEstimationPollTime=Date.now(),r._reflectionCubeMapTextureSize=16,r.directionalLight=null,r.onReflectionCubeMapUpdatedObservable=new f,r._updateReflectionCubeMap=function(){var e;if(r._xrLightProbe){if(r.options.cubeMapPollInterval){var t=Date.now();if(t-r._cubeMapPollTime<r.options.cubeMapPollInterval)return;r._cubeMapPollTime=t}var i=r._getXRGLBinding().getReflectionCubeMap(r._xrLightProbe);if(i&&r._reflectionCubeMap){if(r._reflectionCubeMap._texture)null===(e=r._reflectionCubeMap._texture._hardwareTexture)||void 0===e||e.set(i),r._reflectionCubeMap._texture.getEngine().resetTextureCache();else{var n=new Pi(r._xrSessionManager.scene.getEngine(),Ti.Unknown);n.isCube=!0,n.invertY=!1,n._useSRGBBuffer="srgba8"===r.options.reflectionFormat,n.format=u.TEXTUREFORMAT_RGBA,n.generateMipMaps=!0,n.type="srgba8"!==r.options.reflectionFormat?u.TEXTURETYPE_HALF_FLOAT:u.TEXTURETYPE_UNSIGNED_BYTE,n.samplingMode=u.TEXTURE_LINEAR_LINEAR_MIPLINEAR,n.width=r._reflectionCubeMapTextureSize,n.height=r._reflectionCubeMapTextureSize,n._cachedWrapU=u.TEXTURE_WRAP_ADDRESSMODE,n._cachedWrapV=u.TEXTURE_WRAP_ADDRESSMODE,n._hardwareTexture=new br(i,r._getCanvasContext()),r._reflectionCubeMap._texture=n}r._reflectionCubeMap._texture.isReady=!0,r.options.disablePreFiltering?(r._xrSessionManager.scene.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag),r.onReflectionCubeMapUpdatedObservable.notifyObservers(r._reflectionCubeMap)):(r._xrLightProbe.removeEventListener("reflectionchange",r._updateReflectionCubeMap),r._hdrFilter.prefilter(r._reflectionCubeMap).then((function(){r._xrSessionManager.scene.markAllMaterialsAsDirty(u.MATERIAL_TextureDirtyFlag),r.onReflectionCubeMapUpdatedObservable.notifyObservers(r._reflectionCubeMap),r._xrLightProbe.addEventListener("reflectionchange",r._updateReflectionCubeMap)})))}}},r.xrNativeFeatureName="light-estimation",r.options.createDirectionalLightSource&&(r.directionalLight=new Am("light estimation directional",r._lightDirection,r._xrSessionManager.scene),r.directionalLight.position=new V(0,8,0),r.directionalLight.intensity=0,r.directionalLight.falloffType=un.FALLOFF_GLTF),r._hdrFilter=new Rv(r._xrSessionManager.scene.getEngine()),rr.Warn("light-estimation is an experimental and unstable feature."),r}return m(t,e),Object.defineProperty(t.prototype,"reflectionCubeMapTexture",{get:function(){return this._reflectionCubeMap},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"xrLightingEstimate",{get:function(){return this._xrLightEstimate?{lightColor:this._lightColor,lightDirection:this._lightDirection,lightIntensity:this._intensity,sphericalHarmonics:this._sphericalHarmonics}:this._xrLightEstimate},enumerable:!1,configurable:!0}),t.prototype._getCanvasContext=function(){return null===this._canvasContext&&(this._canvasContext=this._xrSessionManager.scene.getEngine()._gl),this._canvasContext},t.prototype._getXRGLBinding=function(){if(null===this._xrWebGLBinding){var e=this._getCanvasContext();this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,e)}return this._xrWebGLBinding},t.prototype.attach=function(){var t,i=this;if(!e.prototype.attach.call(this))return!1;var r=null!==(t=this.options.reflectionFormat)&&void 0!==t?t:this._xrSessionManager.session.preferredReflectionFormat||"srgba8";return this.options.reflectionFormat=r,this._xrSessionManager.session.requestLightProbe({reflectionFormat:r}).then((function(e){i._xrLightProbe=e,i.options.disableCubeMapReflection||(i._reflectionCubeMap||(i._reflectionCubeMap=new Ya(i._xrSessionManager.scene),i._reflectionCubeMap._isCube=!0,i._reflectionCubeMap.coordinatesMode=u.TEXTURE_CUBIC_MODE,i.options.setSceneEnvironmentTexture&&(i._xrSessionManager.scene.environmentTexture=i._reflectionCubeMap)),i._xrLightProbe.addEventListener("reflectionchange",i._updateReflectionCubeMap))})),!0},t.prototype.detach=function(){var t=e.prototype.detach.call(this);return null===this._xrLightProbe||this.options.disableCubeMapReflection||(this._xrLightProbe.removeEventListener("reflectionchange",this._updateReflectionCubeMap),this._xrLightProbe=null),this._canvasContext=null,this._xrLightEstimate=null,this._xrWebGLBinding=null,t},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onReflectionCubeMapUpdatedObservable.clear(),this.directionalLight&&(this.directionalLight.dispose(),this.directionalLight=null),null!==this._reflectionCubeMap&&(this._reflectionCubeMap._texture&&this._reflectionCubeMap._texture.dispose(),this._reflectionCubeMap.dispose(),this._reflectionCubeMap=null)},t.prototype._onXRFrame=function(e){var t;if(null!==this._xrLightProbe){if(this.options.lightEstimationPollInterval){var i=Date.now();if(i-this._lightEstimationPollTime<this.options.lightEstimationPollInterval)return;this._lightEstimationPollTime=i}if(this._xrLightEstimate=e.getLightEstimate(this._xrLightProbe),this._xrLightEstimate){this._intensity=Math.max(1,this._xrLightEstimate.primaryLightIntensity.x,this._xrLightEstimate.primaryLightIntensity.y,this._xrLightEstimate.primaryLightIntensity.z);var r=this._xrSessionManager.scene.useRightHandedSystem?1:-1;this.options.disableVectorReuse&&(this._lightDirection=new V,this._lightColor=new Z,this.directionalLight&&(this.directionalLight.direction=this._lightDirection,this.directionalLight.diffuse=this._lightColor)),this._lightDirection.copyFromFloats(this._xrLightEstimate.primaryLightDirection.x,this._xrLightEstimate.primaryLightDirection.y,this._xrLightEstimate.primaryLightDirection.z*r),this._lightColor.copyFromFloats(this._xrLightEstimate.primaryLightIntensity.x/this._intensity,this._xrLightEstimate.primaryLightIntensity.y/this._intensity,this._xrLightEstimate.primaryLightIntensity.z/this._intensity),this._sphericalHarmonics.updateFromFloatsArray(this._xrLightEstimate.sphericalHarmonicsCoefficients),this._reflectionCubeMap&&!this.options.disableSphericalPolynomial&&(this._reflectionCubeMap.sphericalPolynomial=this._reflectionCubeMap.sphericalPolynomial||new Sp,null===(t=this._reflectionCubeMap.sphericalPolynomial)||void 0===t||t.updateFromHarmonics(this._sphericalHarmonics)),this._lightDirection.negateInPlace(),this.directionalLight&&(this.directionalLight.direction.copyFrom(this._lightDirection),this.directionalLight.intensity=Math.min(this._intensity,1),this.directionalLight.diffuse.copyFrom(this._lightColor))}}},t.Name=Ss.LIGHT_ESTIMATION,t.Version=1,t}(As);xs.AddWebXRFeature(vI.Name,(function(e,t){return function(){return new vI(e,t)}}),vI.Version,!1);var yI=function(e){function t(t){var i=e.call(this,t)||this;return i.onEyeTrackingStartedObservable=new f,i.onEyeTrackingEndedObservable=new f,i.onEyeTrackingFrameUpdateObservable=new f,i._eyeTrackingStartListener=function(e){i._latestEyeSpace=e.gazeSpace,i._gazeRay=new hs(V.Zero(),V.Forward()),i.onEyeTrackingStartedObservable.notifyObservers(i._gazeRay)},i._eyeTrackingEndListener=function(){i._latestEyeSpace=null,i._gazeRay=null,i.onEyeTrackingEndedObservable.notifyObservers()},i.xrNativeFeatureName="eye-tracking",i._xrSessionManager.session?i._init():i._xrSessionManager.onXRSessionInit.addOnce((function(){i._init()})),i}return m(t,e),t.prototype.dispose=function(){e.prototype.dispose.call(this),this._xrSessionManager.session.removeEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.removeEventListener("eyetrackingend",this._eyeTrackingEndListener),this.onEyeTrackingStartedObservable.clear(),this.onEyeTrackingEndedObservable.clear(),this.onEyeTrackingFrameUpdateObservable.clear()},Object.defineProperty(t.prototype,"isEyeGazeValid",{get:function(){return!!this._gazeRay},enumerable:!1,configurable:!0}),t.prototype.getEyeGaze=function(){return this._gazeRay},t.prototype._onXRFrame=function(e){if(this.attached&&e&&this._latestEyeSpace&&this._gazeRay){var t=e.getPose(this._latestEyeSpace,this._xrSessionManager.referenceSpace);if(t){this._gazeRay.origin.set(t.transform.position.x,t.transform.position.y,t.transform.position.z).scaleInPlace(this._xrSessionManager.worldScalingFactor);var i=t.transform.orientation;H.Quaternion[0].set(i.x,i.y,i.z,i.w),this._xrSessionManager.scene.useRightHandedSystem?V.RightHandedForwardReadOnly.rotateByQuaternionToRef(H.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,H.Quaternion[0].z*=-1,H.Quaternion[0].w*=-1,V.LeftHandedForwardReadOnly.rotateByQuaternionToRef(H.Quaternion[0],this._gazeRay.direction)),this.onEyeTrackingFrameUpdateObservable.notifyObservers(this._gazeRay)}}},t.prototype._init=function(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.addEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.addEventListener("eyetrackingend",this._eyeTrackingEndListener))},t.Name=Ss.EYE_TRACKING,t.Version=1,t}(As);xs.AddWebXRFeature(yI.Name,(function(e){return function(){return new yI(e)}}),yI.Version,!1);var bI=function(){function e(e,t){this._samples=[],this._idx=0;for(var i=0;i<e;++i)this._samples.push(t?t():U.Zero())}return Object.defineProperty(e.prototype,"length",{get:function(){return this._samples.length},enumerable:!1,configurable:!0}),e.prototype.push=function(e,t){this._idx=(this._idx+this._samples.length-1)%this._samples.length,this.at(0).copyFromFloats(e,t)},e.prototype.at=function(e){if(e>=this._samples.length)throw new Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]},e}(),TI=function(){function e(){this._samples=new bI(20),this._entropy=0,this.onFirstStepDetected=new f}return e.prototype.update=function(e,t,i,r){this._samples.push(e,t);var n=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=U.Distance(n,this._samples.at(1)),!(this._entropy>this._entropyThreshold)){var o;for(o=this._samePointCheckStartIdx;o<this._samples.length&&!(U.DistanceSquared(n,this._samples.at(o))<this._samePointSquaredDistanceThreshold);++o);if(o!==this._samples.length){for(var a=-1,s=0,l=void 0,c=1;c<o;++c)(l=U.DistanceSquared(n,this._samples.at(c)))>a&&(s=c,a=l);if(!(a<this._apexSquaredDistanceThreshold)){var u=this._samples.at(s),h=u.subtract(n);h.normalize();var d,p=H.Vector2[0],f=0;for(c=1;c<o;++c)this._samples.at(c).subtractToRef(n,p),d=U.Dot(h,p),f+=p.lengthSquared()-d*d;if(!(f>o*this._squaredProjectionDistanceThreshold)){var _=H.Vector3[0];_.set(i,r,0);var m=H.Vector3[1];m.set(h.x,h.y,0);var g=V.Cross(_,m).z>0,v=n.clone(),y=n.clone();u.subtractToRef(n,h),g?(h.scaleAndAddToRef(this._axisToApexShrinkFactor,v),h.scaleAndAddToRef(this._axisToApexExtendFactor,y)):(h.scaleAndAddToRef(this._axisToApexExtendFactor,v),h.scaleAndAddToRef(this._axisToApexShrinkFactor,y)),this.onFirstStepDetected.notifyObservers({leftApex:v,rightApex:y,currentPosition:n,currentStepDirection:g?"right":"left"})}}}}},e.prototype.reset=function(){for(var e=0;e<this._samples.length;++e)this._samples.at(e).copyFromFloats(0,0)},Object.defineProperty(e.prototype,"_samePointCheckStartIdx",{get:function(){return Math.floor(this._samples.length/3)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"_samePointSquaredDistanceThreshold",{get:function(){return 9e-4},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"_apexSquaredDistanceThreshold",{get:function(){return.0081},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"_squaredProjectionDistanceThreshold",{get:function(){return 9e-4},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"_axisToApexShrinkFactor",{get:function(){return.8},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"_axisToApexExtendFactor",{get:function(){return-1.6},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"_entropyDecayFactor",{get:function(){return.93},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"_entropyThreshold",{get:function(){return.4},enumerable:!1,configurable:!0}),e}(),EI=function(){function e(e,t,i,r){this._leftApex=new U,this._rightApex=new U,this._currentPosition=new U,this._axis=new U,this._axisLength=-1,this._forward=new U,this._steppingLeft=!1,this._t=-1,this._maxT=-1,this._maxTPosition=new U,this._vitality=0,this.onMovement=new f,this.onFootfall=new f,this._reset(e,t,i,"left"===r)}return e.prototype._reset=function(e,t,i,r){this._leftApex.copyFrom(e),this._rightApex.copyFrom(t),this._steppingLeft=r,this._steppingLeft?(this._leftApex.subtractToRef(this._rightApex,this._axis),this._forward.copyFromFloats(-this._axis.y,this._axis.x)):(this._rightApex.subtractToRef(this._leftApex,this._axis),this._forward.copyFromFloats(this._axis.y,-this._axis.x)),this._axisLength=this._axis.length(),this._forward.scaleInPlace(1/this._axisLength),this._updateTAndVitality(i.x,i.y),this._maxT=this._t,this._maxTPosition.copyFrom(i),this._vitality=1},e.prototype._updateTAndVitality=function(e,t){this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._currentPosition.subtractInPlace(this._rightApex):this._currentPosition.subtractInPlace(this._leftApex);var i=this._t,r=U.Dot(this._currentPosition,this._axis);this._t=r/(this._axisLength*this._axisLength);var n=this._currentPosition.lengthSquared()-r/this._axisLength*(r/this._axisLength);this._vitality*=.92-100*Math.max(n-.0016,0)+Math.max(this._t-i,0)},e.prototype.update=function(e,t){if(this._vitality<this._vitalityThreshold)return!1;var i=this._t;return this._updateTAndVitality(e,t),this._t>this._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitality<this._vitalityThreshold||(this._t>i&&(this.onMovement.notifyObservers({deltaT:this._t-i}),i<.5&&this._t>=.5&&this.onFootfall.notifyObservers({foot:this._steppingLeft?"left":"right"})),this._t<.95*this._maxT&&(this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._leftApex.copyFrom(this._maxTPosition):this._rightApex.copyFrom(this._maxTPosition),this._reset(this._leftApex,this._rightApex,this._currentPosition,!this._steppingLeft)),this._axisLength<.03))},Object.defineProperty(e.prototype,"_vitalityThreshold",{get:function(){return.1},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"forward",{get:function(){return this._forward},enumerable:!1,configurable:!0}),e}(),SI=function(){function e(t){var i=this;this._detector=new TI,this._walker=null,this._movement=new U,this._millisecondsSinceLastUpdate=e._MillisecondsPerUpdate,this.movementThisFrame=V.Zero(),this._engine=t,this._detector.onFirstStepDetected.add((function(e){i._walker||(i._walker=new EI(e.leftApex,e.rightApex,e.currentPosition,e.currentStepDirection),i._walker.onFootfall.add((function(){ae.Log("Footfall!")})),i._walker.onMovement.add((function(e){i._walker.forward.scaleAndAddToRef(.024*e.deltaT,i._movement)})))}))}return Object.defineProperty(e,"_MillisecondsPerUpdate",{get:function(){return 1e3/15},enumerable:!1,configurable:!0}),e.prototype.update=function(t,i){i.y=0,i.normalize(),this._millisecondsSinceLastUpdate+=this._engine.getDeltaTime(),this._millisecondsSinceLastUpdate>=e._MillisecondsPerUpdate&&(this._millisecondsSinceLastUpdate-=e._MillisecondsPerUpdate,this._detector.update(t.x,t.z,i.x,i.z),this._walker&&(this._walker.update(t.x,t.z)||(this._walker=null)),this._movement.scaleInPlace(.85)),this.movementThisFrame.set(this._movement.x,0,this._movement.y)},e}(),xI=function(e){function t(t,i){var r=e.call(this,t)||this;return r._up=new V,r._forward=new V,r._position=new V,r._movement=new V,r._sessionManager=t,r.locomotionTarget=i.locomotionTarget,r._isLocomotionTargetWebXRCamera&&ae.Warn("Using walking locomotion directly on a WebXRCamera may have unintended interactions with other XR techniques. Using an XR space parent is highly recommended"),r}return m(t,e),Object.defineProperty(t,"Name",{get:function(){return Ss.WALKING_LOCOMOTION},enumerable:!1,configurable:!0}),Object.defineProperty(t,"Version",{get:function(){return 1},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"locomotionTarget",{get:function(){return this._locomotionTarget},set:function(e){this._locomotionTarget=e,this._isLocomotionTargetWebXRCamera="WebXRCamera"===this._locomotionTarget.getClassName()},enumerable:!1,configurable:!0}),t.prototype.isCompatible=function(){return void 0===this._sessionManager.sessionMode||"immersive-vr"===this._sessionManager.sessionMode},t.prototype.attach=function(){return!(!this.isCompatible||!e.prototype.attach.call(this)||(this._walker=new SI(this._sessionManager.scene.getEngine()),0))},t.prototype.detach=function(){return!!e.prototype.detach.call(this)&&(this._walker=null,!0)},t.prototype._onXRFrame=function(e){var t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(t){var i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,r=t.transform.matrix;this._up.copyFromFloats(r[4],r[5],i*r[6]),this._forward.copyFromFloats(r[8],r[9],i*r[10]),this._position.copyFromFloats(r[12],r[13],i*r[14]),this._forward.scaleAndAddToRef(.05,this._position),this._up.scaleAndAddToRef(-.05,this._position),this._walker.update(this._position,this._forward),this._movement.copyFrom(this._walker.movementThisFrame),this._isLocomotionTargetWebXRCamera||V.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}},t}(As);xs.AddWebXRFeature(xI.Name,(function(e,t){return function(){return new xI(e,t)}}),xI.Version,!1);var AI=function(e){function t(t,i,r,n,o,a,s){void 0===s&&(s=null);var l=e.call(this,t,i,r,n,a)||this;return l.getWidth=t,l.getHeight=i,l.layer=r,l.layerType=n,l.isMultiview=o,l.createRTTProvider=a,l._originalInternalTexture=s,l}return m(t,e),t}(zu),CI=function(e){function t(t,i,r){var n=e.call(this,t.scene,r)||this;return n._xrSessionManager=t,n._xrWebGLBinding=i,n.layerWrapper=r,n._lastSubImages=new Map,n.onRenderTargetTextureCreatedObservable=new f,n._compositionLayer=r.layer,n}return m(t,e),t.prototype._getRenderTargetForSubImage=function(e,t){var i,r,n,o;void 0===t&&(t="none");var a=this._lastSubImages.get(t),s="right"==t?1:0,l=null!==(i=e.colorTextureWidth)&&void 0!==i?i:e.textureWidth,c=null!==(r=e.colorTextureHeight)&&void 0!==r?r:e.textureHeight;if(!this._renderTargetTextures[s]||(null==a?void 0:a.textureWidth)!==l||(null==a?void 0:a.textureHeight)!==c){var u=void 0,h=null!==(n=e.depthStencilTextureWidth)&&void 0!==n?n:l,d=null!==(o=e.depthStencilTextureHeight)&&void 0!==o?o:c;l!==h&&c!==d||(u=e.depthStencilTexture),this._renderTargetTextures[s]=this._createRenderTargetTexture(l,c,null,e.colorTexture,u,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:l,framebufferHeight:c},this.onRenderTargetTextureCreatedObservable.notifyObservers({texture:this._renderTargetTextures[s],eye:t})}return this._lastSubImages.set(t,e),this._renderTargetTextures[s]},t.prototype._getSubImageForEye=function(e){var t=this._xrSessionManager.currentFrame;return t?this._xrWebGLBinding.getSubImage(this._compositionLayer,t,e):null},t.prototype.getRenderTargetTextureForEye=function(e){var t=this._getSubImageForEye(e);return t?this._getRenderTargetForSubImage(t,e):null},t.prototype.getRenderTargetTextureForView=function(e){return this.getRenderTargetTextureForEye(null==e?void 0:e.eye)},t.prototype._setViewportForSubImage=function(e,t){var i,r,n=null!==(i=t.colorTextureWidth)&&void 0!==i?i:t.textureWidth,o=null!==(r=t.colorTextureHeight)&&void 0!==r?r:t.textureHeight,a=t.viewport;e.x=a.x/n,e.y=a.y/o,e.width=a.width/n,e.height=a.height/o},t.prototype.trySetViewportForView=function(e,t){var i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return!!i&&(this._setViewportForSubImage(e,i),!0)},t}(Wu),RI=function(e){function t(t,i,r){var n=e.call(this,(function(){return t.textureWidth}),(function(){return t.textureHeight}),t,"XRProjectionLayer",i,(function(e){return new PI(e,r,n)}))||this;return n.layer=t,n}return m(t,e),t}(AI),PI=function(e){function t(t,i,r){var n=e.call(this,t,i,r)||this;return n.layerWrapper=r,n._projectionLayer=r.layer,n}return m(t,e),t.prototype._getSubImageForView=function(e){return this._xrWebGLBinding.getViewSubImage(this._projectionLayer,e)},t.prototype.getRenderTargetTextureForView=function(e){return this._getRenderTargetForSubImage(this._getSubImageForView(e),e.eye)},t.prototype.getRenderTargetTextureForEye=function(e){var t=this._lastSubImages.get(e);return t?this._getRenderTargetForSubImage(t,e):null},t.prototype.trySetViewportForView=function(e,t){var i=this._lastSubImages.get(t.eye)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)},t}(CI),II={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1,clearOnAccess:!1},MI={},OI=function(e){function t(t,i){void 0===i&&(i={});var r=e.call(this,t)||this;return r._options=i,r._existingLayers=[],r._isMultiviewEnabled=!1,r._projectionLayerInitialized=!1,r._compositionLayerTextureMapping=new WeakMap,r._layerToRTTProviderMapping=new WeakMap,r.xrNativeFeatureName="layers",r}return m(t,e),t.prototype.attach=function(){if(!e.prototype.attach.call(this))return!1;var t=this._xrSessionManager.scene.getEngine();this._glContext=t._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this._existingLayers.length=0;var i=g(g({},II),this._options.projectionLayerInit);return this._isMultiviewEnabled=this._options.preferMultiviewOnInit&&t.getCaps().multiview,this.createProjectionLayer(i),this._projectionLayerInitialized=!0,!0},t.prototype.detach=function(){return!!e.prototype.detach.call(this)&&(this._existingLayers.forEach((function(e){e.dispose()})),this._existingLayers.length=0,this._projectionLayerInitialized=!1,!0)},t.prototype.createXRWebGLLayer=function(e){void 0===e&&(e=MI);var t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new Hu(t)},t.prototype._validateLayerInit=function(e,t){if(void 0===t&&(t=this._isMultiviewEnabled),!this._xrSessionManager.inXRSession)throw new Error("Cannot create a layer outside of a WebXR session. Make sure the session has started before creating layers.");if(t&&"texture-array"!==e.textureType)throw new Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'.");if(!t&&"texture-array"===e.textureType)throw new Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'.")},t.prototype._extendXRLayerInit=function(e,t){return void 0===t&&(t=this._isMultiviewEnabled),t&&(e.textureType="texture-array"),e},t.prototype.createProjectionLayer=function(e,t){void 0===e&&(e=II),void 0===t&&(t=this._isMultiviewEnabled),this._extendXRLayerInit(e,t),this._validateLayerInit(e,t);var i=this._xrWebGLBinding.createProjectionLayer(e),r=new RI(i,t,this._xrWebGLBinding);return this.addXRSessionLayer(r),r},t.prototype._createQuadLayer=function(e,t){var i=this;void 0===e&&(e={params:{}}),this._extendXRLayerInit(e.params,!1);var r=this._existingLayers[0].layer.textureWidth,n=this._existingLayers[0].layer.textureHeight,o=g({space:this._xrSessionManager.referenceSpace,viewPixelWidth:r,viewPixelHeight:n,clearOnAccess:!0},e.params);this._validateLayerInit(o,!1);var a=this._xrWebGLBinding.createQuadLayer(o);a.width=this._isMultiviewEnabled?1:2,a.height=1;var s=new AI((function(){return a.width}),(function(){return a.height}),a,"XRQuadLayer",!1,(function(e){return new CI(e,i._xrWebGLBinding,s)}));t&&this._compositionLayerTextureMapping.set(a,t);var l=s.createRenderTargetTextureProvider(this._xrSessionManager);return this._layerToRTTProviderMapping.set(a,l),this.addXRSessionLayer(s),s},t.prototype.addFullscreenAdvancedDynamicTexture=function(e,t){var i=this;void 0===t&&(t={distanceFromHeadset:1.5});var r=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}},e),n=r.layer,o={x:0,y:0,z:-Math.max(.1,t.distanceFromHeadset)};n.transform=new XRRigidTransform(o,{x:0,y:0,z:0,w:1});var a=this._layerToRTTProviderMapping.get(n);if(!a)throw new Error("Could not find the RTT provider for the layer");var s=this._xrSessionManager.scene.layers.find((function(t){return t.texture===e}));if(!s)throw new Error("Could not find the babylon layer for the texture");return a.onRenderTargetTextureCreatedObservable.add((function(e){e.eye&&"right"===e.eye||(e.texture.clearColor=new J(0,0,0,0),s.renderTargetTextures.push(e.texture),s.renderOnlyInRenderTargetTextures=!0,i._xrSessionManager.scene.onBeforeRenderObservable.add((function(){e.texture.render()})),s.renderTargetTextures.push(e.texture),s.renderOnlyInRenderTargetTextures=!0,i._xrSessionManager.onXRSessionEnded.addOnce((function(){s.renderTargetTextures.splice(s.renderTargetTextures.indexOf(e.texture),1),s.renderOnlyInRenderTargetTextures=!1})))})),r},t.prototype._addLensFlareSystem=function(e){var t=this,i=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}}),r=i.layer;r.width=2,r.height=1;r.transform=new XRRigidTransform({x:0,y:0,z:-10},{x:0,y:0,z:0,w:1});var n=this._layerToRTTProviderMapping.get(r);if(!n)throw new Error("Could not find the RTT provider for the layer");return n.onRenderTargetTextureCreatedObservable.add((function(t){t.texture.clearColor=new J(0,0,0,0),t.texture.customRenderFunction=function(){e.render()}})),this._xrSessionManager.onXRSessionInit.add((function(){t._xrSessionManager.scene.lensFlareSystems.splice(t._xrSessionManager.scene.lensFlareSystems.indexOf(e),1)})),this._xrSessionManager.onXRSessionEnded.add((function(){t._xrSessionManager.scene.lensFlareSystems.push(e)})),i},t.prototype.addXRSessionLayer=function(e){this._existingLayers.push(e),this.setXRSessionLayers(this._existingLayers)},t.prototype.setXRSessionLayers=function(e){void 0===e&&(e=this._existingLayers);var t=g({},this._xrSessionManager.session.renderState);t.baseLayer=void 0,t.layers=e.map((function(e){return e.layer})),this._xrSessionManager.updateRenderState(t),this._projectionLayerInitialized||this._xrSessionManager._setBaseLayerWrapper(e.length>0?e.at(0):null)},t.prototype.isCompatible=function(){return!this._xrSessionManager.isNative&&"undefined"!=typeof XRWebGLBinding&&!!XRWebGLBinding.prototype.createProjectionLayer},t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype._onXRFrame=function(e){for(var t=this._existingLayers,i=0;i<t.length;++i){var r=t[i];if("XRProjectionLayer"!==r.layerType){var n=this._layerToRTTProviderMapping.get(r.layer);if(!n)continue;if(n.layerWrapper.isMultiview){var o=e.getViewerPose(this._xrSessionManager.referenceSpace);if(o)for(var a=o.views,s=0;s<a.length;++s){var l=a[s];n.getRenderTargetTextureForView(l)}}else n.getRenderTargetTextureForView()}}},t.Name=Ss.LAYERS,t.Version=1,t}(As);xs.AddWebXRFeature(OI.Name,(function(e,t){return function(){return new OI(e,t)}}),OI.Version,!1);var DI=function(e){function t(t,i){var r=e.call(this,t)||this;return r.options=i,r._width=null,r._height=null,r._rawValueToMeters=null,r._normDepthBufferFromNormView=null,r._cachedDepthBuffer=null,r._cachedWebGLTexture=null,r._cachedDepthImageTexture=null,r.onGetDepthInMetersAvailable=new f,r.xrNativeFeatureName="depth-sensing",rr.Warn("depth-sensing is an experimental and unstable feature."),r}return m(t,e),Object.defineProperty(t.prototype,"width",{get:function(){return this._width},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"height",{get:function(){return this._height},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"rawValueToMeters",{get:function(){return this._rawValueToMeters},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"normDepthBufferFromNormView",{get:function(){return this._normDepthBufferFromNormView},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"depthUsage",{get:function(){switch(this._xrSessionManager.session.depthUsage){case"cpu-optimized":return"cpu";case"gpu-optimized":return"gpu"}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"depthDataFormat",{get:function(){switch(this._xrSessionManager.session.depthDataFormat){case"luminance-alpha":return"ushort";case"float32":return"float"}},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"latestInternalTexture",{get:function(){var e,t;if(!this._cachedWebGLTexture)return null;var i=this._xrSessionManager.scene.getEngine(),r=new Pi(i,Ti.Unknown);return r.isCube=!1,r.invertY=!1,r._useSRGBBuffer=!1,r.format="ushort"===this.depthDataFormat?u.TEXTUREFORMAT_LUMINANCE_ALPHA:u.TEXTUREFORMAT_RGBA,r.generateMipMaps=!1,r.type="ushort"===this.depthDataFormat?u.TEXTURETYPE_UNSIGNED_SHORT:u.TEXTURETYPE_FLOAT,r.samplingMode=u.TEXTURE_NEAREST_LINEAR,r.width=null!==(e=this.width)&&void 0!==e?e:0,r.height=null!==(t=this.height)&&void 0!==t?t:0,r._cachedWrapU=u.TEXTURE_WRAP_ADDRESSMODE,r._cachedWrapV=u.TEXTURE_WRAP_ADDRESSMODE,r._hardwareTexture=new br(this._cachedWebGLTexture,i._gl),r},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"latestDepthBuffer",{get:function(){return this._cachedDepthBuffer?"ushort"===this.depthDataFormat?new Uint16Array(this._cachedDepthBuffer):new Float32Array(this._cachedDepthBuffer):null},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"latestDepthImageTexture",{get:function(){return this._cachedDepthImageTexture},enumerable:!1,configurable:!0}),t.prototype.attach=function(t){return!!e.prototype.attach.call(this,t)&&null!=this._xrSessionManager.session.depthDataFormat&&null!=this._xrSessionManager.session.depthUsage&&(this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._xrSessionManager.scene.getEngine()._gl),!0)},t.prototype.dispose=function(){var e;null===(e=this._cachedDepthImageTexture)||void 0===e||e.dispose()},t.prototype._onXRFrame=function(e){var t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(null!=i)for(var r=0,n=i.views;r<n.length;r++){var o=n[r];switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,o,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,o,this.depthDataFormat);break;default:rr.Error("Unknown depth usage"),this.detach()}}},t.prototype._updateDepthInformationAndTextureCPUDepthUsage=function(e,t,i){var r,n=e.getDepthInformation(t);if(null!==n){var o=(r=n).data,a=r.width,s=r.height,l=r.rawValueToMeters,c=r.getDepthInMeters;switch(this._width=a,this._height=s,this._rawValueToMeters=l,this._cachedDepthBuffer=o,this.onGetDepthInMetersAvailable.notifyObservers(c.bind(n)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=is.CreateRTexture(null,a,s,this._xrSessionManager.scene,!1,!0,Ja.NEAREST_SAMPLINGMODE,Do.TEXTURETYPE_FLOAT)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(o)).map((function(e){return e*l})));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(o).map((function(e){return e*l})))}}},t.prototype._updateDepthInformationAndTextureWebGLDepthUsage=function(e,t,i){var r,n=e.getDepthInformation(t);if(null!==n){var o=(r=n).texture,a=r.width,s=r.height;this._width=a,this._height=s,this._cachedWebGLTexture=o;var l=this._xrSessionManager.scene,c=l.getEngine().wrapWebGLTexture(o);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=is.CreateRTexture(null,a,s,l,!1,!0,Ja.NEAREST_SAMPLINGMODE,"ushort"===i?Do.TEXTURETYPE_UNSIGNED_BYTE:Do.TEXTURETYPE_FLOAT)),this._cachedDepthImageTexture._texture=c}},t.prototype.getXRSessionInitExtension=function(){var e=this,t=null!=this.options.usagePreference&&0!==this.options.usagePreference.length,i=null!=this.options.dataFormatPreference&&0!==this.options.dataFormatPreference.length;return new Promise((function(r){r(t&&i?{depthSensing:{usagePreference:e.options.usagePreference.map((function(e){switch(e){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}})),dataFormatPreference:e.options.dataFormatPreference.map((function(e){switch(e){case"ushort":return"luminance-alpha";case"float":return"float32"}}))}}:{})}))},t.Name=Ss.DEPTH_SENSING,t.Version=1,t}(As);xs.AddWebXRFeature(DI.Name,(function(e,t){return function(){return new DI(e,t)}}),DI.Version,!1);li.ShadersStore.velocityPixelShader="precision highp float;\n#define CUSTOM_FRAGMENT_BEGIN\nvarying vec4 clipPos;varying vec4 previousClipPos;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nhighp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";li.ShadersStore.velocityVertexShader="#define CUSTOM_VERTEX_BEGIN\n#define VELOCITY\nattribute vec3 position;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;uniform mat4 previousViewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR;\n#endif\nvarying vec4 clipPos;varying vec4 previousClipPos;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#include<instancesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;}\n#elif\nclipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";var NI=function(e){function t(t,i,r,n){void 0===n&&(n=512);var o=e.call(this,"spacewarp rtt",n,r,!1,!0,u.TEXTURETYPE_HALF_FLOAT,!1,void 0,!1,!1,!0,void 0,!0)||this;return o._originalPairing=[],o._previousWorldMatrices=[],o._previousTransforms=[z.Identity(),z.Identity()],o._renderTarget=o.getScene().getEngine().createMultiviewRenderTargetTexture(o.getRenderWidth(),o.getRenderHeight(),t,i),o._renderTarget._disposeOnlyFramebuffers=!0,o._texture=o._renderTarget.texture,o._texture.isMultiview=!0,o._texture.format=u.TEXTUREFORMAT_RGBA,r&&(o._velocityMaterial=new ld("velocity shader material",r,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),o._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,o._velocityMaterial.onBindObservable.add((function(e){o._previousWorldMatrices[e.uniqueId]=o._previousWorldMatrices[e.uniqueId]||e.getWorldMatrix(),o._velocityMaterial.getEffect().setMatrix("previousWorld",o._previousWorldMatrices[e.uniqueId]),o._previousWorldMatrices[e.uniqueId]=e.getWorldMatrix(),o._velocityMaterial.getEffect().setMatrix("previousViewProjection",o._previousTransforms[0]),o._velocityMaterial.getEffect().setMatrix("previousViewProjectionR",o._previousTransforms[1]),o._previousTransforms[0].copyFrom(r.getTransformMatrix()),o._previousTransforms[1].copyFrom(r._transformMatrixR)})),o._velocityMaterial.freeze()),o}return m(t,e),t.prototype.render=function(t,i){var r=this;void 0===t&&(t=!1),void 0===i&&(i=!1),this._originalPairing.length=0;var n=this.getScene();n&&this._velocityMaterial&&n.getActiveMeshes().forEach((function(e){r._originalPairing.push([e,e.material]),e.material=r._velocityMaterial})),e.prototype.render.call(this,t,i),this._originalPairing.forEach((function(e){e[0].material=e[1]}))},t.prototype._bindFrameBuffer=function(){this._renderTarget&&this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget)},t.prototype.getViewCount=function(){return 2},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._velocityMaterial.dispose(),this._previousTransforms.length=0,this._previousWorldMatrices.length=0,this._originalPairing.length=0},t}(Pl),FI=function(){function e(e,t,i){this._scene=e,this._xrSessionManager=t,this._xrWebGLBinding=i,this._lastSubImages=new Map,this._renderTargetTextures=new Map,this._engine=e.getEngine()}return e.prototype._getSubImageForView=function(e){var t=this._xrSessionManager._getBaseLayerWrapper();if(!t)throw new Error("For Space Warp, the base layer should be a WebXR Projection Layer.");if("XRProjectionLayer"!==t.layerType)throw new Error('For Space Warp, the base layer type should "XRProjectionLayer".');var i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)},e.prototype._setViewportForSubImage=function(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight},e.prototype._createRenderTargetTexture=function(e,t,i,r,n){if(!this._engine)throw new Error("Engine is disposed");var o={width:e,height:t},a=new NI(r,n,this._scene,o),s=a.renderTarget;return i&&(s._framebuffer=i),s._colorTextureArray=r,s._depthStencilTextureArray=n,a.disableRescaling(),a.renderListPredicate=function(){return!0},a},e.prototype._getRenderTargetForSubImage=function(e,t){var i=this._lastSubImages.get(t),r=this._renderTargetTextures.get(t.eye),n=e.motionVectorTextureWidth,o=e.motionVectorTextureHeight;return r&&(null==i?void 0:i.textureWidth)===n&&(null==i?void 0:i.textureHeight)==o||(r=this._createRenderTargetTexture(n,o,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,r),this._framebufferDimensions={framebufferWidth:n,framebufferHeight:o}),this._lastSubImages.set(t,e),r},e.prototype.trySetViewportForView=function(e,t){var i=this._lastSubImages.get(t)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)},e.prototype.accessMotionVector=function(e){var t=this._getSubImageForView(e);t&&(t.motionVectorTexture,t.depthStencilTexture)},e.prototype.getRenderTargetTextureForEye=function(e){return null},e.prototype.getRenderTargetTextureForView=function(e){var t=this._getSubImageForView(e);return t?this._getRenderTargetForSubImage(t,e):null},e.prototype.dispose=function(){this._renderTargetTextures.forEach((function(e){return e.dispose()})),this._renderTargetTextures.clear()},e}(),LI=function(e){function t(t){var i=e.call(this,t)||this;return i._onAfterRenderObserver=null,i.dependsOn=[Ss.LAYERS],i.xrNativeFeatureName="space-warp",i._xrSessionManager.scene.needsPreviousWorldMatrices=!0,i}return m(t,e),t.prototype.attach=function(){var t=this;if(!e.prototype.attach.call(this))return!1;var i=this._xrSessionManager.scene.getEngine();return this._glContext=i._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this.spaceWarpRTTProvider=new FI(this._xrSessionManager.scene,this._xrSessionManager,this._xrWebGLBinding),this._onAfterRenderObserver=this._xrSessionManager.scene.onAfterRenderObservable.add((function(){return t._onAfterRender()})),!0},t.prototype.detach=function(){return this._xrSessionManager.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),e.prototype.detach.call(this)},t.prototype._onAfterRender=function(){this.attached&&this._renderTargetTexture&&this._renderTargetTexture.render(!1,!1)},t.prototype.isCompatible=function(){return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat||!1},t.prototype.dispose=function(){e.prototype.dispose.call(this)},t.prototype._onXRFrame=function(e){var t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(t){var i=t.views[0];this._renderTargetTexture=this._renderTargetTexture||this.spaceWarpRTTProvider.getRenderTargetTextureForView(i),this.spaceWarpRTTProvider.accessMotionVector(i)}},t.Name=Ss.SPACE_WARP,t.Version=1,t}(As);xs.AddWebXRFeature(LI.Name,(function(e){return function(){return new LI(e)}}),LI.Version,!1);var wI=function(e){function t(t,i){void 0===i&&(i={});var r=e.call(this,t)||this;return r.options=i,r._cachedInternalTextures=[],r.texturesData=[],r.viewIndex=[],r.cameraIntrinsics=[],r.onTexturesUpdatedObservable=new f,r.xrNativeFeatureName="camera-access",r}return m(t,e),t.prototype.attach=function(t){return!!e.prototype.attach.call(this,t)&&(this._glContext=this._xrSessionManager.scene.getEngine()._gl,this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),!0)},t.prototype.detach=function(){return!!e.prototype.detach.call(this)&&(this._glBinding=void 0,this.options.doNotDisposeOnDetach||(this._cachedInternalTextures.forEach((function(e){return e.dispose()})),this.texturesData.forEach((function(e){return e.dispose()})),this._cachedInternalTextures.length=0,this.texturesData.length=0,this.cameraIntrinsics.length=0),!0)},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onTexturesUpdatedObservable.clear()},t.prototype._updateCameraIntrinsics=function(e,t){var i={width:e.camera.width,height:e.camera.height,x:0,y:0},r=e.projectionMatrix,n=(1-r[8])*i.width/2+i.x,o=(1-r[9])*i.height/2+i.y,a=i.width/2*r[0],s=i.height/2*r[5],l=i.width/2*r[4];this.cameraIntrinsics[t]={u0:n,v0:o,ax:a,ay:s,gamma:l,width:i.width,height:i.height,viewportX:i.x,viewportY:i.y}},t.prototype._updateInternalTextures=function(e,t){var i,r;if(void 0===t&&(t=0),!e.camera)return!1;this.viewIndex[t]=e.eye;var n=null===(i=this._glBinding)||void 0===i?void 0:i.getCameraImage(e.camera);if(this._cachedInternalTextures[t])null===(r=this._cachedInternalTextures[t]._hardwareTexture)||void 0===r||r.set(n);else{var o=new Pi(this._xrSessionManager.scene.getEngine(),Ti.Unknown,!0);o.isCube=!0,o.invertY=!1,o.format=u.TEXTUREFORMAT_RGBA,o.generateMipMaps=!0,o.type=u.TEXTURETYPE_FLOAT,o.samplingMode=u.TEXTURE_LINEAR_LINEAR_MIPLINEAR,o.width=e.camera.width,o.height=e.camera.height,o._cachedWrapU=u.TEXTURE_WRAP_ADDRESSMODE,o._cachedWrapV=u.TEXTURE_WRAP_ADDRESSMODE,o._hardwareTexture=new br(n,this._glContext),this._cachedInternalTextures[t]=o;var a=new Ya(this._xrSessionManager.scene);a.name="WebXR Raw Camera Access (".concat(t,")"),a._texture=this._cachedInternalTextures[t],this.texturesData[t]=a,this._updateCameraIntrinsics(e,t)}return this._cachedInternalTextures[t].isReady=!0,!0},t.prototype._onXRFrame=function(e){var t=this,i=this._xrSessionManager.referenceSpace,r=e.getViewerPose(i);if(r&&r.views){var n=!0;r.views.forEach((function(e,i){n=n&&t._updateInternalTextures(e,i)})),n&&this.onTexturesUpdatedObservable.notifyObservers(this.texturesData)}},t.Name=Ss.RAW_CAMERA_ACCESS,t.Version=1,t}(As);xs.AddWebXRFeature(wI.Name,(function(e,t){return function(){return new wI(e,t)}}),wI.Version,!1);var BI=function(e){function t(t,i,r){var n=e.call(this,t,UI[r],i,r,!0)||this;return n.profileId="generic-hand-select-grasp",n}return m(t,e),t.prototype._getFilenameAndPath=function(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}},t.prototype._getModelLoadingConstraints=function(){return!0},t.prototype._processLoadedModel=function(e){},t.prototype._setRootMesh=function(e){},t.prototype._updateModel=function(){},t}(Pg);Ng.RegisterController("generic-hand-select-grasp",(function(e,t){return new BI(t,e.gamepad,e.handedness)}));var UI={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-none",assetPath:"none.glb"}},VI=function(e){function t(t,i,r){var n=e.call(this,t,kI["left-right"],i,r)||this;return n._mapping={defaultButton:{valueNodeName:"VALUE",unpressedNodeName:"UNPRESSED",pressedNodeName:"PRESSED"},defaultAxis:{valueNodeName:"VALUE",minNodeName:"MIN",maxNodeName:"MAX"},buttons:{"xr-standard-trigger":{rootNodeName:"SELECT",componentProperty:"button",states:["default","touched","pressed"]},"xr-standard-squeeze":{rootNodeName:"GRASP",componentProperty:"state",states:["pressed"]},"xr-standard-touchpad":{rootNodeName:"TOUCHPAD_PRESS",labelAnchorNodeName:"squeeze-label",touchPointNodeName:"TOUCH"},"xr-standard-thumbstick":{rootNodeName:"THUMBSTICK_PRESS",componentProperty:"state",states:["pressed"]}},axes:{"xr-standard-touchpad":{"x-axis":{rootNodeName:"TOUCHPAD_TOUCH_X"},"y-axis":{rootNodeName:"TOUCHPAD_TOUCH_Y"}},"xr-standard-thumbstick":{"x-axis":{rootNodeName:"THUMBSTICK_X"},"y-axis":{rootNodeName:"THUMBSTICK_Y"}}}},n.profileId="microsoft-mixed-reality",n}return m(t,e),t.prototype._getFilenameAndPath=function(){return{filename:"left"===this.handedness?t.MODEL_LEFT_FILENAME:t.MODEL_RIGHT_FILENAME,path:t.MODEL_BASE_URL+"default/"}},t.prototype._getModelLoadingConstraints=function(){var e=Ls.IsPluginForExtensionAvailable(".glb");return e||ae.Warn("glTF / glb loaded was not registered, using generic controller instead"),e},t.prototype._processLoadedModel=function(e){var t=this;this.rootMesh&&(this.getComponentIds().forEach((function(e,i){if(!t.disableAnimation&&e&&t.rootMesh){var r=t._mapping.buttons[e],n=r.rootNodeName;if(!n)return void ae.Log("Skipping unknown button at index: "+i+" with mapped name: "+e);var o=t._getChildByName(t.rootMesh,n);if(!o)return void ae.Warn("Missing button mesh with name: "+n);if(r.valueMesh=t._getImmediateChildByName(o,t._mapping.defaultButton.valueNodeName),r.pressedMesh=t._getImmediateChildByName(o,t._mapping.defaultButton.pressedNodeName),r.unpressedMesh=t._getImmediateChildByName(o,t._mapping.defaultButton.unpressedNodeName),r.valueMesh&&r.pressedMesh&&r.unpressedMesh){var a=t.getComponent(e);a&&a.onButtonStateChangedObservable.add((function(e){t._lerpTransform(r,e.value)}),void 0,!0)}else ae.Warn("Missing button submesh under mesh with name: "+n)}})),this.getComponentIds().forEach((function(e){var i=t.getComponent(e);i.isAxes()&&["x-axis","y-axis"].forEach((function(r){if(t.rootMesh){var n=t._mapping.axes[e][r],o=t._getChildByName(t.rootMesh,n.rootNodeName);o?(n.valueMesh=t._getImmediateChildByName(o,t._mapping.defaultAxis.valueNodeName),n.minMesh=t._getImmediateChildByName(o,t._mapping.defaultAxis.minNodeName),n.maxMesh=t._getImmediateChildByName(o,t._mapping.defaultAxis.maxNodeName),n.valueMesh&&n.minMesh&&n.maxMesh?i&&i.onAxisValueChangedObservable.add((function(e){var i="x-axis"===r?e.x:e.y;t._lerpTransform(n,i,!0)}),void 0,!0):ae.Warn("Missing axis submesh under mesh with name: "+n.rootNodeName)):ae.Warn("Missing axis mesh with name: "+n.rootNodeName)}}))})))},t.prototype._setRootMesh=function(e){var t;this.rootMesh=new Fa(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(var i=0;i<e.length;i++){var r=e[i];r.isPickable=!1,r.parent||(t=r)}t&&t.setParent(this.rootMesh),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=G.FromEulerAngles(0,Math.PI,0))},t.prototype._updateModel=function(){},t.MODEL_BASE_URL="https://controllers.babylonjs.com/microsoft/",t.MODEL_LEFT_FILENAME="left.glb",t.MODEL_RIGHT_FILENAME="right.glb",t}(Pg);Ng.RegisterController("windows-mixed-reality",(function(e,t){return new VI(t,e.gamepad,e.handedness)}));var kI={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-right",assetPath:"right.glb"}},GI=function(e){function t(t,i,r,n,o){void 0===n&&(n=!1),void 0===o&&(o=!1);var a=e.call(this,t,zI[r],i,r)||this;return a._forceLegacyControllers=o,a.profileId="oculus-touch",a}return m(t,e),t.prototype._getFilenameAndPath=function(){return{filename:"left"===this.handedness?t.MODEL_LEFT_FILENAME:t.MODEL_RIGHT_FILENAME,path:this._isQuest()?t.QUEST_MODEL_BASE_URL:t.MODEL_BASE_URL}},t.prototype._getModelLoadingConstraints=function(){return!0},t.prototype._processLoadedModel=function(e){var t=this,i=this._isQuest(),r="right"===this.handedness?-1:1;this.getComponentIds().forEach((function(e){var n=e&&t.getComponent(e);n&&n.onButtonStateChangedObservable.add((function(n){if(t.rootMesh&&!t.disableAnimation)switch(e){case"xr-standard-trigger":return void(i||(t._modelRootNode.getChildren()[3].rotation.x=.2*-n.value,t._modelRootNode.getChildren()[3].position.y=.005*-n.value,t._modelRootNode.getChildren()[3].position.z=.005*-n.value));case"xr-standard-squeeze":return void(i||(t._modelRootNode.getChildren()[4].position.x=r*n.value*.0035));case"xr-standard-thumbstick":return;case"a-button":case"x-button":return void(i||(n.pressed?t._modelRootNode.getChildren()[1].position.y=-.001:t._modelRootNode.getChildren()[1].position.y=0));case"b-button":case"y-button":return void(i||(n.pressed?t._modelRootNode.getChildren()[2].position.y=-.001:t._modelRootNode.getChildren()[2].position.y=0))}}),void 0,!0)}))},t.prototype._setRootMesh=function(e){this.rootMesh=new Fa(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=G.FromEulerAngles(0,Math.PI,0)),e.forEach((function(e){e.isPickable=!1})),this._isQuest()?this._modelRootNode=e[0]:(this._modelRootNode=e[1],this.rootMesh.position.y=.034,this.rootMesh.position.z=.052),this._modelRootNode.parent=this.rootMesh},t.prototype._updateModel=function(){},t.prototype._isQuest=function(){return!!navigator.userAgent.match(/Quest/gi)&&!this._forceLegacyControllers},t.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",t.MODEL_LEFT_FILENAME="left.babylon",t.MODEL_RIGHT_FILENAME="right.babylon",t.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",t}(Pg);Ng.RegisterController("oculus-touch",(function(e,t){return new GI(t,e.gamepad,e.handedness)})),Ng.RegisterController("oculus-touch-legacy",(function(e,t){return new GI(t,e.gamepad,e.handedness,!0)}));var zI={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"x-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"x_button",visualResponses:{}},"y-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"y_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"a-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"a_button",visualResponses:{}},"b-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"b_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-right",assetPath:"right.glb"}},WI=function(e){function t(t,i,r){var n=e.call(this,t,XI[r],i,r)||this;return n.profileId="htc-vive",n}return m(t,e),t.prototype._getFilenameAndPath=function(){return{filename:t.MODEL_FILENAME,path:t.MODEL_BASE_URL}},t.prototype._getModelLoadingConstraints=function(){return!0},t.prototype._processLoadedModel=function(e){var t=this;this.getComponentIds().forEach((function(e){var i=e&&t.getComponent(e);i&&i.onButtonStateChangedObservable.add((function(i){if(t.rootMesh&&!t.disableAnimation)switch(e){case"xr-standard-trigger":return void(t._modelRootNode.getChildren()[6].rotation.x=.15*-i.value);case"xr-standard-touchpad":case"xr-standard-squeeze":return}}),void 0,!0)}))},t.prototype._setRootMesh=function(e){this.rootMesh=new Fa(this.profileId+" "+this.handedness,this.scene),e.forEach((function(e){e.isPickable=!1})),this._modelRootNode=e[1],this._modelRootNode.parent=this.rootMesh,this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=G.FromEulerAngles(0,Math.PI,0))},t.prototype._updateModel=function(){},t.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",t.MODEL_FILENAME="wand.babylon",t}(Pg);Ng.RegisterController("htc-vive",(function(e,t){return new WI(t,e.gamepad,e.handedness)}));var HI,XI={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc-vive-none",assetPath:"none.glb"}},jI=function(){function e(e){var t=this;this._nativeImpl=e,this._xrTransform=new XRRigidTransform,this._xrPose={transform:this._xrTransform,emulatedPosition:!1},this._xrPoseVectorData=new Float32Array(8),this.fillPoses=this._nativeImpl.fillPoses.bind(this._nativeImpl),this.getViewerPose=this._nativeImpl.getViewerPose.bind(this._nativeImpl),this.getHitTestResults=this._nativeImpl.getHitTestResults.bind(this._nativeImpl),this.getHitTestResultsForTransientInput=function(){throw new Error("XRFrame.getHitTestResultsForTransientInput not supported on native.")},this.createAnchor=this._nativeImpl.createAnchor.bind(this._nativeImpl),this.getJointPose=this._nativeImpl.getJointPose.bind(this._nativeImpl),this.fillJointRadii=this._nativeImpl.fillJointRadii.bind(this._nativeImpl),this.getLightEstimate=function(){throw new Error("XRFrame.getLightEstimate not supported on native.")},this.getImageTrackingResults=function(){var e;return null!==(e=t._nativeImpl._imageTrackingResults)&&void 0!==e?e:[]}}return Object.defineProperty(e.prototype,"session",{get:function(){return this._nativeImpl.session},enumerable:!1,configurable:!0}),e.prototype.getPose=function(e,t){if(this._nativeImpl.getPoseData(e,t,this._xrPoseVectorData.buffer,this._xrTransform.matrix.buffer)){var i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];var r=this._xrTransform.orientation;return r.x=this._xrPoseVectorData[4],r.y=this._xrPoseVectorData[5],r.z=this._xrPoseVectorData[6],r.w=this._xrPoseVectorData[7],this._xrPose}},Object.defineProperty(e.prototype,"trackedAnchors",{get:function(){return this._nativeImpl.trackedAnchors},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"worldInformation",{get:function(){return this._nativeImpl.worldInformation},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"detectedPlanes",{get:function(){return this._nativeImpl.detectedPlanes},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"featurePointCloud",{get:function(){return this._nativeImpl.featurePointCloud},enumerable:!1,configurable:!0}),e.prototype.getDepthInformation=function(e){throw new Error("This function is not available in Babylon Native")},e}();pf("NativeXRFrame",jI),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(HI||(HI={}));var YI=function(){function e(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=Qi(),this.connectedPointIds=[],this.name=e,this._connectionType=t}return Object.defineProperty(e.prototype,"connectionType",{get:function(){return this._connectionType},enumerable:!1,configurable:!0}),e.prototype._isSingularConnection=function(){return!0},e.prototype.isConnected=function(){return this._connectedPoint.length>0},e.prototype.connectTo=function(e){if(this._connectionType===e._connectionType)throw new Error("Cannot connect two points of type ".concat(this.connectionType));if(this._isSingularConnection()&&this._connectedPoint.length>0||e._isSingularConnection()&&e._connectedPoint.length>0)throw new Error("Max number of connections for point reached");this._connectedPoint.push(e),e._connectedPoint.push(this)},e.prototype.serialize=function(e){void 0===e&&(e={}),e.uniqueId=this.uniqueId,e.name=this.name,e._connectionType=this._connectionType,e.connectedPointIds=[],e.className=this.getClassName();for(var t=0,i=this._connectedPoint;t<i.length;t++){var r=i[t];e.connectedPointIds.push(r.uniqueId)}},e.prototype.getClassName=function(){return"FGConnection"},e.prototype.deserialize=function(e){this.uniqueId=e.uniqueId,this.name=e.name,this._connectionType=e._connectionType,this.connectedPointIds=e.connectedPointIds},e.Parse=function(e,t){void 0===e&&(e={});var i=new(rr.Instantiate(e.className))(e.name,e._connectionType,t);return i.deserialize(e),i},e}(),KI=function(){function e(e){this.value=this._toInt(e)}return e.prototype._toInt=function(e){return 0|e},e.prototype.add=function(t){return new e(this.value+t.value)},e.prototype.subtract=function(t){return new e(this.value-t.value)},e.prototype.multiply=function(t){return new e(Math.imul(this.value,t.value))},e.prototype.divide=function(t){return new e(this.value/t.value)},e.prototype.getClassName=function(){return e.ClassName},e.prototype.equals=function(e){return this.value===e.value},e.Parse=function(t){return new e(t.value)},e.ClassName="FlowGraphInteger",e}();a("FlowGraphInteger",KI);var QI=function(){function e(e,t){this.typeName=e,this.defaultValue=t}return e.prototype.serialize=function(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue},e.Parse=function(t){return new e(t.typeName,t.defaultValue)},e}(),qI=new QI("any",void 0),ZI=new QI("string",""),JI=new QI("number",0),$I=new QI("boolean",!1),eM=new QI("Vector2",U.Zero()),tM=new QI("Vector3",V.Zero()),iM=new QI("Vector4",k.Zero()),rM=new QI("Matrix",z.Identity()),nM=new QI("Color3",Z.Black()),oM=new QI("Color4",new J(0,0,0,0)),aM=new QI("Quaternion",G.Identity()),sM=new QI("FlowGraphInteger",new KI(0));function lM(e){switch(typeof e){case"string":return ZI;case"number":return JI;case"boolean":return $I;case"object":return e instanceof U?eM:e instanceof V?tM:e instanceof k?iM:e instanceof Z?nM:e instanceof J?oM:e instanceof G?aM:e instanceof KI?sM:qI;default:return qI}}var cM=function(e){function t(t,i,r,n){var o=e.call(this,t,i,r)||this;return o.richType=n,o}return m(t,e),t.prototype._isSingularConnection=function(){return this.connectionType===HI.Input},t.prototype.setValue=function(e,t){t._setConnectionValue(this,e)},t.prototype.connectTo=function(t){e.prototype.connectTo.call(this,t)},t.prototype._getValueOrDefault=function(e){return e._hasConnectionValue(this)?e._getConnectionValue(this):this.richType.defaultValue},t.prototype.getValue=function(e){return this.connectionType===HI.Output?(e._notifyExecuteNode(this._ownerBlock),this._ownerBlock._updateOutputs(e),this._getValueOrDefault(e)):this.isConnected()?this._connectedPoint[0].getValue(e):this._getValueOrDefault(e)},t.prototype.getClassName=function(){return"FGDataConnection"},t.prototype.serialize=function(t){void 0===t&&(t={}),e.prototype.serialize.call(this,t),t.richType={},this.richType.serialize(t.richType)},t.Parse=function(e,t){var i=YI.Parse(e,t);return i.richType=QI.Parse(e.richType),i},t}(YI);function uM(e){return"Mesh"===e||"AbstractMesh"===e||"GroundMesh"===e||"InstanceMesh"===e||"LinesMesh"===e||"GoldbergMesh"===e||"GreasedLineMesh"===e||"TrailMesh"===e}function hM(e){return"Vector2"===e||"Vector3"===e||"Vector4"===e||"Quaternion"===e||"Color3"===e||"Color4"===e}function dM(e,t,i){var r,n,o=null!==(n=null===(r=null==t?void 0:t.getClassName)||void 0===r?void 0:r.call(t))&&void 0!==n?n:"";uM(o)?i[e]={name:t.name,className:o}:hM(o)?i[e]={value:t.asArray(),className:o}:i[e]=t}function pM(e,t,i){var r=t[e],n=null==r?void 0:r.className;return uM(n)?i.getMeshByName(r.name):hM(n)?function(e,t){if("Vector2"===e)return U.FromArray(t);if("Vector3"===e)return V.FromArray(t);if("Vector4"===e)return k.FromArray(t);if("Quaternion"===e)return G.FromArray(t);if("Color3"===e)return new Z(t[0],t[1],t[2]);if("Color4"===e)return new J(t[0],t[1],t[2],t[3]);throw new Error("Unknown vector class name ".concat(e))}(n,r.value):"Matrix"===n?z.FromArray(r.value):n===KI.ClassName?KI.Parse(r):r&&void 0!==r.value?r.value:r}a("FGDataConnection",cM);var fM=function(){function e(e){var t,i;this.config=e,this.uniqueId=Qi(),this.name=null!==(i=null===(t=this.config)||void 0===t?void 0:t.name)&&void 0!==i?i:this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}return e.prototype._updateOutputs=function(e){},e.prototype.registerDataInput=function(e,t){var i=new cM(e,HI.Input,this,t);return this.dataInputs.push(i),i},e.prototype.registerDataOutput=function(e,t){var i=new cM(e,HI.Output,this,t);return this.dataOutputs.push(i),i},e.prototype.getDataInput=function(e){return this.dataInputs.find((function(t){return t.name===e}))},e.prototype.getDataOutput=function(e){return this.dataOutputs.find((function(t){return t.name===e}))},e.prototype.serialize=function(e,t){void 0===e&&(e={}),void 0===t&&(t=dM),e.uniqueId=this.uniqueId,e.config={},this.config&&(e.config.name=this.config.name),e.dataInputs=[],e.dataOutputs=[],e.className=this.getClassName();for(var i=0,r=this.dataInputs;i<r.length;i++){var n={};r[i].serialize(n),e.dataInputs.push(n)}for(var o=0,a=this.dataOutputs;o<a.length;o++){var s={};a[o].serialize(s),e.dataOutputs.push(s)}},e.prototype.getClassName=function(){return"FGBlock"},e.Parse=function(e,t){var i,r=rr.Instantiate(e.className),n={},o=null!==(i=t.valueParseFunction)&&void 0!==i?i:pM;if(e.config)for(var a in e.config)n[a]=o(a,e.config,t.scene);(function(e){return"FGSetPropertyBlock"===e||"FGGetPropertyBlock"===e||"FGPlayAnimationBlock"===e||"FGMeshPickEventBlock"===e})(e.className)&&(n.pathConverter=t.pathConverter);var s=new r(n);s.uniqueId=e.uniqueId;for(var l=0;l<e.dataInputs.length;l++){var c=s.getDataInput(e.dataInputs[l].name);if(!c)throw new Error("Could not find data input with name "+e.dataInputs[l].name+" in block "+e.className);c.deserialize(e.dataInputs[l])}for(l=0;l<e.dataOutputs.length;l++){var u=s.getDataOutput(e.dataOutputs[l].name);if(!u)throw new Error("Could not find data output with name "+e.dataOutputs[l].name+" in block "+e.className);u.deserialize(e.dataOutputs[l])}return s.metadata=e.metadata,s.deserialize&&s.deserialize(e),s},e}(),_M=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.prototype._isSingularConnection=function(){return this.connectionType===HI.Output},t.prototype._activateSignal=function(e){var t;this.connectionType===HI.Input?(e._notifyExecuteNode(this._ownerBlock),this._ownerBlock._execute(e,this),e._increaseExecutionId()):null===(t=this._connectedPoint[0])||void 0===t||t._activateSignal(e)},t}(YI);a("FlowGraphSignalConnection",_M);var mM=function(e){function t(t){var i=e.call(this,t)||this;return i.signalInputs=[],i.signalOutputs=[],i.in=i._registerSignalInput("in"),i}return m(t,e),t.prototype._registerSignalInput=function(e){var t=new _M(e,HI.Input,this);return this.signalInputs.push(t),t},t.prototype._registerSignalOutput=function(e){var t=new _M(e,HI.Output,this);return this.signalOutputs.push(t),t},t.prototype.getSignalInput=function(e){return this.signalInputs.find((function(t){return t.name===e}))},t.prototype.getSignalOutput=function(e){return this.signalOutputs.find((function(t){return t.name===e}))},t.prototype.serialize=function(t){void 0===t&&(t={}),e.prototype.serialize.call(this,t),t.signalInputs=[],t.signalOutputs=[];for(var i=0,r=this.signalInputs;i<r.length;i++){var n={};r[i].serialize(n),t.signalInputs.push(n)}for(var o=0,a=this.signalOutputs;o<a.length;o++){var s={};a[o].serialize(s),t.signalOutputs.push(s)}},t.prototype.deserialize=function(e){for(var t=0;t<e.signalInputs.length;t++){var i=this.getSignalInput(e.signalInputs[t].name);if(!i)throw new Error("Could not find signal input with name "+e.signalInputs[t].name+" in block "+e.className);i.deserialize(e.signalInputs[t])}for(t=0;t<e.signalOutputs.length;t++){var r=this.getSignalOutput(e.signalOutputs[t].name);if(!r)throw new Error("Could not find signal output with name "+e.signalOutputs[t].name+" in block "+e.className);r.deserialize(e.signalOutputs[t])}},t.prototype.getClassName=function(){return"FGExecutionBlock"},t}(fM),gM=function(e){function t(t){var i=e.call(this,t)||this;return i.out=i._registerSignalOutput("out"),i.done=i._registerSignalOutput("done"),i}return m(t,e),t.prototype._startPendingTasks=function(e){this._preparePendingTasks(e),e._addPendingBlock(this)},t}(mM),vM=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.prototype._execute=function(e){e._notifyExecuteNode(this),this.out._activateSignal(e)},t}(gM),yM=function(){function e(e){this.uniqueId=Qi(),this._userVariables={},this._executionVariables={},this._connectionValues={},this._pendingBlocks=[],this._executionId=0,this.onNodeExecutedObservable=new f,this._configuration=e}return e.prototype.hasVariable=function(e){return e in this._userVariables},e.prototype.setVariable=function(e,t){this._userVariables[e]=t},e.prototype.getVariable=function(e){return this._userVariables[e]},Object.defineProperty(e.prototype,"userVariables",{get:function(){return this._userVariables},enumerable:!1,configurable:!0}),e.prototype._getUniqueIdPrefixedName=function(e,t){return"".concat(e.uniqueId,"_").concat(t)},e.prototype._setExecutionVariable=function(e,t,i){this._executionVariables[this._getUniqueIdPrefixedName(e,t)]=i},e.prototype._getExecutionVariable=function(e,t,i){return this._hasExecutionVariable(e,t)?this._executionVariables[this._getUniqueIdPrefixedName(e,t)]:i},e.prototype._deleteExecutionVariable=function(e,t){delete this._executionVariables[this._getUniqueIdPrefixedName(e,t)]},e.prototype._hasExecutionVariable=function(e,t){return this._getUniqueIdPrefixedName(e,t)in this._executionVariables},e.prototype._hasConnectionValue=function(e){return e.uniqueId in this._connectionValues},e.prototype._setConnectionValue=function(e,t){this._connectionValues[e.uniqueId]=t},e.prototype._getConnectionValue=function(e){return this._connectionValues[e.uniqueId]},Object.defineProperty(e.prototype,"configuration",{get:function(){return this._configuration},enumerable:!1,configurable:!0}),e.prototype._addPendingBlock=function(e){this._pendingBlocks.push(e)},e.prototype._removePendingBlock=function(e){var t=this._pendingBlocks.indexOf(e);-1!==t&&this._pendingBlocks.splice(t,1)},e.prototype._clearPendingBlocks=function(){for(var e=0,t=this._pendingBlocks;e<t.length;e++)t[e]._cancelPendingTasks(this);this._pendingBlocks.length=0},e.prototype._notifyExecuteNode=function(e){this.onNodeExecutedObservable.notifyObservers(e)},e.prototype._increaseExecutionId=function(){this._executionId++},Object.defineProperty(e.prototype,"executionId",{get:function(){return this._executionId},enumerable:!1,configurable:!0}),e.prototype.serialize=function(e,t){for(var i in void 0===e&&(e={}),void 0===t&&(t=dM),e.uniqueId=this.uniqueId,e._userVariables={},this._userVariables)t(i,this._userVariables[i],e._userVariables);for(var i in e._connectionValues={},this._connectionValues)t(i,this._connectionValues[i],e._connectionValues)},e.prototype.getClassName=function(){return"FGContext"},e.Parse=function(e,t){var i,r=t.graph.createContext(),n=null!==(i=t.valueParseFunction)&&void 0!==i?i:pM;for(var o in r.uniqueId=e.uniqueId,e._userVariables){var a=n(o,e._userVariables,r._configuration.scene);r._userVariables[o]=a}for(var o in e._connectionValues)a=n(o,e._connectionValues,r._configuration.scene),r._connectionValues[o]=a;return r},v([Ie()],e.prototype,"uniqueId",void 0),e}();function bM(e,t){return!(!e.parent||e.parent!==t&&!bM(e.parent,t))}var TM,EM=function(e){function t(t){var i=e.call(this,t)||this;return i.config=t,i}return m(t,e),t.prototype._getReferencedMesh=function(){var e=this.config.pathConverter.convert(this.config.path),t=e.info.getObject(e.object);if(!(t&&t instanceof Uo))throw new Error("Mesh pick event block requires a valid mesh");return t},t.prototype._preparePendingTasks=function(e){var t=this,i=e._getExecutionVariable(this,"meshPickObserver");if(!i){var r=this._getReferencedMesh();e._setExecutionVariable(this,"mesh",r),i=r.getScene().onPointerObservable.add((function(i){var n,o,a;i.type===Gr.POINTERPICK&&(null===(n=i.pickInfo)||void 0===n?void 0:n.pickedMesh)&&((null===(o=i.pickInfo)||void 0===o?void 0:o.pickedMesh)===r||bM(null===(a=i.pickInfo)||void 0===a?void 0:a.pickedMesh,r))&&t._execute(e)}));var n=r.onDisposeObservable.add((function(){return t._onDispose}));e._setExecutionVariable(this,"meshPickObserver",i),e._setExecutionVariable(this,"meshDisposeObserver",n)}},t.prototype._onDispose=function(e){this._cancelPendingTasks(e),e._removePendingBlock(this)},t.prototype._cancelPendingTasks=function(e){var t=e._getExecutionVariable(this,"mesh"),i=e._getExecutionVariable(this,"meshPickObserver"),r=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(r),e._deleteExecutionVariable(this,"mesh"),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")},t.prototype.getClassName=function(){return t.ClassName},t.prototype.serialize=function(t){e.prototype.serialize.call(this,t),t.config.path=this.config.path},t.ClassName="FGMeshPickEventBlock",t}(vM);a(EM.ClassName,EM),function(e){e[e.Stopped=0]="Stopped",e[e.Started=1]="Started"}(TM||(TM={}));var SM=function(){function e(e){var t=this;this._eventBlocks=[],this._executionContexts=[],this.state=TM.Stopped,this._scene=e.scene,this._coordinator=e.coordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add((function(){return t.dispose()}))}return e.prototype.createContext=function(){var e=new yM({scene:this._scene,coordinator:this._coordinator});return this._executionContexts.push(e),e},e.prototype.getContext=function(e){return this._executionContexts[e]},e.prototype.addEventBlock=function(e){this._eventBlocks.push(e)},e.prototype.start=function(){if(this.state!==TM.Started){this.state=TM.Started,0===this._executionContexts.length&&this.createContext();for(var e=0,t=this._executionContexts;e<t.length;e++)for(var i=t[e],r=0,n=this._getContextualOrder();r<n.length;r++)n[r]._startPendingTasks(i)}},e.prototype._getContextualOrder=function(){for(var e=[],t=0,i=this._eventBlocks;t<i.length;t++){var r=i[t];if(r.getClassName()===EM.ClassName){for(var n=r._getReferencedMesh(),o=0;o<e.length;o++){var a=e[o]._getReferencedMesh();if(n&&a&&bM(n,a))break}e.splice(o,0,r)}else e.push(r)}return e},e.prototype.dispose=function(){if(this.state!==TM.Stopped){this.state=TM.Stopped;for(var e=0,t=this._executionContexts;e<t.length;e++)t[e]._clearPendingBlocks();this._executionContexts.length=0,this._eventBlocks.length=0,this._scene.onDisposeObservable.remove(this._sceneDisposeObserver),this._sceneDisposeObserver=null}},e.prototype.visitAllBlocks=function(e){for(var t=[],i=new Set,r=0,n=this._eventBlocks;r<n.length;r++){var o=n[r];t.push(o),i.add(o.uniqueId)}for(;t.length>0;){e(o=t.pop());for(var a=0,s=o.dataInputs;a<s.length;a++)for(var l=0,c=s[a]._connectedPoint;l<c.length;l++){var u=c[l];i.has(u._ownerBlock.uniqueId)||(t.push(u._ownerBlock),i.add(u._ownerBlock.uniqueId))}if(o instanceof mM)for(var h=0,d=o.signalOutputs;h<d.length;h++)for(var p=0,f=d[h]._connectedPoint;p<f.length;p++)u=f[p],i.has(u._ownerBlock.uniqueId)||(t.push(u._ownerBlock),i.add(u._ownerBlock.uniqueId))}},e.prototype.serialize=function(e,t){void 0===e&&(e={}),e.allBlocks=[],this.visitAllBlocks((function(t){var i={};t.serialize(i),e.allBlocks.push(i)})),e.executionContexts=[];for(var i=0,r=this._executionContexts;i<r.length;i++){var n={};r[i].serialize(n,t),e.executionContexts.push(n)}},e.GetDataOutConnectionByUniqueId=function(e,t){for(var i=0,r=e;i<r.length;i++)for(var n=0,o=r[i].dataOutputs;n<o.length;n++){var a=o[n];if(a.uniqueId===t)return a}throw new Error("Could not find data out connection with unique id "+t)},e.GetSignalInConnectionByUniqueId=function(e,t){for(var i=0,r=e;i<r.length;i++){var n=r[i];if(n instanceof mM)for(var o=0,a=n.signalInputs;o<a.length;o++){var s=a[o];if(s.uniqueId===t)return s}}throw new Error("Could not find signal in connection with unique id "+t)},e.Parse=function(t,i){for(var r,n=i.coordinator.createGraph(),o=[],a=null!==(r=i.valueParseFunction)&&void 0!==r?r:pM,s=0,l=t.allBlocks;s<l.length;s++){var c=l[s],u=fM.Parse(c,{scene:i.coordinator.config.scene,pathConverter:i.pathConverter,valueParseFunction:a});o.push(u),u instanceof vM&&n.addEventBlock(u)}for(var h=0,d=o;h<d.length;h++){for(var p=0,f=(u=d[h]).dataInputs;p<f.length;p++)for(var _=f[p],m=0,g=_.connectedPointIds;m<g.length;m++){var v=g[m],y=e.GetDataOutConnectionByUniqueId(o,v);_.connectTo(y)}if(u instanceof mM)for(var b=0,T=u.signalOutputs;b<T.length;b++)for(var E=T[b],S=0,x=E.connectedPointIds;S<x.length;S++)v=x[S],y=e.GetSignalInConnectionByUniqueId(o,v),E.connectTo(y)}for(var A=0,C=t.executionContexts;A<C.length;A++){var R=C[A];yM.Parse(R,{graph:n,valueParseFunction:a})}return n},e}(),xM=function(){function e(t){var i,r=this;this.config=t,this._flowGraphs=[],this._customEventsMap=new Map,this.config.scene.onDisposeObservable.add((function(){r.dispose()})),(null!==(i=e.SceneCoordinators.get(this.config.scene))&&void 0!==i?i:[]).push(this)}return e.prototype.createGraph=function(){var e=new SM({scene:this.config.scene,coordinator:this});return this._flowGraphs.push(e),e},e.prototype.removeGraph=function(e){var t=this._flowGraphs.indexOf(e);-1!==t&&(e.dispose(),this._flowGraphs.splice(t,1))},e.prototype.start=function(){this._flowGraphs.forEach((function(e){return e.start()}))},e.prototype.dispose=function(){var t;this._flowGraphs.forEach((function(e){return e.dispose()})),this._flowGraphs.length=0;var i=null!==(t=e.SceneCoordinators.get(this.config.scene))&&void 0!==t?t:[],r=i.indexOf(this);-1!==r&&i.splice(r,1)},e.prototype.serialize=function(e,t){e._flowGraphs=[],this._flowGraphs.forEach((function(i){var r={};i.serialize(r,t),e._flowGraphs.push(r)}))},e.Parse=function(t,i){var r,n,o=null!==(r=i.valueParseFunction)&&void 0!==r?r:pM,a=new e({scene:i.scene});return null===(n=t._flowGraphs)||void 0===n||n.forEach((function(e){SM.Parse(e,{coordinator:a,valueParseFunction:o,pathConverter:i.pathConverter})})),a},Object.defineProperty(e.prototype,"flowGraphs",{get:function(){return this._flowGraphs},enumerable:!1,configurable:!0}),e.prototype.getCustomEventObservable=function(e){var t=this._customEventsMap.get(e);return t||(t=new f,this._customEventsMap.set(e,t)),t},e.prototype.notifyCustomEvent=function(e,t){var i=this._customEventsMap.get(e);i&&i.notifyObservers(t)},e.SceneCoordinators=new Map,e}(),AM=function(e){this._context=e,this._context.onNodeExecutedObservable.add((function(e){rr.Log("Node executed: ".concat(e.getClassName()))}))},CM=function(e){function t(t){var i=e.call(this,t)||this;return i.out=i._registerSignalOutput("out"),i}return m(t,e),t}(mM),RM=function(e){function t(t){var i=e.call(this,t)||this;return i.message=i.registerDataInput("message",qI),i}return m(t,e),t.prototype._execute=function(e){var t=this.message.getValue(e);ae.Log(t),this.out._activateSignal(e)},t.prototype.getClassName=function(){return t.ClassName},t.ClassName="FGConsoleLogBlock",t}(CM);a(RM.ClassName,RM);var PM=function(e){function t(t){var i=e.call(this,t)||this;return i.config=t,i.input=i.registerDataInput(t.variableName,qI),i}return m(t,e),t.prototype._execute=function(e){var t=this.config.variableName,i=this.input.getValue(e);e.setVariable(t,i),this.out._activateSignal(e)},t.prototype.getClassName=function(){return t.ClassName},t.ClassName="FGSetVariableBlock",t}(CM);a(PM.ClassName,PM);var IM=new RegExp(/\{(\w+)\}/g),MM=function(){function e(e,t){this.path=e,this.ownerBlock=t,this.templatedInputs=[];for(var i=IM.exec(e);i;){var r=i[1];this.templatedInputs.push(t.registerDataInput(r,sM)),i=IM.exec(e)}}return e.prototype.getAccessor=function(e,t){for(var i=this.path,r=0,n=this.templatedInputs;r<n.length;r++){var o=n[r],a=o.getValue(t).value;i=i.replace("{".concat(o.name,"}"),a.toString())}return e.convert(i)},e}(),OM=function(e){function t(t){var i=e.call(this,t)||this;return i.config=t,i.a=i.registerDataInput("a",qI),i.templateComponent=new MM(t.path,i),i}return m(t,e),t.prototype._execute=function(e){var t=this.a.getValue(e),i=this.templateComponent.getAccessor(this.config.pathConverter,e);i.info.set(t,i.object),this.out._activateSignal(e)},t.prototype.serialize=function(t){void 0===t&&(t={}),e.prototype.serialize.call(this,t),t.config.path=this.config.path},t.prototype.getClassName=function(){return t.ClassName},t.ClassName="FGSetPropertyBlock",t}(CM);a("FGSetPropertyBlock",OM);var DM=function(e){function t(t){var i=e.call(this,t)||this;i.config=t;for(var r=0;r<i.config.eventData.length;r++){var n=i.config.eventData[r];i.registerDataInput(n,qI)}return i}return m(t,e),t.prototype._execute=function(e){var t=this.config.eventId,i=this.dataInputs.map((function(t){return t.getValue(e)}));e.configuration.coordinator.notifyCustomEvent(t,i),this.out._activateSignal(e)},t.prototype.getClassName=function(){return t.ClassName},t.ClassName="FGSendCustomEventBlock",t}(CM);a("FGSendCustomEventBlock",DM);var NM=function(e){function t(t){var i=e.call(this,t)||this;return i.condition=i.registerDataInput("condition",$I),i.onTrue=i._registerSignalOutput("onTrue"),i.onFalse=i._registerSignalOutput("onFalse"),i}return m(t,e),t.prototype._execute=function(e){this.condition.getValue(e)?this.onTrue._activateSignal(e):this.onFalse._activateSignal(e)},t.prototype.getClassName=function(){return"FGBranchBlock"},t}(mM);a("FGBranchBlock",NM);var FM=function(e){function t(t){void 0===t&&(t={startIndex:new KI(0)});var i=e.call(this,t)||this;return i.config=t,i.reset=i._registerSignalInput("reset"),i.n=i.registerDataInput("n",sM),i.value=i.registerDataOutput("value",sM),i}return m(t,e),t.prototype._execute=function(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{var i=this.value.getValue(e);i.value<this.n.getValue(e).value&&(this.value.setValue(new KI(i.value+1),e),this.out._activateSignal(e))}},t.prototype.getClassName=function(){return t.ClassName},t.ClassName="FGDoNBlock",t}(CM);a(FM.ClassName,FM);var LM=function(e){function t(t){var i=e.call(this,t)||this;return i.startIndex=i.registerDataInput("startIndex",JI),i.endIndex=i.registerDataInput("endIndex",JI),i.step=i.registerDataInput("step",JI),i.index=i.registerDataOutput("index",JI),i.onLoop=i._registerSignalOutput("onLoop"),i}return m(t,e),t.prototype._executeLoop=function(e){var t=e._getExecutionVariable(this,"index");t<e._getExecutionVariable(this,"endIndex")?(this.index.setValue(t,e),this.onLoop._activateSignal(e),t+=e._getExecutionVariable(this,"step",1),e._setExecutionVariable(this,"index",t),this._executeLoop(e)):this.out._activateSignal(e)},t.prototype._execute=function(e){var t=this.startIndex.getValue(e),i=this.endIndex.getValue(e),r=this.step.getValue(e);e._setExecutionVariable(this,"index",t),e._setExecutionVariable(this,"endIndex",i),e._setExecutionVariable(this,"step",r),this._executeLoop(e)},t.prototype.getClassName=function(){return"FGForLoopBlock"},t}(CM);a("FGForLoopBlock",LM);var wM=function(e){function t(t){var i=e.call(this,t)||this;return i.reset=i._registerSignalInput("reset"),i.duration=i.registerDataInput("duration",JI),i.timeRemaining=i.registerDataOutput("timeRemaining",JI),i}return m(t,e),t.prototype._execute=function(e,t){var i=e._getExecutionVariable(this,"lastExecutedTime"),r=this.duration.getValue(e),n=Date.now();if(t===this.reset||void 0===i||n-i>r)this.timeRemaining.setValue(0,e),this.out._activateSignal(e),e._setExecutionVariable(this,"lastExecutedTime",n);else{var o=r-(n-i);this.timeRemaining.setValue(o,e)}},t.prototype.getClassName=function(){return"FGThrottleBlock"},t}(CM);a("FGThrottleBlock",wM);var BM=function(e){function t(t){var i=e.call(this,t)||this;return i.timeout=i.registerDataInput("timeout",JI),i}return m(t,e),t.prototype._preparePendingTasks=function(e){var t=this,i=this.timeout.getValue(e);if(void 0!==i&&i>=0){var r=e._getExecutionVariable(this,"runningTimers")||[],n=e.configuration.scene,o=new jg({timeout:i,contextObservable:n.onBeforeRenderObservable,onEnded:function(){return t._onEnded(o,e)}});o.start(),r.push(o),e._setExecutionVariable(this,"runningTimers",r)}},t.prototype._execute=function(e){this._startPendingTasks(e),this.out._activateSignal(e)},t.prototype._onEnded=function(e,t){var i=t._getExecutionVariable(this,"runningTimers")||[],r=i.indexOf(e);-1!==r?i.splice(r,1):rr.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list"),t._removePendingBlock(this),this.done._activateSignal(t)},t.prototype._cancelPendingTasks=function(e){for(var t=0,i=e._getExecutionVariable(this,"runningTimers")||[];t<i.length;t++)i[t].dispose();e._deleteExecutionVariable(this,"runningTimers")},t.prototype.getClassName=function(){return t.ClassName},t.ClassName="FGTimerBlock",t}(gM);a("FGTimerBlock",BM);var UM=function(e){function t(t){var i=e.call(this,t)||this;i.config=t,i._cachedUnusedIndexes=[],i.reset=i._registerSignalInput("reset"),i.currentIndex=i.registerDataOutput("currentIndex",JI),i.config.startIndex=void 0!==i.config.startIndex?i.config.startIndex:0,i.config.startIndex=Math.max(0,Math.min(i.config.startIndex,i.config.numberOutputFlows-1)),i.outFlows=[];for(var r=0;r<i.config.numberOutputFlows;r++)i.outFlows.push(i._registerSignalOutput("out".concat(r)));return i}return m(t,e),t.prototype._getUnusedIndexes=function(e){var t=this._cachedUnusedIndexes;if(t.length=0,e._hasExecutionVariable(this,"unusedIndexes")){var i=e._getExecutionVariable(this,"unusedIndexes");for(r=0;r<i.length;r++)t.push(i[r])}else for(var r=0;r<this.config.numberOutputFlows;r++)t.push(r);return t},t.prototype._getNextOutput=function(e,t){return this.config.isRandom?t[Math.floor(Math.random()*t.length)]:e+1},t.prototype._execute=function(e,t){var i,r=null!==(i=e._getExecutionVariable(this,"currentIndex"))&&void 0!==i?i:this.config.startIndex-1,n=this._getUnusedIndexes(e);if(t===this.reset)return e._deleteExecutionVariable(this,"currentIndex"),void e._deleteExecutionVariable(this,"unusedIndexes");var o=this._getNextOutput(r,n);if(o>=this.config.numberOutputFlows&&this.config.loop)o=0;else if(o>=this.config.numberOutputFlows&&!this.config.loop)return;if(n=n.filter((function(e){return e!==o})),0===n.length)for(var a=0;a<this.config.numberOutputFlows;a++)n.push(a);e._setExecutionVariable(this,"unusedIndexes",n),e._setExecutionVariable(this,"currentIndex",o),this.currentIndex.setValue(o,e),this.outFlows[o]._activateSignal(e)},t.prototype.getClassName=function(){return"FGMultiGateBlock"},t.prototype.serialize=function(t){e.prototype.serialize.call(this,t),t.config.numberOutputFlows=this.config.numberOutputFlows,t.config.isRandom=this.config.isRandom,t.config.loop=this.config.loop,t.config.startIndex=this.config.startIndex},t}(mM);a("FGMultiGateBlock",UM);var VM=function(e){function t(t){var i=e.call(this,t)||this;i.config=t,i.selection=i.registerDataInput("selection",qI),i.outputFlows=[];for(var r=0;r<=i.config.cases.length;r++)i.outputFlows.push(i._registerSignalOutput("out".concat(r)));return i}return m(t,e),t.prototype._execute=function(e,t){for(var i=this.selection.getValue(e),r=0;r<this.config.cases.length;r++)if(i===this.config.cases[r])return void this.outputFlows[r]._activateSignal(e);this.outputFlows[this.outputFlows.length-1]._activateSignal(e)},t.prototype.getClassName=function(){return"FGSwitchBlock"},t.prototype.serialize=function(t){e.prototype.serialize.call(this,t),t.cases=this.config.cases},t}(mM);a("FGSwitchBlock",VM);var kM=function(e){function t(t){var i=e.call(this,t)||this;i.config=t,i.inFlows=[],i._cachedActivationState=[],i.reset=i._registerSignalInput("reset");for(var r=1;r<i.config.numberInputFlows;r++)i.inFlows.push(i._registerSignalInput("in".concat(r)));return i}return m(t,e),t.prototype._getCurrentActivationState=function(e){var t=this._cachedActivationState;if(t.length=0,e._hasExecutionVariable(this,"activationState")){var i=e._getExecutionVariable(this,"activationState");for(r=0;r<i.length;r++)t.push(i[r])}else for(var r=0;r<this.config.numberInputFlows;r++)t.push(!1);return t},t.prototype._execute=function(e,t){var i=this._getCurrentActivationState(e);if(t===this.reset)for(var r=0;r<this.config.numberInputFlows;r++)i[r]=!1;else if(t===this.in)i[0]=!0;else{var n=this.inFlows.indexOf(t);n>=0&&(i[n+1]=!0)}if(e._setExecutionVariable(this,"activationState",i.slice()),i.every((function(e){return e})))for(this.out._activateSignal(e),r=0;r<this.config.numberInputFlows;r++)i[r]=!1},t.prototype.getClassName=function(){return"FGWaitAllBlock"},t.prototype.serialize=function(t){e.prototype.serialize.call(this,t),t.config.numberInputFlows=this.config.numberInputFlows},t}(CM);a("FGWaitAllBlock",kM);var GM=function(e){function t(t){var i=e.call(this,t)||this;return i.count=i.registerDataOutput("count",JI),i.reset=i._registerSignalInput("reset"),i}return m(t,e),t.prototype._execute=function(e,t){var i;if(t===this.reset)return e._setExecutionVariable(this,"count",0),void this.count.setValue(0,e);var r=(null!==(i=e._getExecutionVariable(this,"count"))&&void 0!==i?i:0)+1;e._setExecutionVariable(this,"count",r),this.count.setValue(r,e),this.out._activateSignal(e)},t.prototype.getClassName=function(){return"FGCounterBlock"},t}(CM);a("FGCounterBlock",GM);var zM=function(e){function t(t){var i=e.call(this,t)||this;return i.config=t,i.condition=i.registerDataInput("condition",$I),i.loopBody=i._registerSignalOutput("loopBody"),i}return m(t,e),t.prototype._execute=function(e,t){var i,r=this.condition.getValue(e);for((null===(i=this.config)||void 0===i?void 0:i.isDo)&&!r&&this.loopBody._activateSignal(e);r;)this.loopBody._activateSignal(e),r=this.condition.getValue(e);this.out._activateSignal(e)},t.prototype.getClassName=function(){return t.ClassName},t.prototype.serialize=function(t){var i;e.prototype.serialize.call(this,t),t.isDo=null===(i=this.config)||void 0===i?void 0:i.isDo},t.ClassName="FGWhileLoopBlock",t}(CM);a(zM.ClassName,zM);var WM=function(e){function t(t){var i=e.call(this,t)||this;return i.count=i.registerDataInput("count",JI),i.reset=i._registerSignalInput("reset"),i.currentCount=i.registerDataOutput("currentCount",JI),i}return m(t,e),t.prototype._execute=function(e,t){if(t!==this.reset){var i=this.count.getValue(e),r=e._getExecutionVariable(this,"debounceCount",0)+1;this.currentCount.setValue(r,e),e._setExecutionVariable(this,"debounceCount",r),r>=i&&(this.out._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}else e._setExecutionVariable(this,"debounceCount",0)},t.prototype.getClassName=function(){return"FGDebounceBlock"},t}(CM);a("FGDebounceBlock",WM);var HM=function(e){function t(t){var i=e.call(this,t)||this;return i.onOn=i._registerSignalOutput("onOn"),i.onOff=i._registerSignalOutput("onOff"),i.isOn=i.registerDataOutput("isOn",$I),i}return m(t,e),t.prototype._execute=function(e,t){var i=e._getExecutionVariable(this,"value",!1);i=!i,e._setExecutionVariable(this,"value",i),this.isOn.setValue(i,e),i?this.onOn._activateSignal(e):this.onOff._activateSignal(e)},t.prototype.getClassName=function(){return"FGFlipFlopBlock"},t}(mM);a("FGFlipFlopBlock",HM);var XM=function(e){function t(t){var i=e.call(this,t)||this;i.config=t,i.outFlows=[];for(var r=0;r<i.config.numberOutputFlows;r++)i.outFlows.push(i._registerSignalOutput("".concat(r)));return i}return m(t,e),t.prototype._execute=function(e){for(var t=0;t<this.config.numberOutputFlows;t++)this.outFlows[t]._activateSignal(e)},t.prototype.getClassName=function(){return t.ClassName},t.ClassName="FGSequenceBlock",t}(mM);a(XM.ClassName,XM);var jM=function(e){function t(t){var i=e.call(this,t)||this;return i.config=t,i.templateTargetComponent=new MM(t.targetPath,i),i.templateAnimationComponent=new MM(t.animationPath,i),i.speed=i.registerDataInput("speed",JI),i.loop=i.registerDataInput("loop",$I),i.from=i.registerDataInput("from",JI),i.to=i.registerDataInput("to",JI),i.runningAnimatable=i.registerDataOutput("runningAnimatable",qI),i}return m(t,e),t.prototype._preparePendingTasks=function(e){var t,i=this,r=this.templateTargetComponent.getAccessor(this.config.pathConverter,e),n=r.info.getObject(r.object),o=this.templateAnimationComponent.getAccessor(this.config.pathConverter,e),a=o.info.get(o.object);if(!n||!a)throw new Error("Cannot play animation without target or animation");var s=null!==(t=e._getExecutionVariable(this,"runningAnimatables"))&&void 0!==t?t:[],l=this.runningAnimatable.getValue(e);if(l&&l.paused)l.restart();else{var c=e.configuration.scene.beginDirectAnimation(n,[a],this.from.getValue(e),this.to.getValue(e),this.loop.getValue(e),this.speed.getValue(e),(function(){return i._onAnimationEnd(c,e)}));this.runningAnimatable.setValue(c,e),s.push(c)}e._setExecutionVariable(this,"runningAnimatables",s)},t.prototype._execute=function(e){this._startPendingTasks(e),this.out._activateSignal(e)},t.prototype._onAnimationEnd=function(e,t){var i,r=null!==(i=t._getExecutionVariable(this,"runningAnimatables"))&&void 0!==i?i:[],n=r.indexOf(e);-1!==n&&r.splice(n,1),t._removePendingBlock(this),this.done._activateSignal(t)},t.prototype._cancelPendingTasks=function(e){for(var t,i=0,r=null!==(t=e._getExecutionVariable(this,"runningAnimatables"))&&void 0!==t?t:[];i<r.length;i++)r[i].stop();e._deleteExecutionVariable(this,"runningAnimatables")},t.prototype.getClassName=function(){return t.ClassName},t.prototype.serialize=function(t){void 0===t&&(t={}),e.prototype.serialize.call(this,t),t.config.targetPath=this.config.targetPath,t.config.animationPath=this.config.animationPath},t.ClassName="FGPlayAnimationBlock",t}(gM);a(jM.ClassName,jM);var YM=function(e){function t(t){var i=e.call(this,t)||this;return i.animationToStop=i.registerDataInput("animationToStop",qI),i}return m(t,e),t.prototype._execute=function(e){this.animationToStop.getValue(e).stop(),this.out._activateSignal(e)},t.prototype.getClassName=function(){return"FGStopAnimationBlock"},t}(CM);a("FGStopAnimationBlock",YM);var KM=function(e){function t(t){var i=e.call(this,t)||this;return i.animationToPause=i.registerDataInput("animationToPause",qI),i}return m(t,e),t.prototype._execute=function(e){this.animationToPause.getValue(e).pause(),this.out._activateSignal(e)},t.prototype.getClassName=function(){return"FGPauseAnimationBlock"},t}(CM);a("FGPauseAnimationBlock",KM);var QM=function(e){function t(t){var i=e.call(this,t)||this;return i.condition=i.registerDataInput("condition",$I),i.trueValue=i.registerDataInput("trueValue",qI),i.falseValue=i.registerDataInput("falseValue",qI),i.output=i.registerDataOutput("output",qI),i}return m(t,e),t.prototype._updateOutputs=function(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)},t.prototype.getClassName=function(){return"FGConditionalDataBlock"},t}(fM);a("FGConditionalDataBlock",QM);var qM=function(e){function t(t){var i=e.call(this,t)||this;return i.config=t,i.output=i.registerDataOutput(t.variableName,qI),i}return m(t,e),t.prototype._updateOutputs=function(e){var t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)},t.prototype.getClassName=function(){return t.ClassName},t.prototype.serialize=function(t){e.prototype.serialize.call(this,t),t.config.variableName=this.config.variableName},t.ClassName="FGGetVariableBlock",t}(fM);a(qM.ClassName,qM);var ZM=function(e){function t(t){var i=e.call(this,t)||this;return i.sourceSystem=i.registerDataInput("sourceSystem",qI),i.destinationSystem=i.registerDataInput("destinationSystem",qI),i.inputCoordinates=i.registerDataInput("inputCoordinates",tM),i.outputCoordinates=i.registerDataOutput("outputCoordinates",tM),i}return m(t,e),t.prototype._updateOutputs=function(e){var t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),r=this.inputCoordinates.getValue(e),n=t.getWorldMatrix(),o=i.getWorldMatrix(),a=H.Matrix[0].copyFrom(o);a.invert();var s=H.Matrix[1];a.multiplyToRef(n,s);var l=this.outputCoordinates.getValue(e);V.TransformCoordinatesToRef(r,s,l)},t.prototype.getClassName=function(){return"FGCoordinateTransformBlock"},t}(fM);a("FGCoordinateTransformBlock",ZM);var JM=function(e){function t(t){var i=e.call(this,t)||this;return i.config=t,i.output=i.registerDataOutput("output",lM(t.value)),i}return m(t,e),t.prototype._updateOutputs=function(e){this.output.setValue(this.config.value,e)},t.prototype.getClassName=function(){return"FGConstantBlock"},t.prototype.serialize=function(t,i){void 0===t&&(t={}),void 0===i&&(i=dM),e.prototype.serialize.call(this,t),i("value",this.config.value,t.config)},t}(fM);a("FGConstantBlock",JM);var $M=function(e){function t(t){var i=e.call(this,t)||this;return i.config=t,i.value=i.registerDataOutput("value",qI),i.templateComponent=new MM(t.path,i),i}return m(t,e),t.prototype._updateOutputs=function(e){var t=this.templateComponent.getAccessor(this.config.pathConverter,e),i=t.info.get(t.object);this.value.setValue(i,e)},t.prototype.getClassName=function(){return t.ClassName},t.prototype.serialize=function(t){void 0===t&&(t={}),e.prototype.serialize.call(this,t),t.config.path=this.config.path},t.ClassName="FGGetPropertyBlock",t}(fM);a($M.ClassName,$M);var eO="cachedOperationValue",tO="cachedExecutionId",iO=function(e){function t(t,i){var r=e.call(this,i)||this;return r.value=r.registerDataOutput("value",t),r}return m(t,e),t.prototype._updateOutputs=function(e){var t=e._getExecutionVariable(this,tO),i=e._getExecutionVariable(this,eO);if(void 0!==i&&t===e.executionId)this.value.setValue(i,e);else{var r=this._doOperation(e);e._setExecutionVariable(this,eO,r),e._setExecutionVariable(this,tO,e.executionId),this.value.setValue(r,e)}},t}(fM),rO=function(e){function t(t,i,r,n,o,a){var s=e.call(this,r,a)||this;return s._operation=n,s._className=o,s.a=s.registerDataInput("a",t),s.b=s.registerDataInput("b",i),s}return m(t,e),t.prototype._doOperation=function(e){return this._operation(this.a.getValue(e),this.b.getValue(e))},t.prototype.getClassName=function(){return this._className},t}(iO),nO=function(e){function t(t,i,r,n,o){var a=e.call(this,i,o)||this;return a._operation=r,a._className=n,a.a=a.registerDataInput("a",t),a}return m(t,e),t.prototype._doOperation=function(e){return this._operation(this.a.getValue(e))},t.prototype.getClassName=function(){return this._className},t}(iO),oO="FGLogic",aO="AndBlock",sO="OrBlock",lO="NotBlock",cO=function(e){function t(t){return e.call(this,$I,$I,$I,(function(e,t){return e&&t}),"".concat(oO).concat(aO),t)||this}return m(t,e),t}(rO);a("".concat(oO).concat(aO),cO);var uO=function(e){function t(t){return e.call(this,$I,$I,$I,(function(e,t){return e||t}),"".concat(oO).concat(sO),t)||this}return m(t,e),t}(rO);a("".concat(oO).concat(sO),uO);var hO=function(e){function t(t){return e.call(this,$I,$I,(function(e){return!e}),"".concat(oO).concat(lO),t)||this}return m(t,e),t}(nO);a("".concat(oO).concat(lO),hO);var dO=function(e){function t(t,i,r,n){var o=e.call(this,t,n)||this;return o._operation=i,o._className=r,o}return m(t,e),t.prototype._doOperation=function(e){return this._operation()},t.prototype.getClassName=function(){return this._className},t}(iO),pO=function(e){function t(t,i,r,n,o,a,s){var l=e.call(this,n,s)||this;return l._operation=o,l._className=a,l.a=l.registerDataInput("a",t),l.b=l.registerDataInput("b",i),l.c=l.registerDataInput("c",r),l}return m(t,e),t.prototype._doOperation=function(e){return this._operation(this.a.getValue(e),this.b.getValue(e),this.c.getValue(e))},t.prototype.getClassName=function(){return this._className},t}(iO);function fO(e){return e.getClassName?e.getClassName():""}function _O(e,t){return"Vector2"===e&&"Vector2"===t||"Vector3"===e&&"Vector3"===t||"Vector4"===e&&"Vector4"===t}function mO(e,t){return"Matrix"===e&&"Matrix"===t}function gO(e,t){return"FlowGraphInteger"===e&&"FlowGraphInteger"===t}var vO=function(e){function t(i){var r=e.call(this,qI,qI,qI,(function(e,t){return r._polymorphicAdd(e,t)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicAdd=function(e,t){var i=fO(e),r=fO(t);return _O(i,r)||mO(i,r)||gO(i,r)?e.add(t):e+t},t.ClassName="FGAddBlock",t}(rO);a(vO.ClassName,vO);var yO=function(e){function t(i){var r=e.call(this,qI,qI,qI,(function(e,t){return r._polymorphicAdd(e,t)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicAdd=function(e,t){var i=fO(e),r=fO(t);return _O(i,r)||gO(i,r)?e.subtract(t):mO(i,r)?e.add(t.scale(-1)):e-t},t.ClassName="FGSubBlock",t}(rO);a(yO.ClassName,yO);var bO=function(e){function t(i){var r=e.call(this,qI,qI,qI,(function(e,t){return r._polymorphicMultiply(e,t)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicMultiply=function(e,t){var i=fO(e),r=fO(t);return _O(i,r)||gO(i,r)?e.multiply(t):mO(i,r)?z.FromValues(e.m[0]*t.m[0],e.m[4]*t.m[4],e.m[8]*t.m[8],e.m[12]*t.m[12],e.m[1]*t.m[1],e.m[5]*t.m[5],e.m[9]*t.m[9],e.m[13]*t.m[13],e.m[2]*t.m[2],e.m[6]*t.m[6],e.m[10]*t.m[10],e.m[14]*t.m[14],e.m[3]*t.m[3],e.m[7]*t.m[7],e.m[11]*t.m[11],e.m[15]*t.m[15]):e*t},t.ClassName="FGMultiplyBlock",t}(rO);a(bO.ClassName,bO);var TO=function(e){function t(i){var r=e.call(this,qI,qI,qI,(function(e,t){return r._polymorphicDivide(e,t)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicDivide=function(e,t){var i=fO(e),r=fO(t);return _O(i,r)||gO(i,r)?e.divide(t):mO(i,r)?z.FromValues(e.m[0]/t.m[0],e.m[4]/t.m[4],e.m[8]/t.m[8],e.m[12]/t.m[12],e.m[1]/t.m[1],e.m[5]/t.m[5],e.m[9]/t.m[9],e.m[13]/t.m[13],e.m[2]/t.m[2],e.m[6]/t.m[6],e.m[10]/t.m[10],e.m[14]/t.m[14],e.m[3]/t.m[3],e.m[7]/t.m[7],e.m[11]/t.m[11],e.m[15]/t.m[15]):e/t},t.ClassName="FGDivideBlock",t}(rO);a(TO.ClassName,TO);var EO=function(e){function t(i){return e.call(this,JI,(function(){return Math.random()}),t.ClassName,i)||this}return m(t,e),t.ClassName="FGRandomBlock",t}(dO);a(EO.ClassName,EO);var SO=function(e){function t(i){var r=e.call(this,qI,qI,JI,(function(e,t){return r._polymorphicDot(e,t)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicDot=function(e,t){switch(fO(e)){case"Vector2":return U.Dot(e,t);case"Vector3":return V.Dot(e,t);case"Vector4":return k.Dot(e,t);default:throw new Error("Cannot get dot product of ".concat(e," and ").concat(t))}},t.ClassName="FGDotBlock",t}(rO);a(SO.ClassName,SO);var xO=function(e){function t(i){return e.call(this,JI,(function(){return Math.E}),t.ClassName,i)||this}return m(t,e),t.ClassName="FGEBlock",t}(dO);a(xO.ClassName,xO);var AO=function(e){function t(i){return e.call(this,JI,(function(){return Math.PI}),t.ClassName,i)||this}return m(t,e),t.ClassName="FGPIBlock",t}(dO);a(AO.ClassName,AO);var CO=function(e){function t(i){return e.call(this,JI,(function(){return Number.POSITIVE_INFINITY}),t.ClassName,i)||this}return m(t,e),t.ClassName="FGInfBlock",t}(dO);a(CO.ClassName,CO);var RO=function(e){function t(i){return e.call(this,JI,(function(){return Number.NaN}),t.ClassName,i)||this}return m(t,e),t.ClassName="FGNaNBlock",t}(dO);function PO(e,t){switch(fO(e)){case"FlowGraphInteger":return new KI(t(e.value));case"Vector2":return new U(t(e.x),t(e.y));case"Vector3":return new V(t(e.x),t(e.y),t(e.z));case"Vector4":return new k(t(e.x),t(e.y),t(e.z),t(e.w));case"Matrix":return z.FromValues(t(e.m[0]),t(e.m[4]),t(e.m[8]),t(e.m[12]),t(e.m[1]),t(e.m[5]),t(e.m[9]),t(e.m[13]),t(e.m[2]),t(e.m[6]),t(e.m[10]),t(e.m[14]),t(e.m[3]),t(e.m[7]),t(e.m[11]),t(e.m[15]));default:return t(e)}}a(RO.ClassName,RO);var IO=function(e){function t(i){var r=e.call(this,qI,qI,(function(e){return r._polymorphicAbs(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicAbs=function(e){return PO(e,Math.abs)},t.ClassName="FGAbsBlock",t}(nO);a(IO.ClassName,IO);var MO=function(e){function t(i){var r=e.call(this,qI,qI,(function(e){return r._polymorphicSign(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicSign=function(e){return PO(e,Math.sign)},t.ClassName="FGSignBlock",t}(nO);a(MO.ClassName,MO);var OO=function(e){function t(i){var r=e.call(this,qI,qI,(function(e){return r._polymorphicTrunc(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicTrunc=function(e){return PO(e,Math.trunc)},t.ClassName="FGTruncBlock",t}(nO);a(OO.ClassName,OO);var DO=function(e){function t(i){var r=e.call(this,qI,qI,(function(e){return r._polymorphicFloor(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicFloor=function(e){return PO(e,Math.floor)},t.ClassName="FGFloorBlock",t}(nO);a(DO.ClassName,DO);var NO=function(e){function t(i){var r=e.call(this,qI,qI,(function(e){return r._polymorphicCeiling(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicCeiling=function(e){return PO(e,Math.ceil)},t.ClassName="FGCeilBlock",t}(nO);a(NO.ClassName,NO);var FO=function(e){function t(i){var r=e.call(this,qI,qI,(function(e){return r._polymorphicFract(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicFract=function(e){return PO(e,(function(e){return e-Math.floor(e)}))},t.ClassName="FGFractBlock",t}(nO);a(FO.ClassName,FO);var LO=function(e){function t(i){var r=e.call(this,qI,qI,(function(e){return r._polymorphicNeg(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicNeg=function(e){return PO(e,(function(e){return-e}))},t.ClassName="FGNegBlock",t}(nO);function wO(e,t,i){switch(fO(e)){case"FlowGraphInteger":return new KI(i(e.value,t.value));case"Vector2":return new U(i(e.x,t.x),i(e.y,t.y));case"Vector3":return new V(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z));case"Vector4":return new k(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z),i(e.w,t.w));case"Matrix":return z.FromValues(i(e.m[0],t.m[0]),i(e.m[4],t.m[4]),i(e.m[8],t.m[8]),i(e.m[12],t.m[12]),i(e.m[1],t.m[1]),i(e.m[5],t.m[5]),i(e.m[9],t.m[9]),i(e.m[13],t.m[13]),i(e.m[2],t.m[2]),i(e.m[6],t.m[6]),i(e.m[10],t.m[10]),i(e.m[14],t.m[14]),i(e.m[3],t.m[3]),i(e.m[7],t.m[7]),i(e.m[11],t.m[11]),i(e.m[15],t.m[15]));default:return i(e,t)}}a(LO.ClassName,LO);var BO=function(e){function t(i){var r=e.call(this,qI,qI,qI,(function(e,t){return r._polymorphicRemainder(e,t)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicRemainder=function(e,t){return wO(e,t,(function(e,t){return e%t}))},t.ClassName="FGRemainderBlock",t}(rO);a(BO.ClassName,BO);var UO=function(e){function t(i){var r=e.call(this,qI,qI,qI,(function(e,t){return r._polymorphicMin(e,t)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicMin=function(e,t){return wO(e,t,Math.min)},t.ClassName="FGMinBlock",t}(rO);a(UO.ClassName,UO);var VO=function(e){function t(i){var r=e.call(this,qI,qI,qI,(function(e,t){return r._polymorphicMax(e,t)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicMax=function(e,t){return wO(e,t,Math.max)},t.ClassName="FGMaxBlock",t}(rO);function kO(e,t,i){return Math.min(Math.max(e,Math.min(t,i)),Math.max(t,i))}function GO(e,t,i,r){switch(fO(e)){case"FlowGraphInteger":return new KI(r(e.value,t.value,i.value));case"Vector2":return new U(r(e.x,t.x,i.x),r(e.y,t.y,i.y));case"Vector3":return new V(r(e.x,t.x,i.x),r(e.y,t.y,i.y),r(e.z,t.z,i.z));case"Vector4":return new k(r(e.x,t.x,i.x),r(e.y,t.y,i.y),r(e.z,t.z,i.z),r(e.w,t.w,i.w));case"Matrix":return z.FromValues(r(e.m[0],t.m[0],i.m[0]),r(e.m[4],t.m[4],i.m[4]),r(e.m[8],t.m[8],i.m[8]),r(e.m[12],t.m[12],i.m[12]),r(e.m[1],t.m[1],i.m[1]),r(e.m[5],t.m[5],i.m[5]),r(e.m[9],t.m[9],i.m[9]),r(e.m[13],t.m[13],i.m[13]),r(e.m[2],t.m[2],i.m[2]),r(e.m[6],t.m[6],i.m[6]),r(e.m[10],t.m[10],i.m[10]),r(e.m[14],t.m[14],i.m[14]),r(e.m[3],t.m[3],i.m[3]),r(e.m[7],t.m[7],i.m[7]),r(e.m[11],t.m[11],i.m[11]),r(e.m[15],t.m[15],i.m[15]));default:return r(e,t,i)}}a(VO.ClassName,VO);var zO=function(e){function t(i){var r=e.call(this,qI,qI,qI,qI,(function(e,t,i){return r._polymorphicClamp(e,t,i)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicClamp=function(e,t,i){return GO(e,t,i,kO)},t.ClassName="FGClampBlock",t}(pO);function WO(e){return Math.min(Math.max(e,0),1)}a(zO.ClassName,zO);var HO=function(e){function t(i){var r=e.call(this,qI,qI,(function(e){return r._polymorphicSaturate(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicSaturate=function(e){return PO(e,WO)},t.ClassName="FGSaturateBlock",t}(nO);a(HO.ClassName,HO);var XO=function(e){function t(i){var r=e.call(this,qI,qI,qI,qI,(function(e,t,i){return r._polymorphicInterpolate(e,t,i)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._interpolate=function(e,t,i){return(1-i)*e+i*t},t.prototype._polymorphicInterpolate=function(e,t,i){return GO(e,t,i,this._interpolate)},t.ClassName="FGInterpolateBlock",t}(pO);a(XO.ClassName,XO);var jO=function(e){function t(i){var r=e.call(this,qI,qI,$I,(function(e,t){return r._polymorphicEq(e,t)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicEq=function(e,t){var i=fO(e),r=fO(t);return _O(i,r)||mO(i,r)||gO(i,r)?e.equals(t):e===t},t.ClassName="FGEqBlock",t}(rO);function YO(e,t,i){var r=fO(e);if(r===fO(t)){if(""===r)return i(e,t);if("FlowGraphInteger"===r)return i(e.value,t.value);throw new Error("Cannot compare ".concat(e," and ").concat(t))}throw new Error("".concat(e," and ").concat(t," are of different types."))}a(jO.ClassName,jO);var KO=function(e){function t(i){var r=e.call(this,qI,qI,$I,(function(e,t){return r._polymorphicLessThan(e,t)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicLessThan=function(e,t){return YO(e,t,(function(e,t){return e<t}))},t.ClassName="FGLessThanBlock",t}(rO);a(KO.ClassName,KO);var QO=function(e){function t(i){var r=e.call(this,qI,qI,$I,(function(e,t){return r._polymorphicLessThanOrEqual(e,t)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicLessThanOrEqual=function(e,t){return YO(e,t,(function(e,t){return e<=t}))},t.ClassName="FGLessThanOrEqualBlock",t}(rO),qO=function(e){function t(i){var r=e.call(this,qI,qI,$I,(function(e,t){return r._polymorphicGreaterThan(e,t)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicGreaterThan=function(e,t){return YO(e,t,(function(e,t){return e>t}))},t.ClassName="FGGreaterThanBlock",t}(rO);a(qO.ClassName,qO);var ZO=function(e){function t(i){var r=e.call(this,qI,qI,$I,(function(e,t){return r._polymorphicGreaterThanOrEqual(e,t)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicGreaterThanOrEqual=function(e,t){return YO(e,t,(function(e,t){return e>=t}))},t.ClassName="FGGreaterThanOrEqualBlock",t}(rO);a(ZO.ClassName,ZO);var JO=function(e){function t(i){var r=e.call(this,qI,$I,(function(e){return r._polymorphicIsNan(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicIsNan=function(e){var t=fO(e);if(""===t)return isNaN(e);if("FlowGraphInteger"===t)return isNaN(e.value);throw new Error("Cannot get NaN of ".concat(e))},t.ClassName="FGIsNanBlock",t}(nO);a(JO.ClassName,JO);var $O=function(e){function t(i){var r=e.call(this,qI,$I,(function(e){return r._polymorphicIsInf(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicIsInf=function(e){var t=fO(e);if(""===t)return!isFinite(e);if("FlowGraphInteger"===t)return!isFinite(e.value);throw new Error("Cannot get isInf of ".concat(e))},t.ClassName="FGIsInfBlock",t}(nO),eD=function(e){function t(i){var r=e.call(this,qI,qI,(function(e){return r._polymorphicDegToRad(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._degToRad=function(e){return e*Math.PI/180},t.prototype._polymorphicDegToRad=function(e){return PO(e,this._degToRad)},t.ClassName="FGDegToRadBlock",t}(nO);a(eD.ClassName,eD);var tD=function(e){function t(i){var r=e.call(this,qI,qI,(function(e){return r._polymorphicRadToDeg(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._radToDeg=function(e){return 180*e/Math.PI},t.prototype._polymorphicRadToDeg=function(e){return PO(e,this._radToDeg)},t.ClassName="FGRadToDegBlock",t}(nO);a(tD.ClassName,tD);var iD=function(e){function t(i){var r=e.call(this,qI,qI,(function(e){return r._polymorphicSin(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicSin=function(e){return PO(e,Math.sin)},t.ClassName="FGSinBlock",t}(nO);a(iD.ClassName,iD);var rD=function(e){function t(i){var r=e.call(this,qI,qI,(function(e){return r._polymorphicCos(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicCos=function(e){return PO(e,Math.cos)},t.ClassName="FGCosBlock",t}(nO);a(rD.ClassName,rD);var nD=function(e){function t(i){var r=e.call(this,qI,qI,(function(e){return r._polymorphicTan(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicTan=function(e){return PO(e,Math.tan)},t.ClassName="FGTanBlock",t}(nO);a(nD.ClassName,nD);var oD=function(e){function t(i){var r=e.call(this,qI,qI,(function(e){return r._polymorphicAsin(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicAsin=function(e){return PO(e,Math.asin)},t.ClassName="FGAsinBlock",t}(nO);a(oD.ClassName,oD);var aD=function(e){function t(i){var r=e.call(this,qI,qI,(function(e){return r._polymorphicAcos(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicAcos=function(e){return PO(e,Math.acos)},t.ClassName="FGAcosBlock",t}(nO);a(aD.ClassName,aD);var sD=function(e){function t(i){var r=e.call(this,qI,qI,(function(e){return r._polymorphicAtan(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicAtan=function(e){return PO(e,Math.atan)},t.ClassName="FGAtanBlock",t}(nO);a(sD.ClassName,sD);var lD=function(e){function t(i){var r=e.call(this,qI,qI,qI,(function(e,t){return r._polymorphicAtan2(e,t)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicAtan2=function(e,t){return wO(e,t,Math.atan2)},t.ClassName="FGAtan2Block",t}(rO);a(lD.ClassName,lD);var cD=function(e){function t(i){var r=e.call(this,qI,qI,(function(e){return r._polymorphicSinh(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicSinh=function(e){return PO(e,Math.sinh)},t.ClassName="FGSinhBlock",t}(nO);a(cD.ClassName,cD);var uD=function(e){function t(i){var r=e.call(this,qI,qI,(function(e){return r._polymorphicCosh(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicCosh=function(e){return PO(e,Math.cosh)},t.ClassName="FGCoshBlock",t}(nO);a(uD.ClassName,uD);var hD=function(e){function t(i){var r=e.call(this,qI,qI,(function(e){return r._polymorphicTanh(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicTanh=function(e){return PO(e,Math.tanh)},t.ClassName="FGTanhBlock",t}(nO);a(hD.ClassName,hD);var dD=function(e){function t(i){var r=e.call(this,qI,JI,(function(e){return r._polymorphicAsinh(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicAsinh=function(e){return PO(e,Math.asinh)},t.ClassName="FGAsinhBlock",t}(nO);a(dD.ClassName,dD);var pD=function(e){function t(i){var r=e.call(this,qI,JI,(function(e){return r._polymorphicAcosh(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicAcosh=function(e){return PO(e,Math.acosh)},t.ClassName="FGAcoshBlock",t}(nO);a(pD.ClassName,pD);var fD=function(e){function t(i){var r=e.call(this,qI,JI,(function(e){return r._polymorphicAtanh(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicAtanh=function(e){return PO(e,Math.atanh)},t.ClassName="FGAtanhBlock",t}(nO);a(fD.ClassName,fD);var _D=function(e){function t(i){var r=e.call(this,qI,JI,(function(e){return r._polymorphicExp(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicExp=function(e){return PO(e,Math.exp)},t.ClassName="FGExpBlock",t}(nO);a(_D.ClassName,_D);var mD=function(e){function t(i){var r=e.call(this,qI,JI,(function(e){return r._polymorphicLog(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicLog=function(e){return PO(e,Math.log)},t.ClassName="FGLogBlock",t}(nO);a(mD.ClassName,mD);var gD=function(e){function t(i){var r=e.call(this,qI,JI,(function(e){return r._polymorphicLog2(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicLog2=function(e){return PO(e,Math.log2)},t.ClassName="FGLog2Block",t}(nO);a(gD.ClassName,gD);var vD=function(e){function t(i){var r=e.call(this,qI,JI,(function(e){return r._polymorphicLog10(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicLog10=function(e){return PO(e,Math.log10)},t.ClassName="FGLog10Block",t}(nO);a(vD.ClassName,vD);var yD=function(e){function t(i){var r=e.call(this,qI,JI,(function(e){return r._polymorphicSqrt(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicSqrt=function(e){return PO(e,Math.sqrt)},t.ClassName="FGSqrtBlock",t}(nO);a(yD.ClassName,yD);var bD=function(e){function t(i){var r=e.call(this,qI,JI,(function(e){return r._polymorphicCubeRoot(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicCubeRoot=function(e){return PO(e,Math.cbrt)},t.ClassName="FGCubeRootBlock",t}(nO);a(bD.ClassName,bD);var TD=function(e){function t(i){var r=e.call(this,qI,JI,JI,(function(e,t){return r._polymorphicPow(e,t)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicPow=function(e,t){return wO(e,t,Math.pow)},t.ClassName="FGPowBlock",t}(rO);a(TD.ClassName,TD);var ED=function(e){function t(i){var r=e.call(this,qI,JI,(function(e){return r._polymorphicLength(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicLength=function(e){switch(fO(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw new Error("Cannot compute length of value ".concat(e))}},t.ClassName="FGLengthBlock",t}(nO);a(ED.ClassName,ED);var SD=function(e){function t(i){var r=e.call(this,qI,qI,(function(e){return r._polymorphicNormalize(e)}),t.ClassName,i)||this;return r}return m(t,e),t.prototype._polymorphicNormalize=function(e){switch(fO(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw new Error("Cannot normalize value ".concat(e))}},t.ClassName="FGNormalizeBlock",t}(nO);a(SD.ClassName,SD);var xD=function(e){function t(i){return e.call(this,tM,tM,tM,(function(e,t){return V.Cross(e,t)}),t.ClassName,i)||this}return m(t,e),t.ClassName="FGCrossBlock",t}(rO);a(xD.ClassName,xD);var AD=function(e){function t(i){return e.call(this,eM,JI,eM,(function(e,t){return U.Transform(e,z.RotationZ(t))}),t.ClassName,i)||this}return m(t,e),t.ClassName="FGRotate2DBlock",t}(rO);a(AD.ClassName,AD);var CD=function(e){function t(i){return e.call(this,tM,tM,JI,tM,(function(e,t,i){return V.TransformCoordinates(e,z.RotationAxis(t,i))}),t.ClassName,i)||this}return m(t,e),t.ClassName="FGRotate3DBlock",t}(pO);a(CD.ClassName,CD);var RD=function(e){function t(i){return e.call(this,rM,rM,(function(e){return z.Transpose(e)}),t.ClassName,i)||this}return m(t,e),t.ClassName="FGTransposeBlock",t}(nO);a(RD.ClassName,RD);var PD=function(e){function t(i){return e.call(this,rM,JI,(function(e){return e.determinant()}),t.ClassName,i)||this}return m(t,e),t.ClassName="FGDeterminantBlock",t}(nO);a(PD.ClassName,PD);var ID=function(e){function t(i){return e.call(this,rM,rM,(function(e){return z.Invert(e)}),t.ClassName,i)||this}return m(t,e),t.ClassName="FGInvertMatrixBlock",t}(nO);a(ID.ClassName,ID);var MD=function(e){function t(i){return e.call(this,rM,rM,rM,(function(e,t){return t.multiply(e)}),t.ClassName,i)||this}return m(t,e),t.ClassName="FGMatMulBlock",t}(rO);a(MD.ClassName,MD);var OD=function(e){function t(i){return e.call(this,sM,sM,(function(e){return new KI(~e.value)}),t.ClassName,i)||this}return m(t,e),t.ClassName="FGBitwiseNotBlock",t}(nO);a(OD.ClassName,OD);var DD=function(e){function t(i){return e.call(this,sM,sM,sM,(function(e,t){return new KI(e.value&t.value)}),t.ClassName,i)||this}return m(t,e),t.ClassName="FGBitwiseAndBlock",t}(rO);a(DD.ClassName,DD);var ND=function(e){function t(i){return e.call(this,sM,sM,sM,(function(e,t){return new KI(e.value|t.value)}),t.ClassName,i)||this}return m(t,e),t.ClassName="FGBitwiseOrBlock",t}(rO);a(ND.ClassName,ND);var FD=function(e){function t(i){return e.call(this,sM,sM,sM,(function(e,t){return new KI(e.value^t.value)}),t.ClassName,i)||this}return m(t,e),t.ClassName="FGBitwiseXorBlock",t}(rO);a(FD.ClassName,FD);var LD=function(e){function t(i){return e.call(this,sM,sM,sM,(function(e,t){return new KI(e.value<<t.value)}),t.ClassName,i)||this}return m(t,e),t.ClassName="FGBitwiseLeftShiftBlock",t}(rO);a(LD.ClassName,LD);var wD=function(e){function t(i){return e.call(this,sM,sM,sM,(function(e,t){return new KI(e.value>>t.value)}),t.ClassName,i)||this}return m(t,e),t.ClassName="FGBitwiseRightShiftBlock",t}(rO);a(wD.ClassName,wD);var BD=function(e){function t(i){return e.call(this,sM,sM,(function(e){return new KI(Math.clz32(e.value))}),t.ClassName,i)||this}return m(t,e),t.ClassName="FGCountLeadingZerosBlock",t}(nO);a(BD.ClassName,BD);var UD=function(e){function t(i){return e.call(this,sM,sM,(function(e){return new KI(e.value?31-Math.clz32(e.value&-e.value):32)}),t.ClassName,i)||this}return m(t,e),t.ClassName="FGCountTrailingZerosBlock",t}(nO);a(UD.ClassName,UD);var VD=function(e){function t(i){return e.call(this,sM,sM,(function(e){return new KI(function(e){for(var t=0;e;)t+=1&e,e>>=1;return t}(e.value))}),t.ClassName,i)||this}return m(t,e),t.ClassName="FGCountOneBitsBlock",t}(nO);a(VD.ClassName,VD);var kD=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.prototype._preparePendingTasks=function(e){var t=this;if(!e._getExecutionVariable(this,"sceneReadyObserver")){var i=e.configuration.scene.onReadyObservable.add((function(){t._execute(e)}));e._setExecutionVariable(this,"sceneReadyObserver",i)}},t.prototype._cancelPendingTasks=function(e){var t=e._getExecutionVariable(this,"sceneReadyObserver");e.configuration.scene.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")},t.prototype.getClassName=function(){return t.ClassName},t.ClassName="FGSceneReadyEventBlock",t}(vM);a("FGSceneReadyEventBlock",kD);var GD=function(e){function t(t){var i=e.call(this,t)||this;i.config=t;for(var r=0;r<i.config.eventData.length;r++){var n=i.config.eventData[r];i.registerDataOutput(n,qI)}return i}return m(t,e),t.prototype._preparePendingTasks=function(e){var t=this,i=e.configuration.coordinator.getCustomEventObservable(this.config.eventId);this._eventObserver=i.add((function(i){for(var r=0;r<i.length;r++)t.dataOutputs[r].setValue(i[r],e);t._execute(e)}))},t.prototype._cancelPendingTasks=function(e){var t=e.configuration.coordinator.getCustomEventObservable(this.config.eventId);t?t.remove(this._eventObserver):rr.Warn("FlowGraphReceiveCustomEventBlock: Missing observable for event ".concat(this.config.eventId))},t.prototype.getClassName=function(){return t.ClassName},t.prototype.serialize=function(t){e.prototype.serialize.call(this,t),t.eventId=this.config.eventId,t.eventData=this.config.eventData},t.ClassName="FGReceiveCustomEventBlock",t}(vM);a(GD.ClassName,GD);var zD=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(t,e),t.prototype._preparePendingTasks=function(e){var t=this;if(!e._getExecutionVariable(this,"sceneBeforeRender")){var i=e.configuration.scene.onBeforeRenderObservable.add((function(){t._execute(e)}));e._setExecutionVariable(this,"sceneBeforeRender",i)}},t.prototype._cancelPendingTasks=function(e){var t=e._getExecutionVariable(this,"sceneBeforeRender");e.configuration.scene.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")},t.prototype.getClassName=function(){return t.ClassName},t.ClassName="FGSceneTickEventBlock",t}(vM);a(zD.ClassName,zD);var WD=void 0!==e.g?e.g:"undefined"!=typeof window?window:void 0;if(void 0!==WD){WD.BABYLON=WD.BABYLON||{};var HD=WD.BABYLON;if(!HD.Debug)for(var XD in HD.Debug=HD.Debug||{},i)HD.Debug[XD]||(HD.Debug[XD]=i[XD]);for(var XD in r)HD[XD]||(HD[XD]=r[XD])}var jD={AxesViewer:Nh,BoneAxesViewer:Fh,PhysicsViewer:np,SkeletonViewer:ap};const YD=n;return t.default})()));
//# sourceMappingURL=babylon.js.map